rlegendr-leaflet

Change legends based on selected layer group


I am making an R leaflet map (not Shiny) and I have two control groups, and based on the selection I would like a different legend to become visible. Currently I only manage to have both legends visible at all time.

Below is the code for the leaflet map, and the output can be seen in the image.

Two legends are always visible

leaflet() %>% addSearchOSM() %>% 
  addProviderTiles(providers$CartoDB.Positron,
                   options = providerTileOptions(noWrap = TRUE),
                   group = "kaart") %>%
  # addFullscreenControl() %>%
  addCircleMarkers(data = table@data,
             lat = ~lng, 
             lng = ~lat,
             color = ~palverbruikplaats(Verbruiksplaats),
             label = bepaalPopup(),
             group = "Verbruikplaatscircles"
             )%>%
  addCircleMarkers(data = table@data,
                   lat = ~lng, 
                   lng = ~lat,
                   color = ~palstatus(`Status omschrijving`),
                   label = bepaalPopup(),
                   group = "statuscircles"
                    )%>%
  leaflet::addLegend("bottomleft", pal = palverbruikplaats, values = verbruikplaatsuniek, title = "Legenda") %>%
  leaflet::addLegend("bottomleft", pal = palstatus, values = statusuniek, title = "Legenda") %>%
  addLayersControl(baseGroups = c("Verbruikplaatscircles", "statuscircles"),
                      options = layersControlOptions(collapsed = FALSE))

Solution

  • In your addLayersControl did you mean to set the overlayGroups argument instead of baseGroups?

    library(leaflet)
    leaflet() %>%
      addTiles(group = "OpenStreetMap") %>%
      addCircleMarkers(runif(20, -75, -74), runif(20, 41, 42), group = "Markers1", color ="red") %>%
      addMarkers(runif(20, -75, -74), runif(20, 41, 42), group = "Markers2") %>%
      addLegend(values = 1, group = "Markers1", position = "bottomleft", labels = "1", colors= "red") %>%
      addLegend(values = 2, group = "Markers2", position = "bottomleft", labels = "2" ,colors= "blue") %>%  
      addLayersControl(overlayGroups = c("Markers1", "Markers2"),
                       options = layersControlOptions(collapsed = FALSE))
    

    enter image description here