Google Maps API 3 - limit pan/map bounds
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)
);
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}}
});
}
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);
}
});
}