I am attempting to animate several markers on a map with a for loop, but instead of animating them as intended, the code below is adding the consecutive coordinates simultaneously (full code here):
for (j in jsonObj[i]) {
for (k in jsonObj[i][j]) {
if (jsonObj.hasOwnProperty(i)) {
subindex = Object.keys(jsonObj[i][j][k]);
sublenght = subindex.length;
for (cnt = 0; cnt < sublenght; cnt += 1) {
lat = [],
lon = [],
lat[cnt] = (jsonObj.flightPositions[j].positions[cnt].lat)
lon[cnt] = (jsonObj.flightPositions[j].positions[cnt].lon)
var marker = new L.Marker.movingMarker([[lat[cnt], lon[cnt]]], [2500], {autostart: true}).addTo(map);
};
}
}
}
I tried using closures, always getting the same result. My most recent attempt can be seen here. I guess there is something wrong with it, but what I am most afraid is that my whole approach may be wrong. I was hoping that anyone could throw me a hint. Any help appreciated!
According to Leaflet.MovingMarker plugin usage, you should create only 1 marker (per moving marker you need), and pass it directly an array of positions.
L.movingMarker(<LatLng[]> latlngs, <Number[]> durations [,<Object> options]);
In your code you create 1 marker per position, with only the current position.
I will not build on your JSFiddle as it looks far more complicated than probably necessary (do not know why you ever try some IIFE's), so building on the code you posted, you would have something like:
for (j in jsonObj[i]) { // i === "flightPositions"
for (k in jsonObj[i][j]) { // j === array index, k === "positions"
if (jsonObj.hasOwnProperty(i)) { // should have been checked before
subindex = Object.keys(jsonObj[i][j][k]); // indices of array
sublenght = subindex.length; // could have just done jsonObj[i][j][k].length
var coordinates = [];
for (cnt = 0; cnt < sublenght; cnt += 1) { // iterates in positions array
coordinates.push([
jsonObj.flightPositions[j].positions[cnt].lat,
jsonObj.flightPositions[j].positions[cnt].lon
]);
};
// outside the positions array for loop.
var marker = L.Marker.movingMarker(coordinates, 2500, {
autostart: true
}).addTo(map);
}
}
}