1

I am trying to reduce the loading time of a Shiny App that renders a map via the Leaflet package utilizing large sf object datasets. Much of the slow loading time is attributable to the actual plotting operation of the layers within Leaflet. I would like the app to load quickly and to have the user immediately begin to interact with the app, while loading additional hidden map group layers asynchronously in the background.

My app currently renders a leaflet object then adds additional leaflet map layers via the leafletProxy function. I am trying to figure out a method to load leafletProxy map layers using async programming packages such as the future and promise packages, but the leafletProxy object will not successfully render the layers into the Shiny app. Is there a way to integrate async programing with the leafletProxy function, or is there a better way to load Leaflet layers within the same map using async programming?

A reproducible example below:

library(leaflet)
library(sf)
library(shiny)
library(dplyr)
library(httr)
library(future)
library(promises)
plan(multisession)

points <- read_sf(GET("https://data.ferndalemi.gov/api/download/v1/items/4726274b9bde451ebe679127e50c75ef/geojson?layers=0"))
polygons <- read_sf(GET("https://data-lakecountyil.opendata.arcgis.com/api/download/v1/items/8df706ae1b784276ae02e9b4550da6ae/geojson?layers=0"))

ui <- fluidPage(
  
  selectInput(inputId = "inputPoints",
              label = NULL,
              choices = c("All", sort(unique(points$Company))),
              selected = "All"),
  
  leafletOutput("mymap")
  
)

server <- function(input, output, session) {
  
  points_filtered <- reactive({
    points_filtered <- points
    if(input$inputPoints != "All"){
      points_filtered <- points_filtered %>% filter(Company == input$inputPoints)
    }
    points_filtered
  })
  
  output$mymap = renderLeaflet(
    leaflet() %>%
      addProviderTiles("CartoDB.Positron") %>%
      setView(lat = 39.8283, lng = -98.5795, zoom = 4)
    )
  
  observe({
    future({
      leafletProxy("mymap", session) %>%
      addPolygons(data = polygons)
      })
    NULL
  })

  observe({
    leafletProxy("mymap", session) %>%
      clearGroup("mypoints") %>%
      addMarkers(data = points_filtered(), group = "mypoints")
  })
  
}

shinyApp(ui, server)

0

Browse other questions tagged or ask your own question.