Background Information

Leaflet is an open-source JavaScript library for creating interactive maps that has been around since 2015.

It is used by websites ranging from The New York Times and The Washington Post to GitHub and Flickr, as well as GIS specialists at places like OpenStreetMap, Mapbox, and CartoDB to create insightful maps that offer more than just the basic photo of a map or Google Maps add-on. Its value lies in its customization that allows the developer to show more in-depth and specific features like popups, choropleths (shaded maps by density), and boundary lines (Agafonkin 2016).

Leaflet uses MapBox’s maptiles to create a basemap – a common method popularized by Google Maps and a standard for most interactive web maps. Next, tiles can be added on top of the basemap to create a specific type of overlay to show some type of information (e.g. colored weather rain maps, major roads, cartography maps, etc.) and combined to convey customized levels of information. The default tile that an be added is from OpenStreetMap and includes the basics like roadways, coloring by type of area (e.g. blue for water, green for parks, tan for general land), names of cities/states/countries, etc. Third party tiles can also be installed for more complex and customized overlays (Cheng, 2021a).

Leaflet is currently at version 2.0.4.1 as of January 7, 2021. Here are all the past version release dates:

(Cheng, 2021b)

The main authors of the Leaflet package are Joe Cheng, Bhaskar Karambelkar, and Yihui Xie. Furthermore, the only dependencies are version 3.1.0 and above of R (Cheng, 2021a).

Features

  1. Interactive panning/zooming

  2. Compose maps using arbitrary combinations of:
    • Map tiles
    • Markers
    • Polygons
    • Lines
    • Popups
    • GeoJSO
  3. Create maps right from the R console or RStudio

  4. Embed maps in knitr/R Markdown documents and Shiny apps

  5. Easily render spatial objects from the sp or sf packages, or data frames with latitude/longitude columns

  6. Use map bounds and mouse events to drive Shiny logic

  7. Display maps in non spherical mercator projections

  8. Augment map features using chosen plugins from leaflet plugins repository

Installation

To install this R package, run this command at your R prompt:

install.packages("leaflet")
library(leaflet)

Examples of Usage

Create Maps

Before delving into the features that this package prides itself on, we should first outline the initial steps to getting a basic world map using the leaflet package.

  • leaflet()
  • addTiles()
  • addProviderTiles()
  • addLayersControl()

addTiles()

Using the addTiles() function with no arguments in order to see the most basic world map that leaflet can give you.

leaflet() %>% addTiles() 

addProviderTiles()

The addProviderTiles() function is a tile adding function that is different from addTiles() for one major reason, and it is that the data argument for this function is indication that you are taking a tile template from another known map creator and using it. So in this example map, we’re taking a pre-provided map that makes a realistic map of the earth in terms of imagery, and then again in the form of a roadmap.

leaflet() %>% addProviderTiles(providers$Esri.WorldImagery)
leaflet() %>% addTiles(group = "OSM") %>% addProviderTiles(providers$Esri.WorldStreetMap)

addLayersControl()

The addLayersControl() function allows us to layer multiple different tile sets so that the same leaflet() can create multiple different types of maps in one, and you can select which map to view.

leaflet() %>% addProviderTiles(providers$Esri.WorldImagery, group= 'Satellite') %>% addProviderTiles(providers$Esri.WorldStreetMap, group = 'Street View') %>% addProviderTiles(providers$Stamen.TonerLite, group = 'Toner Lite') %>% addLayersControl(baseGroups = c("Satellite", "Street View", "Toner Lite"), position = "topright", options = layersControlOptions(collapsed = FALSE))

Locations

A feature that absolutely necessary to know when using leaflet() is the ability to set the view to, pin, and label specific points on their map.

Set View to Charlottesville

The setView() function is a leaflet function that allows you to zoom in on the map to a specific set of coordinates and set how intensely you want to zoom in as well!

leaflet() %>%
  addTiles() %>%
  setView(lat = 38.0293, lng = -78.4767, zoom = 12)

Pinning

now that we have zoomed into the Charlottesville area, we can easily see a pin if we placed one, to demonstrate this, we will use the addMarkers() function and put a pin directly on the rotunda.

leaflet() %>%
  addTiles() %>%
  # use the default base map which is OpenStreetMap tiles
  addMarkers(lat = 38.0356 , lng = -78.5034,
             popup = "The Rotunda")

Create Shapes

Another interesting feature that is similar to the pin is the ability to add polygons to highlight areas. The examples that we have are just simple polygons, but there are many different polygons that you can create over the map.

Circle around UVA

The addCircles() function simply adds a circle with its center located at the specified coordinates, and the radius is an argument.

leaflet() %>%
  addTiles() %>%
  addCircles(lng =-78.5080, lat=38.0336, weight = 1,
    radius = 700)

Rectangle around VT

The addRectangles() function is similar to addCircles(), but it just superimposes a rectangle over the coordinates instead of a circle.

leaflet() %>%
  addTiles() %>%
  addRectangles(lng1 = -80.4384, lat1 = 37.2184 ,lng =-80.4234, lat=37.2284, weight = 1)

GeoJson Features and Combinations

One of the most interesting and cool things about leaflet is its ability to take in other location files and place them on the map. Here we take all of the states in the united states and the counties in Virginia in the form of GeoJSON files and and put them on the streetmap from earlier.

map <- leaflet()%>%
  addProviderTiles(providers$Esri.WorldStreetMap)%>%
  setView(lat = 38.57, lng = -79.71, zoom = 6) %>%
    addMarkers(lat = 38.0356 , lng = -78.5034,
             popup = "The Rotunda")%>%
    addCircles(lng =-78.5080, lat=38.0336, weight = 1,
    radius = 700, label = "The University of Virginia")

for (i in counties){
  map = map %>% addPolygons(data = i,  color = "#444444", weight = 1, smoothFactor = 0.5,
    opacity = 1.0, fillOpacity = 0.5, label = ~paste0(name, " County"),
    highlightOptions = highlightOptions(color = "red", weight = 2,
      bringToFront = TRUE))
}

for (i in state_files){
  geo_data <- readLines(i) %>% paste(collapse = "\n")
  map = map %>% addGeoJSON(geo_data, weight =1, color = "#4e8102",fill = FALSE)
}
map

Similar Packages

Plot

plot() is a basic r-function that can be used to create very basic maps for the user. It heavily relies on the sp and raster packages. Overall, this is a generic function that is easy to use and can be used to make a quick map, but isn’t specialized for complex map making. (Lovelace, 2021)

Grid

grid allows for low level static maps (e.g. pngs, jpgs) that allow for a snapshot of the data that is to be conveyed at a moment in time. It has low customization, but can create more complex maps that plot() (Lovelace, 2021)

ggplot2

ggplot2 is tidyverse’s data visualization package that is made for create graphs of all types including bar graphs, scatterplots, line graphs, and maps. While it can create static and interactive maps and is rather easy to use because of its reliance on grammar of graphics, it isn’t specifically made for maps so it can be a bit difficult to navigate and less customizable. Wrappers such as ggiraph(), ggplotly() and gganimate() can be used to build off of ggplot2’s static maps to make interactive maps. However, the interactives maps that can be created with these wrappers are not as good as leaflet’s and requires lots of external research on the user’s part to use which can make it hefty to use. Furthermore, users will need to convert to a dataframe using tidy() which may create issues in some cases. (Lovelace, 2021)

tmap

tmap will be more familiar to ggplot2 users as it also relies on grammar of graphics & separates aesthetics from data processing. It can create a mix of static and interactive maps and has some cool features like creating gifs and faceting graphs. This is the best contender/substitute for leaflet. tmap’s maps can be exported to be used in leaflet, and therefore also shiny which makes it flexible. However, it is overall not as well known so it is used less. (Lovelace, 2021)

leaflet

leaflet can easily create high-level dynamic & interactive maps. The level of 3rd party overlays that users can add in addition to leaflet’s ease of use with Shiny makes it highly user-friendly. However, because leaflet doesn’t rely on a “grammar of graphics” syntax like other graphing packages, it may have a higher learning curve. Furthermore, while leaflet is good at making dynamic maps, other packages like ggplot2 can make better static maps than leaflet can. (Lovelace, 2021)

Reflection

Leaflet is a highly user friendly, aesthetically pleasing, and customizable package to create high-level dynamic & interactive maps. While it may have a learning curve, it has set the standard for interactive map-making today and is widely used in the map-making world.

Suggestions for Improvement

The main issue is the learning curve for the syntax, but isn’t a huge concern for functionality. Leaflet should also focus on increasing functionalities for static maps to become a contender for packages like ggplot2. Furthermore, more documentation can be made for creating custom tiles/overlays in case a developer cannot find a third party tile they are satisfied with.

References

Agafonkin, V. (2016). Leaflet for R. Retrieved from http://rstudio.github.io/leaflet/

Cheng, J. (2021, January 07 a). Create interactive web maps with the JavaScript ‘leaflet’ LIBRARY [R Package leaflet Version 2.0.4.1]. Retrieved from https://cran.r-project.org/web/packages/leaflet/index.html

Cheng, J. (2021b). leaflet v2.0.4.1. Retrieved from https://www.rdocumentation.org/packages/leaflet/versions/2.0.4.1

Lovelace, R., Nowosad, J., & Muenchow, J. (2021, April 6). Geocomputation with R. Retrieved from https://geocompr.robinlovelace.net/adv-map.html

Leaflet for R - working with Geojson & TopoJSON. (n.d.). Retrieved April 06, 2021, from https://rstudio.github.io/leaflet/json.html