Step 6: Zoom

In this step, we will add a zoom functionality to our map.

D3.js draws SVG elements, which are perfectly scalable, as they are vectors. In order to implement a zoom functionality, we therefore have to be able to access the features on the map and scale them.

Map features

We extract the map features.

map.js - extract mapFeatures
13
14
15
16
17
18
19
20
// ...

// We add a <g> element to the SVG element and give it a class to
// style. We also add a class name for Colorbrewer.
var mapFeatures = svg.append('g')
  .attr('class', 'features YlGnBu');

// ...
map.js - add path to mapFeatures
67
68
69
70
71
72
73
74
    // ...

    // We add the features to the <g> element created before.
    // D3 wants us to select the (non-existing) path objects first ...
    mapFeatures.selectAll('path')
        // ... and then enter the data. For each feature, a <path>
        // element is added.
        // ...

We did not really change much, we just did some refactoring by extracting mapFeatures as a variable so we can access it.

Enable zoom

map.js - zoom definition
18
19
20
21
22
23
24
25
26
// ...

// Define the zoom and attach it to the map
var zoom = d3.behavior.zoom()
  .scaleExtent([1, 10])
  .on('zoom', doZoom);
svg.call(zoom);

// ...

Now we need to define the function doZoom() which will actually do the zoom.

map.js - zoom function
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
// ...

/**
 * Zoom the features on the map. This rescales the features on the map.
 */
function doZoom() {
  mapFeatures.attr("transform",
    "translate(" + d3.event.translate + ") scale(" + d3.event.scale + ")");
}

// ...

Next

Proceed to Step 7: Show the name on mouseover.