首先,我看过很多SO答案,而this one越来越接近了。
所以基本上我做到了:
var defaultLatLong = {
lat: 45.4655171,
lng: 12.7700794
};
var map = new google.maps.Map(document.getElementById('map'), {
center: defaultLatLong,
zoom: 3,
minZoom: 3,
restriction: {
latLngBounds: {
east: 180,
north: 85,
south: -85,
west: -180
},
strictBounds: true
}, ...
但这可以防止在仍向左/向右平移时顶部/底部平移。
知道为什么吗?
UDPATE
我尝试了以下操作:
var allowedBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(85, 180),
new google.maps.LatLng(-85, -180)
);
var lastValidCenter = map.getCenter();
google.maps.event.addListener(map, 'center_changed', function() {
if (allowedBounds.contains(map.getCenter())) {
// still within valid bounds, so save the last valid position
lastValidCenter = map.getCenter();
return;
}
// not valid anymore => return to last valid position
map.panTo(lastValidCenter);
});
但是当它停止从水平方向平移时,我无法平移至两极,所以顶部/底部
答案 0 :(得分:1)
可以应用于地图的限制。地图的视口不会超出这些限制。
latLngBounds
类型: LatLngBounds | LatLngBoundsLiteral
设置后,用户只能在给定范围内平移和缩放。边界可以限制经度和纬度,也可以仅限制纬度。 对于仅纬度范围,分别使用西经和东经-180和180。例如,
latLngBounds:{北:北拉,南:南拉,西:-180,东:180}
将经度限制设置为非-180 / + 180。
代码段:
function initMap() {
var defaultLatLong = {
lat: 45.4655171,
lng: 12.7700794
};
var map = new google.maps.Map(document.getElementById('map'), {
center: defaultLatLong,
zoom: 3,
minZoom: 3,
restriction: {
latLngBounds: {
east: 179.9999,
north: 85,
south: -85,
west: -179.9999
},
strictBounds: true
}
});
}
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script>