Home > Mobile >  Adding images to maps with Leafpop
Adding images to maps with Leafpop

Time:10-21

I'm trying to add separate images to popups so that as you click on each location, an image specific to that place/popup appears. I've figured out how to get one image in, but it applies to all of the popups on the map instead of just one. I have been trying to use the package leafpop for this, but I can't really figure out how to make it work. Even if I just use one image, nothing appears on the map.

This is what my code looks like for it:

library(leaflet)
library(leafpop)

img = system.file("file/image_name.jpg", package = "jpg")

leaflet(map) %>% 
  addTiles() %>%
  addCircleMarkers(label = map@data$name,
                   weight = 2,
                   color = "grey",
                   fillColor = "red",
                   fillOpacity = 0.7)%>%
addPopupImages(img, group = "map")

I know there's some bits in there that I'm not quite doing right. At this point, I just want to know if it's even possible to do this the way I'm envisioning. Any help is appreciated.

CodePudding user response:

The images need to be in a vector of the same length as the points passed to leaflet. Here is a reproducible example you can copy paste that will get you started:

library(tidyverse)
library(sf)
library(leaflet)
library(leafpop)

pts <- tibble(x = runif(10, 175, 176), 
              y = runif(10, -38, -37)) %>% 
  st_as_sf(coords = c("x", "y"), crs = 4326)

img <- glue::glue("https://github.com/IQAndreas/sample-images/blob/gh-pages/100-100-color/{11:20}.jpg?raw=true")

pts$img <- img

leaflet() %>%
  addTiles() %>%
  addCircleMarkers(data = pts, group = "pts") %>%
  addPopupImages(pts$img, group = "pts")

CodePudding user response:

Figured it out, with the help of Rich Pauloo! This is the code I ended up using the get local image files. It's a little clunky, but it worked out for me:

data_name <- readOGR("data/map_file.kml")

data_name2 <- data.frame(data_name)

pts <- st_as_sf(data.frame(data_name2),
                coords = c("coords.x1", "coords.x2"), crs = 4326)

img <- c("images/picture_name.jpg") ##did this for every image I wanted to use, in the order 
##that matched up with the data points I wanted them associated with.

pts$img <- img

leaflet() %>%
  addTiles() %>%
  addCircleMarkers(data = pts, group = "pts") %>%
  addPopupImages(pts$img, group = "pts", width = 300)

Sorry if my conventions for writing out code are not quite right for the website. I just wanted to keep things generic and not include any of my file names or anything.

  • Related