Created
August 13, 2021 20:22
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
Author
noamross
commented
Aug 13, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment