Introduction

Features

  • Interactive panning/zooming
  • Compose maps using arbitrary combinations of:
    • Map tiles
    • Markers
    • Polygons
    • Lines
    • Popups
    • GeoJSON
  • Create maps right from the R console or RStudio
  • Embed maps in knitr/R Markdown documents and Shiny apps
  • Easily render spatial objects from the sp or sf packages, or data frames with latitude/longitude columns
  • Use map bounds and mouse events to drive Shiny logic
  • Display maps in non spherical mercator projections
  • 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")
# to install the development version from Github, run
# devtools::install_github("rstudio/leaflet")

Once installed, you can use this package at the R console, within R Markdown documents, and within Shiny applications.

Basic Usage

You create a Leaflet map with these basic steps:

  1. Create a map widget by calling leaflet().
  2. Add layers (i.e., features) to the map by using layer functions (e.g. addTiles, addMarkers, addPolygons) to modify the map widget.
  3. Repeat step 2 as desired.
  4. Print the map widget to display it.

Basic Usage

Here’s a basic example:

library(leaflet) 
my_map <- leaflet(width="100%", height=300) %>%
  addTiles() %>% # Add default OpenStreetMap map tiles
  addMarkers(lat=29.5850369, lng=-98.6182212,   popup="Campbell's Office")
my_map #Print the map

Basic Usage

Recall the magrittr pipe operator (%>%), without it, we’d have to write:

my_map <- leaflet()
my_map <- addTiles(my_map)
my_map <- addMarkers(my_map, lat=29.5850369, lng=-98.6182212, popup="Campbell's Office")
my_map

#Or worse
my_map<-addMarkers(addTiles(leaflet()), lat=29.5850369, lng=-98.6182212, popup="Campbell's Office")

Data sources

Point data for markers can come from a variety of sources:

  • SpatialPoints or SpatialPointsDataFrame objects (from the sp package)
  • POINT, sfc_POINT, and sf objects (from the sf package); only X and Y dimensions will be considered
  • Two-column numeric matrices (first column is longitude, second is latitude)
  • Data frame with latitude and logitude columns. You can explicitly tell the marker function which columns contain the coordinate data (e.g. addMarkers(lng = ~Longitude, lat = ~Latitude)), or let the function look for columns named lat/latitude and lon/lng/long/longitude (case insensitive).
  • Simply provide numeric vectors as lng and lat arguments

Note that MULTIPOINT objects from sf are not supported at this time.

Adding Markers

Markers are added using the addMarkers or the addAwesomeMarkers functions. Their default appearance is a dropped pin.

data(quakes)

# Show first 20 rows from the `quakes` dataset
leaflet(data = quakes[1:20,],width="100%", height=300) %>% addTiles() %>%
  addMarkers(~long, ~lat, popup = ~as.character(mag), label = ~as.character(mag))

Customizing Marker Icons

The blue markers that leaflet comes packaged with may not be enough depending on what you’re mapping. Thankfully you can make your own markers from .png files.

roadrunnerIcon <- makeIcon( 
  iconUrl = "http://a3.espncdn.com/combiner/i?img=%2Fi%2Fteamlogos%2Fncaa%2F500%2F2636.png", 
  iconWidth = 31*215/230, iconHeight = 31, 
  iconAnchorX = 31*215/230/2, iconAnchorY = 16 
) 

roadrunnerLatLong <- data.frame( 
lat = c(29.5850369, 29.5823632, 29.424606), 
lng = c(-98.6182212, -98.621411, -98.5045881)) 

Adding Multiple Popups

When adding multiple markers to a map, you may want to add popups for each marker. You can specify a string of plain text for each popup, or you can provide HTML which will be rendered inside of each popup.

roadrunnerSites<-c("<a href='http://www.business.utsa.edu/mss/index.aspx'>Mgmt Sci & Stat</a>",
"<a href='https://en.wikipedia.org/wiki/Convocation_Center_(University_of_Texas_at_San_Antonio)'>UTSA Convocation Center</a>",
"<a href='http://txsdc.utsa.edu/'>Texas Demographic Center</a>")

roadrunnerLatLong %>% 
  leaflet(width="100%", height=350) %>% 
  addTiles() %>% 
  addMarkers(icon = roadrunnerIcon, popup = roadrunnerSites)

Mapping Clusters

Sometimes you might have so many points on a map that it doesn’t make sense to plot every marker. In these situations leaflet allows you to plot clusters of markers using addMarkers(clusterOptions = markerClusterOptions()). When you zoom in to each cluster, the clusters will separate until you can see the individual markers.

leaflet(quakes,width="100%",heigh=350) %>% addTiles() %>% addMarkers(
  clusterOptions = markerClusterOptions()
)
## Assuming "long" and "lat" are longitude and latitude, respectively

Circle Markers

Instead of adding markers or clusters you can easily add circle markers using addCircleMarkers().

# Some fake pirate data
df <- sp::SpatialPointsDataFrame(
  cbind(
    (runif(20) - .5) * 10 - 90.620130,  # lng
    (runif(20) - .5) * 3.8 + 25.638077  # lat
  ),
  data.frame(type = factor(
    ifelse(runif(20) > 0.75, "pirate", "ship"),
    c("ship", "pirate")
  ))
)

leaflet(df,width="100%",height=200) %>% addTiles() %>% addCircleMarkers()

Drawing Circles

Circles are added using addCircles().

tx.cities<-data.frame(name=c("Austin","Corpus Christi","Dallas","El Paso","Fort Worth","Galveston","Houston","Lubbock","San Angelo","San Antonio","Tyler"), pop=c(815974,305382,1200699,651685,746547,47820,2114761,230622,93644,1333953,97237), lat=c(30.307182,27.754252,32.794176,31.84836,32.779542,29.18326,29.780472,33.566479,31.438912,29.472403,32.314954),lng=c(-97.755996,-97.173385,-96.765503,-106.426979,-97.346335,-94.969755,-95.386342,-101.886677,-100.45185,-98.525142,-95.304631)) 

tx.cities %>% 
  leaflet(width="100%",height=350) %>% 
  addTiles() %>% 
  addCircles(weight = 1, radius = sqrt(tx.cities$pop) * 30)
## Assuming "lng" and "lat" are longitude and latitude, respectively

Drawing Rectangles

You can add rectangles on leaflet maps as well:

leaflet(width="100%",height=400) %>% 
    addTiles() %>% 
    addRectangles(lat1 = 29.15, lng1 = -98.8, 
                  lat2 = 30.5, lng2 = -97.5)

Legends

Adding a legend can be useful if you have markers on your map with different colors:

suppressPackageStartupMessages(library(rgdal))

# From http://data.okfn.org/data/datasets/geo-boundaries-world-110m
countries <- readOGR("https://raw.githubusercontent.com/datasets/geo-boundaries-world-110m/master/countries.geojson")

map <- leaflet(countries) %>% addTiles()

pal <- colorNumeric(
  palette = "YlGnBu",
  domain = countries$gdp_md_est
)
map %>%
  addPolygons(stroke = FALSE, smoothFactor = 0.2, fillOpacity = 1,
    color = ~pal(gdp_md_est)
  ) %>%
  addLegend("bottomright", pal = pal, values = ~gdp_md_est,
    title = "Est. GDP (2010)",
    labFormat = labelFormat(prefix = "$"),
    opacity = 1
  )

Legends

## OGR data source with driver: GeoJSON 
## Source: "https://raw.githubusercontent.com/datasets/geo-boundaries-world-110m/master/countries.geojson", layer: "countries"
## with 177 features
## It has 63 fields

Conclusion