3

I need to add labels (not poups) to each existing marker on the map. I created labelText variable which stores HTML for a label. And now, when I'm using it with then strange thing happen - each label shows data from the whole dataset, not data assigned to individual point:

library(shiny)
library(leaflet)
library(dplyr)
library(sf)

ui <- fluidPage(
    leafletOutput("map")

)

server <- function(input, output, session) {
    
    coords <- quakes %>%
        sf::st_as_sf(coords = c("long","lat"), crs = 4326)
    
    labelText <- paste0("<b>Depth: </b>",coords$depth,"<br/>",
                                         "<b>Mag: </b>",coords$mag,"<br/>",
                                         "<b>Stations: </b>",coords$stations)    

    output$map <- leaflet::renderLeaflet({
    leaflet::leaflet() %>% 
      leaflet::addTiles() %>% 
      leaflet::setView(172.972965,-35.377261, zoom = 4) %>%
      
      leaflet::addCircleMarkers(
        data = coords,
        stroke = FALSE,
        radius = 6,
        label = ~htmltools::HTML(labelText)
        #label = ~htmltools::htmlEscape(labelText)
        #label = ~labelText
      )      
  })
}

shinyApp(ui, server)

I tried different combinations of HTML and htmlEscape (or none of them) but it still doesn't work as it should. You can uncomment code for label and test how it works. What I need is html styled label with data for each individual marker.

mustafa00
  • 751
  • 1
  • 7
  • 28

1 Answers1

6

It works fine if you lapply the HTML function to the labeltext vector:

leaflet::addCircleMarkers(
        data = coords,
        stroke = FALSE,
        radius = 6,
        label = lapply(labelText, htmltools::HTML)
      )
HubertL
  • 19,246
  • 3
  • 32
  • 51