RaBe
RaBe

Reputation: 53

Leaflet Marker Color Changes Reactive to varSelectInput in Shiny

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.

library(shiny)
library(tidyverse)

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"),
    
    mainPanel(
        varSelectInput(
            inputId = "option",
            label = "Options:",
            data = dat %>% select(starts_with("option_"))
        ),
        leafletOutput("map")
    ))

server <- function(input, output) {
    output$map <- renderLeaflet({
        ssd_map
        
    })
    
    observe({
        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:

Upvotes: 1

Views: 1054

Answers (1)

RaBe
RaBe

Reputation: 53

As per @Ben in the comments above, using the following for the observe() section worked perfectly.

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

Upvotes: 1

Related Questions