I have the following code:
for (var i = 0; i < markers.length; i++) {
var lat = markers[i][0];
var lng = markers[i][1];
var img = markers[i][2];
var info = markers[i][3];
setTimeout(function(lat, lng, img, info) {
console.log(lat + ', ' + lng);
$('#map').gmap3({
action: 'addMarker',
latLng:[lat, lng],
options:{
animation: google.maps.Animation.DROP,
icon: img
},
events:{
click: function(marker, event, data){
$(this).gmap3({action:'addinfowindow', anchor:marker, options:{content: '<div id="content" style="width:300px;height:250px;"><img src="' + info + '"></img></div>'}});
/*var infowindow = $(this).gmap3({action:'get', name:'infowindow'});
infowindow.close();*/
},
}
});
}, i* 100);
}
The console.log is showing undefined for lat and lng. Why is this?
Previously I didn’t pass any variables into the function within timeout and they WERE defined but it used the same one for each marker in the for loop which was obviously wrong!
Any ideas?
latandlngare named parameters of your timeout function, butsetTimeoutdoes not pass any parameters to that function, so they remain undefined.You should move the timeout setup into a separate function, in order to establish a closure for your variables: