React Leaflet船舶实时追踪:航线显示在陆地的问题求助
问题根源
你当前使用的Leaflet Routing Machine(LRM)默认依赖陆地道路路由服务(如OSRM),这类服务会自动将航点匹配到最近的陆地道路网络,导致海上坐标被拉到陆地上生成错误航线。
解决方案
方案1:直接绘制直线航线(最简单适配船舶场景)
船舶在海上航行无需遵循道路网络,直接用Leaflet的Polyline连接航点即可生成严格贴合海上坐标的航线。修改RoutingMachine组件如下:
import L from "leaflet"; import { createLayerComponent } from "@react-leaflet/core"; import Ship from "../../../../assets/Icons/ship_route.png"; import "./JourneyRoute.css"; const CreateShipRouteLayer = ({ waypoints }) => { let shipIcon = new L.Icon({ iconUrl: Ship, iconSize: [25, 50], iconAnchor: [-16, 20], }); const TooltipClass = { className: 'class-tooltip' }; // 创建图层组统一管理标记和航线 const layerGroup = L.layerGroup(); // 添加各航点标记 waypoints.forEach((wp, i) => { let marker; if (i === 0) { marker = L.circleMarker(wp, { fillColor: "blue", color: "blue", fillOpacity: 1 }) .bindTooltip("Journey Starting Point", { permanent: true, direction: "right", ...TooltipClass }); } else if (i === 1) { marker = L.marker(wp, { icon: shipIcon }) .bindTooltip(`7.1 KM`, { permanent: true, direction: "left", ...TooltipClass }); } else if (i === 2) { marker = L.circleMarker(wp, { fillColor: "green", color: "green", fillOpacity: 0.8 }) .bindTooltip("Journey Ending Point 9.8 KM", { permanent: true, direction: "right", ...TooltipClass }); } marker && layerGroup.addLayer(marker); }); // 添加海上直线航线 const polyline = L.polyline(waypoints, { color: "#6FA1EC", weight: 6 }); layerGroup.addLayer(polyline); return layerGroup; }; const RoutingMachine = createLayerComponent((props, context) => { const waypoints = [ L.latLng(1.2875422104568421, 103.66667134765369), L.latLng(1.247449, 103.596), L.latLng(1.2160194097204378, 103.64611489779371), ]; const layer = CreateShipRouteLayer({ waypoints }); layer.addTo(context.map); return { layer, context }; }); export default RoutingMachine;
方案2:使用海事专用路由服务(进阶真实航行场景)
如果需要规避陆地、岛屿的真实航线规划,可替换LRM的路由源为海事专用API(需自行寻找支持海事路由的服务,部分商业海事平台提供此类接口):
// 在原CreateRoutineMachineLayer中修改router配置 const instance = L.Routing.control({ waypoints: [/* 你的航点 */], // 替换为海事路由API地址 router: L.Routing.osrmv1({ serviceUrl: "https://your-maritime-routing-api.com/v1/route" }), // 其余配置保持不变 createMarker: function (i, wp, nWps) { /* ... */ }, lineOptions: { /* ... */ }, show: false, addWaypoints: false, routeWhileDragging: true, draggableWaypoints: false, fitSelectedRoutes: true, showAlternatives: false, });
内容的提问来源于stack exchange,提问作者harizh
相关产品推荐
相关产品推荐

