This tutorial (case study) is built using R and the Mapbox api.

In this case study, you will find the trade area available for the CSUB community and identify logistics solutions (e.g.,last-mile delivery solutions) or retail opportunities using Mapbox.

You can do more with Mapbox. For instance, Uber is partnering with Mapbox to design its advanced API ecosystems.

“Collaborating on open-source projects can build relationships between companies in the context of pure engineering, where individuals contribute to making software work better, not only benefitting the individual companies involved, but anyone else who might have a use for the tool.” -Nicolas Garcia Belmonte, Head of Visualization at Uber

Mapbox + - Partnering with Uber to bring advanced data visualization to our developer community

see which companies are using R

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see

Installing packages and dependencies

To get started with mapboxapi, you’ll need to first install some packages. mapboxapi was just released to CRAN this week, so we can install with install.packages():

install.packages("mapboxapi", dependencies = TRUE)

If you’ve been working with R Spatial packages before, installation should go smoothly. If you are new to R/R Spatial, you may need to do some configuration prior to successful installation of the package. mapboxapi depends heavily on the sf package for spatial data processing in R. On Ubuntu, use the following commands in a terminal to install required dependencies:

sudo add-apt-repository ppa:ubuntugis/ubuntugis-unstable
sudo apt-get update
sudo apt-get install -y libudunits2-dev libgdal-dev libgeos-dev libproj-dev

mapboxapi also uses the protolite package for interacting with Mapbox vector tiles and the magick package for image processing and display. On Ubuntu, install dependencies with:

sudo apt-get install -y libprotobuf-dev protobuf-compiler libmagick++-dev

Instructions for other Linux distributions can be found on the package websites linked above.

To run all of the examples in this workshop, you’ll also need to install the following packages that don’t get picked up as mapboxapi dependencies:

install.packages(c("shiny", "fasterize", "tidycensus", "tidyverse"))

Setting up your Mapbox account

Before we get started using Mapbox services in R, you’ll need a valid Mapbox account with an access token. Fortunately, Mapbox has generously provided a coupon code for you to use as workshop participants. To set up your account, visit to establish an account - all you need to provide is an email address to sign up! Fill out the form and verify your account through the email Mapbox sends you; you’ll be taken directly to your Mapbox account dashboard page.

Note the “default public token” that appears on your screen - you’ll come back to this page in a moment. First, look to the right side of your screen and click “View billing.” This is where Mapbox will handle your billing information. Nothing you’ll do today will be intensive enough to incur charges - but your next three months of work will be covered by the coupons Mapbox has provided to this workshop. Scroll down and enter the coupon code you’ve received in the appropriate box, then click Add. Once you’ve entered your coupon code, return to your Mapbox dashboard. Copy the access token that appears on your screen to your clipboard, then return to R.

Loading mapboxapi and setting your access token

All features in mapboxapi require a valid Mapbox access token to work. Now that you have yours in hand, you can set yours up! Load the mapboxapi package and install your token as follows:

my_token <- "pk.eyJ1IjoieWZlZGVyc3BpZWwiLCJhIjoiY2toczU0cGxrMDlvejJ4bXRmNTdjenA4MCJ9.pwBvaHJvIRlpxh1988gEUw"

mb_access_token(my_token, install = TRUE)

The optional argument install = TRUE saves the token to your .Renviron, allowing you to use mapboxapi functions in the future without having to worry about setting your token. To use this feature, restart your R session.

Using Mapbox maps in R

The most well-known feature of Mapbox services is its ability to create stunning web maps which are used on applications all around the world. While mapboxapi is not an interface to Mapbox GL JS, Mapbox’s JavaScript library for building web maps, it does include some tools to help you use Mapbox maps in your R projects. This is important as the Mapbox Terms of Service require that Mapbox API outputs be visualized on Mapbox maps.

Visualizing Mapbox “styles”

Mapbox maps are accessed through styles, which are custom design configurations applied to OpenStreetMap or even user-generated vector map tilesets. You’ll learn how to create and use your own map style with Mapbox later in this workshop. However, Mapbox provides a number of their styles to all users with a Mapbox access token. The most recent versions of these styles (as of the workshop date) are as follows:

One of the most popular R packages for interactive data visualization in R is the Leaflet package maintained by RStudio, which wraps the Leaflet JavaScript library for web mapping.

Let’s load the leaflet and mapboxapi libraries and set up an interactive map:


mapbox_map <- leaflet() %>%
  addMapboxTiles(style_id = "streets-v11",
                 username = "mapbox")


We get a browseable Leaflet map using Mapbox tiles as a basemap.

Using the Mapbox Search API

Once we’ve set up our Leaflet map with a Mapbox basemap, we’ll likely want to focus it on a specific location. mapboxapi includes functionality for R users to interact with the Mapbox Search API. Implemented functions include mb_geocode() for forward geocoding, which refers to the conversion of a description of a place (like an address) into longitude/latitude coordinates; and mb_reverse_geocode(), which converts coordinates into a place description.

Both functions default to using the mapbox.places API endpoint, which is to be used for temporary geocoding. This means that the endpoint cannot be used to store geocoded information nor can it be used for batch geocoding (e.g., a spreadsheet of addresses). These tasks are permissible with the mapbox.places-permanent endpoint, which is not included with free accounts. In turn, R users looking for free batch geocoding solutions should use other packages like the tidygeocoder package. Mapbox geocoding with the mapbox.places endpoint can be used to focus web maps and guide navigation services, which will be illustrated in the following sections.

Let’s use mb_geocode() to identify the coordinates representing the University of Pennsylvania (specifically here, the university bookstore).

CSUB <- mb_geocode("96 Falmouth St, Portland, ME 04103")

## [1] -70.27762  43.66222
mapbox_map %>%
  setView(lng = CSUB[1],
          lat = CSUB[2],
          zoom = 14)

Build An isochrone map for the CSUB community

CSUB_isochrones <- mb_isochrone(CSUB,
                                profile = "driving",
                                time = c(4, 8, 12))

## Simple feature collection with 3 features and 1 field
## geometry type:  POLYGON
## dimension:      XY
## bbox:           xmin: -70.41163 ymin: 43.56673 xmax: -70.18861 ymax: 43.78534
## CRS:            4326
## # A tibble: 3 x 2
##    time                                                                 geometry
##   <int>                                                            <POLYGON [°]>
## 1    12 ((-70.18861 43.78523, -70.19025 43.78485, -70.19148 43.78308, -70.19319…
## 2     8 ((-70.23262 43.73023, -70.23194 43.73022, -70.23362 43.73021, -70.23363…
## 3     4 ((-70.25663 43.67819, -70.25678 43.67422, -70.25698 43.67358, -70.25791…
colors <- viridisLite::viridis(3)

mapbox_map %>%
  addPolygons(data = CSUB_isochrones,
              color = rev(colors),
              fillColor = rev(colors),
              fillOpacity = 0.5,
              opacity = 1,
              weight = 0.2) %>%
  addLegend(labels = c(4, 8, 12),
            colors = colors,
            title = "Drive-time<br/>around CSUB")