在D3 v4中使用zoom.translateExtent约束地图平移 [英] Constraining map panning with zoom.translateExtent in D3 v4
问题描述
我正在尝试显示单个状态的地图,并且缩放和平移限制在该状态的边界.除了在状态路径缩放以适应较小容器时的平移约束之外,它几乎可以正常工作.我认为这归结为我不了解要为zoom.translateExtent
使用什么参数(尽管我对此很陌生,所以可能还有其他原因).
在bl.ocks.org上的实时示例,其中包含与现有技术的链接.
>一个值得注意的事情是我正在为d3.geoPath
使用空投影,因为我使用ogr2ogr
在每种状态的投影坐标中生成一个shapefile.这就是为什么我使用缩放变换将地图适合其容器的原因.
@McGiogen的解决方案几乎是正确的,但是没有想到MIN
需要根据缩放比例因子transform.k
进行更改.
我绘制了一个图表,以查看如何限制svg始终包含在缩放视图中(在我的图形中显示为框的较大,用户只能看到其中的一部分):>
(因为约束x+kw >= w
等效于x >= (1-k)w
,并且对y
使用类似的参数)
因此,假设您的svg
容器尺寸为[w, h]
:
function zoomed() {
var t = d3.event.transform;
t.x = d3.min([t.x, 0]);
t.y = d3.min([t.y, 0]);
t.x = d3.max([t.x, (1-t.k) * w]);
t.y = d3.max([t.y, (1-t.k) * h]);
svg.attr("transform", t);
}
I'm trying to display a map of a single state, with zooming and panning constrained to the boundaries of the state. It's mostly working, except for the panning constraint when the state path is scaled to fit a smaller container. I think this comes down to me not understanding what arguments to use for zoom.translateExtent
(although I'm very new to this, so it could be something else).
Live example on bl.ocks.org, with links to prior art.
One notable thing is that I'm using a null projection for d3.geoPath
, because I used ogr2ogr
to generate a shapefile in projected coordinates for each state. That's why I used a zoom transform to fit the map to its container.
@McGiogen's solution is almost correct but misses that MIN
needs to vary depending on the zoom scale factor transform.k
.
I drew a diagram to see how I needed to constrain my svg to always be contained inside the zoomed view (depicted in my drawing as the LARGER of the boxes, only a portion of which is visible to the user):
(since the constraint x+kw >= w
is equivalent to x >= (1-k)w
, with a similar argument for y
)
thus assuming your svg
container size [w, h]
:
function zoomed() {
var t = d3.event.transform;
t.x = d3.min([t.x, 0]);
t.y = d3.min([t.y, 0]);
t.x = d3.max([t.x, (1-t.k) * w]);
t.y = d3.max([t.y, (1-t.k) * h]);
svg.attr("transform", t);
}
这篇关于在D3 v4中使用zoom.translateExtent约束地图平移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!