Search code examples
rshinyr-leaflet

Is it possible to add images to popups based on groups?


Currently, I have a shiny application that creates a leaflet map of species points. When you hover over a point, the species name is displayed both as a label and a popup.

leafletProxy("map", data = filteredData()) %>%
  clearMarkers() %>%
  addCircleMarkers(popup = ~as.character(species),
                   label = ~as.character(species), 
                   radius = 6,
                   stroke = TRUE,
                   weight = 1,
                   fillOpacity = 5,
                   fillColor = ~pal(species),
                   color = "black")

I have read up on how to add an image to a popup, but this would add the same image to all popups. What I would like to happen is once a point is clicked, a popup appears with the name of the species and a picture (either local file or web-linked, whichever is easiest)- So that each group (species) would have its own associated picture.

Is this possible?


Solution

  • Yes, if you want to each group to have its own image, you need to create a new column which contains URL to your image. And the important part is to use HTML img tag in popup.

    See demo below.

    data <- data.frame(
        lng = c(-1,0,1,2),
        lat = c(-1,0,1,2),
        label = c("p1","p2","p3","p4"),
        # some random images I picked up from google images
        # it can be both local or remote
        image_link = c(
            "https://jessehouwing.net/content/images/size/w2000/2018/07/stackoverflow-1.png",
            "https://store-images.s-microsoft.com/image/apps.18496.14408192455588579.aafb3426-654c-4eb2-b7f4-43639bdd3d75.2c522ca4-9686-4ee2-a4ac-cdbfaf92c618?mode=scale&q=90&h=1080&w=1920",
            "https://mk0jobadderjftub56m0.kinstacdn.com/wp-content/uploads/stackoverflow.com-300.jpg",
            # row number 4 use the same link as row number 1
            "https://mk0jobadderjftub56m0.kinstacdn.com/wp-content/uploads/stackoverflow.com-300.jpg"
        )
    )
    
    
    library(leaflet)
    
    leaflet(data = data) %>%
        addTiles() %>%
        addCircleMarkers(
            lng = ~lng,
            lat = ~lat,
            popup = ~paste0(
                "<img src='",image_link,"' width='50px' height='50px'>"
            )
        )