Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add title to layers control box in Leaflet using R

Tags:

r

leaflet

I am looking to add a title to the layer control box along the lines of "Available layers".

My search has lead me to only one relevant result:

  • Exact same question using JS. Unclear how to translate

My code:

map %>% leaflet() %>%
  addProviderTiles(provider = "CartoDB") %>%
  # Group 1 Polygons
  addPolygons(data = map[!is.na(map$var),] ,weight =1, 
              color = ~g1_pal(g1), fillOpacity = .6,
              group = "Group 1",
              # add labels
              label = ~labels,
              # highlight polygons on hover
              highlight = highlightOptions(weight = 5, color = "white",
                                           bringToFront = TRUE)) %>%
  # Group 2
  addPolygons(data = map[!is.na(map$var2),], weight =1, 
              color = ~g2_pal(g2), fillOpacity = .6,
              group = "Group 2",
              # add labels that display mean income
              label = ~labels2,
              # highlight polygons on hover
              highlight = highlightOptions(weight = 5, color = "white",
                                           bringToFront = TRUE)) %>%
  addLayersControl(baseGroups = c("Group 1", "Group 2"), 
                   options = layersControlOptions(collapsed=F, 
                                                  # Series of attempts 
                                                  label = "Layers",
                                                  title = "Layers"))

Neither of these attempts worked. It does appear from the link above that there is an attribute that can be accessed but I am unsure of how to reference it.

like image 245
MokeEire Avatar asked Sep 19 '18 19:09

MokeEire


1 Answers

The best way to do this (that I'm aware of) is to use htmlwidgets::onRender to add your Javascript to the map upon rendering. This is described in the last section at the bottom of the last page in the docs, so it's easy to miss!

Here's an example that implements the Javascript that Saurabh Yadav described in his answer to the question you linked. You simply add the Javascript function to the end of the leaflet() piped call:

library(leaflet)

leaflet() %>%
    addTiles() %>%
    addLayersControl(
        overlayGroups = "MyImaginaryLine",
        options = layersControlOptions(collapsed = FALSE)) %>%
    htmlwidgets::onRender("
        function() {
            $('.leaflet-control-layers-overlays').prepend('<label style=\"text-align:center\">My Epic Title</label>');
        }
    ")

output

like image 178
heds1 Avatar answered Nov 16 '22 19:11

heds1