2

I have the following code which I am running almost immediately after map is initialised

function showAddress(address) {
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.fitBounds(results[0].geometry.bounds);

        if (map.getZoom() < 12) {
            map.setZoom(12);
        }
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }

The problem is tha the zoom check and set doesn't work. I have checked and the map is initiated but the map.getZoom() function returns undefinted at this time.

Is there anything I can do to force it to wait until the fitbounds have been set and the zoom level is known so I can control the zoom appropriately?

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
paullb
  • 4,293
  • 6
  • 37
  • 65
  • Similar question: http://stackoverflow.com/questions/3506035/google-maps-map-getbounds-immediately-after-a-call-to-map-fitbounds – Tomas Mar 23 '13 at 09:26

2 Answers2

3
  // Define the Bounds Changed event handler to do a "once-only" zoom level check
  google.maps.event.addListener(map, 'bounds_changed', function() {
    InitialZoomCheck()
  });

geocoder.geocode( { 'address': address}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
    map.fitBounds(results[0].geometry.bounds);




function InitialZoomCheck() {

  // Re-define the event handler so that this routine is called only once
  google.maps.event.addListener(map, 'bounds_changed', function() {
    document.posicion.z.value=map.getZoom()
  });

  if (map.getZoom() > 12) {
    map.setZoom (12);
  }
}
mattalxndr
  • 9,143
  • 8
  • 56
  • 87
Wazza
  • 31
  • 2
3

I know it's an old question, but i found this solution more elegant:

google.maps.event.addListenerOnce(map, 'bounds_changed', function() {
    if(map.getZoom() > 16) map.setZoom(16);
});
map.fitBounds(latlngbounds);