When leafletProxy()
is used, the click event of leaflet returns NULL
when a polygone is clicked for the second time.
How can I prevent it from doing so?
Example code:
library(shiny)
library(leaflet)
library(sf)
library(dplyr)
# example polygone file
nc <- st_read(system.file("shape/nc.shp", package="sf")) %>%
select(CNTY_ID) %>%
st_transform(4326)
ui <- fluidPage(
leafletOutput("mymap")
)
server <- function(input, output, session) {
# define map
output$mymap <- renderLeaflet({
leaflet(data = nc) %>%
addPolygons(layerId = ~CNTY_ID)
})
# click event
observeEvent(input$mymap_shape_click, {
# click event
click <- input$mymap_shape_click$id
print(click) # this returns NULL if a polygone is clicked for the second time
# change clicked polygone
selection <- nc %>% filter(CNTY_ID == click)
leafletProxy("mymap") %>% addPolygons(data = selection, color = 'red')
})
}
shinyApp(ui, server)
Best Answer
The problem is caused because you are drawing a new version of the selected polygon when the click event happens. Then, when you think you are clicking on the original polygon for the second time you're actually clicking on the newly drawn version of the polygon. This polygon does not have the layerId information like the original layer which is why you get a NULL from the input$mymap_shape_click$id when you click for the second time.
To solve this you could assign layerId when you addPolygons within the leaflet proxy so the layer ID for the selected polygon is picked up on the second mouse click.
Alternatively, I've also had success with creating a map pane for the new, selected polygon and making it unclickable. The added benefit is you can use a zIndex which will ensure your new polygon draws above the original ones.