Add different legends in different layers on leaflet map in R
<pre><code>library(leaflet)
library(htmltools)
library(htmlwidgets)
library(dplyr)
#
df1 &lt;- data.frame(points=c("p1", "p2"), lat=c(49.47259, 49.48095), long=c(-103.7054, -103.6126), value=c(50.34, 100.25))
df2 &lt;- data.frame(points=c("p1", "p2"), lat=c(49.47809, 49.66849), long=c(-103.5614, -103.0224), value=c(300.56, 505.34))
#
pal1 &lt;- colorNumeric(
palette = "PRGn",
domain = df1$value
)
#
pal2 &lt;- colorNumeric(
palette = "PRGn",
domain = df2$value
)
#
n &lt;- leaflet() %&gt;% addTiles(group="1st layer") %&gt;% addTiles(group="2nd layer") %&gt;%
addCircles(data=df1, lng=~long, lat=~lat, weight = 3, radius=250, color = ~pal1(value),
         stroke = TRUE, fillOpacity = 0.8,group="1st layer") %&gt;%
addCircles(data=df2, lng=~long, lat=~lat, weight = 3, radius=250, color = ~pal2(value),
         stroke = TRUE, fillOpacity = 0.8,group="2nd layer") %&gt;%
addLegend("bottomright", pal = pal1, values = df1$value, title = "legend_df1") %&gt;%
addLegend("topright", pal = pal2, values = df2$value, title = "legend_df2") %&gt;%
addLayersControl(baseGroups=c("1st layer","2nd layer"),
               options=layersControlOptions(collapsed = F))
n
</code></pre>

<p>I want that when I click on "1st layer" then only "legend_df1" will appear and when I click on "2nd layer" then only "legend_df2" will appear and "legend_df1" will be vanished. Therefore, in each layer different legends will appear, not both legends together. Can anybody please help me out?</p>