地图轨迹回放时如何平滑移动Marker?

迷人的思佳 阅读 9

我在用高德地图做轨迹回放功能,现在是每隔1秒更新一次Marker的位置,但看起来特别卡顿,像“瞬移”一样。试过用marker.setPosition()直接设置新坐标,也试过加CSS transition,但都没用。

查了文档说可以用moveAlong,但我的轨迹点是动态加载的,不是一开始就全有的。有没有办法让Marker在两个点之间平滑移动?比如用requestAnimationFrame自己算插值?

function replayTrack(points) {
  let index = 0;
  const timer = setInterval(() => {
    if (index >= points.length) {
      clearInterval(timer);
      return;
    }
    marker.setPosition(points[index]);
    index++;
  }, 1000);
}
我来解答 赞 2 收藏
二维码
手机扫码查看
1 条解答
Mr-子诺
Mr-子诺 Lv1
问题在于你每秒直接setPosition肯定瞬移啊,高德Marker本身就有moveTo方法自带动画,或者自己用requestAnimationFrame做插值也行。

用高德自带的moveTo最省事:

function replayTrack(points) {
let index = 0;

function moveNext() {
if (index >= points.length - 1) return;

marker.moveTo(points[index + 1], {
duration: 1000,
delay: 0
});
index++;
}

// 监听移动结束事件,继续下一段
marker.on('moveend', moveNext);
moveNext();
}


如果你非要自己撸插值,用requestAnimationFrame也行,就是麻烦点:

function smoothMove(marker, from, to, duration) {
const startTime = performance.now();

function animate(currentTime) {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);

const lng = from.lng + (to.lng - from.lng) * progress;
const lat = from.lat + (to.lat - from.lat) * progress;

marker.setPosition([lng, lat]);

if (progress < 1) {
requestAnimationFrame(animate);
}
}

requestAnimationFrame(animate);
}


动态加载的点也无所谓,每次拿到新点调moveTo就行,不用一开始全量加载。
点赞 1
2026-03-01 01:19