MokeEire
MokeEire

Reputation: 698

Add title to layers control box in Leaflet using R

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:

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.

Upvotes: 12

Views: 2950

Answers (1)

heds1
heds1

Reputation: 3438

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

Upvotes: 13

Related Questions