Bounded map panning
Prevents the map from being panned/dragged beyond a bounding box
by jamesdh
HTML
<script src="https://maps.google.com/maps/api/js?sensor=false"></script>
<body>
<div id="map"></div>
<div id="coords">
NE Corner Lat,Lng:
<div id="ne"></div>
<br>
SW Corner Lat,Lng:
<div id="sw"></div>
</div>
</body>
CSS
#map {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0
}
#coords {
position: absolute;
left: 10px;
bottom: 25%;
}
#coords div {
background-color: black;
color: white;
}
JavaScript
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: new google.maps.LatLng(38.50, -70.50),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var allowedBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-60, -180), // SW
new google.maps.LatLng(83.5, 180) // NE
);
var changing = false;
google.maps.event.addListener(map, 'center_changed', function () {
if(!changing) {
changing = true;
var allowed_ne_lng = allowedBounds.getNorthEast().lng();
var allowed_ne_lat = allowedBounds.getNorthEast().lat();
var allowed_sw_lng = allowedBounds.getSouthWest().lng();
var allowed_sw_lat = allowedBounds.getSouthWest().lat();
var currentBounds = map.getBounds();
var current_ne_lng = currentBounds.getNorthEast().lng();
var current_ne_lat = currentBounds.getNorthEast().lat();
var current_sw_lng = currentBounds.getSouthWest().lng();
var current_sw_lat = currentBounds.getSouthWest().lat();
$("#ne").text(Math.round(current_ne_lat*10000)/10000 + ", " + Math.round(current_ne_lng*10000)/10000);
$("#sw").text(Math.round(current_sw_lat*10000)/10000 + ", " + Math.round(current_sw_lng*10000)/10000);
var currentCenter = map.getCenter();
var centerX = currentCenter.lng();
var centerY = currentCenter.lat();
var reset = false;
// We have to take special consideration of lng due to the 180/-180 flip at the antipodal meridian
// First, if NE lng < SW lng, it means our bounds crosses the antipodal meridian
// Secondly, in such a case, we must take care for when one of our bounding points cross it
// For this example we're only concerned about the 2nd half of this as we want a standard mercator style map that is bounded by -180/180 on either side.
// In addition, we have to take special considerations due to flukes in how Google...