Skip to main content

Optimization API v1

Public Beta for the Optimization v2 API

Mapbox is launching a Beta program for the Optimization v2 API with many new features,including time window constraints, vehicle capacity limits, driver shifts, and pickup and drop off constraints.If you are interested in early access to the Optimization v2 API Beta, sign up here. Refer to the Optimization v2 API documentation for more details.

The Mapbox Optimization API returns a duration-optimized route between the input coordinates. This is also known as solving the Traveling Salesperson Problem. A typical use case for the Optimization API is planning the route for deliveries in a city. You can retrieve a route for car driving, bicycling, and walking.

Retrieve an optimization

get
https://api.mapbox.com/optimized-trips/v1/{profile}/{coordinates}

A call to this endpoint retrieves a duration-optimized route between input coordinates.

Required parametersTypeDescription
profilestringA Mapbox Directions routing profile ID.
Profile IDDescription
mapbox/drivingCar travel times, distances, or both
mapbox/walkingPedestrian and hiking travel times, distances, or both
mapbox/cyclingBicycle travel times, distances, or both
mapbox/driving-trafficCar travel times, distances, or both as informed by traffic data
coordinatesnumberA semicolon-separated list of {longitude},{latitude} coordinates. There must be between two and 12 coordinates. The first coordinate is the start and end point of the trip by default.

You can further refine the results from this endpoint with the following optional parameters:

Optional parametersTypeDescription
annotationsstringReturn additional metadata along the route. You can include several annotations as a comma-separated list. Must be used in combination with overview=full.
Possible valuesDescription
durationThe duration between each pair of coordinates, in seconds
distanceThe distance between each pair of coordinates, in meters
speedThe speed between each pair of coordinates, in meters per second
approachesstringA semicolon-separated list indicating the side of the road from which to approach waypoints in a requested route. Accepts unrestricted (default, route can arrive at the waypoint from either side of the road) or curb (route will arrive at the waypoint on the driving_side of the region). If provided, the number of approaches must be the same as the number of waypoints. But, you can skip a coordinate and show its position in the list with the ; separator. Must be used in combination with steps=true.
bearingsintegerInfluences the direction in which a route starts from a waypoint. Used to filter the road segment on which a waypoint will be placed by direction. This is useful for making sure the new routes of rerouted vehicles continue traveling in their current direction. A request that does this would provide bearing and radius values for the first waypoint and leave the remaining values empty. Must be used in combination with the radiuses parameter. Takes 2 values per waypoint: an angle clockwise from true north between 0 and 360, and the range of degrees by which the angle can deviate (recommended value is 45° or 90°), formatted as {angle, degrees}. If provided, the list of bearings must be the same length as the list of waypoints. But, you can skip a coordinate and show its position in the list with the ; separator.
destinationstringSpecify the destination coordinate of the returned route. Accepts any (default) or last.
distributionsintegerSpecify pick-up and drop-off locations for a trip by providing a ; delimited list of number pairs that correspond with the coordinates list. The first number of a pair indicates the index to the coordinate of the pick-up location in the coordinates list, and the second number indicates the index to the coordinate of the drop-off location in the coordinates list. Each pair must contain exactly 2 numbers, which cannot be the same. The returned solution will visit pick-up locations before visiting drop-off locations. The first location can only be a pick-up location, not a drop-off location.
geometriesstringThe format of the returned geometry. Allowed values are: geojson (as LineString), polyline (default, a polyline with precision 5), polyline6 (a polyline with precision 6).
languagestringThe language of returned turn-by-turn text instructions. See supported languages. The default is en (English).
overviewstringThe type of the returned overview geometry. Can be full (the most detailed geometry available), simplified (default, a simplified version of the full geometry), or false (no overview geometry).
radiusesnumber or stringThe maximum distance a coordinate can be moved to snap to the road network, in meters. There must be as many radiuses as there are coordinates in the request, each separated by ;. Values can be any number greater than 0 or the string unlimited. A NoSegment error is returned if no routable road is located within the radius.
sourcestringThe coordinate at which to start the returned route. Accepts any (default) or first.
stepsbooleanWhether to return steps and turn-by-turn instructions (true) or not (false, default).
roundtripbooleanIndicates whether the returned route is round trip, meaning the first coordinate is both the start and end point of the route (true, default) or not (false). If roundtrip=false, the source and destination parameters are required but not all combinations will be possible. See the Fixing start and end points section below for additional notes.

Unrecognized options in the query string result in an InvalidInput error.

Note that routes returned by the Optimization API will behave as if each waypoint setscontinue_straight=false, meaning that the route will continue in the same direction of travel. See the continue_straight parameter in the Directions API for more details on what this means for the route.

Fixing start and end points

You can explicitly set the start or end coordinate of the trip:

  • When source=first, the first coordinate is used as the start coordinate of the trip in the output.
  • When destination=last, the last coordinate is used as the destination coordinate of the trip in the output.
  • If you specify any for source or destination, any of the coordinates can be used as the first or last coordinate in the output.
  • If source=any&destination=any, the returned round trip will start at the first input coordinate by default.

Not all combinations of roundtrip, source, and destination are supported. Right now, the following combinations are possible:

roundtripsourcedestinationsupported
truefirstlastyes
truefirstanyyes
trueanylastyes
trueanyanyyes
falsefirstlastyes
falsefirstanyno
falseanylastno
falseanyanyno

Example request: Retrieve an optimization

# Request an optimized car trip with no additional options

$ curl "https://api.mapbox.com/optimized-trips/v1/mapbox/driving/-122.42,37.78;-122.45,37.91;-122.48,37.73?access_token=YOUR_MAPBOX_ACCESS_TOKEN"

# Request an optimized bicycle trip with steps and a GeoJSON response

$ curl "https://api.mapbox.com/optimized-trips/v1/mapbox/cycling/-122.42,37.78;-122.45,37.91;-122.48,37.73?steps=true&geometries=geojson&access_token=YOUR_MAPBOX_ACCESS_TOKEN"

# Request an optimized car round trip in Berlin with four coordinates, starting at the first coordinate pair and ending at the last coordinate pair

$ curl "https://api.mapbox.com/optimized-trips/v1/mapbox/driving/13.388860,52.517037;13.397634,52.529407;13.428555,52.523219;13.418555,52.523215?source=first&destination=last&roundtrip=true&access_token=YOUR_MAPBOX_ACCESS_TOKEN"

# Request an optimized car trip with four coordinates and one distributions constraint where the last given coordinate must be visited before the second

$ curl "https://api.mapbox.com/optimized-trips/v1/mapbox/driving/13.388860,52.517037;13.397634,52.529407;13.428555,52.523219;13.418555,52.523215?roundtrip=true&distributions=3,1&access_token=YOUR_MAPBOX_ACCESS_TOKEN"

# Request an optimized car trip with specified waypoint approach bearings and turn-by-turn instructions

$ curl "https://api.mapbox.com/optimized-trips/v1/mapbox/driving/-122.42,37.78;-122.45,37.91;-122.48,37.73?radiuses=unlimited;unlimited;unlimited&bearings=45,90;90,1;340,45&steps=true&access_token=YOUR_MAPBOX_ACCESS_TOKEN"

Response: Retrieve an optimization

The response to an Optimization API request is a JSON object that contains the following properties:

PropertyTypeDescription
codestringIndicates the state of the response. This is a separate code than the HTTP status code. On normal valid responses, the value will be Ok.
waypointsarrayAn array of waypoint objects. Each waypoint is an input coordinate snapped to the road and path network. The waypoints appear in the array in the order of the input coordinates.
tripsarrayAn array of 0 or 1 trip objects.

Waypoint objects

A waypoint object is an input coordinate snapped to the roads network that contains the following properties:

PropertyTypeDescription
namestringThe name of the road or path that the input coordinate snapped to.
locationarrayAn array containing the [longitude, latitude] of the snapped coordinate.
trips_indexintegerThe index of the trip object that contains this waypoint in the trips array.
waypoint_indexintegerThe index of the position of the given waypoint within the trip.

Trip object

A trip object describes a route through multiple waypoints, and has the following properties:

PropertyTypeDescription
geometrystringDepending on the geometries parameter, this is either a GeoJSON LineString or a Polyline string. Depending on the overview parameter, this is the complete route geometry (full), a simplified geometry to the zoom level at which the route can be displayed in full (simplified), or is not included (false).
legsarrayAn array of route leg objects.
weightnumberA float indicating the weight in units described by weight_name. Each road potentially included in a route is assigned a weight value, and the Optimization API returns the route that has the smallest possible total weight.
weight_namestringA string indicating which weight the API used to determine the returned route. The default weight is routability, which is duration-based, with additional penalties for less desirable maneuvers.
durationnumberA float indicating the estimated travel time, in seconds.
distancenumberA float indicating the distance traveled, in meters.

A trip object has the same format as a route object in the Directions API.

Example response object

{
"code": "Ok",
"waypoints": [
{
"name": "North Lake Boulevard",
"location": [-120.141159, 39.170872],
"waypoint_index": 0,
"trips_index": 0
},
{
"name": "Virginia Drive",
"location": [-120.14984, 39.159985],
"waypoint_index": 2,
"trips_index": 0
},
{
"name": "Fairway Drive",
"location": [-120.150648, 39.340689],
"waypoint_index": 1,
"trips_index": 0
}
],
"trips": [
{
"geometry": "}panFfahSia@bp@nDcCpYbCqYou@uDsP_U",
"legs": [
{
"summary": "",
"weight": 1962.8,
"duration": 1876.9,
"steps": [],
"distance": 31507.9
},
{
"summary": "",
"weight": 2211.9,
"duration": 2035.1,
"steps": [],
"distance": 32720.5
},
{
"summary": "",
"weight": 283.5,
"duration": 238.1,
"steps": [],
"distance": 1885.2
}
],
"weight_name": "routability",
"weight": 4458.2,
"duration": 4150.1,
"distance": 66113.6
}
]
}

Supported libraries: Retrieve an optimization

Mapbox wrapper libraries help you integrate Mapbox APIs into your existing application. The following SDK supports this endpoint:

See the SDK documentation for details and examples of how to use the relevant methods to query this endpoint.

Optimization v1 API errors

On error, the server responds with different HTTP status codes:

  • For responses with HTTP status codes lower than 500, the JSON response body includes the code property, which may be used by client programs to manage control flow. The response body may also include a message property with a human-readable explanation of the error.
  • If a server error occurs, the HTTP status code will be 500 or higher and the response will not include a code property.
Response body codeHTTP status codeDescription
Ok200Normal success case.
NoRoute200There was no route found for the given coordinates. Check for impossible routes (for example, routes over oceans without ferry connections) or incorrectly formatted coordinates.
NoTrips200For one coordinate, no route to other coordinates available. Check for impossible routes (for example, routes over oceans without ferry connections).
NotImplemented200For the given combination of source, destination, and roundtrip, this request is not supported.
NoSegment200No road segment could be matched for one or more coordinates within the supplied radiuses. Check for coordinates that are too far away from a road.
Not Authorized - No Token401No token was used in the query.
Not Authorized - Invalid Token401Check the access token you used in the query.
Forbidden403There may be an issue with your account. Check your Account page for more details.

In some cases, using an access tokens with URL restrictions can also result in a 403 error. For more information, see our Token management guide.
ProfileNotFound404Use a valid profile as described in Retrieve an optimization.
InvalidInput422The given request was not valid. The message key of the response will hold an explanation of the invalid input.

All other properties might be undefined.

Optimization v1 API restrictions and limits

  • Maximum 12 coordinates per request
  • Maximum 25 distributions per request
  • Maximum 300 requests per minute
If you require a higher rate limit, contact us.

Optimization v1 API pricing

  • Billed by requests
  • See rates and discounts per Optimization API request in the pricing page's Navigation section

Usage of the Optimization API is measured in API requests. A request that contains multiple waypoints is billed as a single API request. Details about the number of Optimization API requests included in the free tier and the cost per request beyond what is included in the free tier are available on the pricing page.

Was this page helpful?