R Leaflet (CRAN) - how to register clicking off a

2019-02-18 02:48发布

问题:

Using the RStudio Leaflet package in a shiny app I've been able to achieve all the functionality I've looked for except deselecting a marker object once it has been clicked on.

More specifically, the input$map_click_id value is set to NULL before any markers are clicked. Upon clicking a marker it is updated with the data (ID, lat, lng, nonce) for that marker. I would like to set the map up so that when a user clicks on any area of the map which is not a marker, input$map_click_id is reset to NULL until another marker is clicked.

I've tried a number of work around solutions for this such as comparing the click times for marker clicks and map clicks, but the marker click variable, once set to a non-NULL value, is updated everytime the map is clicked, regardless of whether it is on a marker or not, so this doesn't work.

Any help here would be greatly appreciated! Below is a very minimal reproducable example. In this case I would like for the marker info to print to the console when it is clicked, and for NULL to be returned to the console when any non-marker area of the map is clicked.

library(leaflet)
library(shiny)

# set basic ui
ui <- fluidPage(
  leafletOutput("map")
)

server <- shinyServer(function(input, output) {

  # produce the basic leaflet map with single marker
  output$map <- renderLeaflet(
    leaflet() %>%
      addProviderTiles("CartoDB.Positron") %>%
      addCircleMarkers(lat = 54.406486, lng = -2.925284)

  )

  # observe the marker click info and print to console when it is changed.
  observeEvent(input$map_marker_click,
               print(input$map_marker_click)
               )

})


shinyApp(ui, server)

This appears to be the same question as asked here but as there was no answer for this, I thought I'd try again.

回答1:

You could use a reactiveValues to store the clicked marker and reset it whenever the user clicks on the map background:

server <- shinyServer(function(input, output) {
  data <- reactiveValues(clickedMarker=NULL)
  # produce the basic leaflet map with single marker
  output$map <- renderLeaflet(
    leaflet() %>%
      addProviderTiles("CartoDB.Positron") %>%
      addCircleMarkers(lat = 54.406486, lng = -2.925284)    
  )

  # observe the marker click info and print to console when it is changed.
  observeEvent(input$map_marker_click,{
               data$clickedMarker <- input$map_marker_click
               print(data$clickedMarker)}
  )
  observeEvent(input$map_click,{
               data$clickedMarker <- NULL
               print(data$clickedMarker)})
})