Skip to content

Instantly share code, notes, and snippets.

@bykes
Forked from mbostock/.block
Created October 8, 2012 12:19
Show Gist options
  • Save bykes/3852229 to your computer and use it in GitHub Desktop.
Save bykes/3852229 to your computer and use it in GitHub Desktop.
Mercator Projection
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
<!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;
var projection = d3.geo.mercator()
.scale(width)
.translate([width / 2, height / 2]);
var path = d3.geo.path()
.projection(projection);
var zoom = d3.behavior.zoom()
.translate(projection.translate())
.scale(projection.scale())
.scaleExtent([height, 50 * height])
.on("zoom", zoom);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var states = svg.append("g")
.attr("id", "states")
.call(zoom);
states.append("rect")
.attr("class", "background")
.attr("width", width)
.attr("height", height);
d3.json("readme.json", function(json) {
states.selectAll("path")
.data(json.features)
.enter().append("path")
.attr("d", path)
.on("click", click);
});
function click(d) {
var centroid = path.centroid(d),
translate = projection.translate();
projection.translate([
translate[0] - centroid[0] + width / 2,
translate[1] - centroid[1] + height / 2
]);
zoom.translate(projection.translate());
states.selectAll("path").transition()
.duration(1000)
.attr("d", path);
}
function zoom() {
projection.translate(d3.event.translate).scale(d3.event.scale);
states.selectAll("path").attr("d", path);
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment