Search code examples
rr-leaflet

Designing hover text for leaflet with HTML - how to insert break for each comma


I'm using leaflet to map observations. I'm also using htmltools to format the hover text that shows variables of each observation.

The problem is, I want the variable hobbies which contains many strings to show on each line. each hobby is separated by a comma.

Installing and loading required packages:

install.packages("leaflet")
library(leaflet)
install.packages("htmltools")
library(htmltools)

Creating dummy observations:

name <- c("john", "mary")
age <- c(20, 29)
gender <- c("male", "female")
hobbies <- c("fishing, football, video games", "painting, skiing, body pump, data science")
lat <- c(-12.80103, -12.37845)
long <- c(130.9558, 130.8770)

df <- as.data.frame(cbind(name, age, gender, hobbies, lat, long))

Creating map using leaflet:

# Designing hover text with HTML
# lapply here necessary - my real data has much more than 2 rows#
labs <- lapply(seq(nrow(df)), function(i) {
  paste0( '<p>', "Name : ", df[i, "name"], '<p></p>', 
          "Age : ", df[i, "age"], ', ', 
          "Gender : ", df[i, "gender"],'</p><p>',
          "Hobbies : ", df[i, "hobbies"], ','
  )
})

leaflet(df) %>% 
  addProviderTiles("Esri.WorldImagery") %>% 
  addCircleMarkers(lng = ~ long, 
                   lat= ~ lat, 
                   label = lapply(labs, HTML),
                   clusterOptions = markerClusterOptions()
                   ) 

I get the below output :

my_ouput

I'm not familiar with html syntax. I can't figure out how to add break lines
for each hobby to show on a separate line with a tab as below:

Name : mary
Age : 29, Gender : female
Hobbies : painting
          skiing
          body pump
          data science

Solution

  • You can use gsub on the hobbies vector to replace each comma with a comma followed by a linebreak:

    hobbies <- c("fishing, football, video games", "painting, skiing, body pump, data science") %>%
      gsub(",", ",<br>", .)
    

    Then build your dataframe and generate your labels as normal.

    If you want the list of hobbies to be aligned with each other you can simple insert some html whitespace characters after the line break. I found four &emsp; + one &ensp; filled the right amount of space.

    hobbies <- c("fishing, football, video games", "painting, skiing, body pump, data science") %>%
      gsub(",", ",<br>&emsp;&emsp;&emsp;&emsp;&ensp;", .)
    

    Finally, note that in order to get your example to run I had to change df <- as.data.frame(cbind(name, age, gender, hobbies, lat, long)) to df <- data.frame(name, age, gender, hobbies, lat, long) , because the code you provided was converting your coordinates to factors which caused leaflet to throw an error. I assume this is just a bug with the way you put this example together and not your real data.