在我構建的應用程序中,Google Maps API佔用了大部分(如果不是全部)屏幕。但是,在測試過程中,我發現用戶可以將地圖向下拖動得足夠遠,以便地圖不再顯示,並且所有剩下的都是灰色背景。停止Google Maps API滾動到灰色區域
我該如何解決這個問題?我已經設置了一個minZoom,但這隻能解決頁面加載時和用戶想要縮小的問題。
在我構建的應用程序中,Google Maps API佔用了大部分(如果不是全部)屏幕。但是,在測試過程中,我發現用戶可以將地圖向下拖動得足夠遠,以便地圖不再顯示,並且所有剩下的都是灰色背景。停止Google Maps API滾動到灰色區域
我該如何解決這個問題?我已經設置了一個minZoom,但這隻能解決頁面加載時和用戶想要縮小的問題。
我和你有同樣的問題。我周圍有一種方法是把這個地方你初始化地圖:
google.maps.event.trigger(map, 'resize');
map.setZoom(map.getZoom());
google.maps.event.addListener(map, "idle", function(){
google.maps.event.trigger(map, 'resize');
});
當你拖動地圖,併爲「辦結」這基本上意味着,該事件被觸發,其調整其大小,因此意味着地圖出於某種原因顯示。
如果你認爲他們不喜歡他們,請分享。 :)
您可以檢查地圖的邊界並查看用戶是否在預期範圍外平移,然後禁用平移並返回到地圖區域。
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中解釋)。
該解決方案基於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中的堆棧溢出錯誤,因爲事件將被觸發的次數)