如何在Leaflet for R中基于addLayerControl()隐藏/切换图例 [英] How to hide/toggle legends based on addLayerControl() in Leaflet for R

查看:283
本文介绍了如何在Leaflet for R中基于addLayerControl()隐藏/切换图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在Leaflet for R中基于addLayerControl()隐藏/切换图例?切换选项层a时,addPolygons()不会显示选项层b的数据,因为我可以使用GROUP.但是,addLegend()选项不具有GROUP功能,因此当我选择组图层a(红色)时,我无法隐藏组图层b(蓝色)的图例:

I'm wondering how to hide/toggle legends based on addLayerControl() in Leaflet for R? When option layer a is toggled, then the data of option layer b is not showed by addPolygons() because I can use GROUP. However, the addLegend() option doesn't have the GROUP functionality so I'm not able to hide the legend of group layer b(blue) when I selected group layer a(red):

来源: https ://gis.stackexchange.com/questions/214773/how-to-hide-toggle-legends-with-layer-controls-in-leaflet-for-r

您知道如何执行此操作吗?

Do you have any idea how to do this?

此致

乔里斯

推荐答案

万一将来有人在关注这个问题,有一种新的可行方法.

In case anyone is looking at this in the future, there's a new viable method.

如果使用的是leaflet包的development/Github版本,则addLegend()现在支持grouplayerId参数.

If you're using the development/Github version of the leaflet package, addLegend() now supports the group and layerId arguments.

(运行命令devtools::install_github('rstudio/leaflet')进行安装)

即使最新的CRAN版本(1.1.0)也支持layerID.

Even the latest CRAN version (1.1.0) supports layerID.

假设您使用的是开发版本,则以下代码应该起作用:

Assuming you go with the development version, the following code should work:

leaflet() %>%
    #Polygon Layers
    addPolygons(data = exampleDataOne, group = "Group A") %>%
    addPolygons(data = exampleDataTwo, group = "Group B") %>%

    #Legend Layers
    addLegend(values = exampleValuesOne, group = "Group A", 
              position = "bottomright") %>%
    addLegend(values = exampleValuesTwo, group = "Group B",
              position = "bottomright") %>%

    #Layers Control
    addLayersControl(overlayGroups = c("Group A","Group B"),
              options = layersControlOptions(collapsed = FALSE))

这应该具有只在相应层处于活动状态时才显示图例的预期效果.

This should have the desired effect of only displaying a legend when the corresponding layer is active.

一个潜在的问题是,默认情况下,所有leaflet层均处于活动状态.如果您有重叠的多边形,则可能会导致地图的视觉吸引力降低.而且,如果您有多个图例,这也将是一个问题.

One potential issue is that by default, all leaflet layers are active. If you have overlapping polygons, this can lead to a less visually appealing map. And, if you have multiple legends, this will also be an issue.

您可以做的是使用hideGroup()功能.

What you can do is use the hideGroup() function.

如果您希望仅使上述示例中的Group A在启动时处于活动状态,则可以添加

If you wanted to have only Group A from the above example active at start, you could add

%>% hideGroup("Group B")

到上面代码块的末尾.

这篇关于如何在Leaflet for R中基于addLayerControl()隐藏/切换图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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