0

If we just take a standard leaflet map like the one below:

library(leaflet)
library(maps)

mapStates = map("state", fill = TRUE, plot = FALSE)

leaflet(data = mapStates) %>% addTiles() %>%
  addPolygons(fillColor = topo.colors(10, alpha = NULL), stroke = FALSE)

Is there a way to add a button that adds and removes certain polygons? For example, if the map above contained several layers (i.e. uninsured rates & average age), I would want a button or toggle switch that would allow a user to add and remove all states that begin with "a" (silly example). So instead of having 4 layers (two with those statistics across all states and two with those statistics across the states that do not begin with "a"), I would only have two layers and a button.

My caveat is that it needs to be exportable in .html format, which means I cannot deploy a shiny solution.

Perhaps there's an addEasyButton solution?

1 Answer 1

0

You will need to add a unique identifier in the group parameter of the addPolygons() function, then pipe to addLayersControl(), per https://rstudio.github.io/leaflet/showhide.html

I am not able to fully provide code, since I don't have your mapStates data, but here's an attempt

library(leaflet)
library(maps)

mapStates = map("state", fill = TRUE, plot = FALSE)

leaflet(data = mapStates) %>% addTiles() %>%
  addPolygons(fillColor = topo.colors(10, alpha = NULL), stroke = FALSE, group = "stateShape") %>%
addLayersControl(overlayGroups = c("stateShape"))

Not the answer you're looking for? Browse other questions tagged or ask your own question.