Skip to content

Instantly share code, notes, and snippets.

@vasturiano vasturiano/
Last active Jun 4, 2018

What would you like to do?
Map Pan & Zoom D3v4

D3 v4/5 version of mbostock's Map Pan & Zoom.

Demonstrates map panning and zooming using SVG transforms to avoid the overhead of reprojecting at every zoom iteration.

body {
margin: 0
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;
<script src="//"></script>
<script src="//"></script>
const width = window.innerWidth;
const height = window.innerHeight;
const projection = d3.geoMercator()
.translate([width / 2, height / 2])
.scale((width - 1) / 2 / Math.PI);
const path = d3.geoPath()
const zoom = d3.zoom()
.scaleExtent([1, 8])
.on('zoom', zoomed);
const svg ='body').append('svg')
.attr('width', width)
.attr('height', height);
const g = svg.append('g');;
.then(world => {
.datum({ type: 'Sphere' })
.attr('class', 'sphere')
.attr('d', path);
.datum(topojson.merge(world, world.objects.countries.geometries))
.attr('class', 'land')
.attr('d', path);
.datum(topojson.mesh(world, world.objects.countries, (a, b) => a !== b))
.attr('class', 'boundary')
.attr('d', path);
function zoomed() {
.selectAll('path') // To prevent stroke width from scaling
.attr('transform', d3.event.transform);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.