2011-01-25 53 views
2

我有我的地图后立即运行下面的代码被初始化fitBounds和getZoom不打不错

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); 
     } 
    }); 
    } 

的问题是THA变焦检查和设置不起作用。我已经检查并启动了地图,但此时map.getZoom()函数返回undefinted。

有什么我可以做的强迫它等待,直到fitbounds已设置和缩放级别已知,所以我可以适当地控制缩放?

+0

类似的问题:http://stackoverflow.com/questions/3506035/google-maps-map-getbounds -immediately-后一个呼叫到MAP-fitbounds – TMS 2013-03-23 09:26:20

回答

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); 
    } 
} 
3

我知道这是一个老问题,但我发现这个解决方案更优雅:

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