I am using Google Maps API (v3) to render a world map. When I zoom all the way out (to zoom level 1) and start dragging the canvas, I am able to move out of the map boundaries, and the area outside shows up in grey color. I want to prevent the user from dragging the map outside the boundaries of the world map. How do I do that?
Google Maps api has the corresponding option: https://developers.google.com/maps/documentation/javascript/reference/map#MapRestriction.latLngBounds. Need to add something like:
restriction: {
latLngBounds: { north: 85, south: -85, west: -180, east: 180 }
}
to the initial options of the map.
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(0,0);
var myOptions = {
zoom: 1,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
map.addListener( 'drag', function() { handle(); });
//map.addListener( 'zoom_changed', function() { handle(); });
}
function handle(){
var proj = map.getProjection();
var bounds = map.getBounds();
var sLat = map.getBounds().getSouthWest().lat();
var nLat = map.getBounds().getNorthEast().lat();
if (sLat < -85 || nLat > 85) {
// alert('Gray area visible');
map.setOptions({
zoom: 1,
center: new google.maps.LatLng(
0 , // set Latitude for center of map here
0) // set Langitude for center of map here
});
//Map.fitBounds(boundsNew);
// Or Define bound that u want show
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps</title>
<script async defer src="https://maps.googleapis.com/maps/api/js">
</script>
</head>
<body onload="initialize()" >
<div id="map_canvas" style="width:500px;height:500px;"></div>
</body></html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With