Skip to content

Instantly share code, notes, and snippets.

@jlegewie
Last active December 10, 2015 10:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jlegewie/4420559 to your computer and use it in GitHub Desktop.
Save jlegewie/4420559 to your computer and use it in GitHub Desktop.
Interactive approach to center view in map

Step two from Mike Bostock's excellent tutorial with interactive way to find the correct translation and scale, which makes it easy to display the desired part of the map. Click and move to position map, scroll to scale. The parameters are show in the console.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
/* CSS goes here. */
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v0.min.js"></script>
<script>
var width = 960,
height = 1160;
var projection = d3.geo.mercator()
.scale(500)
.translate([width / 2, height / 2]);
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.json("uk.json", function(error, uk) {
var map = svg.append("path")
.datum(topojson.object(uk, uk.objects.subunits))
.attr("d", path);
svg.call(d3.behavior.zoom()
.translate(projection.translate())
.scale(projection.scale())
.on("zoom", redraw));
function redraw() {
if (d3.event) {
projection
.translate(d3.event.translate)
.scale(d3.event.scale);
console.log("Current scale:" + projection.scale())
console.log("Current translate:" + projection.translate())
console.log("Current rotate:" + projection.rotate())
}
map.datum(topojson.object(uk, uk.objects.subunits))
.attr("d", path);
}
});
</script>
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment