Ostatnio aktywny 10 months ago

此範例使用 Leaflet 在 OpenStreetMap 上顯示多個地點標記,並使用自訂圖示來強調特定位置,如台北 101、中正紀念堂和士林夜市。點擊標記可顯示彈出資訊,並支援地圖點擊事件以顯示座標。

leaflet_multiple_locations_example.html Surowy
1<!DOCTYPE html>
2<html>
3<head>
4 <title>Leaflet 多個地點範例</title>
5 <meta charset="utf-8" />
6 <meta name="viewport" content="width=device-width, initial-scale=1.0">
7 <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css" />
8 <style>
9 #map {
10 height: 600px;
11 width: 100%;
12 }
13 </style>
14</head>
15<body>
16 <div id="map"></div>
17 <script src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js"></script>
18 <script>
19 // 初始化地圖,設定中心點及縮放級別
20 var map = L.map('map').setView([25.0330, 121.5654], 13);
21
22 // 添加 OpenStreetMap 圖層
23 L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
24 attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
25 }).addTo(map);
26
27 // 定義自訂圖示
28 var customIcon = L.icon({
29 iconUrl: 'custom-marker.png', // 圖示圖片檔案的路徑
30 iconSize: [38, 38], // 圖示的尺寸
31 iconAnchor: [19, 38], // 圖示的錨點(基準點)
32 popupAnchor: [0, -38] // 彈出視窗的位置
33 });
34
35 // 定義多個地點
36 var locations = [
37 {"name": "台北 101", "coords": [25.0330, 121.5654], "popup": "<b>台北 101</b><br>台北市地標之一"},
38 {"name": "中正紀念堂", "coords": [25.0341, 121.5194], "popup": "<b>中正紀念堂</b><br>歷史紀念建築"},
39 {"name": "士林夜市", "coords": [25.0872, 121.5250], "popup": "<b>士林夜市</b><br>著名的夜市"}
40 ];
41
42 // 添加多個標記
43 locations.forEach(function(location) {
44 L.marker(location.coords, {icon: customIcon}).addTo(map)
45 .bindPopup(location.popup);
46 });
47
48 // 地圖點擊事件
49 function onMapClick(e) {
50 alert("你點擊了地圖座標:" + e.latlng);
51 }
52
53 map.on('click', onMapClick);
54 </script>
55</body>
56</html>
57