Search code examples
rshinyleafletr-leaflet

Update leaflet provider tile options without adding and removing


I'm using leaflet in a shiny app to display my data along with several base layers. One of the layers is the very nice daily MODIS satellite imagery provided by NASA GIBS. The issue is that I cannot figure out how to update the date of the NASA image gracefully.

Below is an example of my first approach.

library(shiny)
library(leaflet)

ui <- fluidPage(
        dateInput("date", label = "Date"),
           leafletOutput("map", width = "600px")
)

server <- function(input, output, session) {

  output$map <- renderLeaflet({
    leaflet() %>%
      addProviderTiles("Esri.WorldGrayCanvas", group = "Gray") %>%
      fitBounds(-130, 23, -60, 50)
  })

  observe({

    leafletProxy("map", session) %>%
      addProviderTiles("NASAGIBS.ModisTerraTrueColorCR", group = 'MODIS',
                       options = providerTileOptions(time = input$date)) %>%
      addLayersControl(baseGroups = c("Gray", "MODIS"))
  })

}

# Run the application
shinyApp(ui = ui, server = server)

This "works," but the problem is evident if you change the date a few times while on the gray map (go backwards in time, since future satellite data doesn't exist) and then switch the view to MODIS. You will see the tiles load for each of the dates you selected in turn.

Another approach I tried was to add the MODIS tiles on the initial loading:

server_v2 <- function(input, output, session) {

  output$map <- renderLeaflet({
    leaflet() %>%
      addProviderTiles("Esri.WorldGrayCanvas", group = "Gray") %>%
      addProviderTiles("NASAGIBS.ModisTerraTrueColorCR", group = 'MODIS',
                       options = providerTileOptions(time = input$date)) %>%
      addLayersControl(baseGroups = c("Gray", "MODIS")) %>%
      fitBounds(-130, 23, -60, 50)
  })

  observe({

    leafletProxy("map", session) %>%
      addProviderTiles("NASAGIBS.ModisTerraTrueColorCR", group = 'MODIS',
                       options = providerTileOptions(time = input$date))

  })

}

This also "works," and solves the problem of all past selected dates loading, but creates a different problem. In this case, switching the date will now cause the map to revert to its original default state (gray basemap and original zoom level), which really hinders use.

What I really want (I think) is an updateProviderTiles function, but that doesn't exist in the leaflet R package. Can you see a solution or workaround?


Solution

  • Joe Cheng provided the answer when I posted the question to Github:

    If you call addProviderTiles with a layerId argument (just make up an identifier), then any previous addProviderTiles with the same layerId are removed before the new one is added.

    See http://rstudio.github.io/leaflet/shiny.html#understanding-layer-ids for more details.