Skip to contents

Using Mapbox GL JS

Your gateway to Mapbox GL JS v3 in R is the mapboxgl() function. Run the function with no arguments to get an interactive globe using Mapbox’s Standard style:

To use Mapbox maps, you will need a Mapbox access token. If you are a user of the mapboxapi package and have installed your Mapbox access token, mapboxgl() will pick up your token for you. If you are new to my R packages, you’ll want to get a token from your Mapbox account, run usethis::edit_r_environ(), and set the environment variable MAPBOX_PUBLIC_TOKEN="your_token_here". It’s important for you to know that Mapbox GL JS is a commercial product that charges you for map views; however, it does have a generous free tier.

Mapbox’s default styles are accessible with the mapbox_style() function, and can be passed to the style parameter to change the style of your map. Mapbox GL JS also supports modifying map projections; here we use projection = "winkelTripel" for the Winkel Tripel global projection.

mapboxgl(
  style = mapbox_style("satellite"),
  projection = "winkelTripel")

To get a more local view in your map, you can use the center, zoom, pitch, and bearing arguments. In the example shown below, these arguments are incorporated into a “fly to” animation. mapgl supports several of these animated transitions. In Mapbox GL JS v3, the new Standard style includes custom-rendered buildings around the world, such as the American Airlines Center in Dallas.

mapboxgl(
  center = c(-97.6, 25.4)
) |> 
  fly_to(
    center = c(-96.810481, 32.790869),
    zoom = 18.4,
    pitch = 75,
    bearing = 136.8
  )

Using Maplibre GL JS

Maplibre GL JS, a fork of the more permissively-licensed Mapbox GL JS 1.0, is also available to R users in mapgl. The core function to initialize a MapLibre map is maplibre(). The default tiles in maplibre() are CARTO’s Voyager tiles, which are usable without an API key.

MapTiler tiles are also available via the maptiler_style() function. These styles work quite well with MapLibre, but do require an API key; set the environment variable MAPTILER_API_KEY in your .Renviron file to store your key. The example below uses the Bright MapTiler style, and adds a fullscreen control and a navigation control to the map.

These controls and styles are available with mapboxgl() as well; mapgl aims to provide a consistent API to work with either Mapbox or MapLibre.

maplibre(
  style = maptiler_style("bright"),
  center = c(-43.23412, -22.91370),
  zoom = 14
) |> 
  add_fullscreen_control(position = "top-left") |> 
  add_navigation_control()

Comparing map views

mapgl includes a function compare() that allows users to create synced swipe maps that can compare two styles. This function works for either Mapbox or MapLibre maps. I don’t have this working correctly in rendered R Markdown / Quarto docs or Shiny apps yet, but I’m working on it!

m1 <- mapboxgl()
m2 <- mapboxgl(mapbox_style("satellite-streets"))

compare(m1, m2)