Skip to content

Instantly share code, notes, and snippets.

@itbakery
Forked from d3noob/.block
Last active August 29, 2015 14:15
Show Gist options
  • Save itbakery/1acc830dc04018c0c127 to your computer and use it in GitHub Desktop.
Save itbakery/1acc830dc04018c0c127 to your computer and use it in GitHub Desktop.

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>
<html>
<head>
<title>Leaflet and D3 Map</title>
<meta charset="utf-8" />
<link
rel="stylesheet"
href="http://cdn.leafletjs.com/leaflet-0.7/leaflet.css"
/>
</head>
<body>
<div id="map" style="width: 600px; height: 400px"></div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script
src="http://cdn.leafletjs.com/leaflet-0.7/leaflet.js">
</script>
<script>
var map = L.map('map').setView([-41.2858, 174.7868], 13);
mapLink =
'<a href="http://openstreetmap.org">OpenStreetMap</a>';
L.tileLayer(
'http://{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>
Display the source blob
Display the rendered blob
Raw
{
"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 ]
] ]
}
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment