How do I get my D3 map to zoom to a location?

给你一囗甜甜゛ 提交于 2019-12-02 23:04:30

The easiest way to approach this, that I've found, is to set a transform on the g element enclosing the states (#states in the example), based on the bounding box of the state you're zooming to:

// your starting size
var baseWidth = 600;

d3.selectAll('#states path')
    .on('click', function(d) {
        // getBBox() is a native SVG element method
        var bbox = this.getBBox(),
            centroid = [bbox.x + bbox.width/2, bbox.y + bbox.height/2],
            zoomScaleFactor = baseWidth / bbox.width,
            zoomX = -centroid[0],
            zoomY = -centroid[1];

        // set a transform on the parent group element
        d3.select('#states')
            .attr("transform", "scale(" + scaleFactor + ")" +
                "translate(" + zoomX + "," + zoomY + ")");
    });

There's a lot more you can do here to clean it up - give some margin to the final zoom, check whether you should base the zoom on width or height, change the stroke width depending on zoom, animate the transition, etc - but that's the basic concept.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!