3

所有善良的灵魂,需要帮助。我正在创建一张传单地图,但无法解决一个奇怪的标签问题。我创建了带有少量变量的标签,如果第一个变量是数字,则标签呈现正常,但如果第一个变量是字符串,它们会失败 - 知道有什么问题吗?让我们从一个虚拟 spdf 开始:

library(htmltools)
library(sp)
library(leaflet)

df <- new("SpatialPointsDataFrame", data = structure(list(PMID = c(184397, 184397), SPACEID = c("184397_1", "184397_2")), .Names = c("PMID", "SPACEID"), row.names = 1:2, class = "data.frame"), coords.nrs = numeric(0), coords = structure(c(-0.14463936, -0.14468822, 51.50726534, 51.50730171), .Dim = c(2L, 2L), .Dimnames = list(c("1", "2"), c("x", "y"))), bbox = structure(c(-0.14468822, 51.50726534, -0.14463936, 51.50730171), .Dim = c(2L, 2L), .Dimnames = list(c("x", "y"), c("min", "max"))), proj4string = new("CRS", projargs = "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))

现在我们(m)应用一个简单的 HTML 行(原来使用 df 行但它不是必需的,可以简化为

df@data$HT<-mapply(function(x,y){htmltools::HTML(sprintf("<h2>%s</h2> %s",x,y))},1,"L", SIMPLIFY = F) 

这个可以正常工作。但是如果顺序颠倒了——而不是 (1,"L") 我们改为 ("L",1)——它会失败:

df@data$HT<-mapply(function(x,y){htmltools::HTML(sprintf("<h2>%s</h2> %s",x,y))},"L",1, SIMPLIFY = F) 

在第一种情况下,地图包含正确的标签,在另一种情况下,它产生空标签

leaflet() %>%
addTiles() %>%
addMarkers(data = df, label = ~ HT)

如果我使用label = ~as.character(HT)它,它会产生一个逐字的 HTML 标签,而不是标签。它出什么问题了?

4

1 回答 1

4

After playing around the code, I found that replacing mapply() with map2() in the purrr package does the trick here. I am not totally sure why this is the case. Both Slav and I confirmed that this solution is working on our machines.

library(sp)
library(leaflet)
library(htmltools)
library(purrr)

df@data$HT1 <- map2(1, "L", ~htmltools::HTML(sprintf("<h2>%s</h2> %s",.x,.y))) 
df@data$HT2 <- map2("L", 1, ~htmltools::HTML(sprintf("<h2>%s</h2> %s",.x,.y))) 

leaflet()%>%
addProviderTiles("OpenStreetMap.Mapnik") %>%
addLabelOnlyMarkers(data = df, label = ~HT2, 
                    labelOptions = labelOptions(noHide = TRUE, direction = 'center',
                                                textOnly = FALSE, textsize = "15px"))

enter image description here enter image description here

于 2018-01-19T12:15:06.727 回答