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

如何在Leaflet地图中添加带多点的彩色路线路径

解决方案:Leaflet 多点路线生成与标记点隐藏

一、修复Leaflet Routing Machine路径显示并隐藏标记点

如果你的Leaflet Routing Machine只显示标记点不显示彩色路径,大概率是未正确引入插件样式文件,或者配置项限制了路径渲染。同时要隐藏途经点标记,可通过以下步骤实现:

  1. 确保引入Leaflet Routing Machine的CSS(路径样式依赖此文件)
<link rel="stylesheet" href="https://unpkg.com/leaflet-routing-machine@latest/dist/leaflet-routing-machine.css" />
  1. 初始化路由控件时,通过配置项隐藏标记点并确保路径渲染:
// 初始化地图
const map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);

// 初始化路由控件,隐藏标记点并显示路径
L.Routing.control({
  waypoints: [
    L.latLng(51.5, -0.1),
    L.latLng(51.51, -0.12),
    L.latLng(51.52, -0.1)
  ],
  // 隐藏途经点标记
  createMarker: function() {
    return null;
  },
  // 禁用拖拽编辑(非可编辑路线)
  routeWhileDragging: false,
  draggableWaypoints: false,
  // 可选:自定义路径样式
  lineOptions: {
    styles: [{color: '#2ecc71', weight: 4}]
  }
}).addTo(map);

二、2023年适用的预定义坐标路线方案(规避OSRM服务器问题)

旧版Leaflet Routing Machine依赖的公共OSRM服务器可能不稳定,推荐以下两种无需依赖旧插件的方案:

方案1:直接用Leaflet原生Polyline绘制预定义路径

如果你已经有完整的路径坐标数组(不是仅途经点),直接用Leaflet原生L.Polyline即可生成非可编辑路线:

const map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);

// 预定义路径坐标数组
const routeCoords = [
  [51.5, -0.1],
  [51.505, -0.11],
  [51.51, -0.12],
  [51.52, -0.1]
];

// 创建路线并添加到地图
L.polyline(routeCoords, {
  color: '#e74c3c',
  weight: 4,
  opacity: 0.8
}).addTo(map);

方案2:使用OpenRouteService API生成路径(免费可用)

如果只有途经点,需要生成最优路径,可使用OpenRouteService的免费API(2023年仍稳定提供服务),获取路径坐标后用Polyline绘制:

  1. 先去OpenRouteService官网申请免费API密钥
  2. 编写代码请求路径并渲染:
const map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);

// 预定义途经点
const waypoints = [
  [51.5, -0.1],
  [51.51, -0.12],
  [51.52, -0.1]
];

// 转换为API要求的格式(lon, lat)
const formattedWaypoints = waypoints.map(pt => `${pt[1]},${pt[0]}`).join('|');

// 请求OpenRouteService API
fetch(`https://api.openrouteservice.org/v2/directions/driving-car?api_key=你的API密钥&start=${formattedWaypoints.split('|')[0]}&end=${formattedWaypoints.split('|').pop()}&waypoints=${formattedWaypoints.split('|').slice(1, -1).join('|')}`)
  .then(res => res.json())
  .then(data => {
    // 提取路径坐标并转换为Leaflet格式
    const routeCoords = data.features[0].geometry.coordinates.map(coord => [coord[1], coord[0]]);
    // 绘制路线
    L.polyline(routeCoords, {
      color: '#3498db',
      weight: 4
    }).addTo(map);
  })
  .catch(err => console.error('路径请求失败:', err));

注意:OpenRouteService免费额度为每天2000次请求,足够小型项目使用;若需更高额度,可考虑Mapbox Directions API等付费服务。

内容的提问来源于stack exchange,提问作者Mm-Art-In

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 13:55:09