In case anyone is looking at this in the future, there's a new viable method.
If you're using the development/Github version of the leaflet
package, addLegend()
now supports the group
and layerId
arguments.
(Run the command devtools::install_github('rstudio/leaflet')
to install)
Even the latest CRAN version (1.1.0) supports layerID
.
Assuming you go with the development version, the following code should work:
leaflet() %>%
#Polygon Layers
addPolygons(data = exampleDataOne, group = "Group A") %>%
addPolygons(data = exampleDataTwo, group = "Group B") %>%
#Legend Layers
addLegend(values = exampleValuesOne, group = "Group A",
position = "bottomright") %>%
addLegend(values = exampleValuesTwo, group = "Group B",
position = "bottomright") %>%
#Layers Control
addLayersControl(overlayGroups = c("Group A","Group B"),
options = layersControlOptions(collapsed = FALSE))
This should have the desired effect of only displaying a legend when the corresponding layer is active.
One potential issue is that by default, all leaflet
layers are active. If you have overlapping polygons, this can lead to a less visually appealing map. And, if you have multiple legends, this will also be an issue.
What you can do is use the hideGroup()
function.
If you wanted to have only Group A
from the above example active at start, you could add
%>% hideGroup("Group B")
to the end of the code block above.