R Shiny:使用传单地图单击更新多个相关下拉菜单

问题描述

我在 leafletshiny 仪表板中使用 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)])
    }
    
  })

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...