Introduction

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 CavemanCaveysPizza 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 + kepler.gl - Partnering with Uber to bring advanced data visualization to our developer community

https://blog.mapbox.com/hello-mapbox-and-keplergl-4d71fc8e1d02

see which companies are using R

https://github.com/ThinkR-open/companies-using-r

https://appsilon.com/

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 http://rmarkdown.rstudio.com.

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 https://account.mapbox.com/auth/signup/ 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.eyJ1IjoidXRqaW1teXgiLCJhIjoiY2tnMmI1OWRpMDZsdDJxb2Y4MjdnZmxpMyJ9.ImwwUvDQpod7-B0YnIUytw"

library(mapboxapi)
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:

library(leaflet)
library(mapboxapi)

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

mapbox_map

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).

CavemanCaveysPizza <- mb_geocode("3620 Mt Pinos Way #107, Frazier Park, CA 93225")

CavemanCaveysPizza
## [1] -118.94602   34.82226
mapbox_map %>%
  setView(lng = CavemanCaveysPizza[1],
          lat = CavemanCaveysPizza[2],
          zoom = 14)

Build An isochrone map for the CavemanCaveysPizza community

CavemanCaveysPizza_isochrones <- mb_isochrone(CavemanCaveysPizza,
                                profile = "driving",
                                time = c(4, 8, 12))

CavemanCaveysPizza_isochrones
## Simple feature collection with 3 features and 1 field
## geometry type:  POLYGON
## dimension:      XY
## bbox:           xmin: -119.0748 ymin: 34.77477 xmax: -118.8168 ymax: 34.86826
## CRS:            4326
## # A tibble: 3 x 2
##    time                                                                 geometry
##   <int>                                                            <POLYGON [°]>
## 1    12 ((-118.885 34.86826, -118.8849 34.86733, -118.884 34.86731, -118.8838 3…
## 2     8 ((-119.0279 34.83135, -119.0276 34.83062, -119.026 34.83052, -119.025 3…
## 3     4 ((-118.9398 34.82744, -118.9392 34.82408, -118.9395 34.82279, -118.9402…
colors <- viridisLite::viridis(3)

mapbox_map %>%
  addPolygons(data = CavemanCaveysPizza_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 CavemanCaveysPizza")

An isochrone map (or chart/diagram) in geography and urban planning is “a map showing areas related to isochrones between different points. … In hydrology and transportation planning isochrone maps are commonly used to depict areas of equal travel time.”

The filled areas represent the estimated reachable area around CavemanCaveysPizza without traffic. Currently, the Mapbox API does not support traffic-adjusted isochrones, so isochrone results should be interpreted appropriately depending on what you plan to represent.

References