Reputation: 2803
I have an problem with an for loop in an LeafletJs map, for some reason i can't get it give me the correct Id from a array, instead it give me the last id on all clickevent's. Outside the $.get()
the Id is displayed correct. But inside i just get the last in the Array. Are it possible to Exend the option to get an custom one ore are there other ways to do it.
for (var i = 0; i < myColumnDefs.length; i++) {
var obj = myColumnDefs[i];
// obj.id = i;
var latitude = obj.GisLatitude.toFixed(5);
var longitude = obj.GisLongitude.toFixed(5);
//The correct id
console.log(obj.Id);
var m = L.marker([latitude, longitude], { icon: greenIcon }).on('click', function (e) {
var markeren = this;
debugger;
$.get(ol.url('~/Map/MapContent/'), {id: m.id }, function(data) {
L.popup()
.setLatLng(markeren.getLatLng())
.setContent(data)
.openOn(map);
});
}).addTo(map);
m.id = obj.Id;
console.log('Latitude: '+latitude + ' - Longitude: ' + longitude);
}
Upvotes: 0
Views: 105
Reputation: 494
In success/error handler of $.get the context bound is of event.target and the loop you are iterating is long finished before the event handler is called. Hence, you get the last ID on click handlers.
log this @ var markeren = this;
on the console. The context is what you require.
Again log markeren
inside $.get and it will not be what you expected!
Bind the function context appropriately and your issue will go away.
Upvotes: 1