Skip to content

Instantly share code, notes, and snippets.

@khan2sa
Last active March 28, 2017 15:32
Show Gist options
  • Save khan2sa/57de2433c743b2118fb98c0f39a3d46a to your computer and use it in GitHub Desktop.
Save khan2sa/57de2433c743b2118fb98c0f39a3d46a to your computer and use it in GitHub Desktop.
Zoom Map
license: mit
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.background {
fill: blue;
pointer-events: all;
}
#states {
fill: #aaa;
}
.active{
fill: orange;
}
.hover{
fill: orange;
}
#state-borders {
fill: none;
stroke: #e50000;
stroke-width: 2px;
stroke-linejoin: round;
stroke-linecap: round;
pointer-events: none;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script src="//d3js.org/topojson.v1.min.js"></script>
<script>
var width = 960,
height = 900,
centered;
var projection = d3.geo.albersUsa()
.scale(1070)
.translate([width / 2, 300]);
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", clicked);
var g = svg.append("g");
d3.json("https://gist.githubusercontent.com/mbostock/4090846/raw/d534aba169207548a8a3d670c9c2cc719ff05c47/us.json", function(error, us) {
if (error) throw error;
g.append("g")
.attr("id", "states")
.selectAll("path")
.data(topojson.feature(us, us.objects.states).features)
.enter().append("path")
.attr("d", path)
.on("click", clicked);
g.append("path")
.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 = 5.5;
centered = d;
} else {
x = width / 2;
y = height / 2;
k = 1;
centered = null;
}
g.selectAll("path")
.classed("active", centered && function(d) { return d === centered; });
g.transition()
.duration(750)
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + k + ")translate(" + -x + "," + -y + ")")
.style("stroke-width", 1.5 / k + "px");
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment