1

我在以下位置使用示例:

Google Maps v3 - 限制可视区域和缩放级别

问题是我确定了自定义地图上的 sw 和 ne 点,但它似乎只能防止基于地图中心的平移,这允许在严格范围之外进行平移。

这是我的代码:

   var strictBounds = new google.maps.LatLngBounds(
     new google.maps.LatLng(sw_lat, sw_lon), 
     new google.maps.LatLng(ne_lat, ne_lon)
   );

   google.maps.event.addListener(map, 'drag', 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));
   });
4

2 回答 2

1

我发现这是一个更清洁的解决方案。它通过基于中心点的侦听/平移来组合功能,但使用检测一组边界是否在另一个范围内的测试。似乎对我来说很完美。

google.maps.event.addListener(map, 'center_changed', function(){

        var mapBounds = map.getBounds();

        if (imageBounds.contains(mapBounds.getNorthEast()) && imageBounds.contains(mapBounds.getSouthWest()))
        {
            lastValidCenter = map.getCenter();
            return;
        }

        map.panTo(lastValidCenter);

    });

// 更新:+ 缺少分号

于 2013-11-26T17:18:45.900 回答
-1

您可能必须使用 map.getBounds 而不是 map.getCenter,并查看它的边缘是否超出了 strictBounds 的范围。

这是完全未经测试的,但我会这样处理它:

   var strictBounds = new google.maps.LatLngBounds(
     new google.maps.LatLng(sw_lat, sw_lon), 
     new google.maps.LatLng(ne_lat, ne_lon)
   );

   google.maps.event.addListener(map, 'drag', function()
   {
        var mapBounds = map.getBounds(),
        map_SW_lat = mapBounds.getSouthWest().lat(),
        map_SW_lng = mapBounds.getSouthWest().lng(),
        map_NE_lat = mapBounds.getNorthEast().lat(),
        map_NE_lng = mapBounds.getNorthEast().lng(),
        maxX = strictBounds.getNorthEast().lng(),
        maxY = strictBounds.getNorthEast().lat(),
        minX = strictBounds.getSouthWest().lng(),
        minY = strictBounds.getSouthWest().lat();

        if (strictBounds.contains(mapBounds.getNorthEast()) && strictBounds.contains(mapBounds.getSouthWest())) 
        {
            return;
        }

        // We're out of bounds - Move the map back within the bounds
        if (map_SW_lng < minX) map_SW_lng = minX;
        if (map_SW_lng > maxX) map_SW_lng = maxX;
        if (map_NE_lng < minX) map_NE_lng = minX;
        if (map_NE_lng > maxX) map_NE_lng = maxX;

        if (map_SW_lat < minY) map_SW_lat = minY;
        if (map_SW_lat > maxY) map_SW_lat = maxY;
        if (map_NE_lat < minY) map_NE_lat = minY;
        if (map_NE_lat > maxY) map_NE_lat = maxY;

        map.panToBounds(new google.maps.LatLngBounds(
        new google.maps.LatLng(map_SW_lat, map_SW_lng), 
        new google.maps.LatLng(map_NE_lat, map_NE_lng)
        ));
    });
于 2012-10-11T13:49:11.690 回答