2011-02-04 54 views
2

在我的頁面中,緯度,經度和信息窗口內容存在於名爲obj的對象數組中。Google Maps API V3 infoWindow - 顯示相同內容的所有infoWindows

所以如果我需要第一個對象的屬性的緯度,我可以調用obj [0] .latitude。

每個對象的infoWindow內容存儲在obj [i] .text中。

我正在使用下面的循環遍歷緯度&長值並顯示標記和infoWindows。

 for (x=1; x<=obj.length; x++) 
    { 
     var latlng1 = new google.maps.LatLng(obj[x].latitude, obj[x].longitude);

var marker2 = new google.maps.Marker({ position : latlng1, map : map, icon : prevIcon }); infowindow = new google.maps.InfoWindow(); info = obj[x].text; google.maps.event.addListener(marker2, 'mouseover', function() { infowindow.setContent(info); infowindow.open(map, this); });

}

上面的代碼的工作,但所有的信息窗口中顯示的是最後的obj [I]的.text的內容。

如何將特定infoWindow(obj [x] .text)的infoWindow內容關聯到該infoWindow實例?

如果有人能指出一個解決方案而不使用jQuery或任何其他外部庫會更好。

謝謝,

+2

JavaScript有沒有塊範圍中,將在同一變量每次循環寫。最後,只有1個信息變量,幷包含最後一個obj的文本。 – BGerrissen 2011-02-04 11:15:00

回答

4

應該給你一個很長的路要走。

function attachMarker(data) { 

    var latLng = new google.maps.LatLng(data.latitude, data.longitude); 

    var marker = new google.maps.Marker({ 
     position : latLng, 
     map  : map, // global variable? 
     icon  : prevIcon // global variable? 
    }); 

    google.maps.event.addListener(marker, 'mouseover', function() { 
     infowindow.setContent(data.text); 
     infowindow.open(map, this); 
    }); 

    // add marker here. 

} 

// afaik, you only need 1 instance of InfoWindow if you only change content. 
var infowindow = new google.maps.InfoWindow(); 

var i = obj.length; 
while (i--) { 
    attachMarker(obj[ i ]); 
} 
相關問題