Skip to content

路径规划

上次更新 2025年8月20日星期三 3:16:20 字数 0 字 时长 0 分钟

示例

TIP

本示例展示了如何在 Leaflet 地图上实现路径规划功能。主要实现了以下功能:

  • 使用 leaflet-routing-machine 插件实现路径规划
  • 支持拖拽修改路线
  • 显示备选路线
  • 自定义路线样式

新标签页预览

代码实现

vue
<template>
  <div id="map" class="w-full h-96"></div>
</template>

<script setup>
import L from "leaflet";
import "leaflet/dist/leaflet.css";
import "leaflet-routing-machine/dist/leaflet-routing-machine.css";
import "leaflet-routing-machine";
import { onMounted, ref } from "vue";

const map = ref(null);

onMounted(() => {
  const urlLayer =
    "http://t0.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=d32c6748c80f81a44acd8633cea41dfd";

  map.value = L.map("map", {
    center: [39.094899, 117.33083], // 天津
    zoom: 12,
    zoomControl: true,
    doubleClickZoom: false,
    attributionControl: false,
  });

  // 底图
  const baseLayer = L.tileLayer(urlLayer).addTo(map.value);

  // 添加路线规划控件
  L.Routing.control({
    waypoints: [
      L.latLng(39.084899, 117.20083), // 起点
      L.latLng(39.094899, 117.33083), // 终点
    ],
    routeWhileDragging: true,
    // language: "zh", // 设置语言为中文
    showAlternatives: true, // 显示备选路线
    lineOptions: {
      styles: [{ color: "blue", opacity: 0.6, weight: 4 }],
    },
  }).addTo(map.value);
});
</script>
关注公众号