Skip to content

Instantly share code, notes, and snippets.

@jatorre
Forked from mbostock/.block
Created November 22, 2012 22:10
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 jatorre/4133108 to your computer and use it in GitHub Desktop.
Save jatorre/4133108 to your computer and use it in GitHub Desktop.
d3.geo.tile

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">
<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 = 960,
height = 500;
var tile = d3.geo.tile();
var zoom = d3.behavior.zoom()
.scale(1024)
.translate([width / 2, height / 2])
.on("zoom", zoomed);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.call(zoom);
var g = svg.append("g");
zoomed();
function zoomed() {
var tiles = tile
.scale(zoom.scale())
.translate(zoom.translate())
();
var image = g
.attr("transform", function(d) { return "scale(" + tiles.scale + ")translate(" + tiles.translate + ")"; })
.selectAll("image")
.data(tiles, function(d) { return d; });
image.exit()
.remove();
image.enter().append("image")
.attr("xlink:href", function(d) { return "http://2.tiles.cartocdn.com/jatorre-beta/tiles/regions/" + d[2] + "/" + d[0] + "/" + d[1] + ".png?sql=SELECT%20*%20FROM%20regions&cache_buster=2012-11-22T12:37:07+01:00&cache_policy=persist&interactivity=cartodb_id%2Coriginal_c"; })
.attr("width", 1)
.attr("height", 1)
.attr("x", function(d) { return d[0]; })
.attr("y", function(d) { return d[1]; });
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment