This example uses d3.behavior.zoom with a dynamic projection for map panning and zooming. This approach is slower than using a transform or transforming pre-projected geometry because it requires reprojecting whenever the zoom changes.
-
-
Save yoon-gu/4104a4e12549c6f5dea43242011aea68 to your computer and use it in GitHub Desktop.
Map Pan & Zoom II
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
license: gpl-3.0 |
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> | |
svg { | |
background: #eee; | |
} | |
.sphere { | |
fill: #fff; | |
} | |
.land { | |
fill: #000; | |
} | |
.boundary { | |
fill: none; | |
stroke: #fff; | |
stroke-linejoin: round; | |
stroke-linecap: round; | |
vector-effect: non-scaling-stroke; | |
} | |
.overlay { | |
fill: none; | |
pointer-events: all; | |
} | |
</style> | |
<script src="//d3js.org/d3.v3.min.js"></script> | |
<script src="//d3js.org/topojson.v1.min.js"></script> | |
<body> | |
<script> | |
var width = 960, | |
height = 960, | |
scale0 = (width - 1) / 2 / Math.PI; | |
var projection = d3.geo.mercator(); | |
var zoom = d3.behavior.zoom() | |
.translate([width / 2, height / 2]) | |
.scale(scale0) | |
.scaleExtent([scale0, 8 * scale0]) | |
.on("zoom", zoomed); | |
var path = d3.geo.path() | |
.projection(projection); | |
var svg = d3.select("body").append("svg") | |
.attr("width", width) | |
.attr("height", height) | |
.append("g"); | |
var g = svg.append("g"); | |
svg.append("rect") | |
.attr("class", "overlay") | |
.attr("width", width) | |
.attr("height", height); | |
svg | |
.call(zoom) | |
.call(zoom.event); | |
d3.json("/mbostock/raw/4090846/world-110m.json", function(error, world) { | |
if (error) throw error; | |
g.append("path") | |
.datum({type: "Sphere"}) | |
.attr("class", "sphere") | |
.attr("d", path); | |
g.append("path") | |
.datum(topojson.merge(world, world.objects.countries.geometries)) | |
.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 zoomed() { | |
projection | |
.translate(zoom.translate()) | |
.scale(zoom.scale()); | |
g.selectAll("path") | |
.attr("d", path); | |
} | |
d3.select(self.frameElement).style("height", height + "px"); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment