Dan
Dan

Reputation: 27

D3 zoom is constantly zooming down and right of SVG, how do I fix this?

I have a geographical map which I am trying to add zoom functionality to using D3. I am able to zoom but it seems like whenever I do it is constantly zooming down and to the right of where my cursor is. How can I make it so it zooms to the location of the cursor?

Below is a plunk of all my code. The zoom function is in "main.js". It's used in the "map" variable and is created right after that.

 //create a new svg element with the above dimensions
var map = d3.select("body")
            .append("svg")
            .attr("width", width)
            .attr("height", height)
            .call(d3.zoom()
                .scaleExtent([1/2, 4])
                .on("zoom", zoomed));

//zoom function used above                
function zoomed() {
  map.attr("transform", d3.event.transform);
}

http://plnkr.co/edit/0S1OJr?p=preview

Upvotes: 1

Views: 317

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102174

You should transform a <group> element, not the SVG:

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

//creating a group element named 'map':
var map = svg.append("g").call(d3.zoom()
    .scaleExtent([1 / 2, 4])
    .on("zoom", zoomed));

function zoomed() {
    map.attr("transform", d3.event.transform);
    //applying the transform to 'map'
}

Here is the updated plunker: http://plnkr.co/edit/B0o0tULpve1rbpyRgFpz?p=preview

Upvotes: 1

Related Questions