从应用程序内重新启动闪亮的应用程序(重新加载数据)

Restart shiny app from within app (reloading data)

我想从应用程序中重新启动一个闪亮的应用程序,例如global.R 中的代码将再次执行(重新加载包含数据的 csv 文件)。这是一个显示我想要做什么的最小示例:

这个闪亮的应用程序加载一些坐标数据并在地图上绘制标记。将新标记添加到地图时,应将新坐标附加到旧数据并保存为 csv 文件。然后应用程序应该重新启动,再次加载 data.csv,因此所有标记都显示在地图上。我尝试从这里改编代码:Restart Shiny Session 但这不起作用。应用程序重新启动,但它不会重新加载 csv 文件。

library(shinyjs)
library(leaflet)
library(leaflet.extras)

jsResetCode <- "shinyjs.reset = function() {history.go(0)}"

# data <- data.frame(latitude = 49, longitude = 13)
data <- read.csv2("data.csv") # this should get executed whenever js$reset is called

ui <- fluidPage(
  useShinyjs(),                     
  extendShinyjs(text = jsResetCode),
    leafletOutput("map")
)

server <- function(input, output, session){
  output$map <- renderLeaflet({
    leaflet(data) %>% addTiles()  %>%
      setView(11.5, 48, 7) %>%
      addDrawToolbar() %>% 
      addMarkers()
  })

  data_reactive <- reactiveValues(new_data = data)

  # add new point to existing data and save data as data.csv
  # after that the app should restart
  observeEvent(input$map_draw_new_feature, {
    data_reactive$new_data <- rbind(rep(NA, ncol(data)), data_reactive$new_data)
    data_reactive$new_data$longitude[1] <- input$map_draw_new_feature$geometry$coordinates[[1]]
    data_reactive$new_data$latitude[1] <- input$map_draw_new_feature$geometry$coordinates[[2]]
    write.csv2(data_reactive$new_data, "data.csv", row.names = FALSE)
    js$reset() # this should restart the app
  })
}

shinyApp(ui, server)

要重新加载 csv 文件,您需要在服务器中读取该文件。

server <- function(input, output, session){

    #Read the data inside the server!!!
    data <- read.csv2("data.csv")# this should get executed whenever js$reset is called

    output$map <- renderLeaflet({
      leaflet(data) %>% addTiles()  %>%
        setView(11.5, 48, 7) %>%
        addDrawToolbar() %>% 
        addMarkers()
    })

    data_reactive <- reactiveValues(new_data = data)

    # add new point to existing data and save data as data.csv
    # after that the app should restart
    observeEvent(input$map_draw_new_feature, {
      # browser()
      data_reactive$new_data <- rbind(rep(NA, ncol(data)), data_reactive$new_data)
      data_reactive$new_data$longitude[1] <- input$map_draw_new_feature$geometry$coordinates[[1]]
      data_reactive$new_data$latitude[1] <- input$map_draw_new_feature$geometry$coordinates[[2]]
      write.csv2(data_reactive$new_data, "data.csv", row.names = FALSE)
      js$reset() # this should restart the app
    })
  }