在我正在构建的应用程序中,Google Maps API 占据了屏幕的大部分(如果不是全部)。然而,在测试过程中,我发现用户可以将地图向下拖动到足够低的位置,以至于地图不再显示,只剩下一个灰色背景。
我该怎么办?我已经设置了最小缩放,但这仅解决了当页面加载并且用户想要缩小视图时的问题。
在我正在构建的应用程序中,Google Maps API 占据了屏幕的大部分(如果不是全部)。然而,在测试过程中,我发现用户可以将地图向下拖动到足够低的位置,以至于地图不再显示,只剩下一个灰色背景。
我该怎么办?我已经设置了最小缩放,但这仅解决了当页面加载并且用户想要缩小视图时的问题。
new google.maps.Map(document.getElementById('map'), {
restriction: {
latLngBounds: {
north: 85,
south: -85,
west: -180,
east: 180
}
},
});
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..
(在旧论坛中的此帖子中有解释)。
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错误,因为事件将被触发多次。
我和你遇到了同样的问题。我解决的方法是在初始化地图的地方加入以下代码:
google.maps.event.trigger(map, 'resize');
map.setZoom( map.getZoom() );
google.maps.event.addListener(map, "idle", function(){
google.maps.event.trigger(map, 'resize');
});
这基本上意味着当您拖动地图并且它“停止移动”时,事件被触发,从而调整其大小,并因此显示地图。
如果您找到了一种非hacky的方法,请分享。:)