Leaflet Marker Color Changes Reactive to varSelectInput in Shiny

Greetings all,

I am attempting to produce a Leaflet map in which the marker colors change based on the user selecting a variable from the data set using varSelectInput(). Below is the reprex as well as what I have tried already and articles I have referenced.


dat <- tibble(
    state = c("lak", "cent", "east", "east"),
    option_1 = c("no", "yes", "no", "yes"),
    option_2 = c("yes", "yes", "yes", "yes"),
    option_3 = c("no", "no", "no", "yes"),
    lat = c(6.87239, 4.01313, 5.00959, 4.77239),
    lon = c(29.57524, 30.56462, 32.39547, 33.59156)

pal <- colorFactor(
    palette = c("#FF0000", "green4"),
    levels = c("no", "yes")

ssd_map <- leaflet() %>%
    addProviderTiles(providers$CartoDB) %>%
    setView(lng = 31.2189853,
            lat = 7.8751893,
            zoom = 6)

ui <- fluidPage(
    titlePanel("Reprex Map"),
            inputId = "option",
            label = "Options:",
            data = dat %>% select(starts_with("option_"))

server <- function(input, output) {
    output$map <- renderLeaflet({
        leafletProxy("map", data = dat) %>%
            clearMarkers() %>%
            addCircleMarkers(data = dat,
                             color = ~pal(input$option)) #Causes the app to crash or non-reactive markers

shinyApp(ui = ui, server = server)

What I have tried:

  • Adding !!, !!as.name(), !!!, before input$option in the color parameter of addCircleMarkers() to ensure it is not reading a character string, but a symbol. However, if I use any of those, the app crashes and I get a warning "Error in !: invalid argument type". If I don't add those, the app runs, but the markers are grey and non-reactive to input$option

  • Using observeEvent({}) (I'm uncertain that I'm using it 100% correctly), though it seems that this is more for usage with buttons, not when you want the map to update as soon as the input option is changed.

  • This topic and this topic seem to be the closest to my problem, but there was no solution posted. I've also looked extensively on SO without success.

Any guidance would be greatly appreciated.

Thanks to an answer from @Ben at SO and sharing here for others.

The following observe({}) section works perfectly:

        leafletProxy("map", data = dat) %>%
            clearMarkers() %>%
            addCircleMarkers(data = dat,
                             color = ~pal(eval(as.symbol(input$option))))
1 Like

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