Skip to content

Instantly share code, notes, and snippets.

@piwodlaiwo
Created January 17, 2018 03:39
Show Gist options
  • Save piwodlaiwo/a8ed2603f9cafb1253471cc5f7759d71 to your computer and use it in GitHub Desktop.
Save piwodlaiwo/a8ed2603f9cafb1253471cc5f7759d71 to your computer and use it in GitHub Desktop.
D3v4 World Map with MapBox Tiles
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.js"></script>
<script src="https://d3js.org/topojson.v2.min.js"></script>
<script src="https://d3js.org/d3-tile.v0.0.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
svg { width:100%; height: 100% }
.stroke {
fill: none;
stroke: #000;
stroke-width: .5;
}
</style>
</head>
<body>
<script>
var width = 900;
var height = 500;
var svg = d3.select("body").append("svg");
var projection = d3.geoMercator();
var path = d3.geoPath().projection(projection);
var tile = d3.tile()
.scale(projection.scale() * 2 * Math.PI)
.translate(projection([0, 0]))
.zoomDelta((window.devicePixelRatio || 1) - .5);
var url = "https://gist.githubusercontent.com/mbostock/4090846/raw/d534aba169207548a8a3d670c9c2cc719ff05c47/world-50m.json";
d3.json(url, function(error, world) {
if (error) throw error;
var tiles = tile();
var defs = svg.append("defs");
defs.append("path")
.attr("id", "land")
.datum(topojson.feature(world, world.objects.countries))
.attr("d", path);
defs.append("clipPath")
.attr("id", "clip")
.append("use")
.attr("xlink:href", "#land");
svg.append("g")
.attr("clip-path", "url(#clip)")
.selectAll("image")
.data(tiles)
.enter().append("image")
.attr("xlink:href", function(d) { return "http://" + ["a", "b", "c", "d"][Math.random() * 4 | 0] + ".tiles.mapbox.com/v3/mapbox.natural-earth-2/" + d[2] + "/" + d[0] + "/" + d[1] + ".png"; })
.attr("width", Math.round(tiles.scale))
.attr("height", Math.round(tiles.scale))
.attr("x", function(d) { return Math.round((d[0] + tiles.translate[0]) * tiles.scale); })
.attr("y", function(d) { return Math.round((d[1] + tiles.translate[1]) * tiles.scale); });
svg.append("use")
.attr("xlink:href", "#land")
.attr("class", "stroke");
});
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment