Google Maps API 3 - 限制平移/地图边界

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Google Maps API 3 - 限制平移/地图边界相关的知识,希望对你有一定的参考价值。

我是谷歌地图的新手,我只是创建了我的第一张地图,以便将其合并到我的网站中。

我试图限制用户可以移动到只有英国的区域,并在这里查看了几个所有给出非常相似的答案的帖子,但是我无法让代码为我工作。 This solution is the closest that I have got然而,每当我尝试移动地图时,它都集中在我的一个边界点上,我无法将其移动到其他任何地方。

我可能犯了一个非常愚蠢的错误,在这种情况下我道歉,但是我无法弄清楚什么是错的。有没有人有任何想法?

谢谢

我的代码如下(取自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>
答案

你有你的strictBounds混乱 - 改变它们的顺序,它应该工作正常。

一个LatLngBounds应该是SW角落第一,NE角落第二:http://code.google.com/apis/maps/documentation/javascript/reference.html#LatLngBounds

var strictBounds = new google.maps.LatLngBounds(
  new google.maps.LatLng(49.90878, -7.69042),
  new google.maps.LatLng(60.88770, -0.83496) 
);
另一答案

上面的代码帮助了我,但没有解决我的问题。我需要根据地图上绘制的多边形禁用平移。我需要将平移限制到地图的特定窗口。所以用户不要偏离最初的地图。

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

}

另一答案

对于那些偶然发现此页面上现在过时的信息的人来说,maps API现在提供了一种通过restriction界面的MapOptions属性来限制地图视口边界的内置方法,请参阅docs here。此示例限制南北向平移显示南极洲:

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

以上是关于Google Maps API 3 - 限制平移/地图边界的主要内容,如果未能解决你的问题,请参考以下文章

如何限制 Google 地图 API V3 中的平移?

Google Maps Geocoding API 使用限制

Google Maps API [Directions API] 航点限制?

检测Google Maps API配额限制

Android Google Maps Direction Api - Api 密钥限制不起作用

Google Maps API OVER QUERY LIMIT 每秒限制