You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Leaflet中结合flyTo()与setInterval()/setTimeout()实现循环飞行路线?

解决Leaflet地图循环飞行路线的问题

我来帮你搞定这个循环飞行的问题!你的代码现在只能跑一次就停,核心问题是用了多个独立的setInterval,它们各自重复触发,时间线混乱,根本没有形成连贯的路线循环逻辑。

问题分析

你原来的代码里,每个城市的函数都绑定了不同间隔的setInterval:萨格勒布每5秒飞一次,奥西耶克每10秒,以此类推。这会导致到了第20秒的时候,四个函数会同时触发,地图收到一堆冲突的飞行指令,最后就乱套了,自然没法完成循环路线。

正确的实现方式

我们可以把所有目标地点放进一个数组,然后用递归+setTimeout的方式,依次完成每个地点的飞行,跑完一轮后自动回到开头,实现无限循环。

基础版(固定间隔)

// 定义完整的循环路线:萨格勒布 → 奥西耶克 → 斯普利特 → 里耶卡
const flightRoute = [
  { coords: [45.806367, 15.982061], zoom: 13 }, // 萨格勒布
  { coords: [45.554614, 18.696247], zoom: 13 }, // 奥西耶克
  { coords: [43.511787, 16.440155], zoom: 13 }, // 斯普利特
  { coords: [45.327369, 14.440395], zoom: 13 }  // 里耶卡
];

let currentStop = 0; // 跟踪当前飞到第几个地点
const stayDuration = 5000; // 每个地点停留的时间(毫秒)

function flyToNextStop() {
  // 获取当前要飞往的地点信息
  const target = flightRoute[currentStop];
  mymap.flyTo(target.coords, target.zoom);
  
  // 更新索引:跑完最后一个地点后回到第一个,实现循环
  currentStop = (currentStop + 1) % flightRoute.length;
  
  // 设置下一次飞行的定时器
  setTimeout(flyToNextStop, stayDuration);
}

// 启动循环飞行
flyToNextStop();

进阶版(自定义每个地点的停留时间)

如果想让不同城市的停留时间不一样,比如斯普利特多停2秒,只需要把停留时间加到路线数组里就行:

const flightRoute = [
  { coords: [45.806367, 15.982061], zoom: 13, stay: 5000 }, // 萨格勒布停5秒
  { coords: [45.554614, 18.696247], zoom: 13, stay: 6000 }, // 奥西耶克停6秒
  { coords: [43.511787, 16.440155], zoom: 13, stay: 7000 }, // 斯普利特停7秒
  { coords: [45.327369, 14.440395], zoom: 13, stay: 5000 }  // 里耶卡停5秒
];

let currentStop = 0;

function flyToNextStop() {
  const target = flightRoute[currentStop];
  mymap.flyTo(target.coords, target.zoom);
  
  currentStop = (currentStop + 1) % flightRoute.length;
  
  // 使用当前地点自定义的停留时间
  setTimeout(flyToNextStop, target.stay);
}

flyToNextStop();

额外提示

如果需要随时停止循环,可以保存setTimeout的返回值,然后用clearTimeout终止:

let timeoutId; // 存储定时器ID

function flyToNextStop() {
  const target = flightRoute[currentStop];
  mymap.flyTo(target.coords, target.zoom);
  
  currentStop = (currentStop + 1) % flightRoute.length;
  
  timeoutId = setTimeout(flyToNextStop, stayDuration);
}

// 停止循环的函数
function stopFlight() {
  clearTimeout(timeoutId);
}

内容的提问来源于stack exchange,提问作者Dominik Fuček

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:43:15