如何在 Google Maps API V3 中限制平移? [英] How do I limit panning in Google maps API V3?

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

问题描述

在 V2 中,有一种方法可以限制平移/拖动,以便地图保持在特定范围内.在 V3 中是如何做到的?

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...

推荐答案

我想我参加聚会有点晚了,但由于这正是我刚刚需要的并且我对其进行了改进,我想我'无论如何都要发布答案.

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.

Daniel Vassallobrendo,用户仍然可以使用平移控件(如果它被激活)从想要的区域移开.@Yauhen.F 在评论中提到的事情.

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.

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

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. ......

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

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