Google地图在完全缩小时无限制平移。我将最小缩放级别限制为2
:
// Limit the zoom level
google.maps.event.addListener(map, 'zoom_changed', function () {
// This is the minimum zoom level that we'll allow
var minZoomLevel = 2;
if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
});
现在的问题是地图上方和下方都有灰色区域。我想将平移限制为仅限地图边界。好的例子是原始的Google Maps。
我尝试使用从Northeast
到Southwest
的世界地图范围:
var allowableBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(85, -180), // top left corner of map
new google.maps.LatLng(-85, 180) // bottom right corner
);
使用此对象allowableBounds
限制可视区域:
// 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() {
var mapBounds = map.getBounds();
var mapNe = mapBounds.getNorthEast();
var mapSw = mapBounds.getSouthWest();
var center = map.getCenter();
if( allowedBounds.contains(mapNe) && allowedBounds.contains(mapSw) ) {
//the user is scrolling within the bounds.
lastValidCenter = center;
return;
}
//the user has scrolled beyond the edge.
var mapWidth = mapNe.lng() - mapSw.lng();
var mapHeight = mapNe.lat() - mapSw.lat();
var x = center.lng();
var y = center.lat();
var maxX = allowedBounds.getNorthEast().lng();
var maxY = allowedBounds.getNorthEast().lat();
var minX = allowedBounds.getSouthWest().lng();
var minY = allowedBounds.getSouthWest().lat();
//shift the min and max dimensions by 1/2 of the screen size, so the bounds remain at the edge of the screen
maxX -= (mapWidth / 2);
minX += (mapWidth / 2);
maxY -= (mapHeight / 2);
minY += (mapHeight / 2);
if (x < minX) {
x = minX;
}
if (x > maxX) {
x = maxX;
}
if (y < minY){
y = minY;
}
if (y > maxY){
y = maxY;
}
map.panTo(new google.maps.LatLng(y, x));
});
但是我收到了这个错误:Uncaught RangeError: Maximum call stack size exceeded
似乎限制了最小缩放级别没有引用它。是否有更简单的谷歌地图属性来限制类似于谷歌地图的无限平移?