6

I am completely new to Google Maps and am just creating my first map so that I can incorporate it into my website.

I am trying to limit the area that the user can move around to just the UK and have looked at several posts on here that all give very similar answers, however I haven't been able to get the code to work for me. This solution is the closest that I have got however whenever I try and move the map at all it centers on one of my boundary points and I am unable to move it anywhere else.

I may have made a really silly mistake, in which case I apologise, however I can't work out what is wrong. Does anyone have any ideas?

Thank you

My code is below (taken from Google's sample code and then added to) - the part that is relevant to the bounds is near the bottom, starting with setting the bounds 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>
Community
  • 1
  • 1
Lucy Grainger
  • 63
  • 1
  • 1
  • 5

3 Answers3

12

Just for anyone who stumbles upon the now-outdated info on this page as I did, the maps API now provides a built-in way to restrict the map viewport bounds via the restriction property of the MapOptions interface, see docs here. This example restricts north-south panning from showing 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}}
    }); 
}
keymap
  • 864
  • 7
  • 16
11

You have your strictBounds mixed up - change the order of them and it should work fine.

A LatLngBounds should be SW corner first, NE corner 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) 
);
Mike Jeffrey
  • 3,149
  • 1
  • 19
  • 18
  • 2
    I have discovered that this method works well when you move the map around with the mouse, however I can still over come the boundaries if I use the navigation tools above the zoom buttons, is there anwyay of preventing this? – Lucy Grainger Feb 02 '12 at 10:59
  • Good catch! You can change the event type in your listener from `dragend` to `bounds_changed`. That looks for any change in the viewport, so it'll include zooming out past the boundaries, dragging, using the nav controls, etc. I'm glad you've got it working! – Mike Jeffrey Feb 02 '12 at 17:25
  • @MikeJeffrey What does the strictBounds means and how do you find the lat long for Singapore map? –  May 21 '14 at 01:20
  • 1
    Hi @Newbie - `strictBounds` is the name that the original poster assigned to a LatLngBounds object - basically a rectangular area on the map. If you want her code to work for your purposes, change the coordinates in `strictBounds`: the first LatLng is the SW corner, the second LatLng is the NE corner. An easy way to find coordinates is to go to maps.google.com, right-click on the location you want coordinates for, and select 'What's here?' The clicked location's coordinates are at the top-left of the window. – Mike Jeffrey May 21 '14 at 15:21
  • Good explanation form all of you guys. Thanks dude – Faris Rayhan Jul 11 '17 at 03:32
5

Above code helped me, but didn't solve my issue. I needed to disable the panning based on polygon drawn on the map. I needed to limit panning to that particular window of the map. So user not pan faraway from the initial 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);
    }
});

}

Ravi
  • 191
  • 2
  • 6