我试图将Google地图的滚动限制为世界各个方向的一个实例。但是我发现我的地图中心从未包含在我的严格范围内,从我的阅读中可以看出,该范围是一个“世界”的范围。有人知道为什么我的地图中心永远不会包含在我的地图中吗?

编辑:我希望地图的中心在strictBounds内的任何地方都有效...即世界的单个实例(即您不能左右左右滚动两次以查看北美)我的直觉告诉我如果它不包含在我的坐标中,则坐标是错误的,但是this堆栈溢出后告诉我。

// Bounds for world
var strictBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(85, -180),           // top left corner of map
      new google.maps.LatLng(-85, 180)           // bottom right corner
);

var lastValidCenter = map.getCenter();

// Listen for the dragend event
google.maps.event.addListener(map, 'dragend', function() {
  console.log("dragend");
    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;

    console.log(x,y);

    // not valid anymore => return to last valid position
    map.panTo(lastValidCenter);

});

最佳答案

我看到需要进行以下更改:


  
  您的maxY和minY值混合在一起:
  


maxX = strictBounds.getNorthEast().lng(),
minY = strictBounds.getNorthEast().lat(),
minX = strictBounds.getSouthWest().lng(),
maxY = strictBounds.getSouthWest().lat();



  
  如果当前坐标中的任何一个不在严格坐标范围内,则我们要平移到最后一个有效中心:
  


if (x < minX || x > maxX || y < minY || y > maxY)
    map.panTo(lastValidCenter);



  
  根据所需功能的类型,更新lastValidCenter的值:
  


if (x < minX || x > maxX || y < minY || y > maxY)
    map.panTo(lastValidCenter);
else
    lastValidCenter = map.getCenter();



  
  只是我的意见,但我会使用其他事件,而不是使用dragend而不是center_changed这样的直接事件。但这又取决于您所需的功能。

关于javascript - Google Maps将范围限制为一个世界实例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34933144/

10-10 23:31
查看更多