library(leaflet)
library(htmltools)
library(htmlwidgets)
library(dplyr)
#
df1 <- data.frame(points=c("p1", "p2"), lat=c(49.47259, 49.48095), long=c(-103.7054, -103.6126), value=c(50.34, 100.25))
df2 <- data.frame(points=c("p1", "p2"), lat=c(49.47809, 49.66849), long=c(-103.5614, -103.0224), value=c(300.56, 505.34))
#
pal1 <- colorNumeric(
palette = "PRGn",
domain = df1$value
)
#
pal2 <- colorNumeric(
palette = "PRGn",
domain = df2$value
)
#
n <- leaflet() %>% addTiles(group="1st layer") %>% addTiles(group="2nd layer") %>%
addCircles(data=df1, lng=~long, lat=~lat, weight = 3, radius=250, color = ~pal1(value),
stroke = TRUE, fillOpacity = 0.8,group="1st layer") %>%
addCircles(data=df2, lng=~long, lat=~lat, weight = 3, radius=250, color = ~pal2(value),
stroke = TRUE, fillOpacity = 0.8,group="2nd layer") %>%
addLegend("bottomright", pal = pal1, values = df1$value, title = "legend_df1") %>%
addLegend("topright", pal = pal2, values = df2$value, title = "legend_df2") %>%
addLayersControl(baseGroups=c("1st layer","2nd layer"),
options=layersControlOptions(collapsed = F))
n
当我点击&#34;第一层&#34;那么只有&#34; legend_df1&#34;将出现,当我点击&#34;第二层&#34;那么只有&#34; legend_df2&#34;将出现&#34; legend_df1&#34;将消失。因此,在每一层中都会出现不同的图例,而不是两个图例。有人可以帮帮我吗?
答案 0 :(得分:0)
现在可以使用overlayGroups
library(leaflet)
df1 <- data.frame(points=c("p1", "p2"), lat=c(49.47259, 49.48095), long=c(-103.7054, -103.6126), value=c(50.34, 100.25))
df2 <- data.frame(points=c("p1", "p2"), lat=c(49.47809, 49.66849), long=c(-103.5614, -103.0224), value=c(300.56, 505.34))
pal1 <- colorNumeric(
palette = "inferno",
domain = df1$value
)
pal2 <- colorNumeric(
palette = "viridis",
domain = df2$value
)
leaflet() %>%
addProviderTiles(providers$CartoDB.DarkMatter) %>%
addCircleMarkers(data=df1, lng=~long, lat=~lat,
color = ~pal1(value),
group="group_1") %>%
addCircleMarkers(data=df2, lng=~long, lat=~lat,
color = ~pal2(value),
group="group_2") %>%
addLegend("bottomright", pal = pal1, title="grp1",
values = df1$value, group="group_1") %>%
addLegend("bottomright", pal = pal2, title="grp2",
values = df2$value, group="group_2") %>%
addLayersControl(overlayGroups = c("group_1","group_2"),
options = layersControlOptions(collapsed = FALSE))