這是我第一次嘗試將閃亮的應用程式重組為閃亮的模塊,因此,歡迎提供一些幫助。
我的目標是創建一個可點擊的地圖模塊leaflet,它將緯度和經度存盤在一個input我可以在其他模塊中重用的模塊中。目前,該模塊通過在uia leafletOutput(id="mymap") 中創建并在server函式中使用一個回應observeEvent點擊地圖的函式來作業。單擊事件生成input經度和緯度 ( input$input$mymap_click$lat[1]& input$mymap_click$lng[1])的向量,用于在地圖上放置標記。但是我很難將它們提取到值中,以便其他模塊或render*函式在外部使用它。(它在沒有“模塊方法”的情況下作業,但代碼有點亂)
為了在我的示例中清楚起見,我嘗試在textOutputwithrenderText而不是在模塊中使用緯度和經度。
# clickable leaflet module ----------------------------------------------------------
## loads leaflet library
library(leaflet)
##ui function
clicMapOutput <- function(id) {
ns <- NS(id)
tagList(leafletOutput(ns("mymap")),
textOutput(ns("text")))
}
## serverfunction
clicMapServer <- function(id) {
moduleServer(id,
function(input, output, session) {
# outputs a map
output$mymap <-
leaflet::renderLeaflet({
leaflet() %>% addTiles() %>% setView(lat = 0,
lng = 0,
zoom = 2)
})
# makes map clickable to obtain a marker and a longitude latitude vector
observeEvent(input$mymap_click, {
output$mymap <-
leaflet::renderLeaflet({
leaflet() %>% addTiles() %>% addMarkers(lat = input$mymap_click$lat[1],
lng = input$mymap_click$lng[1])
})
})
})
}
# Calling modules ---------------------------------------------------------
library(shiny)
ui<-fluidPage(
clicMapOutput("map"),
textOutput("lng")
)
server<-function(input,output,session){
clicMapServer("map")
output$lng<-renderText({
input$mymap_click$lng[1]
})
}
shinyApp(ui=ui,server=server)
uj5u.com熱心網友回復:
這樣做的常用方法是在模塊的服務器部分定義一個回傳值,然后在模塊使用者中使用它
## module server
clicMapServer <- function(id) {
moduleServer(id, function(input, output, session) {
## ...
return(reactive(input$mymap_click$lng[1])))
}
}
## consumer server
server <- function(input, output, session) {
lng <- clicMapServer("map")
output$lng <- renderText({ lng() })
}
您應該始終確保使用反應式包裝回傳值并像使用函式一樣使用回傳值。如果您想回傳多個變數,請參閱我對此問題的回答以了解詳細資訊。
library(leaflet)
library(shiny)
## module ui
clicMapOutput <- function(id) {
ns <- NS(id)
leafletOutput(ns("mymap"))
}
## module server
clicMapServer <- function(id) {
moduleServer(id, function(input, output, session) {
output$mymap <- renderLeaflet({
leaflet() %>% addTiles() %>% setView(
lat = 0, lng = 0, zoom = 2)
})
# handle click events
observeEvent(input$mymap_click, {
output$mymap <- renderLeaflet({
leaflet() %>% addTiles() %>% addMarkers(
lat = input$mymap_click$lat[1],
lng = input$mymap_click$lng[1])
})
})
return(reactive(input$mymap_click$lng[1]))
})
}
# main ui
ui <- fluidPage(
clicMapOutput("map"),
textOutput("lng")
)
# main server
server <- function(input, output, session) {
lng <- clicMapServer("map")
output$lng <- renderText({ lng() })
}
shinyApp(ui = ui, server = server)
我注意到的另一件事是您正在通過覆寫output$mymap. 用它leaflet::leafletProxy()代替會更好。一般來說,outputs 不應該被賦值給內部observe()或observeEvent()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/351303.html
上一篇:R:基于索引的應用到向量
