I have an interactive map rendered with leaflet
in a shiny
dashboard in R
. The dashboard also contains two dropdown menus created with selectizeInput
, where the options available in the second dropdown depend on the selection in the first dropdown. In the toy example below, the second dropdown presents a list of cities, which depends on the country selected in the first dropdown.
I would like to specify the selections in these two dropdown menus by clicking on the city in the map. In the code below, this works once you have chosen a country. For example, if I select "Australia" from the first dropdown and then click on Australian cities in the map, the selected city in the second dropdown updates correctly. However, if I then click on a city in New Zealand, "Auckland" (the first city in the New Zealand list) is selected in the city dropdown regardless of which New Zealand city I actually clicked on. Subsequent clicks on cities in New Zealand then work correctly.
How can I get the city dropdown to update correctly the first time I click on a city in a different country to that currently selected in the country dropdown?
Note: This is only intended as a simple, reproducible example of the functionality that I require.
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)