如何获得我的D3地图放大到一个位置? [英] How do I get my D3 map to zoom to a location?

查看:219
本文介绍了如何获得我的D3地图放大到一个位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用D3,到目前为止,我已经能够调整chlorpleth例子只绘制一个特定的状态。这包括简单地删除所有其他多边形数据,使我留在我需要的状态。

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:

但是, 'd喜欢做的是在创建时自动平移/缩放地图,使状态在显示器前面和中心,如下所示:

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:

我通过D3库做这件事吗?或者一些独立的代码(我目前有jquery-svgpan运行与d3允许手动平移/缩放),以使这种情况发生?

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?

推荐答案

我找到的最简单的方法是在 g 元素上设置一个变换,包含状态(

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.

这篇关于如何获得我的D3地图放大到一个位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆