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.

Your default access token is available on your Account Dashboard. You can also manage and create additional tokens on your Access tokens page or with the Tokens API.

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.

Your application must use the Link header for pagination instead of constructing your own URLs as the specific URLs used for pagination may change at any time. The Python requests library, and the link-header-parser module for JavaScript can parse Link headers. Link headers follow the RFC 5988 specifications.

Pagination is supported on the Datasets, Uploads, Styles, Tilesets, and Tokens list endpoints.

Query Parameter Description
limit 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.
Link: <https://api.mapbox.com/uploads/v1/1454024795582?start=cijywvxlm004rtikohhqf99jv&limit=100>; rel="next"

Dates

Most dates and times returned by the API are represented in RFC 3339 format, which can be parsed by the JavaScript Date constructor, the Python arrow library, and many other libraries and languages.

The only exception to this rule is the Retrieve TileJSON metadata endpoint that returns created and modified properties as Unix time.

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

Mapbox APIs use GeoJSON formatting wherever possible to represent geospatial data. The Directions, Map Matching, Geocoding, and Datasets APIs all return GeoJSON-formatted responses, and the Upload and Map Matching APIs accept GeoJSON input.

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 the retrieval of vector and raster tilesets as images, TileJSON, or embeddable HTML slippy maps.

If you use Mapbox GL JS, Mapbox.js, or another library like Leaflet, you're already using the Maps API. You do not need to read this reference to design or use Mapbox maps. Instead, this documentation is meant for software developers who want to programmatically understand these resources.

Restrictions and limits

  • Use of the Mapbox Maps API endpoint is rate limited based on your user plan. The default is 100,000 requests per minute.
  • Exceeding your user plan's number requests per minute will result in an HTTP 429 Too Many Requests response.
  • For information on rate limit headers, see the Rate limits section.

If you require a higher rate limit, contact us.

Retrieve tiles

Returns an image tile, vector tile, or UTFGrid in the specified format.

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.

URL parameter Description
map_id Unique identifier for the tileset in the format username.id . To composite multiple tilesets, use a comma-separated list of up to 15 tileset IDs.
zoom Specifies the tile's zoom level, as described in the Slippy Map Tilenames specification.
{x}/{y} Specifies the tile's column {x} and row {y} , as described in the Slippy Map Tilenames specification.
@2x
(optional)
Request a higher DPI version of the image.
format Specifies the format of the returned tiles:
.grid.json UTFGrid
.mvt Vector tile
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
The format of any image request can be replaced by any of these 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.

Note: Tiles that include mapbox.satellite are always delivered as JPEGs, even if the URL specifies PNG. The PNG format can't efficiently encode photographic images like those used by mapbox.satellite .

Request style-optimized tiles

Vector tiles can be further optimized by including a style ID with the tile request. If the style parameter is provided, the sources, filters, minzoom, and maxzoom properties of that style? are analyzed, and data that won't be visible on the map is removed from the vector tile. Mapbox GL JS? can request style-optimized vector tiles? that are hosted on Mapbox with a Mapbox Style JSON.

A style-optimized tile request requires the style query parameter:

Query parameter Description
style
(optional)
The 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, which is included with any style created with Mapbox Studio.

Note: Unused layers and features are removed from optimized styles. If you plan to dynamically change the style at runtime using Mapbox GL JS or a Mapbox mobile SDK, broadening filters and zoom ranges won't work the same way since any data that isn't visible with the loaded style also won't be included in the data.

GET
/v4/{map_id}/{zoom}/{x}/{y}{@2x}.{format}

Example request

curl "https://api.mapbox.com/v4/mapbox.mapbox-streets-v7/1/0/0.png?access_token="

# Retrieve a 2x tile; this 512x512 tile is appropriate for high-density displays like Retina
curl "https://api.mapbox.com/v4/mapbox.mapbox-terrain-v2/1/0/0@2x.png?access_token="

# Retrieve a tile with 70% quality JPG encoding
curl "https://api.mapbox.com/v4/mapbox.satellite/3/2/3.jpg70?access_token="

# Retrieve a tile with 32 color indexed PNG
curl "https://api.mapbox.com/v4/mapbox.mapbox-streets-v7/3/2/3.png32?access_token="

# Return a style-optimized tile using the style query parameter
curl "https://api.mapbox.com/v4/mapbox.mapbox-streets-v7/12/1171/1566.png?style=mapbox://styles/mapbox/streets-v10@00&access_token="

Retrieve an HTML slippy map

Returns HTML for a slippy map that can be used for sharing or embedding.

URL parameter Description
map_id Unique identifier for the tileset in the format username.id
options
(optional)
A comma-separated list of controls and map behaviors to be included in the map:
  • zoomwheel : Enable zooming with the mouse wheel
  • zoompan : Enable zoom and pan controls
  • geocoder : Add a geocoder control to the result slippy map
  • share : Add a share control

A request to retrieve an HTML slippy map can be further refined by adding the optional hash parameter:

Query parameter Description
hash
(optional)
Specify a zoom level and location for the map to center on, in the format #zoom/lat/lon . Note: This hash is placed after the access_token in the request.
GET
/v4/{map_id}{/options}.html{#hash}

Example request

# Returns a map with zoom and pan controls, a geocoder, and a share control
curl "https://api.mapbox.com/v4/mapbox.mapbox-streets-v7/zoomwheel,zoompan,geocoder,share.html?access_token="

Retrieve TileJSON metadata

Returns TileJSON metadata for a tileset?. The TileJSON? object describes a map's resources, like tiles, markers, and UTFGrid, as well as its name, description, and centerpoint.

URL parameter Description
map_id Unique identifier for the tileset in the format username.id .

This endpoint can be further customized with the optional secure parameter:

Query parameter Description
secure
(optional)
By default, resource URLs in the retrieved TileJSON (such as in the "tiles" array) will use the HTTP scheme. Include this query parameter in your request to receive HTTPS resource URLs instead.
GET
/v4/{map_id}.json

Example request

curl "https://api.mapbox.com/v4/mapbox.satellite.json?access_token="

# Request HTTPS resource URLs in the retrieved TileJSON
curl "https://api.mapbox.com/v4/mapbox.satellite.json?secure&access_token="

Example response

{
  "attribution": "<a href=\"https://www.mapbox.com/about/maps/\" target=\"_blank\">&copy; Mapbox</a> <a href=\"http://www.openstreetmap.org/about/\" target=\"_blank\">&copy; OpenStreetMap</a> <a class=\"mapbox-improve-map\" href=\"https://www.mapbox.com/map-feedback/\" target=\"_blank\">Improve this map</a> <a href=\"https://www.digitalglobe.com/\" target=\"_blank\">&copy; DigitalGlobe</a>",
  "autoscale": true,
  "bounds": [-180, -85, 180, 85],
  "cacheControl": "max-age=43200,s-maxage=604800",
  "center": [0, 0, 3],
  "created": 1358310600000,
  "description": "",
  "id": "mapbox.satellite",
  "maxzoom": 19,
  "minzoom": 0,
  "modified": 1446150592060,
  "name": "Mapbox Satellite",
  "private": false,
  "scheme": "xyz",
  "tilejson": "2.0.0",
  "tiles": [
    "http://a.tiles.mapbox.com/v4/mapbox.satellite/{z}/{x}/{y}.png",
    "http://b.tiles.mapbox.com/v4/mapbox.satellite/{z}/{x}/{y}.png"
  ],
  "webpage": "http://a.tiles.mapbox.com/v4/mapbox.satellite/page.html"
}

Retrieve a standalone marker

Request a single marker? image without an accompanying background map.

URL Parameter Description
name Marker shape and size. Options are pin-s and pin-l .
label
(optional)
A Maki v0.5.0 icon value. 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 in uppercase only.
color
(optional)
A 3- or 6-digit hexadecimal color code. The default color is gray.
@2x
(optional)
Include to request a high DPI version of the image.
GET
/v4/marker/{name}-{label}+{color}{@2x}.png

Example request

# Returns a small red marker that contains a car icon, high DPI version
curl "https://api.mapbox.com/v4/marker/pin-s-car+f44@2x.png?access_token="

# Returns a large default gray marker
curl "https://api.mapbox.com/v4/marker/pin-l.png?access_token="

# Returns a small blue marker labeled A
curl "https://api.mapbox.com/v4/marker/pin-s-a+00f.png?access_token="

Styles

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

If you use Studio, Mapbox GL JS, or the Mapbox Mobile SDKs, you are already using the Styles API. This documentation is meant for software developers who want to programmatically read and write these resources. It isn't necessary for you to read or understand this reference to design or use Mapbox maps.

You will need to be familiar with the Mapbox Style Specification to use the Styles API. The Mapbox Style? Specification defines the structure of map styles and is the open standard that helps Studio communicate with APIs and produce maps that are compatible with Mapbox libraries.

Mapbox styles

The following Mapbox styles are available to all accounts using a valid access token?:

Navigation styles feature coverage in geographies that Mapbox supports.

Restrictions and 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.
  • An account is allowed to have an unlimited number of styles regardless of its pricing plan.

The style object

A style? object is an object that conforms to the Mapbox Style Specification, with some additional account-related properties:

Property Description
version The style specification version number.
name A human-readable name for the style.
metadata Information about the style that is used in Mapbox Studio.
sources Sources supply the data that will be shown on the map.
layers Layers will be drawn in the order of this array.
created The date and time the style was created.
id The ID of the style.
modified The date and time the style was last modified.
owner The username of the style owner.
visibility Access control for the style, either public or private . Private styles require an access token belonging to the owner. Public styles may be requested with an access token belonging to any user.
draft Indicates whether the style is a draft ( true ) or whether it has been published ( false ).

About drafts

The Styles API supports drafts, so every style can have both published and draft versions. This means that you can make changes to a style without publishing them or deploying them in your app. For each style-related endpoint, you can interact with the draft version of a style by placing draft/ after the style ID, like /styles/v1/{username}/{style_id}/draft/sprite.

Example style object

{
  "version": 8,
  "name": "{name}",
  "metadata": "{metadata}",
  "sources": "{sources}",
  "sprite": "mapbox://sprites/{username}/{style_id}",
  "glyphs": "mapbox://fonts/{username}/{fontstack}/{range}.pbf",
  "layers": ["{layers}"],
  "created": "2015-10-30T22:18:31.111Z",
  "id": "{style_id}",
  "modified": "2015-10-30T22:22:06.077Z",
  "owner": "{username}",
  "visibility": "private",
  "draft": true
}

Retrieve a style

Retrieve a style? as a JSON document. The returned style object will be in the Mapbox Style format.

URL parameters Description
username The username of the account to which the style belongs.
style_id The ID of the style to be retrieved.
GET
/styles/v1/{username}/{style_id}
styles:read Token scope

Example request

curl "https://api.mapbox.com/styles/v1/examples/cjikt35x83t1z2rnxpdmjs7y7?access_token="

Example response

{
  "version": 8,
  "name": "Meteorites",
  "metadata": {
    "mapbox:origin": "basic-template-v1",
    "mapbox:autocomposite": true,
    "mapbox:type": "template",
    "mapbox:sdk-support": {
      "js": "0.45.0",
      "android": "6.0.0",
      "ios": "4.0.0"
    }
  },
  "center": [
    74.24426803763072,
    -2.2507114487818853
  ],
  "zoom": 0.6851443156248076,
  "bearing": 0,
  "pitch": 0,
  "sources": {
    "composite": {
      "url": "mapbox://mapbox.mapbox-streets-v7,examples.0fr72zt8",
      "type": "vector"
    }
  },
  "sprite": "mapbox://sprites/examples/cjikt35x83t1z2rnxpdmjs7y7",
  "glyphs": "mapbox://fonts/{username}/{fontstack}/{range}.pbf",
  "layers": [
    {
      "id": "background",
      "type": "background",
      "layout": {},
      "paint": {
        "background-color": [ ]
      }
    },
    { }
  ],
  "created": "2015-10-30T22:18:31.111Z",
  "id": "cjikt35x83t1z2rnxpdmjs7y7",
  "modified": "2015-10-30T22:22:06.077Z",
  "owner": "examples",
  "visibility": "public",
  "draft": false
}

List styles

Retrieve a list of styles for a specific account. This endpoint returns style? metadata instead of returning full styles.

URL parameters Description
username The username of the account to which the styles belong.
GET
/styles/v1/{username}
styles:list Token scope

Example request

curl "https://api.mapbox.com/styles/v1/{username}?access_token="

Example response

[
  {
    "version": 8,
    "name": "My Awesome Style",
    "created": "{timestamp}",
    "id": "cige81msw000acnm7tvsnxcp5",
    "modified": "{timestamp}",
    "owner": "{username}"
  },
  {
    "version": 8,
    "name": "My Cool Style",
    "created": "{timestamp}",
    "id": "cig9rvfe300009lj9kekr0tm2",
    "modified": "{timestamp}",
    "owner": "{username}"
  }
]

Create a style

Creates a style? in your account. The posted style object must be both valid JSON and aligned to the most recent version of the Mapbox Style Specification. Invalid styles will produce a descriptive validation error.

GeoJSON sources are not supported by the Styles API.

If the optional name property is not used in the request body, the name of the new style will be automatically set to the style's ID.

The style you get back from the API will contain new properties that the server has added: created, id, modified, owner, and draft.

URL parameters Description
username The username of the account to which the new style will belong.
POST
/styles/v1/{username}
styles:write Token scope

Example request

curl -X POST "https://api.mapbox.com/styles/v1/{username}?access_token=" \
  --data @basic-v9.json \
  --header "Content-Type:application/json"

Example request body

{
  "version": 8,
  "name": "My Awesome Style",
  "metadata": { },
  "sources": {
    "myvectorsource": {
      "url": "mapbox://{map_id}",
      "type": "vector"
    },
    "myrastersource": {
      "url": "mapbox://{map_id}",
      "type": "raster"
    }
  },
  "glyphs": "mapbox://fonts/{username}/{fontstack}/{range}.pbf",
  "layers": [ ]
}

Example response

{
  "version": 8,
  "name": "My Awesome Style",
  "metadata": { },
  "sources": {
    "myvectorsource": {
      "url": "mapbox://{map_id}",
      "type": "vector"
    },
    "myrastersource": {
      "url": "mapbox://{map_id}",
      "type": "raster"
    }
  },
  "sprite": "mapbox://sprites/{username}/{style_id}",
  "glyphs": "mapbox://fonts/{username}/{fontstack}/{range}.pbf",
  "layers": [ ],
  "created": "2015-10-30T22:18:31.111Z",
  "id": "{style_id}",
  "modified": "2015-10-30T22:22:06.077Z",
  "owner": "{username}",
  "draft": true
}

Update a style

Updates an existing style? in your account with new content.

If you request a style and then use the same content to update the style, this action will fail. You must remove the created and modified properties before updating a style. The name property, which is optional for creating a style, is required to update a style.

Cross-version PATCH requests are rejected.

URL parameters Description
username The username of the account to which the style belongs.
style_id The ID of the style to be updated.
PATCH
/styles/v1/{username}/{style_id}
styles:write Token scope

Example request

curl -X PATCH "https://api.mapbox.com/styles/v1/{username}/{style_id}" \
  --data @basic-v9.json \
  --header "Content-Type:application/json"

Example request body

{
  "version": 8,
  "name": "New Style Name",
  "metadata": { },
  "sources": { },
  "sprite": "mapbox://sprites/{username}/{style_id}",
  "glyphs": "mapbox://fonts/{username}/{fontstack}/{range}.pbf",
  "layers": [{
    "id": "new-layer",
    "type": "background",
    "paint": {
      "background-color": "#111"
    },
    "interactive": true
  }],
  "owner": "{username}",
  "draft": true
}

Example response

{
  "version": 8,
  "name": "New Style Name",
  "metadata": { },
  "sources": { },
  "sprite": "mapbox://sprites/{username}/{style_id}",
  "glyphs": "mapbox://fonts/{username}/{fontstack}/{range}.pbf",
  "layers": [{
    "id": "new-layer",
    "type": "background",
    "paint": {
      "background-color": "#111"
    },
    "interactive": true
  }],
  "created": "2015-10-30T22:18:31.111Z",
  "id": "{style_id}",
  "modified": "2015-10-30T22:22:06.077Z",
  "owner": "{username}",
  "draft": true
}

Delete a style

Delete a style?. All sprites that belong to this style will also be deleted, and the style will no longer be available.

URL parameters Description
username The username of the account to which the style belongs.
style_id The ID of the style to be deleted.
DELETE
/styles/v1/{username}/{style_id}
styles:write Token scope

Example request

curl -X DELETE "https://api.mapbox.com/styles/v1/{username}/{style_id}?access_token="

Response

HTTP 204

Request embeddable HTML

Request embeddable HTML. The results can be displayed as a fullscreen map or can be inserted into <iframe> content.

URL parameters Description
username The username of the account to which the style belongs.
style_id The ID of the style to be embedded.

The embeddable HTML that is returned can be further modified with the following optional query parameters:

Query Parameter Description
zoomwheel
(optional)
Whether to provide a zoomwheel, which enables a viewer to zoom in and out of the map using the mouse ( true , default), or not ( false ).
title
(optional)
Whether to display a title box with the map's title and owner in the upper right corner of the map ( true ) or not ( false , default).
fallback
(optional)
Serve a fallback raster map ( true ) or not ( false , default).
GET
/styles/v1/{username}/{style_id}.html
styles:read Token scope

Example style embed

<iframe
  src='https://api.mapbox.com/styles/v1/mapbox/streets-v10.html?title=true&zoomwheel=false&access_token=' />

Sprites

Sprites are the way that Mapbox GL JS? and Mapbox Mobile efficiently request and show images. Sprites are collections of images that can be used in styles as icons or patterns in symbol layers. An image in a sprite? can be an icon, a pattern, or an illustration. These SVG? images can be added and removed from the sprite 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 image is positioned.

The sprite JSON document is specified as part of the the Mapbox Style Specification.

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

Restrictions and limits

  • Each image must be smaller than 400kB.
  • Mapbox supports most, but not all, SVG properties. These limits are described in our SVG troubleshooting guide.
  • Images can be up to 512px in each dimension.
  • Image names must be fewer than 255 characters in length.
  • Sprites can contain up to 500 images.

Retrieve a sprite image or JSON

Retrieve a sprite? image or its JSON document from a Mapbox style?.

URL Parameter Description
username The username of the account to which the style belongs.
style_id The ID of the style to which the sprite belongs.
@2x
(optional)
Render the sprite at a @2x , @3x , or @4x scale factor for high-density displays.
format
(optional)
By default, this endpoint returns a sprite's JSON document. Specify .png to return the sprite image instead.
GET
/styles/v1/{username}/{style_id}/sprite{@2x}.{format}
styles:read Token scope

Example request

# Request the sprite image as a png
curl "https://api.mapbox.com/styles/v1/{username}/{style_id}/sprite.png?access_token="

# Request json for a 3x scale sprite
curl "https://api.mapbox.com/styles/v1/{username}/{style_id}/sprite@3x?access_token="

Example response

{
  "default_marker": {
    "width": 20,
    "height": 50,
    "x": 0,
    "y": 0,
    "pixelRatio": 2
  },
  "secondary_marker": {
    "width": 20,
    "height": 50,
    "x": 20,
    "y": 0,
    "pixelRatio": 2
  }
}

Add new image to sprite

Add a new image to an existing sprite? in a Mapbox style?. The request body should be raw SVG? data.

URL Parameter Description
username The username of the account to which the style belongs.
style_id The ID of the style to which the sprite belongs.
icon_name The name of the new image that is being added to the style.
PUT
/styles/v1/{username}/{style_id}/sprite/{icon_name}
styles:write Token scope

Example request

# Add a new image (`aerialway`) to an existing sprite
curl -X PUT \
  "https://api.mapbox.com/styles/v1/{username}/{style_id}/sprite/aerialway?access_token=" \
  --data @aerialway-12.svg

Example response

{
  "newsprite": {
    "width": 1200,
    "height": 600,
    "x": 0,
    "y": 0,
    "pixelRatio": 1
  },
  "default_marker": {
    "width": 20,
    "height": 50,
    "x": 0,
    "y": 600,
    "pixelRatio": 1
  }
}

Delete image from sprite

Remove an image from an existing sprite?.

URL Parameter Description
username The username of the account to which the style belongs.
style_id The ID of the style to which the sprite belongs.
icon_name The name of the new image to delete from the style.
DELETE
/styles/v1/{username}/{style_id}/sprite/{icon_name}
styles:write Token scope

Example request

curl -X DELETE "https://api.mapbox.com/styles/v1/{username}/{style_id}/sprite/{icon_name}?access_token="

Example response

{
  "default_marker": {
    "width": 20,
    "height": 50,
    "x": 0,
    "y": 600,
    "pixelRatio": 1
  },
  "secondary_marker": {
    "width": 20,
    "height": 50,
    "x": 20,
    "y": 600,
    "pixelRatio": 1
  }
}

Fonts

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

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

Restrictions and limits

  • Fonts must be smaller than 30MB.
  • Accounts are limited to 100 fonts.

Retrieve font glyph ranges

While glyph ranges are usually not of interest unless you're building a map renderer, this is the endpoint you can use to 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.

URL Parameter Description
username The username of the account to which the font belongs.
font The name of the font. This endpoint supports queries with multiple comma-separated font names.
start A multiple of 256 between 0 and 65280 .
end The number indicated by start , plus 255 .

Response body

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

GET
/fonts/v1/{username}/{font}/{start}-{end}.pbf
fonts:read Token scope

Example request

# Query contains 2 comma-separated font names
curl "https://api.mapbox.com/fonts/v1/examples/DIN Offc Pro Medium,Arial Unicode MS Regular/0-255?access_token="

Response

HTTP 200 Success

Static

The Mapbox Static API returns static maps and raster tiles from styles in the Mapbox Style Specification.

  • Static maps are standalone images that can be displayed on web and mobile devices without the aid of a mapping library or API. They look like an embedded map, but do not have interactivity or controls. The returned static map will be a PNG file.
  • Raster tiles can be used in traditional web mapping libraries like Mapbox.js, Leaflet, OpenLayers, and others. The returned raster tile will be a JPEG, and will be 512px by 512px by default.

Swift and Objective-C support for the Static API is provided by the MapboxStatic.swift library.

To build a Static API request by zooming and panning around an interactive map, use the Static API playground.

Restrictions and limits

  • Static maps: The default rate limit is 600 requests per minute.
  • Raster tiles: The default rate limit is 2,000 requests per minute. The rate limit is higher for Enterprise customers.
  • Exceeding these limits will result in an HTTP 429 response. For information on rate limit headers, see Rate limits.

If you require a higher rate limit, contact us.

Retrieve a static map from a style

Returns a static map from a specified style? as a PNG. Use of the static maps endpoint is rate-limited by access token?. By default, the rate limit is set to 600 requests per minute.

The position of the map is represented by either the word auto or by five numbers: the longitude, latitude, zoom, bearing, and pitch.

If you specify auto, omit numbers for longitude, latitude, zoom, bearing, or pitch.

Bearing and pitch are optional. If you only specify bearing and not pitch, the pitch will default to 0. If you specify neither bearing nor pitch, they will both default to 0.

Parameter Description
username The username of the account to which the style belongs.
style_id The ID of the style from which to create a static map.
overlay One or more comma-separated features that can be applied on top of the map at request time. The order of features in an overlay 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). Format can be a mix of geojson , marker , or path . For more details on each option, see the Overlay options section .
lon Longitude for the center point of the static map; a number between -180 and 180 .
lat Latitude for the center point of the static map; a number between -90 and 90 .
zoom Zoom level; a number between 0 and 20 . Fractional zoom levels will be rounded to two decimal places.
bearing
(optional)
Bearing rotates the map around its center. A number between 0 and 360 , interpreted as decimal degrees. 90 rotates the map 90° clockwise, while 180 flips the map. Defaults to 0 .
pitch
(optional)
Pitch tilts the map, producing a perspective effect. A number between 0 and 60 , measured in degrees. Defaults to 0 (looking straight down at the map).
auto The viewport will fit the bounds of the overlay. If used, auto replaces lon , lat , zoom , bearing , and pitch .
width Width of the image; a number between 1 and 1280 pixels.
height Height of the image; a number between 1 and 1280 pixels.
@2x
(optional)
Render the static map at a @2x scale factor for high-density displays.

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

Query parameter Description
attribution
(optional)
A boolean value controlling whether there is attribution on the image. Defaults to true . Note: If attribution=false , the watermarked attribution is removed from the image. You still have a legal responsibility to attribute maps that use OpenStreetMap data, which includes most maps from Mapbox. If you specify attribution=false , you are legally required to include proper attribution elsewhere on the webpage or document .
logo
(optional)
A boolean value controlling whether there is a Mapbox logo on the image. Defaults to true .
before_layer (optional) A string value for controlling where the overlay is inserted in the style. All overlays will be inserted before the specified layer.

Overlay options

GeoJSON

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

Marker

{name}-{label}+{color}({lon},{lat})
Argument Description
name Marker shape and size. Options are pin-s and 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 in uppercase only.
color
(optional)
A 3- or 6-digit hexadecimal color code.
lon, lat The location at which to center the marker. When using an asymmetric marker, make sure that the tip of the pin is at the center of the image.

Custom marker

url-{url}({lon},{lat})
Argument Description
url A percent-encoded URL for the image. Type can be PNG or JPG .
lon, lat The location at which to center the marker. When creating an asymmetric marker like a pin, make sure that the tip of the pin is at the center of the image.

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.

Path

path-{strokeWidth}+{strokeColor}-{strokeOpacity}+{fillColor}-{fillOpacity}({polyline})

Encoded polylines with a precision of 5 decimal places can be used with the Static API via the path parameter.

Argument Description
strokeWidth
(optional)
A positive number for the line stroke width
strokeColor
(optional)
A 3- or 6-digit hexadecimal color code for the line stroke
strokeOpacity
(optional)
A number between 0 (transparent) and 1 (opaque) for line stroke opacity
fillColor
(optional)
A 3- or 6-digit hexadecimal color code for the fill
fillOpacity
(optional)
A number between 0 (transparent) and 1 (opaque) for fill opacity
polyline A valid encoded polyline encoded as a URI component
GET
/styles/v1/{username}/{style_id}/static/{overlay}/{lon},{lat},{zoom},{bearing},{pitch}|{auto}/{width}x{height}{@2x}
styles:tiles Token scope

Example request

# Retrieve a map at -122.4241 longitude, 37.78 latitude,
# zoom 14.24, bearing 0, and pitch 60. The map
# will be 600 pixels wide and 600 pixels high
curl "https://api.mapbox.com/styles/v1/mapbox/streets-v10/static/-122.4241,37.78,14.25,0,60/600x600?access_token="

# Retrieve a map at 0 longitude, 10 latitude, zoom 3,
# and bearing 20. Pitch will default to 0.
curl "https://api.mapbox.com/styles/v1/mapbox/streets-v10/static/0,10,3,20/600x600?access_token="

# Retrieve a map at 0 longitude, 0 latitude, zoom 2.
# Bearing and pitch default to 0.
curl "https://api.mapbox.com/styles/v1/mapbox/streets-v10/static/0,0,2/600x600?access_token="

# Retrieve a map with a custom marker overlay
curl "https://api.mapbox.com/styles/v1/mapbox/streets-v10/static/url-https%3A%2F%2Fwww.mapbox.com%2Fimg%2Frocket.png(-76.9,38.9)/-76.9,38.9,15/1000x1000?access_token="

# Retrieve a map with a GeoJSON overlay
curl "https://api.mapbox.com/styles/v1/mapbox/streets-v10/static/geojson(%7B%22type%22%3A%22Point%22%2C%22coordinates%22%3A%5B-73.99%2C40.7%5D%7D)/-73.99,40.70,12/500x300?access_token="

# Retrieve a map with 2 points and a polyline overlay,
# with its center point automatically determined with `auto`
curl "https://api.mapbox.com/styles/v1/mapbox/streets-v10/static/pin-s-a+9ed4bd(-122.46589,37.77343),pin-s-b+000(-122.42816,37.75965),path-5+f44-0.5(%7DrpeFxbnjVsFwdAvr@cHgFor@jEmAlFmEMwM_FuItCkOi@wc@bg@wBSgM)/auto/500x300?access_token="

Retrieve raster tiles from styles

Retrieve 512x512 pixel or 256x256 pixel raster tiles from a Mapbox Studio? style?. The returned raster tile will be a JPEG.

Libraries like Mapbox.js? and Leaflet.js use this endpoint to render raster tiles from a Mapbox Studio style with L.mapbox.styleLayer and L.tileLayer. By default, the rate limit is set to 2,000 requests per minute. The rate limit is higher for Enterprise customers.

URl parameter Description
username The username of the account to which the style belongs.
style_id The ID of the style from which to return a raster tile.
tilesize
(optional)
Default is 512x512 pixels. (512x512 image tiles are offset by 1 zoom level compared to 256x256 tiles from Mapbox Studio Classic styles. For example, 512x512 tiles at zoom level 4 are equivalent to Mapbox Studio Classic styles tiles at zoom level 5.) 256x256 tiles from the endpoint are one quarter of the size of 512x512 tiles. Therefore, they require 4 times as many API requests and accumulate 4 times as many map views to render the same area.
{z}/{x}/{y} The tile coordinates as described in the Slippy Map Tilenames specification . They specify the tile's zoom level {z} , column {x} , and row {y} .
@2x
(optional)
Render the raster tile at a @2x scale factor, so tiles are scaled to 1024x1024 pixels.
GET
/styles/v1/{username}/{style_id}/tiles/{tilesize}/{z}/{x}/{y}{@2x}

Example request

# Returns a default 512x512 pixel tile
curl "https://api.mapbox.com/styles/v1/mapbox/streets-v10/tiles/1/1/0?access_token="

# Returns a 256x256 pixel tile
curl "https://api.mapbox.com/styles/v1/mapbox/streets-v10/tiles/256/1/1/0?access_token="

# Returns a 1024x1024 pixel tile
curl "https://api.mapbox.com/styles/v1/mapbox/streets-v10/tiles/512/1/1/0@2x?access_token="

Retrieve a map's WMTS document

Mapbox supports access via the WMTS standard, which lets you use maps with desktop and online GIS software like ArcMap and QGIS.

URL parameter Description
username The username of the account to which the style belongs.
style_id The ID of the style for which to return a WMTS document.
GET
/styles/v1/{username}/{style_id}/wmts

Example request

curl "https://api.mapbox.com/styles/v1/mapbox/streets-v10/wmts?access_token="

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 follows these steps:

  1. Request temporary S3 credentials that allow you to stage the file. Jump to the Retrieve S3 credentials section.
  2. Use an S3 client to upload the file to Mapbox's S3 staging bucket using these credentials. Learn more about this process in the Upload to Mapbox using cURL tutorial.
  3. Create an upload using the staged file's URL. Jump to the Create an upload section.
  4. Retrieve the upload's status as it is being processed into a tileset. Jump to the Retrieve upload status section.

Note: This documentation discusses how to interact with the Mapbox Uploads API programatically. For a step-by-step guide on how to use the Uploads API to stage a file to Amazon S3 and create an upload, use the Upload to Mapbox using cURL tutorial.

Restrictions and limits

  • Tileset names are limited to 64 characters.
  • The Uploads API supports different file sizes for various file types:
File type Size limit
TIFF and GeoTIFF 10 GB
MBTiles 25 GB
GeoJSON 1 GB
CSV 1 GB
KML 260 MB
GPX 260 MB
Shapefile (unzipped) 260 MB (combined uncompressed size of .shp and .dbf files)
Shapefiles must be uploaded as compressed .zip files.
Mapbox Dataset 1 GB

Error messages

To see a list of possible upload errors, visit the Uploads errors page.

Retrieve S3 credentials

Mapbox provides an Amazon S3 bucket to stage your file while your upload is processed. This endpoint allows you to retrieve temporary S3 credentials to use during the staging process.

Note: This step is necessary before you can stage a file in the Amazon S3 bucket provided by Mapbox. All uploads must be staged in this Amazon S3 bucket before being uploaded to your Mapbox account. To learn more about how to stage an upload to Amazon S3, read the Upload to Mapbox using cURL tutorial.

URL parameters Description
username The username of the account to which you are uploading a tileset.

Response body

The response body is a JSON object that contains the following properties:

Property Description
accessKeyId AWS Access Key ID
bucket S3 bucket name
key The unique key for data to be staged
secretAccessKey AWS Secret Access Key
sessionToken A temporary security token
url The 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 AWS CLI usage

$ export AWS_ACCESS_KEY_ID={accessKeyId}
$ export AWS_SECRET_ACCESS_KEY={secretAccessKey}
$ export AWS_SESSION_TOKEN={sessionToken}
$ aws s3 cp /path/to/file s3://{bucket}/{key} --region us-east-1
POST
/uploads/v1/{username}/credentials
uploads:write Token scope

Example request

curl -X POST "https://api.mapbox.com/uploads/v1/{username}/credentials?access_token="

Example response

{
  "accessKeyId": "{accessKeyId}",
  "bucket": "somebucket",
  "key": "hij456",
  "secretAccessKey": "{secretAccessKey}",
  "sessionToken": "{sessionToken}",
  "url": "{url}"
}

Create an upload

After you have used the temporary S3 credentials to transfer your file to Mapbox's staging bucket, you can trigger the generation of a tileset? using the file's URL and a destination tileset ID.

Uploaded files must be in the bucket provided by Mapbox. Requests for resources from other S3 buckets or URLs will fail.

URL parameters Description
username The username of the account to which you are uploading

Request body

The request body must be a JSON object that contains the following properties:

Property Description
tileset The map ID to create or replace, in the format username.nameoftileset . Limited to 32 characters. This character limit does not include the username. The only allowed special characters are - and _ .
url The HTTPS URL of the S3 object provided in the credential request, or the dataset ID of an existing Mapbox dataset to be uploaded.
name
(optional)
The name of the tileset. Limited to 64 characters.

If you reuse a tileset value, this action will replace existing data. Use a random value to make sure that a new tileset is created, or check your existing tilesets first.

Response body

The response body is a JSON object that contains the following properties:

Property Description
complete Whether the upload is complete ( true ) or not complete ( false ).
tileset The ID of the tileset that will be created or replaced if upload is successful.
error If null , the upload is in progress or has successfully completed. Otherwise, provides a brief explanation of the error.
id The unique identifier for the upload.
name The name of the upload.
modified A timestamp indicating when the upload resource was last modified.
created A timestamp indicating when the upload resource was created.
owner The unique identifier for the owner's account.
progress The progress of the upload, expressed as a float between 0 (started) and 1 (completed).
POST
/uploads/v1/{username}
uploads:write Token scope

Example request

curl -X POST -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d '{
  "url": "http://{bucket}.s3.amazonaws.com/{key}",
  "tileset": "{username}.{tileset-name}"
}' 'https://api.mapbox.com/uploads/v1/{username}?access_token=secret_access_token'

Example request body to upload a Mapbox dataset (AWS S3 bucket not required)

{
  "tileset": "{username}.mytileset",
  "url": "mapbox://datasets/{username}/{dataset}",
  "name": "example-dataset"
}

Example response

{
  "complete": false,
  "tileset": "example.markers",
  "error": null,
  "id": "hij456",
  "name": "example-markers",
  "modified": "{timestamp}",
  "created": "{timestamp}",
  "owner": "{username}",
  "progress": 0
}

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

URL parameters Description
username The username of the account for which you are requesting an upload status.
upload_id The ID of the upload. Provided in the response body to a successful upload request.

Response body

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

Property Description
complete Boolean. Indicates whether the upload is complete ( true ) or not complete ( false ).
tileset The ID of the tileset that will be created or replaced if upload is successful.
error If null , the upload is in progress or has successfully completed. Otherwise, provides a brief explanation of the error.
id The unique identifier for the upload.
name The name of the upload.
modified The timestamp for when the upload resource was last modified.
created The timestamp for when the upload resource was created.
owner The unique identifier for the owner's account.
progress The progress of the upload, expressed as a float between 0 (started) and 1 (completed).
GET
/uploads/v1/{username}/{upload_id}
uploads:read Token scope

Example request

curl "https://api.mapbox.com/uploads/v1/{username}/{upload_id}?access_token="

Example response

{
  "complete": true,
  "tileset": "example.markers",
  "error": null,
  "id": "hij456",
  "name": "example-markers",
  "modified": "{timestamp}",
  "created": "{timestamp}",
  "owner": "{username}",
  "progress": 1
}

Retrieve recent upload statuses

Retrieve multiple upload statuses at the same time, sorted by the most recently created. This request returns the same information as an individual upload status request does, but for all an account's recent uploads. The list is limited to 1MB of JSON.

This endpoint supports pagination so that you can list many uploads.

URL parameters Description
username The username of the account for which you are requesting upload statuses.

The results from this endpoint can be further modified with the following optional parameters:

Query parameter Description
reverse
(optional)
Set to true to reverse the default sort order of the results listing.
limit
(optional)
The maximum number of statuses to return, up to 100 .
GET
/uploads/v1/{username}
uploads:list Token scope

Example request

curl "https://api.mapbox.com/uploads/v1/{username}?access_token="

# Return at most 10 upload statuses, in chronological order
curl "https://api.mapbox.com/uploads/v1/{username}?reverse=true&limit=10&access_token="

Example response

[{
  "complete": true,
  "tileset": "example.mbtiles",
  "error": null,
  "id": "abc123",
  "name": null,
  "modified": "2014-11-21T19:41:10.000Z",
  "created": "2014-11-21T19:41:10.000Z",
  "owner": "example",
  "progress": 1
}, {
  "complete": false,
  "tileset": "example.foo",
  "error": null,
  "id": "xyz789",
  "name": "foo",
  "modified": "2014-11-21T19:41:10.000Z",
  "created": "2014-11-21T19:41:10.000Z",
  "owner": "example",
  "progress": 0
}]

Remove an upload status

Remove the status of a completed upload from the upload listing.

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

URL parameters Description
username The username of the associated account.
upload_id The ID of the upload. Provided in the response body to a successful upload request.
DELETE
/uploads/v1/{username}/{upload_id}
uploads:write Token scope

Example request

$ curl -X DELETE "https://api.mapbox.com/uploads/v1/{username}/{upload_id}?access_token="

Example response

HTTP 204

Datasets

A dataset is an editable collection of GeoJSON features. The Datasets API offers persistent storage for custom geographic data. It supports reading, creating, updating, and removing features from a dataset?. To serve your geographic 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 one or more collections of features.

Restrictions and limits

  • The Dataset API is limited on a per dataset basis.
  • The default rate limit is 40 writes and 480 reads per minute.
  • Dataset names are limited to 60 characters, and dataset descriptions are limited to 300 characters.
  • Each feature cannot exceed 1023 KB compressed. Features are compressed server-side using geobuf.

If you require a higher rate limit, contact us.

The dataset object

The dataset object contains information pertinent to a specific dataset?. Each dataset object contains the following properties:

Property Description
owner The username of the dataset owner.
id The ID for an existing dataset.
created A timestamp indicating when the dataset was created.
modified A timestamp indicating when the dataset was last modified.
bounds The extent of features in the dataset in the format [ west , south , east , north ] .
features The number of features in the dataset.
size The size of the dataset in bytes.
name
(optional)
The name of the dataset.
description
(optional)
A description of the dataset.

The dataset object

{
  "owner": "{username}",
  "id": "{dataset_id}",
  "created": "{timestamp}",
  "modified": "{timestamp}",
  "bounds": [-10, -10, 10, 10],
  "features": 100,
  "size": 409600,
  "name": "{name}",
  "description": "{description}"
}

List datasets

List all the datasets that belong to a particular account.

URL parameters Description
username The username of the account for which to list datasets.
GET
/datasets/v1/{username}
datasets:list Token scope

Example request

$ curl "https://api.mapbox.com/datasets/v1/{username}?access_token="

Example response

[
  {
    "owner": "{username}",
    "id": "{dataset_id}",
    "created": "{timestamp}",
    "modified": "{timestamp}",
    "bounds": [-10, -10, 10, 10],
    "features": 100,
    "size": 409600,
    "name": "{name}",
    "description": "{description}"
  },
  {
    "owner": "{username}",
    "id": "{dataset_id}",
    "created": "{timestamp}",
    "modified": "{timestamp}",
    "bounds": [-10, -10, 10, 10],
    "features": 100,
    "size": 409600,
    "name": "{name}",
    "description": "{description}"
  }
]

Create dataset

Create a new, empty dataset?.

URL parameters Description
username The username of the account to which the new dataset belongs.
POST
/datasets/v1/{username}
datasets:write Token scope

Example request

curl -X POST "https://api.mapbox.com/datasets/v1/{username}?access_token=" \
  -d @request.json \
  --header "Content-Type:application/json

Example request body

{
  "name": "foo",
  "description": "bar"
}

Example response

{
  "owner": "{username}",
  "id": "{dataset_id}",
  "created": "{timestamp}",
  "modified": "{timestamp}",
  "bounds": [-10, -10, 10, 10],
  "features": 100,
  "size": 409600,
  "name": "foo",
  "description": "bar"
}

Retrieve a dataset

Retrieve information about a single existing dataset?.

URL parameters Description
username The username of the account to which the dataset belongs.
dataset_id The ID of the dataset to be retrieved.
GET
/datasets/v1/{username}/{dataset_id}
datasets:read Token scope

Example request

curl "https://api.mapbox.com/datasets/v1/{username}/{dataset_id}?access_token="

Example response

{
  "owner": "{username}",
  "id": "{dataset_id}",
  "created": "{timestamp}",
  "modified": "{timestamp}",
  "bounds": [-10, -10, 10, 10],
  "features": 100,
  "size": 409600,
  "name": "{name}",
  "description": "{description}"
}

Update a dataset

Update the properties of a specific dataset?. The request body must be valid JSON.

URL parameters Description
username The username of the account to which the dataset belongs.
dataset_id The ID of the dataset to be updated.
PATCH
/datasets/v1/{username}/{dataset_id}
datasets:write Token scope

Example request

curl -X PATCH "https://api.mapbox.com/datasets/v1/{username}/{dataset_id}?access_token=" \
  -d @data.json

Example request body

{
  "name": "foo",
  "description": "bar"
}

Example response

{
  "owner": "{username}",
  "id": "{dataset_id}",
  "created": "{timestamp}",
  "modified": "{timestamp}",
  "bounds": [-10, -10, 10, 10],
  "features": 100,
  "size": 409600,
  "name": "foo",
  "description": "bar"
}

Delete a dataset

Delete a specific dataset?. All the features contained in the dataset will be deleted too.

URL parameters Description
username The username of the account to which the dataset belongs.
dataset_id The ID of the dataset to be deleted.
DELETE
/datasets/v1/{username}/{dataset_id}
datasets:write Token scope

Example request

curl -X DELETE "https://api.mapbox.com/datasets/v1/{username}/{dataset_id}?access_token="

Example response

HTTP 204

The feature object

A feature is a GeoJSON? Feature object representing a feature in the dataset?. GeometryCollections and null geometries are not supported. For a full list of GeoJSON Feature properties, see the GeoJSON specification.

The feature object

{
  "id": "{feature_id}",
  "type": "Feature",
  "properties": {
    "prop0": "value0"
  },
  "geometry": {
    "coordinates": [102, 0.5],
    "type": "Point"
  }
}

List features

List all the features in a dataset?. The response body will be a GeoJSON? FeatureCollection.

This endpoint supports pagination so that you can list many features.

URL parameters Description
username The username of the account to which the dataset belongs.
dataset_id The ID of the dataset for which to retrieve features.
Query parameters Description
limit
(optional)
The maximum number of features to return, from 1 to 100 . The default is 10 .
start
(optional)
The ID of the feature after which to start the listing. See the pagination section for details.
GET
/datasets/v1/{username}/{dataset_id}/features
datasets:read Token scope

Example request

curl "https://api.mapbox.com/datasets/v1/{username}/{dataset_id}/features?access_token="

# Limit results to 10 features
curl "https://api.mapbox.com/datasets/v1/{username}/{dataset_id}/features?limit=10&access_token="

# Use pagination to start the listing after the feature with ID f6d9
curl "https://api.mapbox.com/datasets/v1/{username}/{dataset_id}/features?start=f6d9&access_token="

Example response

{
  "type": "FeatureCollection",
  "features": [
    {
      "id": "{feature_id}",
      "type": "Feature",
      "properties": {
        "prop0": "value0"
      },
      "geometry": {
        "coordinates": [ 102,0.5 ],
        "type": "Point"
      }
    },
    {
      "id": "{feature_id}",
      "type": "Feature",
      "properties": {
        "prop0": "value0"
      },
      "geometry": {
        "coordinates": [
          [ 102, 0 ],
          [ 103, 1 ],
          [ 104, 0 ],
          [ 105, 1 ]
        ],
        "type": "LineString"
      }
    }
  ]
}

Insert or update a feature

Insert or update a feature in a specified dataset?:

  • Insert: If a feature with the given feature_id does not already exist, a new feature will be created.
  • Update: If a feature with the given feature_id does exist already, it will be replaced.

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

URL parameters Description
username The username of the account to which the dataset belongs.
dataset_id The ID of the dataset for which to insert or update features.
feature_id The ID of the feature to be inserted or updated.
PUT
/datasets/v1/{username}/{dataset_id}/features/{feature_id}
datasets:write Token scope

Example request

curl "https://api.mapbox.com/datasets/v1/{username}/{dataset_id}/features/{feature_id}?access_token=" \
  -X PUT \
  -H "Content-Type: application/json" \
  -d @file.geojson

Example request body

{
  "id": "{feature_id}",
  "type": "Feature",
  "geometry": {
    "type": "Polygon",
    "coordinates": [
      [
        [ 100, 0 ],
        [ 101, 0 ],
        [ 101, 1 ],
        [ 100, 1 ],
        [ 100, 0 ]
      ]
    ]
  },
  "properties": {
    "prop0": "value0"
  }
}

Example response

{
  "id": "{feature_id}",
  "type": "Feature",
  "geometry": {
    "type": "Polygon",
    "coordinates": [
      [
        [ 100, 0 ],
        [ 101, 0 ],
        [ 101, 1 ],
        [ 100, 1 ],
        [ 100, 0 ]
      ]
    ]
  },
  "properties": {
    "prop0": "value0"
  }
}

Retrieve a feature

Retrieve a specific feature from a dataset?.

URL parameters Description
username The username of the account to which the dataset belongs.
dataset_id The ID of the dataset from which to retrieve a feature.
feature_id The ID of the feature to be retrieved.
GET
/datasets/v1/{username}/{dataset_id}/features/{feature_id}
datasets:read Token scope

Example request

curl "https://api.mapbox.com/datasets/v1/{username}/{dataset_id}/features/{feature_id}?access_token="

Example response

{
  "id": "{feature_id}",
  "type": "Feature",
  "geometry": {
    "type": "Polygon",
    "coordinates": [
      [
        [ 100, 0 ],
        [ 101, 0 ],
        [ 101, 1 ],
        [ 100, 1 ],
        [ 100, 0 ]
      ]
    ]
  },
  "properties": {
    "prop0": "value0"
  }
}

Delete a feature

Remove a specific feature from a dataset?.

URL parameters Description
username The username of the account to which the dataset belongs.
dataset_id The ID of the dataset from which to delete a feature.
feature_id The ID of the feature to be deleted.
DELETE
/datasets/v1/{username}/{dataset_id}/features/{feature_id}
datasets:write Token scope

Example request

curl -X DELETE "https://api.mapbox.com/datasets/v1/{username}/{dataset_id}/features/{feature_id}?access_token="

Example response

HTTP 204

Tilesets

The Mapbox Tilesets API supports reading metadata for raster and vector tilesets. To request tiles, use the Maps API instead.

Restrictions and limits

  • The Tilesets API is limited to 50 requests per minute.
  • Requests must be made over HTTPS. HTTP is not supported.

The tileset object

A request to the Tilesets API returns one or more tileset? objects. Each tileset object contains the following properties:

Property Description
type The kind of data contained, either raster or vector .
center The longitude, latitude, and zoom level for the center of the contained data, given in the format [lon, lat, zoom] .
created A timestamp indicating when the tileset was created.
description A human-readable description of the tileset.
filesize The storage in bytes consumed by the tileset.
id The unique identifier for the tileset.
modified A timestamp indicating when the tileset was last modified.
name The name of the tileset.
visibility The access control for the tileset, either public or private .
status The processing status of the tileset, one of: available , pending , or invalid .

The tileset object

{
  "type": "vector",
  "center": [-0.2680000000000007, 11.7014165, 2],
  "created": "2015-09-09T23:30:17.936Z",
  "description": "",
  "filesize": 17879790,
  "id": "mapbox.05bv6e12",
  "modified": "2015-09-09T23:30:17.906Z",
  "name": "routes.geojson",
  "visibility": "public",
  "status": "available"
}

List tilesets

List all the tilesets that belong to a specific account. This endpoint supports pagination.

URL parameters Description
username The username of the account for which to list tilesets

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

Query Parameter Description
type Filter results by tileset type, either raster or vector .
visibility Filter results by visibility, either public or private . Private tilesets require an access token that belong to the owner. Public tilesets can be requested with any user's access token.
sortby Sort the listings by their created or modified timestamps.
limit The maximum number of tilesets to return, from 1 to 500 . The default is 100 .
start The tileset after which to start the listing. The key is found in the Link header of a response. See the pagination section for details.
GET
/tilesets/v1/{username}
tilesets:list Token scope

Example request

curl "https://api.mapbox.com/tilesets/v1/{username}?access_token="

# Limit the results to the 25 most recently created vector tilesets
curl "https://api.mapbox.com/tilesets/v1/{username}?type=vector&limit=25&sortby=created&access_token="

# Limit the results to the tilesets after the tileset with a start key of abc123
curl "https://api.mapbox.com/tilesets/v1/{username}?start=abc123&access_token="

Example response

[
  {
    "type": "vector",
    "center": [-0.2680000000000007, 11.7014165, 2],
    "created": "2015-09-09T23:30:17.936Z",
    "description": "",
    "filesize": 17879790,
    "id": "mapbox.05bv6e12",
    "modified": "2015-09-09T23:30:17.906Z",
    "name": "routes.geojson",
    "visibility": "public",
    "status": "available"
  },
  {
    "type": "raster",
    "center": [-110.32479628173822, 44.56501277250615, 8],
    "created": "2016-12-10T01:29:37.682Z",
    "description": "",
    "filesize": 794079,
    "id": "mapbox.4umcnx2j",
    "modified": "2016-12-10T01:29:37.289Z",
    "name": "sample-4czm7e",
    "visibility": "private",
    "status": "available"
  }
]

Tilequery

The Mapbox Tilequery API allows you to retrieve data about specific features from a vector tileset?, based on a given latitude and longitude?. The Tilequery API makes it possible to query for features within a radius, do point in polygon queries, query for features in multiple composite layers, and augment data from the Mapbox Geocoding API with custom data.

Mapbox Tilequery API has some functional similarities to the reverse geocoding? function of the Mapbox Geocoding API, which accepts a {longitude},{latitude} pair and returns an address. The Tilequery API returns the location and properties of the features within the query radius.

Restrictions and limits

  • Use of the Tilequery API endpoint is rate limited based on your user plan. The default is 300 requests per minute.
  • Exceeding your user plan's number requests per minute will result in an HTTP 429 Too Many Requests response.
  • For information on rate limit headers, see the Rate limits section.

If you require a higher rate limit, contact us.

The tilequery object

A request to the Tilequery API returns a GeoJSON? FeatureCollection of features at or near the geographic point described by {longitude},{latitude} and within the distance described by the optional radius parameter.

Each feature in the response body also includes a tilequery object, which contains the following additional properties:

Property Description
distance The approximate distance in meters from the feature result to the queried point.
geometry The original geometry type of the feature. This can be ”point” , ”linestring” , or ”polygon” . The actual geometry of the feature is not returned in the result set.
layer The vector tile layer of the feature result.

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 {longitude},{latitude} if the query point exists within the polygon. If the query point is outside the polygon, the geometry is the closest point along the nearest edge of the feature within the radius threshold.
  • For LineString and MultiLineString features, the geometry is the nearest point along the feature within the radius threshold of {longitude},{latitude}.
  • For Point and MultiPoint features, the geometry is the nearest point within the radius threshold of {longitude},{latitude}.

The tilequery object

{
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [
                    -122.42901,
                    37.80633
                ]
            },
            "properties": {
                "class": "wood",
                "type": "wood",
                "tilequery": {
                    "distance": 0,
                    "geometry": "polygon",
                    "layer": "landuse"
                }
            }
        },
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [
                    -122.42901,
                    37.80633
                ]
            },
            "properties": {
                "class": "national_park",
                "type": "national_park",
                "tilequery": {
                    "distance": 0,
                    "geometry": "polygon",
                    "layer": "landuse_overlay"
                }
            }
        }
    ]
}

Retrieve features from vector tiles

Use this endpoint to retrieve features from vector tiles?.

URL parameter Description
map_id The ID of the map being queried. To composite multiple layers, provide a comma-separated list of map IDs.
{lon},{lat} The longitude and latitude to be queried.

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

Query parameter Description
radius
(optional)
The approximate distance in meters to query for features. Defaults to 0 . Has no upper bound. 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. Queries will use tiles from the maximum zoom of the tileset, and will only include the intersecting tile plus 8 surrounding tiles when searching for nearby features.
limit
(optional)
The number of features between 1 - 50 to return. Defaults to 5 .
dedupe
(optional)
Determines whether results will be deduplicated ( true , default) or not ( false ).
geometry
(optional)
Queries for a specific geometry type. Options are polygon , linestring , or point .
layers
(optional)
A comma-separated list of layers to query, rather than querying all layers. If a specified layer does not exist, it is skipped. If no layers exist, returns an empty FeatureCollection .
GET
/v4/{map_id}/tilequery/{lon},{lat}.json

Example requests

# Retrieve features within a 10 meter radius of the specified location
curl "https://api.mapbox.com/v4/mapbox.mapbox-streets-v8/tilequery/-122.42901,37.80633.json?radius=10&access_token="

# Return at most 20 features
curl "https://api.mapbox.com/v4/mapbox.mapbox-streets-v8/tilequery/-122.42901,37.80633.json?limit=20&access_token="

# Query multiple maps
curl "https://api.mapbox.com/v4/{map_id_1},{map_id_2},{map_id_3}/tilequery/-122.42901,37.80633.json&access_token="

# Return only results from the poi_label and building layers within a 30 meter radius of the specified location
curl "https://api.mapbox.com/v4/mapbox.mapbox-streets-v8/tilequery/-122.42901,37.80633.json?radius=30&layers=poi_label,building&access_token="

Example response

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [
          -122.42901,
          37.80633
        ]
      },
      "properties": {
        "class": "national_park",
        "type": "national_park",
        "tilequery": {
          "distance": 0,
          "geometry": "polygon",
          "layer": "landuse_overlay"
        }
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [
          -122.4289919435978,
          37.806283149631255
        ]
      },
      "properties": {
        "localrank": 1,
        "maki": "park",
        "name": "Fort Mason",
        "name_ar": "Fort Mason",
        "name_de": "Fort Mason",
        "name_en": "Fort Mason Center",
        "name_es": "Fort Mason",
        "name_fr": "Fort Mason",
        "name_pt": "Fort Mason",
        "name_ru": "Fort Mason",
        "name_zh": "梅森堡",
        "name_zh-Hans": "梅森堡",
        "ref": "",
        "scalerank": 1,
        "type": "National Park",
        "tilequery": {
          "distance": 5.4376397785894595,
          "geometry": "point",
          "layer": "poi_label"
        }
      }
    }
  ]
}

Geocoding

The Mapbox Geocoding? API does two things: forward geocoding and reverse geocoding.

Forward geocoding converts location text into geographic coordinates, turning 2 Lincoln Memorial Circle NW into -77.050,38.889.

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

For more background information on the Mapbox Geocoding API and how it works, see the How geocoding works guide.

Geocoding plug-ins and libraries

These Mapbox wrapper libraries help you integrate the Mapbox Geocoding API into your existing application seamlessly:

Endpoints

The geocoding? API includes two different endpoints: mapbox.places and mapbox.places-permanent.

mapbox.places

The mapbox-places endpoint is accessible to all geocoding customers. Requests to this endpoint must be triggered by user activity. Any results must be displayed on a Mapbox map and cannot be stored permanently, as described in Mapbox’s terms of service.

mapbox.places-permanent

The mapbox.places-permanent endpoint is accessible to Enterprise customers with a license for permanent geocodes. This endpoint allows for permanent storage of results and for batch geocoding.

Note that the mapbox.places-permanent endpoint does not include POI (point-of-interest) features. The data available for other feature types may vary slightly compared to the data available in the mapbox.places endpoint.

Search for places

The forward geocoding query type allows you to look up a single location by name and returns its geographic coordinates.

Try forward geocoding? in the Search Playground.

URL parameter Description
endpoint One of mapbox.places or mapbox.places-permanent , as described in the Endpoints section .
search_text The feature you’re trying to look up. This could be an address, a point of interest name, a city name, etc. When searching for points if interest, it can also be a category name (for example, “coffee shop”). For information on categories, see the Point of interest category coverage section . The search text should be expressed as a URL-encoded UTF-8 string, and must not contain the semicolon character (either raw or URL-encoded). Your search text, once decoded, must consist of at most 20 words and numbers separated by spacing and punctuation, and at most 256 characters.
access_token All geocoding requests must include a valid Mapbox access token .

You can further refine the results of a forward geocoding query with the following optional parameters:

Query parameter Description
autocomplete
(optional)
Specify whether to return autocomplete results ( true , default) or not ( false ). When autocomplete is enabled, results will be included that start with the requested string, rather than just responses that match it exactly. For example, a query for India might return both India and Indiana with autocomplete enabled, but only India if it’s disabled.
bbox
(optional)
Limit results to only those contained within the supplied bounding box. Bounding boxes should be supplied as four numbers separated by commas, in minLon,minLat,maxLon,maxLat order. The bounding box cannot cross the 180th meridian.
country
(optional)
Limit results to one or more countries. Permitted values are ISO 3166 alpha 2 country codes separated by commas.
fuzzyMatch Specify whether the Geocoding API should attempt approximate, as well as exact, matching when performing searches ( true , default), or whether it should opt out of this behavior and only attempt exact matching ( false ). For example, the default setting might return Washington, DC for a query of wahsington , even though the query was misspelled.
language
(optional)
Specify the user’s language. This parameter controls the language of the text supplied in responses, and also affects result scoring, with results matching the user’s query in the requested language being preferred over results that match in another language. For example, an autocomplete query for things that start with Frank might return Frankfurt as the first result with an English ( en ) language parameter, but Frankreich (“France”) with a German ( de ) language parameter.

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, for applications that need to display labels in multiple languages.

For more information on which specific languages are supported, see the language coverage section .
limit
(optional)
Specify the maximum number of results to return. The default is 5 and the maximum supported is 10 .
proximity
(optional)
Bias the response to favor results that are closer to this location, provided as two comma-separated coordinates in longitude,latitude order.
routing Specify whether to request additional metadata about the recommended navigation destination corresponding to the feature ( true ) or not ( false , default). Only applicable for address features.

For example, if routing=true the response could include data about a point on the road the feature fronts. Response features may include an array containing one or more routable points. Routable points cannot always be determined. Consuming applications should fall back to using the feature’s normal geometry for routing if a separate routable point is not returned.
types
(optional)
Filter results to include only a subset (one or more) of the available feature types. Options are country , region , postcode , district , place , locality , neighborhood , address , and poi . Multiple options can be comma-separated. Note that poi.landmark is a deprecated type that, while still supported, returns the same data as is returned using the poi type.

For more information on the available types, see the data types section .

Interpreting the response

The API response for a forward geocoding query returns a GeoJSON? feature collection in Mapbox Geocoding Response format. For more details on how a response from the Geooding API is formatted, see the response object section.

GET
/geocoding/v5/{endpoint}/{search_text}.json

Example request

# A basic forward geocoding request  
# Find Los Angeles
curl "https://api.mapbox.com/geocoding/v5/mapbox.places/Los%20Angeles.json?access_token="

# Find a town called 'Chester' in a specific region
# Add the proximity parameter with local coordinates
# This ensures the town of Chester, New Jersey is in the results
curl "https://api.mapbox.com/geocoding/v5/mapbox.places/chester.json?proximity=-74.70850,40.78375&access_token="

# Specify types=country to search only for countries named Georgia
# Results will exclude the American state of Georgia
curl "https://api.mapbox.com/geocoding/v5/mapbox.places/georgia.json?types=country&access_token="

# Search for "Starbucks" in Washington, D.C.
# Use a bounding box to limit results to within the district
curl "https://api.mapbox.com/geocoding/v5/mapbox.places/starbucks.json?bbox=-77.083056,38.908611,-76.997778,38.959167&access_token="

# Limit the results to 2 results using the limit option
# 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

The reverse geocoding query type allows you to look up a single pair of coordinates and returns the geographic feature or features that exist at that location.

Batch geocoding? is only available with an Enterprise plan. For other plan levels, one geocode is permitted per request.

Try reverse geocoding in the Search Playground.

URL parameter Description
endpoint One of mapbox.places or mapbox.places-permanent , as described in the Endpoints section .
longitude,latitude A longitude,latitude pair that specifies the location being queried.
access_token All geocoding requests must include a Mapbox access token .

You can further refine the results of a reverse geocoding query with the following optional parameters:

Query parameter Description
country
(optional)
Limit results to one or more countries. Permitted values are ISO 3166 alpha 2 country codes separated by commas.
language
(optional)
Specify the user’s language. This parameter controls the language of the text supplied in responses.

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, for applications that need to display labels in multiple languages.

For more information on which specific languages are supported, see the language coverage section .
limit
(optional)
Specify the maximum number of results to return. The default is 1 and the maximum supported is 10 .

The default behavior in reverse geocoding is to return at most one feature at each of the multiple levels of the administrative hierarchy (for example, one address, one region, one country). Increasing the limit allows returning multiple features of the same type, but only for one type (for example, multiple address results). Consequently, setting limit to a higher-than-default value requires specifying exactly one types parameter.
reverseMode
(optional)
Decides how results are sorted in a reverse geocoding query if multiple results are requested using a limit other than 1 . Options are distance (default), which causes the closest feature to always be returned first, and score , which allows high-prominence features to be sorted higher than nearer, lower-prominence features.
routing Specify whether to request additional metadata about the recommended navigation destination corresponding to the feature ( true ) or not ( false , default). Only applicable for address features.

For example, if routing=true the response could include data about a point on the road the feature fronts. Response features may include an array containing one or more routable points. Routable points cannot always be determined. Consuming applications should fall back to using the feature’s normal geometry for routing if a separate routable point is not returned.
types
(optional)
Filter results to include only a subset (one or more) of the available feature types. Options are country , region , postcode , district , place , locality , neighborhood , address , and poi . Multiple options can be comma-separated. Note that poi.landmark is a deprecated type that, while still supported, returns the same data as is returned using the poi type.

For more information on the available types, see the data types section .

Interpreting the response

The API response for a reverse geocoding query returns a GeoJSON? feature collection in Mapbox Geocoding Response format. For more details on how a response from the Geooding API is formatted, see the response object section.

GET
/geocoding/v5/{endpoint}/{longitude},{latitude}.json

Example request

# A basic reverse geocoding request
# Retrieve places near a specific location
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

The batch geocoding query type allows you to have multiple forward or reverse geocoding queries in a single request. You must have an enterprise plan to use batch geocoding?, and it is only available using the mapbox.places-permanent endpoint. On all other plan levels, one geocode is permitted per request.

Batch geocoding requests are formatted similarly to ordinary forward or reverse geocoding requests, but with multiple search queries one after another, separated by semicolons. Each query should be URL encoded, but the ; character should not be encoded and should be included verbatim.

A batch forward geocoding request can be made using an HTTP GET request:

https://api.mapbox.com/geocoding/v5/mapbox.places-permanent/{search_text_1};{search_text_2}[;{search_text_N};...].json?parameters

A batch reverse geocoding request can be made using an HTTP GET request:

https://api.mapbox.com/geocoding/v5/mapbox.places-permanent/{lon_1},{lat_1};{lon_2},{lat_2}[;{lon_N},{lat_N};...].json?parameters
URL Parameter Description
search_text_N For batch forward queries. The features to look up (addresses, point of interest names, city names, etc.). They should be expressed as URL-encoded UTF-8 strings, and must not contain the semicolon character (either raw or URL-encoded), as this is the delimiter between search items. Each search text, once decoded, must consist of at most 20 words and numbers separated by spacing and punctuation, and at most 256 characters. You may supply at most 50 search texts within one request.
{lon_N},{lat_N} For batch reverse queries. The longitude and latitude, respectively, of the locations being queried. You may supply at most 50 longitude-latitude coordinate pairs within one request.
access_token All geocoding requests must include an access token.

For batch forward queries, you may use any optional parameters that are available for single forward queries, and they will apply to all search texts. Likewise, for reverse queries, you may use any optional parameters that apply to single reverse queries.

Interpreting the response

The response from batch geocoding query is an array of results in GeoJSON feature collection format.

[
  <response for 1st query> { }
  <response for 2nd query> { }
  ...
]

Details on the format and properties of Geocoding API responses can be found in the response object section.

Example request

curl "https://api.mapbox.com/geocoding/v5/mapbox.places-permanent/20001;20009;22209.json?access_token="

Response object

The response to a Geocoding? API request is an object that contains the following properties:

Property Description
type "FeatureCollection" , a GeoJSON type from the GeoJSON specification .
query Forward geocodes: An array of space and punctuation-separated strings from the original query.
Reverse geocodes: An array containing the coordinates being queried.
features An array of feature objects.
Forward geocodes: Returned features are ordered by relevance .
Reverse geocodes: Returned features are ordered by index hierarchy, from most specific features to least specific features that overlap the queried coordinates.
attribution A string that attributes the results of the Mapbox Geocoding API to Mapbox.

Feature object

Mapbox's geocoding data is constantly being updated and improved. This means that 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 API version.

Each feature object in the features array may have the properties described below:

Property Description
id A feature ID in the format {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.
type "Feature" , a GeoJSON type from the GeoJSON specification .
place_type An array of feature types describing the feature. Options are country , region , postcode , district , place , locality , neighborhood , address , and poi . Most features have only one type, but if the feature has multiple types, all applicable types will be listed in the array. (For example, Vatican City is a country , region , and place .)
relevance A score from 0 (least relevant) to 1 (most relevant) that measures the textual match of each returned feature to the query. You can use the relevance property to remove results that 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 properties object may change with data improvements. 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)
Describes whether or not the feature is in the poi.landmark data type. This data type is deprecated, and this property will be present on all poi features for backwards compatibility reasons but will always be true .
properties.wikidata
(optional)
The Wikidata identifier for the returned feature.
properties.short_code
(optional)
The ISO 3166-1 country and ISO 3166-2 region code for the returned feature.
text 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 ( en ) 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 ( en ) 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 multiple languages are requested using the language parameter, 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 multiple languages are requested using the language parameter, and will be present for each requested language.
language
(optional)
A string of the IETF language tag of the query’s primary language.
language_{language}
(optional)
A string of the IETF language tag of the query’s fallback language. This field is only returned when multiple languages are requested using the language parameter, and will be present for each requested language.
bbox A bounding box array in the form [minX,minY,maxX,maxY] .
center The coordinates of the feature’s center in the form [longitude,latitude] . This may be the literal centroid of the feature’s geometry, or the center of human activity within the feature (for example, the downtown area of a city).
geometry An object describing the spatial geometry of the returned feature.
geometry.type "Point" , a GeoJSON type from the GeoJSON specification .
geometry.coordinates An array in the format [longitude,latitude] at the center of the specified bbox .
geometry.interpolated
(optional)
If present, indicates that an address is interpolated along a road network. The geocoder can usually return exact address points, but if an address is not present the geocoder can use interpolated data as a fallback. In edge cases, interpolation may not be possible if surrounding address data is not present, in which case the next fallback will be the center point of the street feature itself.
context An array representing the hierarchy of encompassing parent features. Each parent feature may include any of the above properties.
routable_points
(optional)
An object with the routable points for the feature.
routable_points.points
(optional)
An array of points in the form of [{ coordinates: [lon, lat] }] , or null if no points were found.

Example forward geocoding response object

{
  "type": "FeatureCollection",
  "query": [
    "los",
    "angeles"
  ],
  "features": [
    {
      "id": "place.9962989141465270",
      "type": "Feature",
      "place_type": [
        "place"
      ],
      "relevance": 0.99,
      "properties": {
        "wikidata": "Q65"
      },
      "text": "Los Angeles",
      "place_name": "Los Angeles, California, United States",
      "bbox": [
        -118.529221009603,
        33.901599990108,
        -118.121099990025,
        34.1612200099034
      ],
      "center": [
        -118.2439,
        34.0544
      ],
      "geometry": {
        "type": "Point",
        "coordinates": [
          -118.2439,
          34.0544
        ]
      },
      "context": [
        {
          "id": "region.3591",
          "short_code": "US-CA",
          "wikidata": "Q99",
          "text": "California"
        },
        {
          "id": "country.3145",
          "short_code": "us",
          "wikidata": "Q30",
          "text": "United States"
        }
      ]
    },
    {
      "id": "place.10952642230180310",
      "type": "Feature",
      "place_type": [
        "place"
      ],
      "relevance": 0.99,
      "properties": {
        "wikidata": "Q16910"
      },
      "text": "Los Ángeles",
      "place_name": "Los Ángeles, Bío Bío, Chile",
      "bbox": [
        -72.68248,
        -37.663862,
        -72.041277,
        -37.178368
      ],
      "center": [
        -72.35,
        -37.46667
      ],
      "geometry": {
        "type": "Point",
        "coordinates": [
          -72.35,
          -37.46667
        ]
      },
      "context": [
        {
          "id": "region.3552",
          "short_code": "CL-BI",
          "wikidata": "Q2170",
          "text": "Bío Bío"
        },
        {
          "id": "country.344",
          "short_code": "cl",
          "wikidata": "Q298",
          "text": "Chile"
        }
      ]
    },
    {
      "id": "poi.1611278850983920",
      "type": "Feature",
      "place_type": [
        "poi"
      ],
      "relevance": 0.99,
      "properties": {
        "address": "1 World Way",
        "category": "international airport, airport",
        "tel": "(310) 646-5252",
        "wikidata": "Q8731",
        "landmark": true,
        "maki": "airport"
      },
      "text": "Los Angeles International Airport",
      "place_name": "Los Angeles International Airport, 1 World Way, Los Angeles, California 90045, United States",
      "center": [
        -118.408056,
        33.9425
      ],
      "geometry": {
        "coordinates": [
          -118.408056,
          33.9425
        ],
        "type": "Point"
      },
      "context": [
        {
          "id": "neighborhood.33720",
          "text": "Westchester"
        },
        {
          "id": "postcode.8081932850252730",
          "text": "90045"
        },
        {
          "id": "place.9962989141465270",
          "wikidata": "Q65",
          "text": "Los Angeles"
        },
        {
          "id": "region.3591",
          "short_code": "US-CA",
          "wikidata": "Q99",
          "text": "California"
        },
        {
          "id": "country.3145",
          "short_code": "us",
          "wikidata": "Q30",
          "text": "United States"
        }
      ]
    },
    {
      "id": "neighborhood.2104633",
      "type": "Feature",
      "place_type": [
        "neighborhood"
      ],
      "relevance": 0.99,
      "properties": {},
      "text": "Los Angeles Heights - Keystone",
      "place_name": "Los Angeles Heights - Keystone, San Antonio, Texas 78201, United States",
      "bbox": [
        -98.534942,
        29.453364,
        -98.514652,
        29.485214
      ],
      "center": [
        -98.52,
        29.47
      ],
      "geometry": {
        "type": "Point",
        "coordinates": [
          -98.52,
          29.47
        ]
      },
      "context": [
        {
          "id": "postcode.7069290925572850",
          "text": "78201"
        },
        {
          "id": "place.7705127234253710",
          "wikidata": "Q975",
          "text": "San Antonio"
        },
        {
          "id": "region.3818",
          "short_code": "US-TX",
          "wikidata": "Q1439",
          "text": "Texas"
        },
        {
          "id": "country.3145",
          "short_code": "us",
          "wikidata": "Q30",
          "text": "United States"
        }
      ]
    },
    {
      "id": "poi.17555628334440500",
      "type": "Feature",
      "place_type": [
        "poi"
      ],
      "relevance": 0.99,
      "properties": {
        "address": "3939 S Figueroa St",
        "category": "stadium, arena",
        "tel": "(213) 747-7111",
        "wikidata": "Q849784",
        "landmark": true,
        "maki": "baseball"
      },
      "text": "Los Angeles Memorial Coliseum",
      "place_name": "Los Angeles Memorial Coliseum, 3939 S Figueroa St, Los Angeles, California 90037, United States",
      "center": [
        -118.287778,
        34.014167
      ],
      "geometry": {
        "coordinates": [
          -118.287778,
          34.014167
        ],
        "type": "Point"
      },
      "context": [
        {
          "id": "neighborhood.293901",
          "text": "South Los Angeles"
        },
        {
          "id": "postcode.15612390715732530",
          "text": "90037"
        },
        {
          "id": "place.9962989141465270",
          "wikidata": "Q65",
          "text": "Los Angeles"
        },
        {
          "id": "region.3591",
          "short_code": "US-CA",
          "wikidata": "Q99",
          "text": "California"
        },
        {
          "id": "country.3145",
          "short_code": "us",
          "wikidata": "Q30",
          "text": "United States"
        }
      ]
    }
  ],
  "attribution": "NOTICE: © 2018 Mapbox and its suppliers. All rights reserved. Use of this data is subject to the Mapbox Terms of Service (https://www.mapbox.com/about/maps/). This response and the information it contains may not be retained."
}

Data types

Various types of geographic features are available in the Mapbox geocoder. Any type might appear as a top-level response, as context in a top-level response, or as a filtering option using the types parameter. Not all features are available or relevant in all parts of the world. New types are occasionally added as necessary to correctly capture global administrative hierarchies.

The data types available in the geocoder are:

Data type Description
country Generally recognized countries or, in some cases like Hong Kong, an area of quasi-national administrative status that has been given a designated country code under ISO 3166-1.
region Top-level sub-national administrative features, such as states in the United States or provinces in Canada or China.
postcode Postal codes used in country-specific national addressing systems.
district Features that are smaller than top-level administrative features but typically larger than cities, in countries that use such an additional layer in postal addressing (for example, prefectures in China).
place Typically these are cities, villages, municipalities, etc. They’re usually features used in postal addressing, and are suitable for display in ambient end-user applications where current-location context is needed (for example, in weather displays).
locality Official sub-city features present in countries where such an additional administrative layer is used in postal addressing, or where such features are commonly referred to in local parlance. Examples include city districts in Brazil and Chile and arrondissements in France.
neighborhood Colloquial sub-city features often referred to in local parlance. Unlike locality features, these typically lack official status and may lack universally agreed-upon boundaries.
address Individual residential or business addresses.
poi Points of interest. These include restaurants, stores, concert venues, parks, museums, etc.

Geographic coverage

Data availability in the geocoder varies by country and feature type.

The Mapbox Geocoding API coverage map lists the types of geocoding? results supported in each area of the world.

Language coverage

Translation availability also varies by language and region. We provide the following tiers of language support:

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
ca Catalan cs Czech fi Finnish
he Hebrew hu Hungarian is Icelandic
fi Finnish ka Georgian ja Japanese
ko Korean lv Latvian nb Norwegian Bokmål
pl Polish pt Portuguese sk Slovak
sl Slovenian sr Serbian th Thai
tl Tagalog 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 bg (Bulgarian) bs (Bosnian)
da (Danish) es Spanish id (Indonesian)
kk Kazakh mn (Mongolian) sq Albanian
ro (Romanian) sv (Swedish) tr Turkish
zh (Chinese)

Geocoding rate limits

Rate limits vary by plan level and are enforced per account. Each plan includes up to:

Plan level Rate limit Batch geocoding Store results
Pay-as-you-go 600 requests per minute
Commercial 600 requests per minute
Enterprise 2,400+ requests per minute

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

For more information on plans, see the Mapbox Plans and pricing page.

Point of interest category coverage

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.

Some of the most common POI categories are:

  • advertising, marketing
  • airport
  • amusement park, theme park
  • assisted living service, assisted, assisted living, home
  • athletic field, sports field
  • bagel, donut
  • bar, alcohol
  • base, military
  • beach
  • beauty, hair, salon, barber
  • beer, wine, spirit, alcohol, booze
  • bicycle, bike, cycle
  • boating
  • bookstore, book shop
  • bowling, bowl, bowling alley
  • brewery, beer
  • bus station, bus stop, bus
  • campground, rv park
  • candy store, candy, candies, confectionary, chocolatier, chocolate
  • car rental, truck rental
  • car wash, detail, car detail, car wax
  • casinos, gaming
  • category search
  • cemetery, graveyard, mausoleum
  • clothing, accessories, apparel
  • college, university
  • combat sports, boxing, martial arts, fighting
  • computer, electronic
  • contractor, repair
  • dance
  • day care, preschool, daycare, child care
  • department store, big box store, department
  • dog park
  • drug services, alcohol services, clinic
  • dry cleaning, laundry, dry cleaner, laundry service, laundromat
  • education, school
  • embassy, foreign
  • er, emergency room
  • fast food
  • fire stations, fire house, fire department
  • florist, flowers, flower shop
  • forest, woods
  • funeral service, funeral home
  • furniture, decor
  • garden
  • gas station, fuel, gas
  • gift, novelty
  • glasses, optical
  • government agency
  • gun range
  • home improvement, repairman, handyman, repair
  • hospital, clinic, medical center
  • hotel, motel
  • houseware, home goods
  • ice cream parlor, ice cream
  • insurance
  • jewelry, watches, accessories
  • juice bar, smoothie, juice
  • lake
  • landmark
  • legal, lawyer, law, law office
  • lodging
  • massage, masseuse
  • meat, seafood, butcher, deli
  • miniature golf, minigolf
  • mountain
  • museum
  • music, show venue, concert, concert hall
  • natural park
  • newsstand, newspaper, news, magazine
  • night club, disco
  • notary, notary public
  • nursery, garden, garden center
  • outdoors
  • painting, art
  • park
  • parking, parking lot
  • pet, petshop, dog, cat
  • pharmacy
  • photo, frame, framing
  • photography, photo service
  • physical therapy, rehabilitation
  • pizza, restaurant
  • police station, law enforcement
  • port, ferry
  • post office, mail
  • professional cleaning, cleaning
  • rail station, train station
  • real estate agent, realtor, real estate agency
  • rest area, rest stop, pitstop
  • restaurant
  • scuba diving, pool
  • shoes, apparel
  • shopping center, mall, shopping mall
  • spa
  • sporting good, sports store
  • storage, storage facility, storage lot
  • supermarket, groceries, grocery, market, super
  • swimming pool, pool, swim club
  • tailor
  • tattoo, tattooing
  • theater, movie theater, cinema
  • tour, travel agent
  • tourist information, services, tourism, information
  • toy, toy shop
  • utility companies, utilities, utility, public utility, electricity, natural gas, - water, sewage, power company
  • vehicle maintenance, car maintenance, vehicle repair, car repair
  • winery, vineyard, wine tasting
  • zoo, aquarium, wildlife sanctuary

The current list of POI categories is subject to change.

Directions

This documentation is for v5 of the Directions API. For information about the earlier version, see the v4 documentation.

The Mapbox Directions API will show you how to get where you're going. With the Directions API, you can:

  • Calculate optimal driving, walking, and cycling routes using traffic- and incident-aware routing
  • Produce turn-by-turn instructions
  • Produce routes with up to 25 coordinates anywhere on earth

This API supports 4 different routing profiles:

Profile Description
mapbox/driving-traffic For automotive routing. This profile factors in current and historic traffic conditions to avoid slowdowns. Traffic information is available in these supported geographies .
mapbox/driving For automotive 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 shortest path by using sidewalks and trails.
mapbox/cycling For bicycle routing. This profile shows routes that are short and safer for cyclists by avoiding highways and preferring streets with bike lanes.

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

Restrictions and limits

  • Requests using the driving, walking, and cycling profiles can specify up to 25 total waypoints (input coordinates that are snapped to the roads network) along the route.
  • Requests using the driving-traffic profile can specify up to 3 waypoints along the route.
  • 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.
  • Maximum 300 requests per minute.
  • Maximum total of 10,000 kilometers between all waypoints.

Retrieve directions

Retrieve directions between waypoints. Directions requests must specify at least two waypoints as starting and ending points.

Try this in the API Playground.

URL parameter Description
profile The routing profile to use. Possible values are mapbox/driving-traffic , mapbox/driving , mapbox/walking , or mapbox/cycling .
coordinates A semicolon-separated list of {longitude},{latitude} coordinate pairs to visit in order. There can be between 2 and 25 coordinates for most requests, or up to 3 coordinates for driving-traffic requests.

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

Query parameter Description
alternatives
(optional)
Whether to try to return alternative routes ( true ) or not ( false , default). An alternative route is a route that is significantly different than the fastest route, but also still reasonably fast. Such a route does not exist in all circumstances. Up to 2 alternatives may be returned.
annotations
(optional)
Return additional metadata along the route. Possible values are: duration , distance , speed , and congestion . You can include several annotations as a comma-separated list. See the route leg object for more details on what is included with annotations. Must be used in conjunction with overview=full .
approaches
(optional)
A 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. However, you can skip a coordinate and show its position in the list with the ; separator. Must be used in combination with steps=true .
banner_instructions
(optional)
Whether to return banner objects associated with the route steps ( true ) or not ( false , default). Must be used in conjunction with steps=true .
bearings
(optional)
Influences the direction in which a route starts from a waypoint. Used to filter the road segment the waypoint will be placed on 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 conjunction with the radiuses parameter. Takes 2 comma-separated 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 coordinates. However, you can skip a coordinate and show its position in the list with the ; separator.
continue_straight
(optional)
Sets the 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 .
exclude
(optional)
Exclude certain road types from routing. The default is to not exclude anything from the profile selected. The following exclude flags are available for each profile:
Profile Available excludes
mapbox/driving One of toll , motorway , or ferry
mapbox/driving-traffic One of toll , motorway , or ferry
mapbox/walking No excludes supported
mapbox/cycling ferry
geometries
(optional)
The format of the returned geometry. Allowed values are: geojson (as LineString ), polyline (default, a polyline with precision 5), polyline6 (a polyline with precision 6).
language
(optional)
The language of returned turn-by-turn text instructions. See supported languages . The default is en (English). Must be used in combination with steps=true .
overview
(optional)
The type of 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).
radiuses
(optional)
The 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 found within the radius.
roundabout_exits
(optional)
Whether to emit instructions at roundabout exits ( true ) or not ( false , default). Without this parameter, roundabout maneuvers are given as a single instruction that includes both entering and exiting the roundabout. With roundabout_exits=true , this maneuver becomes two instructions, one for entering the roundabout and one for exiting it.
steps
(optional)
Whether to return steps and turn-by-turn instructions ( true ) or not ( false , default).
voice_instructions
(optional)
Whether to return SSML marked-up text for voice guidance along the route ( true ) or not ( false , default). Must be used in conjunction with steps=true .
voice_units
(optional)
Specify which type of units to return in the text for voice instructions. Can be imperial (default) or metric . Must be used in conjunction with be used in conjunction with steps=true and voice_instructions=true .
waypoint_names
(optional)
A semicolon-separated list of custom names for entries in the list of coordinates , used for the arrival instruction in banners and voice instructions. Values can be any string, and the total number of all characters cannot exceed 500. If provided, the list of waypoint_names must be the same length as the list of coordinates , but you can skip a coordinate pair and show its position in the list with the ; separator.
waypoint_targets
(optional)
A semicolon-separated list of coordinate pairs used to specify drop-off locations that are distinct from the locations specified in coordinates . If this parameter is provided, the Directions API will compute the side of the street, left or right, for each target based on the  waypoint_targets and the driving direction. The maneuver.modifier , banner and voice instructions will be updated with the computed side of street. The number of waypoint_targets must be the same as the number of coordinates , but you can skip a coordinate pair and show its position in the list with the ; separator. Must be used with steps=true .

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

Instructions languages

The table below shows supported language codes used with the language parameter for turn-by-turn instructions. The language parameter will automatically be set to en (English) if an unsupported language code is used.

Code Language
da Danish
de German
en English
eo Esperanto
es Spanish
es-ES Spanish (Spain)
fi Finnish
fr French
he Hebrew
id Indonesian
it Italian
ko Korean
my Burmese
nl Dutch
no Norwegian (Bokmål)
pl Polish
pt-BR Portuguese (Brazil)
pt-PT Portuguese (Portugal)
ro Romanian
ru Russian
sv Swedish
tr Turkish
uk Ukrainian
vi Vietnamese
zh-Hans Chinese (Simplified)
GET
/directions/v5/{profile}/{coordinates}

Example request

# Request directions with no additional options
curl "https://api.mapbox.com/directions/v5/mapbox/cycling/-122.42,37.78;-77.03,38.91?access_token="

# Request directions with steps and alternatives
curl "https://api.mapbox.com/directions/v5/mapbox/cycling/-122.42,37.78;-77.03,38.91?steps=true&alternatives=true&access_token="

# Request directions with radiuses and a polyline6 response through multiple waypoints
curl "https://api.mapbox.com/directions/v5/mapbox/driving/13.43,52.51;13.42,52.5;13.41,52.5?radiuses=40;;100&geometries=polyline6&access_token="

# Specify bearings and radiuses
curl "https://api.mapbox.com/directions/v5/mapbox/driving/13.43,52.51;13.42,52.5;13.43,52.5?bearings=60,45;;45,45&radiuses=100;100;100&access_token="

# Request a route that approaches the destination on the curb of the driving side
curl "https://api.mapbox.com/directions/v5/mapbox/driving/13.43,52.51;13.43,52.5?approaches=unrestricted;curb&access_token="

# Request directions with voice and banner instructions
curl "https://api.mapbox.com/directions/v5/mapbox/cycling/-122.42,37.78;-77.03,38.91?steps=true&voice_instructions=true&banner_instructions=true&voice_units=imperial&access_token="

# Request directions with voice and banner instructions specifying waypoint_names
curl "https://api.mapbox.com/directions/v5/mapbox/cycling/-122.42,37.78;-77.03,38.91?steps=true&voice_instructions=true&banner_instructions=true&voice_units=imperial&waypoint_names=Home;Work&access_token="

Directions response object

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

Property Description
code A string indicating the state of the response. This is a different code than the HTTP status code. On normal valid responses, the value will be Ok . For other responses, see the Directions API errors table .
waypoints An 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.
routes An array of route objects ordered by descending recommendation rank. The response object may contain at most 2 routes.

Example response object

{
  "routes": [
    {
      "geometry": "mnn_Ick}pAfBiF`CzA",
      "legs": [
        {
          "summary": "Köpenicker Straße, Engeldamm",
          "weight": 44.4,
          "duration": 26.2,
          "steps": [
            {
              "intersections": [
                {
                  "out": 0,
                  "entry": [ true ],
                  "bearings": [ 125 ],
                  "location": [ 13.426579, 52.508068 ]
                },
                {
                  "out": 1,
                  "in": 2,
                  "entry": [ true, true, false ],
                  "bearings": [ 30, 120, 300 ],
                  "location": [ 13.426688, 52.508022 ]
                }
              ],
              "driving_side": "right",
              "geometry": "mnn_Ick}pAHUlAqDNa@",
              "mode": "driving",
              "maneuver": {
                "bearing_after": 125,
                "bearing_before": 0,
                "location": [ 13.426579, 52.508068 ],
                "modifier": "right",
                "type": "depart",
                "instruction": "Head southeast on Köpenicker Straße (L 1066)"
              },
              "ref": "L 1066",
              "weight": 35.9,
              "duration": 17.7,
              "name": "Köpenicker Straße (L 1066)",
              "distance": 98.1,
              "voiceInstructions": [
                {
                  "distanceAlongGeometry": 98.1,
                  "announcement": "Head southeast on Köpenicker Straße (L 1066), then turn right onto Engeldamm",
                  "ssmlAnnouncement": "<speak><amazon:effect name=\"drc\"><prosody rate=\"1.08\">Head southeast on Köpenicker Straße (L <say-as interpret-as=\"address\">1066</say-as>), then turn right onto Engeldamm</prosody></amazon:effect></speak>"
                },
                {
                  "distanceAlongGeometry": 83.1,
                  "announcement": "Turn right onto Engeldamm, then you will arrive at your destination",
                  "ssmlAnnouncement": "<speak><amazon:effect name=\"drc\"><prosody rate=\"1.08\">Turn right onto Engeldamm, then you will arrive at your destination</prosody></amazon:effect></speak>"
                }
              ],
              "bannerInstructions": [
                {
                  "distanceAlongGeometry": 98.1,
                  "primary": {
                    "text": "Engeldamm",
                    "components": [ { "text": "Engeldamm" } ],
                    "type": "turn",
                    "modifier": "right"
                  },
                  "secondary": null,
                  "then": null
                }
              ]
            },
            {
              "intersections": [
                {
                  "out": 2,
                  "in": 3,
                  "entry": [ false, true, true, false ],
                  "bearings": [ 30, 120, 210, 300 ],
                  "location": [ 13.427752, 52.50755 ]
                }
              ],
              "driving_side": "right",
              "geometry": "ekn_Imr}pARL\\T^RHDd@\\",
              "mode": "driving",
              "maneuver": {
                "bearing_after": 202,
                "bearing_before": 125,
                "location": [ 13.427752, 52.50755 ],
                "modifier": "right",
                "type": "turn",
                "instruction": "Turn right onto Engeldamm"
              },
              "weight": 8.5,
              "duration": 8.5,
              "name": "Engeldamm",
              "distance": 78.6,
              "voiceInstructions": [
                {
                  "distanceAlongGeometry": 27.7,
                  "announcement": "You have arrived at your destination",
                  "ssmlAnnouncement": "<speak><amazon:effect name=\"drc\"><prosody rate=\"1.08\">You have arrived at your destination</prosody></amazon:effect></speak>"
                }
              ],
              "bannerInstructions": [
                {
                  "distanceAlongGeometry": 78.6,
                  "primary": {
                    "text": "You will arrive at your destination",
                    "components": [ { "text": "You will arrive at your destination" } ],
                    "type": "arrive",
                    "modifier": "straight"
                  },
                  "secondary": {
                    "text": "Engeldamm",
                    "components": [ { "text": "Engeldamm" } ],
                    "type": "arrive",
                    "modifier": "straight"
                  }
                },
                {
                  "distanceAlongGeometry": 15,
                  "primary": {
                    "text": "You have arrived at your destination",
                    "components": [ { "text": "You have arrived at your destination" } ],
                    "type": "arrive",
                    "modifier": "straight"
                  },
                  "secondary": {
                    "text": "Engeldamm",
                    "components": [ { "text": "Engeldamm" } ]
                  }
                }
              ]
            },
            {
              "intersections": [
                {
                  "in": 0,
                  "entry": [ true ],
                  "bearings": [ 25 ],
                  "location": [ 13.427292, 52.506902 ]
                }
              ],
              "driving_side": "right",
              "geometry": "cgn_Iqo}pA",
              "mode": "driving",
              "maneuver": {
                "bearing_after": 0,
                "bearing_before": 205,
                "location": [ 13.427292, 52.506902 ],
                "type": "arrive",
                "instruction": "You have arrived at your destination"
              },
              "weight": 0,
              "duration": 0,
              "name": "Engeldamm",
              "distance": 0,
              "voiceInstructions": [ ],
              "bannerInstructions": [ ]
            }
          ],
          "distance": 176.7
        }
      ],
      "weight_name": "routability",
      "weight": 44.4,
      "duration": 26.2,
      "distance": 176.7
    }
  ],
  "waypoints": [
    {
      "name": "Köpenicker Straße",
      "location": [ 13.426579, 52.508068 ]
    },
    {
      "name": "Engeldamm",
      "location": [ 13.427292, 52.506902 ]
    }
  ],
  "code": "Ok",
  "uuid": "cjd51uqn5005447p8nte2zc4w"
}

Waypoint object

The response body of a Directions API query contains a waypoint object, the input coordinates snapped to the roads network. A waypoint object contains the following properties:

Property Description
name A string with the name of the road or path to which the input coordinate has been snapped.
location An array containing the [longitude, latitude] of the snapped coordinate.

Example waypoint object

{
    "name": "Kirkjubøarvegur",
    "location": [ -6.80897, 62.000075 ]
}

Route object

The response body of a Directions API query also contains an array of route objects. A route object describes a route through multiple waypoints. A route object contains the following properties:

Property Description
duration A float indicating the estimated travel time through the waypoints in seconds.
distance A float indicating the distance traveled through the waypoints in meters.
weight_name A string indicating which weight was used. The default is routability , which is duration-based, with additional penalties for less desirable maneuvers.
weight A float indicating the weight in units described by weight_name .
geometry Depending on the geometries query parameter, this is either a GeoJSON LineString or a Polyline string . Depending on the overview query 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 ).
legs An array of route leg objects.
voiceLocale A string of the locale used for voice instructions. Defaults to en (English). Can be any accepted instruction language . voiceLocale is only present in the response when voice_instructions=true .

Example route object

{
    "duration": 88.4,
    "distance": 830.4,
    "weight": 88.4,
    "weight_name": "routability",
    "geometry": "oklyJ`{ph@yBuY_F{^_FxJoBrBs@d@mAT",
    "legs": [ ],
    "voiceLocale": "en"
}

Route leg object

A route object contains a nested route leg object for each leg of the journey, which is one fewer than the number of input coordinates. A route leg object contains the following properties:

Property Description
distance A number indicating the distance traveled between waypoints in meters.
duration A number indicating the estimated travel time between waypoints in seconds.
steps Depending on the optional steps parameter, either an array of route step objects ( steps=true ) or an empty array ( steps=false , default).
summary A string summarizing the route.
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. See the following table for more information about the annotation object:
annotation Description
distance The distance between each pair of coordinates in meters.
duration The duration between each pair of coordinates in seconds.
speed The speed between each pair of coordinates in meters per second.
congestion The level of congestion, described as severe , heavy , moderate , low or unknown , between each entry in the array of coordinate pairs in the route leg. 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.

Example route leg object

{
    "annotation": {
        "distance": [
            4.294596842089401,
            5.051172053200946,
            5.533254065167979,
            6.576513793849532,
            7.4449640160938015,
            8.468757534990829,
            15.202780313562714,
            7.056346577326572
        ],
        "duration": [
            1,
            1.2,
            2,
            1.6,
            1.8,
            2,
            3.6,
            1.7
        ],
        "speed": [
            4.3,
            4.2,
            2.8,
            4.1,
            4.1,
            4.2,
            4.2,
            4.2
        ],
        "congestion": [
            "low",
            "moderate",
            "moderate",
            "moderate",
            "heavy",
            "heavy",
            "heavy",
            "heavy"
        ]
    },
    "duration": 14.3,
    "weight": 14.3,
    "distance": 53.4,
    "steps": [],
    "summary": ""
}

Route step object

In a route leg object, a nested route step object includes one step maneuver object as well as information about travel to the following route step:

Property Description
maneuver One step maneuver object.
distance A number indicating the distance traveled in meters from the maneuver to the next route step.
duration A number indicating the estimated time traveled in seconds from the maneuver to the next route step.
geometry Depending on the geometries parameter, this is a GeoJSON LineString or a Polyline string representing the full route geometry from this route step to the next route step.
name A string with the name of the road or path that forms part of the route step.
ref Any road designations associated with the road or path leading from this step’s maneuver to the next step’s maneuver. If multiple road designations are associated with the road, they are separated by semicolons. Typically consists of an alphabetic network code (identifying the road type or numbering system), a space or hyphen, and a route number . Optionally included, if data is available.
Note: A network code is not necessarily globally unique, and should not be treated as though it is. A route number may not uniquely identify a road within a given network.
destinations A string with the destinations of the road or path along which the travel proceeds. Optionally included, if data is available.
exits A string with the exit numbers or names of the road or path. Optionally included, if data is available.
driving_side The legal driving side at the location for this step. Either left or right .
mode A string indicating the mode of transportation.
Profile Possible values
mapbox/driving driving , ferry , unaccessible
mapbox/walking walking , ferry , unaccessible
mapbox/cycling cycling , walking , ferry , train , unaccessible
pronunciation A string containing an IPA phonetic transcription indicating how to pronounce the name in the name property. Omitted if pronunciation data is not available for the step.
intersections An array of objects representing all the intersections along the step. See the following table for more information on the intersections array:
intersections Description
location A [longitude, latitude] pair describing the location of the turn.
bearings A list of bearing values 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 Description
toll Road continues on a toll road
ferry Road continues on a ferry
restricted Road continues on with access restrictions
motorway Road continues on a motorway
tunnel Road continues in a tunnel
entry A list of entry flags, corresponding 1:1 to bearings . If true , indicates that the respective road could be entered on a valid route. If false , the turn onto the respective road would violate a restriction.
in The index in the bearings and entry arrays. 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 The index in the bearings and entry arrays. 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 arrival maneuvers.
lanes An 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.

Example route step object

{
    "intersections": [
      {
        "out": 1,
        "location": [ 13.424671, 52.508812 ],
        "bearings": [ 120, 210, 300 ],
        "entry": [ false, true, true ],
        "in": 0,
        "lanes": [
          {
            "valid": true,
            "indications": [ "left" ]
          },
          {
            "valid": true,
            "indications": [ "straight" ]
          },
          {
            "valid": false,
            "indications": [ "right" ]
          }
        ]
      }
    ],
    "geometry": "asn_Ie_}pAdKxG",
    "maneuver": {
      "bearing_after": 202,
      "type": "turn",
      "modifier": "left",
      "bearing_before": 299,
      "location": [ 13.424671, 52.508812 ],
      "instruction": "Turn left onto Adalbertstraße"
    },
    "duration": 59.1,
    "distance": 236.9,
    "driving_side": "right",
    "weight": 59.1,
    "name": "Adalbertstraße",
    "mode": "driving"
}

Step maneuver object

A route step object contains a nested step maneuver object, which contains the following properties:

Property Description
bearing_before A number between 0 and 360 indicating the clockwise angle from true north to the direction of travel immediately before the maneuver.
bearing_after A number between 0 and 360 indicating the clockwise angle from true north to the direction of travel immediately after the maneuver.
instruction A human-readable instruction of how to execute the returned maneuver.
location An array of [longitude, latitude] coordinates for the point of the maneuver.
modifier An optional string indicating the direction change of the maneuver. The meaning of each modifier depends on the type property.
Possible values Description
uturn Indicates a reversal of direction. type can be turn or continue when staying on the same road.
sharp right A sharp right turn.
right A normal turn to the right.
slight right A slight turn to the right.
straight No relevant change in direction.
slight left A slight turn to the left.
left A normal turn to the left.
sharp left A sharp turn to the left.
type A string indicating the type of maneuver. See the full list of maneuver types in the maneuver types table .
  • If no modifier is provided, the type of maneuvers is limited to depart and arrive.
  • If the source or target location is close enough to the depart or arrive location, no modifier will be given.

Maneuver types

type Description
turn A basic turn in the direction of the modifier.
new name The road name changes (after a mandatory turn).
depart Indicates departure from a leg. The modifier value indicates the position of the departure point in relation to the current direction of travel.
arrive Indicates arrival to a destination of a leg. The modifier value indicates the position of the arrival point in relation to the current direction of travel.
merge Merge onto a street.
on ramp Take a ramp to enter a highway.
off ramp Take a ramp to exit a highway.
fork Take the left or right side of a fork.
end of road Road ends in a T intersection.
continue Continue on a street after a turn.
roundabout Traverse roundabout. Has an additional property exit in the route step that contains 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 parameters, rotary_pronunciation parameters, or both, located in the route step object in addition to the exit property.
roundabout turn A small roundabout that is treated as an intersection.
notification Indicates a change of driving conditions, for example changing the mode from driving to ferry .
exit roundabout Indicates the exit maneuver from a roundabout. Will not appear in results unless you supply the roundabout_exits=true query parameter in the request.
exit rotary Indicates the exit maneuver from a rotary. Will not appear in results unless you supply the roundabout_exits=true query parameter in the request.

Note: New properties (potentially depending on type) may be introduced in the future without an API version change.

Example step maneuver object

{
    "bearing_before": 299,
    "bearing_after": 202,
    "type": "turn",
    "modifier": "left",
    "location": [ 13.424671, 52.508812 ],
    "instruction": "Turn left onto Adalbertstraße"
}

Lane object

A route step object contains a nested lane object. The lane object describes the available turn lanes at an intersection. Lanes are provided in their order on the street, from left to right.

Property Description
valid Indicates whether a lane can be taken to complete the maneuver ( true ) or not ( false ). For instance, if the lane array has four objects and the first two are valid, the driver can take either of the left lanes and stay on the route.
indications An array of indications (based on signs, road markings, or both) for each turn lane. A road can have multiple indications. For example, a turn lane can have a sign with an arrow pointing left and another arrow pointing straight.
Possible values Description
none No dedicated indication is shown
straight An indication signaling to continue straight
sharp left An indication signaling a sharp left turn
left An indication signaling a left turn
slight left An indication signaling a slight left turn
slight right An indication signaling a slight right turn
right An indication signaling a right turn
sharp right An indication signaling a sharp right turn
uturn An indication signaling the possibility to reverse direction by making a u-turn

Example lane object

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

Voice instruction object

A route step object contains a nested voice instruction object if the optional voice_instructions=true query parameter is present. The voice instruction object contains the text that should be announced, along with how far from the maneuver it should be emitted. The voice instructions are children of the route step during which they should be spoken, but they refer to the maneuver in the following step.

Property Description
distanceAlongGeometry A float indicating how far from the upcoming maneuver the voice instruction should begin in meters.
announcement A string containing the text of the verbal instruction.
ssmlAnnouncement A string with SSML markup for proper text and pronunciation. This property is designed for use with Amazon Polly . The SSML tags may not work with other text-to-speech engines.

Example voice instruction object

{
    "distanceAlongGeometry": 375.7,
    "announcement": "In a quarter mile, take the ramp on the right towards I 495: Baltimore",
    "ssmlAnnouncement": "<speak><amazon:effect name=\"drc\"><prosody rate=\"1.08\">In a quarter mile, take the ramp on the right towards <say-as interpret-as=\"address\">I-495</say-as>: Baltimore</prosody></amazon:effect></speak>"
}

A route step object contains a nested banner instruction object if the optional banner_instructions=true query parameter is present. The banner instruction object contains the contents of a banner that should be displayed as added visual guidance for a route. The banner instructions are children of the route steps during which they should be displayed, but they refer to the maneuver in the following step.

Property Description
distanceAlongGeometry A float indicating how far from the upcoming maneuver the banner instruction should begin being displayed in meters. Only one banner should be displayed at a time.
primary The most important content to display to the user. This text is larger and at the top.
secondary Additional content useful for visual guidance. This text is slightly smaller and below primary . Can be null .
sub Additional information that is included if the driver needs to be notified about something. Can include information about the next maneuver (the one after the upcoming one) if the step is short. If lane information is available, that takes precedence over information about the next maneuver.

Each of the different banner types (primary, secondary, and sub) contains the following properties:

Property Description
text A string that contains all the text that should be displayed.
type The type of maneuver. May be used in combination with the modifier (and, if it is a roundabout, the degrees ) to for an icon to display. Possible values: turn , merge , depart , arrive , fork , off ramp , and roundabout .
modifier
(optional)
The modifier for the maneuver. Can be used in combination with the type (and, if it is a roundabout, the degrees ) to for an icon to display.
Possible values Description
uturn Indicates a reversal of direction
sharp right A sharp right turn
right A normal turn to the right
slight right A slight turn to the right
straight No relevant change in direction
slight left A slight turn to the left
left A normal turn to the left
sharp left A sharp turn to the left
degrees
(optional)
The degrees at which you will be exiting a roundabout, assuming 180 indicates going straight through the roundabout.
driving_side
(optional)
A string representing which side the of the street people drive on in that location. Can be left or right .
components Objects that, together, make up what should be displayed in the banner. Includes additional information intended to be used to aid in visual layout. A component can contain the following properties:
components Description
type A string with more context about the component that may help in visual markup and display choices. If the type of the component is unknown, it should be treated as text.
Possible values Description
text Default. Indicates the text is part of the instructions and no other type.
icon This is text that can be replaced by an imageBaseURL icon.
delimiter This is text that can be dropped, and should be dropped if you are rendering icons.
exit-number Indicates the exit number for the maneuver.
exit Provides the the word for exit in the local language.
lane Indicates which lanes can be used to complete the maneuver.
The introduction of new types is not considered a breaking change.
text The sub-string of the text of the parent objects that may have additional context associated with it
abbr
(optional)
The abbreviated form of text . If this is present, there will also be an abbr_priority value. For an example of using abbr and abbr_priority , see the abbreviation examples table.
abbr_priority
(optional)
An integer indicating the order in which the abbreviation abbr should be used in place of text . The highest priority is 0 , while a higher integer value means it should have a lower priority. There are no gaps in integer values. Multiple components can have the same abbr_priority . When this happens, all components with the same abbr_priority should be abbreviated at the same time. Finding no larger values of abbr_priority means that the string is fully abbreviated.
imageBaseURL
(optional)
A string pointing to a shield image to use instead of the text.
directions An array indicating which directions you can go from a lane (left, right, or straight). If the value is [ 'left', 'straight' ] , the driver can go straight or left from that lane. Present if components.type is lane .
active A boolean that tells you whether that lane can be used to complete the upcoming maneuver. If multiple lanes are active, then they can all be used to complete the upcoming maneuver. Present if components.type is lane .

Abbreviation examples

text abbr abbr_priority
North N 1
Franklin Drive Franklin Dr 0

Given the components in the table above, the possible abbreviations are, in order:

  • North Franklin Dr
  • N Franklin Dr

Example banner instruction object

{
    "distanceAlongGeometry": 100,
    "primary": {
        "type": "turn",
        "modifier": "left",
        "text": "I 495 North / I 95",
        "components": [
          {
            "text": "I 495",
            "imageBaseURL": "https://s3.amazonaws.com/mapbox/shields/v3/i-495",
            "type": "icon"
          },
          {
            "text": "North",
            "type": "text",
            "abbr": "N",
            "abbr_priority": 0
          },
          {
            "text": "/",
            "type": "delimiter"
          },
          {
            "text": "I 95",
            "imageBaseURL": "https://s3.amazonaws.com/mapbox/shields/v3/i-95",
            "type": "icon"
          }
        ]
    },
    "secondary": {
        "type": "turn",
        "modifier": "left",
        "text": "Baltimore / Northern Virginia",
        "components": [
          {
            "text": "Baltimore",
            "type": "text"
          },
          {
            "text": "/",
            "type": "text"
          },
          {
            "text": "Northern Virginia",
            "type": "text"
          }
      ]
    },
    "sub": {
        "text": "",
        "components": [
          {
            "text": "",
            "type": "lane",
            "directions": ["left"],
            "active": true
          },
          {
            "text": "",
            "type": "lane",
            "directions": ["left", "straight"],
            "active": true
          },
          {
            "text": "",
            "type": "lane",
            "directions": ["right"],
            "active": false
          }
        ]
    }
}

Directions 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 code HTTP status code Description
Ok 200 Normal success case.
NoRoute 200 There was no route found for the given coordinates. Check for impossible routes (for example, routes over oceans without ferry connections).
NoSegment 200 No road segment could be matched for coordinates. Check for coordinates that are too far away from a road.
ProfileNotFound 404 Use a valid profile as described in the list of routing profiles .
InvalidInput 422 The given request was not valid. The message key of the response will hold an explanation of the invalid input.

Isochrone

An isochrone, from the Greek root words iso (equal) and chrone (time), is a line that connects points of equal travel time around a given location. The Mapbox Isochrone API computes areas that are reachable within a specified amount of time from a location, and returns the reachable regions as contours of polygons or lines that you can display on a map.

Restrictions and limits

  • The Isochrone API is limited to 300 requests per minute.
  • The Isochrone API supports one coordinate per request.
  • The Isochrone API can support a maximum of 4 isochrone contours per request.
  • The maximum time that can be specified for an isochrone contour is 60 minutes.
  • Results must be displayed on a Mapbox map using one of the Mapbox libraries or SDKs.

If you require a higher rate limit, contact us.

Retrieve isochrones around a location

Given a location and a routing profile?, retrieve up to four isochrone contours. The contours are calculated using rasters and are returned as either polygon or line features, depending on your input setting for the polygons parameter.

Required parameters Description
profile A Mapbox Directions routing profile ID.
Profile ID Description
mapbox/driving Car travel times, distances, or both
mapbox/walking Pedestrian and hiking travel times, distances, or both
mapbox/cycling Bicycle travel times, distances, or both
coordinates A {longitude,latitude} coordinate pair around which to center the isochrone lines.
contours_minutes The times in minutes to use for each isochrone contour. You can specify up to four contours. Times must be in increasing order. The maximum time that can be specified is 60 minutes.

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

Optional parameters Description
contours_colors The colors to use for each isochrone contour, specified as hex values without a leading # (for example, ff0000 for red). If this parameter is used, there must be the same number of colors as there are entries in contours_minutes . If no colors are specified, the Isochrone API will assign a default rainbow color scheme to the output.
polygons Specify whether to return the contours as GeoJSON polygons ( true ) or linestrings ( false , default). When polygons=true , any contour that forms a ring is returned as a polygon.
denoise A floating point value from 0.0 to 1.0 that can be used to remove smaller contours. The default is 1.0 . A value of 1.0 will only return the largest contour for a given time value. A value of 0.5 drops any contours that are less than half the area of the largest contour in the set of contours for that same time value.
generalize A positive floating point value in meters used as the tolerance for Douglas-Peucker generalization . There is no upper bound. If no value is specified in the request, the Isochrone API will choose the most optimized generalization to use for the request. Note that the generalization of contours can lead to self-intersections, as well as intersections of adjacent contours.
GET
/isochrone/v1/mapbox/{profile}/{coordinates}

Example request

https://api.mapbox.com/isochrone/v1/mapbox/driving/-118.22258,33.99038?contours_minutes=5,10,15&contours_colors=6706ce,04e813,4286f4&polygons=true&access_token=

Isochrone response object

In the response to a request to the Mapbox Isochrone API, the isochrone contours are returned as a GeoJSON Feature Collection. Each feature object in the Feature Collection is an isochrone, and contains the following properties:

Property Description
type Feature , a GeoJSON type from the GeoJSON specification .
properties An object that describes how the isochrone should be drawn.
properties.contour The time in minutes used for the isochrone contour.
properties.color The color of the isochrone line if the geometry property is Linestring .
properties.opacity The opacity of the isochrone line if the geometry property is Linestring .
properties.fill The fill color of the isochrone polygon if the geometry property is Polygon , suitable for use in geojson.io .
properties.fill-opacity The fill opacity of the isochrone polygon if the geometry property is Polygon , suitable for use in geojson.io .
properties.fillColor The fill color of the isochrone polygon if the geometry property is Polygon , suitable for use in Leaflet .
properties.fillOpacity The fill opacity of the isochrone polygon if the geometry property is Polygon , suitable for use in Leaflet .
geometry An object that describes the geometry of the isochrone.
geometry.coordinates An array of arrays that contain the coordinates for the isochrone, formatted as [longitude,latitude] .
geometry.type The GeoJSON type of the returned geometry. Either Linestring (default) or Polygon (if polygons=true was specified in the query).

Example response

{
    "features": [
        {
            "properties": {
                "contour": 15,
                "color": "#4286f4",
                "opacity": 0.33,
                "fill": "#4286f4",
                "fill-opacity": 0.33,
                "fillColor": "#4286f4",
                "fillOpacity": 0.33
            },
            "type": "Feature",
            "geometry": {
                "coordinates": [ "arrays of longitude, latitude coordinates" ],
                "type": "Polygon"
            }
        },
        {
            "properties": {
                "contour": 10,
                "color": "#04e813",
                "opacity": 0.33,
                "fill": "#04e813",
                "fill-opacity": 0.33,
                "fillColor": "#04e813",
                "fillOpacity": 0.33
            },
            "type": "Feature",
            "geometry": {
                "coordinates": [ "arrays of longitude, latitude coordinates" ],
                "type": "Polygon"
            }
        },
        {
            "properties": {
                "contour": 5,
                "color": "#6706ce",
                "opacity": 0.33,
                "fill": "#6706ce",
                "fill-opacity": 0.33,
                "fillColor": "#6706ce",
                "fillOpacity": 0.33
            },
            "type": "Feature",
            "geometry": {
                "coordinates": [ "arrays of longitude, latitude coordinates" ],
                "type": "Polygon"
            }
        }
    ],
    "type": "FeatureCollection"
}

Map Matching

This documentation is for v5 of the Map Matching API. For information about the earlier version, see the v4 documentation.

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. The Map Matching API can also return a full directions response to queries.

Swift and Objective-C support for Map Matching is provided by the MapboxDirections.swift library.

Restrictions and limits

  • The Map Matching API is limited to 300 requests per minute.
  • Each request can have a maximum of 100 coordinates.
  • Results must be displayed on a Mapbox map using one of the Mapbox libraries or SDKs.

For high volume or other use cases, contact us.

Retrieve a match

Return a path on the road and path network that is closest to the input traces.

URL parameter Description
profile A Mapbox Directions routing profile ID.
Profile ID Description
mapbox/driving Car travel times, distances, or both.
mapbox/walking Pedestrian and hiking travel times, distances, or both
mapbox/cycling Bicycle travel times, distances, or both
mapbox/driving-traffic Car travel times, distances, or both as informed by traffic data
coordinates A semicolon-separated list of {longitude},{latitude} coordinate pairs to visit in order. There can be between 2 and 100 coordinates.

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

Query parameter Description
annotations
(optional)
Return additional metadata along the route. Possible values are: duration , distance , and speed . You can include several annotations as a comma-separated list. See the route leg object for more details on what is included with annotations.
approaches
(optional)
A 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. However, you can skip a coordinate and show its position in the list with the ; separator. If waypoints is not specified (so all coordinates are treated as waypoints), the list of approaches must be the same length as the list of coordinates. Must be used in combination with steps=true .
geometries
(optional)
The format of the returned geometry. Allowed values are: geojson (as LineString ), polyline (default, a polyline with precision 5), and polyline6 (a polyline with precision 6).
language
(optional)
The language of returned turn-by-turn text instructions. See supported languages . The default is en (English). Must be used in combination with steps=true .
overview
(optional)
The type of 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).
radiuses
(optional)
A semicolon-separated list indicating the maximum distance a coordinate can be moved to snap to the road network in meters. If provided, the number of radiuses must be the same as the number of coordinates. However, you can skip a coordinate and show its position in the list with the ; separator. 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 ( true ) or not ( false , default).
tidy
(optional)
Whether to remove clusters and re-samples traces for improved map matching results ( true ) or not ( false , default).
timestamps
(optional)
A semicolon-separated list of numbers in Unix time that correspond to each input coordinate. If provided, the number of timestamps must be the same as the number of coordinates, no coordinates can be skipped, and the timestamps must occur in ascending order. For best results, timestamps should have a sample rate of about 5 seconds.
waypoint_names
(optional)
A semicolon-separated list of custom names for waypoints. These names will be used for the arrival instruction in banners and voice instructions. Values can be any string, and the total number of all characters (including semicolons) cannot exceed 500 . The list of waypoint_names must be the same length as the list of waypoints, but you can skip a waypoint and show its position with the ; separator. If waypoints is not specified (so all coordinates are treated as waypoints), the list of waypoint_names must be the same length as the list of coordinates.
waypoints
(optional)
A semicolon-separated list indicating which input coordinates should be treated as waypoints. If a coordinate is treated as a waypoint, it receives arrival and departure events in the match object's route. If a list of waypoints is not provided, all coordinates are treated as waypoints. Each item in the list must be the zero-based index of an input coordinate, and the list must include 0 (the index of the first coordinate) and the index of the last coordinate. Waypoints are most useful in combination with steps=true and requests based on traces with high sample rates.

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 it is that the input traces are poorly aligned to the road network.

Some pre-processing tips to achieve the best results:

  • Timestamps improve the quality of the matching and are highly recommended.
  • 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 that you 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.
  • 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.
GET
/matching/v5/{profile}/{coordinates}.json

Example request

# Basic request that returns a match object with route legs between each waypoint
curl "https://api.mapbox.com/matching/v5/mapbox/driving/-117.17282,32.71204;-117.17288,32.71225;-117.17293,32.71244;-117.17292,32.71256;-117.17298,32.712603;-117.17314,32.71259;-117.17334,32.71254?access_token="

# Request with the approaches parameter set to 'curb' for each waypoint
curl "https://api.mapbox.com/matching/v5/mapbox/driving/-117.17282,32.71204;-117.17288,32.71225;-117.17293,32.71244;-117.17292,32.71256?approaches=curb;curb;curb;curb&access_token="


# Request with various parameters, returns a match object with 1 route leg between the first and last waypoints
curl "https://api.mapbox.com/matching/v5/mapbox/driving/2.344003,48.85805;2.34675,48.85727;2.34868,48.85936;2.34955,48.86084;2.34955,48.86088;2.34962,48.86102;2.34982,48.86125?steps=true&tidy=true&waypoints=0;6&waypoint_names=Home;Work&banner_instructions=true&access_token="

Example response

{
  "matchings": [
    {
      "confidence": 0.816975633159885,
      "geometry": "{qeiHayhMzCsQLW@_@Ia@UY{TaK",
      "legs": [
        {
          "summary": "Quai de la Mégisserie, Boulevard de Sébastopol",
          "weight": 194.8,
          "duration": 143.7,
          "steps": [ ],
          "distance": 701.9
        }
      ],
      "weight_name": "routability",
      "weight": 194.8,
      "duration": 143.7,
      "distance": 701.9
    }
  ],
  "tracepoints": [ ],
  "code": "Ok"
}

The match response object

The match response object contains one or more match objects, as well as one or more tracepoint objects.

Property Description
code A string indicating the state of the response. The potential values are listed in the Map Matching status codes section .
matchings An array of match objects .
tracepoints An array of tracepoint objects that represent the location an input point was matched with, in the order in which they were matched. If a trace point is omitted by the Map Matching API because it is an outlier, the entry will be null .

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 it is that the input traces are poorly aligned to the road network.

Example match response object

{
  "matchings": [
    {
      "confidence": 0.9857403441039709,
      "geometry": "gatfEfidjUk@Lc@@Y?",
      "legs": [
        {
          "summary": "",
          "weight": 2.7,
          "duration": 2.7,
          "steps": [],
          "distance": 25
        },
        {
          "summary": "",
          "weight": 2.4,
          "duration": 2.4,
          "steps": [],
          "distance": 21
        },
        {
          "summary": "",
          "weight": 1.6,
          "duration": 1.6,
          "steps": [],
          "distance": 14
        }
      ],
      "weight_name": "routability",
      "weight": 6.699999999999999,
      "duration": 6.699999999999999,
      "distance": 60
    }
  ],
  "tracepoints": [
    {
      "alternatives_count": 0,
      "waypoint_index": 0,
      "matchings_index": 0,
      "name": "North Harbor Drive",
      "location": [
        -117.172836,
        32.712041
      ]
    },
    {
      "alternatives_count": 0,
      "waypoint_index": 1,
      "matchings_index": 0,
      "name": "North Harbor Drive",
      "location": [
        -117.17291,
        32.712256
      ]
    },
    {
      "alternatives_count": 0,
      "waypoint_index": 2,
      "matchings_index": 0,
      "name": "North Harbor Drive",
      "location": [
        -117.17292,
        32.712444
      ]
    },
    {
      "alternatives_count": 9,
      "waypoint_index": 3,
      "matchings_index": 0,
      "name": "North Harbor Drive",
      "location": [
        -117.172922,
        32.71257
      ]
    }
  ],
  "code": "Ok"
}

The match object

A match object is a route object with an additional confidence field:

Property Description
confidence A float indicating the level of confidence in the returned match, from 0 (low) to 1 (high).
distance A float indicating the distance traveled in meters.
duration A float indicating the estimated travel time in seconds.
weight A string indicating the weight in the units described by weight_name .
weight_name A string indicating the weight that was used. The default is routability , which is duration-based with additional penalties for less desirable maneuvers.
geometry Depending on the geometries parameter in the request, this is a GeoJSON LineString or a Polyline string . Depending on the overview parameter in the request, 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 ).
legs An array of route leg objects .
voice_locale The locale used for voice instructions. Defaults to en (English). See supported languages . Optionally included if steps=true .

Example match object

{
    "confidence": 0.9548844020537051,
    "distance": 103.7,
    "duration": 16.4,
    "geometry": "gatfEfidjUi@Le@@Y?E??J?^Hf@",
    "legs": []
}

The tracepoint object

A tracepoint object is a waypoint object with 3 additional fields: matchings_index, waypoint_index, and alternatives_count.

Property Description
matchings_index The index of the match object in matchings that the sub-trace was matched to.
waypoint_index The index of the waypoint inside the matched route.
alternatives_count The number of probable alternative matchings for this trace point. A value of 0 indicates that this point was matched unambiguously. Split the trace at these points for incremental map matching.
name The name of the road or path the coordinate snapped to.
location An array that contains the location of the snapped coordinate, in the format [longitude, latitude] .

Example tracepoint object

{
    "waypoint_index": 0,
    "location": [-117.172836, 32.71204],
    "name": "North Harbor Drive",
    "matchings_index": 0,
    "alternatives_count": 0
}

Map Matching status codes

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.
Status code 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.
TooManyCoordinates There are more than 100 points in the request.
InvalidInput message will hold an explanation of the invalid input.
ProfileNotFound Needs to be a valid profile ( mapbox/driving , mapbox/driving-traffic , mapbox/walking , or mapbox/cycling ).

Using HTTP POST

The Map Matching API supports access via the HTTP POST method. To submit a request using HTTP POST, you must make the following changes to the request:

  1. The HTTP method must be POST
  2. The Content-Type of the request must be application/x-www-form-urlencoded
  3. The coordinate list must be present in the request body as the coordinates= parameter, and there must be no coordinates in the URL
  4. The access_token parameter must be part of the POST URL, not the body
  5. All other parameters must be part of the request body

An example POST request looks like this:

POST /matching/v5/mapbox/driving?access_token= HTTP/1.0
Content-Type: application/x-www-form-urlencoded

coordinates=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
# Basic request using POST interface
$ curl -d "coordinates=-117.17282,32.71204;-117.17288,32.71225;-117.17293,32.71244;-117.17292,32.71256;-117.17298,32.712603;-117.17314,32.71259;-117.17334,32.71254"
"https://api.mapbox.com/matching/v5/mapbox/driving?access_token="

# Request with various parameters, will return a match object with one route leg between the first and last waypoints
$ curl -d "coordinates=2.344003,48.85805;2.34675,48.85727;2.34868,48.85936;2.34955,48.86084;2.34955,48.86088;2.349625,48.86102;2.34982,48.86125&steps=true&tidy=true&waypoints=0;6&waypoint_names=Home;Work&banner_instructions=true" "https://api.mapbox.com/matching/v5/mapbox/driving?access_token="

Matrix

The Matrix API returns travel times between many points.

For example, given 3 locations A, B, and 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 or the distance on the fastest route for each element in the matrix, where an element is an origin-destination pair in the matrix. The Matrix API returns durations in seconds and distances in meters. It does not return route geometries.

Durations or distances between points may not be symmetric, since the routes may differ by direction due to one-way streets or turn restrictions. For example, A to B may have a different duration than B to A.

The Matrix API allows you to 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

  • For the mapbox/driving, mapbox/walking, and mapbox/cycling profiles:

    • Maximum 25 input coordinates per request
    • Maximum 300 requests per minute
  • For the mapbox/driving-traffic profile:

    • Maximum 10 input coordinates per request
    • Maximum 300 requests per minute

For higher volumes, contact us.

Retrieve a matrix

Returns a duration matrix, a distance matrix, or both, showing travel times and distances between coordinates. In the default case, this endpoint returns a symmetric matrix that uses all the input coordinates as sources and destinations. Using the optional sources and destination parameters, you can also generate an asymmetric matrix that uses only some coordinates as sources or destinations.

URL parameter Description
profile A Mapbox Directions routing profile ID.
Profile ID Description
mapbox/driving Car travel times, distances, or both.
mapbox/walking Pedestrian and hiking travel times, distances, or both
mapbox/cycling Bicycle travel times, distances, or both
mapbox/driving-traffic Car travel times, distances, or both as informed by traffic data
coordinates A semicolon-separated list of {longitude},{latitude} coordinates. There must be between 2 and 25 coordinates.

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

Query parameter Description
annotations
(optional)
Used to specify the resulting matrices. Possible values are: duration (default), distance , or both values separated by comma.
approaches
(optional)
A 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. However, you can skip a coordinate and show its position in the list with the ; separator.
destinations
(optional)
Use the coordinates at a given index as destinations. Possible values are: a semicolon-separated list of 0-based indices, or all (default). The option all allows using all coordinates as destinations.
sources
(optional)
Use the coordinates at a given index as sources. Possible values are: a semicolon-separated list of 0-based indices, or all (default). The option all allows using all coordinates as sources.

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

GET
/directions-matrix/v1/{profile}/{coordinates}

Example requests

# Request a symmetric 3x3 matrix for cars with a curbside approach for each destination
curl "https://api.mapbox.com/directions-matrix/v1/mapbox/driving/-122.42,37.78;-122.45,37.91;-122.48,37.73?approaches=curb;curb;curb&access_token="

# Request an asymmetric 2x3 matrix for bicycles
curl "https://api.mapbox.com/directions-matrix/v1/mapbox/cycling/-122.42,37.78;-122.45,37.91;-122.48,37.73?sources=0;2&destinations=all&access_token="

# Request a 1x3 matrix for walking that includes both duration and distance
curl "https://api.mapbox.com/directions-matrix/v1/mapbox/walking/-122.418563,37.751659;-122.422969,37.75529;-122.426904,37.759617?sources=1&annotations=distance,duration&access_token="

Example response

{
    "code": "Ok",
    "durations": [
        [ 0,      573, 1169.5 ],
        [ 573,    0,      597 ],
        [ 1169.5, 597,      0 ]
    ],
    "destinations": [
        {
            "name": "Mission Street",
            "location": [ -122.418408, 37.751668 ]
        },
        {
            "name": "22nd Street",
            "location": [ -122.422959, 37.755184 ]
        },
        {
            "name": "",
            "location": [ -122.426911, 37.759695 ]
        }
    ],
    "sources": [
        {
            "name": "Mission Street",
            "location": [ -122.418408, 37.751668 ]
        },
        {
            "name": "22nd Street",
            "location": [ -122.422959, 37.755184 ]
        },
        {
            "name": "",
            "location": [ -122.426911, 37.759695 ]
        }
    ]
}

The matrix response object

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

Property Description
code A 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 an array of arrays that represent 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 cannot be found, the result is null .
distances Distances as an array of arrays that represent the matrix in row-major order. distances[i][j] gives the travel distance from the i th source to the j th destination. All values are in meters. The distance between the same coordinate is always 0 . If a distance cannot be found, the result is null .
destinations: An 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, or in the order specified in the destinations query parameter.
sources An 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, or in the order specified in the sources query parameter.

Note: If no route is found between a source? and a destination, the respective value in the durations or distances matrix will be null.

Example matrix response object

{
    "code": "Ok",
    "durations": [
        [ 0,    77.3, null ],
        [ 75.7, 0,    null ],
        [ null, null, 0    ]
    ],
    "distances": [
        [ 0,   846.2, null ],
        [ 832.2,   0, null ],
        [ null, null,    0 ]
    ],
    "destinations": [
        {
            "location": [ -6.80897, 62.000075 ],
            "name": "Kirkjubøarvegur"
        },
        {
            "location": [ -6.802374, 62.004142 ],
            "name": "Marknagilsvegur"
        },
        {
            "location": [ 7.419449, 43.731931 ],
            "name": "Avenue du Port"
        }
    ],
    "sources": [
        {
            "location": [ -6.80897, 62.000075 ],
            "name": "Kirkjubøarvegur"
        },
        {
            "location": [ -6.802374, 62.004142 ],
            "name": "Marknagilsvegur"
        },
        {
            "location": [ 7.419449, 43.731931 ],
            "name": "Avenue du Port"
        }
    ]
}

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.

In the case of a server error, the HTTP status code will be 500 or higher and the response will not include a code property.

Response body code HTTP status code Description
Ok 200 Normal success case.
ProfileNotFound 404 Use a valid profile as described in Retrieve a matrix .
InvalidInput 422 The given request was not valid. The message key of the response will hold an explanation of the invalid input.

In cases where no route is found between a source? and a destination, no error will be returned. Instead, the respective value in the durations or distances matrix will be null.

Optimization

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.

Restrictions and limits

  • Maximum 12 coordinates per request
  • Maximum 25 distributions per request
  • Maximum 300 requests per minute

For higher volumes, contact us.

Retrieve an optimization

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

URL parameter Description
profile A Mapbox Directions routing profile ID.
Profile ID Description
mapbox/driving Car travel times, distances, or both.
mapbox/walking Pedestrian and hiking travel times, distances, or both
mapbox/cycling Bicycle travel times, distances, or both
The Optimization API does not support the mapbox/driving-traffic profile.
coordinates 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.

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

Query parameter Description
annotations
(optional)
Return additional metadata along the route. You can include several annotations as a comma-separated list. Possible values are:
annotations Description
duration The duration between each pair of coordinates in seconds
distance The distance between each pair of coordinates in meters
speed The speed between each pair of coordinates in meters per second
approaches
(optional)
A 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. However, you can skip a coordinate and show its position in the list with the ; separator. Must be used in combination with steps=true .
bearings
(optional)
Influences 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 conjunction 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. However, you can skip a coordinate and show its position in the list with the ; separator.
destination
(optional)
Specify the destination coordinate of the returned route. Accepts any (default) or last .
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 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.
geometries
(optional)
The format of the returned geometry. Allowed values are: geojson (as LineString ), polyline (default, a polyline with precision 5), polyline6 (a polyline with precision 6).
language
(optional)
The language of returned turn-by-turn text instructions. See supported languages . The default is en (English).
overview
(optional)
The 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).
radiuses
(optional)
The 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 found within the radius.
source
(optional)
The coordinate at which to start the returned route. Accepts any (default) or first .
steps
(optional)
Whether to return steps and turn-by-turn instructions ( true ) or not ( false , default).
roundtrip
(optional)
Indicates whether the returned route is roundtrip, meaning the route returns to the first location ( 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 continue_straight=false was set at each waypoint, 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

It is possible to 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 roundtrip 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:

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
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 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="

# Request an optimized car roundtrip 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="

# 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="

# 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="

Example response

{
    "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": "}panFfah|Ujj@ru@`Dp`BwNdpAwc@pw@ibAxm@snA|Ic^|\\q{@{S}`@lVewBzUa}@t^}oAdEkbB}[{{AvHqdDs\\qn@lV_OqpA{`A}bBaRucA_gB}eCbI_MzXzY`Va]xUbPzE|[{E}[_WoP{Tl]{X{YoLfQtjBvdCbRpcA|_A|`BbD`qA~y@{WpdDr\\z{AwHh}A`\\hsA{Dv~@c_@dwB{U|`@mVp{@zSfe@_`@niA}G|aAin@~b@mx@|LunBsBw}@{Sia@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
        }
    ]
}

Optimization response object

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

Property Description
code A 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 .
waypoints An 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 An 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:

Property Description
name A string with the name of the road or path that the input coordinate snapped to.
location An array containing the [longitude, latitude] of the snapped coordinate.
trips_index The index of the trip object that contains this waypoint in the trips array.
waypoint_index The 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:

Property Description
geometry Depending 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 simplfied geometry to the zoom level at which the route can be displayed in full ( simplified ), or is not included ( false ).
legs An array of route leg objects.
weight_name A string indicating which weight was used. The default is routability , which is duration-based, with additional penalties for less desirable maneuvers.
weight A float indicating the weight in the units described by weight_name .
duration A float indicating the estimated travel time in seconds.
distance A 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": [
        {
            "location": [ -6.80897, 62.000075 ],
            "waypoint_index": 0,
            "name": "Kirkjubøarvegur",
            "trips_index": 0
        },
        {
            "location": [ -6.802374, 62.004142 ],
            "waypoint_index": 1,
            "name": "Marknagilsvegur",
            "trips_index": 0
        }
    ],
    "trips": [
        {
            "distance": 1660.8,
            "duration": 153,
            "legs": [
                {
                    "summary": "",
                    "duration": 77.3,
                    "steps": [],
                    "distance": 830.4
                },
                {
                    "distance": 830.4,
                    "steps": [],
                    "duration": 75.7,
                    "summary": ""
                }
            ],
            "geometry": "oklyJ`{ph@yBuY_F{^_FxJoBrBs@d@mATlAUr@e@nBsB~EyJ~Ez^xBtY"
        }
    ]
}

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 Description
Ok 200 Normal success case.
NoTrips 200 For one coordinate, no route to other coordinates could be found. Check for impossible routes (for example, routes over oceans without ferry connections).
NotImplemented 200 For the given combination of source , destination , and roundtrip , this request is not supported.
ProfileNotFound 404 Use a valid profile as described in Retrieve an optimization .
InvalidInput 422 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 provides access to Mapbox resources on behalf of a user. The Mapbox Tokens API provides you with a programmatic way to create, update, delete, and retrieve tokens, as well as list a user's tokens and token scopes.

All user accounts have a default public token. Additional tokens can be created to grant additional, or more limited, privileges.

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.

To create additional tokens using the Mapbox Tokens API, you need to have an authorizing token that has the tokens:write scope, as well as all the scopes you want to add to the newly created token. To create the authorization token, visit your Account Dashboard, and click Create a token.

Restrictions and limits

  • Requests must be made over HTTPS. HTTP is not supported.
  • The Tokens API is limited to 120 requests per minute per account.

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.

  • Header. A literal value of either pk (public token), sk (secret token), or tk (temporary token).
  • Payload. A base64-encoded JSON object containing the identity and authorities of the token. pk and sk tokens contain a reference to metadata that holds the rights granted for the token. tk tokens contain the contents of the metadata directly in the payload.
  • Signature. Signed by Mapbox and used to verify the token has not been tampered with.

The token metadata object

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

Property Description
id The token's unique identifier.
usage The type of token. One of: pk (public), sk (secret), or tk (temporary).
client The client for the token. This is always api .
default Indicates whether the token is a default token.
scopes An array that contains the scopes granted to the token.
note A human-readable description of the token.
created The date and time the token was created.
modified The date and time the token was last modified.
token The token itself.

The token metadata object

{
  "id": "cijucimbe000brbkt48d0dhcx",
  "usage": "pk",
  "client": "api",
  "default": false,
  "note": "My website",
  "scopes": ["styles:read", "fonts:read"],
  "created": "2018-01-25T19:07:07.621Z",
  "modified": "2018-01-26T00:39:57.941Z",
  "token": "pk.eyJ1Ijoic2NvdGhpcyIsImEiOiJjaWp1Y2ltYmUwMDBicmJrdDQ4ZDBkaGN4In0.sbihZCZJ56-fsFNKHXF8YQ"
}

List tokens

List all the tokens that belong to an account. This endpoint supports pagination.

URL parameters Description
username The username of the account for which to list tokens.

Response body

The response body will contain all the tokens that belong to the username specified in the query, each containing the properties described in the token metadata object section.

If a listed token's usage property is sk, the token property will not be included in the response.

GET
/tokens/v2/{username}
tokens:read Token scope

Example request

curl "https://api.mapbox.com/tokens/v2/{username}?access_token="

Example response

[
  {
    "client": "api",
    "note": "a public token",
    "usage": "pk",
    "id": "cijucimbe000brbkt48d0dhcx",
    "default": false,
    "scopes": ["styles:read", "fonts:read"],
    "created": "2016-01-25T19:07:07.621Z",
    "modified":"2016-01-26T00:39:57.941Z",
    "token": "pk.eyJ1Ijoic2NvdGhpcyIsImEiOiJjaWp1Y2ltYmUwMDBicmJrdDQ4ZDBkaGN4In0.sbihZCZJ56-fsFNKHXF8YQ"
  },
  {
    "client": "api",
    "note": "a secret token",
    "usage": "sk",
    "id": "cijuorumy001cutm5r4fl2y1b",
    "default": false,
    "scopes": ["styles:list"],
    "created": "2016-01-26T00:50:13.701Z",
    "modified": "2016-01-26T00:50:13.701Z"
  }
]

Create a token

Creates a new token. Every requested scope must be present in the access 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.

Note that while it is possible to create a token with no scopes, you will not be able to update this token later to include any scopes.

Available scopes

The scopes included in the token decide whether the token is public or secret. A public token may only contains public scopes, while a secret token can contain both public and secret scopes.

  • Public tokens: styles:tiles, styles:read, fonts:read, datasets:read
  • Secret tokens: scopes:list, map:read, map:write, user:read, user:write, uploads:read, uploads:list, uploads:write, styles:write, styles:list, tokens:read, tokens:write, datasets:list, datasets:write, tilesets:list, tilesets:read, tilesets:write, analytics:read (if user has a Commercial or Enterprise account)

Request body

The request body must be a JSON object that contains the following properties:

Parameter Description
note Create a description for the token.
scopes Specify the scopes that the new token will have. The authorizing token needs to have the same scopes as, or more scopes than, the new token you are creating.

Response body

The response body for a successful request will be a new public or secret token.

POST
/tokens/v2/{username}
tokens:write Token scope

Example request

# Create a public token with styles:read and fonts:read scopes
curl -H "Content-Type: application/json" -X POST -d '{"note": "My top secret project","scopes": ["styles:read", "fonts:read"]}' 'https://api.mapbox.com/tokens/v2/{username}?access_token='

Example request body

{
  "scopes": ["styles:read", "fonts:read"],
  "note": "My top secret project"
}

Example response

{
  "client": "api",
  "note": "My top secret project",
  "usage": "pk",
  "id": "cijucimbe000brbkt48d0dhcx",
  "default": false,
  "scopes": ["styles:read", "fonts:read"],
  "created": "2016-01-25T19:07:07.621Z",
  "modified":"2016-01-25T19:07:07.621Z",
  "token": "pk.eyJ1Ijoic2NvdGhpcyIsImEiOiJjaWp1Y2ltYmUwMDBicmJrdDQ4ZDBkaGN4In0.sbihZCZJ56-fsFNKHXF8YQ"
}

Create a temporary token

Creates a new temporary token that automatically expires at a set time. You can create a temporary token using a public or a secret token, or using another temporary token. Temporary tokens can't be updated or revoked after they are created.

Request body

The request body must be a JSON object that contains the following properties:

Parameter Description
expires Specify when the temporary token will expire. Cannot be a time in the past or more than one hour in the future. If the authorizing token is temporary, the expires time for the new temporary token cannot be later than that of the authorizing temporary token.
scopes Specify the scopes that the new temporary token will have. The authorizing token needs to have the same scopes as, or more scopes than, the new temporary token you are creating.

Response body

The response body for a successful request will be a new temporary token. 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.

POST
/tokens/v2/{username}
tokens:write Token scope

Example request

# Request a temp token with styles:read and font:read scopes
curl -H "Content-Type: application/json" -X POST -d '{"expires": "2018-09-20T06:30:00Z","scopes": ["styles:read", "fonts:read"]}' 'https://api.mapbox.com/tokens/v2/{username}?access_token='

Example request body

{
  "expires": "2016-09-15T19:27:53.000Z",
  "scopes": ["styles:read", "fonts:read"]
}

Example response

{
  "token": "tk.eyJ1IjoibWFwYm94IiwiZXhwIjoxNDczOTY3NjczLCJpYXQiOjE0NzM5Njc2NDMsInNjb3BlcyI6WyJzdHlsZXM6cmVhZCIsImZvbnRzOnJlYWQiXSwiY2xpZW50IjoiYXBpIn0.ZepsWvpjTMlpePE4IQBs0g"
}

Update a token

Update the note, the scopes, or both in a token's metadata. 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.

URL parameter Description
token_id The ID of the token that you want to update.

Request body

The request body must be a JSON object that contains one or both of the following properties:

Parameter Description
note Update the token's description.
scopes Update the token's scopes. The authorizing token needs to have the same scopes as, or more scopes than, the token you are updating. A public token may only be updated to include other public scopes. A secret token may be updated to contain public and secret scopes.

Response body

The response body for a successful request will be a new temporary token.

PATCH
/tokens/v2/{username}/{token_id}
tokens:write Token scope

Example request

# Update a token to have fonts:read scope
curl -H 'Content-Type: application/json' -X PATCH -d '{"scopes": ["fonts:read"]}' 'https://api.mapbox.com/tokens/v2/{username}/{token_id}?access_token='

Example request body

{
  "scopes": ["styles:tiles", "styles:read", "fonts:read"]
}

Example response

{
  "client": "api",
  "note": "My top secret project",
  "usage": "pk",
  "id": "cijucimbe000brbkt48d0dhcx",
  "default": false,
  "scopes": ["styles:tiles", "styles:read", "fonts:read"],
  "created": "2016-01-25T19:07:07.621Z",
  "modified":"2016-01-25T19:07:07.621Z",
  "token": "pk.eyJ1Ijoic2NvdGhpcyIsImEiOiJjaWp1Y2ltYmUwMDBicmJrdDQ4ZDBkaGN4In0.sbihZCZJ56-fsFNKHXF8YQ"
}

Delete a token

Delete an access token?. This will revoke its authorization and remove its access to Mapbox APIs. Applications using the revoked token will need to get a new access token before they can access Mapbox APIs.

Note that cached resources may continue to be accessible for a little while after a token is deleted. No new or updated resources will be accessible with the deleted token.

URL parameter Description
token_id The ID of the token that you want to delete.
DELETE
/tokens/v2/{username}/{token_id}
tokens:write Token scope

Example request

curl -X DELETE "https://api.mapbox.com/tokens/v2/{username}/{token_id}?access_token="

Example response

HTTP 204

Retrieve a token

Retrieve an access token? and check whether it is valid. If the token is invalid, an explanation is returned as the code property in the response body.

Query parameter Description
access_token The access token to retrieve.

Response body

The body of the token is parsed and included as the token property in object form. The returned object contains the following properties:

Property Description
code Indicates whether the token is valid. If the token is invalid, describes the reason. One of:
Code Description
TokenValid The token is valid and active.
TokenMalformed The token cannot be parsed.
TokenInvalid The signature for the token does not validate.
TokenExpired The token was temporary and has expired.
TokenRevoked The token's authorization has been deleted.
token The token object. Contains the following properties:
token.usage The token type. One of pk , sk , or tk .
token.user The user to whom the token belongs.
token.authorization The token's unique identifier.
token.expires tk tokens only. The expiration time of the token.
token.created tk tokens only. The creation time of the token.
token.scopes tk tokens only. The token's assigned scopes.
token.client tk tokens only. Always "api" .
GET
/tokens/v2?access_token={access_token}

Example request

curl "https://api.mapbox.com/tokens/v2?access_token="

Example response for a public token

{
  "code": "TokenValid",
  "token": {
    "usage": "pk",
    "user": "mapbox",
    "authorization": "cijucimbe000brbkt48d0dhcx"
  }
}

Example response for a temporary token

{
  "code": "TokenExpired",
  "token": {
    "usage": "tk",
    "user": "mapbox",
    "expires": "2016-09-15T19:27:53.000Z",
    "created": "2016-09-15T19:27:23.000Z",
    "scopes": ["styles:read", "fonts:read"],
    "client": "api"
  }
}

List scopes

List scopes for a user. All potential scopes a user has access to are listed.

Public tokens may only contain scopes with the public property set to true. Secret tokens may contain any scope.

URL parameter Description
username The username of the account for which to list scopes.

Response body

The response body will contain an object for each scope the user has access to, each with the following properties:

Property Description
id The identifier of the scope.
description A description of permissions granted by the scope.
public true if the scope is available for public tokens.
GET
/scopes/v1/{username}?access_token=
scopes:list Token scope

Example request

$ curl "https://api.mapbox.com/scopes/v1/{username}?access_token="

Example response (truncated)

[
  {
    "id": "scopes:list",
    "description": "List all available scopes."
  },
  {
    "id": "styles:read",
    "public": true,
    "description": "Read styles."
  }
]

Analytics

This API is available for Commercial and Enterprise plans.

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

To use the Mapbox Analytics API, you need an access token with the analytics:read scope. To create a new secret token with the correct scope, visit your Account Dashboard. Click Create a token and select the analytics:read scope.

Retrieve analytics

Returns the request counts per day for the given resource, in the specified period of time.

URL parameter Description
resource_type The resource being requested. Valid resource types are: accounts , tokens , tilesets or styles .
username The username of the account that owns the resource.
id
(optional)
The ID of the resource.
If resource_type is: The id is:
accounts Not required.
tokens The complete token.
styles The style ID, which is the alphanumeric segment at the end of a style URL. (The style URL mapbox://styles/user/cimdoca6f00 contains the style ID cimdoca6f00 .)
tilesets The map ID.

You can further refine the results from this endpoint with the optional period query parameter:

Query parameter Description
period
(optional)
Two comma-separated dates as ISO formatted strings . The first date must be earlier than the second, and the maximum period is one year. period is inclusive of the dates provided. The default value is the previous 90 days.

Response body

A response to the Analytics API is a JSON object that contains the following properties:

Property Description
timestamps An array of dates as ISO formatted strings for each day included in the response.
period A two-element array with the start and end dates of the response period as ISO formatted strings.
services An object with a key for each applicable service. The value for each key 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:
Resource type Services returned in response
accounts mapview , static , tile , directions , geocode
tokens mapview , static , tile , directions , geocode
tilesets mapview , static , tile
styles mapview , static , tile
For the styles resource type, static and tile services refer to the Static API . For the tilesets resource type, static and tile services refer to the Maps API .
GET
/analytics/v1/{resource_type}/{username}/{id}?period={period}
analytics:read Token scope

Example Request

# Request usage data for the user mapbox's tileset mapbox.streets during a specific 2-day period
curl "https://api.mapbox.com/analytics/v1/tilesets/mapbox/mapbox.streets?period=2018-03-22T00:00:00.000Z,2018-03-24T00:00:00.000Z&access_token="

Example response

{
    "period": ["2016-03-22T00:00:00.000Z", "2016-03-24T00:00:00.000Z"],
    "timestamps": ["2016-03-22T00:00:00.000Z", "2016-03-23T00:00:00.000Z", "2016-03-24T00:00:00.000Z"],
    "services": {
        "mapview": [ 25, 22, 37 ],
        "static": [ 23, 20, 34 ],
        "tiles": [ 30, 39, 53 ]
    }
}
Mapbox API Documentation