Issues with Datamaps D3 Pin/marker constant size and relative position while zooming
Asked Answered
W

1

5

I have a D3.js Datamaps.js map with pin markers, that I've been trying to implement zooming for.

http://jsbin.com/xoferi/edit?html,output

The image pin markers are 20x20 and the point of the pin (at x+10,y+20) is over the latitude/longitude spot selected.

I'm having issues when zooming the map, with the images drifting from their relative position. For example: take a look a the Iceland pin. As you zoom in it drifts up and to the left.

How can I keep the pins the same size, and in the same relative position while zooming and click-dragging the map?

I've looked for other examples and I'm just not sure what I'm missing. Maybe the viewport size needs to be added to the calculation soemhow. Or maybe the origin of the pin markers needs to be changed from the default. I'm just not sure.

ref: d3 US state map with markers, zooming transform issues

Wizened answered 30/9, 2016 at 16:45 Comment(0)
W
5

Your original calculations make use of the width/height of the marker being 20x20 pixels:

return latLng[0] - 10;

Your "recalcs" need to do this to as well with the resized image. I would stash the "real" x/y positoin in your data, so you can re-perform the calculations:

datum.realx = latLng[0];
if ( latLng ) return latLng[0] - 10;

And then move them in your zoom handler:

map.svg.selectAll("image")
  .attr("height", 20*(1/scale))
  .attr("width", 20*(1/scale))
  .attr("x", function(d){
    return d.realx  - (20*(1/scale)/2);
  })
  .attr("y", function(d){
    return d.realy  - (20*(1/scale));
  }); 
Weywadt answered 30/9, 2016 at 19:51 Comment(1)
Thanks for the help! I've updated the sample with your working solution: jsbin.com/barekeyaca/edit?html,outputWizened

© 2022 - 2024 — McMap. All rights reserved.