Search code examples
rshinyr-leaflet

Way to add hyperlink to Leaflet popup in Shiny


Using leaflet in shiny to make an interactive map. Pulling data for popups from a CSV:

Row on CSV:
Name    lat          lng
Tufts   42.349598   -71.063541

Code on R for markers:

m %>% addMarkers(~lng, ~lat, icon = custommarker1 popup = ~htmlEscape(Name))

This returns marker in correct spot with popup displaying 'tufts'

Wondering if there is a way to encode a hyperlink into the popup directly in the CSV? Or to put plain text as a new CSV column and have R/Shiny then turn it into a hyperlink.


Solution

  • Just include the link in the popup as html:

    output$mymap <- renderLeaflet({
    m <- leaflet() %>%
      addTiles() %>%  # Add default OpenStreetMap map tiles
      addMarkers(lng=174.768, lat=-36.852, popup= '<a href = "https://rstudio.github.io/leaflet/"> R </a>')
    m  # Print the map
    })
    

    You can set the popup equal to a column in your dataframe as well. If your dataframe was called df and it contained longitude = long, latitude= lat, and urls = link :

    output$mymap <- renderLeaflet({
    m <- leaflet() %>%
    addTiles() %>%  # Add default OpenStreetMap map tiles
    addMarkers(lng=df$long, lat=df$lat, popup= df$link)
    m  # Print the map
    

    })