场景
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; 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、效果