Search code examples
rshinyflexdashboardr-leaflet

Filter Leaflet markers by input selection in R Flexdashboard


I am trying to filter the markers that are drawn on a Leaflet map based on what is selected in a user defined date range. The below codes is returning an error that it is unable to find hfxLoc object. I have used the below approach (filtering within the render function in other elements (i.e. renderPlot, renderValueBox, etc.). Is my approach to filtering correct, or does it need to occur in a different place in the Leaflet code block?

The inputSelect code is as follows:

selectizeInput("shiptypeInput", "Vessel type: ", choices = hfxVessels, selected = "Cargo ships", multiple = TRUE)

The leaflet code is as follows:

renderLeaflet({
  hfxLoc <- hfxETA %>%
    dplyr::filter(as.Date(eta_date) >= input$dateRange[1] & as.Date(eta_date) <=  input$dateRange[2]) %>%
  leaflet(data = hfxLoc) %>% 
  setView(lng = -60.25, lat = 46, zoom = 6) %>%
  addProviderTiles(providers$CartoDB.Positron,
                   options = providerTileOptions(minZoom = 2, maxZoom = 16)) %>%
  addMarkers(lng = ~lon, lat = ~lat, clusterOptions = markerClusterOptions())

Solution

  • You can remove data = hfxLoc from leaflet, as you are already piping in the filtered data from the filter results. The piped-in resultant data will be assumed the first argument data in leaflet.

    renderLeaflet({
      hfxLoc <- hfxETA %>%
        dplyr::filter(as.Date(eta_date) >= input$dateRange[1] & as.Date(eta_date) <=  input$dateRange[2]) %>%
        leaflet() %>%
        ...