【问题标题】:Add title to layers control box in Leaflet using R使用 R 向 Leaflet 中的图层控制框添加标题
【发布时间】:2018-09-19 19:59:29
【问题描述】:

我希望按照“可用图层”的行向图层控制框添加标题。

我的搜索只找到了一个相关结果:

我的代码:

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"))

这些尝试都没有奏效。从上面的链接中确实可以看到有一个可以访问的属性,但我不确定如何引用它。

【问题讨论】:

    标签: r leaflet


    【解决方案1】:

    最好的方法(据我所知)是使用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>');
            }
        ")
    

    【讨论】:

    • 对于基本组,您需要 .leaflet-control-layers-list 而不是 .leaflet-control-layers-overlays
    猜你喜欢
    • 2018-04-23
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    相关资源
    最近更新 更多