使用 for 循环在地图上设置动画标记

Animating markers on a map with a for loop

我正在尝试使用 for 循环为地图上的多个标记制作动画,但下面的代码并没有按预期为它们制作动画,而是同时添加了连续的坐标 (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);

   };
  }
 }
}

我试过使用闭包,总是得到相同的结果。我最近的尝试可以看here。我猜想是有问题,但我最怕的是我的整个做法可能是错误的。我希望有人能给我一个提示。感谢任何帮助!

根据 Leaflet.MovingMarker plugin usage,你应该只创建 1 个标记(每个你需要的移动标记),并直接传递一个 位置数组 .

L.movingMarker(<LatLng[]> latlngs, <Number[]> durations [,<Object> options]);

在您的代码中,您为每个位置创建 1 个标记,只有当前位置。

我不会在你的 JSFiddle 上构建,因为它看起来比可能需要的复杂得多(不知道你为什么要尝试一些 IIFE),所以在你发布的代码上构建,你会得到类似的东西:

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);
    }
  }
}