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)