Dynamically adding listeners in Google Maps where iframe src is set differently for each marker
Hi I've read the articles and the excellent piece on scope and closures by Robert Nyman. However i cannot get this to work. I'm trying to assign a mouseover event to various markers and then set an iframe src depending on the marker moused over. I get the infamous last entry for every mouseover event. I've played with it for the better part of a few days and not even the 'thinking fluid' is helping :). Any guidance appreciated
for(var i=0; i
var latlngr = new google.maps.LatLng(mylatd,mylongd);
markerno = "marker_"+i;
开发者_高级运维 markerarray[i] = new google.maps.Marker({
position: latlngr,
map: map,
title:myname
});
google.maps.event.addListener(markerarray[i], 'mouseover', function(markerno)
{return function()
{
mysrc = 'http://adds.aviationweather.gov/metars/index.php?submit=1&station_ids='+myicao+'&chk_metars=on&chk_tafs=on&std_trans=translated';
alert (mysrc);
$('#weather').attr({src: mysrc});
}(markerno)
});
}
I think you can solve your problem by wrapping your block in a self-executing wrapper function:
for(var i = 0; i < someLength; i++) (function(i){
// Your internal code here. i will be bound to it's value in the correct context
})(i);
'Thinking fluid doesn't work' - clarity of thought in the mornings does. I resolved it by looking a little more closely at what i was doing. I had a closure issue and wasn't even passing the correct variable into the function i was creating. This works - but thanks for the ideas.
for(var i=0; i
var latlngr = new google.maps.LatLng(mylatd,mylongd);
markerarray[i] = new google.maps.Marker({
position: latlngr,
map: map,
title:myname
});
google.maps.event.addListener(markerarray[i], 'mouseover',
function(myair)
{return function()
{
mysrc = 'http://adds.aviationweather.gov/metars/index.php?submit=1&station_ids='+myair+'&chk_metars=on&chk_tafs=on&std_trans=translated';
$('#weather').attr({src: mysrc});
};}
(myicao));
}
精彩评论