rshinyleafletr-leaflet

Markers on map leaflet for shiny


Is there a way to set visible markers (plural) on a leaflet map, when a user clicks on this map in a shiny application? Furthermore, is it possible to retrieve the coordinates of this marker?

If not in shiny, can you do that in leaflet JS?


Solution

  • It is hard to be specific without any code, but here are the basics.

    1) Shiny/Leaflet lets you subscribe to events such as mouse click. If your map is called MyMap you would use the code:

    ClickVar<-input$MyMap_click  
    

    then ClickVar is a reactive variable - a list, that includes the lat, long and the layerId.

    Now that you have the lat and long you can use that to add your popup. Do all of this in an observerEvent like so:

    observeEvent( input$MyMap_click, {
        ClickVar<-input$MyMap_click
        addPopups(MyMap, lng=ClickVar$lng, lat=ClickVar$lat, popup="Here I am")
    })
    

    Note - I have not tested this so you may need to alter it slightly. You may also want to think about removing one popup when another is clicked, assigning them a layerID or group etc.