getBounds() in Google Maps API v3

If you need to know the latitude and longitude for the corners of the visible area of the google map, you’ll probably use something like getBounds(); 

In Google Maps API v2, to get them, you will do something like this:

var bounds = map.getBounds();
var southWest = bounds.getSouthWest();
var northEast = bounds.getNorthEast();

But in API v3 you will get “bounds is undefined” error.

So to get our latitude and longitude we need to move getBounds(), to some event listener.

Most common probably will be bounds_changed:

<script type="text/javascript">
         var map = new google.maps.Map(document.getElementById("map"), {
                 zoom: 10,
                 center: new google.maps.LatLng(lat, lng),
                 mapTypeId: google.maps.MapTypeId.ROADMAP
         });
         google.maps.event.addListener(map, 'bounds_changed', function() {
                  var bounds =  map.getBounds();
                  var ne = bounds.getNorthEast();
                  var sw = bounds.getSouthWest();
                  //do whatever you want with those bounds
         });
</script>

Description of bounds_changed in documentation is: “This event is fired when the viewport bounds have changed.”

It seems, that it’s the best moment to get our bounds. But if you want to make some ajax call in it, then every time when position of map has changed the ajax call will be fired. Most of the time we don’t need to firing ajax until we get our final map. With this event every zoom or panning will fire ajax call.

In my opinion, better solution is to use event “idle”. Especially if you want to make that ajax call. Description says: “This event is fired when the map becomes idle after panning or zooming.”. So the code will look like that:

<script type="text/javascript"> 
         var map = new google.maps.Map(document.getElementById("map"), {
                 zoom: 10,
                 center: new google.maps.LatLng(lat, lng),
                 mapTypeId: google.maps.MapTypeId.ROADMAP
          });
         google.maps.event.addListener(map, 'idle', function() {
                  var bounds =  map.getBounds();
                  var ne = bounds.getNorthEast();
                  var sw = bounds.getSouthWest();
                  //do whatever you want with those bounds
         });
</script>

But you can choose event which will suits your needs, not mine ;o). Just read description of them in documentation of google.maps.Map class – section events and decide which one is best for you.

4.2 5 votes
Article Rating