iT邦幫忙

2024 iThome 鐵人賽

DAY 19
0

在leaflet中,使用polyline實現道路規劃的方式並不方便,因此我發現了一個leaflet插件
Leaflet Routing Machine是一個強大的Leaflet插件,專門用於在地圖上進行路徑規劃和導航。它支援將起點和終點設置在地圖上,並計算出路徑,顯示詳細的轉向指引,提供高效的路徑規劃功能。

實現方式

首先使用cdn引入

<link rel="stylesheet" href="https://unpkg.com/leaflet-routing-machine@latest/dist/leaflet-routing-machine.css" />
<script src="https://unpkg.com/leaflet-routing-machine@latest/dist/leaflet-routing-machine.js"></script>

在初始化地圖時加上L.Routing.control,在裡面設定起始點和終點

var map = L.map('map');
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
    }).addTo(map);
    L.Routing.control({
        waypoints: [
            L.latLng(25.034257884674552, 121.5632085197662),
            L.latLng(25.047432705625663, 121.51942841585432)
        ],
     routeWhileDragging: true
}).addTo(map);

如果有設定routeWhileDragging,還可以透過一個可移動的marker指定路徑中要經過甚麼地方
https://ithelp.ithome.com.tw/upload/images/20240927/20161223buJD8O2EKk.png
在地圖右上角還會顯示經過了哪幾條路、每一段路要往哪個方向移動

今天先這樣,明天見


上一篇
Day18:3D地圖
系列文
深入前端地圖框架技術探索19
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言