场景
Leaflet快速入门与加载OSM显示地图:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/122290880
在上面加载显示地图的基础上,怎样实现添加标记、折线、圆形、多边形等。
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。
实现
1、添加标记
//添加一个标记 L.marker([36.09, 120.35]).addTo(map).bindPopup("公众号:霸道的程序猿<br>").openPopup();
效果
2、添加折线
//添加一条折线 var polyline = L.polyline([ [36.1, 120.32], [36.05, 120.3] ],{color: '#FFFF00'}).addTo(map).bindPopup("这是折线");
效果
3、添加圆圈
//添加一个圆圈 L.circle([36.01, 120.22], 5000, { color: 'red', fillColor: '#f03', fillOpacity: 0.5 }).addTo(map).bindPopup("青岛欢迎你");
效果
4、添加多边形
//添加一个多边形 L.polygon([ [39.92096, 116.38591], [39.91079, 116.38676], [39.91118, 116.3962], [39.92014, 116.39482] ]).addTo(map).bindPopup("故宫");
效果
5、点击地图弹窗显示坐标
//弹窗显示点击处的坐标 var popup = L.popup(); function onMapClick(e) { popup .setLatLng(e.latlng) .setContent("You clicked the map at " + e.latlng.toString()) .openOn(map); } map.on('click', onMapClick);
效果
6、完整代码
<!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); //添加一个标记 L.marker([36.09, 120.35]).addTo(map).bindPopup("公众号:霸道的程序猿<br>").openPopup(); //添加一个圆圈 L.circle([36.01, 120.22], 5000, { color: 'red', fillColor: '#f03', fillOpacity: 0.5 }).addTo(map).bindPopup("青岛欢迎你"); //添加一个多边形 L.polygon([ [39.92096, 116.38591], [39.91079, 116.38676], [39.91118, 116.3962], [39.92014, 116.39482] ]).addTo(map).bindPopup("故宫"); //添加一条折线 var polyline = L.polyline([ [36.1, 120.32], [36.05, 120.3] ],{color: '#FFFF00'}).addTo(map).bindPopup("这是折线"); //弹窗显示点击处的坐标 var popup = L.popup(); function onMapClick(e) { popup .setLatLng(e.latlng) .setContent("You clicked the map at " + e.latlng.toString()) .openOn(map); } map.on('click', onMapClick); </script> </body> </html>