Google Maps API 3 - Limit Pan / Map Borders

I am completely new to Google Maps and just creating my first map so that I can include it in my site.

I am trying to limit the area in which the user can only move to the UK, and looked at a few posts here that all give very similar answers, however I could not get the code to work for me.This solution is the closest that I have , but whenever I try to move a map, it focuses on one of my boundary points and I can’t move it anywhere,

Perhaps I made a really stupid mistake, and in this case I apologize, but I can not understand what is wrong. Does anyone have any ideas?

thank

My code is below (taken from a sample Google code and then added) - the border part is at the bottom, starting with setting borders for the UK:

    <!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>
+5
source share
3 answers

You have your own strict mixture, reorder them, and it should work fine.

A LatLngBoundsmust be the SW corner first, the NE corner the second: 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) 
);
+12
source

The above code helped me, but did not solve my problem. I needed to turn off panning based on the polygon drawn on the map. I needed to limit the panning in this particular map window. Thus, the user cannot evade the original map.

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

}

+5

Just for those who stumbled upon the outdated information on this page, like me, the map API now provides a built-in way to limit the boundaries of the map viewing area through the restrictioninterface property MapOptions, see Documents here . This example restricts panning from north to south to show Antarctica:

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

All Articles