How to Use LatLngBounds in Google Maps

  • google plus

In Brief...

An instance of the LatLngBounds class represents a rectangle in geographical coordinates. Here's how to create and use a LatLngBounds instance in Google Maps.

Instructions

  1. Start with the following basic Google Map with no options specified. Make sure to replace YOUR_API_KEY in the script tag with your API key that you got from https://developers.google.com/maps.
  2. 
    <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8">
    	<title>A Basic Map</title>
    	<style>
    		#map {
    			height: 100%;
    		}
    		/* Optional: Makes the sample page fill the window. */
    		html, body {
    			height: 100%;
    			margin: 0;
    			padding: 0;
    		}
    	</style>
    	<script>
    	function initMap() {
    		var mapOptions = {
    			zoom: 8,
    			center: new google.maps.LatLng(44, -110),
    			mapTypeId: 'roadmap'
    		};
    		var map = new google.maps.Map(document.getElementById('map'), mapOptions);
    	}
    	</script>
    </head>
    <body>
    <div id="map"></div>
    <script async defer
    		src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
    </body>
    </html>
    
  3. Add an event listener inside the initMap() function to detect changes to the current map boundaries.
  4. 
    function initMap() {
    	var mapOptions = {
    		zoom: 8,
    		center: new google.maps.LatLng(44, -110),
    		mapTypeId: 'roadmap'
    	};
    	var map = new google.maps.Map(document.getElementById('map'), mapOptions);
    	google.maps.event.addListener(map, 'bounds_changed', function() {
    
    	});
    }
    
  5. Use an alert() containing the map.getBounds() function to display the current LatLngBounds object's values when they change.
  6. 
    function initMap() {
    	var mapOptions = {
    		zoom: 8,
    		center: new google.maps.LatLng(44, -110),
    		mapTypeId: 'roadmap'
    	};
    	var map = new google.maps.Map(document.getElementById('map'), mapOptions);
    	google.maps.event.addListener(map, 'bounds_changed', function() {
    		alert(map.getBounds());
    	});
    }
    
  7. Open your web page in a browser.
  8. Click and drag on the map to change the boundries. An alert will appear and show you the four coordinates of the LatLngBounds object that make up the current boundaries of the map.
    Viewing the LatLngBounds

Author: Chris Minnick

Chris is a prolific author and trainer, and the CEO of WatzThis?. His published books include Writing Computer Code, JavaScript for Kids, Coding with JavaScript For Dummies, Beginning HTML5 and CSS3 For Dummies, Webkit For Dummies, CIW eCommerce Certification Bible, and New Riders' XHTML.

Discuss