Skip to content

Instantly share code, notes, and snippets.

@pbogden
Last active June 17, 2023 17:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pbogden/16417ea36900f44710b2 to your computer and use it in GitHub Desktop.
Save pbogden/16417ea36900f44710b2 to your computer and use it in GitHub Desktop.
D3 + Leaflet
<!DOCTYPE html>
<meta charset="utf-8">
<title>leaflet</title>
<style>
@import url(//cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.2/leaflet.css);
#map {
width: 960px;
height: 500px;
}
path {
fill: #000;
fill-opacity: .2;
stroke: #fff;
stroke-width: 1.5px;
}
path:hover {
fill: brown;
fill-opacity: .7;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/topojson/1.6.19/topojson.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.2/leaflet.js"></script>
<body>
<div id="map"</div>
<script>
var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
osmAttrib = '&copy; <a href="http://openstreetmap.org/copyright">OpenStreetMap</a> contributors',
osm = L.tileLayer(osmUrl, {maxZoom: 18, attribution: osmAttrib});
var map = L.map('map').setView([37.8, -96.9], 4).addLayer(osm);
var svg = d3.select(map.getPanes().overlayPane).append("svg"),
g = svg.append("g").attr("class", "leaflet-zoom-hide");
var transform = d3.geo.transform({point: projectPoint}),
path = d3.geo.path().projection(transform);
d3.json("us.json", function(error, us) {
var features = us.objects.us.geometries.map(function(d) { return topojson.feature(us, d); });
var all = topojson.merge(us, us.objects.us.geometries);
var states = g.selectAll("path")
.data(features)
.enter()
.append("path");
map.on("viewreset", reset);
reset();
// Reposition the SVG to cover the features.
function reset() {
var bounds = path.bounds(all),
topLeft = bounds[0],
bottomRight = bounds[1];
svg .attr("width", bottomRight[0] - topLeft[0])
.attr("height", bottomRight[1] - topLeft[1])
.style("left", topLeft[0] + "px")
.style("top", topLeft[1] + "px");
g.attr("transform", "translate(" + -topLeft[0] + "," + -topLeft[1] + ")");
states.attr("d", path);
}
});
// Use Leaflet to implement a D3 geometric transformation.
function projectPoint(x, y) {
// Returns the map layer point that corresponds to the given geographical coordinates
var point = map.latLngToLayerPoint(new L.LatLng(y, x));
this.stream.point(point.x, point.y);
}
</script>
Display the source blob
Display the rendered blob
Raw
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