Search code examples
rshinyobserversr-leaflettmap

Use clickEvents in shiny with tmap


You can use clickEvents for the tmap package in shiny as in this example for leaflet in shiny.

However, I don't know how to acces the click events. On each click an Id is given, but where is this id linked to?

See the below example where the click events are printed on the console.

library(shiny)
library(tmap)
tmap_mode("view")
data("NLD_muni")

# User interface
ui <- fluidPage(
        mainPanel(
            leafletOutput("map")
        )
)

# Sever
server <- function(input, output) {

    # define map
    output$map <- renderLeaflet(
        tmap_leaflet(
            tm_shape(NLD_muni) +
                tm_polygons('pop_65plus') 
        )
    )


    # reactive values for map
    rv_map <-reactiveValues(Clicks=list())

    observeEvent(input$map_shape_click, {
        click <- input$map_shape_click
        print(str(click))
        rv_map$Clicks<-c(rv_map$Clicks, click$id)
        print(rv_map$Clicks)
    }) #END OBSERVE EVENT


}

# Run the application 
shinyApp(ui = ui, server = server)

Solution

  • The id is linked to the first column in the attached data of the leaflet object if there is no layerId given.

    So the solution is to make make the first column an id column or specify an layerId in the shape plotting function