0

I have an app with an observeEvent that reacts when the user clicks on a polygon or a marker on a map. After clicking, I run some code to do stuff with the last polygon OR marker clicked.

Question is : how can I know which one was the last clicked so I know which ID to use in the next operations ? Can I do it without making two separated observeEvent, or can I keep one and "detect" which expression was triggered ?

library(shiny)
library(leaflet)


ui <- shinyUI(fluidPage(leafletOutput("map")))

server <- function(input, output, session){
  i <- reactiveValues(i=0)
  # Draw a map with a marker and a polygon
  output$map <- renderLeaflet(
    leaflet() %>%
      addTiles() %>%
      setView(lng = 49, lat = 13.4, zoom = 10) %>%
      addPolygons(
        lng = c(48.99831, 49.08815, 49.08815, 48.99831, 48.99831),
        lat = c(13.42666, 13.42666, 13.56383, 13.56358, 13.42666),
        layerId=c("poly1")) %>%
      addMarkers(
        lng = 48.99,
        lat = 13.35,
        layerId = c("mark1")
      )
  )

  observeEvent({
    input$map_shape_click # react when polygon is clicked
    input$map_marker_click # react when marker is clicked
    1
  }, {
    print(i$i) # just to keep count on the clicks
    print(input$map_shape_click$id)
    print(input$map_marker_click$id)
    i$i = i$i +1
    # do stuff with the last shape OR marker clicked
  })
}

shinyApp(ui, server)
gdevaux
  • 2,308
  • 2
  • 10
  • 19
  • 3
    In general, I believe that `shiny` does not tell you which reactive object triggered execution. You might set up `prev <- reactiveValues(map_shape_click=NULL, map_marker_click=NULL)`, then check the current (`input$...`) value against the previous (`prev$...`) value and act accordingly, making sure to update `prev$... <- input$...` before exiting that reactive block. – r2evans Dec 10 '20 at 14:57
  • Thank you for that idea. I will use it if nothing simplier comes up – gdevaux Dec 10 '20 at 15:01
  • 1
    This might be of interest : https://stackoverflow.com/a/56771353/13513328 – Waldi Dec 12 '20 at 17:01
  • That is a great help thanks ! – gdevaux Dec 13 '20 at 08:27

0 Answers0