-
-
Save larskotthoff/f7340645d4cda3ff6ac5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<style> | |
.feature { | |
fill: #ccc; | |
stroke: #fff; | |
stroke-width: 2px; | |
} | |
.feature.active { | |
fill: orange; | |
} | |
</style> | |
<body> | |
<script src="http://d3js.org/d3.v3.min.js"></script> | |
<script src="http://d3js.org/topojson.v1.min.js"></script> | |
<script> | |
var width = 960, | |
height = 500, | |
active; | |
var projection = d3.geo.mercator(); | |
var path = d3.geo.path() | |
.projection(projection); | |
var svg = d3.select("body").append("svg") | |
.attr("width", width) | |
.attr("height", height); | |
var g = svg.append("g"); | |
d3.json("paris.json", function(error, us) { | |
projection | |
.scale(1) | |
.translate([0, 0]); | |
var b = path.bounds(us), | |
s = .95 / Math.max((b[1][0] - b[0][0]) / width, (b[1][1] - b[0][1]) / height), | |
t = [(width - s * (b[1][0] + b[0][0])) / 2, (height - s * (b[1][1] + b[0][1])) / 2]; | |
projection | |
.scale(s) | |
.translate(t); | |
g.selectAll("path") | |
.data(us.features) | |
.enter().append("svg:path") | |
.attr("class", "feature") | |
.attr("d", path) | |
.on("click", click); | |
}); | |
function click(d) { | |
if (active === d) return reset(); | |
g.selectAll(".active").classed("active", false); | |
d3.select(this).classed("active", active = d); | |
var b = path.bounds(d), | |
s = .95 / Math.max((b[1][0] - b[0][0]) / width, (b[1][1] - b[0][1]) / height), | |
t = [(width - s * (b[1][0] + b[0][0])) / 2, (height - s * (b[1][1] + b[0][1])) / 2]; | |
var transform = | |
"translate(" + width/2 + "," + height/2 + ")" + | |
"scale(" + .95 / Math.max((b[1][0] - b[0][0]) / width, (b[1][1] - b[0][1]) / height) + ")" | |
+ | |
"translate(" + -(b[1][0] + b[0][0]) / 2 + "," + -(b[1][1] + b[0][1]) / 2 + ")"; | |
g.transition().duration(750).attr("transform", transform); | |
} | |
function reset() { | |
g.selectAll(".active").classed("active", active = false); | |
g.transition().duration(750).attr("transform", ""); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment