Skip to content

Instantly share code, notes, and snippets.

@d3noob
Forked from mbostock/.block
Last active Nov 30, 2019
Embed
What would you like to do?
Constrained Zoom Map. Centered on the Pacific
license: mit

This example is a minor variation on Mike Bostocks zoom constrained map, which demonstrates using the zoom event to constrain the zoom behavior’s translation. However, this version is centered on the anti-meridian (the Pacific).

The centering on a position other thann the prime medidian is accomplished by setting .rotate([-180,0]); as part of the var projection = section.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
.overlay {
fill: none;
pointer-events: all;
}
.land {
fill: #000;
}
.boundary {
fill: none;
stroke: #fff;
stroke-linejoin: round;
stroke-linecap: round;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<script src="http://d3js.org/topojson.v0.min.js"></script>
<body>
<script>
var width = 960,
height = 500;
var projection = d3.geo.mercator()
.translate([0, 0])
.scale(width)
.rotate([-180,0]);
var zoom = d3.behavior.zoom()
.scaleExtent([1, 8])
.on("zoom", move);
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
.call(zoom);
var g = svg.append("g");
svg.append("rect")
.attr("class", "overlay")
.attr("x", -width / 2)
.attr("y", -height / 2)
.attr("width", width)
.attr("height", height);
d3.json("https://gist.githubusercontent.com/mbostock/4090846/raw/d534aba169207548a8a3d670c9c2cc719ff05c47/world-50m.json", function(error, world) {
g.append("path")
.datum(topojson.object(world, world.objects.countries))
.attr("class", "land")
.attr("d", path);
g.append("path")
.datum(topojson.mesh(world, world.objects.countries, function(a, b) { return a !== b; }))
.attr("class", "boundary")
.attr("d", path);
});
function move() {
var t = d3.event.translate,
s = d3.event.scale;
t[0] = Math.min(width / 2 * (s - 1), Math.max(width / 2 * (1 - s), t[0]));
t[1] = Math.min(height / 2 * (s - 1) + 230 * s, Math.max(height / 2 * (1 - s) - 230 * s, t[1]));
zoom.translate(t);
g.style("stroke-width", 1 / s).attr("transform", "translate(" + t + ")scale(" + s + ")");
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment