R-Shiny Leaflet Right-Click Context Menu

Viewed 242

I got a R-Shiny app and a leaflet map in my UI output. I want to setup something where I can right click on the map and it opens a context menu on cursor coordinates, where I can select icons and input text. This will allow me to place custom markers on the map and name them.

observeEvent(input$map_right_click, {
showCustomMarkerMenu(location = (input$map_click$lat, input$map_click$lng)) //sample
addMarkers(lat = input$map_click$lat, lng = input$map_click$lng)
})
1 Answers

You can achieve right clicks with htmlwidgets::onRender and Shiny.setInputValue. With htmlwidgets::onRender its possible to retrieve the leaflet map instance, which you need to get the coordinates of the click. Next with Shiny.setInputValue you send the coordinates to your shiny module or application and trigger a change event of the input which you observe with observeEvent.

leaflet::leaflet() %>% 
leaflet::addTiles() %>%
htmlwidgets::onRender("
    function(el,x) {
        map = this;
        map.on('contextmenu', function(e) {
        var coords = {lng: e.latlng.lng, lat: e.latlng.lat}
        Shiny.setInputValue('map_right_click', coords);
    });
    }
")

shiny::observeEvent(input$map_right_click, {
    output$myLng<- renderText({ input$map_right_click$lng })
})
Related