【发布时间】:2021-06-08 11:56:30
【问题描述】:
我在R 的shiny 仪表板中有一个使用leaflet 渲染的交互式地图。仪表板还包含两个使用selectizeInput 创建的下拉菜单,其中第二个下拉菜单中可用的选项取决于第一个下拉菜单中的选择。在下面的玩具示例中,第二个下拉列表显示了一个城市列表,这取决于在第一个下拉列表中选择的国家/地区。
我想通过单击地图中的城市来指定这两个下拉菜单中的选择。在下面的代码中,一旦您选择了一个国家,这将起作用。例如,如果我从第一个下拉列表中选择“澳大利亚”,然后单击地图中的澳大利亚城市,则第二个下拉列表中的所选城市会正确更新。但是,如果我随后单击新西兰的一个城市,无论我实际单击的是哪个新西兰城市,都会在城市下拉列表中选择“奥克兰”(新西兰列表中的第一个城市)。随后点击新西兰城市即可正常工作。
当我第一次点击与当前在国家/地区下拉列表中选择的不同国家/地区的城市时,如何正确更新城市下拉列表?
注意:这只是作为我需要的功能的一个简单、可重现的示例。
library(shiny)
library(leaflet)
cities <- data.frame(country = c(rep('Australia',5),rep('New Zealand',3)),
city = c("Adelaide", "Brisbane", "Melbourne", "Perth", "Sydney", "Auckland", "Christchurch", "Wellington"),
lat = c(-34.9329, -27.469, -37.8142, -31.9527, -33.868, -36.85, -43.53, -41.2889),
long = c(138.5998, 153.0235, 144.9632, 115.8605, 151.21, 174.7833, 172.6203, 174.7772))
ui <- fluidPage(
fluidRow(column(width=12, leafletOutput("map"))),
fluidRow(
column(width=4,
selectizeInput(inputId = "countrySelected",label = "Country", choices = cities$country),
uiOutput("citySelectedUI"))
)
)
server <- function(input, output, session){
# THE MAP:
output$map <- renderLeaflet({
leaflet(cities) %>%
addTiles() %>%
setView(lng=152, lat=-36, zoom=4) %>%
addCircleMarkers(lng = ~long, lat = ~lat, radius=4, label=~city)
})
# THE CITIES DROPDOWN (CONDITIONAL ON SELECTED COUNTRY)
output$citySelectedUI <- renderUI({
selectizeInput("citySelected", "City", choices=cities$city[cities$country==input$countrySelected])
})
# NOT WORKING CORRECTLY: Clicking city on map should update country and city selected
observe({
if(!is.null(input$map_marker_click)){
updateSelectizeInput(
session, "countrySelected",
selected = cities$country[(cities$lat==input$map_marker_click$lat)&(cities$long==input$map_marker_click$lng)])
updateSelectizeInput(
session, "citySelected",
selected = cities$city[(cities$lat==input$map_marker_click$lat)&(cities$long==input$map_marker_click$lng)])
}
})
}
shinyApp(ui = ui, server = server)
【问题讨论】:
标签: r shiny drop-down-menu r-leaflet selectinput