0

I would like to write a script that selects a marker on the map whenever I click on it and then deselect it when I click/select another marker (that is, so that no more that one marker is selected on the map at any time). I managed to get the selection bit working for the multiple "current" marker, but not the deselection of the last clicked marker, partly because I am confused with the time ordering/reactivity of objects in shiny environment. I attempted to use leafletProxy() to substitute default icons with selected icons to mimic selection, but that only took me this far.

Clinics map

library(shiny) 
library(leaflet)

ui <- fluidPage(
   fluidRow(leafletOutput("clinics.map"))
)

server <- function(input, output, session) {
     icons <- makeIcon(iconUrl = "clinic_icon.png", iconWidth = 27, iconHeight = 30)
     icons.sel <- makeIcon(iconUrl = "clinic_icon_selected.png", iconWidth = 27, iconHeight = 30)

   output$clinics.map <- renderLeaflet({
      leaflet(data = clinics) %>%
      addProviderTiles("CartoDB.Positron") %>%
      setView(lat = 37.900000, lng = -121.900000, zoom = 9) %>%
      addMarkers(lng = ~lon, lat = ~lat, icon = icons, layerId = ~ID) 
   }) 

   previous.markers <- reactiveValues(markerID = c(), marker.lat = c(), marker.lon = c())

   observeEvent(input$clinics.map_marker_click, {
      marker.click <- input$clinics.map_marker_click
      previous.markers$markerID <- c(previous.markers$markerID, marker.click$id)
      previous.markers$marker.lat <- c(previous.markers$marker.lat, marker.click$lat)
      previous.markers$marker.lon <- c(previous.markers$marker.lon, marker.click$lng)

      last.marker.id <- tail(previous.markers$markerID, 1)
      last.marker.lat <- tail(previous.markers$lat, 1)
      last.marker.lon <- tail(previous.markers$lon, 1)

      leafletProxy("clinics.map", session) %>%
      removeMarker(last.marker.id) %>% 
      #addMarkers(last.marker.id,      # This bit doesn't work b/c there's no last marker initially
      #           lng = last.marker.lon,
      #           lat = last.marker.lat,
      #           icon = icons) %>% 
      addMarkers(marker.click$id,
                 lng = marker.click$lng,
                 lat = marker.click$lat,
                 icon = icons.sel)
   })

shinyApp(ui, server)

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.