问题描述
(var j = 0; j< layerData [i] .data.length; j ++)对于(var i = 0; i< layerCount; i ++){)的
{
var text = layerData [i] .data [j] .text;
var latlng = new google.maps.LatLng(layerData [i] .data [j] .lat,layerData [i] .data [j] .lng);
var marker = new google.maps.Marker({map:map,position:latlng});
var infowindow = new google.maps.InfoWindow({content:text});
google.maps.event.addListener(marker,'click',function(){infowindow.open(map,marker);});
上面代码中的问题很可能在以 google.maps.event.addListener 开头。无论点击哪个标记,我都会获得一个infowindow,用于数据字段 layerdata [i] .data [j] 中的最后一项。好像我是通过引用调用而不是按值调用的,所以所有监听器的 infowindow 和标记是最后一项数组。
但我怎么能解决这个问题?
非常感谢!
您必须创建一个:(var i = 0; i< layerCount; i ++){
for(var) j = 0; j var text = layerData [i] .data [j] .text;
var latlng = new google.maps.LatLng(layerData [i] .data [j] .lat,layerData [i] .data [j] .lng);
var marker = new google.maps.Marker({map:map,position:latlng});
var infowindow = new google.maps.InfoWindow({content:text});
bindOpenWindow(infowindow,map,marker);
函数bindOpenWindow(infowindow,map,marker)
{
google.maps.event.addListener(marker,'click', function(){infowindow.open(map,marker);});
}
看看是否有帮助;)
for (var i=0; i<layerCount; i++){ for (var j=0; j<layerData[i].data.length; j++){ var text = layerData[i].data[j].text; var latlng = new google.maps.LatLng(layerData[i].data[j].lat, layerData[i].data[j].lng); var marker = new google.maps.Marker({map: map, position: latlng}); var infowindow = new google.maps.InfoWindow({content: text}); google.maps.event.addListener(marker, 'click', function() {infowindow.open(map,marker);}); } }
The problem in the above code most likely is in the line starting with google.maps.event.addListener. Whichever marker I click, I get a infowindow opening up for the last item in the data field of layerdata[i].data[j]. Seems like I am calling by reference and not by value, so infowindow and marker for all listeners are the last items in the arrays.
But how can I solve this?
many thanks!
You have to create a closure:
for (var i=0; i<layerCount; i++){ for (var j=0; j<layerData[i].data.length; j++){ var text = layerData[i].data[j].text; var latlng = new google.maps.LatLng(layerData[i].data[j].lat, layerData[i].data[j].lng); var marker = new google.maps.Marker({map: map, position: latlng}); var infowindow = new google.maps.InfoWindow({content: text}); bindOpenWindow(infowindow, map, marker); } } function bindOpenWindow(infowindow, map, marker) { google.maps.event.addListener(marker, 'click', function() {infowindow.open(map, marker);}); }
See if it helps ;)
这篇关于Javascript:通过数组循环创建监听器,通过引用和值调用问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!