leaflet with R: add text labels
Asked Answered
N

2

20

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?

Natch answered 31/7, 2015 at 11:51 Comment(0)
S
29

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))
Speciosity answered 31/7, 2015 at 12:20 Comment(1)
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.Stainless
T
5

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

Trunks answered 15/12, 2015 at 17:27 Comment(6)
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>"))Chutney
@ChristopheD. You need to build the Leaflet package from the Master Branch, the changes are not yet pushed to CRAN.Trunks
Ok ! Thanks @Bhaskar Karambelkar.Chutney
I have constructed from the Master and still get that error. It is confounding.Justifier
Works well. But needs to be installed from GitHub, not from CRAN. Find out how to install it from GitHub here: github.com/rstudio/leafletInimical
@Inimical 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.Toolis

© 2022 - 2024 — McMap. All rights reserved.