block by d3noob 9211665

Map using leaflet.js and d3,js combined

Full Screen

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.

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Leaflet and D3 Map</title>
    <meta charset="utf-8" />
    <link 
        rel="stylesheet" 
        href="//cdn.leafletjs.com/leaflet-0.7/leaflet.css"
    />

</head>
<body>

    <div id="map" style="width: 600px; height: 400px"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>

    <script
        src="//cdn.leafletjs.com/leaflet-0.7/leaflet.js">
    </script>

    <script>
	
        var map = L.map('map').setView([-41.2858, 174.7868], 13);
        mapLink = 
            '<a href="//openstreetmap.org">OpenStreetMap</a>';
        L.tileLayer(
            '//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; ' + mapLink + ' Contributors',
            maxZoom: 18,
            }).addTo(map);

		// Add an SVG element to Leaflet’s overlay pane
		var svg = d3.select(map.getPanes().overlayPane).append("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")
			.data(geoShape.features)
			.enter().append("path");

		map.on("viewreset", reset);

		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)
				.attr('fill','blue');
		} 

		// Use Leaflet to implement a D3 geometric transformation.
		function projectPoint(x, y) {
			var point = map.latLngToLayerPoint(new L.LatLng(y, x));
			this.stream.point(point.x, point.y);
		}

	})
        
    </script>
</body>
</html>

rectangle.json

{
"type": "FeatureCollection",
"features": [ { 
	"type": "Feature", 
	"geometry": { 
		"type": "Polygon", 
		"coordinates": [ [ 
		[ 174.78, -41.29 ], 
		[ 174.79, -41.29 ], 
		[ 174.79, -41.28 ], 
		[ 174.78, -41.28 ], 
		[ 174.78, -41.29 ] 
		] ] 
		}
	}	
]
}