請給我從沙田第一城到香港會議展覽中心的最短路徑 請把航點在地圖中標示出來 使用javascript實作 使用OpenStreetMap with Leaflet
- User
請給我從沙田第一城到香港會議展覽中心的最短路徑 請把航點在地圖中標示出來 使用javascript實作 使用OpenStreetMap with Leaflet
Assistant
請給我從沙田第一城到香港會議展覽中心的最短路徑 請把航點在地圖中標示出來 使用javascript實作 使用OpenStreetMap with Leaflet
好的,這是一個使用 JavaScript、OpenStreetMap 和 Leaflet 實作的互動式地圖,顯示從沙田第一城到香港會議展覽中心的最短駕駛路徑。
這個實作使用了 Leaflet Routing Machine 插件,它會自動連接到 OSRM (Open Source Routing Machine) 的公共服務器來計算路徑。
您將會看到一個地圖,上面有:
請將以下所有程式碼複製並儲存為一個 HTML 檔案(例如 route_map.html),然後用任何現代的網頁瀏覽器打開它即可。
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<title>沙田第一城 到 香港會議展覽中心 路線圖</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 1. 引入 Leaflet CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY="
crossorigin=""/>
<!-- 2. 引入 Leaflet Routing Machine CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet-routing-machine@3.2.12/dist/leaflet-routing-machine.css" />
<style>
body {
padding: 0;
margin: 0;
}
html, body, #map {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<!-- 3. 引入 Leaflet JS -->
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"
integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo="
crossorigin=""></script>
<!-- 4. 引入 Leaflet Routing Machine JS -->
<script src="https://unpkg.com/leaflet-routing-machine@3.2.12/dist/leaflet-routing-machine.js"></script>
<script>
// 5. 初始化地圖
// 設定一個中心點(大約在香港的中心位置)和縮放級別
var map = L.map('map').setView([22.34, 114.18], 12);
// 6. 加入 OpenStreetMap 圖層
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
// 7. 建立路線控制器
L.Routing.control({
// 設定航點 (waypoints)
waypoints: [
// 起點:沙田第一城 (大約座標)
L.latLng(22.3850, 114.2090),
// 終點:香港會議展覽中心 (大約座標)
L.latLng(22.2855, 114.1725)
],
// 當拖動路線時,是否重新計算路徑
routeWhileDragging: true,
// 設定路線顏色
lineOptions: {
styles: [{color: 'blue', opacity: 0.8, weight: 6}]
},
// 設定顯示語言為繁體中文
language: 'zh-TW',
// 讓使用者可以輸入地點進行搜尋 (使用 Nominatim 服務)
geocoder: L.Control.Geocoder.nominatim(),
// 自訂航點的顯示文字
createMarker: function(i, waypoint, n) {
var markerText = i === 0 ? '起點: 沙田第一城' : '終點: 香港會議覽中心';
return L.marker(waypoint.latLng)
.bindPopup(markerText)
.openPopup();
}
}).addTo(map);
</script>
</body>
</html>
L.map): 在 ID 為 map 的 <div> 元素中建立一個地圖實例。setView 設定了地圖的初始中心點經緯度和縮放級別。L.tileLayer): 使用 OpenStreetMap 作為地圖的底圖。attribution 是版權聲明,使用 OpenStreetMap 時必須顯示。L.Routing.control): 這是最關鍵的部分。
waypoints: 設定路線的起點和終點。這裡我們使用 "沙田第一城" 和 "香港會議展覽中心" 的經緯度座標。路徑規劃服務會自動將這些座標對應到最近的道路上。routeWhileDragging: true: 允許使用者用滑鼠拖動地圖上的藍色路徑,路線會即時重新計算。language: 'zh-TW': 將左側面板的轉彎指示等文字設定為繁體中文。geocoder: 增加一個搜尋框,讓使用者可以直接輸入地址來變更起點或終點。createMarker: 自訂航點標記的外觀和彈出視窗文字,使其更具可讀性。.addTo(map): 最後將這個路線控制器加到地圖上。