Search code examples
rleafletr-markdownflexdashboardleaflet.markercluster

Improving Performance of a leaflet


I am trying to plot a map using Leaflet on Flexdashboard, output : html. I have a 50,000 data points i needed to plot. i tried using addCircleMarker(lng,lat) and it works in Base R but when the output is generated in an HTML file the performance of the map is so slow. I also tried using leafletOptions(preferCanvas = TRUE)but the performance is still very slow.

I also tried using a different library(leaflet.glify) to improve performance as leaflet.glifycan handle large dataset and used addGlifyPoints(data, color = cbind(0, 0, 0.1), group = "All cases") to plot the map. but i could not run it in an HTML output. It provided me with below error.

pandoc: Could not determine mime type for `/Library/Frameworks/R.framework/Versions/3.5/Resources/library/leaflet.glify/htmlwidgets/Leaflet.glify/src/shader/fragment/dot.glsl'
CallStack (from HasCallStack):
  error, called at src/Text/Pandoc/SelfContained.hs:156:35 in pandoc-1.19.2.1-JIeRA5EnQv74mk86CvVbbp:Text.Pandoc.SelfContained
Error: pandoc document conversion failed with error 1
Execution halted

Any help please.


Solution

  • For leaflet.glify you need to set self_contained: false in your yaml header:

    ---
    title: "testing gl"
    output: 
      flexdashboard::flex_dashboard:
        vertical_layout: fill
        self_contained: false
    ---
    
    ### Chart 1
    
    ```{r}
    library(mapview)
    library(leaflet)
    library(leaflet.glify)
    library(sf)
    
    n = 1e5
    
    df1 = data.frame(id = 1:n,
                     x = rnorm(n, 10, 3),
                     y = rnorm(n, 49, 1.8))
    
    pts = st_as_sf(df1, coords = c("x", "y"), crs = 4326)
    
    options(viewer = NULL) # view in browser
    
    system.time({
      m = leaflet() %>%
        addProviderTiles(provider = providers$CartoDB.DarkMatter) %>%
        addGlifyPoints(data = pts, group = "pts") %>%
        addMouseCoordinates() %>%
        setView(lng = 10.5, lat = 49.5, zoom = 6) %>% 
        addLayersControl(overlayGroups = "pts")
    })
    
    m
    ```
    
    ### Chart 2
    
    ```{r}
    plot(cars)
    ```