Step 6: Zoom¶
In this step, we will add a zoom functionality to our map.
Contents
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.
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');
// ...
|
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¶
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.
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.
Code¶
- For reference, the file
index.html
after step 6: https://github.com/lvonlanthen/data-map-d3/blob/step-06/index.html
- For reference, the file
- For reference, the file
style.css
after step 6: https://github.com/lvonlanthen/data-map-d3/blob/step-06/style.css
- For reference, the file
- For reference, the file
map.js
after step 6: https://github.com/lvonlanthen/data-map-d3/blob/step-06/map.js
- For reference, the file
- The diff view of step 5 and step 6:
https://github.com/lvonlanthen/data-map-d3/compare/step-05...step-06?diff=split