如何将Leaflet扩展(AllMaps插件)创建的图层分配到分组?
如何为Leaflet扩展(AllMaps)生成的图层添加分组并实现切换
要让AllMaps插件生成的WarpedMapLayer能通过leaflet::addLayersControl()实现切换,需要在JavaScript层面将图层关联到指定分组,以下是两种可行方案:
方案1:直接操作Leaflet图层控制器
在R代码中先声明分组,再在onRender的JS代码里将自定义图层添加到图层控制器的底图分组中:
library(leaflet) library(htmltools) library(htmlwidgets) allMapsPlugin <- htmlDependency( "@allmaps_leaflet", "1.0.0", src = c(href = 'https://cdn.jsdelivr.net/npm/@allmaps/leaflet@1.0.0-beta.35/dist/bundled'), script = 'allmaps-leaflet-1.9.umd.min.js' ) registerPlugin <- function(map, plugin) { map$dependencies <- c(map$dependencies, list(plugin)) map } leaflet() %>% # 添加原生底图并指定分组 addTiles(group = "OpenStreetMap") %>% setView(lat = 51.054450, lng = 3.724924, zoom = 13) %>% registerPlugin(allMapsPlugin) %>% # 配置图层控制器,包含两个底图分组 addLayersControl( baseGroups = c("OpenStreetMap", "AllMaps 纠偏图层"), options = layersControlOptions(collapsed = FALSE) ) %>% onRender("function(el, x) { const annotationUrl = 'https://annotations.allmaps.org/manifests/8f9faeba73d67031' const warpedMapLayer = new L.WarpedMapLayer(annotationUrl) // 获取地图的图层控制器实例 const layersControl = this.control.layers // 将自定义图层添加到底图分组 layersControl.addBaseLayer(warpedMapLayer, 'AllMaps 纠偏图层') // 可选:设置默认显示AllMaps图层 // warpedMapLayer.addTo(this) }")
原理说明
- R代码中通过
addLayersControl声明要切换的底图分组名称; - JS代码里创建
WarpedMapLayer后,调用layersControl.addBaseLayer()将图层绑定到对应分组,参数需和R中baseGroups的名称匹配; - 若需要默认显示AllMaps图层,取消注释
warpedMapLayer.addTo(this)即可。
方案2:通过R的图层组关联
先在R中创建空的图层组并指定分组,再在JS里将自定义图层添加到该组:
library(leaflet) library(htmltools) library(htmlwidgets) allMapsPlugin <- htmlDependency( "@allmaps_leaflet", "1.0.0", src = c(href = 'https://cdn.jsdelivr.net/npm/@allmaps/leaflet@1.0.0-beta.35/dist/bundled'), script = 'allmaps-leaflet-1.9.umd.min.js' ) registerPlugin <- function(map, plugin) { map$dependencies <- c(map$dependencies, list(plugin)) map } leaflet() %>% addTiles(group = "OpenStreetMap") %>% # 创建空图层组并指定分组名称 addLayersGroup(group = "AllMaps 纠偏图层") %>% setView(lat = 51.054450, lng = 3.724924, zoom = 13) %>% registerPlugin(allMapsPlugin) %>% addLayersControl( baseGroups = c("OpenStreetMap", "AllMaps 纠偏图层"), options = layersControlOptions(collapsed = FALSE) ) %>% onRender("function(el, x) { const annotationUrl = 'https://annotations.allmaps.org/manifests/8f9faeba73d67031' const warpedMapLayer = new L.WarpedMapLayer(annotationUrl) // 通过layerManager获取R中创建的图层组 const allMapsGroup = this.layerManager.getLayer('group', 'AllMaps 纠偏图层') // 将自定义图层添加到该组 warpedMapLayer.addTo(allMapsGroup) }")
原理说明
- 利用
leaflet::addLayersGroup()创建绑定了分组的空图层组; - JS代码通过Leaflet的
layerManager获取该组,再将WarpedMapLayer添加进去,自动继承分组属性,无需手动操作图层控制器。
内容的提问来源于stack exchange,提问作者John J.
相关产品推荐
相关产品推荐

