Swaroop
Swaroop

Reputation: 541

Bubbles in Map not getting zoomed on Map zoom on mouse wheel in d3

I have brought in the zoom functionality on mouse wheel to my world map in d3. I am using the below code for that,

.on("wheel.zoom",function(){
                            var currScale = projection.scale();
                            var newScale = currScale - 2*event.deltaY;
                            var currTranslate = projection.translate();
                            var coords = projection.invert([event.offsetX, event.offsetY]);
                            projection.scale(newScale);
                            var newPos = projection(coords);

                            projection.translate([currTranslate[0] + (event.offsetX - newPos[0]), currTranslate[1] + (event.offsetY - newPos[1])]);
                            g.selectAll("path").attr("d", path);

                        })
                        .call(d3.drag().on("drag", function(){
                            var currTranslate = projection.translate();
                            projection.translate([currTranslate[0] + d3.event.dx,
                                                  currTranslate[1] + d3.event.dy]);
                            g.selectAll("path").attr("d", path);
                        }))  

But my problem is that the bubbles placed on map is not getting zoomed as per the zoomin of map also the location of bubbles getting misplaced. Below is the link for my current working code. https://plnkr.co/edit/jHJ4R1YhI9yPLusUMLh0?p=preview

Upvotes: 1

Views: 166

Answers (1)

Andrew Reid
Andrew Reid

Reputation: 38151

If you update your projection, you need to update all your features to reflect the new projection. You've done this with your path (this in relation to your drag event, as I was unable to scroll wheel zoom, but the principle is the same):

// update projection
var currTranslate = projection.translate();
  projection.translate([currTranslate[0] + d3.event.dx, currTranslate[1] + d3.event.dy]);

// update paths
g.selectAll("path").attr("d", path);

But, you did not update the circles, as circles are not paths.

You can simply re-apply how you positioned the circles in the first place, afterall you are doing the same thing only with an updated projection:

// update projection
var currTranslate = projection.translate();
projection.translate([currTranslate[0] + d3.event.dx, currTranslate[1] + d3.event.dy]);

// update paths coordinates
g.selectAll("path").attr("d", path);

// update circle coordinates                
svg.selectAll(".city-circle")
  .attr("cx",function(d){
              var coords = projection([d.Attribute_Longitude,d.Attribute_Latitude]);
    return coords[0];
  })
  .attr("cy",function(d){
    var coords = projection([d.Attribute_Longitude,d.Attribute_Latitude]);
    return coords[1];
  })

Here's an updated plunker.

Upvotes: 1

Related Questions