如何防止在 google 地图上平移外部世界边缘?

How to prevent panning outside world edges on google maps?

首先我要说我已经看了很多 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
      }, ...

但这会阻止 top/bottom 在它仍在平移时进行平移 left/right。

知道为什么吗?

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);
    });

但是当它停止水平平移时,我无法平移到两极所以 top/bottom

根据the documentation

A restriction that can be applied to the Map. The map's viewport will not exceed these restrictions.

latLngBounds

Type: LatLngBounds|LatLngBoundsLiteral
When set, a user can only pan and zoom inside the given bounds. Bounds can restrict both longitude and latitude, or can restrict latitude only. For latitude-only bounds use west and east longitudes of -180 and 180, respectively. For example,
latLngBounds: {north: northLat, south: southLat, west: -180, east: 180}

将经度限制设置为不是 -180/+180 的值。

proof of concept fiddle

代码片段:

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>