使用R将标题添加到Leaflet中的图层控制框 [英] Add title to layers control box in Leaflet using R

查看:29
本文介绍了使用R将标题添加到Leaflet中的图层控制框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

  • I am looking to add a title to the layer control box along the lines of "Available layers".

    My search has lead me to only one relevant result:

    My code:

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

    Neither of these attempts worked. It does appear from the link above that there is an attribute that can be accessed but I am unsure of how to reference it.

    解决方案

    The best way to do this (that I'm aware of) is to use htmlwidgets::onRender to add your Javascript to the map upon rendering. This is described in the last section at the bottom of the last page in the docs, so it's easy to miss!

    Here's an example that implements the Javascript that Saurabh Yadav described in his answer to the question you linked. You simply add the Javascript function to the end of the leaflet() piped call:

    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>');
            }
        ")
    

    这篇关于使用R将标题添加到Leaflet中的图层控制框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆