0

Recently I have been working with the package 'leaflet' in R. I have already created my interactive map and so on, but I would prefer to style it up a bit. My program recieves a list of Cities inputted by the user whose names I store in a dataframe. My goal is to have the first image that comes up in Google search while looking for every city as the marker's pop-up. I would really appreciate if someone could help me out.

mapa<- leaflet() %>% 
        addTiles() %>%
        addMarkers(data=df,lat=~Latitudes,lng=~Longitudes, label=~Nombres)
      mapa <- setView(mapa,lat  = 40.416775, lng = -3.703790, zoom = 5)
      mapa <-  addProviderTiles(mapa,providers$Esri.NatGeoWorldMap)

Thanks

2
  • Please provide enough code so others can better understand or reproduce the problem.
    – Community Bot
    Commented Oct 3, 2023 at 14:58
  • Yoy need to do a little webscraping first library(rvest) and then loop over the results to put image links in your popup.
    – G. Cocca
    Commented Oct 10, 2023 at 8:14

1 Answer 1

0
library(leaflet)
library(rvest)

df <- read.table(text=c("Tokyo;35.6839;139.7744",
                    "New York;40.6943;-73.9249",
                    "Mexico City;19.4333;-99.1333",
                    "Mumbai;18.9667;72.8333",
                    "São Paulo;-23.5504;-46.6339"),
             sep = ";",
             col.names = c("Nombres", "Latitudes", "Longitudes"),
             stringsAsFactors = FALSE)

df$Nombres_html <- sub(" ", "+", df$Nombres)

mypages <- paste0("https://www.google.com/search?q=", 
              df$Nombres_html, 
              "&sca_esv=571963393&hl=en&tbm=isch&source=hp&biw=1530&bih=746")

page <- lapply(mypages, read_html)

node2 <- lapply(page, function(x) {
                  html_nodes(x, xpath = '//img')
})


mapa <- leaflet(options = leafletOptions(zoomSnap = 0.25)) %>% 
        addTiles() 

  for (i in 1:length(node2)) {

  mapa <- mapa %>%

  addCircleMarkers(data=df,
                   lat=df$Latitudes[i],
                   lng=df$Longitudes[i], 
                   label=df$Nombres[i],
                   popup = paste0("<style> div.leaflet-popup-content {width:auto !important;}</style>",
                        node2[[i]][2], 
                        "<br>", paste('<a href =', mypages[i], '>', df$Nombres[i], '</a>'))
         )
  }

mapa

Not the answer you're looking for? Browse other questions tagged or ask your own question.