如何限制谷歌地图API V3中的平移? [英] How do I limit panning in Google maps API V3?

查看:94
本文介绍了如何限制谷歌地图API V3中的平移?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在V2中,有一种方法可以限制平移/拖动,因此地图保持在特定范围内。 V3如何完成?

假设我希望用户只看欧洲。我已经限制了缩放,但是如果我允许拖动(在这种情况下我必须出于其他原因),那么用户可以移动到我想要展示的区域之外。



请给出工作示例或代码片段 - 我不是专家编码人员...



谢谢!



这两个答案都是 Daniel Vassallo and brendo ,用户仍然可以使用pan-control(如果已激活)从想要的区域移开。这个东西@ Yauhen.F在评论中提到。



因此,我不使用dragend事件,而是使用center_changed事件。在拖动过程中以及每次使用平移控制时都会持续触发。

  //所需区域的边界
var allowedBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(70.33956792419954,178.01171875),
new google.maps.LatLng(83.86483689701898,-88.033203125)
);
var lastValidCenter = map.getCenter();

google.maps.event.addListener(map,'center_changed',function(){
if(allowedBounds.contains(map.getCenter())){
//仍然在有效范围内,所以保存上一个有效位置
lastValidCenter = map.getCenter();
return;
}

//不再有效=>返回上一个有效位置
map.panTo(lastValidCenter);
});

通过在拖动过程中连续保存最后一个有效位置,移动一旦超出边界就会停止,而不是在拖动结束后再回头。
......


In V2 there was a way to limit panning/dragging so the map stays within certain bounds. How is that done in V3?

Let's say I want the users to only look at Europe. I've already limited the zoom, but if I allow dragging (which I have to in this case, for other reasons) then the user can pan beyond the area I want to show.

Please give working example or code snippet - I'm not an expert coder...

Thanks!

解决方案

I guess I'm a little bit late to the party, but since this was exactly what I needed just now AND I improved on it, I thought I'd post an answer anyway.

With both the answers of Daniel Vassallo and brendo, the user can still use the pan-control (if it's activated) to move away from the wanted area. The thing @Yauhen.F mentioned in a comment.

So instead of using the dragend event, I use the center_changed event. This is continuously fired during dragging and every time someone uses the pan control.

// bounds of the desired area
var allowedBounds = new google.maps.LatLngBounds(
     new google.maps.LatLng(70.33956792419954, 178.01171875), 
     new google.maps.LatLng(83.86483689701898, -88.033203125)
);
var lastValidCenter = map.getCenter();

google.maps.event.addListener(map, 'center_changed', function() {
    if (allowedBounds.contains(map.getCenter())) {
        // still within valid bounds, so save the last valid position
        lastValidCenter = map.getCenter();
        return; 
    }

    // not valid anymore => return to last valid position
    map.panTo(lastValidCenter);
});

By saving the last valid position continuously during the dragging, the movement will just stop once it's out of bounds, instead of yerking back once the dragging ended. ......

这篇关于如何限制谷歌地图API V3中的平移?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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