我正在尝试设置边界,这样您就不能平移离开overlayImages边界。然而,尽管我在这里找到了很多线索,但我似乎无法让它发挥作用——我做错了什么?
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.740, lng: -74.18},
zoom : 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var imageBounds = {
north: 40.773941,
south: 40.712216,
east: -74.12544,
west: -74.22655
};
historicalOverlay = new google.maps.GroundOverlay(
'https://i.stack.imgur.com/0mgx2.jpg',
imageBounds);
historicalOverlay.setMap(map);
var strictBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(40.773941, -74.12544),
new google.maps.LatLng(40.712216, -74.22655)
);
// Listen for the dragend event
google.maps.event.addListener(map, 'dragend', function() {
if (strictBounds.contains(map.getCenter())) return;
// We're out of bounds - Move the map back within the bounds
var c = map.getCenter(),
x = c.lng(),
y = c.lat(),
maxX = strictBounds.getNorthEast().lng(),
maxY = strictBounds.getNorthEast().lat(),
minX = strictBounds.getSouthWest().lng(),
minY = strictBounds.getSouthWest().lat();
if (x < minX) x = minX;
if (x > maxX) x = maxX;
if (y < minY) y = minY;
if (y > maxY) y = maxY;
map.setCenter(new google.maps.LatLng(y, x));
});
您混淆了google.maps.LatLngBounds
的参数。第一个是西南角,第二个是东北角。试试这个,而不是你的strictBounds
:
var strictBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(imageBounds.south, imageBounds.west),
new google.maps.LatLng(imageBounds.north, imageBounds.east)
);
如果您还想禁止区域缩小过多或放大过多,可以在创建地图时使用minZoom
和maxZoom
参数,如下所示:
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.740, lng: -74.18},
zoom : 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
minZoom: 12,
maxZoom: 14
});
此外,我建议使用bounds_changed
而不是dragend
,在我看来,它为用户提供了更流畅的体验。所以你会有:
google.maps.event.addListener(map, 'bounds_changed', function() { ...
最后一件事。您使用的算法只确保地图的CENTER不会从strictBounds
中平移出来。因此,当用户在图像两侧平移时,将能够看到底层地图的一部分。使用这种算法不会得到更好的结果(不过,我目前还不知道有更好的解决方案)。