Search code examples
rtextpopuphover

Combining Several Popups Together


I am following this R tutorial here (https://cengel.github.io/R-spatial/mapping.html). This tutorial shows you how to make an interactive map with popup text:

# start with file: philly_WGS84

p_popup <- paste0("<strong>Homicide Density: </strong>", philly_WGS84$homic_rate)

leaflet(philly_WGS84) %>%
  addPolygons(
    stroke = FALSE, 
    fillColor = ~pal_fun(homic_rate),
    fillOpacity = 0.8, smoothFactor = 0.5,
    popup = p_popup) %>%
  addTiles() %>%
  addLegend("bottomright", 
            colors = brewer.pal(7, "YlOrRd"), 
            labels = paste0("up to ", format(breaks_qt$brks[-1], digits = 2)),
            title =  'Philadelphia homicide density per sqkm')

Is there a straightforward way of adding multiple popups to this map? For example - suppose I wanted these 3 popups (e.g. imagine that the file "p_popup_1" had columns var_1, var_2, var_3) :

p_popup_1 <- paste0("<strong> Text 1: </strong>", philly_WGS84$var_1)
p_popup_2 <- paste0("<strong> Text 2: </strong>", philly_WGS84$var_2)
p_popup_3 <- paste0("<strong> Text 3: </strong>", philly_WGS84$var_3)

combined_popup <- c(p_popup_1, p_popup_2, p_popup_3)

Could I then somehow add this "combined_popup" to the map?

leaflet(philly_WGS84) %>%
  addPolygons(
    stroke = FALSE, 
    fillColor = ~pal_fun(homic_rate),
    fillOpacity = 0.8, smoothFactor = 0.5,
    popup = combined_popup) %>%
  addTiles() %>%
  addLegend("bottomright", 
            colors = brewer.pal(7, "YlOrRd"), 
            labels = paste0("up to ", format(breaks_qt$brks[-1], digits = 2)),
            title =  'Philadelphia homicide density per sqkm')

Is this possible in R?

Thank you!


Solution

  • It sounds like you want to display multiple columns in your popup (3 columns in this case). If true, you can include HTML breaks <br> in your character vector to separate each label and value you'd like to include.

    For example:

    p_popup <- paste0("<strong>Homicide Density: </strong>", philly_WGS84$homic_rate,
                      "<br><strong>Tract Area: </strong>", philly_WGS84$tract_area,
                      "<br><strong>N Homicides: </strong>", philly_WGS84$n_homic)
    

    Then p_popup in addPolygons should include the 3 column values in a single popup.