It’s one of the openly used openscript libraries for making interactive maps and used by many to publish maps. This R package helps bring the same functionality to R, and makes it easy to integrate and control Leaflet maps in R.
Create maps right from the R console or RStudio
Embed maps in R Markdown documents and Shiny apps
Easily render spatial objects from the sp or sf packages, or data frames with latitude/longitude columns
To install this R package, run this command at your R prompt:
install.packages("leaflet") # main package
install.packages("maps")
You create a Leaflet map with these basic steps:
Create a map widget by calling leaflet().
Add layers (i.e., features) to the map by using layer functions (e.g. addTiles, addMarkers, addPolygons) to modify the map widget.
Repeat step 2 as desired.
Print the map widget to display it.
To get a sense of the package, lets start out with an example for its usage:
library(leaflet)
m <- leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addMarkers(lng=-73.2013, lat=44.4783, popup="Waterman building, UVM") # Decimal degrees - latitude and longitude, the values are bounded by ±90° and ±180° respectively.
m # Print the map
Note that using the print() to print the output in Rmarkdown does not give the actual output.
require(leaflet)
m <- leaflet() %>% addTiles()
#setView()
m %>% setView(-73.2, 44.48, zoom = 16) #Restricts the map view to the given bounds
#fitBounds()
m %>% fitBounds(-73.2, 44.48,-73.1, 44.49) #Set the bounds of a map
Other examples:
#setMaxBounds()
m %>%
setMaxBounds(-73.2, 44.48,-73.1, 44.49) #Restricts the map view to the given bounds
#clearBounds()
m %>% clearBounds() # world view
Both leaflet() and map layer function has an optional parameter that is designed to receive data in one of the several forms:
From base R: from matrix or data frame with lat/long columns
From sp
packages
From the maps package
Example 1. From Base R
df = data.frame(Lat = 1:10, Long = rnorm(10))
leaflet(df) %>% addTiles() %>% addCircles()
Example 2. From the maps package
require("maps")
## Loading required package: maps
library(maps)
mapStates = map("state", fill = TRUE, plot = FALSE)
leaflet(data = mapStates) %>% addTiles() %>%
addPolygons(fillColor = topo.colors(10, alpha = NULL), stroke = FALSE)
The easiest way to add tiles is by calling addTiles() with no arguments; by default, OpenStreetMap tiles are used.
m <- leaflet() %>% setView(lng=-73.2013454, lat=44.4783732, zoom = 12)
m %>% addTiles() #default:OpenStreetMap
Popular free third-party basemaps can be added using the addProviderTiles()
function, which is implemented using the leaflet-providers plugin. The list of third party map providers can also be obtained by running the below code:
head(names(providers))
## [1] "OpenStreetMap" "OpenStreetMap.Mapnik"
## [3] "OpenStreetMap.BlackAndWhite" "OpenStreetMap.DE"
## [5] "OpenStreetMap.CH" "OpenStreetMap.France"
With the adjustent in opacity, different base maps can be stacked on top of each other. This helps in augmenting the deatails in a given map. You might need to work a bit all the map types to get a sense of which all combinations works best. The example below uses the NatGeoWorldMap from ESRI and overlay it with the contrasting map lines and names of Stamen Toner.
m %>% addProviderTiles(providers$Esri.NatGeoWorldMap) %>%
addProviderTiles(providers$Stamen.TonerLines,
options = providerTileOptions(opacity = 0.75)) %>%
addProviderTiles(providers$Stamen.TonerLabels)
Circles: The circle size is not based on pixel, so even when you zoom in or zoom out, it does not vary in shape. An example of this is given below.
cities <- read.csv(textConnection("
City,Lat,Long,Pop
Boston,42.3601,-71.0589,645966
Hartford,41.7627,-72.6743,125017
New York City,40.7127,-74.0059,8406000
Philadelphia,39.9500,-75.1667,1553000
Pittsburgh,40.4397,-79.9764,305841
Providence,41.8236,-71.4222,177994
"))
leaflet(cities) %>% addTiles() %>%
addCircles(lng = ~Long, lat = ~Lat, weight = 1,
radius = ~sqrt(Pop) * 50, popup = ~City
)
Rectangles: Similar concepts apply here, but instead of using a data set to set the size, you need to define the four corners of the rectangle with lat and long values.
leaflet() %>% addTiles() %>%
addRectangles(
lng1=-118.456554, lat1=34.078039,
lng2=-118.436383, lat2=34.062717,
fillColor = "red"
)
It’s always useful to mark your datapoints on a map to observe the spatial distribution of the dataset.
data(quakes) #Locations of Earthquakes off Fiji
head(quakes)
## lat long depth mag stations
## 1 -20.42 181.62 562 4.8 41
## 2 -20.62 181.03 650 4.2 15
## 3 -26.00 184.10 42 5.4 43
## 4 -17.97 181.66 626 4.1 19
## 5 -20.42 181.96 649 4.0 11
## 6 -19.68 184.31 195 4.0 12
# Show first 20 rows from the `quakes` dataset
leaflet(data = quakes[1:20,]) %>% addTiles() %>%
addMarkers(~long, ~lat, popup = ~as.character(mag), label = ~as.character(mag))
Note that the marker size is defined based on pixels, and will keep the shape irrespectiev of the zoom level. However, it might become cumbersome to observe this with a large number of dataset. When there are a large number of markers on the map, you can cluster them together using the argument clusterOptions
.
leaflet(quakes) %>% addTiles() %>% addMarkers(
clusterOptions = markerClusterOptions()
)
## Assuming "long" and "lat" are longitude and latitude, respectively
Various utility functions can be used to augment your map with additional elements. One basic example is given below is to add a distance measuring tool and a minimap.
leaflet(quakes) %>% addTiles() %>% addMarkers(
clusterOptions = markerClusterOptions()
) %>% addMeasure() %>% addMiniMap()
## Assuming "long" and "lat" are longitude and latitude, respectively
These are the basics of using the leaflet
package and just barely skimmed the surface of what this package is capable of doing. For more details, check the leaflet documention site listed below. The R markdown for this tutorial is also given below. Hope you had fun following through this tutorial.
The R markdown for this tutorial: Leaflet tutorial
documentation source: https://rstudio.github.io/leaflet/
Full extent of leaflet application: https://leafletjs.com/examples.html