beginner
JavaScript
Getting started with the Mapbox Directions API

Providing routes, turn-by-turn instructions, and trip durations are all possible with the Mapbox Directions API. This tutorial walks you through the process of requesting directions, adding a single bike route between two points to a web map, and displaying turn-by-turn instructions.

Getting started

Here are a few resources you’ll need before getting started:

  • An access token from your account. The access token is used to associate a map with your account and can be found on your Account page.
  • Mapbox Directions API documentation. A reference for all options available when making requests and how to interpret responses.
  • jQuery. A JavaScript library you will use to add your API request to your application.
  • Mapbox GL JS. The Mapbox JavaScript library that uses WebGL to render interactive maps from Mapbox GL styles.
  • A text editor. You’ll be writing HTML, CSS, and JavaScript.

Build the request

When making a request to any Mapbox web service, the general structure of the request URL will start like this:

https://api.mapbox.com/{service}/

In this case, the {service} will be directions, but you can also make requests of styles, geocoding, and more.

The next part will be the version number which is helpful to know since this may change over time and provide you with greater capabilities or change how the requests may work. The current version for directions is v5:

https://api.mapbox.com/directions/v5/

Parameters

At this point, the request will not return anything because you still need to pass in some parameters that will narrow the scope of your request. In the case of the Mapbox Directions API, you are required to supply a profile (mode of travel) and coordinates (origin and destination) for your request:

  • In this case, use the cycling profile to generate a bike route.
  • Use -84.518641, 39.134270 as your starting coordinate and -84.512023, 39.102779 as your destination. Note that these coordinates must be separated by a semi-colon ;.
  • Use the optional parameter geometries=geojson to specify that you would like it to return the route as a GeoJSON feature.
https://api.mapbox.com/directions/v5/mapbox/cycling/-84.518641,39.134270;-84.512023,39.102779?geometries=geojson

Access token

The only required item left is your access token. The access token is required in order to track the requests you make from your account for this particular service. You can create specific tokens for your requests or use your default token.

When adding this token, use an & before the token to append this to the request:

https://api.mapbox.com/directions/v5/mapbox/cycling/-84.518641,39.134270;-84.512023,39.102779?geometries=geojson&access_token=<your access token here>

Now that you have a basic request, take a look at what you get in return by pasting the full URL into a new browser window.

Review the response

When you make your request, a JSON object will be returned with the following information:

  • waypoints: This is an array of Waypoint objects. In this case, this array will include your starting and ending points.
  • routes: This is an array of Route objects ordered by descending recommendation rank. In this case, you have not requested alternative routes, so only one route will be returned. You will use the geometry property to display the route on a map in the next step.
  • code: This string indicates the state of the response. On normal valid responses, the value will be Ok.
{
  "waypoints": [
    {
      "location": [
        -84.518399,
        39.134126
      ],
      "name": ""
    },
    {
      "location": [
        -84.511987,
        39.102638
      ],
      "name": "East 6th Street"
    }
  ],
  "routes": [
    {
      "legs": [
        {
          "steps": [],
          "weight": 1332.6,
          "distance": 4205,
          "summary": "",
          "duration": 1126
        }
      ],
      "weight_name": "cyclability",
      "geometry": {
        "coordinates": [
          [
            -84.518399,
            39.134126
          ],
          [
            -84.51841,
            39.133781
          ],
          [
            -84.520024,
            39.133456
          ],
          [
            -84.520321,
            39.132597
          ],
          [
            -84.52085,
            39.128019
          ],
          [
            -84.52036,
            39.127901
          ],
          [
            -84.52094,
            39.122783
          ],
          [
            -84.52022,
            39.122713
          ],
          [
            -84.520768,
            39.120841
          ],
          [
            -84.519639,
            39.120268
          ],
          [
            -84.51233,
            39.114141
          ],
          [
            -84.512652,
            39.11311
          ],
          [
            -84.512399,
            39.112216
          ],
          [
            -84.513232,
            39.112084
          ],
          [
            -84.512127,
            39.107599
          ],
          [
            -84.512904,
            39.107489
          ],
          [
            -84.511692,
            39.102682
          ],
          [
            -84.511987,
            39.102638
          ]
        ],
        "type": "LineString"
      },
      "weight": 1332.6,
      "distance": 4205,
      "duration": 1126
    }
  ],
  "code": "Ok"
}

Add route to a map

Now that you understand how Mapbox Directions API requests and responses both work, you can use this API request to add a route to a web map.

Set up your HTML file

Create a new HTML file called index.html and initialize a Mapbox GL JS map using the code below.

<!DOCTYPE html>
<html>
  <head>
    <meta charset='utf-8' />
    <title></title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
    <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.44.2/mapbox-gl.js'></script>
    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.44.2/mapbox-gl.css' rel='stylesheet' />
    <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
    <style>
      body {
        margin: 0;
        padding: 0;
      }

      #map {
        position: absolute;
        top: 0;
        bottom: 0;
        width: 100%;
      }
    </style>
  </head>
  <body>
    <div id='map'></div>
    <script>
    mapboxgl.accessToken = '<your access token here>';
    var map = new mapboxgl.Map({
      container: 'map',
      style: 'mapbox://styles/mapbox/streets-v10',
      center: [-122.42, 37.78],
      zoom: 12
    });
    // this is where the code from the next step will go
    </script>
  </body>
</html>

Add your route

Build a function called getRoute to make the API request and add the resulting route as a new layer. Then, call that function when the map loads.

Within the getRoute function, specify a start and an end coordinate. Use those variables to build your Directions API request as outlined in the previous section. Use an AJAX call to make the API request. Once the response has been received, find the route within the directions response object and add a new layer using that route as the data source.

You’ll want to wait to make the request and add the route to the map until after the map has loaded. You can do this by calling the getRoute function inside map.on('load', function(){...});

Use the following code right after the code you’ve already written to initialize your map.

map.on('load', function() {
  getRoute();
});

function getRoute() {
  var start = [-84.518641, 39.134270];
  var end = [-84.512023, 39.102779];
  var directionsRequest = 'https://api.mapbox.com/directions/v5/mapbox/cycling/' + start[0] + ',' + start[1] + ';' + end[0] + ',' + end[1] + '?geometries=geojson&access_token=' + mapboxgl.accessToken;
  $.ajax({
    method: 'GET',
    url: directionsRequest,
  }).done(function(data) {
    var route = data.routes[0].geometry;
    map.addLayer({
      id: 'route',
      type: 'line',
      source: {
        type: 'geojson',
        data: {
          type: 'Feature',
          geometry: route
        }
      },
      paint: {
        'line-width': 2
      }
    });
    // this is where the code from the next step will go
  });
}

The bicycle route should now appear on your map!

Add your origin and destination

Next, add two circles to show the start and end of your route. You can do this by adding two more layers after the response is returned. Place the following code directly after the code that adds your route:

map.addLayer({
  id: 'start',
  type: 'circle',
  source: {
    type: 'geojson',
    data: {
      type: 'Feature',
      geometry: {
        type: 'Point',
        coordinates: start
      }
    }
  }
});
map.addLayer({
  id: 'end',
  type: 'circle',
  source: {
    type: 'geojson',
    data: {
      type: 'Feature',
      geometry: {
        type: 'Point',
        coordinates: end
      }
    }
  }
});
// this is where the JavaScript from the next step will go

Add turn-by-turn instructions

Finally, you can add turn-by-turn instructions. To retrieve turn-by-turn instructions, you will need to alter your API request to include steps=true. Replace the current request with this new one:

var directionsRequest = 'https://api.mapbox.com/directions/v5/mapbox/cycling/' + start[0] + ',' + start[1] + ';' + end[0] + ',' + end[1] + '?steps=true&geometries=geojson&access_token=' + mapboxgl.accessToken;

In the directions response object, turn-by-turn instructions are stored in the routes property. You can find instructions inside routes > legs > steps > maneuver. Each instruction is a string that describes what the bicycle rider should do next along a route.

Start by adding another div to your HTML right below the div with id='map'. The id for this div will be instructions.

<div id='instructions'></div>

Next, add some CSS to style the div so it appears on the left side of your map and has a white background.

#instructions {
  position: absolute;
  margin: 20px;
  width: 25%;
  top: 0;
  bottom: 0;
  padding: 20px;
  background-color: rgba(255, 255, 255, 0.9);
  overflow-y: scroll;
  font-family: sans-serif;
}

Then, add some Javascript inside the getRoute function to select the div with the id instructions and create an array of all the steps found in the directions response object. Iterate through all steps and add the instruction for each step to the div using insertAdjacentHTML.

var instructions = document.getElementById('instructions');
var steps = data.routes[0].legs[0].steps;
steps.forEach(function(step) {
  instructions.insertAdjacentHTML('beforeend', '<p>' + step.maneuver.instruction + '</p>');
});

Finished product

Congratulations! You’ve used the Mapbox Directions API and Mapbox GL JS to add a bicycle route to a map.

Next steps

Now that you’ve had some practice with the Mapbox Directions API, check out additional options in the Directions API documentation or try adding more details to your application:

Don’t forget to explore other directions-related services like the Mapbox Matrix API and Optimization API.