Mousehover over country in leaflet to see its name

Viewed 1462

I am creating a map of the world:

library(leaflet)
library(rnaturalearth)
countries <- rnaturalearth::countries110
mymap <- leaflet(countries)
mymap %>% addPolygons(stroke = FALSE, smoothFactor = 0.2, fillOpacity = 1)

Is it possible to either hover over any country to see its name or to click on any country to see its name?

Thanks a lot!

2 Answers

Or, even simpler:

library(leaflet)
library(rnaturalearth)

countries <- rnaturalearth::countries110
mymap <- leaflet(countries)
mymap %>% addPolygons(stroke = FALSE, smoothFactor = 0.2, 
                      fillOpacity = 1, label = ~name)

As long as the data for the labels is part of the data frame to be plotted the ~ notation works like a charm.

I figured out a solution. First, create a list of labels using library "htmltools" Then lapply it under label = . So, the final code is:

library(leaflet)
library(rnaturalearth)
library(htmltools)

countries <- rnaturalearth::countries110
mymap <- leaflet(countries)
labs <- as.list(countries$name)
mymap %>% addPolygons(stroke = FALSE, smoothFactor = 0.2, 
                      fillOpacity = 1, label = lapply(labs, HTML))
Related