2011-02-04 47 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 ]); 
} 
相关问题