在闪亮的模块中下载地图不起作用

Download map in shiny modules is not working

提问人:akshay bholee 提问时间:8/30/2022 最后编辑:akshay bholee 更新时间:9/1/2022 访问量:166

问:

我有一个只有下载按钮的模块和其他 2 个模块,用于绘制地图的 ui 和服务器功能。

现在我想实现下载按钮来打印地图。我尝试了很多方法,但我无法下载pdf格式的地图。

在我的原始脚本中,我有几个模块来绘制多个图表。我必须能够将所有图表下载到一个pdf中。

下载不起作用。 我试过这个例子:https://community.rstudio.com/t/shiny-module-downloading-all-plots-into-a-single-pdf/124869

如何下载pdf格式的地图?

这是我的可重现代码:

#The map UI
trade_agreement_ui <- function(id) {
  ns <- NS(id)
  
  tagList(
          fluidRow(column(
            8,
            offset = 2,
            box(
              solidHeader = TRUE,
              column(12, align = 'left', h4(strong("Trade Agreement"))),
              br(),
              column(
                12,
                align = 'left',
                br(),
                
                leafletOutput(outputId = ns("map1"),height = "650px", width = "100%")
              ),
              width = 16
            )
            
          )))
  
}
#The map server
trade_agreement_server <- function(id) {
  moduleServer(id,
               
               function(input, output, session) {
               
                 val <- reactiveValues(map1=NULL) 
                 
                 output$map1 <- renderLeaflet({
                   
                
                   val$map1 <- leaflet() %>%
                     addTiles(urlTemplate = "https://api.mapbox.com/styles/v1/bholee/cl75rvfqs002q14o0rwzd6oe5/tiles/{z}/{x}/{y}@2x?access_token=pk.eyJ1IjoiYmhvbGVlIiwiYSI6ImNrN2tibG9pNzAwajMzbWw4ZnlpcDNqY2wifQ.o-qJAmRdkh-McoubI4E2DA"
                                                 ) 
                   val$map1 
                 })
                 
                 val
                 
                 
               })
  
}
#Main UI
ui <-
  tagList( 
    
    tags$style(HTML(
      paste(
        "html,",
        ".container{
                    width: 100%;
                    margin: 0 auto;
                    padding: 0;
                }
               @media screen and (min-width: 700px){
                .container{
                    min-width: 1850px;
                    max-width: 1920px;
                }
               }
                          ",
        sep = " "
      )
    )),
    tags$div(
      class = "container",
    dashboardPage(
      dashboardHeader(disable = TRUE),
      dashboardSidebar(disable = TRUE),
      dashboardBody( 
        #UI for download
        fluidRow(column(
          8, offset = 2, box(
            solidHeader = TRUE, 
            column(6, align = 'right',  class = 'download_padding', downloadButton(
              outputId =   "download",
              label = "Download Report",
              class = 'download_button',
              width = 150,
            )
            ),
            width = 16,
            
          )
          
        )),
        #End of UI for download
       
        #UI for Trade Agreements
        trade_agreement_ui(id = "agreement")
        #End of UI Trade Agreements
        
        
      )
    )
    )
  )
#### End Create User Interface #####
#Main Server
#### Create Server actions #####
server <- shinyServer(function(input, output, session) {
  
  #### Trade Agreements ####
 v1 <- trade_agreement_server(
    id = "agreement"
  )
  #### Trade Agreements ####

output$download <- downloadHandler(
  filename = function() {
    paste0("plot.pdf")
  },
  content = function(file) {
    pdf(file)
    v1$map1
    dev.off()
  }
)
  
  
})
#### End create Server actions #####

#### Run application #####
shinyApp(ui, server)
#### End Run application #####
R Shiny 下载 ShinyModules

评论

0赞 YBS 8/31/2022
您可能需要考虑使用对应于reporter_download_ui(..)
0赞 akshay bholee 8/31/2022
我试图完全按照您的建议进行操作,但它不起作用,因为我必须在reporter_download_ui中获取地图 ID 才能下载地图。

答:

0赞 YBS 8/31/2022 #1

您可以使用 a 在主服务器中下载地图。我不确定在您的用例中是否需要单独模块中的下载按钮;然后你需要测试一下。downloadHandler

library(leaflet)
library(mapview)
library(webshot)

#The map UI
trade_agreement_ui <- function(id) {
  ns <- NS(id)
  
  tagList(
    fluidRow(column(
      8,
      offset = 2,
      box(
        solidHeader = TRUE,
        column(12, align = 'left', h4(strong("Trade Agreement"))),
        br(),
        column(
          12,
          align = 'left',
          br(),
          
          leafletOutput(outputId = ns("map"),height = "650px", width = "100%")
        ),
        width = 16
      )
      
    )))
  
}
#The map server
trade_agreement_server <- function(id) {
  moduleServer(id,
               function(input, output, session) {
                 
                 ### initial map
                 mymap <- reactive({
                   leaflet() %>%
                     addTiles(urlTemplate = "https://api.mapbox.com/styles/v1/bholee/cl75rvfqs002q14o0rwzd6oe5/tiles/{z}/{x}/{y}@2x?access_token=pk.eyJ1IjoiYmhvbGVlIiwiYSI6ImNrN2tibG9pNzAwajMzbWw4ZnlpcDNqY2wifQ.o-qJAmRdkh-McoubI4E2DA"
                     ) 
                 })
                 
                 output$map <- renderLeaflet({ mymap() })
                 
                 # return(mymap)  ## does not work
                 
                 user_created_map <- reactive({
                   
                   # call the initial Leaflet map
                   mymap() %>%
                     
                     # store the view based on UI
                     setView( lng = input$map_center$lng
                              , lat = input$map_center$lat
                              , zoom = input$map_zoom
                     )
                   
                 }) # end of creating user.created.map()
                 
                 return(user_created_map)
               })
  
}
#Main UI
ui <-
  tagList(  #shinyjs::useShinyjs(),
    # tags$head(# the javascript is checking the screen resolution to adapt the display
    #   tags$script(src = "javascripts.js")),
    
    tags$style(HTML(
      paste(
        "html,",
        ".container{
                    width: 100%;
                    margin: 0 auto;
                    padding: 0;
                }
               @media screen and (min-width: 700px){
                .container{
                    min-width: 1850px;
                    max-width: 1920px;
                }
               }
                          ",
        sep = " "
      )
    )),
    tags$div(
      class = "container",
      dashboardPage(
        dashboardHeader(disable = TRUE),
        dashboardSidebar(disable = TRUE),
        dashboardBody( 
          # 
          # tags$head(
          #   tags$link(rel = "stylesheet", type = "text/css", href = "styles.css")
          # ),
          fluidRow(column(4,""), column(2, offset = 1,
                                        downloadBttn("savePDF",
                                                     HTML(" Download Report"),
                                                     style = "fill",
                                                     color = "warning",
                                                     size = "lg",
                                                     block = TRUE,
                                                     no_outline = TRUE
                                        )
                                        )),
          
          #UI for download
          #reporter_download_ui(id = "reporterdownload"),
          #End of UI for download
          
          #UI for Trade Agreements
          trade_agreement_ui(id = "agreement")
          #End of UI Trade Agreements
          
          
        )
      )
    )
  )
#### End Create User Interface #####
#Main Server
#### Create Server actions #####
server <- shinyServer(function(input, output, session) {
  
  #### Trade Agreements ####
  mymap <- trade_agreement_server(id = "agreement")
  #### Trade Agreements ####
  
  
  # create the output file name
  # and specify how the download button will take
  # a screenshot - using the mapview::mapshot() function
  # and save as a PDF
  output$savePDF <- downloadHandler(
    filename = function(){
      paste0('mymap', Sys.Date(), '.pdf', sep='')
    },
    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))
      saveWidget(mymap(), "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")
    }
  )
  
})
#### End create Server actions #####

#### Run application #####
shinyApp(ui, server)

评论

0赞 akshay bholee 9/1/2022
谢谢。但这在我的用例中不起作用,因为在我的主应用程序中,我还有其他图表需要下载。每个图表都在一个模块中。这就是为什么我将 downloadHandler 放在主服务器中,以便能够下载不同模块中的所有图表。
0赞 YBS 9/1/2022
你可以把它放在主服务器上。
0赞 YBS 9/1/2022
请尝试更新后的代码。
0赞 akshay bholee 9/1/2022
谢谢。我会尝试一下并在这里做出回应。