使用R

时间:2018-09-19 19:59:30

标签: r leaflet

我希望沿着“可用图层”的行添加一个标题到图层控制框。

我的搜索仅使我得到一个相关结果:

我的代码:

map %>% leaflet() %>%
  addProviderTiles(provider = "CartoDB") %>%
  # Group 1 Polygons
  addPolygons(data = map[!is.na(map$var),] ,weight =1, 
              color = ~g1_pal(g1), fillOpacity = .6,
              group = "Group 1",
              # add labels
              label = ~labels,
              # highlight polygons on hover
              highlight = highlightOptions(weight = 5, color = "white",
                                           bringToFront = TRUE)) %>%
  # Group 2
  addPolygons(data = map[!is.na(map$var2),], weight =1, 
              color = ~g2_pal(g2), fillOpacity = .6,
              group = "Group 2",
              # add labels that display mean income
              label = ~labels2,
              # highlight polygons on hover
              highlight = highlightOptions(weight = 5, color = "white",
                                           bringToFront = TRUE)) %>%
  addLayersControl(baseGroups = c("Group 1", "Group 2"), 
                   options = layersControlOptions(collapsed=F, 
                                                  # Series of attempts 
                                                  label = "Layers",
                                                  title = "Layers"))

这些尝试均无效。从上面的链接看来,确实存在可以访问的属性,但是我不确定如何引用它。

1 个答案:

答案 0 :(得分:2)

(我知道)执行此操作的最佳方法是使用htmlwidgets::onRender在渲染时将Javascript添加到地图中。 last section at the bottom of the last page in the docs中对此进行了描述,因此很容易错过!

下面是一个示例,该示例实现了Saurabh Yadav在对question you linked的答复中描述的Javascript。您只需将Javascript函数添加到leaflet()管道调用的末尾:

library(leaflet)

leaflet() %>%
    addTiles() %>%
    addLayersControl(
        overlayGroups = "MyImaginaryLine",
        options = layersControlOptions(collapsed = FALSE)) %>%
    htmlwidgets::onRender("
        function() {
            $('.leaflet-control-layers-overlays').prepend('<label style=\"text-align:center\">My Epic Title</label>');
        }
    ")

output