Подтвердить что ты не робот

Сохранить карту буклета в Shiny

Я создал карту буклета в приложении Shiny. Теперь мне нужна кнопка загрузки, так что пользователь может загрузить отображаемую карту, включая все маркеры, полигоны и т.д. В формате pdf.

Я нашел это решение, как сохранить карту буклета в R: Как сохранить листок в карте R в виде файла png или jpg?

Но как он работает в Shiny? Я сохранил пример кода простым, но думаю об этом, как если бы было много изменений в карте через leafletProxy(), прежде чем пользователь захочет сохранить карту в формате pdf.

Это моя попытка, но она не работает.

server.R

library(shiny)
library(leaflet)
library(devtools)
install_github("wch/webshot") # first install phantomjs.exe in your directory

library(htmlwidgets)
library(webshot)

server <- function(input, output){

  output$map <- renderLeaflet({
    leaflet() %>% addTiles()
  })

 observe({
    if(input$returnpdf == TRUE){
      m <- leafletProxy("map")
      saveWidget(m, "temp.html", selfcontained = FALSE)
      webshot("temp.html", file = "plot.pdf", cliprect = "viewport")
    }
  })

  output$pdflink <- downloadHandler(
    filename <- "map.pdf",
    content <- function(file) {
      file.copy("plot.pdf", file)
    }
  )
}

ui.R

ui <- fluidPage(
     sidebarPanel(
     checkboxInput('returnpdf', 'output pdf?', FALSE), 
     conditionalPanel(
       condition = "input.returnpdf == true",
       downloadLink('pdflink')
      ) 
     ), 
     mainPanel(leafletOutput("map"))
)
4b9b3361

Ответ 1

Я обновил свой предыдущий ответ, чтобы сделать его более понятным и проиллюстрировать, как использовать mapshot из пакета mapview. Более того, следуя рассмотренному ниже вопросу Джейка, я заметил, что может потребоваться указать ссылку на фрагмент (в addTiles), или карта может быть загружена с серого фона.

Сервер

server = function(input, output){

    mymap <- reactive({
      # here I have specified a tile from openstreetmap
      leaflet() %>% addTiles('http://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png')
    })

    output$map <- renderLeaflet({
      mymap()
    })

    # function with all the features that we want to add to the map
    myfun <- function(map){
      addCircles(map,12.5,42,radius=500) %>% addMarkers(12,42,popup="Rome")
    }

    observe({
      leafletProxy("map") %>% myfun()
    })

    # map that will be downloaded
    mapdown <- reactive({
      # we need to specify coordinates (and zoom level) that we are currently viewing
      bounds <- input$map_bounds
      latRng <- range(bounds$north, bounds$south)
      lngRng <- range(bounds$east, bounds$west)
      mymap() %>% myfun() %>% setView(lng = (lngRng[1]+lngRng[2])/2, lat = (latRng[1]+latRng[2])/2, zoom = input$map_zoom)
    })

    output$map_down <- downloadHandler(
      filename = 'mymap.pdf',

      content = function(file) {
        # temporarily switch to the temp dir, in case you do not have write
        # permission to the current working directory
        owd <- setwd(tempdir())
        on.exit(setwd(owd))

        # using saveWidget and webshot (old)
        saveWidget(mapdown(), "temp.html", selfcontained = FALSE)
        webshot("temp.html", file = file, cliprect = "viewport")

        # using mapshot we can substitute the above two lines of code
        # mapshot(mapdown(), file = file, cliprect = "viewport")
      }
    )
  }

Пользовательский интерфейс

ui <- fluidPage(
     sidebarPanel(
     checkboxInput('returnpdf', 'output pdf?', FALSE), 
     conditionalPanel(
       condition = "input.returnpdf == true",
       downloadButton('map_down')
      ) 
     ), 
     mainPanel(leafletOutput("map"))

)