Skip to content

Instantly share code, notes, and snippets.

@noamross
Created August 13, 2021 20:22
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save noamross/98c2053d81085517e686407096ec0a69 to your computer and use it in GitHub Desktop.
Save noamross/98c2053d81085517e686407096ec0a69 to your computer and use it in GitHub Desktop.
A quick hack to have the legends associated with radio-button "Base Groups" in R leaflet maps toggle along with layers
library(leaflet)
library(tidyverse)
outline <- quakes[chull(quakes$long, quakes$lat),]
map <- leaflet(quakes) %>%
addTiles(group = "OSM (default)") %>%
# Overlay groups
addCircles(~long, ~lat, ~10^mag/5, stroke = F, group = "Quakes") %>%
addPolygons(data = outline, lng = ~long, lat = ~lat,
fill = F, weight = 2, color = "#FFFFCC", group = "Outline") %>%
addLayersControl(
baseGroups = c("Quakes", "Outline"),
options = layersControlOptions(collapsed = FALSE)
) %>%
addLegend("bottomright", colors = "green", labels = "1",
title = "Quakes Legend",
layerId="Quakes" # Give a LayerId the same as the layer group name
) %>%
addLegend("bottomright", colors = "yellow", labels = "1",
title = "Outline Legend",
layerId = "Outline" # Give a LayerId the same as the layer group name
) %>%
htmlwidgets::onRender("
function(el, x) {
var initialLegend = 'Outline' // Set the initial legend to be displayed by layerId
var myMap = this;
for (var legend in myMap.controls._controlsById) {
var el = myMap.controls.get(legend.toString())._container;
if(legend.toString() === initialLegend) {
el.style.display = 'block';
} else {
el.style.display = 'none';
};
};
myMap.on('baselayerchange',
function (layer) {
for (var legend in myMap.controls._controlsById) {
var el = myMap.controls.get(legend.toString())._container;
if(legend.toString() === layer.name) {
el.style.display = 'block';
} else {
el.style.display = 'none';
};
};
});
}")
map
@noamross
Copy link
Author

legend

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment