Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the smallest LatLngBounds that still contains a set of Lat/Long Coordinates in Google Maps JS API?

I need to plot a set of coordinates on the map in response to a user selection, and when it happens, I'd like to pan the map to focus on that set of points. How can I find the smallest bounding box (LatLngBounds) that contains all of the coordinates?

like image 789
airportyh Avatar asked Jul 30 '10 15:07

airportyh


People also ask

How do I get latitude and longitude from Google Maps API?

That's right, you can go straight to the simplest page on the Internet—google.com—and enter your latitude and longitude into the search box. Usually coordinates are listed with latitude first, then longitude. Double check that is the case and that you've included a comma between the numbers.

How do I see Geocodes on Google Maps?

Getting startedGo to the Google Cloud Console. Click the Select a project button, then select the same project you set up for the Maps JavaScript API and click Open. From the list of APIs on the Dashboard, look for Geocoding API. If you see the API in the list, you're all set.


1 Answers

In addition to the Stack Overflow post which @Crescent Fresh pointed to above (which is using the v2 API), the method you'd want to use is the LatLngBounds.extend().

Here's a complete example, using the v3 API:

<!DOCTYPE html>
<html> 
<head> 
   <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
   <title>Google Maps LatLngBounds.extend() Demo</title> 
   <script src="http://maps.google.com/maps/api/js?sensor=false" 
           type="text/javascript"></script> 
</head> 
<body> 
   <div id="map" style="width: 400px; height: 300px;"></div> 

   <script type="text/javascript"> 

   var map = new google.maps.Map(document.getElementById('map'), { 
     mapTypeId: google.maps.MapTypeId.TERRAIN
   });

   var markerBounds = new google.maps.LatLngBounds();

   var randomPoint, i;

   for (i = 0; i < 10; i++) {
     // Generate 10 random points within North East America
     randomPoint = new google.maps.LatLng( 39.00 + (Math.random() - 0.5) * 20, 
                                          -77.00 + (Math.random() - 0.5) * 20);

     // Draw a marker for each random point
     new google.maps.Marker({
       position: randomPoint, 
       map: map
     });

     // Extend markerBounds with each random point.
     markerBounds.extend(randomPoint);
   }

   // At the end markerBounds will be the smallest bounding box to contain
   // our 10 random points

   // Finally we can call the Map.fitBounds() method to set the map to fit
   // our markerBounds
   map.fitBounds(markerBounds);

   </script> 
</body> 
</html>

Screenshot:

Google Maps LatLngBounds.extend() Demo

like image 145
Daniel Vassallo Avatar answered Oct 08 '22 23:10

Daniel Vassallo