Leaflet JS有一个插件,允许对图层控件中的图层进行分组。 https://github.com/ismyrnow/Leaflet.groupedlayercontrol
Leaflet R似乎没有这个插件,但我发现这篇文章说有一种方法可以在Leaflet R中使用任意Leaflet JS插件。 https://gist.github.com/jcheng5/c084a59717f18e947a17955007dc5f92
我尝试将此方法应用于Leaflet.groupedlayercontrol插件但未成功。您是否知道如何使用此插件或任何其他方式在Leaflet R生成的图层控件中对图层进行分组?谢谢。
答案 0 :(得分:4)
你绝对可以在leafletR中进行图层控制。如果您的版本没有它,那么您需要更新,可能来自最新的GITHUB版本。
我正在制作一张有图层控件的地图,请参阅照片。这是实现它的代码。正如您所看到的,每个addPolygons
都有group = " A Name"
这是您在我的图片上的复选框中识别图层的位置。
map<-leaflet()%>%
addTiles()%>%
addPolygons(data = plotMerge,
fillColor = ~pal(plotMerge$incomePerCapita),
color = "#000000", #this is an outline color
fillOpacity = 0.8,
group="Tract",
weight = 0.2,
popup=popup)%>%
addPolygons(data = countyPoly,
fillColor = "transparent",
color = "#000000", #this is an outline color
fillOpacity = 0.8,
group="County",
popup=countyPoly@data$NAME,
weight = 2)%>%
addPolygons(data = townPoly,
fillColor = "transparent",
color = "#000000", #this is an outline color
fillOpacity = 0.8,
group="Town",
weight = .8,
popup=townPoly@data$TOWN)%>%
addPolygons(data = rphnPoly,
fillColor = "transparent",
color = "#000000", #this is an outline color
fillOpacity = 0.8,
group="Public Health Region",
weight = .8,
popup=rphnPoly@data$PHN)%>%
addLegend(pal = pal,
values = plotMerge$incomePerCapita,
position = "bottomright",
title = "State-wide Income Percentiles",
labFormat = labelFormat(digits=1))%>%
addLayersControl(
overlayGroups =c("County", "Town", "Public Health Region", "Tract"),
options = layersControlOptions(collapsed=FALSE)
)
saveWidget(map, file="map1.html", selfcontained=FALSE)
您还可以添加其他控件在此处查看:
答案 1 :(得分:0)
我知道这是一个古老的问题,但是我在其他地方找不到很好的答案-将来可能会对其他人有所帮助。
这里是带有注释的代表,解释了代码:
#load library
library(tidyverse)
library(leaflet)
#load data
data("quakes")
#map all points
# quakes %>%
# leaflet() %>%
# addProviderTiles(providers$CartoDB.Positron) %>%
# addCircleMarkers(lng = ~long, lat = ~lat, radius = 1)
#create a grouping variable -- this can be whatever you want to filter by
quakes <- quakes %>%
mutate(groups = case_when(
stations < 30 ~ 1,
stations < 50 ~ 2,
TRUE ~ 3
))
#function to plot a map with layer selection
map_layers <- function() {
#number of groups
k <- n_distinct(quakes$groups)
#base map
map <- leaflet() %>%
addProviderTiles(providers$CartoDB.Positron)
#loop through all groups and add a layer one at a time
for (i in 1:k) {
map <- map %>%
addCircleMarkers(
data = quakes %>% filter(groups == i), group = as.character(i),
lng = ~long, lat = ~lat, radius = 1
)
}
#create layer control
map %>%
addLayersControl(
overlayGroups = c(1:k),
options = layersControlOptions(collapsed = FALSE)) %>%
hideGroup(as.character(c(2:k))) #hide all groups except the 1st one
}
#plot the map
map_layers()