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

巧了我就是萌 提交于 2019-12-03 07:56:47

问题


I'm working with D3 and so far I've been able to tweak the chloropleth example to only draw a specific state. This involved simply removing all the other polygon data so that I'm left with the state I need.

I started with this:

and then tweaked things to this:

However, what I'd like to do is to auto pan/zoom the map upon creation so that the state is front and center on the display, like this:

Do I do this through the D3 library? or some independent code (I currently have jquery-svgpan running with d3 to allow for manual panning/zooming) in order to make this happen?


回答1:


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.



来源:https://stackoverflow.com/questions/12467504/how-do-i-get-my-d3-map-to-zoom-to-a-location

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