如何通过再次单击要素来删除使用 Shiny 和 mapedit 所做的选择?

How do I remove a selection made using Shiny and mapedit by clicking again on the feature?

使用 Shiny、leaflet 和 mapedit 包,我可以使用下面的代码生成包含多个系列的图表。

凭直觉,我想再次单击选定的地图图标,相关数据将从图表中删除。本质上,点击事件可以打开或关闭。

有人有什么建议吗?

# devtools::install_github("r-spatial/sf")
# devtools::install_github("r-spatial/mapview@develop")
# devtools::install_github("bhaskarvk/leaflet.extras")
# devtools::install_github("r-spatial/mapedit")
library(tidyverse)
library(sf)
library(leaflet)
library(mapedit)
library(mapview)
library(shiny)
library(shinyjs)

locnCoord <-
  data.frame(location = c('Sit1','Site2','Site3'),
             lat=c(-18.1, -18.3, -18.4),
             lon=c(145.8, 145.9, 145.9)) %>%
  mutate(depth = runif(3))

locnSF <- st_as_sf(locnCoord, coords = c('lon','lat'), crs="+proj=longlat +datum=WGS84 +no_defs")

#### User input

ui <- fluidPage(
  shinyjs::useShinyjs(),
  shinyjs::extendShinyjs(text = "shinyjs.refresh = function() { location.reload(); }"),
  fluidRow(
    # edit module ui
    column(6,
           selectModUI("selectmap"),
           actionButton("refresh", "Refresh Map")
           ),
    column(6,
           h3("Point of Depth"),
           plotOutput("selectstat")
           )
    )
  )

#### Server

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

  observeEvent(input$refresh, {
    shinyjs::js$refresh()
  })

  g_sel <- callModule(
    selectMod,
    "selectmap",
    leaflet() %>%
      addTiles() %>%
      addFeatures(
        data = locnSF,
        layerId = ~location,
        stroke = TRUE,
        color = 'orange',
        fill = TRUE,
        fillColor = 'black',
        radius=10)
  )

  rv <- reactiveValues(selected=NULL)

  observe({
    gs <- g_sel()

    if(length(gs$id) > 0) {
      rv$selected <- locnSF %>% filter(location %in% gs$id)
    } else {
      rv$selected <- NULL
    }
  })

  output$selectstat <- renderPlot({
    ggplot()
    if(!is.null(rv$selected) && nrow(rv$selected) > 0) {
      ggplot(data=rv$selected, aes(location, depth))+
        geom_point(color='red', size=5)
    } else {
      ggplot()
    }
  })
}
shinyApp(ui, server)

这行得通。在你的服务器上试试这个:

observe({
   gs <- g_sel()

   if(length(gs$id) > 0) {
     site_select <- c(gs$selected)
     rv$selected <- locnSF %>% filter(location %in% gs$id) %>% 
       mutate(keeps = site_select) %>% filter(keeps == "TRUE")
   } else {
     rv$selected <- NULL
   }
})

这是根据您上面的代码编辑的。我所做的是添加一个名为 keeps via mutate 的新列,其中包含一个逻辑项,表示是否选择了站点,然后仅过滤了 TRUE(即当前选定的)观察结果。当您取消选择一个站点时,keeps 中的术语变为 FALSE,因此从 rv$selected 中省略。

希望对您有所帮助。