場景
Leaflet中添加標記、折線、圓圈、多邊形、彈窗顯示點擊處坐標:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/122309679
在上面加載標記使用的是默認圖標,如果要自定義圖標怎么用。
官網有詳細的教程
https://leafletjs.com/examples/custom-icons/
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。
實現
1、與官方教程一樣,准備一張陰影照片,三張不同顏色的icon
2、創建ICON構造函數,相當於繼承ICON,可以重新設置屬性
//創建ICON構造函數,相當於繼承於ICON,可以重新設置屬性 var LeafIcon = L.Icon.extend({ options: { shadowUrl: './icon/leaf-shadow.png', //陰影地址 iconSize: [38, 95], //圖標寬高 shadowSize: [50, 64], //陰影寬高 iconAnchor: [22, 94], //圖標錨點 shadowAnchor: [4, 62], //陰影錨點 popupAnchor: [-3, -76] //彈出框彈出位置,相對於圖標錨點 } });
3、創建多個icon
//創建多個icon var greenIcon = new LeafIcon({ iconUrl: './icon/leaf-green.png' }), redIcon = new LeafIcon({ iconUrl: './icon/leaf-red.png' }), orangeIcon = new LeafIcon({ iconUrl: './icon/leaf-orange.png' });
4、創建marker添加到地圖上
//創建marker添加到地圖上 L.marker([36.09, 120.35], { icon: greenIcon }).bindPopup("I am a green leaf.").addTo(map); L.marker([36.13, 120.25], { icon: redIcon }).bindPopup("I am a red leaf.").addTo(map); L.marker([36.16, 120.15], { icon: orangeIcon }).bindPopup("I am an orange leaf.").addTo(map);
5、完整代碼
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>leaflet自定義標記圖標</title> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" /> <style> html, body, #map { padding: 0; margin: 0; width: 100%; height: 100%; overflow: hidden; } </style> </head> <body> <div id="map"></div> <script type="text/javascript" src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script> <script type="text/javascript"> var map = L.map('map').setView([36.09, 120.35], 13); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© <a href="OpenStreetMaphttps://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' }).addTo(map); //創建原始圖標ICON //創建ICON構造函數,相當於繼承於ICON,可以重新設置屬性 var LeafIcon = L.Icon.extend({ options: { shadowUrl: './icon/leaf-shadow.png', //陰影地址 iconSize: [38, 95], //圖標寬高 shadowSize: [50, 64], //陰影寬高 iconAnchor: [22, 94], //圖標錨點 shadowAnchor: [4, 62], //陰影錨點 popupAnchor: [-3, -76] //彈出框彈出位置,相對於圖標錨點 } }); //創建多個icon var greenIcon = new LeafIcon({ iconUrl: './icon/leaf-green.png' }), redIcon = new LeafIcon({ iconUrl: './icon/leaf-red.png' }), orangeIcon = new LeafIcon({ iconUrl: './icon/leaf-orange.png' }); //創建marker添加到地圖上 L.marker([36.09, 120.35], { icon: greenIcon }).bindPopup("I am a green leaf.").addTo(map); L.marker([36.13, 120.25], { icon: redIcon }).bindPopup("I am a red leaf.").addTo(map); L.marker([36.16, 120.15], { icon: orangeIcon }).bindPopup("I am an orange leaf.").addTo(map); </script> </body> </html>
6、效果