Skip to content

Instantly share code, notes, and snippets.

Last active September 16, 2020 09:18
Show Gist options
  • Save d3noob/9211665 to your computer and use it in GitHub Desktop.
Save d3noob/9211665 to your computer and use it in GitHub Desktop.
Map using leaflet.js and d3,js combined
license: mit

This is a map that uses leaflet.js and d3.js in a way that combines the two so that the d3.js object zooms and pans with the map. It is as used as an example in the book D3 Tips and Tricks.

It is derived from the Mike Bostock tutorial on Leaflet but is simplified somewhat.

<!DOCTYPE html>
<title>Leaflet and D3 Map</title>
<meta charset="utf-8" />
<div id="map" style="width: 600px; height: 400px"></div>
<script src=""></script>
var map ='map').setView([-41.2858, 174.7868], 13);
mapLink =
'<a href="">OpenStreetMap</a>';
'http://{s}{z}/{x}/{y}.png', {
attribution: '&copy; ' + mapLink + ' Contributors',
maxZoom: 18,
// Add an SVG element to Leaflet’s overlay pane
var svg ="svg"),
g = svg.append("g").attr("class", "leaflet-zoom-hide");
d3.json("rectangle.json", function(geoShape) {
// create a d3.geo.path to convert GeoJSON to SVG
var transform = d3.geo.transform({point: projectPoint}),
path = d3.geo.path().projection(transform);
// create path elements for each of the features
d3_features = g.selectAll("path")
map.on("viewreset", reset);
// fit the SVG element to leaflet's map layer
function reset() {
bounds = path.bounds(geoShape);
var 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] + ")");
// initialize the path data
d3_features.attr("d", path)
.style("fill-opacity", 0.7)
// Use Leaflet to implement a D3 geometric transformation.
function projectPoint(x, y) {
var point = map.latLngToLayerPoint(new L.LatLng(y, x));, point.y);
Display the source blob
Display the rendered blob
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