18

I'd like to add a title to the whole map (different from the legend title: addLegend(..., title = "", ...): by "title", I mean an overlaid map component that stays in place while the map is moved (unlike an overlaid image)what the map title could look like.

Is that an option in RStudio's leaflet for R?

leafletR has a title="" argument but it updates the title of the webpage: it does not add a title to the map.

MLavoie
  • 9,671
  • 41
  • 36
  • 56
YGS
  • 623
  • 1
  • 6
  • 16

2 Answers2

21

@MLavoie's idea is correct, but I was looking for something more specific like this:

tag.map.title <- tags$style(HTML("
  .leaflet-control.map-title { 
    transform: translate(-50%,20%);
    position: fixed !important;
    left: 50%;
    text-align: center;
    padding-left: 10px; 
    padding-right: 10px; 
    background: rgba(255,255,255,0.75);
    font-weight: bold;
    font-size: 28px;
  }
"))

title <- tags$div(
  tag.map.title, HTML("Map title")
)  

map_leaflet <- leaflet() %>%
  addTiles() %>%
  addControl(title, position = "topleft", className="map-title")

This will center the leaflet-control title as shown in the screenshot and place it at the top.

prusswan
  • 6,853
  • 4
  • 40
  • 61
  • 1
    hi Prusswan, this is very clean but I'm a bit of a newbie and need a reprex to understand what's happening here. Could you provide one please? I just don't know what the `tags` variable is or how that works in the flow of an R script. – Adhi R. Apr 15 '20 at 02:04
  • 1
    @AdhiR. the only bit missing here for reproducibility is the attaching of leaflet and htmltools. `tags` is from htmltools and is a list of functions for constructing HTML. eg `htmltools::tags$h1("header!")`. The code above creates a DIV with STYLE and content for the text label. – Spacedman Jul 02 '20 at 07:36
  • This method does work but when you knit an html document, the title actually stays in the middle of the html page and does not stick with the leaflet map, and as you scroll down the page, the title gets dragged along too. – Ed_Gravy Sep 29 '21 at 19:18
18

You should provide a reproducible example. But using addControl you could try:

 library(leaflet)
 library(htmlwidgets)
 library(htmltools)

 rr <- tags$div(
   HTML('<a href="https://cran.r-project.org/"> <img border="0" alt="ImageTitle" src="/PathToImage/ImageR.jpeg" width="300" height="100"> </a>')
 )  

 map_leaflet <- leaflet() %>%
   addTiles() %>%
   addMarkers(50, 50) %>%
   addControl(rr, position = "bottomleft")

 saveWidget(map_leaflet, file="testing.html")

Open testing.html saved in your working directory and you will see an image (just create an image with Map Title in it) over your map. It is not center you can only put the control on the four corners. Hope it helps!

MLavoie
  • 9,671
  • 41
  • 36
  • 56