问题描述
我需要为地图上的每个现有标记添加标签(而不是弹出框)。我创建了 labelText
变量来存储标签的 HTML。现在,当我使用它时,奇怪的事情发生了 - 每个标签显示来自整个数据集的数据,而不是分配给单个点的数据:
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,"<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)
我尝试了 HTML
和 htmlEscape
(或没有)的不同组合,但它仍然无法正常工作。您可以取消注释 label
的代码并测试它是如何工作的。我需要的是带有每个单独标记数据的 html 样式标签。
解决方法
如果您将 lapply
函数HTML
labeltext
向量:
leaflet::addCircleMarkers(
data = coords,stroke = FALSE,radius = 6,label = lapply(labelText,htmltools::HTML)
)