GARY PANG

Blog of YouTube's PangOfHunger

D3.js Map with zoom slider

(Update Oct. 2, 2016: I have made new D3.js maps of the world. You can see them at http://codewritingcow.com/d3-js/maps/)

When a co-worker tested my zoomable map of local gas stations, he couldn’t figure out how to zoom.

He’s a tech-savvy guy. However, my map had no visual cue telling him what to do.

I added two buttons (“+” and “-“) but had trouble adding zoom functions to them.

Fortunately, I stumbled upon another solution: zoom sliders! Someone posted the code for a nice slider at http://bl.ocks.org. So I “borrowed” it for my map.


Here’s the zoom function from my previous maps, with a new line added:

var zoom = d3.behavior.zoom()
    .scaleExtent([1, 10])
    .on("zoom", zoomed);

function zoomed() {
  features.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
  slider.property("value",  d3.event.scale); // THIS IS THE NEW LINE
}

Here’s what creates the zoom slider. Part One:

var slider = d3.select(".wpd3-765-0").append("p").append("input")
  .datum({})
  .attr("type", "range")
  .attr("value", zoom.scaleExtent()[0])
  .attr("min", zoom.scaleExtent()[0])
  .attr("max", zoom.scaleExtent()[1])
  .attr("step", (zoom.scaleExtent()[1] - zoom.scaleExtent()[0]) / 100)
  .on("input", slided);

And Part Two:


function slided(d){
  zoom.scale(d3.select(this).property("value"))
    .event(svg_slider_map);
}

In Part One, instead of writing:

d3.select("body)

I wrote:

d3.select(".wpd3-765-0")

Here’s a good explanation of why I did that. This is one of the quirks of using Wp-D3, a WordPress plug-in for D3.js. I can’t complain, though. This neat plug-in allows me to use D3.js on WordPress.

Demosthenes.info has a good primer on the HTML5 range Slider Input.


 

Hmm … the map behaves very differently when I zoom with the slider and with the mouse.

If I use the mouse scroll button to zoom into, let’s say Danville, Pennsylvania, and then I use the slider, the map moves to a different location.

But if I touch the map with the mouse (click, drag or zoom on the map), then the map goes back to Danville at the zoom level (scale) where I left it off!

I’ll address this problem further in my next post and work on a solution.


2 Comments

  1. Thanks for posting this, the extra line in the zoomed function was exactly what I was lacking.

    • Hello Tim, glad I could be of help! I’d love to see what you’re making with D3.js. This site now focuses on food and cooking, but it was once my “online lab” for practicing D3.js and JavaScript. In the future I might launch another site for D3.js tutorials. Anyway, thank you for visiting!

Leave a Reply

Your email address will not be published. Required fields are marked *

© 2019 GARY PANG

Theme by Anders NorenUp ↑