Solved - Error when using mapshot with Shiny Leaflet

Thanks for posting the reprex!

The issue appears to be with the fact the "map" is not actually a leaflet object, but rather a shiny output.

If you create the leaflet object in its own reactive expression and then pass that into the renderLeaflet and first mapshot observer then that first save button works.

For the proxy option, I am not able to get it to work as I am getting the following error:

Warning: Error in system.file: 'package' must be of length 1

This seems to be an issue with saveWidget which is what mapshot calls. I am also not entirely sure what you are accomplishing by saving it with the proxy option that is not already being captured by the first save option. But I may be missing something.

Anyway, Here is the app with a working save button for the first option:

library(leaflet)
library(mapview)
library(shiny)

ui <- fluidPage(
  
  titlePanel("Mapshot error example"),
  
  sidebarLayout(
    sidebarPanel(
      actionButton("addMarkers", "Add markers"),
      actionButton("saveMapUsingID", "Screenshot map with ID")
      # actionButton("saveMapUsingProxy", "Screenshot map with Proxy")
    ),
    mainPanel(
      leafletOutput("map")
    )
  )
)

server <- function(input, output, session) {
  
  map_reactive <- reactive({
    leaflet() %>%
      addProviderTiles(providers$OpenStreetMap)
  })
  
  output$map <- renderLeaflet({
    map_reactive()
  })
  
  observeEvent(input$addMarkers, {
    # Somewhere in London
    randPoint1 <- runif(1, min=-0.34, max=0.16)
    randPoint2 <- runif(1, min=51.34, max=51.67)
    leafletProxy("map") %>%
      addMarkers(lng=randPoint1, lat=randPoint2) %>%
      setView(lng=randPoint1, lat=randPoint2, zoom=10)
  })
  
  observeEvent(input$saveMapUsingID, {
    mapshot(map_reactive(), file=paste0(getwd(), '/exported_map.png'))
  })
  

  
}

shinyApp(ui = ui, server = server)

As a final note, please indicate when you have cross-posted your question (here is your question also on SO). This will prevent people from spending time trying to answer your question if you have already gotten an answer. Please see the FAQ about cross-posting questions:

1 Like