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

我们两清 提交于 2020-01-11 06:07:08

问题


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)})
})


来源:https://stackoverflow.com/questions/35266730/r-leaflet-cran-how-to-register-clicking-off-a-marker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!