leaflet with R: add text labels

22,497

Solution 1

UPDATE

When this answer was posted, I think addLabelOnlyMarkers() was not officially included in the CRAN version. As of the 8th of January, 2018, leaflet is in version 1.1.0 on CRAN. This version has the function. No need to download a github version.

ORIGINAL ANSWER

If you have your leaflet package installed from GitHub, you can do

leaflet(data = quakes[1:20,]) %>% addTiles() %>%
  addLabelOnlyMarkers(~long, ~lat, label =  ~as.character(mag), 
                      labelOptions = labelOptions(noHide = T, direction = 'top', textOnly = T))

enter image description here


The addPopups function might be a valuable workaround if you don't want to work with the package version from GitHub. (This was the case before the official release of addLabelOnlyMarkers() in the CRAN version.)

leaflet(data = quakes[1:20,]) %>% addTiles() %>%
        addPopups(~long, ~lat, ~as.character(mag), 
        options = popupOptions(minWidth = 20, closeOnClick = FALSE, closeButton = FALSE))

Solution 2

You can add static/hover labels to markers

https://github.com/rstudio/leaflet/blob/master/inst/examples/labels.R

Demo http://rpubs.com/bhaskarvk/leaflet-awesome-markers http://rpubs.com/bhaskarvk/leaflet-label

Share:
22,497

Related videos on Youtube

luciano
Author by

luciano

Updated on July 19, 2022

Comments

  • luciano
    luciano almost 2 years

    This code is taken from this page:

    library(leaflet)
    leaflet(data = quakes[1:20,]) %>% addTiles() %>%
      addMarkers(~long, ~lat, popup = ~as.character(mag))
    

    Instead of markers, is there any way to plot mag as text labels?

  • Christophe D.
    Christophe D. over 8 years
    Hi, i tried to make your example but all the label options doesent work for me. Any idea ? unused argument (label = htmltools::HTML("<em>I'm a HTML Label</em>"))
  • Admin
    Admin over 8 years
    @ChristopheD. You need to build the Leaflet package from the Master Branch, the changes are not yet pushed to CRAN.
  • Christophe D.
    Christophe D. over 8 years
    Ok ! Thanks @Bhaskar Karambelkar.
  • sconfluentus
    sconfluentus over 7 years
    I have constructed from the Master and still get that error. It is confounding.
  • elevendollar
    elevendollar over 7 years
    Works well. But needs to be installed from GitHub, not from CRAN. Find out how to install it from GitHub here: github.com/rstudio/leaflet
  • geneorama
    geneorama over 7 years
    @elevendollar this should be a part of the answer. Why is "label" missing from the main package I wonder? I installed leaflet so long ago, I forgot that I installed from github.
  • Mathias711
    Mathias711 over 7 years
    Do you know if there is by now a new solution for 'non-Github' users? Your addPopups solution is working, but it is not very graphical attractive.