8

I've created a d3 map with US states, following this example:

http://bl.ocks.org/mbostock/4699541

and added markers following this SO question:

Put markers to a map generated with topoJSON and d3.js

The problem is that on zoom, the map markers stay in place. I believe I need to translate them into a new position, but not sure how to make that happen.

enter image description here

var width = 900,
  height = 500,
  active = d3.select(null);

var projection = d3.geo.albersUsa()
  .scale(1000)
  .translate([width / 2, height / 2]);

var path = d3.geo.path()
  .projection(projection);

var svg = d3.select(".rebates").append("svg")
  .attr("width", width)
  .attr("height", height);

svg.append("rect")
  .attr("class", "background")
  .attr("width", width)
  .attr("height", height)
  .on("click", reset);

var g = svg.append("g")
  .style("stroke-width", "1.5px");

d3.json("/files/d3-geo/us.json", function(error, us) {
  if (error) { throw error; }

  g.selectAll("path")
    .data(topojson.feature(us, us.objects.states).features)
    .enter().append("path")
    .attr("d", path)
    .attr("class", function(item) {
      return window.US_STATES[item.id].water_authorities > 0 ? 'avail' : 'unavail';
    })
    .on("click", clicked);

  g.append("path")
    .datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; }))
    .attr("class", "mesh")
    .attr("d", path);
});

d3.json('/files/coordinates.json', function(error, coords) {
  if (error) { throw error; }

  svg.selectAll(".mark")
    .data(coords)
    .enter()
    .append("image")
    .attr('class','mark')
    .attr('width', 20)
    .attr('height', 20)
    .attr("xlink:href",'assets/gmap_red.png')
    .attr("transform", function(d) {
      return "translate(" + projection([d[1],d[0]]) + ")";
    });
});

function clicked(d) {
  if (active.node() === this) { return reset(); }
  if (window.US_STATES[d.id].water_authorities === 0) { return; }

  active.classed("active", false);
  active = d3.select(this).classed("active", true);

  var bounds = path.bounds(d),
    dx = bounds[1][0] - bounds[0][0],
    dy = bounds[1][1] - bounds[0][1],
    x = (bounds[0][0] + bounds[1][0]) / 2,
    y = (bounds[0][1] + bounds[1][1]) / 2,
    scale = .9 / Math.max(dx / width, dy / height),
    translate = [width / 2 - scale * x, height / 2 - scale * y];

  g.transition()
    .duration(750)
    .style("stroke-width", 1.5 / scale + "px")
    .attr("transform", "translate(" + translate + ")scale(" + scale + ")");
}

function reset() {
  active.classed("active", false);
  active = d3.select(null);

  rebatesTable.clear().draw();

  g.transition()
    .duration(750)
    .style("stroke-width", "1.5px")
    .attr("transform", "");
}
Community
  • 1
  • 1
Troy
  • 710
  • 1
  • 10
  • 18

1 Answers1

14

Step 1

Add all the points in the group and not in the svg. This will ensure that the marker points translate with the main group.

  g.selectAll(".mark")//adding mark in the group
    .data(marks)
    .enter()
    .append("image")
    .attr('class', 'mark')
    .attr('width', 20)
    .attr('height', 20)
    .attr("xlink:href", 'https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/24x24/DrawingPin1_Blue.png')
    .attr("transform", function(d) {
      return "translate(" + projection([d.long, d.lat]) + ")";
    });

Step2

Negate the scaling effect of the main group. else the markers will come zoomed up.

  g.selectAll(".mark")
  .transition()
    .duration(750)
    .attr("transform", function(d) {
      var t = d3.transform(d3.select(this).attr("transform")).translate;//maintain aold marker translate 
      return "translate(" + t[0] +","+ t[1] + ")scale("+1/scale+")";//inverse the scale of parent
    });        

Step3

On zoom out make the marker scale back to 1.

  g.selectAll(".mark")
    .attr("transform", function(d) {
      var t = d3.transform(d3.select(this).attr("transform")).translate;
      console.log(t)
      return "translate(" + t[0] +","+ t[1] + ")scale("+1+")";
    });   

Working code here

Hope this helps!

Cyril Cherian
  • 32,177
  • 7
  • 46
  • 55
  • 1
    Really excellent answer, thank you! I made a small improvement to step 3 by adding .transform().duration(750) (before .attr(...)) which adds the same kind of easing on zoom-out as on zoom-in. – Troy Dec 18 '15 at 17:05
  • How can I maintain the markers relative position when zooming, rather than moving it to the center of the selected state path? – Nathan Sep 28 '16 at 04:51
  • Inside the `clicked` function the translate is calculated you will have to update it accordingly..to make the marker on the center – Cyril Cherian Sep 28 '16 at 05:03
  • Can you be more specific about the changes to lines 110-116 in your example code, that would allow the pin to stay positioned in the same location in the state shape while zooming in? Thanks – Nathan Sep 29 '16 at 03:12
  • in 110-116 i am in-versing the scale just for the markers. **Reason:** the markers are inside the group which also has the path. we are zooming the group. so naturally the marker image will also zoom. Thus, i am giving 1/scale to the pin so that it does not zoom up. You can comment the lines to see the effect. – Cyril Cherian Sep 29 '16 at 07:28
  • My goal would be to keep the markers at a constant size, while the rest of the image zooms. Much like you get with a Google/Bing Maps marker. The marker stays in the relative same location and size, while the underlying map scales. – Nathan Sep 29 '16 at 20:58
  • I think best if you post a question may be I or some one else can help you get around that. – Cyril Cherian Sep 30 '16 at 03:15
  • 3
    Question posted: https://stackoverflow.com/questions/39796327/issues-with-datamaps-d3-pin-marker-constant-size-and-relative-position-while-zoo along with an answer: http://jsbin.com/barekeyaca/edit?html,output – Nathan Oct 01 '16 at 12:54