Skip to content

Instantly share code, notes, and snippets.

@ZJONSSON
Last active April 28, 2016 07:18
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save ZJONSSON/5529395 to your computer and use it in GitHub Desktop.
Save ZJONSSON/5529395 to your computer and use it in GitHub Desktop.
D3 GeoJSON in Leaflet

UPDATE: The Vector Tiles are not being served at this time by Openstreetmap. Try later or a different provider (example) Services seem to have resumed

A simple test of extending the L.TileLayer to fetch geoJSON tiles from openstreetmap and render them with d3. This is probably not the most efficient way to do this, as we accept empty image tags (from the standard TileLayer) and use them as containers for the data/requests.

<!DOCTYPE html>
<meta charset="utf-8">
<title>D3 GeoJSON in Leaflet</title>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.5.1/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet-0.5.1/leaflet.js"></script>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="TileLayer.d3_geoJSON.js"></script>
<style>
html, body, #map { height: 100%;width:100%;}
body { padding: 0; margin: 0; }
.road { stroke : black; fill : none; }
.water { stroke:black; fill:blue; }
</style>
<body>
<div id="map"></div>
<script>
map = L.map(map).setView([40.74, -73.99], 13);
map._initPathRoot();
new L.TileLayer.d3_geoJSON('http://{s}.tile.openstreetmap.us/vectiles-highroad/{z}/{x}/{y}.json',{class:"road"})
.addTo(map);
new L.TileLayer.d3_geoJSON('http://{s}.tile.openstreetmap.us/vectiles-water-areas/{z}/{x}/{y}.json',{class:"water"})
.addTo(map);
</script>
</body>
L.TileLayer.d3_geoJSON = L.TileLayer.extend({
onAdd : function(map) {
L.TileLayer.prototype.onAdd.call(this,map);
this.g = d3.select(map._container).select("svg").append("g");
this._path = d3.geo.path().projection(function(d) {
var point = map.latLngToLayerPoint(new L.LatLng(d[1],d[0]));
return [point.x,point.y];
});
this.on("tileunload",function(d) {
if (d.tile.xhr) d.tile.xhr.abort();
if (d.tile.nodes) d.tile.nodes.remove();
d.tile.nodes = null;
d.tile.xhr = null;
});
},
_loadTile : function(tile,tilePoint) {
var self = this;
this._adjustTilePoint(tilePoint);
if (!tile.nodes && !tile.xhr) {
tile.nodes = d3.select();
tile.xhr = d3.json(this.getTileUrl(tilePoint),function(d) {
tile.xhr = null;
tile.nodes = self.g.append("path")
.datum(d)
.attr("d",self._path)
.attr("class",self.options.class);
});
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment