Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps API - load the US

I am new to google maps api. I'd like suggestions on achieving the following functionality: whenever the page loads, the map will load centered around the US. Imagine a box around the US with given lat/longs specifying the minimum and maximum boundaries. I need the map to load at the appropriate zoom (and zoom needs to be disabled) such that this box composes the entire map.

Basically, I'm wondering if there is a function that loads the map based on lat/long boundaries (or some way to acheive this), rather then loading the map given a zoom level.

like image 390
hjk Avatar asked May 29 '10 23:05

hjk


1 Answers

Assuming you are using the v3 API, you may want to use the fitBounds method as follows:

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

   <script type="text/javascript"> 
      var myOptions = { mapTypeId: google.maps.MapTypeId.ROADMAP };
      var map = new google.maps.Map(document.getElementById("map"), myOptions);
      var geocoder = new google.maps.Geocoder();

      geocoder.geocode({'address': 'US'}, function (results, status) {
         var ne = results[0].geometry.viewport.getNorthEast();
         var sw = results[0].geometry.viewport.getSouthWest();

         map.fitBounds(results[0].geometry.viewport);               
      }); 
   </script> 
</body> 
</html>

Screenshot:

Google Maps fitBounds

In the above example, I'm getting the viewport of the US by geocoding. However, you could also create a LatLngBounds object yourself by passing the North East and South West points, and the fitBounds method will zoom and pan your map such that it will fit on the map canvas.

like image 166
Daniel Vassallo Avatar answered Oct 20 '22 16:10

Daniel Vassallo