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)