Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying Leaflet Popups in R

I want to modify the appearance of leaflet popups in R.

The helpfile states that ... in the popupOptions() function takes "extra options passed to underlying Javascript object constructor."

In this example, the style option is set to a list of CSS parameters that modify the appearance of markers:

  addMarkers(
    lng = -118.456554, lat = 34.075,
    label = "Label w/ custom CSS style",
    labelOptions = labelOptions(noHide = T, direction = "bottom",
      style = list(
        "color" = "red",
        "font-family" = "serif",
        "font-style" = "italic",
        "box-shadow" = "3px 3px rgba(0,0,0,0.25)",
        "font-size" = "12px",
        "border-color" = "rgba(0,0,0,0.5)"
      )))

However, the same approach does not seem to work with Popups, as this minimal working example demonstrates:

if (!require("pacman")) install.packages("pacman")
pacman::p_load(leaflet, eurostat, dplyr)

map <- get_eurostat_geospatial() %>% subset(., .$NUTS_ID == "AT11")

leaflet() %>%

  addPolygons(data = map , 
              group = map$NUTS_ID,
              fillColor = "grey",
              weight = 1,
              color = "black") %>%

  addPopups(lng = 16.3, lat = 47, popup = "Paint it black!",
            options = popupOptions(closeButton = FALSE,
                                   opacity = 0.5,
                                   style = list("background" = "black",
                                                "padding" = "2px",
                                                "border-radius" = "0px")))

Some webpages explain the customization of the labels with CSS using the javascript version of Leaflet (e.g. here). The key seems to be to edit .leaflet-popup-tip and .leaflet-popup-content-wrapper. But how can I do this in R (not using Shiny)?

Related: this question, which however only addresses modifying elements within a popup and not popups themselves.

I welcome any suggestions.

like image 281
mzuba Avatar asked Jan 29 '23 21:01

mzuba


1 Answers

Maybe you could use the package htmltools to get what you want.

map2 <- leaflet() %>%
    addPolygons(data = map , 
                group = map$NUTS_ID,
                fillColor = "grey",
                weight = 1,
                color = "black") %>%
    addPopups(lng = 16.3, lat = 47, popup = "Paint it black!")

library(htmltools)
browsable(
  tagList(list(
    tags$head(
      tags$style(
        ".leaflet-popup-content-wrapper {
    background: black;
    color: #ffffff;
    padding: 2px;
border-radius: 0px;
    }
        "
      )
    ),
    map2
  ))
)
like image 187
MLavoie Avatar answered Jan 31 '23 23:01

MLavoie