我有以下代码,我在初始化地图后几乎立即运行
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);
}
});
}
问题是缩放检查和设置不起作用。我已经检查并启动了地图,但map.getZoom()函数此时返回undefinted。
我有什么办法可以强迫它等到设置好配合并且缩放级别已知,这样我才能适当地控制缩放?
答案 0 :(得分: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);
}
}
答案 1 :(得分:3)
我知道这是一个老问题,但我发现这个解决方案更优雅:
google.maps.event.addListenerOnce(map, 'bounds_changed', function() {
if(map.getZoom() > 16) map.setZoom(16);
});
map.fitBounds(latlngbounds);