rshinyr-leafletr-mapview

How to save leaflet map as png or pdf after zooming in


How can I save a map displayed on the main panel either as pdf or png? I am able to save the default map but if I zoom in or out it still saves the default map. How can I tell shiny to capture what's being displayed currently? Small example below:

library(shiny)
library(leaflet)
library(webshot2)
library(htmlwidgets)
library(mapview)

ui <- fluidPage(
  titlePanel("Download Leaflet Map as PNG"),
  sidebarLayout(
    sidebarPanel(
      downloadButton("Download_map", "Download Map as PNG")
    ),
    mainPanel(
      leafletOutput("map")
    )
  )
)

server <- function(input, output, session) {
  
  create_map <- reactive({
  leaflet(options = leafletOptions(zoomControl = FALSE)) %>% #hide the zoom controls button in leaflet map
    addTiles() %>%
    setView(lng = -122.6765, lat = 45.5231, zoom = 12) %>%
    addMarkers(lng = -122.6765, lat = 45.5231, popup = "Portland, OR")
})
  # Render the leaflet map
  output$map <- renderLeaflet({
   create_map()
  })
 
  output$Download_map <- downloadHandler(
    filename = "map.png",
    
    content = function(file) {
      mapview::mapshot(create_map(), file = file)
    }
  )
}
shinyApp(ui = ui, server = server)

Solution

  • server <- function(input, output, session) {
      
      output$map <- renderLeaflet({
        leaflet(options = leafletOptions(zoomControl = FALSE)) %>%
          addTiles() %>%
          setView(lng = -122.6765, lat = 45.5231, zoom = 12) %>%
          addMarkers(lng = -122.6765, lat = 45.5231, popup = "Portland, OR")
      })
      
      # create map with current view
      create_current_map <- function() {
        bounds <- input$map_bounds
        zoom <- input$map_zoom
        center <- input$map_center
        
        if (is.null(bounds) || is.null(zoom) || is.null(center)) {
          lng <- -122.6765
          lat <- 45.5231
          zoom_level <- 12
        } else {
          lng <- center$lng
          lat <- center$lat
          zoom_level <- zoom
        }
        
        leaflet(options = leafletOptions(zoomControl = FALSE)) %>%
          addTiles() %>%
          setView(lng = lng, lat = lat, zoom = zoom_level) %>%
          addMarkers(lng = -122.6765, lat = 45.5231, popup = "Portland, OR")
      }
      
      output$Download_map <- downloadHandler(
        filename = "map.png",
        content = function(file) {
          mapview::mapshot(create_current_map(), file = file)
        }
      )
    }