问题描述
我在 leaflet
的 shiny
仪表板中使用 R
呈现交互式地图。仪表板还包含两个使用 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)
解决方法
试试这个
# WORKING CORRECTLY: Clicking city on map should update country and city selected
observeEvent(input$map_marker_click,{
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)])
}
},ignoreInit = TRUE)
observe({
if(!is.null(input$map_marker_click)){
req(input$countrySelected)
updateSelectizeInput(
session,"citySelected",selected = cities$city[(cities$lat==input$map_marker_click$lat)&(cities$long==input$map_marker_click$lng)])
}
})