Skip to content

Instantly share code, notes, and snippets.

@wboykinm
Created November 10, 2013 03:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wboykinm/7393314 to your computer and use it in GitHub Desktop.
Save wboykinm/7393314 to your computer and use it in GitHub Desktop.
Leaflet w/ basic D3 interpretation of Vector Tiles
<!DOCTYPE html>
<meta charset="utf-8">
<title>D3 GeoJSON in Leaflet</title>
<link href='http://api.tiles.mapbox.com/mapbox.js/v1.4.0/mapbox.css' rel='stylesheet' />
<!--[if lte IE 8]>
<link href='http://api.tiles.mapbox.com/mapbox.js/v1.4.0/mapbox.ie.css' rel='stylesheet'>
<![endif]--><style>
html, body, #map { height: 100%;width:100%; background:#020B26}
body { padding: 0; margin: 0; }
.road { stroke : #3C80A9; fill : none ; }
.water { stroke:none; fill:#031536;}
</style>
<body>
<div id="map"></div>
<script src="http://api.tiles.mapbox.com/mapbox.js/v1.4.0/mapbox.js"></script>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
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);
});
}
}
});
map = L.map(map).setView([45.5086699, -73.553992], 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);
var topPane = map._createPane('leaflet-top-pane', map.getPanes().mapPane);
var topLayer = new L.tileLayer('http://{s}.tile.stamen.com/toner-labels/{z}/{x}/{y}.png', {
maxZoom: 17
}).addTo(map);
topPane.appendChild(topLayer.getContainer());
topLayer.setZIndex(7);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment