Skip to content

Instantly share code, notes, and snippets.

Forked from mbostock/.block
Last active October 19, 2021 16:36
Show Gist options
  • Save mbostock/2206590 to your computer and use it in GitHub Desktop.
Save mbostock/2206590 to your computer and use it in GitHub Desktop.
click-to-zoom via transform
license: gpl-3.0
<!DOCTYPE html>
<meta charset="utf-8">
.background {
fill: none;
pointer-events: all;
#states {
fill: #aaa;
#states .active {
fill: orange;
#state-borders {
fill: none;
stroke: #fff;
stroke-width: 1.5px;
stroke-linejoin: round;
stroke-linecap: round;
pointer-events: none;
<script src="//"></script>
<script src="//"></script>
var width = 960,
height = 500,
var projection = d3.geo.albersUsa()
.translate([width / 2, height / 2]);
var path = d3.geo.path()
var svg ="body").append("svg")
.attr("width", width)
.attr("height", height);
.attr("class", "background")
.attr("width", width)
.attr("height", height)
.on("click", clicked);
var g = svg.append("g");
d3.json("/mbostock/raw/4090846/us.json", function(error, us) {
if (error) throw error;
.attr("id", "states")
.data(topojson.feature(us, us.objects.states).features)
.attr("d", path)
.on("click", clicked);
.datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; }))
.attr("id", "state-borders")
.attr("d", path);
function clicked(d) {
var x, y, k;
if (d && centered !== d) {
var centroid = path.centroid(d);
x = centroid[0];
y = centroid[1];
k = 4;
centered = d;
} else {
x = width / 2;
y = height / 2;
k = 1;
centered = null;
.classed("active", centered && function(d) { return d === centered; });
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + k + ")translate(" + -x + "," + -y + ")")
.style("stroke-width", 1.5 / k + "px");
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.

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:

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?

Copy link

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