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

Leaflet路径模拟问题:图标弯道减速、直道超速

解决方案:Leaflet路径模拟匀速行驶问题

问题根源

当前代码以固定时间间隔(300ms * 索引)更新标记位置,但Leaflet Routing Machine返回的路径坐标点在弯道处密度远高于直道,导致相同时间内弯道移动距离短(视觉减速)、直道移动距离长(视觉超速),本质是基于坐标点数量而非实际距离控制移动节奏。

修复思路

改为基于实际行驶距离计算移动时间:

  • 计算相邻坐标点间的地理距离
  • 设定恒定的行驶速度(如10m/s,即36km/h)
  • 根据每段距离和速度计算所需时间,累计总时间后设置定时器,确保车辆匀速行驶

修改后的代码

替换原routesfound事件中的for循环部分:

L.Routing.control({
    waypoints: [
        L.latLng(EO.lat, EO.lng ),
        L.latLng(ZO.lat, ZO.lng)
    ],
    routeWhileDragging: true,
    draggableWaypoints: false,
    addWaypoints: false
}).on('routesfound', function (e) {
    var route = e.routes[0];
    var coordinates = route.coordinates;
    var totalTime = 0;
    // 设定匀速:10米/秒(可根据需求调整,如20m/s对应72km/h)
    const speedMps = 10;

    // 从第二个坐标点开始遍历,计算与前一点的距离和时间
    for (let i = 1; i < coordinates.length; i++) {
        const prevCoord = coordinates[i-1];
        const currCoord = coordinates[i];
        // 计算两点间的实际距离(单位:米)
        const distance = L.latLng(prevCoord).distanceTo(L.latLng(currCoord));
        // 计算该路段所需时间(毫秒)
        const segmentTime = (distance / speedMps) * 1000;
        totalTime += segmentTime;

        setTimeout(function () {
            marker.setLatLng([currCoord.lat, currCoord.lng]);
            // 可选:更新车辆朝向,让图标沿路径方向转动
            const bearing = prevCoord.bearingTo(currCoord);
            marker.setRotationAngle(bearing); // 需要Leaflet.Marker.Rotate插件支持
        }, totalTime);
    }
}).addTo(map);

额外优化(可选)

如果需要让车辆图标沿路径方向转动,需引入Leaflet.Marker.Rotate插件,代码中已添加setRotationAngle的示例,可根据实际情况集成。

内容的提问来源于stack exchange,提问作者Erebus

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 13:01:02