如果有人感兴趣,我会发布我的答案,因为我无法通过此处发布的任何其他解决方案实现我所需要的。
我需要的是限制地图的垂直边界(纬度),这样用户就无法平移到地球的纬度边界之外(~ +/- 85 度),但任何其他边界都可以也是。
此方法使用与其他地方描述的相同的 center_changed 事件,并简单地固定中心,以防显示部分禁止边界。
此机制仅在设置了地图的最小缩放比例时才有效,这样缩小显示的区域永远不会超过允许范围内的区域。
工作示例:http://jsbin.com/vizihe
function initMap() {
// sample bounds, can be anything and goes hand in hand with minZoom
var northBoundary = 40
var southBoundary = -40
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 0, lng: 0},
zoom: 4,
// it's important to set this to a large enough value
// so that zooming out does not show an area larger than allowed
minZoom: 4
})
map.addListener('center_changed', function () {
var bounds = map.getBounds();
var ne = bounds.getNorthEast()
var sw = bounds.getSouthWest()
var center = map.getCenter()
if(ne.lat() > northBoundary) {
map.setCenter({lat: center.lat() - (ne.lat() - northBoundary), lng: center.lng()})
}
if(sw.lat() < southBoundary) {
map.setCenter({lat: center.lat() - (sw.lat() - southBoundary), lng: center.lng()})
}
})
}
html, body, #map {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="limit google map panning">
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
</head>
<body>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap"
async defer></script>
</body>
</html>