谷歌地图API 3 - 限制平移/地图边界

6
我是完全的Google Maps新手,并且正创建我的第一个地图,以便将其整合到我的网站中。
我正在尝试限制用户可以移动的区域仅为英国,并且已经查看了此处发布的几篇文章,所有这些文章都给出非常类似的答案,但我无法让代码为我工作。虽然这个解决方案最接近我的问题,但每当我尝试移动地图时,它就会在我的边界点之一上居中,并且我无法将其移动到其他任何地方。
我可能犯了一个非常愚蠢的错误,在这种情况下,我很抱歉,但我无法弄清楚哪里错了。有人有什么想法吗?
谢谢。
我的代码如下(从Google的示例代码中提取并添加) - 与边界相关的部分靠近底部,从设置英国范围开始:
    <!DOCTYPE html>
    <html>
    <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <title>Google Maps</title>
    <style type="text/css">
        html { height: 100% }
        body { height: 100%; margin: 0; padding: 0 }
        #map_canvas { height: 100% }
    </style>
    <script type="text/javascript"
        src="https://maps.googleapis.com/maps/api/js?key=MYKEY&sensor=false">
    </script>

    <?
    //code to get long and lat from http://www.webmonkey.com/2010/02/get_started_with_google_geocoding_via_http
    $apikey = MYKEY;
    $geourl = "http://maps.google.com/maps/geo?q=LS255AA&output=csv&key=$apikey";

    // Create cUrl object to grab XML content using $geourl
    $c = curl_init();
    curl_setopt($c, CURLOPT_URL, $geourl);
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
    $csvContent = trim(curl_exec($c));
    curl_close($c);

    // Split pieces of data by the comma that separates them
    list($httpcode, $elev, $lat, $long) = split(",", $csvContent);
    ?>

    <script type="text/javascript">
    var lat = "<?= $lat ?>";
    var long = "<?= $long ?>";
    </script>

    <script type="text/javascript">
        function initialize() {
            //sets the long and lat of map
            var myLatlng = new google.maps.LatLng(lat, long);

            //options for the map
            var myOptions = {
                center: myLatlng,
                zoom: 9,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            //creates the map
            var mymap = new google.maps.Map(document.getElementById("map_canvas"),
                myOptions);

            //sets min and max zoom values
            var opt = { minZoom: 7, maxZoom: 11 };
                mymap.setOptions(opt);

            //creates marker
            var marker = new google.maps.Marker({
                position: myLatlng,
                map: mymap,
                title:"Hello World!"
            });

            //content of infowindow
            var contentString = '<h2>I am an info window</h2>'+'<p>Hello my name is infowindow, I need more text to test how big I get</p>';

            //creates infowindow
            var infowindow = new google.maps.InfoWindow({
                    content: contentString,
            });

            //infowindow options
            infowindow.setOptions({maxWidth:200}); 

            //listens for click and opens infowindow
            google.maps.event.addListener(marker, 'click', function() {
                 infowindow.open(mymap,marker);
            });
            // Bounds for UK
            var strictBounds = new google.maps.LatLngBounds(
                    new google.maps.LatLng(60.88770, -0.83496), 
                    new google.maps.LatLng(49.90878, -7.69042)
            );

            // Listen for the dragend event
            google.maps.event.addListener(mymap, 'dragend', function() {
                if (strictBounds.contains(mymap.getCenter())) return;

                // We're out of bounds - Move the map back within the bounds
                var c = mymap.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;

                mymap.setCenter(new google.maps.LatLng(y, x));
            });
        }
    </script>
</head>
<body onload="initialize()">
    <div id="map_canvas" style="width:50%; height:50%"></div>

</body>
</html>
3个回答

12

如果有人像我一样偶然发现了此页面上已过时的信息,那么地图API现在提供了一种内置方式来通过MapOptions接口的restriction属性限制地图视口范围,参见文档这里。以下例子限制了南北平移以避免显示南极洲:

function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: 20, lng: -52},
      zoom: 3,        
      restriction: {latLngBounds:{north: 83.8, south: -57, west: -180, east: 180}}
    }); 
}

11

2
我发现当你用鼠标移动地图时,这种方法效果很好,但是如果我使用缩放按钮上方的导航工具,仍然可以越过边界,有没有什么办法可以防止这种情况发生? - Lucy Grainger
不错!您可以在监听器中将事件类型从“dragend”更改为“bounds_changed”。这将寻找视口中的任何更改,因此它将包括超出边界的缩放、拖动、使用导航控件等。我很高兴看到它运行了! - Mike Jeffrey
@MikeJeffrey 严格边界是什么意思,如何在新加坡地图上找到纬度和经度? - user2424370
1
嗨@新手- strictBounds是原帖作者为LatLngBounds对象分配的名称-基本上是地图上的矩形区域。如果您想让她的代码适用于您的目的,请更改strictBounds中的坐标:第一个LatLng是SW角,第二个LatLng是NE角。查找坐标的简单方法是转到maps.google.com,右键单击要获取坐标的位置,然后选择“这里是什么?”所点击位置的坐标位于窗口左上角。 - Mike Jeffrey
你们所有人都给出了很好的解释。谢谢,伙计。 - Faris Rayhan

5
上述代码对我有所帮助,但没有完全解决我的问题。我需要根据在地图上绘制的多边形来禁用平移操作。我需要限制平移范围在地图窗口内。这样用户就不会从初始地图中平移到其他地方了。
function disablePanning(enableBounds) {
// listen to bound change event once to store the SW and NE corner

google.maps.event.addListener(map, 'bounds_changed', function() {
    // only set it once
    if (enableBounds == null) {
        enableBounds = map.getBounds();
    }
});
var lastValidCenter=null;
google.maps.event.clearListeners(map,'center_changed');
google.maps.event.addListener(map, 'center_changed', function() {
    if(enableBounds!=null && lastValidCenter==null){
        lastValidCenter = enableBounds.getCenter();
    }
    if (enableBounds != null && enableBounds != 'undefined') {
        var ne = enableBounds.getNorthEast();
        var sw = enableBounds.getSouthWest();
        var allowedBounds = new google.maps.LatLngBounds(
                new google.maps.LatLng(sw.lat(), sw.lng()),
                new google.maps.LatLng(ne.lat(), ne.lng()));

        if (allowedBounds.contains(map.getCenter())) {
            // still within valid bounds, so save the last valid position
            lastValidCenter = enableBounds.getCenter();
            return;
        }

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

}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接