Speed up leaflet redraw in shiny

I am using leaflet to draw a few thousand coloured lines on a map (they are rivers). The lines generally stay the same, but the colours change in response to user input. However leaflet seems very slow to redraw the lines. How can I make it snappier? This reprex illustrates the issue.

library(shiny)
library(leaflet)

dlat <- 1 / 111000 * 100 # degrees per metre
n <- 10000 # number of circles
mylng <- 175.322 + (runif(n) * 2 - 1) * dlat * 6
mylat <- -37.789 + (runif(n) * 2 - 1) * dlat * 1.5
myrad <- dlat * runif(n) * dlat
hex <- c(0:9, LETTERS[1:6])

ui <- fluidRow(
  tags$h2("Speed up Leaflet in Shiny"),
  actionButton("plotbutton", label = "Recolouring Shapes is Slow"),
  leafletOutput("map")
)

server <- function(input, output, session) {
  output$map <- renderLeaflet({
    cat("renderLeaflet\n")
    leaflet() %>%
      addTiles() %>%
      setView(175.322, -37.789, zoom = 17)
  })
  
  observeEvent(input$plotbutton, {
    col <- paste0("#", paste0(sample(hex, 6, replace = TRUE), collapse = ""))
    leafletProxy("map") %>%
      clearShapes() %>% 
      addCircles(
        lng = mylng,
        lat = mylat,
        radius = myrad, 
        color = col)
  })
}

shinyApp(ui = ui, server = server)
1 Like

looks like a branch with this functionality exists but hasnt been merged to the release version.

Is it possible that you could think of a scheme to write some circles on different layers, where circles more likely to change when other circles should change, are in that way grouped, then only clear that layer to redraw with colour rather than all the circles.

In computer graphics there is an old tradition of this sort of thing for performance. 'dirty rectangles'
https://wiki.c2.com/?DirtyRectangles

3 Likes

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.