Skip to content

Instantly share code, notes, and snippets.

@bewest
Forked from mbostock/.block
Created December 11, 2012 17:42
Show Gist options
  • Save bewest/4260548 to your computer and use it in GitHub Desktop.
Save bewest/4260548 to your computer and use it in GitHub Desktop.
d3.geo.tile

d3 tile plugin demo

demo src

Modified from the original d3 tile demo A demo of the d3.geo.tile plugin, which determines which 256x256 tiles are visible in the viewport based on a scale and translate. This demo combines the tile plugin with d3.behavior.zoom for panning and zooming, resulting in a a simple slippy map. Based partly on an example by Tom MacWright.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
margin: 0;
}
.map {
position: relative;
overflow: hidden;
}
.layer {
position: absolute;
}
.tile {
position: absolute;
width: 256px;
height: 256px;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="https://raw.github.com/d3/d3-plugins/master/geo/tile/tile.js"></script>
<script>
var width = window.innerWidth,
height = window.innerHeight,
prefix = prefixMatch(["webkit", "ms", "Moz", "O"]);
var tile = d3.geo.tile()
.size([width, height]);
var zoom = d3.behavior.zoom()
.scale(2 << 11)
.scaleExtent([2 << 8, 2 << 22])
.translate([width / 2, height / 2])
.on("zoom", zoomed);
var map = d3.select("body").append("div")
.attr("class", "map")
.style("width", width + "px")
.style("height", height + "px")
.call(zoom);
var layer = map.append("div")
.attr("class", "layer");
zoomed();
function zoomed() {
var tiles = tile
.scale(zoom.scale())
.translate(zoom.translate())
();
var image = layer
.style(prefix + "transform", matrix3d(tiles.scale, tiles.translate))
.selectAll(".tile")
.data(tiles, function(d) { return d; });
image.exit()
.remove();
image.enter( ).append('div')
.attr("class", "tile")
.style("left", function(d) { return (d[0] << 8) + "px"; })
.style("top", function(d) { return (d[1] << 8) + "px"; })
.text( function (d) {
return "x:" + d[0]
+ " y:" + d[1]
+ " z:" + d[2];
})
;
/*
image.enter().append("img")
.attr("class", "tile")
.attr("src", function(d) { return "http://" + ["a", "b", "c", "d"][Math.random() * 4 | 0] + ".tiles.mapbox.com/v3/mapbox.mapbox-streets/" + d[2] + "/" + d[0] + "/" + d[1] + ".png"; })
.style("left", function(d) { return (d[0] << 8) + "px"; })
.style("top", function(d) { return (d[1] << 8) + "px"; });
*/
}
function matrix3d(scale, translate) {
var k = scale / 256, r = scale % 1 ? Number : Math.round;
return "matrix3d(" + [k, 0, 0, 0, 0, k, 0, 0, 0, 0, k, 0, r(translate[0] * scale), r(translate[1] * scale), 0, 1 ] + ")";
}
function prefixMatch(p) {
var i = -1, n = p.length, s = document.body.style;
while (++i < n) if (p[i] + "Transform" in s) return "-" + p[i].toLowerCase() + "-";
return "";
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment