停止Google Maps API滚动到灰色区域

时间:2012-08-10 14:25:17

标签: google-maps

在我正在构建的应用程序中,Google Maps API会占用大部分(如果不是全部)屏幕。但是,在测试过程中,我发现用户可以将地图拖得足够远,以便不再显示地图,剩下的就是灰色背景。

我怎么能阻止这个?我设置了一个minZoom,但这只解决了加载页面和用户想要缩小的问题。

4 个答案:

答案 0 :(得分: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..(在旧论坛的this post中进行了解释)。

答案 1 :(得分:1)

此解决方案基于Marcelo的非常好的答案,但是一旦地图超出了世界的最大或最小纬度,他的解决方案将完全禁用任何进一步的拖动(包括有效拖动地图的可见区域)。这是一个澄清的版本,如果用户通过拖动超过最大或最小纬度,将拉回地图。它仍然允许用户拖动所有可见区域。

此外,此解决方案还为地图设置了最小缩放级别,可用于确保尝试的缩放不会导致地图显示灰色区域。

(另见How do I limit panning in 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错误,因为事件将被触发的次数)

答案 2 :(得分:1)

新解决方案

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

答案 3 :(得分:-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方式,请分享。 :)