Shiny Leaflet地图交互问题:选中站点未过滤仍显示全部站点
问题修复方案
你的代码核心问题是在添加标记时没有使用过滤后的数据集,同时UI部分存在语法缺失,以下是修正后的完整代码:
library(shiny) library(shinythemes) library(leaflet) library(dplyr) # 生成模拟数据 Site_Name <- sample(c('a','b','c'), replace=T, 5) Latitude <- runif(5, min=-26, max=-22) Longitude <- runif(5, min=-54, max=-48) Sites <- data.frame(Site_Name, Latitude, Longitude) ui <- fluidPage( theme = shinytheme("cerulean"), sidebarLayout( sidebarPanel( selectizeInput("sites", "Site Name", choices = Sites$Site_Name, options = list(maxItems = 2)) ), mainPanel( tabsetPanel( tabPanel("Plots", leafletOutput("Station")) ) ) ) ) server <- shinyServer(function(input, output, session) { df1 <- eventReactive(input$sites, { Sites %>% dplyr::filter(Site_Name %in% input$sites) }) output$Station = renderLeaflet({ leaflet(data = df1()) %>% addProviderTiles(providers$Esri.WorldStreetMap) %>% addMarkers(lng = ~Longitude, lat = ~Latitude, popup = ~Site_Name, icon = list( iconUrl = 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-red.png', iconSize = c(13, 20))) }) }) shinyApp(ui, server)
关键修改说明:
- UI语法补全:添上了
sidebarPanel和mainPanel的闭合括号,保证UI结构合法 - 标记数据关联:
addMarkers中使用~Longitude、~Latitude和~Site_Name,自动绑定到传入的过滤后数据集df1(),仅展示选中站点 - 弹窗内容优化:绑定过滤后数据的站点名称,确保弹窗显示对应站点的准确名称
内容的提问来源于stack exchange,提问作者Dome
相关产品推荐
相关产品推荐

