iT邦幫忙

2024 iThome 鐵人賽

DAY 4
0
Modern Web

深入前端地圖框架技術探索系列 第 4

Day4:使用 Leaflet 添加地圖標記

  • 分享至 

  • xImage
  •  

簡介

在 Leaflet 中,標記(Markers)是常見的互動元素之一,用來在地圖上標示特定的位置,並能夠綁定彈出視窗 (popup) 或工具提示 (tooltip) 以提供更多資訊。在這篇文章中,我們將深入介紹如何在地圖上添加標記,以及如何自訂標記的圖標、樣式、彈出視窗和互動效果。

基本的標記添加

要在地圖上添加一個基本的標記,只需要調用 L.marker() 方法並傳入標記的經緯度座標,然後將標記添加到地圖上。

var marker = L.marker([25.0330, 121.5654]).addTo(map);

添加彈出視窗 (Popup) 與工具提示 (Tooltip)

標記不僅僅是靜態的元素,你還可以為其綁定彈出視窗和工具提示。當使用者點擊或滑過標記時,這些互動元素會顯示額外的信息。

marker.bindPopup("<b>台北 101</b><br>台灣著名地標").openPopup();//綁定popup

marker.bindTooltip("台北 101").openTooltip();//綁定tooltip

https://ithelp.ithome.com.tw/upload/images/20240912/20161223aCELQmyxrP.png
popup設定openPopup()時預設popup會顯示,openTooltip()同理

popup可以設定一些額外的設定,來介紹幾個常用的

maxWidth minWidth maxHeight minHeight

用來設定popup的最大寬度、最小寬度、最大高度、最小高度

var popup = L.popup({ maxWidth: 400 })
    .setLatLng([25.0330, 121.5654])
    .setContent("This popup has a maximum width of 400px, which limits how wide the popup can be.")
    .openOn(map);

https://ithelp.ithome.com.tw/upload/images/20240912/20161223rv1eTQgJT8.png
https://ithelp.ithome.com.tw/upload/images/20240912/20161223HXMnlL6Y8I.png

keepInView

如果popup不在地圖視野內,會被強制拉回去

var popup = L.popup({ keepInView: true })
        .setLatLng([25.0330, 121.5654])
        .setContent("This popup will remain in view even if you pan the map.")
        .openOn(map);

closeButton

取消popup的關閉按鈕

var popup = L.popup({ closeButton: false })
        .setLatLng([25.0330, 121.5654])
        .setContent("This popup does not have a close button.")
        .openOn(map);

autoClose

會把其他的popup關閉

var popup1 = L.popup({ autoClose: true })
    .setLatLng([25.0330, 121.5654])
    .setContent("This popup will not close when another popup is opened.")
    .openOn(map);

var popup2 = L.popup()
    .setLatLng([25.0340, 121.5660])
    .setContent("Another popup.")
    .openOn(map);

closePopupOnClick

點擊空白的區域時不會關閉popup

var map = L.map('map', { closePopupOnClick: false }).setView([25.0330, 121.5654], 13);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 19,
}).addTo(map);

var popup = L.popup()
    .setLatLng([25.0330, 121.5654])
    .setContent("Clicking elsewhere on the map will not close this popup.")
    .openOn(map);

自訂標記圖標

Leaflet 允許開發者使用自訂的圖標替換預設的標記圖標。這對於需要在地圖上顯示不同類型的標記(例如,餐廳、地鐵站或景點等)非常有用。

var customIcon = L.icon({
    iconUrl: 'images.jfif',  // 自訂圖標的 URL
    iconSize: [38, 95],  // 圖標大小
    iconAnchor: [22, 94],  // 圖標的錨點,表示圖標的哪一點會放置在座標上
    popupAnchor: [-3, -76]  // 彈出視窗的錨點
});

var customMarker = L.marker([25.0330, 121.5654], { icon: customIcon }).addTo(map);

https://ithelp.ithome.com.tw/upload/images/20240912/20161223kcgR4ef7fs.png

今天就先這樣,明天見


上一篇
Day3:day3:Leaflet 地圖初始化與顯示地圖
下一篇
Day5:選擇與自訂地圖圖層
系列文
深入前端地圖框架技術探索20
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言