阻止谷歌地图API滚动到灰色区域

5

在我正在构建的应用程序中,Google Maps API 占据了屏幕的大部分(如果不是全部)。然而,在测试过程中,我发现用户可以将地图向下拖动到足够低的位置,以至于地图不再显示,只剩下一个灰色背景。

我该怎么办?我已经设置了最小缩放,但这仅解决了当页面加载并且用户想要缩小视图时的问题。

4个回答

18
新方案
new google.maps.Map(document.getElementById('map'), {
restriction: {
    latLngBounds: {
        north: 85,
        south: -85,
        west: -180,
        east: 180
    }
},
});

这对我有用,通过将限制选项添加到现有的地图选项中,灰色区域消失了。 - brucelin
成功。谢谢。 - Sherali Turdiyev

8
您可以检查地图的范围并查看用户是否超出了预期范围,如果是,则禁用平移并返回到地图区域。
map.getBounds().getSouthWest().lat() must be > -85

map.getBounds().getNorthEast().lat() must be < 85

那么,举个例子:
  G.event.addListener(map, 'drag', checkLatitude);

然后

function checkLatitude(){
    var proj = map.getProjection();
    var bounds = map.getBounds();
    var sLat = map.getBounds().getSouthWest().lat();
    var nLat = map.getBounds().getNorthEast().lat();
    if (sLat < -85 || nLat > 85) {
//gray areas are visible
         alert('Gray area visible');
         map.setOptions({draggable:false});
  //return to a valid position
    }

}

-85和85的极限值仅为近似值。 确切的值为atan(sinh(PI)) *180 / PI = 85.05112878..(在旧论坛中的此帖子中有解释)。


3
这个解决方案基于Marcelo的非常好的答案,但是他的解决方案会完全禁用任何进一步的拖动(包括地图可见区域的有效拖动),一旦地图超出了世界最大或最小纬度。这里是一个澄清版,如果用户通过拖动超过了最大或最小纬度,它将把地图拉回到视图中。它仍然允许用户拖动所有可见区域。
此外,此解决方案为地图设置了最小缩放级别,可以用来确保尝试缩放不会导致地图显示灰色区域。
(另请参见如何限制Google Maps API V3中的平移?
var lastValidCenter;
var minZoomLevel = 2;

setOutOfBoundsListener();

function setOutOfBoundsListener() {
        google.maps.event.addListener(map, 'dragend', function () {
            checkLatitude(map);
        });
        google.maps.event.addListener(map, 'idle', function () {
            checkLatitude(map);
        });
        google.maps.event.addListener(map, 'zoom_changed', function () {
            checkLatitude(map);
        });
};

function checkLatitude(map) {
    if (this.minZoomLevel) {
        if (map.getZoom() < minZoomLevel) {
            map.setZoom(parseInt(minZoomLevel));
        }
    }

    var bounds = map.getBounds();
    var sLat = map.getBounds().getSouthWest().lat();
    var nLat = map.getBounds().getNorthEast().lat();
    if (sLat < -85 || nLat > 85) {
        //the map has gone beyone the world's max or min latitude - gray areas are visible
        //return to a valid position
        if (this.lastValidCenter) {
            map.setCenter(this.lastValidCenter);
        }
    }
    else {
        this.lastValidCenter = map.getCenter();
    }
}

我没有使用'center_changed'监听器。在地图被平移时,'center_changed'事件会不断触发,这可能会阻止用户将地图平移到灰色区域,而是“弹回”。这可能会在Chrome中导致stackoverflow错误,因为事件将被触发多次。


-1

我和你遇到了同样的问题。我解决的方法是在初始化地图的地方加入以下代码:

            google.maps.event.trigger(map, 'resize');
            map.setZoom( map.getZoom() );

            google.maps.event.addListener(map, "idle", function(){
                google.maps.event.trigger(map, 'resize');
            }); 

这基本上意味着当您拖动地图并且它“停止移动”时,事件被触发,从而调整其大小,并因此显示地图。

如果您找到了一种非hacky的方法,请分享。:)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接