Clickable url link in mapview visualization

I have a large simple features dataset. The data has a column "url_1" containing the web address specific to each location. I would like to create a map from the sf object with a popup referencing the url for each location. I have succeeded in creating the link individually specifying each popup with coords and a url. While this works for 3 records, it is not realistic for my data. I'd appreciate any assistance.

Thanks

# Popup link reprex

library(dplyr)
library(sf)

# Create tibble
dat <- tibble(site = c("loc_1", "loc_2", "loc_3"),
              url_1 = c("https://forum.posit.co/", 
                        "https://cran.r-project.org/", 
                        "https://rstudio.github.io/leaflet/"),
              coord_x = c(1, 4, 8),
              coord_y = c(3, 2, 6))

# Convert to sf
dat_sf <- st_as_sf(dat, coords = c("coord_x", "coord_y"))

# Create map with clickable link.  This fails with error
mapview::mapview(dat_sf, popup = url)

# Create map with clickable link.  This works but creates a single link for all records.
# I could specify coords and url for each record in popup argument (not efficient)
mapview::mapview(dat_sf, popup = '<a href = "https://rstudio.github.io/leaflet/"> Leaflet </a>')

This is actually a pretty common use case, and a while back I wrote a blogpost about this (and other leaflet.js tricks in R). You might find it interesting - Leaflet in R · Jindra Lacko

But in case you are just after the TLDR solution: consider the following code

  • it first creates a valid HTML column based on your URL
  • then it uses this HTML for popup while constructing the marker

I hope this helps...

library(dplyr)
library(sf)

# Create tibble
dat <- tibble(site = c("loc_1", "loc_2", "loc_3"),
              url_1 = c("https://forum.posit.co/", 
                        "https://cran.r-project.org/", 
                        "https://rstudio.github.io/leaflet/"),
              coord_x = c(1, 4, 8),
              coord_y = c(3, 2, 6))

# Convert to sf
dat_sf <- st_as_sf(dat, coords = c("coord_x", "coord_y"))

# turn the url to HTML anchor tag
dat_sf <- dat_sf %>% 
   mutate(tag = paste0("lookie: <a href=", url_1,">", url_1, "</a>"))
   
# draw the map using {leaflet}
library(leaflet)

leaflet(dat_sf) %>% 
   addProviderTiles("CartoDB.Positron") %>% # or some other...
   addCircleMarkers(popup = ~tag, # note the tilde notation!
                    opacity = .75,
                    stroke = NA)

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.