Google Maps fitBounds is not working properly

user160820 picture user160820 · Aug 4, 2010 · Viewed 21.7k times · Source

I have a problem with googlemaps fitBounds functions.

for (var i = 0; i < countries.length; i++) {
 var country = countries[i];
 var latlng = new google.maps.LatLng(parseFloat(country.lat), parseFloat(country.lng));
 mapBounds.extend(latlng); 
}

map.fitBounds(mapBounds);

Some icons will be displayed outside the viewport / Visible area.

And idea?

Thanks in advance.

Answer

Daniel Vassallo picture Daniel Vassallo · Aug 5, 2010

Consider the following example, which will generate 10 random points on the North East USA, and applies the fitBounds() method.

<!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 USA
     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>

Refreshing this example many times, no marker ever goes outside the viewport. At most, sometimes a marker is slightly clipped from the top when hidden behind the controls:

Google Maps LatLngBounds.extend() Demo

It is also worth nothing that the fitBounds() always leaves a small margin between the LatLngBounds object and the viewport. This is clearly shown in the screenshots below, where the red bounding box represents the LatLngBounds which is passed to the fitBounds() method:

fitBounds Padding

fitBounds Padding

You may also be interested in checking out the following Stack Overflow posts on the topic: