I understand why it doesn' work. But have no idea how to get result:
There is a global array:
var members=[[1,x,y,z],[2,x1,y1,z1],[3,x2,y2,z3]];
function drop() {
for (var i = 0; i < members.length-1; i++) {
setTimeout(function() {
addMarker();
}, i * 30);
}
}
function addMarker() {
var marker = new google.maps.Marker({
position: members[iterator][1],
icon: pinImage[members[iterator][2]],
shadow: shadow,
map: map,
draggable: false,
title: members[iterator][3],
animation: google.maps.Animation.DROP });
google.maps.event.addListener(marker, 'click', function() {
$.ajax({
url : 'ajax/get_infowindow_content.php?id='+members[iterator][0],
success: function(data) {
infowindow.close();
infowindow.setContent(data);
infowindow.open(map, marker);
}
});
});
markers.push(marker);
iterator++;
}
The problem is here:
url : 'ajax/get_infowindow_content.php?id='+members[iterator][0],
when i click the marker, it fires the function and checks the members[iterator][0] but the iterator is the last value of iterator (after the whole loop).
The best solution would be some kind of .value() like:
url : 'ajax/get_infowindow_content.php?id='+members[iterator][0].value(),
but of course it doesn't work.
I'm stacked..
You just need a closure and to pass a parameter to the addMarker function :
var members = [[1, x, y, z], [2, x1, y1, z1], [3, x2, y2, z3]];
function drop() {
for (var i = 0; i < members.length; i++) {
(function(j) {
setTimeout(function() {
addMarker(members[j]); //pass the value
}, i * 30);
})(i); //closure to keep the value
}
}
function addMarker(member) {
var marker = new google.maps.Marker({
position: member[1],
icon: pinImage[member[2]],
shadow: shadow,
map: map,
draggable: false,
title: member[3],
animation: google.maps.Animation.DROP
});
google.maps.event.addListener(marker, 'click', function() {
$.ajax({
url: 'ajax/get_infowindow_content.php?id=' + member[0],
success: function(data) {
infowindow.close();
infowindow.setContent(data);
infowindow.open(map, marker);
}
});
});
markers.push(marker);
}
Try passing i
as an argument of addMarker()
function addMarker(i){/* code*/}
Then in loop:
setTimeout(function() {
addMarker(i);
}, i * 30);