I am using the leaflet library in shinyapps. I am trying to show markers which I have saved as icons depending on a user input dropdown choice. In the example below, I am unable to filter out the markers based on the user input. Similar code works when I run using only leaflet package without shiny.
The sample code below is in server.r in Shiny.
filteredData <- reactive({
sampling_data[sampling_data$county == input$county_select, ]
})
theData <- filteredData()
leafletProxy("mapData") %>%
clearMarkers() %>%
addMarkers(lng = sampling_data$lon,
lat = sampling_data$lat,
clusterOptions = markerClusterOptions())
})
output$mapData <- renderLeaflet({
leaflet(sampling_data) %>%
addProviderTiles(providers$Esri.WorldTopoMap) %>%
setView(lng = -75, lat = 43, zoom = 6)
})
observe({
theData <- filteredData()
leafletProxy("mapData") %>%
clearMarkers() %>%
addMarkers(lng = sampling_data$lon,
lat = sampling_data$lat,
clusterOptions = markerClusterOptions())
})
This code, without shiny, works fine
subsetData <- sampling_data %>%
filter(county == "Albany")
leaflet(subsetData) %>%
addTiles() %>%
addMarkers(lng = ~lon,
lat = ~lat)
You only need the leafletProxy
to appear in your observe
block.
library(shiny)
library(dplyr)
library(leaflet)
ui <- fluidPage(
mainPanel(
leafletOutput("map"),
sliderInput("depth", "Depth",
min = min(quakes$depth),
max = max(quakes$depth),
value = c(min(quakes$depth), max(quakes$depth))
),
textOutput("value")
)
)
server <- function(input, output) {
filteredData <- reactive({
quakes %>%
filter(depth >= input$depth[1] & depth <= input$depth[2])
})
output$value <- renderText({paste("min: ", input$depth[1], " max: ", input$depth[2])})
output$map <- renderLeaflet({
leaflet(quakes) %>%
fitBounds(~min(long),
~min(lat),
~max(long),
~max(lat))
})
observe({
leafletProxy("map") %>%
clearTiles %>%
clearMarkers %>%
addTiles %>%
addMarkers(lng = filteredData()$long, lat = filteredData()$lat)
})
}
shinyApp(ui = ui, server = server)