场景
Vue+Leaflet实现加载OSM显示地图:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/122317394
Vue+Leaflet实现加载Stamen显示地图:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/122318989
参考上面实现的效果,如果要实现切换地图图层,以及控制标记图层整个所有标记的marker显示与隐藏怎么弄。
leaflet官方提供了组件与教程,可以通过LayerGroup去存储并控制整个marker的显示与隐藏。
以及LayerControl实现地图图层切换功能。
官方教程:
https://leafletjs.com/examples/layers-control/
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。
实现
1、声明layerGroup,图层组,用来存储城市标记marker
//声明图层组,存储城市标记marker var cities = L.layerGroup();
2、声明两个城市的marker并添加进图层组
//声明两个城市marker并添加进图层组 var linyi = L.marker([36.01, 120.24]).bindPopup('这里属于青岛').addTo(cities); var qingdao = L.marker([35.51, 117.92]).bindPopup('这里属于临沂').addTo(cities);
3、声明两个地图图层
//声明osm地图图层 var osmLayer = L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", { attribution: "osm" }); //声明stamen地图图层 var stamenLayer = L.tileLayer("https://stamen-tiles-{s}.a.ssl.fastly.net/watercolor/{z}/{x}/{y}.png", { attribution: "stamen" });
4、声明地图并添加地图图层
//声明地图并添加图层 var map = L.map('map', { center: [36.09, 120.35], zoom: 13, layers: [osmLayer, stamenLayer] });
5、新建图层空间的数据源
//新建图层控件的数据源-地图 var baseLayers = { 'osm地图': osmLayer, 'stamen地图': stamenLayer }; ////新建图层控件的数据源-城市 var overlays = { '城市': cities };
6、新建图层控件并添加到地图
//新建图层控件并添加到地图 var layerControl = L.control.layers(baseLayers, overlays).addTo(map);
7、完整代码
<!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"> //声明图层组,存储城市标记marker var cities = L.layerGroup(); //声明两个城市marker并添加进图层组 var linyi = L.marker([36.01, 120.24]).bindPopup('这里属于青岛').addTo(cities); var qingdao = L.marker([35.51, 117.92]).bindPopup('这里属于临沂').addTo(cities); //声明osm地图图层 var osmLayer = L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", { attribution: "osm" }); //声明stamen地图图层 var stamenLayer = L.tileLayer("https://stamen-tiles-{s}.a.ssl.fastly.net/watercolor/{z}/{x}/{y}.png", { attribution: "stamen" }); //声明地图并添加图层 var map = L.map('map', { center: [36.09, 120.35], zoom: 13, layers: [osmLayer, stamenLayer] }); //新建图层控件的数据源-地图 var baseLayers = { 'osm地图': osmLayer, 'stamen地图': stamenLayer }; ////新建图层控件的数据源-城市 var overlays = { '城市': cities }; //新建图层控件并添加到地图 var layerControl = L.control.layers(baseLayers, overlays).addTo(map); </script> </body> </html>
8、效果