Cannot bind Legend layer to Polygon layer in Leaflet/R

I try to plot a map of concentrations of chemicals. These have very different ranges, so a shared legend is not feasible. The ultimate goal is to have the different layers for the different chemicals selectable and show the respective legend.

From what I read in the documentation of addLegend(), exactly this should be handled by the group parameter that was set to the same name in the addPolygons() for that layer before. However, it just does not work. Does anyone have an idea for the reason? Here's what I tried:

library(spData)
library(leaflet)
library(sf)
library(tidyverse)


set.seed(1)

vietnam <- world %>%
  filter(name_long == "Vietnam")

grids <-
  st_make_grid(vietnam, square = FALSE)

grids_sf <- st_sf(
  id = 1:length(grids),
  geometry = grids,
  category = sample(letters[1:3], size = length(grids), replace = TRUE),
  value = rnorm(length(grids))
)

addPolygonsLayers <- function(map, data, layer_by, fill_by) {
      
  data_groups <- split(data, data[[layer_by]])
  data_groups_names <- names(data_groups)

  for (i in seq_along(data_groups)) {
    group_data <- data_groups[[i]]
    group_name <- data_groups_names[i]
    group_values <- pull(group_data, fill_by)

    pal <- colorNumeric(palette = "viridis", domain = group_values)

    map <-
      map %>%
      addPolygons(
        data = group_data,
        fillColor = ~ pal(group_values),
        fillOpacity = 1,
        group = group_name,
        popup = str_c(group_name, " </br> Value: ", group_values)
      ) %>%
      addLegend(
        group = group_name,
        opacity = 1,
        pal = pal,
        values = group_values,
        position = "bottomright"
      )
  }
  map <-
    map %>%
    addLayersControl(
      baseGroups = data_groups_names,
      options = layersControlOptions(collapsed = FALSE),
      position = "topright"
    )
  return(map)
}


leaflet() %>%
  addTiles() %>%
  addPolygonsLayers(
    data = grids_sf,
    layer_by = "category",
    fill_by = "value"
  )

Hi @telegott. I can't figure out why legend layers overlaid as the same time when using baseGroups. This may be a bug, or somethings else that you may report an issue. Using overlayGroups can work, but the layers control will not be radio button and change to checkboxes.

map <-
    map %>%
    addLayersControl(
      overlayGroups = data_groups_names,
      options = layersControlOptions(collapsed = FALSE),
      position = "topright"
    ) %>%
    hideGroup("b") %>%
    hideGroup("c")

Thanks alot for your response and suggestion! I wrote an issue on that, still couldn't get it to work in the meantime

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.