Leaflet package in R - GeeksforGeeks

05 Nov, 2021
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 this same functionality in the R Language, we have the leaflet package library. The leaflet R package is an easy-to-use library that is designed with simplicity, performance, and usability all around.
Supports interactive maps that provide features like panning and zooming.
Supports various elements for the composition of maps such as Map tiles, Markers, Polygons, Lines, Popups, and GeoJSON.
Supports full dynamic map creation from the R Console itself.
Easy to embed map objects in various markdown files.
Can also display maps in non-spherical Mercator projections
Augment map features using chosen plugins from leaflet plugins repository
We can install the leaflet library in the R Language by using:
# installs the leaflet package
install.packages("leaflet")
Run the above command in the R console and select desired cran mirror to install the Leaflet R Package.
To create a map widget using the leaflet package in the R Language we use the leaflet() function. The leaflet() function returns a map object that can be viewed in itself or can be modified by adding more layers. The basic leaflet widget shows an empty map widget with no tiles or markers.
Syntax: map <- leaflet()
Example: Basic map object made by using the leaflet() function.
R
# load leaflet librarylibrary(leaflet)  # create map widgetmap <- leaflet()  # print map widgetmap
Output:
Since above code creates a map widget that is empty. To add tiles to it for the creation of the desired map we use the addTiles() function of the leaflet package. By default, if no argument is passed it creates an OpenStreetMap map tile on top of the map widget. For custom map tile we pass that map as an argument to the addTiles() function.
Syntax: map <- leaflet() %>%addTiles()
Example: Basic map with OpenStreetMap tile.
R
# load leaflet librarylibrary(leaflet)  # create map widget with OpenStreetMap tilemap <- leaflet() %>%       addTiles()  # print map widgetmap
Output:
Now since we have created a basic map, it in itself is not that useful. we can now add markers on the map using the addMarkers() function of the leaflet package. we can add as many markers as we require by just adding new layers.
Syntax: map <- leaflet() %>%addTiles() %>% addMarkers( lng, lat, popup)
Parameters:
lng: determines the longitude of the marker position
lat: determines the latitude of the maeker position
popup: determines the text that would be shown on marker popup
Example: Interactive map with a marker in Delhi India.
R
# load leaflet librarylibrary(leaflet)  # create map widget with OpenStreetMap tile# added marker at Delhi Indiamap <- leaflet() %>%       addTiles() %>%       addMarkers(lng=77.1025, lat=28.7041,                   popup="Delhi, India")  # print map widgetmap
Output:
We can add multiple layers to the leaflet 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))
Example: Basic leaflet map with two options for tiles and two markers with checkboxes.
R
# load library leafletlibrary(leaflet)  # draw mapleaflet() % >%# add first tileaddTiles(group="One") % >%# add second tileaddProviderTiles(providers$Esri.WorldImagery,                 group="Two") % >%# add first markeraddMarkers(lng=25.505206, lat=65.9767231,           group="mark1") % >%# add second markeraddMarkers(lng=-45.445206, lat=45.5327231,           group="mark2") % >%# add Layer controlsaddLayersControl(baseGroups=c("One", "two"),                 overlayGroups=c("mark1", "mark2"),                 options=layersControlOptions(collapsed=FALSE))
Output:
Spatial objects in your R environment can also be added as map layers, provided that they have a CRS defined with a datum. We can use those data points on top of the leaflet map using the addMarkers() or the addPloygons() function depending on the type of dataset. If the dataset is single-dimensional we use markers and for multidimensional data we use polygons.
Example: Plotted data variables as markers on top of the leaflet map. The data set used in the example can be downloaded here.
R
# load librarylibrary(sf)library(leaflet)# read datasetdataset <- st_read("wqp_sites.shp")  # draw plot with markers at dataset pointleaflet() %>%  addTiles() %>%  addMarkers(data = dataset)
Output:
Picked
R-Charts
R-Graphs
R-Packages
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
R - if statement
How to filter R dataframe by multiple conditions?