Introduction

The Mapbox web services? APIs allow for programmatic access to Mapbox tools
and services. Use these APIs to retrieve information about your account,
upload and change resources, and use core Mapbox tools, like geocoding? and
directions.

This documentation provides examples of six different techniques for accessing
Mapbox web services APIs:

Each library’s documentation provides information on installing the library and
how to use it.

This is REST API documentation: it’s the most technical level of documentation
for Mapbox’s web services. If you're looking to use a map in an application,
you probably want to use a library like Mapbox GL JS or Mapbox Mobile
instead. The APIs described in this document are subject to Mapbox's
Terms of Service.

Reading this Documentation

This documentation is structured by API, which is a group of related functionality
like Geocoding or Uploads, and then by endpoint, which
is a specific method within that API that performs one action and is located
at a specific URL.

Each endpoint in this documentation is described using several parts:

The HTTP method: includes GET, POST, PUT, PATCH, DELETE

The path: for instance, /geocoding/v5/{mode}/{query}.json

URL parameters: these are the parts of the endpoint path wrapped in brackets,
like {mode} in this example.

Query parameters: contained in a table with an Option header, these are added
to the query string part of the request.

A token scope, if one is required.

All URLs referenced in the documentation have the base path https://api.mapbox.com.
This base path goes before the endpoint path. In this example, you'd
combine https://api.mapbox.com and /geocoding/v5/{mode}/{query}.json to get
the request URL https://api.mapbox.com/geocoding/v5/{mode}/{query}.json.

For this endpoint, {mode} and {query} are the URL parameters. In a request,
you replace their placeholders with real values: for instance, you'd choose
mapbox.places as your mode and Chester as your query, and get the URL
https://api.mapbox.com/geocoding/v5/mapbox.places/Chester.json

Query parameters are added to the end of the URL with query string encoding.
If you wanted to add the country query parameter to that Geocoding? request, you'd
the query string ?country=us to the end of the URL, producing
https://api.mapbox.com/geocoding/v5/mapbox.places/Chester.json?country=us.

All endpoints require an access token?, which is provided as a query parameter.
So the final geocoding request you would construct would look like
https://api.mapbox.com/geocoding/v5/mapbox.places/Chester.json?country=us&access_token=pk.my-token-value
The next section covers how you get and use access tokens.

https://api.mapbox.com

Access tokens

Access to Mapbox web services? requires an access token that connects API
requests to your account. The example requests in this documentation don't include
an access token?: you will need to supply one using the access_token query
option or by specifying the token in the SDK or library.

When creating a new access token, you have the option of adding one or more scopes.
Each scope adds a different permission to the token, allowing it to be used to
access restricted APIs. Throughout the documentation, we specify the scope
required to access each endpoint.

Access token example

https://api.mapbox.com/{endpoint}?access_token=

Versioning

Each Mapbox API is versioned with a version string specified in the base URL that
can be incremented independently from other APIs.

The Maps API is an exception: its endpoint is prefixed
with /v4/{map_id} instead of putting the version after the API name.
This mismatch will be fixed in the next API version.

Using the newest available API is always encouraged.

These changes are considered backwards compatible and will
not require the version string to be incremented:

Adding properties to JSON objects.

Changing the number of items returned in a single listing request.

Changing rate limiting thresholds.

The structure or length of identifiers generated by the API.

Changing error messages.

These changes are considered backwards incompatible and will require
the version string to be incremented:

Removing properties from JSON objects.

Changing an API's URL structure

In the event that certain functionality is deprecated, we will give at least
90 days notice via email. You will only receive a deprecation email if we
detect you are using part of the API that is being deprecated.

Versioning example

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

Rate limits

Mapbox APIs have rate limits that cap the number of requests
that can be made against an endpoint. If you exceed a rate limit, your
request will be throttled and you will receive HTTP 429 Too Many Requests
responses from the API.

Header

Description

X-Rate-Limit-Interval

Length of rate-limiting interval in seconds.

X-Rate-Limit-Limit

Maximum number of requests you may make in the current interval before reaching the limit.

X-Rate-Limit-Reset

Unix timestamp of when the current interval will end and the ratelimit counter is reset.

CORS

Mapbox web services? support Cross-Origin
Requests with no domain restrictions.
To support Internet Explorer 8 and 9, use a library that falls back to
XDomainRequest, like corslite.

Retina

Mapbox supports Retina image output on all APIs that serve images.
Add @2x before the file extension on a URL to request an image at
double scale. For instance, a map tile that is 256×256 pixels will be
512×512 pixels with @2x, but show the same content. When displayed
on a page, the image will be still sized to 256×256 pixels, but
4 pixels of the original will represent 1 pixel in screen units.

The @2x part of the URL goes before the entire format, so a URL
that ends in .png would end with @2x.png as a Retina image.

The only assets that are not available at Retina scale are tilesets
uploaded from TileMill? or as MBTiles?.

# a 400x200 static map
https://api.mapbox.com/v4/mapbox.dark/-76.9,38.9,5/400x200.png?access_token=
# the same static map for Retina
# displays: this image will be 800x400
# pixels, but show the same content
# and look the same when scaled down
https://api.mapbox.com/v4/mapbox.dark/-76.9,38.9,5/400x200@2x.png?access_token=

HTTPS

We recommend all access to Mapbox is over HTTPS. Except for the
Maps API, requests initiated over HTTP are automatically upgraded to HTTPS.

Pagination

Pagination lets you list many objects from an API by using more than one
request. After receiving a page of objects, the next page can be requested using
the next link relation in Link header
of the response. This process can be repeated until the server sends a response
without a Link header or without a next link relation, which signals the end
of the collection.

The
maximum
number of objects to return. The API will attempt to return the requested number of objects, but receiving fewer objects does not necessarily signal the end of the collection. Receiving a response with no
Link
header or no
next
link relation is the only way to determine when you are at the end of a collection.

Coordinates

Where geographic coordinates are provided to a Mapbox API, they should be formatted
in the order longitude, latitude and specified as decimal degrees in the WGS84
coordinate system. This pattern matches existing standards, including GeoJSON? and KML?.

The only exception to longitude, latitude ordering is the polyline format, supported
in Static (Classic) overlays and Directions responses. When polyline input
or output is specified, the polyline content should follow the Google Encoded Polyline format,
which specifies latitude, longitude ordering.

The Mapbox Swift libraries use the Core Location framework’s
CLLocationCoordinate2D
type to represent geographic coordinates. When initializing a
CLLocationCoordinate2D, always specify the latitude before the longitude.

Maps

The Mapbox Maps API supports reading raster tilesets, vector tilesets, and Mapbox Editor? project features.
Tilesets can be retrieved as images, TileJSON, or HTML slippy maps for embedding.
Mapbox Editor project features can be retrieved as GeoJSON? or KML?.

If you use Mapbox.js,
Mapbox GL JS, or another library like
Leaflet,
you're already using this API. This documentation is geared toward software developers
who want to programmatically read these resources: it isn't
necessary to read or understand this reference to design or use maps.

Mapbox classic map IDs

The following map IDs are accessible to all accounts using a valid access token?:

The {z}/{x}/{y} parameters are the tile coordinates as described
in the Slippy Map Tilenames
specification: they specify the tile's zoom level {z} and column {x} and row {y}.

The format of any image request can be replaced by any of the following formats
to adjust image quality for different bandwidth requirements. Higher-compression
formats like jpg70 or png32 can be useful to favor performance
over image quality.

Image format

Description

png

true color PNG

png32

32 color indexed PNG

png64

64 color indexed PNG

png128

128 color indexed PNG

png256

256 color indexed PNG

jpg70

70% quality JPG

jpg80

80% quality JPG

jpg90

90% quality JPG

You can prefix the format with @2x to request a high DPI version. The @2x
is placed after the {z}/{x}/{y} and before the ., like
1/0/0@2x.png

Tiles that include mapbox.satellite are always delivered as JPEG, even if the URL specifies PNG. The PNG
format can't efficiently encode photographic images like mapbox.satellite.

The response is an image tile in the specified format. For performance,
image tiles are delivered with a max-age header value set 12 hours in the future.

Style-optimized vector tiles

Vector tiles? can be further optimized by including a style ID with the tile request. If the style parameter is provided, we analyze the sources, filters, minzoom, and maxzoom properties of that style? and remove data from the vector tile that won't be visible on the map.

A style-optimized tile request requires a style parameter in the request. This style parameter is broken into two parts, the style ID and the style's recently edited timestamp. The timestamp parameter comes from the style JSON's modified property that is included with any style created with Mapbox Studio?.

Mapbox GL JS? can request style-optimized vector tiles that are hosted on Mapbox with a Mapbox Style JSON.

Optimized tiles remove unused layers and features. If you plan on dynamically modifying the style at runtime using Mapbox GL JS or Mapbox Mobile, broadening filters and zoom ranges won't work the same, since any data that isn't visible with the loaded style also won't be included in the data.

Retrieve an HTML slippy map

a comma-separated list of controls and map behaviors to be included in the map

hash
(optional)

a zoom level and location for the map in format
#{zoom}/{lat}/{lon}

Query Parameter

Description

zoomwheel

enable zooming with the mouse wheel

zoompan

enable zoom and pan controls

geocoder

add a geocoder control

share

add a share control

The response is HTML of a slippy map.

GET

/v4/{map_id}{/options}.html{hash}

Example request

# a map with zoom controls, mouse controls, a geocoder, and share
$ curl "https://api.mapbox.com/v4/mapbox.light/zoomwheel,zoompan,geocoder,share.html?access_token="# the same map without any options
$ curl "https://api.mapbox.com/v4/mapbox.light.html?access_token="

Retrieve features from Mapbox Editor projects

Retrieve vector features from Mapbox Editor? projects as GeoJSON? or KML?. GeoJSON
returns a FeatureCollection with features that conform to
the simplestyle-spec.

URL Parameter

Description

format

json
for GeoJSON,
kml
for KML

GET

/v4/{map_id}/features.{format}

Example request

$ curl "https://api.mapbox.com/v4/mapbox.dc-markers/features.json?access_token="# or the same dataset as KML
$ curl "https://api.mapbox.com/v4/mapbox.dc-markers/features.kml?access_token="

Retrieve features from vector tiles

Retrieve data about specific vector features at a specified location within a vector tileset?. The response body is a GeoJSON?FeatureCollection of features at or near the geographic point described by {lon},{lat} and within the distance described by the radius parameter. The geometry of the feature is not returned.

Query Parameter

Description

radius
(optional)

Approximate distance in meters to query for features. Defaults to
0
.

limit
(optional)

Number of features between 1-50 to return. Defaults to
5
.

The radius parameter has no upper bound and is required for queries against point and line data. Due to the nature of tile buffering, a query with a large radius made against equally large point or line data may not include all possible features in the results.

Restrictions and limits

Use of this endpoint is rate limited to 300 requests per minute. For a higher rate limit, contact us.

Exceeding the limits above will result in an HTTP 429 response. For information on rate limit headers, see Rate limits.

The original geometry of the result features will not be returned in the resultset. The geometry type in the response will be Point for all features returned in the FeatureCollection:

For Polygon and MultiPolygon features the geometry is the point at the queried lon,lat

For LineString and MultiLineString features the geometry is the nearest point on the feature within the radius threshold of lon,lat

For Point and MultiPoint features the geometry is the nearest point within the radius threshold of lon,lat

Features in the response body will include a tilequery object with the following additional properties:

Property

Description

distance

Approximate distance in meters from the feature result to the queried point.

Styles

The Mapbox Styles API lets you read and change map styles, fonts, and icons.
This API is the basis for Mapbox Studio,
our cartography software.

If you use Studio, Mapbox GL JS or
the Mapbox Mobile SDKs, you're already
using the Styles API. This documentation is geared toward software developers
who want to programmatically read & write these resources: it isn't
necessary to read or understand this reference to design or use maps.

You'll want to be familiar with the Mapbox Style Specification to use this API: it defines the structure of map styles and is the
open standard that helps Studio communicate with APIs and produce
maps compatible with our libraries (like GL JS and Mobile). When we refer to
style objects, they are objects that fit
the Mapbox Style Specification. You can see examples of these styles
in our mapbox-gl-styles project,
or you can create a new style? using Mapbox Studio.

Limits

Styles cannot reference more than 15 sources.

Styles cannot be larger than 5MB. This limit only applies to the style
document itself, not the sprites, fonts, tilesets, or other resources it
references.

Update a style

Requesting a style and then using the same content to update the style will
fail: you'll need to remove the created and modified properties before
updating a style. The name property, which is optional for style creation,
is required when updating a style. Cross-version PATCH requests are rejected.

Example request

Response

HTTP 204

Fonts

Two types of fonts are supported: TrueType fonts, usually with
.ttf file extensions, and OpenType fonts, with .otf extensions. The API
accepts fonts as raw binary data, allows those fonts to be deleted,
and generates encoded letters for map renderers.

Fonts are managed on a per-account basis: styles can use any font from the
same account.

Font limits

Fonts must be smaller than 30MB.

Accounts are limited to 100 fonts.

Retrieve font glyph ranges

Glyph ranges are usually not of interest unless you're building a map renderer,
but this is the endpoint where you can access them.

Font glyph ranges are protocol buffer-encoded signed distance fields. They can be used to
show fonts at a variety of scales and rotations. One glyph is used at all scales.

Example request

Response

A successful request will return HTTP 200 Success. The response body will be
a buffer of the glyphs with Content-Type: application/x-protobuf.

Sprites

Sprites are the way
that Mapbox GL JS? and Mapbox Mobile efficiently request and show icons. They are collections of icons that can be used in styles as markers or
patterns in symbol layers. Icons are SVG? images that can be added and removed
at will. The Styles API automatically collects these SVG images and renders
them into a single PNG image and a JSON document that describes where
each icon is positioned.

Sprites are managed on a per-style basis: each sprite belongs to a style,
so the sprite limit of 500 icons is also a per-style limit. All sprite-related
API methods will require a {style_id} parameter referring to the style? that sprite belongs to.

Retrieve a static map from a style

The position of the map is represented by 5 numbers: longitude, latitude,
zoom, bearing, and pitch. The last two numbers, bearing and pitch, are
optional: if you only specify bearing and not pitch, pitch will default to
0. If you specify neither, they will both default to 0.

URL Parameter

Description

overlay

one or more comma-separated features to draw on top of the map. These can be in
marker
,
geojson
or
path
format.

lon

longitude for the center point of the static map; number between
-180
and
180

lat

latitude for the center point of the static map; number between
-90
and
90

zoom

zoom level; number between
0
and
22
. Fractional zoom levels will be rounded to two decimal places.

bearing
(optional)

bearing: rotates the map around its center. number between
0
and
360
, interpreted as decimal degrees. 90 rotates the map 90° to the left. 180 flips the map. Defaults to
0
.

pitch
(optional)

pitch: tilts the map, producing a perspective effect. number between
0
and
60
. Defaults to
0
.

auto

If
auto
is added, the viewport will fit the bounds of the overlay. If used,
auto
replaces
lon
and
lat
.

width

width of the image; number between
1
and
1280

height

height of the image; number between
1
and
1280

@2x
(optional)

If
@2x
is added to request a retina 2x image will be returned

Query Parameter

Description

attribution
(optional)

boolean
value controlling whether there is attribution on the image; defaults to
true

logo
(optional)

boolean
value controlling whether there is a Mapbox logo on the image; defaults to
true

before_layer
(optional)

string
value for controlling where the
overlay
is inserted in the style. All overlays will be inserted before the specified layer.

Tiles and static images returned from this API will be one zoom level offset from tiles and static images returned from the Static (Classic) API. This is due to the size of the individual tiles being created -- this API creates 512px by 512px tiles and the Static Classic API creates 256px by 256px tiles. The offset was introduced to keep zoom level 0 the lowest zoom (one tile for the whole world).

Example: the tile at zoom level 0 from this API covers 512px by 512px. This is the same pixel area as zoom level 1 in the Static (Classic) API, where there are 4 tiles to fill the same space. The features shown in zoom level 0 of the Static API are matched identically to the features shown in zoom level 1 of the Static (Classic) API.

Overlay

An overlay is data that can be applied on top of the map at request time. These are comma separated and can be a mix of valid GeoJSON, a marker?, a custom marker or path. Overlays cannot consist of more than 100 features. The maximum overlay length is 2083 characters. The order of the features dictates their Z-order on the page. The last item in the list will have the highest Z-order (will overlap the other features in the list), and the first item in the list will have the lowest (will underlap the other features).

Marker

{name}-{label}+{color}({lon},{lat})

URL Parameter

Description

name

Marker shape and size. Options are
pin-s
,
pin-m
,
pin-l
.

label
(optional)

Marker symbol. Options are an alphanumeric label
a
through
z
,
0
through
99
, or a valid
Maki
icon. If a letter is requested, it will be rendered uppercase only.

color
(optional)

A 3- or 6-digit hexadecimal color code.

Custom marker

url-{url}({lon},{lat})

URL Parameter

Description

url

a percent-encoded URL for the image. Can be of type
PNG
or
JPG
.

Custom markers are cached according to the
Expires and Cache-Control headers. Make sure that at least one of these
headers is set to a proper value to prevent repeated requests for the custom
marker image.

The marker image is always centered on the specified location. When creating
an asymmetric marker like a pin, make sure that the tip of the pin is at the
center of the image.

GeoJSON

geojson({geojson})

The {geojson} argument must be a valid GeoJSON object.
simplestyle-spec styles for
GeoJSON? features will be respected and rendered.

Use of the raster tiles endpoint is rate-limited by access token?. By default, the rate limit is set to 2,000 requests per minute. Exceeding the limit will result in an HTTP 429 response. For information on rate limit headers, see Rate limits.

512px vs 256px tiles

By default, the API will return 512x512 pixel tiles. 512x512 image tiles are offset by 1 zoom level compared to 256x256 tiles from Mapbox Editor? projects or Mapbox Studio Classic? styles. For example, 512x512 tiles at zoom level 4 are equivalent to Mapbox Editor projects or Mapbox Studio Classic styles tiles at zoom level 5. If the @2x parameter is included, tiles are scaled to 1024x1024 pixels. 256x256 tiles from the endpoint are one quarter of the size of 512x512 tiles and thus require 4 times as many API requests and accumulate 4 times as many map views to render the same area.

Example request

Uploads

The Mapbox Uploads API transforms geographic data into tilesets that can
be used with maps and geographic applications. Given a wide variety
of geospatial formats, it normalizes projections and generates tiles
at multiple zoom levels to make data viewable on the web.

The upload workflow begins with a file and ends with a tileset?, or if you
have invalid data, an error.

Retrieve S3 credentials to stage the file

Use an S3 client, like the AWS SDK, to upload a file to S3 using
those credentials

Create an upload using the staged file's URL

Retrieve the upload's status as it is processed into a tileset

Once the upload is complete, use the tileset ID like you'd use any other tileset

Limits

Type

Size limit

TIFF and GeoTIFF

10 GB

MBTiles

25 GB

GeoJSON

1 GB

CSV

1 GB

KML

260 MB

GPX

260 MB

Shapefile (zipped)

260 MB

Mapbox Dataset

1 GB

Retrieve S3 credentials

Mapbox provides an Amazon S3 bucket to stage your file while your upload
is processed. Uploads must be staged in this bucket before being uploaded to
your Mapbox account. You can retrieve temporary credentials from this endpoint.

The response body is a JSON object containing the following properties.

Property

Description

accessKeyId

AWS Access Key ID

bucket

S3 bucket name

key

unique key for data to be staged

secretAccessKey

AWS Secret Access Key

sessionToken

temporary security token

url

destination URL of the file

Use these credentials to store your data in the provided bucket with the provided
key using the AWS CLI or AWS SDK of your choice. The bucket is located in AWS region us-east-1.

Example response

Retrieve upload status

Upload processing is fast but not immediate. Once an upload is created, you can
track its status. Uploads have a progress property that will start at 0
and end at 1 when an upload is complete. If there's an error processing
an upload, the error property will include an error message.

Example response

Retrieve recent upload statuses

You can retrieve multiple upload statuses at the same time, sorted
by the most recently created. This request returns the same information
as individual upload status, but for all recent uploads. The list is
limited to 1MB of JSON.

This endpoint supports pagination so that you can list
many uploads. Up to 100 items can be requested at a time using the limit
parameter. It also supports another parameter, reverse:

Query Parameter

Description

reverse

List uploads in chronological order, rather than reverse chronological order.

Remove an upload

Remove a completed upload status from the upload listing.

Uploads are only statuses: removing an upload from the listing doesn't
delete the associated tileset?. Tilesets can only be
deleted from within Mapbox Studio?.
An upload cannot be removed until it is completed.

Example request

Example response

HTTP 204

Datasets

A dataset is an editable collection of GeoJSON features.
The Datasets API offers persistent storage for custom geographic data and supports
reading, creating, updating, and removing features. The goal of this API is to let you manage your geodata using Mapbox. To serve this data at scale, convert your dataset? into a tileset? using the Uploads API.

Using the Datasets API involves interacting with two types of resources:
datasets and features. Datasets contain a collection of features.

The dataset object

A dataset contains information about the dataset?. Each dataset contains the following properties:

Property

Description

owner

the username of the dataset owner

id

id for an existing dataset

created

date and time the dataset was created

modified

date and time the dataset was last modified

bounds

the extent of features in the dataset as an array of west, south, east, north coordinates

Example request

curl "https://api.mapbox.com/datasets/v1/{username}/{dataset_id}/features?access_token="# using pagination to only list 10 features
curl "https://api.mapbox.com/datasets/v1/{username}/{dataset_id}/features?limit=10&access_token="# using pagination to start the listing after feature with the id f6d9
curl "https://api.mapbox.com/datasets/v1/{username}/{dataset_id}/features?start=f6d9&access_token="

Insert or update a feature

Inserts or updates a feature in a dataset?. If there's already a feature
with the given ID in the dataset, it will be replaced. If there isn't
a feature with that ID, a new feature is created.

If you are inserting a feature, you must add the feature as the body of the PUT request. This should be one individual GeoJSON? feature and not a GeoJSON FeatureCollection. If the GeoJSON feature has a top-level id property, it must match the feature_id you use in the URL endpoint.

Filter results visibility, either
public
or
private
. Private tilesets require an access token belonging to the owner, while public tilesets may be requested with an access token belonging to any user.

sortby

Sort the listing by
created
or
modified
timestamps.

limit

The
maximum
number of objects to return. An integer between 1 and 500 is expected, defaults to 100. See
pagination
for details

Reverse geocoding turns geographic coordinates into place names,
turning -77.050, 38.889 into 2 Lincoln Memorial Circle NW. These place names
can vary from specific addresses to states and countries that contain
the given coordinates.

Queries are limited to either a total of 20 words and numbers separated by spacing and punctuation or 256 characters.

If you use the optional bounding box? parameter to filter? results, note that the bounding box cannot cross the 180th meridian.

Request format

Both geocoding? and reverse geocoding requests have the same basic format. Since
the {query} parameter can contain any value, it should be URL-encoded UTF-8.

URL Parameter

Description

query

a location; a place name for forward geocoding or a coordinate pair (longitude, latitude) for reverse geocoding

mode

mapbox.places
for ephemeral geocoding or
mapbox.places-permanent
for storing results and batch geocoding

Query Parameter

Description

country
(optional)

Limit results to one or more countries. Options are
ISO 3166 alpha 2
country codes separated by commas.

proximity
(optional)

Bias local results based on a provided location. Options are
longitude,latitude
coordinates.

types
(optional)

Filter results by one or more feature types. Options are
country
,
region
,
postcode
,
district
,
place
,
locality
,
neighborhood
,
address
,
poi
, and
poi.landmark
. Note that
poi.landmark
returns a subset of the results returned by
poi
. Multiple options can be comma-separated.

autocomplete
(optional)

Return autocomplete results or not. Options are
true
or
false
and the default is
true
.

bbox
(optional)

Limit results to a bounding box. Options are in the format
minX,minY,maxX,maxY
.

limit
(optional)

Limit the number of results returned. The default is
5
for forward geocoding and
1
for reverse geocoding.

language
(optional)

Specify the language to use for response text and, for forward geocoding, query result weighting. Options are
IETF language tags
comprised of a mandatory
ISO 639-1 language code
and optionally one or more IETF subtags for country or script. More than one value can also be specified, separated by commas.

The {proximity} parameter biases search results within 5 miles of a specific
location given in {longitude},{latitude} coordinates. Results will not be
filtered by location or ordered by distance, but location will be considered
along with textual relevance and other criteria when scoring and sorting
results.

The {autocomplete} parameter controls whether autocomplete results
are included. Autocomplete results can partially match the query: for example,
searching for washingto could include washington even though only
the prefix matches. Autocomplete is useful for offering fast, type-ahead
results in user interfaces. If your queries represent complete addresses or
place names, you can disable this behavior and exclude partial matches by
setting the {autocomplete} parameter to false.

The {limit} parameter specifies the maximum number of results to
return. For forward geocoding, the default is 5 and the maximum is
10. For reverse geocoding, the default is 1 and the maximum is 5.
If a limit other than 1 is used for reverse geocoding, a single types
option must also be specified.

The {language} parameter specifies the desired response language for user
queries. For forward geocodes, results that match the requested language are
favored over results in other languages. If more than one language tag is
supplied, text in all requested languages will be returned. For forward
geocodes with more than one language tag, only the first language will be used
to weight results.

Any valid IETF language tag can be submitted, and a best effort will be made to
return results in the requested language or languages, falling back first to
similar and then to common languages in the event that text is not available in
the requested language. In the event a fallback language is used, the language
field will have a different value than the one requested.

Translation availability varies by language and region:

Global coverage:these languages are almost always present for country, region, and prominent place features

Language

de
German

en
English

fr
French

it
Italian

nl
Dutch

Local coverage:these languages may lack global coverage but are almost always present for country, region, and prominent place features where they are widely used

Language

bs
Bosnian

bg
Bulgarian

ca
Catalan

cs
Czech

da
Danish

el
Greek

et
Estonian

fi
Finnish

ka
Georgian

he
Hebrew

hu
Hungarian

is
Icelandic

ja
Japanese

ko
Korean

lt
Lithuanian

lv
Latvian

mn
Mongolian

nb
Norwegian Bokmål

pl
Polish

pt
Portuguese

ro
Romanian

ru
Russian

sk
Slovak

sl
Slovenian

sr
Serbian

sv
Swedish

tl
Tagalog

th
Thai

uk
Ukrainian

zh-Hans
Simplified Chinese

zh-Hant
Traditional Chinese

Limited coverage:these languages are sometimes present but coverage tends to be inconsistent or geographically constrained

Language

ar
Arabic

es
Spanish

fa
Persian

kk
Kazakh

ms
Malay

sq
Albanian

tr
Turkish

uz
Uzbek

vi
Vietnamese

GET

/geocoding/v5/{mode}/{query}.json

Response object

Because Mapbox's geocoding? data is constantly updated and improved, the values of properties in the response object are not guaranteed and may change within the same version of the API. Properties may be added to but will not be removed from the response within the same version. Geocoding results are returned
in Carmen GeoJSON format.

An array of space and punctuation-separated strings from the original query.

features

An array of feature objects.

attribution

A string attributing the results of the Mapbox Geocoding API to Mapbox and links to Mapbox's terms of service and data sources.

Feature object

Each feature object in the "features" array may have the properties described below. Forward geocodes return features ordered by relevance. Reverse geocodes return features in order of index hierarchy from most specific features to least specific features that overlap the queried coordinates.

Property

Description

id

A string feature id in the form
{type}.{id}
where
{type}
is the lowest hierarchy feature in the
place_type
field. The
{id}
suffix of the feature id is unstable and may change within versions.

An array of feature types describing the feature. Options are
country
,
region
,
postcode
,
district
,
place
,
locality
,
neighborhood
,
address
,
poi
, and
poi.landmark
. Most features have only one type, but if the feature has multiple types, (for example, Vatican City is a
country
,
region
, and
place
), all applicable types will be listed in the array.

relevance

A numerical score from 0 (least relevant) to 0.99 (most relevant) measuring how well each returned feature matches the query. You can use the
relevance
property to remove results which don't fully match the query.

address
(optional)

A string of the house number for the returned
address
feature. Note that unlike the
address
property for
poi
features, this property is outside the
properties
object.

properties

An object describing the feature. The property object is unstable and only
Carmen GeoJSON
properties are guaranteed. Your implementation should check for the presence of these values in a response before it attempts to use them.

properties.address
(optional)

A string of the full street address for the returned
poi
feature. Note that unlike the
address
property for
address
features, this property is inside the
properties
object.

properties.category
(optional)

A string of comma-separated categories for the returned
poi
feature.

properties.tel
(optional)

A formatted string of the telephone number for the returned
poi
feature.

properties.maki
(optional)

The name of a suggested
Maki
icon to visualize a
poi
feature based on its
category
.

properties.landmark
(optional)

A boolean value indicating whether a
poi
feature is a landmark. Landmarks are particularly notable or long-lived features like schools, parks, museums and places of worship.

A string representing the feature in the requested language, if specified.

place_name

A string representing the feature in the requested language, if specified, and its full result hierarchy.

matching_text
(optional)

A string analogous to the
text
field that more closely matches the query than results in the specified language. For example, querying "Köln, Germany" with language set to English might return a feature with the
text
"Cologne" and the
matching_text
"Köln".

matching_place_name
(optional)

A string analogous to the
place_name
field that more closely matches the query than results in the specified language. For example, querying "Köln, Germany" with language set to English might return a feature with the
place_name
"Cologne, Germany" and a
matching_place_name
of "Köln, North Rhine-Westphalia, Germany".

text_{language}
(optional)

A string analogous to the
text
field that matches the query in the requested language. This field is only returned when requesting multiple languages and will be present for each requested language.

place_name_{language}
(optional)

A string analogous to the
place_name
field that matches the query in the requested language. This field is only returned when requesting multiple languages and will be present for each requested language.

Example request

curl "https://api.mapbox.com/geocoding/v5/mapbox.places/2+lincoln+memorial+circle+nw.json?access_token="# use the country option to limit# results to Canada and exclude the# Lincoln Memorial in America
curl "https://api.mapbox.com/geocoding/v5/mapbox.places/2+lincoln+memorial+circle+nw.json?country=ca&access_token="# there are many towns named 'Chester', but adding the# proximity parameter with local coordinates ensures that the town# of Chester, New Jersey is in the search results
curl "https://api.mapbox.com/geocoding/v5/mapbox.places/chester.json?proximity=-74.70850,40.78375&access_token="# search only for countries named Georgia,# so that we don't find the state in America
curl "https://api.mapbox.com/geocoding/v5/mapbox.places/georgia.json?types=country&access_token="# use the bounding box option to limit results for a# search for "Starbucks" to those within Washington, D.C.
curl "https://api.mapbox.com/geocoding/v5/mapbox.places/starbucks.json?bbox=-77.083056,38.908611,-76.997778,38.959167&access_token="# use the limit option to limit the number of# results to `2`. Even though there are many possible matches# for `Washington`, this query will only return 2 results.
curl "https://api.mapbox.com/geocoding/v5/mapbox.places/Washington.json?limit=2&access_token="

Retrieve places near a location

This is often called reverse geocoding. Request feature data located at the input {longitude},{latitude} coordinates. The response includes at most one result from each type, unless using the limit option.

Filter results by one or more type. Options are
country
,
region
,
postcode
,
district
,
place
,
locality
,
neighborhood
,
address
,
poi
, and
poi.landmark
. Multiple options can be comma-separated. Note that
poi.landmark
returns a subset of the results returned by
poi
.

limit
(optional)

Limit the maximum number of results. The default is
1
, and the maximum is
5
. If using this option a single
types
is required.

GET

/geocoding/v5/{mode}/{longitude},{latitude}.json

Example request

curl "https://api.mapbox.com/geocoding/v5/mapbox.places/-73.989,40.733.json?access_token="# filter results to only include points of interest
curl "https://api.mapbox.com/geocoding/v5/mapbox.places/-73.989,40.733.json?types=poi&access_token="

Batch requests

This feature is only available with the mapbox.places-permanent mode.

Batch requests have the same parameters as normal requests, but can include
more than one query by separating queries with the ; character. Each
query should be URL encoded, but the ; character should not be encoded: it
should be included verbatim.

With the mapbox.places-permanent mode, you can make up to 50 forward
or reverse geocoding? queries in a single request. The response is
an array of individual geocoder responses.
Each query in a batch request counts individually against
your account's rate limits.

POI categories

POI category search supports forward geocoding? requests of poi feature types in a queried category. Using the proximity query parameter with POI category search returns points of interest local to a provided location; for example, restaurants near a user. Any category that is returned in the properties.category property of the response object is supported.

Here are some of the most common POI categories:

Category

bakery

bank

bar

cafe

church

cinema

coffee

concert

fast food

finance

gallery

historic

hotel

landmark

museum

music

park

pizza

restaurant

retail

school

shop

tea

theater

university

The current list of POI categories is subject to change. A full list of supported categories will be made available in the future.

Directions requests must specify at least two waypoints as starting & ending
points. Requests using driving, walking, and cycling profiles can specify
up to 25 total waypoints along the route. Requests using the driving-traffic
profile can specify up to 3 waypoints.

Traffic coverage for the driving-traffic profile is available in supported geographies. Requests to this profile revert to driving profile results for areas without traffic coverage.

Retrieve directions

Semicolon-separated list of
{longitude},{latitude}
coordinate pairs to visit in order; there can be between 2 and 25 coordinates.

The response may be altered with optional query parameters:

Query Parameter

Description

alternatives
(optional)

Whether to try to return alternative routes. An alternative is classified as a route that is significantly different then the fastest route, but also still reasonably fast. Not in all circumtances such a route exists. At the moment at most one alternative can be returned. Can be
true
or
false
(default).

Type of returned overview geometry. Can be
full
(the most detailed geometry available),
simplified
(a simplified version of the full geometry), or
false
(no overview geometry). The default is
simplified
.

radiuses
(optional)

Maximum distance in meters that each coordinate is allowed to move when snapped to a nearby road segment. 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 they can be the string
unlimited
. If no routable road is found within the radius, a
NoSegment
error is returned.

steps
(optional)

Whether to return steps and turn-by-turn instructions. Can be
true
or
false
. The default is
false
.

continue_straight
(optional)

Sets allowed direction of travel when departing intermediate waypoints. If
true
the route will continue in the same direction of travel. If
false
the route may continue in the opposite direction of travel. Defaults to
true
for
mapbox/driving
and
false
for
mapbox/walking
and
mapbox/cycling
.

bearings
(optional)

Used to filter the road segment the waypoint will be placed on by direction and dictates the angle of approach. This option should always be used in conjunction with the
radiuses
parameter. The parameter takes two values per waypoint: the first is an angle clockwise from true north between 0 and 360. The second is the range of degrees the angle can deviate by. We recommend a value of 45° or 90° for the range, as bearing measurements tend to be inaccurate. This is useful for making sure we reroute vehicles on new routes that 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. 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 with the
;
separator.

annotations
(optional)

Whether or not to return additional metadata along the route. Possible values are:
duration
,
distance
,
speed
and
congestion
. Several annotations can be used by separating them with
,
. See the
RouteLeg object
for more details on what is included with annotations.

language
(optional)

Language of returned turn-by-turn text instructions. See
supported languages
. The default is
en
for English.

exclude
(optional)

Exclude certain road types from routing. Valid values depend on the profile in use, see below for valid values. The default is to not exclude anything from the profile selected.

roundabout_exits
(optional)

Emit instructions at roundabout exits. Can be
true
or
false
(default).

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

weight_name: String indicating which weight was used. The default is routability which is duration based, with additional penalties for less desirable maneuvers.

geometry: Depending on the geometries parameter this is 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).

RouteLeg object

steps: Depending on the steps parameter, either an Array of RouteStep objects (true, default) or an empty array (false)

summary: Depending on the summary parameter, either a String summarizing the route (true, default) or an empty String (false)

annotation: An annotations object that contains additional details about each line segment along the route geometry. Each entry in an annotations field corresponds to a coordinate along the route geometry.

annotation

Description

distance

The distance, in meters, between each pair of coordinates

duration

The duration, in seconds, between each pair of coordinates

speed

The speed, in meters per second, between each pair of coordinates

congestion

The level of congestion, described as one of
severe
,
heavy
,
moderate
,
low
or
unknown
, between each pair of coordinates. For any profile other than
mapbox/driving-traffic
a list of
unknown
s will be returned. A list of
unknown
s will also be returned if the route is very long.

RouteStep object

Includes one StepManeuver object and travel to the following RouteStep.

distance: Number indicating the distance traveled in meters from the maneuver to the next RouteStep.

duration: Number indicating the estimated time traveled time in seconds from the maneuver to the next RouteStep.

geometry: Depending on the geometries parameter this is a GeoJSON LineString or a Polyline string representing the full route geometry from this RouteStep to the next RouteStep

name: String with the name of the way along which the travel proceeds

ref: Any road designations associated with the road or path leading from this step’s maneuver to the next step’s maneuver. Optionally included, if data is available. If multiple road designations are associated with the road, they are separated by semicolons. A road designation typically consists of an alphabetic network code (identifying the road type or numbering system), a space or hyphen, and a route number. You should not assume that the network code is globally unique: for example, a network code of “NH” may appear on a “National Highway” or “New Hampshire”. Moreover, a route number may not even uniquely identify a road within a given network.

destinations: String with the destinations of the way along which the travel proceeds. Optionally included, if data is available.

exits: String with the exit numbers or names of the way. Optionally included, if data is available.

driving_side: The legal driving side at the location for this step. Either left or right.

pronunciation: A string containing an IPA phonetic transcription indicating how to pronounce the name in the name property. This property is omitted if pronunciation data is unavailable for the step.

intersections: Array of objects representing all intersections along the step.

location: A [longitude, latitude] pair describing the location of the turn.

bearings: A list of bearing values (for example [0,90,180,270]) that are available at the intersection. The bearings describe all available roads at the intersection.

classes: An array of strings signifying the classes of the road exiting the intersection. Possible values:

toll: the road continues on a toll road

ferry: the road continues on a ferry

restricted: the road continues on with access restrictions

motorway: the road continues on a motorway

tunnel: the road continues in a tunnel

entry: A list of entry flags, corresponding in a 1:1 relationship to the bearings. A value of true indicates that the respective road could be entered on a valid route. false indicates that the turn onto the respective road would violate a restriction.

in: Index into bearings/entry array. Used to calculate the bearing before the turn. Namely, the clockwise angle from true north to the direction of travel before the maneuver/passing the intersection. To get the bearing in the direction of driving, the bearing has to be rotated by a value of 180. The value is not supplied for departure maneuvers.

out: Index into the bearings/entry array. Used to extract the bearing after the turn. Namely, The clockwise angle from true north to the direction of travel after the maneuver/passing the intersection. The value is not supplied for arrive maneuvers.

lanes: Array of Lane objects that represent the available turn lanes at the intersection. If no lane information is available for an intersection, the lanes property will not be present.

traverse roundabout, has additional property
exit
in
RouteStep
containing the exit number. The modifier specifies the direction of entering the roundabout.

rotary

a traffic circle. While very similar to a larger version of a roundabout, it does not necessarily follow roundabout rules for right of way. It can offer
rotary_name
and / or
rotary_pronunciation
parameters located in the
RouteStep
object in addition to the
exit
property.

roundabout turn

small roundabout that is treated as an intersection

notification

change of driving conditions, e.g. change of
mode
from
driving
to
ferry

exit roundabout

indicates the exit maneuver from a roundabout*

exit rotary

indicates the exit maneuver from a rotary rotary*

* Note: exit roundabout and exit rotary will not appear in results unless you supply the roundabout_exits=true query parameter.

Lane object

Available turn lanes at the intersection. Lanes are provided in their order on the street, from left to right.

valid: Boolean value for whether this lane can be taken to complete the maneuver. For instance, if the lane array has four objects and the first two are marked as valid, then the driver can take either of the left lanes and stay on the route.

indications: Array of signs for each turn lane. There can be multiple signs. For example, a turning lane can have a sign with an arrow pointing left and another sign with an arrow pointing straight.

Example Lane object

{
"valid": true,
"indications": [
"left"
]
}

Directions 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
code

HTTP status code

comment

Ok

200

Normal success case

NoRoute

200

There was no route found for the given coordinates. Check for impossible routes (e.g. routes over oceans without ferry connections).

NoSegment

200

No road segment could be matched for coordinates. Check for coordinates too far away from a road.

Map Matching

The Mapbox Map Matching API snaps fuzzy, inaccurate traces from a
GPS unit or a phone to the OpenStreetMap?
road and path network using the Directions API. This produces clean paths that can be displayed on a map
or used for other analysis.

A list of integers in meters indicating the assumed precision of the used tracking device. There must be as many radiuses as there are coordinates in the request, each separated by
;
. Values can be a number between 0.0 and 50.00. Use higher numbers (20-50) for noisy traces and lower numbers (1-10) for clean traces. The default value is 5.

steps
(optional)

Whether to return steps and turn-by-turn instructions. Can be
true
or
false
. The default is
false
.

overview
(optional)

Type of returned overview geometry. Can be
full
(the most detailed geometry available),
simplified
(a simplified version of the full geometry), or
false
(no overview geometry). The default is
simplified
.

timestamps
(optional)

Timestamps corresponding to each coordinate provided in the request; must be numbers in
Unix time
(seconds since the Unix epoch). There must be as many timestamps as there are coordinates in the request, each separated by
;
.

annotations
(optional)

Whether or not to return additional metadata along the route. Possible values are:
duration
,
distance
and
speed
. Several annotations can be used by separating them with
,
. See the
RouteLeg object
for more details on what is included with annotations.

tidy
(optional)

Whether or not to transparently remove clusters and re-sample traces for improved map matching results. Can be
true
or
false
. The default is
false
.

language
(optional)

Language of returned turn-by-turn text instructions. See
supported languages
. The default is
en
for English.

waypoints
(optional)

Which input coordinates should be treated as waypoints. By default, all coordinates result in a waypoint with arrival and departure events in the
MatchObject's
route. Most useful in combination with
steps=true
and requests based on traces with high sample rates. Can be an index corresponding to any of the input coordinates, but must contain the first (
0
) and last coordinates' index separated by
;
.

It is recommended to include timestamps, since they help improve the quality of the matching. The timestamps must be ascending. For best results, your timestamps should have a sample rate of about 5 seconds.

Some pre-processing tips to achieve the best results:

The Map Matching API is limited to processing traces with up to 100 coordinates.
If you need to process longer traces, you can split the trace and make
multiple requests.

Clusters of points (like a person waiting at a train crossing for a few minutes)
often don't add more information to a trace and can negatively impact map-matching
quality. We recommend to tidy the trace: remove clusters and provide a uniform sample
rate. You can use the tidy=true query parameter or pre-process your traces with
external tools like geojson-tidy.

Map matching works best with a sample rate of 5 seconds between points.
If your trace has a higher sample rate, you may want to downsample your trace.

GET

/matching/v5/{profile}/{coordinates}.json

Example request

# basic request, will return a match object with route legs between each waypoint
$ curl "https://api.mapbox.com/matching/v5/mapbox/driving/-117.1728265285492,32.71204416018209;-117.17288821935652,32.712258556224;-117.17293113470076,32.712443613445814;-117.17292040586472,32.71256999376694;-117.17298477888109,32.712603845608285;-117.17314302921294,32.71259933203019;-117.17334151268004,32.71254065549407?access_token="# request with various parameters, will return a match object with one route leg between first and last waypoint
$ curl "https://api.mapbox.com/matching/v5/mapbox/driving/2.344003915786743,48.85805170891599;2.346750497817993,48.85727523615161;2.348681688308716,48.85936462637049;2.349550724029541,48.86084691113991;2.349550724029541,48.8608892614883;2.349625825881958,48.86102337068847;2.34982967376709,48.86125629633996?steps=true&tidy=true&waypoints=0;6&access_token="

Match response object

With clean matches, only one match object is returned. When the the algorithm cannot decide the correct match between two points, it will omit that line and return several sub-matches as match objects. The higher the number of sub-match match objects, the more likely that the input traces are poorly aligned to the road network.

Note that with the waypoints parameter specified, traces that would normally return with sub-matches will error. We recommend tidying traces before using them with the waypoints parameter.

code: a string depicting the state of the response; see below for options

tracepoints: an array of Tracepoint objects representing the location an input point was matched with. Array of Waypoint objects representing all input points of the trace in the order they were matched. If a trace point is omitted by map matching because it is an outlier, the entry will be null.

Tracepoint object

matchings_index: Index to the match object in matchings the sub-trace was matched to.

waypoint_index: Index of the waypoint inside the matched route.

alternatives_count: Number of probable alternative matchings for this trace point. A value of zero indicates that this point was matched unambiguously. Split the trace at these points for incremental map matching.

Example Tracepoint object

Map Matching 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 explaination 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.

Code option

Description

Ok

Normal case

NoMatch

The input did not produce any matches, or the
waypoints
requested were not found in the resulting match.
features
will be an empty array.

Matrix

For example, given 3 locations A, B, C, the Matrix API will return a matrix of all travel times in seconds between the locations:

A

B

C

A

A → A

A → B

A → C

B

B → A

B → B

B → C

C

C → A

C → B

C → C

The Matrix API will always return the duration on the fastest route for each element in the matrix, where an element is an origin-destination pair in the matrix. Durations between points may not be symmetric (for example A to B may have a different duration than B to A), as the routes may differ by direction due to one-way streets or turn restrictions. The Matrix API returns durations in seconds. It does not return route geometries or distances.

This API allows you to build tools that efficiently check the reachability of coordinates from each other, filter? points by travel time, or run your own algorithms for solving optimization problems.

Restrictions and limits

Requests using mapbox/driving, mapbox/walking, and mapbox/cycling profiles can specify
up to 25 input coordinates per request. Requests using the mapbox/driving-traffic profiles can specify
up to 10 input coordinates per request.

Requests using mapbox/driving, mapbox/walking, and mapbox/cycling profiles have a maximum limit of
60 requests per minute. Requests using the mapbox/driving-traffic profiles have a maximum of 30 requests
per minute.

For example you can request a symmetric 25x25 matrix, an asymmetric 1x24 matrix with distinct coordinates or a 12x24 where sources and destinations share some coordinates.

Retrieve a matrix

The {profile} parameter of your request should be a Mapbox Directions routing profile? ID. The following IDs are supported:

mapbox/driving for car travel times

mapbox/walking for pedestrian and hiking travel times

mapbox/cycling for bicycle travel times

mapbox/driving-traffic for car travel times with traffic

The {coordinates} parameter is a semicolon-separated list of {longitude},{latitude} coordinates. There must be between 2 and 25 coordinates.

In the default case, the matrix returns a symmetric matrix, using all input coordinates as sources and destinations. You may also generate an asymmetric matrix, with only some coordinates as sources or destinations:

Query Parameter

Values

sources
(optional)

{index};{index}[;{index} ...]
or
all
(default)

destinations
(optional)

{index};{index}[;{index} ...]
or
all
(default)

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

Matrix response format

code: String indicating the state of the response. This is a separate code than the HTTP status code. On normal valid responses, the value will be Ok. See the errors section below for more information.

durations: Durations as array of arrays representing the matrix in row-major order. durations[i][j] gives the travel time from the i-th source to the j-th destination. All values are in seconds. The duration between the same coordinate is always 0. If a duration can not be found, the result is null.

destinations:: Array of waypoint objects. Each waypoints is an input coordinate snapped to the road and path network. The waypoints appear in the array in the order of the input coordinates, or in the order as specified in the destinations query parameter.

sources: Array of waypoint objects. Each waypoints is an input coordinate snapped to the road and path network. The waypoints appear in the array in the order of the input coordinates, or in the order as specified in the sources query parameter.

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

Note that in cases where no route is found between a source? and destination, no error will be returned, but instead the respective value in the durations matrix will be null.

The given request was not valid. The
message
key of the response will hold an explanation of the invalid input.

Optimization

The 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 this API is planning the route for deliveries in a city. Route can be retrieved for car driving, bicycling and walking or hiking.

Retrieve an optimization

The {profile} parameter of your request should be a Mapbox Directions routing profile?
ID. The following IDs are supported:

mapbox/driving for car trips

mapbox/walking for pedestrian and hiking trips

mapbox/cycling for bicycle trips

The mapbox/driving-traffic profile is not supported.

The {coordinates} parameter is a semicolon-separated list of {longitude},{latitude} coordinates. There must be between 2 and 12 coordinates. The first coordinate is the start and end point of the trip.

The response may be altered with optional query parameters:

Query Parameter

Description

roundtrip
(optional)

Returned route is a roundtrip (route returns to first location). Allowed values are:
true
(default),
false
. If the roundtrip is set to
false
, then
source
and
destination
parameters are required but not all combinations are possible. See Fixing Start and End Points for additional notes.

source
(optional)

Returned route starts at
any
or
first
coordinate. Allowed values are:
any
(default),
first
.

destination
(optional)

Returned route ends at
any
or
last
coordinate. Allowed values are:
any
(default),
last
.

Type of returned overview geometry. Allowed values are:
simplified
(default, a simplified version of the geometry),
full
(the most detailed geometry available),
false
(no overview geometry).

radiuses
(optional)

Maximum distance in meters that each coordinate is allowed to move when snapped to a nearby road segment. 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 they can be the string
unlimited
. If no routable road is found within the radius, a
NoSegment
error is returned.

Used to filter the road segment the waypoint will be placed on by direction and dictates the angle of approach. This option should always be used in conjunction with the
radiuses
parameter. The parameter takes two values per waypoint: the first is an angle clockwise from true north between 0 and 360. The second is the range of degrees the angle can deviate by. We recommend a value of 45° or 90° for the range, as bearing measurements tend to be inaccurate. This is useful for making sure we reroute vehicles on new routes that 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. 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 with the
;
separator.

annotations
(optional)

Whether or not to return additional metadata along the route. Possible values are:
duration
,
distance
and
speed
. Several annotations can be used by separating them with
,
. See the
RouteLeg object
for more details on what is included with annotations.

language
(optional)

Language of returned turn-by-turn text instructions. See
supported languages
. The default is
en
for English.

distributions
(optional)

Specify 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 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 two numbers. Pick-up and drop-off locations in one pair cannot be the same. The returned solution will visit pick-up locations before visiting drop-off locations. The depot (first location) can only be a pick-up location but not a drop-off location.

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

Note that routes returned by the Optimization API will behave as if continue_straight=false was set at each waypoint. See the continue\straight parameter for more details on what this means for the route.

Fixing Start and End Points

It is possible to explicitly set the start or end coordinate of the trip.
When source? is set to first, the first coordinate is used as the start coordinate of the trip in the output. When destination is set to last, the last coordinate will be used as destination of the trip in the returned output. If you specify any, any of the coordinates can be used as the first or last coordinate in the output.

If source=any&destination=any the returned roundtrip will still 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:

roundtrip

source

destination

supported

true

first

last

yes

true

first

any

yes

true

any

last

yes

true

any

any

yes

false

first

last

yes

false

first

any

no

false

any

last

no

false

any

any

no

GET

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

Example requests

# 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="# request an optimized bicycle trip with steps and 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="# request an optimized car roundtrip in Berlin with four coordinates, starting at the first coordinate pair, ending at the 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="# 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="

Optimization response format

code: String indicating the state of the response. This is a separate code than the HTTP status code. On normal valid responses, the value will be Ok. See the errors section below for more information.

waypoints: 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.

trips: Array of trip objects. Will have zero or one trip.

Waypoint object

An input coordinate snapped to the roads network.

name: String with the name of the way the coordinate snapped to

location: Array of [ longitude, latitude ] for the snapped coordinate

trips_index: Index to the trip object in the trips array that contains this waypoint

waypoint_index: Index of position of the waypoint within the trip

Trip object

A trip object is a route through (potentially multiple) waypoints. It follows the exact same format as the Route object in the Directions API. Please refer to the Directions API documentation.

Optimization 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
code

HTTP status code

comment

Ok

200

Normal success case

NoTrips

200

For one coordinate no route to other coordinates could be found. Check for impossible routes (e.g. routes over oceans without ferry connections).

NotImplemented

200

For the given combination of
source
,
destination
and
roundtrip
, this request is not supported.

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

Tokens

An access token, referred to hereafter as 'token', grants access to Mapbox resources on behalf of a user. All accounts have a public token by default. Additional tokens can be created to grant additional, or more limited, privileges.

To create additional tokens using this API you will first need to create an initial token. This initial token must contain the tokens:write scope and all scopes you want to add to the created token. To create the initial token visit your Account Dashboard, and click Create a token.

The token format

Mapbox uses JSON Web Tokens (JWT) as the token format. Each token is a string delimited by dots into three parts: header, payload, and signature.

The header is a literal value of either pk (public token), sk (secret token), or tk (temporary token).

The payload is a base64-encoded JSON object containing the identity and authorities of the token. pk and sk tokens contain a reference to metadata which holds the rights granted for the token. tk tokens contain the content of the metadata directly in the payload.

The signature is signed by Mapbox and used to verify the token has not been tampered with.

The actions allowed by a token are based on scopes. A scope is a string that often is a resource type and action separated by a colon. For example, the styles:read scope allows read access to styles. Tokens will have access to different scopes depending on their account level and other features of their account.

The token metadata object

Every token has a metadata object that contains information about the capabilities of the token. Token metadata contains the following properties:

Create temporary token

Creates a new temporary token that automatically expires at a fixed time.

The expires property for a temporary token cannot be in the past or more than 1 hour in the future. If the authorizing token is temporary, the expires cannot be later than that of the authorizing token.

Every requested scope must be present in the authorizing token used to allow the request. It is not possible to create a token with access to more scopes than the token that created it.

Unlike public and secret tokens, a temporary token contains its metadata inside the payload of the token instead of referencing a metadata object that persists on the server. Temporary tokens cannot be updated or revoked after they are created.

Example response

Update a token

Update note or scopes in a token's metadata.

A public, pk, token may only be updated to include other public scopes. A secret, sk, token may be updated to contain public and secret scopes.

When updating scopes for an existing token, the token sent along with the request must also have the scopes you're requesting. It is not possible to create a token with access to more scopes than the token that updated it.

Delete a token

Revoke a token's authorization, removing its access to Mapbox APIs. This is the same as deleting a token. Applications using the revoked token will need to get a new access token? before they can access Mapbox APIs.

Note: Cached resources may continue to be accessible for a short period after a token is revoked. No new or updated resources will be accessible with the revoked token.

Analytics

The Mapbox Analytics API returns API usage for services by resource. For example, it can calculate the number of geocoding? requests made in a week with a specific access token?.

Retrieve analytics

Returns the request counts per day for given resource and period.

If the {resourceType} is tokens, the {id} is the complete token.

If the {resourceType} is styles, the {id} is the Style ID. Not to be confused with the Style URL, the id is the alphanumeric segment at the end of the style: the Style URL mapbox://styles/user/cimdoca6f00 contains the Style ID cimdoca6f00, so the analytics request would have the path /analytics/v1/styles/user/cimdoca6f00.

2 comma separated dates as
ISO formatted strings
. The first date must be earlier than the second. The period is inclusive of dates provided. Defaults to last 90 days if not provided. The maximum period is 1 year. If the provided dates are more than 1 year apart, an error will be returned.

Responses include arrays of request counts per service.

Property

Description

timestamps

an array of dates as ISO formatted strings for each day included in the response.

period

a 2 element array with start and end dates as ISO formatted strings for the response period.

services

an object with a key per service the value of which is an array of request counts per day in the same sequence as
timestamps
.

Only services applicable to the given resource are returned in the response.