The Incremental Stranglehold - Or Why leaflet::clearShapes() Can Slowly Render an Interactive Map Unusable
This issue in a single image ...
Issue When creating a Shiny map with thousands of points, you start to hit a point where interactivity gets rather sluggish.
A great way to improve performance is to dynamically add only those points which fall within the current map window. Unfortunately - This does not work due to an underlying bug: clearShapes() does not remove points already added.
Therefore, as users interact with the map and points are dynamically added, the old ones are never removed ... Thus the stranglehold towards sluggishness commences ...
Show Me the Proof The best example of the issue and replication is likely RStudio's superZip dashboard:
- http://shiny.rstudio.com/gallery/superzip-example.html
Many others have come across this, as documented and replicated:
- http://stackoverflow.com/questions/31907805/leafletproxy-clearshapes-works-once-subsequently-data-dots-are-added-and-not
- https://groups.google.com/forum/?utm_medium=email&utm_source=footer#!msg/shiny-discuss/AFmWBWJCbsk/3a1Q_xdbFQAJ
- http://stackoverflow.com/questions/32107667/clearshapes-not-working-leaflet-for-r (This is a slightly different underlying cause it appears, yet susceptible to the same issue ...)
How Important is This? Important. The Shiny / Leaflet combination is incredible, and the potential for expansive geographic analysis groundbreaking. Unfortunately, as long as this issue remains in effect there is an unnecessarily low and persistent limit on the number of points you can essentially work with.
Are There Workarounds? Maybe. Leveraging markers instead of points is a possibility as suggested in #246. This isn't always what you're looking to accomplish with the geographic visualization however ...
What If It Was Fixed Quickly? @jcheng5 @yihui - I'd send a pizza of your choice straight to your office!
Great work as always on Shiny / Leaflet!
Hmm, I'm not seeing this issue. Can you give me a minimal reproducible example? This is what I tried:
library(shiny)
library(leaflet)
library(dplyr)
ui <- fluidPage(
leafletOutput("map")
)
server <- function(input, output, session) {
output$map <- renderLeaflet({
leaflet() %>% addTiles() %>% addCircles(data = quakes)
})
observe({
invalidateLater(1000)
leafletProxy("map", data = quakes %>% sample_n(100)) %>%
clearShapes() %>%
addCircles()
})
}
shinyApp(ui, server)
@jcheng5 - Joe, I appreciate the quick response.
Expanding slightly on the example you provided, I've replicated the issue with the following code.
Essentially, the use case here is that we're supposing quakesto be a dataset with more points than we want to display on the visible portion of the map at one time. To enable this, I have a reactive expression which filters out any points that aren't within the bounds of the map, and limits the total number to 5.
As you zoom in and out, you'll notice the odd behavior - Essentially, each zoom will add 5 more points to the screen. Through visibleQuakes() and clearShapes(), I would expect a maximum of 5 points and all the previously plotted points removed.
Oddly, we actually see the previous points are never cleared, so the total number keeps growing.

library(shiny)
library(leaflet)
library(dplyr)
ui <- fluidPage(
leafletOutput("map")
)
server <- function(input, output, session) {
# Establish Initial View of Map ---
output$map <- renderLeaflet({
leaflet() %>%
addTiles() %>%
setView(lng = 167.189941, lat = -15.940202, zoom = 3)
})
# Regenerate Quakes as Map Bounds Change ---
# We're supposing that there are too many quakes to render quickly,
# so we want to limit it a max of 5 within the bounds of the map.
visibleQuakes <- reactive({
# Return Empty Data Frame If Necessary ---
if (is.null(input$map_bounds)) {
return(quakes[FALSE,])
}
# Extract View Window Boundaries, Filter and Return ---
bounds <- input$map_bounds
latRng <- range(bounds$north, bounds$south)
lngRng <- range(bounds$east, bounds$west)
visibleQuakesDF <- filter(quakes,
lat >= latRng[1], lat <= latRng[2],
long >= lngRng[1], long <= lngRng[2])
# Filter Quakes to Manageable Number
visibleQuakesDF <- sample_n(visibleQuakesDF, 5)
# Return Filtered Quake DF ---
return(visibleQuakesDF)
})
# Watch for Changes to Map Bounds and Plot Accordingly
observe({
leafletProxy("map", data = visibleQuakes()) %>%
clearShapes() %>%
addCircles(
lng = ~long,
lat = ~lat)
})
}
shinyApp(ui, server)
The problem is with this:
# Return Empty Data Frame If Necessary ---
if (is.null(input$map_bounds)) {
return(quakes[FALSE,])
}
Sending an empty data frame to addCircles causes a JavaScript error (you can see this in your browser's JavaScript console). As a result, the data structure we use to store map layer info is in an inconsistent state, and things break after that (including but presumably not limited to clearing shapes).
Replace that expression with req and everything is fine:
req(input$map_bounds)
That said, it's certainly a bug that empty data frames choke Leaflet so badly (and I think we have the same problem with NA lat/long values). I'll file a separate issue for that, if there isn't one already.
@jcheng5 - You're the man, thanks Joe. Fixing the zero-data aspect, or displaying an error to the R console, would be a big help.
I am in your pizza debt.
Hi,
This is an insteresting topic. Is there a way to make the map update, but with external data? I currently have a leaflet map , but the data is streamed from a .json transformed an then mapped. I just need the map to read the latest data.
This is my project:
https://github.com/danvargg/uw001/blob/master/sensors/server.R
How could this be implemented?
observe({
invalidateLater(1000)
leafletProxy("map", data = **function that transforms the data?** %>%
})
}
DV
@danvargg Not that way; that will perform that action every second whether the data has actually changed or not. Instead you can use something like reactivePoll to do this efficiently:
https://shiny.rstudio.com/reference/shiny/latest/reactivePoll.html You can also watch this video starting at about 12:00: https://www.rstudio.com/resources/videos/building-dashboards-with-shiny-tutorial/
@jcheng5 Thanks! I will give it a try.
@jcheng5 I tried to implement the valueFunc and checkFunc in my code for reactivePoll.
The valueFunc is a long function (transformdata ), that returns the dataframe sensors (used for the leaflet map).
I create the checkFunc as a very cheap function that just displays system time.
I really don't understand what I'm doeing wrong. Is the checkFunc in the wrong output class? Do the functions output classes not match the reactivePoll expected class?
I get below error (code is below it).
Sorry for so many questions.
Listening on http://127.0.0.1:4572
Warning: Error in UseMethod: no applicable method for 'metaData' applied to an object of class "c('reactiveExpr', 'reactive')"
Stack trace (innermost first):
91: metaData
90: eval
89: resolveFormula
88: derivePoints
87: addCircleMarkers
86: function_list[[k]]
85: withVisible
84: freduce
83: _fseq
82: eval
81: eval
80: withVisible
79: %>%
78: func [C:\Users\b0572519\Desktop\R Codes\sensor/app.R#59]
77: origRenderFunc
76: output$map
1: runApp
library(jsonlite)
library(dplyr)
library(lubridate)
library(curl)
library(chron)
library(magrittr)
library(leaflet)
library(shiny)
## Data transformation
options(digits = 10)
transformdata = function(){
data <- fromJSON(paste(readLines("https://android-hc05-app-arduino-c5f17.firebaseio.com/.json"), collapse=""))
data <- add_rownames(data, "Time")
names(data) <- c("Time", "Values")
.............................................................. Truncated .......................................
sensor <- cbind(dat, coord)
sensor <- sensor[, c("Date", "Hour", "PPM", "lng", "lat")]
sensors <- sensor %>%
group_by(Date) %>%
slice(which.max(sensor$Hour))
sensors
}
checklog = function(){
Sys.Date()
}
## Application
ui <- fluidPage(leafletOutput("map", height = "1000px"))
server <- function(input, output, session) {
sensors <- reactivePoll(5000, session, checklog, transformdata)
output$map <- renderLeaflet({
sensors %>%
leaflet() %>%
addTiles(
urlTemplate = "//{s}.tiles.mapbox.com/v3/jcheng.map-5ebohr46/{z}/{x}/{y}.png",
attribution = 'Maps by <a href="http://www.mapbox.com/">Mapbox</a>'
) %>%
addCircleMarkers(lat = ~lng, lng = ~lat,
popup = paste("PPM:", sensors$PPM, "<br>",
"Date:", sensors$Date, "<br>",
"Time:", sensors$Hour),
radius = 5,
color = "black",
stroke = FALSE,
fillOpacity = 0.8)
})
}
shinyApp(ui = ui, server = server)
@jcheng5 Nevermind, I was able to implement it. Thanks a lot!
@danvargg Hi there! How did you work around it? I'm facing the same error code right now...
Listening on http://127.0.0.1:4129
Warning: Error in UseMethod: no applicable method for 'metaData' applied to an object of class "NULL"
Stack trace (innermost first):
94: metaData
93: eval
92: resolveFormula
91: derivePoints
90: addCircleMarkers
89: function_list[[k]]
88: withVisible
87: freduce
86: _fseq
85: eval
84: eval
83: withVisible
82: %>%
81: func [#8]
80: origRenderFunc
79: output$map
4: <Anonymous>
3: do.call
2: print.shiny.appobj
1: <Promise>
@JessieChiu You probably forgot to provide a data= argument--if you use formulas you need to provide one either to leaflet() or addCircleMarkers(), or else we don't know where to pull the data from.