Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error - Zoom in D3 map - d3.behavior is undefined

I've started to study D3 a few days, and I'm trying to add a zoom feature for a map that I did.

I'm using this example as a basis, but when I try to adapt to my map I receive this error, and my map disappears

TypeError: d3.behavior is undefined

Here is my code:

var projection = d3.geoMercator()
    .translate([width / 2, height / 2])
    .scale((width - 1) / 2 / Math.PI);

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

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

var svg = d3.select("#map")
    .classed("svg-cont", true)
    .append("svg")
    .attr("preserveAspectRatio", "xMinYMin meet")
    .attr("viewBox", "0 0 560 350")
    .classed("svg-content-responsive", true)
    .append("g");

svg
    .call(zoom)
    .call(zoom.event);

And below

function zoomed() {
    g.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
like image 968
abaporu Avatar asked Jan 28 '18 06:01

abaporu


1 Answers

As pointed out, I was using an old version of D3. With d3.v4, I found that all I need to do is insert

.call(d3.zoom().on("zoom", function () {
    svg.attr("transform", d3.event.transform)
}))

So I got:

var svg = d3.select("#map")
    .append("svg")
    .attr("preserveAspectRatio", "xMinYMin meet")
    .attr("viewBox", "0 0 700 300")
    .classed("svg-content-responsive", true)
    .call(d3.zoom().on("zoom", function () {
        svg.attr("transform", d3.event.transform)
    }));

And it works!

like image 194
abaporu Avatar answered Nov 12 '22 07:11

abaporu