Skip to content

Instantly share code, notes, and snippets.

@mbostock
Forked from mbostock/.block
Last active October 19, 2021 16:36
Show Gist options
  • Select an option

  • Save mbostock/2206590 to your computer and use it in GitHub Desktop.

Select an option

Save mbostock/2206590 to your computer and use it in GitHub Desktop.
click-to-zoom via transform
<!DOCTYPE html>
<meta charset="utf-8">
<script src="http://mbostock.github.com/d3/d3.v2.js?2.8.1"></script>
<style>
.background {
fill: none;
pointer-events: all;
}
#states path {
fill: #aaa;
stroke: #fff;
stroke-width: 1.5px;
}
#states path:hover {
stroke: white;
}
</style>
<body>
<script>
var width = 960,
height = 500,
centered;
var projection = d3.geo.albersUsa()
.scale(width)
.translate([0, 0]);
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
svg.append("rect")
.attr("class", "background")
.attr("width", width)
.attr("height", height)
.on("click", click);
var states = svg.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
.append("g")
.attr("id", "states");
d3.json("us-states.json", function(json) {
states.selectAll("path")
.data(json.features)
.enter().append("path")
.attr("d", path)
.on("click", click);
});
function click(d) {
var x = 0,
y = 0,
k = 1;
if (d && centered !== d) {
var centroid = path.centroid(d);
x = -centroid[0];
y = -centroid[1];
k = 4;
}
centered = d;
states.transition()
.duration(1000)
.attr("transform", "scale(" + k + ")translate(" + x + "," + y + ")");
}
</script>
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@dannycochran
Copy link

Thanks for this template. Thought I would share this – it might be nice to include hover states for the states as a default in this code.

http://stanford.edu/~c0chran/cgi-bin/v3/index.html

@thedod
Copy link

thedod commented Jan 19, 2013

Thanks (both for d3 and for this specific example).
I've forked it into a clickable heat-map of petition signatures: http://bl.ocks.org/4548858

@Jvalal-zz
Copy link

Hi, I'm new to this and I thought I'd be able to just cut and paste the code from above and have it "work".

what am I missing? http://jasonvalalik.com/OpenLayers-1.0-rc1/examples/Leaflet.html

@altvers3
Copy link

altvers3 commented Jun 9, 2013

Hi Guys, how can I use this example for Brazilian map project?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment