我正在尝试设置边界,以便您无法远离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(
'http://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));
});
答案 0 :(得分:1)
您混合了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() { ...
最后一件事。您使用的算法只能确保地图的中心不会超出strictBounds
。因此,当在图像的两侧平移时,用户将能够看到底层地图的一部分。使用这种算法你不会得到更好的结果(尽管我目前还不知道更好的解决方案)。