Google Maps Api v3 - getBounds is undefined

JavascriptGoogle MapsGoogle Maps-Api-3

Javascript Problem Overview


I'm switching from v2 to v3 google maps api and got a problem with gMap.getBounds() function.

I need to get the bounds of my map after its initialization.

Here is my javascript code:


var gMap;
$(document).ready(



function() {

    var latlng = new google.maps.LatLng(55.755327, 37.622166);
    var myOptions = {
        zoom: 12,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    gMap = new google.maps.Map(document.getElementById("GoogleMapControl"), myOptions);

    alert(gMap.getBounds());
}




);

);

So now it alerts me that gMap.getBounds() is undefined.

I've tried to get getBounds values in click event and it works fine for me, but I cannot get the same results in load map event.

Also getBounds works fine while document is loading in Google Maps API v2, but it fails in V3.

Could you please help me to solve this problem?

Javascript Solutions


Solution 1 - Javascript

In the early days of the v3 API, the getBounds() method required the map tiles to have finished loading for it to return correct results. However now it seems that you can listen to bounds_changed event, which is fired even before the tilesloaded event:

<!DOCTYPE html>
<html> 
<head> 
   <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
   <title>Google Maps v3 - getBounds is undefined</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 map = new google.maps.Map(document.getElementById("map"), {
         zoom: 12,
         center: new google.maps.LatLng(55.755327, 37.622166),
         mapTypeId: google.maps.MapTypeId.ROADMAP
      });
      
      google.maps.event.addListener(map, 'bounds_changed', function() {
         alert(map.getBounds());
      });
   </script> 
</body> 
</html>

Solution 2 - Javascript

It should be working, atleast according to the documentation for getBounds(). Nevertheless:

var gMap;
$(document).ready(function() {
    var latlng = new google.maps.LatLng(55.755327, 37.622166);
    var myOptions = {
        zoom: 12,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    gMap = new google.maps.Map(document.getElementById("GoogleMapControl"), myOptions);
    google.maps.event.addListenerOnce(gMap, 'idle', function(){
        alert(this.getBounds());
    });
});

See it working here.

Solution 3 - Javascript

I was saying Salman's solution is better because the idle event is called earlier than the tilesloaded one, since it waits for all the tiles to be loaded. But on a closer look, it seems bounds_changed is called even earlier and it also makes more sense, since you're looking for the bounds, right? :)

So my solution would be:

google.maps.event.addListenerOnce(gMap, 'bounds_changed', function(){
    alert(this.getBounds());
});

Solution 4 - Javascript

In other comments here, it's adviced to use the "bounds_changed" event over "idle", which I agree with. Certainly under IE8 which triggers "idle" before "bounds_changed" on my dev machine at least, leaving me with a reference to null on getBounds.

The "bounds_changed" event however, will be triggered continuously when you'll drag the map. Therefor, if you want to use this event to start loading markers, it will be heavy on your webserver.

My multi browser solution to this problem:

google.maps.event.addListenerOnce(gmap, "bounds_changed", function(){
   loadMyMarkers();
   google.maps.event.addListener(gmap, "idle", loadMyMarkers);
});

Solution 5 - Javascript

Well, i'm not sure if i'm too late, but here's my solution using gmaps.js plugin:

map = new GMaps({...});

// bounds loaded? if not try again after 0.5 sec
var check_bounds = function(){

		var ok = true;

		if (map.getBounds() === undefined)
			ok = false;
				
		if (! ok) 
			setTimeout(check_bounds, 500);
		else {
			 //ok to query bounds here
              var bounds = map.getBounds();
		}	
	}
   
    //call it
	check_bounds();

Solution 6 - Javascript

Adding an answer for 2021.

Map.getBounds() may return undefined initially. The preferred workaround to this is to use the bounds_changed event. Typically, an undefined value will only happen in the initialization of the map and never again.

const map = new google.maps.Map(document.getElementById("map"), {
  zoom: 12,
  center: new google.maps.LatLng(55.755327, 37.622166),
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

map.addEventListener('bounds_changed', () => {
  console.log(map.getBounds());
});

https://developers.google.com/maps/documentation/javascript/reference/map#Map.bounds_changed

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDolceVitaView Question on Stackoverflow
Solution 1 - JavascriptDaniel VassalloView Answer on Stackoverflow
Solution 2 - JavascriptSalman AView Answer on Stackoverflow
Solution 3 - JavascripttreznikView Answer on Stackoverflow
Solution 4 - JavascriptAlmerView Answer on Stackoverflow
Solution 5 - JavascriptFernandoView Answer on Stackoverflow
Solution 6 - JavascriptjpoehneltView Answer on Stackoverflow