Layer Control
We can add multiple layers to the leaflet in r map using addTiles() or addMarker() function. Now if we want to give the user a choice of which layer he/she wants to look at, we can do that by using layer control. Layers can be assigned to named groups. To name a group in the leaflet we add group argument to that layer. Now, these groups can be toggled on and off by the user. The Base Groups that form the basics of the map for example tiles are selected with radio buttons so that you can only choose one at a time, and the Overlay Groups that can have multiple layers active at the same time get checkboxes.
To implement layers control, add group names to individual layers with the group = argument AND add the layers control layer using addLayersControl().
Syntax: leaflet() %> addTiles(group = “One”) %>% addProviderTiles(providers$Esri.WorldImagery, group = “Two”) %>% addLayersControl(baseGroups = c(“One”, “Two”) options = layersControlOptions(collapsed = FALSE))
Basic leaflet map with two options for tiles and two markers with checkboxes
# Load library
library(leaflet)
library(dplyr)
# Draw map
leaflet() %>%
# Add first tile
addTiles(group="One") %>%
# Add second tile
addProviderTiles(providers$Esri.WorldImagery, group="Two") %>%
# Add first marker
addMarkers(lng=25.505206, lat=65.9767231, group="mark1") %>%
# Add second marker
addMarkers(lng=-45.445206, lat=45.5327231, group="mark2") %>%
# Add Layer controls
addLayersControl(baseGroups=c("One", "Two"),
overlayGroups=c("mark1", "mark2"),
options=layersControlOptions(collapsed=FALSE))
Output:
Leaflet package in R
The leaflet is one of the most popular open-source JavaScript libraries for mobile-friendly interactive maps. It’s used widely by many top organizations in the world. To use leaflet in r functionality in the R Programming Language, we have the leaflet package library. The leaflet in r package is an easy-to-use library that is designed with simplicity, performance, and usability all around.
Table of Content
- Features of the leaflet in R
- Installation of leaflet in R
- Creating Interactive maps using leaflet leaflet in R
- Adding tiles to map
- Adding Markers on Map
- Layer Control
- Plot data on top of map