Hi, I'm putting google maps markers into array, and everything works fine, when i do it manually:
var m =[];
m[0] = new google.maps.Marker(.....
google.maps.event.addListener(m[0], 'click', function()
{
alert('Markerklik');
$("#trasa").append(m[0].getPosition().toString()+"<br>");
});
m[1] = new google.maps.Marker( .....
google.maps.event.addListener(m[1], 'click', function()
{
alert('Markerklik');
$("#trasa").append(m[1].getPosition().toString()+"<br>");
});
But if i want to loop with for:
for ( var i=0 ; i<2; i++ )
{
// do the same with m[i]
}
Im getting m[i] is undefined when clicking a marker (m[i].getPosition()).
Any suggestions how to do it automatically with loop ?
Note, that if i put marker into variable temp, add listener to temp and do a m.push( temp ); in loop - clicking on any marker giving me position of last added marker.
This looks like adding a event to m[i] doesn't even check value of i, it's not looking for m[1] for example, but something like variable "named" m[i]
if i do all the code manualy with m[0] and m[1] - everythings work fine, there are events connected to m[0] and m[1], but creating markers with for loop with m[i] looks like binding event not to m[0] and after one loop m[1], but adding event to "m[i]" when i is just letter i, not a value of i
Ok, looks like this code from a response works:
for (var i=0 ; i<2; i++ )
{
(function(x) {
m[x] = new google.maps.Marker( {
position: getRandomPoint(),
title: 'Mojmarkers'
});
google.maps.event.addListener(m[x], 'click', function() {
alert('Markerklik');
$("#trasa").append(m[x].getPosition().toString()+"<br>");
});
return m[x];
})(i);
}
Anyone can explain why this unusual solution works as i want ?