Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 44 ยท Maps and Geo

Zoomable and Interactive Maps

Make D3 maps interactive: pan and zoom with d3.zoom, click-to-zoom on a region with fitExtent, hover highlighting, a draggable rotating globe and map performance tips.

A static map answers one question. An interactive map lets readers ask their own: they zoom into a region, hover for details, spin the globe. D3 combines tools you already know (zoom behaviors, events, transitions) with the geo module, and three approaches cover nearly all cases. This lesson uses the same TopoJSON file as Choropleth and World Maps.

Approach 1: zoom by transforming a group

The simplest approach is to put all map paths into a group and apply the zoom transform to it. Because strokes scale too, divide the stroke width by k so lines stay thin:

Pan and zoom a world map

This works for any projection and is fast because the browser moves one group. Its weakness is that strokes, text and symbols scale too, and curves are not re-simplified at higher zoom.

Approach 2: click a region to zoom to it

A popular pattern: click a country or state and the view glides to fit it. Compute the bounding box with path.bounds(feature) (in pixels) and derive a transform:

JavaScript
function zoomTo(event, d) {
  const [[x0, y0], [x1, y1]] = path.bounds(d);
  event.stopPropagation();
  svg.transition().duration(750).call(
    zoom.transform,
    d3.zoomIdentity
      .translate(width / 2, height / 2)
      .scale(Math.min(8, 0.9 / Math.max((x1 - x0) / width, (y1 - y0) / height)))
      .translate(-(x0 + x1) / 2, -(y0 + y1) / 2),
    d3.pointer(event, svg.node())
  );
}

How it works: the scale makes the box fill 90% of the larger dimension, then the two translate calls move the box centre to the screen centre. Clicking the background should call zoom.transform with d3.zoomIdentity to reset. Calling event.stopPropagation() stops the click from also triggering the background reset.

Click a country to zoom, click the sea to reset

vector-effect: non-scaling-stroke in the CSS keeps lines the same width at any zoom, a simpler fix than dividing by k. Note the double meaning of svg.call(zoom).on("click", ...): the background click only fires if the country handlers stop propagation.

Approach 3: re-project instead of scaling

For a very detailed map (a country at city level) scaling a group of low-resolution shapes looks coarse. The alternative is to change the projection itself on zoom: update projection.scale(baseScale * k).translate([tx, ty]) and redraw every path with path. Shapes are recomputed with proper detail and clipped to the viewport. It costs more CPU per frame, so keep the shapes simple or use canvas.

A draggable globe

With geoOrthographic, dragging should rotate the globe, not pan it. Map the drag distance to rotation angles:

Drag to rotate the globe

event.dx and event.dy are the pointer movement since the last event. Horizontal drag changes the longitude angle (lambda), vertical drag the latitude angle (phi), which is clamped to avoid flipping over the poles. d3.timer runs a callback each animation frame, ideal for continuous spinning.

Hover highlighting and info panels

Interactions on regions follow the same pattern as other marks:

JavaScript
countries.on("pointerenter", function () { d3.select(this).raise().attr("stroke-width", 1.5); })
         .on("pointerleave", function () { d3.select(this).attr("stroke-width", 0.5); });

Update a side panel with d3.select("#info").text(d.properties.name) on enter. Remember to raise() the hovered path so its outline is not hidden by neighbours.

Performance

  • Simplify geometry: use the 110m file for world views; load 50m only when zoomed in.
  • Draw borders once with topojson.mesh and fill the shapes without strokes.
  • Set projection.precision(1) for faster paths.
  • For big maps (thousands of features), render to canvas: create d3.geoPath(projection, context) and it draws directly.
  • Never rebuild the whole DOM on each zoom event; update attributes of existing nodes.
flowchart TD
  Q{"What should happen on drag?"} -->|"slide the flat map"| A["d3.zoom + transform on a group"]
  Q -->|"turn the globe"| B["d3.drag + projection.rotate"]
  Q -->|"see more detail"| C["re-project: change projection.scale"]

Pick the technique from the intended gesture.

Common mistakes

  • Using d3.zoom with an orthographic globe: panning a sphere makes no sense; rotate instead.
  • Forgetting event.stopPropagation() on region clicks when the background also handles clicks.
  • Scaling strokes unintentionally: use vector-effect: non-scaling-stroke.
  • Re-projecting and redrawing thousands of SVG paths per frame; switch to canvas.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you keep stroke width constant when a group is scaled by zoom?

    Scaling a group scales its strokes; the CSS property keeps them in screen pixels, or you divide by the zoom factor.
  2. 2. Which method gives the pixel bounding box of a feature for click-to-zoom?

    path.bounds(feature) returns [[x0, y0], [x1, y1]] in the projected pixel space; geoBounds returns degrees.
  3. 3. What should dragging do on an orthographic globe?

    A sphere is turned, not slid. Update projection.rotate from the drag deltas and redraw.
  4. 4. Why use topojson.mesh for borders on an interactive map?

    One border path instead of hundreds of stroked shapes means less drawing work and no doubled lines.

Summary

  • Zoom a flat map by applying d3.zoom transforms to a group; keep strokes thin with vector-effect.
  • Click-to-zoom uses path.bounds to build a transform and a transition to animate it.
  • Rotate globes with d3.drag and projection.rotate.
  • Re-project or move to canvas when detail and speed demand it.

Next: Reusable Charts and Responsive Design