Leaflet JS有一个插件,它允许在layer控件中对层进行分组。https://github.com/ismyrnow/Leaflet.groupedlayercontrol
这个插件似乎不存在于Leaflet R,但我发现这篇文章说在Leaflet R中有一种使用任意Leaflet JS插件的方法。https://gist.github.com/jcheng5/c084a59717f18e947a17955007dc5f92
我尝试将此方法应用于Leaflet.groupedlayercontrol插件,但没有成功。您是否知道如何使用此插件或其他方式在Leaflet R生成的layercontrol中对层进行分组?谢谢。
发布于 2016-09-08 11:49:25
你绝对可以在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)下面是它看起来的样子:

您还可以添加其他控件,请在此处查看:
发布于 2019-04-13 07:55:17
我知道这是一个古老的问题,但我在其他地方找不到好的答案-这可能会在未来帮助其他人。
下面是一个带有注释的reprex,用于解释代码:
#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()https://stackoverflow.com/questions/38701359
复制相似问题