Skip to content

Instantly share code, notes, and snippets.

@nunojpg
Last active July 14, 2017 20:20
Show Gist options
  • Save nunojpg/cc204e57cc6c57dcc1f1ba311393e1f1 to your computer and use it in GitHub Desktop.
Save nunojpg/cc204e57cc6c57dcc1f1ba311393e1f1 to your computer and use it in GitHub Desktop.
geoVoronoi Leaflet
license: mit
<!DOCTYPE html>
<html>
<head>
<title>geoVoronoi Leaflet</title>
<link rel="stylesheet" href="//unpkg.com/[email protected]/dist/leaflet.css" />
<script src="//unpkg.com/[email protected]/dist/leaflet.js"></script>
<script src="//d3js.org/d3.v4.min.js"></script>
<script src="//d3js.org/d3-geo-projection.v2.min.js"></script>
<script src="//unpkg.com/d3-geo-voronoi"></script>
<script src="//unpkg.com/unique-colors"></script>
<style type="text/css">
html,
body {
margin: 0px;
padding: 0px;
}
html,
body,
#map {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script type="text/javascript">
'use strict';
d3.json("point.json", function (error, pointjson) {
if (error) throw error;
const map = L.map('map').setView([40.505, -8.09], 5);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
const proj = d3.geoEquirectangular().translate([0, 0]).scale(180 / Math.PI)
const reflect = d3.geoIdentity().reflectY(true)
const antimeridian_cut = a => d3.geoProject(d3.geoProject(a, proj), reflect);
const voronoi = d3.geoVoronoi()(pointjson.features)
const polygons = antimeridian_cut(voronoi.polygons())
L.geoJSON(pointjson).addTo(map);
const palette = unique_colors(polygons.features.length)
let color = 0
polygons.features.forEach(a => L.geoJSON(a, {
style: {
"interactive": false,
"opacity": 0.2,
"color": palette[color++],
"weight": 0
}
}).addTo(map))
let polyline = null;
let polyline_on = false
const onmousemove = function (e) {
const latlng_mouse = e.latlng
const site = voronoi.find(latlng_mouse.lng, latlng_mouse.lat)
const latlng_site = [site.geometry.coordinates[1], site.geometry.coordinates[0]]
const distance = latlng_mouse.distanceTo(latlng_site)
if (polyline)
map.removeLayer(polyline)
polyline = L.polyline([latlng_mouse, latlng_site], { color: 'blue' })
polyline.addTo(map).bindTooltip((distance / 1000.0).toFixed(1) + " km - " + site.id, { permanent: true });
}
map.on("click", function (e) {
if (polyline_on) {
polyline_on = false
map.off("mousemove");
if (polyline)
map.removeLayer(polyline)
polyline = null
}
else {
polyline_on = true
map.on("mousemove", onmousemove);
}
});
});
</script>
</body>
</html>
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment