Skip to main content

Directions v4

Legacy

v4 of the Directions API is a legacy product. It is no longer in active development. To learn more about Mapbox's newer web services APIs see the Directions v5 documentation.

The Mapbox Directions API will show you how to get where you're going. Routing is fundamental to business logistics and consumer applications. With the Directions API, you can:

  • calculate optimal driving, walking, and cycling routes
  • produce turn-by-turn directions
  • produce routes with up to 25 waypoints anywhere on earth

This API supports three different routing profiles:

  • mapbox.driving for car and motorcycle routing. This profile shows the fastest routes by preferring high-speed roads like highways.
  • mapbox.walking for pedestrian and hiking routing. This profile shows the optimal path by using sidewalks and trails.
  • mapbox.cycling for bicycle routing. This profile shows routes that are short and safer for cyclist, avoiding highways and preferring streets with bike lanes.
@import MapboxDirections;

MBDirections *directions = [[MBDirections alloc] initWithAccessToken:@"<#your access token#>"];
@import MapboxDirections;

// If you’ve already set `MGLMapboxAccessToken` in your Info.plist:
MBDirections *directions = [MBDirections sharedDirections];
import MapboxDirections

let directions = Directions(accessToken: "<#your access token#>")
import MapboxDirections

// If you’ve already set `MGLMapboxAccessToken` in your Info.plist:
let directions = Directions.shared

Swift and Objective-C support for Directions v4 is provided by the MapboxDirections.swift library.

Retrieve directions

Retrieve directions between waypoints. This can include both the route's geometry and instructions for each turn.

get
https://api.mapbox.com/v4/directions/{profile}/{waypoints}.json
URL ParameterDescription
profilerouting profile; either mapbox.driving, mapbox.walking, or mapbox.cycling
waypointsa semicolon-separated list of {longitude},{latitude} coordinate pairs to visit in order, containing at least two elements (origin and destination). There can be anywhere between two and 25 coordinate pairs in the list.
Query ParameterDescription
alternatives
(optional)
whether to generate alternative routes; can be true or false
instructions
(optional)
format to return route instructions; can be text (default) or html
geometry
(optional)
format to return route geometry; can be geojson (default), polyline for an encoded polyline, or false to omit geometry from response
steps
(optional)
whether to include steps in response; can be true or false

Polylines are encoded with a precision level of 6: be sure to configure your decoding library to use 6 precision. Polyline decoding libraries exist for JavaScript, Swift, Ruby, and many other languages.

Example request

curl "https://api.mapbox.com/v4/directions/mapbox.driving/-122.42,37.78;-77.03,38.91.json"
>>> from Mapbox import Directions
>>> service = Directions()
>>> origin = {
... 'type': 'Feature',
... 'properties': {'name': 'Portland, OR'},
... 'geometry': {
... 'type': 'Point',
... 'coordinates': [-122.7282, 45.5801]}}
>>> destination = {
... 'type': 'Feature',
... 'properties': {'name': 'Bend, OR'},
... 'geometry': {
... 'type': 'Point',
... 'coordinates': [-121.3153, 44.0582]}}
>>> response = service.directions([origin, destination],
... 'mapbox.driving')
var mapboxClient = new MapboxClient('ACCESSTOKEN');
mapboxClient.getDirections(
[
{ latitude: 33.6, longitude: -95.4431 },
{ latitude: 33.2, longitude: -95.4431 }
],
function (err, res) {
// res is a document with directions
}
);
# get walking directions
mapbox directions "[-122.681032, 45.528334]" "[-122.71679, 45.525135]" --profile mapbox.walking
NSArray<MBWaypoint *> *waypoints = @[
[[MBWaypoint alloc] initWithCoordinate:CLLocationCoordinate2DMake(38.9099711, -77.0361122) name:@"Mapbox"],
[[MBWaypoint alloc] initWithCoordinate:CLLocationCoordinate2DMake(38.8977, -77.0365) name:@"White House"],
];
MBRouteOptions *options = [[MBRouteOptionsV4 alloc] initWithWaypoints:waypoints profileIdentifier:MBDirectionsProfileIdentifierCycling];
options.includesSteps = YES;

NSURLSessionDataTask *task = [directions calculateDirectionsWithOptions:options completionHandler:^(NSArray<MBWaypoint *> * _Nullable waypoints, NSArray<MBRoute *> * _Nullable routes, NSError * _Nullable error) {
MBRoute *route = routes.firstObject;
MBRouteLeg *leg = route.legs.firstObject;
if (leg) {
NSLog(@"Route via %@:", leg);

NSLengthFormatter *distanceFormatter = [[NSLengthFormatter alloc] init];
NSString *formattedDistance = [distanceFormatter stringFromMeters:leg.distance];

NSDateComponentsFormatter *travelTimeFormatter = [[NSDateComponentsFormatter alloc] init];
travelTimeFormatter.unitsStyle = NSDateComponentsFormatterUnitsStyleShort;
NSString *formattedTravelTime = [travelTimeFormatter stringFromTimeInterval:route.expectedTravelTime];

NSLog(@"Distance: %@; ETA: %@", formattedDistance, formattedTravelTime);

for (MBRouteStep *step in leg.steps) {
NSString *formattedDistance = [distanceFormatter stringFromMeters:step.distance];
NSLog(@"%@ %@", step.instructions, formattedDistance);
}
}
}];
let waypoints = [
Waypoint(
coordinate: CLLocationCoordinate2D(latitude: 38.9099711, longitude: -77.0361122),
name: "Mapbox"),
Waypoint(
coordinate: CLLocationCoordinate2D(latitude: 38.8977, longitude: -77.0365),
name: "White House"),
]
let options = RouteOptionsV4(waypoints: waypoints, profileIdentifier: .cycling)
options.includesSteps = true

let task = directions.calculate(options) { (waypoints, routes, error) in
guard error == nil else {
print("Error calculating directions: \(error!)")
return
}

if let route = routes?.first, let leg = route.legs.first {
print("Route via \(leg):")

let distanceFormatter = LengthFormatter()
let formattedDistance = distanceFormatter.string(fromMeters: route.distance)

let travelTimeFormatter = DateComponentsFormatter()
travelTimeFormatter.unitsStyle = .short
let formattedTravelTime = travelTimeFormatter.string(from: route.expectedTravelTime)

print("Distance: \(formattedDistance); ETA: \(formattedTravelTime!)")

for step in leg.steps {
print("\(step.instructions)")
let formattedDistance = distanceFormatter.string(fromMeters: step.distance)
print("— \(formattedDistance) —")
}
}
}

Example response

The response to a directions request is a JSON object with the following properties:

{
"origin": {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-122.42001342773438, 37.780094146728516]
},
"properties": { "name": "McAllister Street" }
},
"destination": {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-122.41999816894531, 37.77000045776367]
},
"properties": { "name": "Duboce Avenue" }
},
"waypoints": [],
"routes": [
{
"distance": 1239,
"duration": 111,
"summary": "Van Ness Avenue (US 101) - Otis Street",
"geometry": {
"type": "LineString",
"coordinates": [
[-122.420017, 37.780096],
[-122.42016, 37.780081],
[-122.420324, 37.780074],
[-122.420197, 37.770403],
[-122.420184, 37.770132],
[-122.42018, 37.769996],
[-122.419998, 37.77]
]
},
"steps": [
{
"maneuver": {
"type": "depart",
"location": {
"type": "Point",
"coordinates": [-122.420017, 37.780096]
},
"instruction": "Head west on McAllister Street"
},
"distance": 28,
"duration": 9,
"way_name": "McAllister Street",
"direction": "W",
"heading": 268,
"mode": "driving"
},
{
"maneuver": {
"type": "bear right",
"location": {
"type": "Point",
"coordinates": [-122.418702, 37.773081]
},
"instruction": "Bear right onto Otis Street"
},
"distance": 358,
"duration": 24,
"way_name": "Otis Street",
"direction": "SW",
"heading": 223,
"mode": "driving"
},
{
"maneuver": {
"type": "arrive",
"location": {
"type": "Point",
"coordinates": [-122.419998, 37.77]
},
"instruction": "You have arrived at your destination"
}
}
]
}
]
}
  • origin: a GeoJSON Feature with a Point geometry type representing the starting point of the route. Must have a name property, but more properties are also acceptable.
  • destination: as above, but representing the final destination of the route.
  • waypoints: an array of GeoJSON Feature Objects, as above, representing intermediate waypoints.
  • routes: an array containing the recommended (fastest) route and, at most, one alternative route. Each element is a JSON object with the following properties:
    • distance: the distance of the route, in meters
    • duration: the estimated travel time, in seconds
    • summary: a short, human-readable summary of the route
    • geometry: the geometry of the route as either a GeoJSON LineString or encoded polyline with precision 6
    • steps: an array of route steps -- maneuvers like turns or merges followed by a distance of travel to the next step. Each element is a JSON object with the following properties:
      • distance: the distance to the next maneuver, in meters
      • duration: the estimated travel time to the next maneuver, in seconds
      • way_name: the road or path the maneuver is on
      • direction: the rough cardinal direction of travel following the maneuver ('N', 'NE', 'E', 'SE', 'S', 'SW', 'W', or 'NW')
      • heading: the clockwise angle from true north to the direction of travel following the maneuver
      • maneuver: a JSON object representing the maneuver with the following properties:
        • type: the type of maneuver; one of: continue, bear right, turn right, sharp right, u-turn, sharp left, turn left, bear left, waypoint, depart, enter roundabout, and arrive. New maneuver types may be introduced in the future without an API version change.
        • location: a GeoJSON Point geometry where the maneuver is located.
        • instruction: human-readable text or HTML describing the maneuver. See the instructions parameter above.
        • mode: the mode of transportation. Possible values as follows:
          • For driving: driving, ferry, movable bridge, unaccessible
          • For walking: walking, ferry, unaccessible
          • For cycling: cycling, walking, ferry, train, moveable bridge, unaccessible