Skip to content

Instantly share code, notes, and snippets.

Forked from mbostock/.block
Last active Dec 22, 2015
What would you like to do?

An example of d3.behavior.zoom and d3.geo.path. By modifying the transform, the browser can rapidly redraw geographic features while panning and zooming, without the overhead of reprojection. This technique can be extended by combining with d3.geo.tile.

<!DOCTYPE html>
<meta charset="utf-8">
.overlay {
fill: none;
pointer-events: all;
.state {
fill: #aaa;
.state-border {
fill: none;
stroke: #fff;
stroke-linejoin: round;
stroke-linecap: round;
<button onclick="zoom.scale(1).translate([0,0]).event(zoomRect)">Zoom out</button>
<button onclick="zoom.on('zoom', function(d){ console.log('no zooming!'); })">Disable zoom event</button>
<script src=""></script>
<script src=""></script>
var width = 960,
height = 500;
var path = d3.geo.path()
var svg ="body").append("svg")
.attr("width", width)
.attr("height", height);
var zoom = d3.behavior.zoom()
.translate([0, 0])
.scaleExtent([1, 8]);
var zoomRect;
d3.json("/mbostock/raw/5925375/us.json", function(error, us) {
var features = svg.append("g");
.datum(topojson.feature(us, us.objects.states))
.attr("class", "state")
.attr("d", path);
.datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; }))
.attr("class", "state-border")
.style("stroke-width", "1.5px")
.attr("d", path);
.datum(topojson.mesh(us, us.objects.counties, function(a, b) { return a !== b && !( / 1000 ^ / 1000); }))
.attr("class", "county-border")
.style("stroke-width", ".5px")
.attr("d", path);
zoomRect = svg.append("rect")
.attr("class", "overlay")
.attr("width", width)
.attr("height", height)
.call(zoom.on("zoom", zoomed));
function zoomed() {
features.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");".state-border").style("stroke-width", 1.5 / d3.event.scale + "px");".county-border").style("stroke-width", .5 / d3.event.scale + "px");
});"height", height + "px");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment