You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shiny应用问题:点击Leaflet地图标记无法更新selectInput选中项

问题解决:点击Leaflet标记更新Shiny下拉选单

核心问题是input$map_marker_click对象默认不包含station_name字段,只能通过标记的layerId来关联站点信息。以下是修复后的代码和关键说明:

关键修改点

  • 在addCircleMarkers中添加layerId = ~station_name,将站点名称绑定为标记的唯一ID
  • 从input$map_marker_click$id提取点击的站点名称,而非station_name字段

修复后的完整代码

library(leaflet)
library(sf)
library(dplyr)
library(shiny)

geopackage_path <- "C:/Users/yagmur/work/Spain/data/"

year <- 2022
sf_data <- st_read(file.path(geopackage_path, paste0("meteo_andalucia_", 
                                                     year, ".gpkg")))

# Select unique locations
unique_locations <- sf_data %>% distinct(station_name, .keep_all = TRUE)

ui <- fluidPage(
  fluidRow(
    column(width = 4,
           selectInput("station", "Select a Station", 
                       choices = unique_locations$station_name),
           actionButton("compare", "Compare Temperature")
    ),
    column(width = 8,
           leafletOutput("map")
    )
  ),
  plotOutput("graph")
)

server <- function(input, output, session) {
  # Initialize the selected station with the first option
  selected_station <- reactiveVal(unique_locations$station_name[1])
  
  # Render the leaflet map
  output$map <- renderLeaflet({
    leaflet(data = unique_locations) %>%
      addTiles() %>%
      addCircleMarkers(radius = 4,
                       color = "red",
                       fillOpacity = 0.8,
                       label = ~station_name,
                       group = "markers",
                       layerId = ~station_name)  # 新增:绑定站点名称为标记ID
  })
  
  # Update the selected station when a marker is clicked
  observeEvent(input$map_marker_click, {
    clicked_station <- input$map_marker_click$id  # 从id字段获取站点名称
    selected_station(clicked_station)
    
    # Update the select input with the clicked station
    updateSelectInput(session, "station", selected = clicked_station)
  })
  
  # 可选:当下拉选单手动更改时同步更新响应式值
  observeEvent(input$station, {
    selected_station(input$station)
  })
  
  # 示例:渲染温度图表(根据选中站点过滤数据)
  output$graph <- renderPlot({
    req(selected_station())
    station_data <- sf_data %>% filter(station_name == selected_station())
    # 这里替换为你的温度图表绘制逻辑,例如:
    plot(station_data$date, station_data$temperature, type = "l", 
         main = paste("Temperature at", selected_station()),
         xlab = "Date", ylab = "Temperature")
  })
}

shinyApp(ui, server)

补充说明

  1. 添加layerId = ~station_name后,每个标记都会关联对应的站点名称,点击时input$map_marker_click会返回该ID
  2. 初始化selected_station时设置了默认值,避免初始状态为NULL导致图表渲染出错
  3. 新增了下拉选单手动更改的事件监听,确保响应式值与选单状态始终同步

内容的提问来源于stack exchange,提问作者Yagmur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 00:05:35