2010-12-17 56 views
1

我有這段JavaScript代碼動態谷歌地圖縮放的getBounds()未定義

var myOptions = { 
     zoom:9, 
     mapTypeId: google.maps.MapTypeId.ROADMAP, 
     mapTypeControl: false 
    } 
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
    var latlongcollection = new Array(); 
      // some more code to push latlng objects into latlongcollection 
    map.setCenter(latlongcollection[0]); 

    for(latlong in latlongcollection){ 
     map.getBounds().extend(latlong); 
    } 

    map.fitBounds(map.getBounds()); 

但每次它給我的錯誤map.getBounds()是不確定的。中心設置,甚至。在我調用map.getBounds()之前設置縮放。使用新google.maps.LatLngBounds對象,而不是map.getBounds()的請幫忙

回答

2

嘗試:

var bounds = new google.maps.LatLngBounds() 
// note: this for/in loop is erronous 
//for(latlong in latlongcollection){ 
// bounds.extend(latlong); 
//} 
for (var i = 0,len=latlongcollection.length;i<len;i++) { 
    bounds.extend(latlongcollection[ i ]); 
} 
map.fitBounds(bounds); 

此外,您所使用循環與數組一起壞。數組中的for/in不僅會循環索引值,還會循環使用屬性和方法。所以你會延長你的界限.length和.push等等。這本身也可能導致了錯誤。始終讀取for/in循環爲:

for property in object 

其中包括方法等。

相關問題