我的 Shiny 应用程序使用基于传单标记单击的值更新 selectizeInput 小部件。
selectizeInput 小部件允许多个站点选择,我设法弄清楚如何使用以下代码根据传单地图标记单击来更新所选站点列表。
library(tidyverse)
library(shiny)
library(shinydashboard)
library(leaflet)
sensor_locations <- data.frame(site_id=c("Site1","Site2","Site3","Site4","Site5"),
latitude=c(-37.80079, -37.80052, -37.80230, -37.80058, -37.80063),
longitude=c(144.9665, 144.9641, 144.9609, 144.9646, 144.9651))
ui <- fluidPage(
fluidRow(
sidebarPanel(width = 3,
selectizeInput("selectedSites", "Select Sites :",
choices = c("Site1","Site2","Site3","Site4","Site5"),
multiple = TRUE,
selected = c("Site1","Site2"),
options = list('plugins' = list('remove_button'))),
fluidRow(leafletOutput("sitemap"))
))
)
server <- function(input, output, session) {
output$sitemap <- renderLeaflet({
leaflet(data = sensor_locations,
options = leafletOptions(zoomControl = FALSE)) %>%
addProviderTiles(providers$CartoDB.Positron) %>%
addCircleMarkers(layerId = ~site_id,
label = ~site_id,
radius= 15,
opacity = 1)
})
observeEvent(input$sitemap_marker_click, {
click <- input$sitemap_marker_click
updateSelectInput(session, "selectedSites",
selected = c(input$selectedSites, click$id))
})
}
shinyApp(ui = ui, server = server)
我的应用程序当前允许在单击时将站点添加到选定列表,现在我还希望允许用户在单击传单标记时取消选择站点(从 selectizeInput 框上的选定列表中删除)。
你可以这样做:
observeEvent(input$sitemap_marker_click, {
click <- input$sitemap_marker_click
if(click$id %in% input$selectedSites)
selected = input$selectedSites[input$selectedSites != click$id]
else
selected = c(input$selectedSites, click$id)
updateSelectInput(session, "selectedSites",
selected = selected)
})
如果您喜欢更简洁(且可读性较差)的代码:
observeEvent(input$sitemap_marker_click, {
click <- input$sitemap_marker_click
updateSelectInput(session, "selectedSites",
selected = c(click$id[!click$id %in% input$selectedSites],
input$selectedSites[input$selectedSites != click$id]))
})