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 the right side of your Mapbox Studio home page. You can also manage and create additional tokens on your API access tokens page in Mapbox Studio? 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 and Directions API are the exceptions: their endpoints are prefixed with /v4/{map_id} and /v4/directions 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.

Uploads

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

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

  1. Retrieve S3 credentials to stage the file
  2. Use an S3 client, like the AWS SDK, to upload a file to S3 using those credentials
  3. Create an upload using the staged file's URL
  4. Retrieve the upload's status as it is processed into a tileset
  5. Once the upload is complete, use the tileset ID like you'd use any other tileset

Limits

Type Size limit
TIFF and GeoTIFF 10 GB
MBTiles 25 GB
GeoJSON 1 GB
CSV 1 GB
KML 260 MB
GPX 260 MB
Shapefile (zipped) 260 MB
Mapbox Dataset 1 GB

Uploading Mapbox Datasets is only available to users who are part of the Mapbox Dataset beta.

Retrieve S3 credentials

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

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

Property Description
accessKeyId AWS Access Key ID
bucket S3 bucket name
key unique key for data to be staged
secretAccessKey AWS Secret Access Key
sessionToken temporary security token
url destination URL of the file

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

GET
/uploads/v1/{username}/credentials
uploads:write Token scope

Example request

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

Example response

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

Example AWS CLI usage

Create an upload

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

Uploads can only be use files in Mapbox's provided buckets, they cannot request resources from other S3 buckets or URLs.

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

Property Description
tileset the map ID to create or replace in the format username.nameoftileset
url HTTPS URL of the S3 object provided in the credential request or the Mapbox Dataset identifier.
name
(optional)
name for the tileset

Reuse of a tileset value will replace existing data: use a random value to make sure that a new tileset is created, or check existing tilesets first.

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

Property Description
complete whether the upload is complete (true) or not (false)
tileset The id of the tileset (map) that will be created or replace if upload is successful
error if null, the upload is in progress or successfully completed. Otherwise, a brief explanation of the error
id the unique identifier for the upload
name the name of the upload
modified time when the upload resource was last modified
created time 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 and 1
POST
/uploads/v1/{username}
uploads:write Token scope

Example request

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

Example request body

{
  "tileset": "{username}.mytileset",
  "url": "http://somebucket.s3.amazonaws.com/markers.json",
  "name": "example-markers"
}

Example requests to upload a Mapbox Dataset

{
  "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 will start at 0 and end at 1 when an upload is complete. If there's an error processing an upload, the error property will include an error message.

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

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

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

Query Parameter Description
reverse List uploads in chronological order, rather than reverse chronological order.
GET
/uploads/v1/{username}
uploads:list Token scope

Example request

curl "https://api.mapbox.com/uploads/v1/{username}?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

Remove a completed upload status from the upload listing.

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

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

Styles

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

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

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

Limits

  • Styles cannot reference more than 15 sources.
  • Styles cannot be larger than 5MB. This limit only applies to the style document itself, not the sprites, fonts, tilesets, or other resources it references.
  • The number of styles allowed per account varies based on plan level.

Mapbox styles

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

The style object

The style object conforms to the Mapbox Style Specification, with these additional account-related properties:

Property Description
metadata information about the style that is used in Mapbox Studio
created date and time the style was created
id id of the style
modified date and time the style was last modified
owner the username of the style owner
draft whether the style is draft or published
{
  "version": 8,
  "name": "{name}",
  "metadata": "{metadata}",
  "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}",
  "draft": true
}

Retrieve a style

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

GET
/styles/v1/{username}/{style_id}
styles:read Token scope

Example request

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

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
}

List styles

Retrieve a list of styles for an account. This endpoint does not return full styles, but returns style? metadata.

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 Mapbox Style Specification: invalid styles will produce a descriptive validation error.

Only the most recent version of the Mapbox Style Specification is supported. If the optional "name" property is omitted, it will be automatically set to the style's ID.

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

POST
/styles/v1/{username}
styles:write Token scope

Example request

# assuming that you have a valid style named basic-v8.json
curl -X POST "https://api.mapbox.com/styles/v1/{username}?access_token=" \
  --data @basic-v8.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.

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

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-v8.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
  }],
  "created": "2015-10-30T22:18:31.111Z",
  "id": "{style_id}",
  "modified": "2015-10-30T22:22:06.077Z",
  "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

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

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

Fonts

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

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

Font limits

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

Retrieve font glyph ranges

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

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

URL Parameter Description
font name of the font, can be multiple comma-separated font names
start A multiple of 256 between 0 and 65280
end start + 255
GET
/fonts/v1/{username}/{font},{font}/{start}-{end}.pbf
fonts:read Token scope

Example request

curl "https://api.mapbox.com/fonts/v1/{username}/{font},{font}/{start}-{end}.pbf?access_token="

Response

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

Sprites

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

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 100 icons is also a per-style limit. All sprite-related API methods will require a {style_id} parameter referring to the style? that sprite belongs to.

Sprite limits

  • Each icon must be smaller than 400kB.
  • Mapbox supports most, but not all SVG properties. Our SVG troubleshooting document describes these limits.
  • Icons can be up to 512px in each dimension.
  • Sprites can contain up to 100 icons.

Retrieve a sprite image or JSON

Retrieves a sprite? image or JSON document.

URL Parameter Description
@2x
(optional)
Render sprite at 2x resolution, appropriate for high-density displays
format
(optional)
.png for the sprite image, or .json for the document. Without a format specified, JSON will be returned.
GET
/styles/v1/{username}/{style_id}/sprite[@2x].{format}
styles:read Token scope

Example request

# requesting retina json
curl "https://api.mapbox.com/styles/v1/{username}/{style_id}/sprite@2x?access_token="

# requesting normal-resolution png
curl "https://api.mapbox.com/styles/v1/{username}/{style_id}/sprite.png?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 icon to sprite

Adds a new icon to an existing sprite?.

The request body should be raw SVG? data.

PUT
/styles/v1/{username}/{style_id}/sprite/{icon_name}
styles:write Token scope

Example request

curl -X PUT \
  "https://api.mapbox.com/styles/v1/{username}/{style_id}/sprite/{icon_name}?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 icon from sprite

Deletes an icon from an existing sprite?.

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

Embed a style

Request embeddable HTML suitable for fullscreen map displays or for inserting into blog posts and articles as <iframe> content.

Query Parameter Description
zoomwheel
(optional)
Disables zooming with mouse scroll wheel (default true)
title
(optional)
If true , shows a title box in upper right corner with map title and owner (default false )

Embed request format

GET
/styles/v1/{username}/{style_id}.html
styles:read Token scope

Example style embed

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

Maps

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

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

Mapbox classic map IDs

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

Retrieve tiles

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

URL Parameter Description
map_id unique identifier for the tileset in format username.id
format return format; .grid.json for UTFGrid, .mvt for vector tile, or an image extension listed below

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

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

Image format Description
png true color PNG
png32 32 color indexed PNG
png64 64 color indexed PNG
png128 128 color indexed PNG
png256 256 color indexed PNG
jpg70 70% quality JPG
jpg80 80% quality JPG
jpg90 90% quality JPG

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

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

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

Style-optimized vector tiles

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

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

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

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

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

Example request

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

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

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

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

# this requests a UTFGrid useful for interactivity
$ curl "https://api.mapbox.com/v4/my.tileset/1/0/0.grid.json?access_token="

# a style-optimized tile with "?style" in the query
$ curl "https://api.mapbox.com/v4/mapbox.mapbox-terrain-v2,mapbox.mapbox-streets-v7/12/1171/1566.mvt?style=mapbox://styles/mapbox/streets-v9@00&access_token="

Retrieve an HTML slippy map

Returns an HTML slippy map for sharing or embedding.

URL Parameter Description
options
(optional)
a comma-separated list of controls and map behaviors to be included in the map
hash
(optional)
a zoom level and location for the map in format #{zoom}/{lat}/{lon}
Query Parameter Description
zoomwheel enable zooming with the mouse wheel
zoompan enable zoom and pan controls
geocoder add a geocoder control
share add a share control

The response is HTML of a slippy map.

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

Example request

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

# the same map without any options
$ curl "https://api.mapbox.com/v4/mapbox.light.html?access_token="

Retrieve features from Mapbox Editor projects

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

URL Parameter Description
format json for GeoJSON, kml for KML
GET
/v4/{map_id}/features.{format}

Example request

$ curl "https://api.mapbox.com/v4/mapbox.dc-markers/features.json?access_token="

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

Example response

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "id": "{marker_id}",
        "title": "{title}",
        "description": "{description}",
        "marker-size": "{simplestyle size}",
        "marker-color": "{simplestyle color}",
        "marker-symbol": "{maki symbol}"
      },
      "geometry": {
        "coordinates": [ -77.031952, 38.913184 ],
        "type": "Point"
      },
      "id": "{feature_id}"
    }
  ]
}

Retrieve features from vector tiles

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

Query Parameter Description
radius
(optional)
Approximate distance in meters to query for features. Defaults to 0 .
limit
(optional)
Number of features between 1-50 to return. Defaults to 5 .

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

Restrictions and limits

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

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

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

  • For Polygon and MultiPolygon features the geometry is the point at the queried lon,lat
  • For LineString and MultiLineString features the geometry is the nearest point on the feature within the radius threshold of lon,lat
  • For Point and MultiPoint features the geometry is the nearest point within the radius threshold of lon,lat

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

Property Description
distance Approximate distance in meters from the feature result to the queried point.
layer The vector tile layer of the feature result.
GET
/v4/{map_id}/tilequery/{lon},{lat}.json

Example request

$ curl "https://api.mapbox.com/v4/mapbox.mapbox-terrain-v2/tilequery/-122.42901,37.80633.json?radius=10&access_token="

Example response

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [
          -122.42901,
          37.80633
        ]
      },
      "properties": {
        "ele": -10,
        "index": -1,
        "tilequery": {
          "distance": 0,
          "layer": "contour"
        }
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [
          -122.42901,
          37.80633
        ]
      },
      "properties": {
        "ele": 0,
        "index": -1,
        "tilequery": {
          "distance": 0,
          "layer": "contour"
        }
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [
          -122.42901,
          37.80633
        ]
      },
      "properties": {
        "ele": 10,
        "index": 1,
        "tilequery": {
          "distance": 0,
          "layer": "contour"
        }
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [
          -122.42901,
          37.80633
        ]
      },
      "properties": {
        "ele": 20,
        "index": 2,
        "tilequery": {
          "distance": 0,
          "layer": "contour"
        }
      }
    }
  ]
}

Retrieve TileJSON metadata

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

Query Parameter Description
?secure
(optional)
request resources in the response as HTTPS endpoints
GET
/v4/{map_id}.json

Example request

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

# the same request with HTTPS endpoints
$ curl "https://api.mapbox.com/v4/mapbox.emerald.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"
}

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 without interactivity or controls.

Raster tiles can be used in traditional web mapping libraries like Mapbox.js, Leaflet, OpenLayers, and others.

Retrieve a static map from a style

In contrast to the legacy Static API, this API supports pitch, bearing, and decimal zoom levels.

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

URL Parameter Description
lon longitude for the center point of the static map; number between -180 and 180
lat latitude for the center point of the static map; number between -90 and 90
zoom zoom level; number between 0 and 22 . Fractional zoom levels will be rounded to two decimal places.
bearing
(optional)
bearing: rotates the map around its center. number between 0 and 360 , interpreted as decimal degrees. 90 rotates the map 90° to the left. 180 flips the map. Defaults to 0 .
pitch
(optional)
pitch: tilts the map, producing a perspective effect. number between 0 and 60 . Defaults to 0 .
width width of the image; number between 1 and 1280
height height of the image; number between 1 and 1280
@2x
(optional)
If @2x is added to request a retina 2x image will be returned
Query Parameter Description
attribution
(optional)
boolean value controlling whether there is attribution on the image; defaults to true
logo
(optional)
boolean value controlling whether there is a Mapbox logo on the image; defaults to true

The attribution option removes watermarked attribution from the image, but not the 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.

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

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

GET
/styles/v1/{username}/{style_id}/static/{lon},{lat},{zoom},{bearing},{pitch}/{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-v8/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-v8/static/0,20,3,20/600x600?access_token="

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

Retrieve raster tiles from styles

Request 256x256 or 512x512 image tiles from a style? that can be arranged and displayed with the help of a mapping library. Normally, you will not need to interact with this API directly, as our SDKs handle this for you.

Mapbox.js? has built-in support for raster tiles from a style with L.mapbox.styleLayer.

256px vs 512px tiles

By default, the API will return 512x512 pixel image tiles. 512x512 image tiles will be offset by 1 zoom level when compared to traditional 256x256 tiles (for example, 512x512 tiles at zoom level 4 are equivalent to traditional tiles at zoom level 5). Tiles are 512x512 pixels unless the @2x parameter is included, in which case they're scaled to 1024x1024 pixels.

If you are using Leaflet? directly, the following options will need to included in the options argument to the L.tileLayer constructor:

{ tileSize: 512, zoomOffset: -1 }
GET
/styles/v1/{username}/{style_id}/tiles/tileSize?/{z}/{x}/{y}{@2x}

Example request

# default to 512x512 pixel tiles
curl "https://api.mapbox.com/styles/v1/mapbox/streets-v8/tiles/1/1/0?access_token="
# specify 256x256 pixel tiles
curl "https://api.mapbox.com/styles/v1/mapbox/streets-v8/tiles/256/1/1/0?access_token="
# specify 512x512 pixel tiles
curl "https://api.mapbox.com/styles/v1/mapbox/streets-v8/tiles/512/1/1/0?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.

GET
/styles/v1/{username}/{style_id}/wmts

Example request

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

Static (Classic)

The classic Mapbox Static API lets you request static maps from tilesets, with the option to add vector data as overlays. 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 without any interactivity or controls.

If you've uploaded data to Mapbox, you've already seen the classic Static API in action, powering the images at the top of all tileset? detail pages.

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

Limits

  • The maximum size for a static map image is 1280x1280 pixels.
  • The URL for a request to this API cannot be longer than 4096 characters.
  • Overlays cannot consist of more than 100 features.
  • Markers must be fewer than 160,000 pixels square (width multiplied by height).
  • Static map images give you design flexibility in how you want to display map attribution. When using Static maps it is your responsibility to add proper attribution for maps in your website or application.

Retrieve a static map image

URL Parameter Description
map_id unique identifier for the tileset in format username.id . These can be a comma-separated list of IDs.
overlay
(optional)
one or more comma-separated features to draw on top of the map. These can be in marker , geojson or path format.
position center and zoom level for the map. You can use auto to automatically fit image to overlay features, or {lon},{lat},{zoom} to set a specific location and zoom
width width of the image in pixels
height height of the image in pixels
format format of the image

The support formats are the same as for the Mapbox Maps API:

Image format Description
png True color PNG
png32 32 color indexed PNG
png64 64 color indexed PNG
png128 128 color indexed PNG
png256 256 color indexed PNG
jpg70 70% quality JPG
jpg80 80% quality JPG
jpg90 90% quality JPG

The {overlay} parameter can specify one or more features to draw on top of the map. The list of features should be comma-separated. Each overlay feature can be in one of three formats: marker, geojson or path.

Marker

{name}-{label}+{color}({lon},{lat})
URL Parameter Description
name Marker shape and size. Options are pin-s , pin-m , pin-l .
label
(optional)
Marker symbol. Options are an alphanumeric label a through z , 0 through 99 , or a valid Maki icon.
color
(optional)
A 3- or 6-digit hexadecimal color code.

Custom marker

url-{url}({lon},{lat})
URL Parameter Description
url a percent-encoded URL for the image

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

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

GeoJSON

geojson({geojson})

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

URL Parameter Description
geojson a valid GeoJSON object. simplestyle-spec styles for

GeoJSON features will be respected and rendered.

Path

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

URL Parameter Description
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
/v4/{map_id}/{overlay}/{position}/{width}x{height}{@2x}.{format}

Example Request

# without an overlay
curl "https://api.mapbox.com/v4/mapbox.dark/-76.9,38.9,5/1000x1000.png?access_token="

# as a jpg file
curl "https://api.mapbox.com/v4/mapbox.satellite/-76.9,38.9,5/1000x1000.jpg?access_token="

# as a 32 color indexed png file
curl "https://api.mapbox.com/v4/mapbox.dark/-76.9,38.9,5/1000x1000.png32?access_token="

# with a custom marker overlay
curl "https://api.mapbox.com/v4/mapbox.dark/url-https%3A%2F%2Fmapbox.com%2Fimg%2Frocket.png(-76.9,38.9)/-76.9,38.9,15/1000x1000.png?access_token="

# with a polyline overlay
curl "https://api.mapbox.com/v4/mapbox.streets/path-5+f44-0.5+f44-0.2(kumwFrjvbMaf%40kuD%7BnCkS)/-73.99,40.70,12/500x300.png?access_token="

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

Retrieve a standalone marker

Request a single marker image without any background map.

URL Parameter Description
name Marker shape and size. Options are pin-s , pin-m , pin-l .
label
(optional)
A Maki v0.5.0 icon value.
color
(optional)
A 3- or 6-digit hexadecimal color code. Default is gray.
@2x
(optional)
Include to request a high DPI version of the image.
GET
/v4/marker/{name}-{label}+{color}{@2x}.png

Example request

curl "https://api.mapbox.com/v4/marker/pin-s-car+f44@2x.png?access_token="

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

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

Datasets

A dataset is an editable collection of GeoJSON features. The Datasets API offers persistent storage for custom geographic data and supports reading, creating, updating, and removing features.

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

The dataset object

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

Property Description
owner the username of the dataset owner
id id for an existing dataset
created date and time the dataset was created
modified date and time the dataset was last modified
bounds the extent of features in the dataset as an array of west, south, east, north coordinates
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)
the 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}"
}

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.

Limits

  • Each feature cannot exceed 1023KB compressed. Features are compressed server side using geobuf.
  • The Dataset API is limited by per dataset id. Each dataset can receive 40 writes and 8 reads per second.

The feature object

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

List datasets

Lists all datasets for a particular account.

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

Creates a new, empty dataset.

POST
/datasets/v1/{username}
datasets:write Token scope

Example request

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

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

Returns a single dataset.

Retrieve information about an existing dataset.

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

Updates the properties of a particular dataset.

PATCH
/datasets/v1/{username}/{dataset_id}
datasets:write Token scope

Example request

curl --request 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

Deletes a dataset, including all features it contains.

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

List features

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

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

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

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

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

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

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

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

Property Description
id the id of an existing feature in the dataset
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

Retrieves a feature in a dataset.

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

Removes a feature from a dataset.

DELETE
https://api.mapbox.com/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

Tokens

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

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

The token format

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

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

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

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

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

The authorization object

An authorization contains information about the capabilities of a token. Each authorization contains the following properties:

Property Description
id the identifier for the authorization
usage the type of authorization
client the client for the authorization, always 'api'
default if the token is a default token
scopes array of scopes the authorization grants
note human friendly description of the authorization
created date and time the authorization was created
modified date and time the authorization was last modified
token the token representing the authorization

Limits

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

The authorization object

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

List tokens

Lists all tokens for an account.

This endpoint supports pagination.

Note: The token property will not be included for sk tokens.

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

The scopes included in the token decide whether the token is public or secret. A public token may only contains public scopes.

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

Example request

curl -X POST "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 temporary token

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

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

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

Unlike public and secret tokens, a temporary token contains the authorization inside the payload of the token instead of referencing an authorization persisted on the server. Temporary tokens cannot be updated or revoked after they are created.

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

Example request

curl -X POST "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's authorization

Update the authorization's note or scopes.

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

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

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

Example request

curl -X PATCH  "https://api.mapbox.com/tokens/v2/{username}/{authorization_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 an authorization

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

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

DELETE
/tokens/v2/{username}/{authorization_id}
tokens:write Token scope

Example request

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

Example response

HTTP 204

Retrieve a token

Check if a token is valid. If the token is invalid an explanation of why is returned as the code property.

The body of the token is parsed and included as the token property in object form.

Code Description
TokenValid the token is valid and active
TokenMalformed the token can not be parsed
TokenInvalid the signature for the token does not validate
TokenExpired the token was temporary and expired
TokenRevoked the authorization associated with the token has been deleted
GET
/tokens/v2?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.

Property Description
id identifier of the scope
description human friendly description of 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."
  }
]

Directions

This documentation is for the v5 API. See the documentation for the legacy v4 API.

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
  • produce turn-by-turn instructions
  • produce routes with up to 25 coordinates anywhere on earth

This API supports four different routing profiles:

  • mapbox/driving-traffic for automotive routing. This profile factors in current and historic traffic conditions to avoid slowdowns.
  • 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

  • Directions requests must specify at least two waypoints as starting & ending points. Requests using driving, walking, and cycling profiles can specify up to 25 total waypoints along the route. Requests using the driving-traffic profile can specify up to 3 waypoints.
  • Traffic coverage for the driving-traffic profile is limited to the United States, Mexico, and Canada. Requests to this profile revert to driving profile results for areas without traffic coverage.
  • Maximum 60 requests per minute

Retrieve directions

Try this in API Playground

URL Parameter Description
profile Routing profile; either mapbox/driving-traffic , mapbox/driving , mapbox/walking , or mapbox/cycling
coordinates Semicolon-separated list of {longitude},{latitude} coordinate pairs to visit in order; there can be between 2 and 25 coordinates.

The response may be altered with optional query parameters:

Query Parameter Description
alternatives
(optional)
Whether to return alternative routes. Can be true or false (default).
geometries
(optional)
Format of the returned geometry. Allowed values are: geojson (as LineString ), polyline ( documentation ) with precision 5, polyline6 ( documentation polyline with precision 6). The default value is polyline .
overview
(optional)
Type of returned overview geometry. Can be full (the most detailed geometry available), simplified (a simplified version of the full geometry), or false (no overview geometry). The default is simplified .
radiuses
(optional)
Maximum distance in meters that each coordinate is allowed to move when snapped to a nearby road segment. There must be as many radiuses as there are coordinates in the request, each separated by ; . Values can be any number greater than 0 or they can be the string unlimited . If no routable road is found within the radius, a NoSegment error is returned.
steps
(optional)
Whether to return steps and turn-by-turn instructions. Can be true or false . The default is false .
continue_straight
(optional)
Sets allowed direction of travel when departing intermediate waypoints. If true the route will continue in the same direction of travel. If false the route may continue in the opposite direction of travel. Defaults to true for mapbox/driving and false for mapbox/walking and mapbox/cycling .
bearings
(optional)
Used to filter the road segment the waypoint will be placed on by direction and dictates the angle of approach. This option should always be used in conjunction with the radiuses parameter. The parameter takes two values per waypoint: the first is an angle clockwise from true north between 0 and 360. The second is the range of degrees the angle can deviate by. We recommend a value of 45° or 90° for the range, as bearing measurements tend to be inaccurate. This is useful for making sure we reroute vehicles on new routes that continue traveling in their current direction. A request that does this would provide bearing and radius values for the first waypoint and leave the remaining values empty. If provided, the list of bearings must be the same length as the list of waypoints, but you can skip a coordinate and show its position with the ; separator.
annotations
(optional)
Whether or not to return additional metadata along the route. Can be one or all of 'duration' or 'distance', each separated by , . See the RouteLeg object for more details on what it is included with annotations.

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

GET
https://api.mapbox.com/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 polyline response
curl "https://api.mapbox.com/directions/v5/mapbox/driving/13.4301,52.5109;13.4265,52.5080;13.4194,52.5072?radiuses=40;;100&geometries=polyline&access_token="

# specify bearings
curl "https://api.mapbox.com/directions/v5/mapbox/driving/13.4301,52.5109;13.4265,52.5080;13.4316,52.5021?bearings=60,45;;45,45&radiuses=100;100;100&access_token="

Directions response object

  • code: String indicating the state of the response. This is a separate code than the HTTP status code. On normal valid responses, the value will be Ok.
  • waypoints: Array of Waypoint objects. Each waypoints is an input coordinate snapped to the road and path network. The waypoints appear in the array in the order of the input coordinates.
  • routes: Array of Route objects ordered by descending recommendation rank. May contain at most two routes.

Example response

{
    "code": "Ok",
    "routes": [
        {
            "legs": [
                {
                    "steps": [
                        {
                            "intersections": [
                                {
                                    "out": 0,
                                    "entry": [
                                        true
                                    ],
                                    "bearings": [
                                        74
                                    ],
                                    "location": [
                                        -6.80897,
                                        62.000075
                                    ]
                                },
                                {
                                    "out": 0,
                                    "location": [
                                        -6.807551,
                                        62.000267
                                    ],
                                    "bearings": [
                                        75,
                                        150,
                                        255
                                    ],
                                    "entry": [
                                        true,
                                        true,
                                        false
                                    ],
                                    "in": 2
                                },
                                {
                                    "out": 0,
                                    "location": [
                                        -6.804464,
                                        62.000737
                                    ],
                                    "bearings": [
                                        60,
                                        255,
                                        330
                                    ],
                                    "entry": [
                                        true,
                                        false,
                                        true
                                    ],
                                    "in": 1
                                }
                            ],
                            "geometry": "oklyJ`{ph@e@{G]gEu@qJIo@}AuLcAmHs@gF",
                            "maneuver": {
                                "bearing_after": 74,
                                "location": [
                                    -6.80897,
                                    62.000075
                                ],
                                "bearing_before": 0,
                                "type": "depart",
                                "instruction": "Head east on Kirkjubøarvegur"
                            },
                            "duration": 78.2,
                            "distance": 527.1,
                            "name": "Kirkjubøarvegur",
                            "mode": "driving"
                        },
                        {
                            "intersections": [
                                {
                                    "out": 2,
                                    "location": [
                                        -6.799599,
                                        62.001805
                                    ],
                                    "bearings": [
                                        135,
                                        240,
                                        315
                                    ],
                                    "entry": [
                                        true,
                                        false,
                                        true
                                    ],
                                    "in": 1
                                },
                                {
                                    "out": 2,
                                    "location": [
                                        -6.800793,
                                        62.002501
                                    ],
                                    "bearings": [
                                        60,
                                        135,
                                        315
                                    ],
                                    "entry": [
                                        true,
                                        false,
                                        true
                                    ],
                                    "in": 1
                                }
                            ],
                            "geometry": "ivlyJn`oh@gBpDa@z@Sb@aAfBw@|@w@t@s@d@q@P[B",
                            "maneuver": {
                                "bearing_after": 320,
                                "type": "end of road",
                                "modifier": "left",
                                "bearing_before": 64,
                                "location": [
                                    -6.799599,
                                    62.001805
                                ],
                                "instruction": "Turn left onto Marknagilsvegur"
                            },
                            "duration": 43.6,
                            "distance": 303.2,
                            "name": "Marknagilsvegur",
                            "mode": "driving"
                        },
                        {
                            "intersections": [
                                {
                                    "in": 0,
                                    "entry": [
                                        true
                                    ],
                                    "bearings": [
                                        175
                                    ],
                                    "location": [
                                        -6.802374,
                                        62.004141
                                    ]
                                }
                            ],
                            "geometry": "{dmyJxqoh@",
                            "maneuver": {
                                "bearing_after": 0,
                                "location": [
                                    -6.802374,
                                    62.004141
                                ],
                                "bearing_before": 355,
                                "type": "arrive",
                                "instruction": "You have arrived at your destination"
                            },
                            "duration": 0,
                            "distance": 0,
                            "name": "Marknagilsvegur",
                            "mode": "driving"
                        }
                    ],
                    "summary": "Kirkjubøarvegur, Marknagilsvegur",
                    "duration": 121.8,
                    "distance": 830.3
                }
            ],
            "geometry": "oklyJ`{ph@yBuY_F{^_FxJoBrBs@d@mAT",
            "duration": 121.8,
            "distance": 830.3
        }
    ],
    "waypoints": [
        {
            "name": "Kirkjubøarvegur",
            "location": [
                -6.80897,
                62.000075
            ]
        },
        {
            "name": "Marknagilsvegur",
            "location": [
                -6.802374,
                62.004141
            ]
        }
    ]
}

Waypoint object

An input coordinate snapped to the roads network.

  • name: String with the name of the way the coordinate snapped to
  • location: Array of [ longitude, latitude ] for the snapped coordinate

Example Waypoint object

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

Route object

A route through (potentially multiple) waypoints.

  • distance: Float indicating the distance traveled in meters
  • duration: Float indicating the estimated travel time in seconds
  • geometry: Depending on the geometries parameter this is a GeoJSON LineString or a Polyline string. Depending on the overview parameter this is the complete route geometry (full), a simplified geometry to the zoom level at which the route can be displayed in full (simplified), or is not included (false).
  • legs: Array of RouteLeg objects

Example Route object

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

RouteLeg object

A route between only two waypoints.

  • distance: Number indicating the distance traveled in meters

  • duration: Number indicating the estimated travel time in seconds

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

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

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

    annotation | Description -------------------|--------------------------------- distance | The distance, in meters, between each pair of coordinates duration | The duration, in seconds, between each pair of coordinates

Example RouteLeg object

{
    "annotation": {
        "duration": [
            10.6,
            7.1,
            4.8,
            12.8,
            9.3,
            17.3,
            11,
            15.6
        ]
    },
    "duration": 88.4,
    "distance": 830.4,
    "steps": [ ],
    "summary": ""
}

RouteStep object

Includes one StepManeuver object and travel to the following RouteStep.

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

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

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

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

  • ref: String with reference number or code of the way along which the travel proceeds. Optionally included, if data is available.

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

  • mode: String indicating the mode of transportation. Possible values:

    • For mapbox/driving: driving, ferry, unaccessible
    • For mapbox/walking: walking, ferry, unaccessible
    • For mapbox/cycling: cycling, walking, ferry, train, unaccessible
  • maneuver: One StepManeuver object

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

    • location: A [longitude, latitude] pair describing the location of the turn.
    • bearings: A list of bearing values (for example [0,90,180,270]) that are available at the intersection. The bearings describe all available roads at the intersection.
    • entry: A list of entry flags, corresponding in a 1:1 relationship to the bearings. A value of true indicates that the respective road could be entered on a valid route. false indicates that the turn onto the respective road would violate a restriction.
    • in: Index into bearings/entry array. Used to calculate the bearing before the turn. Namely, the clockwise angle from true north to the direction of travel before the maneuver/passing the intersection. To get the bearing in the direction of driving, the bearing has to be rotated by a value of 180. The value is not supplied for departure maneuvers.
    • out: Index into the bearings/entry array. Used to extract the bearing after the turn. Namely, The clockwise angle from true north to the direction of travel after the maneuver/passing the intersection. The value is not supplied for arrive maneuvers.
    • lanes: Array of Lane objects that represent the available turn lanes at the intersection. If no lane information is available for an intersection, the lanes property will not be present.

Example RouteStep object

{
    "intersections": [
      {
        "out": 1,
        "location": [
          13.424671,
          52.508812
        ],
        "bearings": [
          120,
          210,
          300
        ],
        "entry": [
          false,
          true,
          true
        ],
        "in": 0
      }
    ],
    "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,
    "name": "Adalbertstraße",
    "mode": "driving"
}

StepManeuver object

  • location: Array of [ longitude, latitude ] coordinates for the point of the maneuver

  • bearing_before: Number between 0 and 360 indicating the clockwise angle from true north to the direction of travel right before the maneuver

  • bearing_after: Number between 0 and 360 indicating the clockwise angle from true north to the direction of travel right after the maneuver

  • instruction: A human-readable instruction of how to execute the returned maneuver

  • type: String indicating the type of maneuver

  • modifier Optional String indicating the direction change of the maneuver

    modifier | Description -------------------|--------------------------------- uturn | indicates 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

The list of turns without a modifier is limited to: depart / arrive. If the source / target location is close enough to the depart / arrive location, no modifier will be given.

The meaning depends on the type property.

type Description
depart / arrive modifier indicates the position of departure point and arrival point in relation to the current direction of travel

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

Example StepManeuver object

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

Maneuver types

type Description
turn a basic turn into direction of the modifier
new name the road name changes (after a mandatory turn)
depart indicates departure from a leg
arrive indicates arrival to a destination of a leg
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/right side of a fork
end of road road ends in a T intersection
use lane use specific lanes to continue going straight
continue continue on a street after a turn
roundabout traverse roundabout, has additional field exit
rotary a large roundabout , that can have additional properties rotary_name and rotary_pronunciation
roundabout turn small roundabout that is treated as an intersection
notification change of driving conditions, e.g. change of mode from driving to ferry

Lane object

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

  • valid: Boolean value for whether this lane can be taken to complete the maneuver. For instance, if the lane array has four objects and the first two are marked as valid, then the driver can take either of the left lanes and stay on the route.
  • indications: Array of signs for each turn lane. There can be multiple signs. For example, a turning lane can have a sign with an arrow pointing left and another sign with an arrow pointing straight.

Example Lane object

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

Directions errors

On error, the server responds with different HTTP status codes. For responses with HTTP status codes lower than 500, the JSON response body includes the code property, which may be used by client programs to manage control flow. The response body may also include a message property, with a human-readable explanation of the error. If a server error occurs, the HTTP status code will be 500 or higher and the response will not include a code property.

Response body code HTTP status code comment
Ok 200 Normal success case
NoRoute 200 There was no route found for the given coordinates. Check for impossible routes (e.g. routes over oceans without ferry connections).
NoSegment 200 No road segment could be matched for coordinates. Check for coordinates too far away from a road.
ProfileNotFound 404 Use a valid profile as described above
InvalidInput 422 The given request was not valid. The message key of the response will hold an explanation of the invalid input.

Map Matching

This documentation is for the v5 API. See the documentation for the v4 API.

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.

Limits

  • Maximum 60 requests per minute
  • Maximum 100 coordinates per request
  • Results must be displayed on a Mapbox map using one of our libraries or SDKs

For high volume or other use cases, contact us.

Match response object

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

  • code: a string depicting the state of the response; see below for options
  • matchings: an array of Match objects
  • tracepoints: an array of Tracepoint objects representing the location an input point was matched with. Array of Waypoint objects representing all input points of the trace in the order they were matched. If a trace point is omitted by map matching because it is an outlier, the entry will be null.
{
    "code": "Ok",
    "matchings": [{
        "confidence": 0.9548844020537051,
        "distance": 103.7,
        "duration": 16.4,
        "geometry": "gatfEfidjUi@Le@@Y?E??J?^Hf@",
        "legs": [{
            "steps": [],
            "summary": "",
            "duration": 1.6,
            "distance": 24.8
        }, {
            "steps": [],
            "summary": "",
            "duration": 1.3,
            "distance": 21.1
        }, {
            "steps": [],
            "summary": "",
            "duration": 0.9,
            "distance": 13.9
        }, {
            "steps": [],
            "summary": "",
            "duration": 6.3,
            "distance": 9.1
        }, {
            "steps": [],
            "summary": "",
            "duration": 2.7,
            "distance": 14.8
        }, {
            "steps": [],
            "summary": "",
            "duration": 3.6,
            "distance": 20
        }]
    }],
    "tracepoints": [{
        "waypoint_index": 0,
        "location": [-117.172836, 32.71204],
        "name": "North Harbor Drive",
        "matchings_index": 0
    }, {
        "waypoint_index": 1,
        "location": [-117.172909, 32.712254],
        "name": "North Harbor Drive",
        "matchings_index": 0
    }, {
        "waypoint_index": 2,
        "location": [-117.17292, 32.712443],
        "name": "North Harbor Drive",
        "matchings_index": 0
    }, {
        "waypoint_index": 3,
        "location": [-117.172921, 32.712568],
        "name": "North Harbor Drive",
        "matchings_index": 0
    }, {
        "waypoint_index": 4,
        "location": [-117.172984, 32.7126],
        "name": "West G Street",
        "matchings_index": 0
    }, {
        "waypoint_index": 5,
        "location": [-117.173142, 32.712596],
        "name": "West G Street",
        "matchings_index": 0
    }, {
        "waypoint_index": 6,
        "location": [-117.173344, 32.712545],
        "name": "West G Street",
        "matchings_index": 0
    }]
}

Match object

A match object is a Route object with an additional confidence field.

  • confidence: a number between 0 (low) and 1 (high) indicating level of confidence in the returned match

Refer to the Route object documentation for how the rest of a Match object is structured.

Example Match object

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

Tracepoint object

A tracepoint object is Waypoint object with two additional fields:

  • matchings_index: Index to the match object in matchings the sub-trace was matched to.
  • waypoint_index: Index of the waypoint inside the matched route.

Example Tracepoint object

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

Retrieve a match

Returns a path on the road and path network closest to the input traces.

URL Parameter Description
profile A directions profile ID; either mapbox/driving , mapbox/walking , or mapbox/cycling
Query Parameter Description
geometries
(optional)
Format of the returned geometry. Allowed values are: geojson (as LineString ), polyline ( documentation ) with precision 5, polyline6 ( documentation polyline with precision 6). The default value is polyline .
radiuses
(optional)
A list of integers in meters indicating the assumed precision of the used tracking device. There must be as many radiuses as there are coordinates in the request, each separated by ; . Values can be a number between 0 and 30. Use higher numbers (20-30) for noisy traces and lower numbers (1-10) for clean traces. The default value is 5.
steps
(optional)
Whether to return steps and turn-by-turn instructions. Can be true or false . The default is false .
overview
(optional)
Type of returned overview geometry. Can be full (the most detailed geometry available), simplified (a simplified version of the full geometry), or false (no overview geometry). The default is simplified .
timestamps
(optional)
Timestamps corresponding to each coordinate provided in the request; must be numbers in Unix time (seconds since the Unix epoch). There must be as many timestamps as there are coordinates in the request, each separated by ; .
annotations
(optional)
Whether or not to return additional metadata along the route. Can be one or all of 'duration' or 'distance', each separated by , . See the RouteLeg object for more details on what it is included with annotations.

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

Some pre-processing tips to achieve the best results:

  • The Map Matching API is limited to processing traces with up to 100 coordinates. If you need to process longer traces, you can split the trace and make multiple requests.
  • Clusters of points (like a person waiting at a train crossing for a few minutes) often don't add more information to a trace and should be removed.
  • 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.
  • geojson-tidy removes clusters and re-samples traces. If provided traces are known to be of poor quality, GeoJSON tidying is highly recommended, otherwise map matching results are likely to be poor.
GET
/matching/v5/{profile}/{coordinates}.json

Example request

$ curl "https://api.mapbox.com/matching/v5/mapbox/driving/-117.1728265285492,32.71204416018209;-117.17288821935652,32.712258556224;-117.17293113470076,32.712443613445814;-117.17292040586472,32.71256999376694;-117.17298477888109,32.712603845608285;-117.17314302921294,32.71259933203019;-117.17334151268004,32.71254065549407?access_token="

Matching errors

On error, the server responds with different HTTP status codes. For responses with HTTP status codes lower than 500, the JSON response body includes the code property, which may be used by client programs to manage control flow. The response body may also include a message property, with a human-readable explaination of the error. If a server error occurs, the HTTP status code will be 500 or higher and the response will not include a code property.

Code option Description
Ok Normal case
NoMatch The input did not produce any matches. 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 Profile should be mapbox.driving , mapbox.walking , or mapbox.cycling .

Geocoding

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

Geocoding lets you convert location text into geographic coordinates: turning 1600 Pennsylvania Ave NW into -77.0366, 38.8971.

Reverse geocoding turns geographic coordinates into place names: from -77.036, 38.897 to 1600 Pennsylvania Ave NW. These place names can vary from specific addresses to states and countries that contain the given coordinate.

Swift and Objective-C support for Geocoding is provided by the MapboxGeocoder.swift library.

Restrictions and limits

Use of the geocoding API is rate limited by access token?. These limits vary by plan.

Account level Rate limit
Starter 600 requests per minute
Premium 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.

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

The results from geocoding with the mapbox.places mode must be displayed on a Mapbox map and cannot be stored permanently. The mapbox.places-permanent mode, available with an Enterprise plan, does not have these licensing restrictions.

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

Queries are limited to a total of 20 words and numbers, separated by spacing or punctuation. They also can't be longer than 256 characters.

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

Request format

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

URL Parameter Description
query a location; a place name for forward geocoding or a coordinate pair (longitude, latitude location) for reverse geocoding
mode mapbox.places or mapbox.places-permanent for enterprise/batch geocoding (see Response format below)
Query Parameter Description
country
(optional)
ISO 3166 alpha 2 country codes, separated by commas
proximity
(optional)
Location around which to bias results, given as longitude,latitude
types
(optional)
Filter results by one or more type. Options are country , region , postcode , place , locality , neighborhood , address , poi , poi.landmark . Multiple options can be comma-separated.
autocomplete
(optional)
Whether or not to return autocomplete results. Options are true and false . The default is true .
bbox
(optional)
Bounding box within which to limit results, given as minX,minY,maxX,maxY
limit
(optional)
Limit the number of results returned. The default is 5 for forward geocoding and 1 for reverse geocoding.

The {country} parameter limits results to a set of one or more countries, specified with ISO 3166 alpha 2 country codes and separated by commas.

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

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

The {bbox} parameter limits search results to those falling within a bounding box? given in minX,minY,maxX,maxY coordinates.

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

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

Response format

Our geocoding data is updated and improved constantly and responses for a given query may change. Geocoding results are returned in Carmen GeoJSON format. This format declares the types and existence of properties, but not their specific values: their values can change as our data improves.

Feature IDs are formatted like {type}.{id}. {type} is one of the types listed above. Additional feature types may be added in the future, but the current types will stay the same. The numeric part of a feature ID may change between data updates.

The {properties} property of the feature is unstable: only what is specified in Carmen GeoJSON is part of the stable API. But a response feature may include the following additional information in its properties or context sections. Your implementation should check for the presence of these values in a response before it attempts to use them.

Name Description
short_code ISO 3166-1 country and ISO 3166-2 region codes
wikidata The Wikidata identifier for a country , region or place
category
Comma-separated list of categories applicable to a poi
maki
Suggested icon mapping from the most current version of the Maki project for a poi feature, based on its category
landmark Boolean value indicating whether a poi feature is a landmark. Landmarks are particularly notable or long-lived features like schools, parks, museums and places of worship.

Results are returned in order of relevance. They also have a relevance property that is based on how much of the query matched text in the result. You can use the relevance property to remove rough results if you require a response that matches your whole query.

Example response

{
  "type": "FeatureCollection",
  "query": [
    "los",
    "angeles"
  ],
  "features": [
    {
      "id": "place.33004",
      "type": "Feature",
      "text": "Los Angeles",
      "place_name": "Los Angeles, California, United States",
      "relevance": 0.99,
      "properties": {
        "wikidata": "Q65"
      },
      "bbox": [
        -118.521455009776,
        33.90189299,
        -118.12130699003,
        34.1614390095055
      ],
      "center": [
        -118.2439,
        34.0544
      ],
      "geometry": {
        "type": "Point",
        "coordinates": [
          -118.2439,
          34.0544
        ]
      },
      "context": [
        {
          "id": "postcode.8055854450707500",
          "text": "90012"
        },
        {
          "id": "region.6020809690311220",
          "text": "California",
          "short_code": "US-CA",
          "wikidata": "Q99"
        },
        {
          "id": "country.12862386939497690",
          "text": "United States",
          "short_code": "us",
          "wikidata": "Q30"
        }
      ]
    },
    {
      "id": "place.15100",
      "type": "Feature",
      "text": "Los Ángeles",
      "place_name": "Los Ángeles, Bío Bío, Chile",
      "relevance": 0.99,
      "properties": {},
      "bbox": [
        -72.6835636,
        -37.6587686,
        -72.0420575,
        -37.1736364
      ],
      "center": [
        -72.3277,
        -37.4079
      ],
      "geometry": {
        "type": "Point",
        "coordinates": [
          -72.3277,
          -37.4079
        ]
      },
      "context": [
        {
          "id": "region.7807420235045040",
          "text": "Bío Bío",
          "short_code": "CL-BI",
          "wikidata": "Q2170"
        },
        {
          "id": "country.14661701841731110",
          "text": "Chile",
          "short_code": "cl",
          "wikidata": "Q298"
        }
      ]
    }
  ],
  "attribution": "NOTICE: © 2016 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."
}

Search for places

Try this in API Playground

This is often called forward geocoding. Request feature data that best matches the input {query} text. The response includes one or more results ordered by relevance.

This API is used by the Mapbox.js L.mapbox.geocoderControl and the mapbox-gl-geocoder user interfaces.

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

Example request

curl "https://api.mapbox.com/geocoding/v5/mapbox.places/1600+pennsylvania+ave+nw.json&access_token="

# using the proximity option to limit
# results to Canada. even though 1600 pennsylvania
# ave nw will usually return the white house
# in America, this will only return
# addresses in Canada
curl "https://api.mapbox.com/geocoding/v5/mapbox.places/1600+pennsylvania+ave+nw.json?country=ca&access_token="

# there are many towns named 'Chester', but adding a
# proximity parameter in New Jersey ensures that the town
# of Chester, New Jersey is in the search results
curl "https://api.mapbox.com/geocoding/v5/mapbox.places/chester.json?proximity=-74.70850,40.78375&access_token="

# search only for countries named Georgia,
# so that we don't find the state in America
curl "https://api.mapbox.com/geocoding/v5/mapbox.places/georgia.json?types=country&access_token="

# using the bounding box option, limit results for a search for "Starbucks" to those within a portion of
# Washington, D.C.
curl "https://api.mapbox.com/geocoding/v5/mapbox.places/starbucks.json?bbox=-77.083056,38.908611,-76.997778,38.959167&access_token="

# using limit option to limit the numbe of 
# results to `2`. Even though there are many possible matches
for `Washington`, this query will return only 2 results.
curl "https://api.mapbox.com/geocoding/v5/mapbox.places/Washington.json?limit=2&access_token="

Retrieve places near a location

Try this in API Playground

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

URL Parameter Description
mode mapbox.places or mapbox.places-permanent for enterprise/batch geocoding (see Response format below)
Query Parameter Description
types
(optional)
Filter results by one or more type. Options are country , region , postcode , place , locality , neighborhood , address , poi , poi.landmark . Multiple options can be comma-separated. Note that poi.landmark returns a subset of the results returned by poi .
limit
(optional)
Limit the maximum number of results. The default is 1 , and the maximum is 5 . If using this option a single types is required.
GET
/geocoding/v5/{mode}/{longitude},{latitude}.json

Example request

curl "https://api.mapbox.com/geocoding/v5/mapbox.places/-73.989,40.733.json?access_token="

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

Batch requests

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

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

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

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

Tilesets

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

Limits

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

The tileset object

Each tileset? object contains the following properties:

Property Description
type kind of data contained, either raster or vector
center longitude, latitude and zoom level for the center of contained data
created date and time the tileset was created
description human friendly description of the tileset
filesize storage in bytes consumed by the tileset
id machine identifier for the tileset
modified date and time the tileset was last modified
visibility access control for the tileset, either public or private
status 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

Lists all tilesets for an account.

This endpoint supports pagination.

The response may be altered with optional query parameters:

Query Parameter Description
type Filter results by tileset type, either raster or vector .
visibility Filter results visibility, either public or private . Private tilesets require an access token belonging to the owner, while public tilesets may be requested with an access token belonging to any user.
sortby Sort the listing by created or modified timestamps.
limit The maximum number of objects to return. An integer between 1 and 500 is expected, defaults to 100. See pagination for details
GET
/tilesets/v1/{username}
tilesets:list Token scope

Example request

$ curl "https://api.mapbox.com/tilesets/v1/{username}?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": "vector",
    "center": [-122.43612326651723, 37.75953636431886, 12],
    "created": "2016-01-07T19:12:56.530Z",
    "description": "",
    "filesize": 3271136,
    "id": "mapbox.0z6e1qup",
    "modified": "2016-01-30T02:13:00.093Z",
    "name": "Zoning_Districts",
    "visibility": "private",
    "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"
  }
]

Distance

The Mapbox Distance API returns all travel times between many points.

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

A B C
A A → A A → B A → C
B B → A B → B B → C
C C → A C → B C → C

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

Limits

  • Maximum 100 coordinate pairs per request
  • Maximum 60 requests per minute

For higher volumes, contact us.

Retrieve a duration matrix

Returns a duration matrix showing travel times between given locations.

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

  • driving for car travel times
  • walking for pedestrian and hiking travel times
  • cycling for bicycle travel times

The Content-Type header of the request needs to be set to application/json.

Property Description
coordinates an array of up to 100 [longitude, latitude] coordinate pairs

The Distance API returns an object that resembles a matrix, or table, of durations: the time it takes to get between two points on the shortest route in seconds. The order of durations in the response object is directly related to the order of coordinates in the request body.

The Distance API will always return the duration on the fastest route. Durations between points may not be symmetric, as the routes may differ by direction (for example, A to B may have a different duration than B to A). The Distance API only returns durations in seconds; it does not return route geometries.

The duration between the same coordinate is always 0. If a duration can not be found, the result is null. All values are in seconds.

Property Description
durations an array of arrays of durations in seconds
POST
/distances/v1/mapbox/{profile}

Example Request

curl -X POST \
  --header "Content-Type:application/json" \
  -d @coordinates.json \
  "https://api.mapbox.com/distances/v1/mapbox/driving?access_token="

Example request body

{
  "coordinates": [
    ["A"],
    ["B"],
    ["C"]
  ]
}
{
  "coordinates": [
    [13.41894, 52.50055],
    [14.10293, 52.50055],
    [13.50116, 53.10293]
  ]
}

Example response

{
  "durations": [
    ["A to A", "A to B", "A to C"],
    ["B to A", "B to B", "B to C"],
    ["C to A", "C to B", "C to C"]
  ]
}
{
  "durations": [
    [0,    2910, null],
    [2903, 0,    5839],
    [4695, 5745, 0   ]
  ]
}

Optimized Trips

The Mapbox Optimized Trips API returns a duration-optimized trip between the input coordinates. This is also known as solving the Travelling Salesperson Problem. A typical use case for this API is planning the route for deliveries in a city. Optimized trips can be retrieved for car driving, bicycling and walking or hiking.

Limits

  • Maximum 12 coordinates
  • Maximum 60 requests per minute

For higher volumes, contact us.

Note that for under 10 coordinates, the returned results will be optimal. For 10 and more coordinates, the results will be optimized approximations.

Retrieve optimized trips

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

  • driving for car trips
  • walking for pedestrian and hiking trips
  • cycling for bicycle trips

The driving-traffic profile is not support.

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

The response may be altered with optional query parameters:

Query Parameter Description
geometries
(optional)
Format of the returned geometries. Allowed values are: polyline (default, documentation , polyline with precision 5), polyline6 ( documentation , polyline with precision 6), geojson (as LineString ).
overview
(optional)
Type of returned overview geometry. Allowed values are: simplified (default, a simplified version of the geometry), full (the most detailed geometry available), false (no overview geometry).
radiuses
(optional)
Maximum distance in meters that each coordinate is allowed to move when snapped to a nearby road segment. There must be as many radiuses as there are coordinates in the request, each separated by ; . Values can be any number greater than 0 or they can be the string unlimited . If no routable road is found within the radius, a NoSegment error is returned.
steps
(optional)
Whether to return steps and turn-by-turn instructions. Allowed values are: false (default), true
bearings
(optional)
Used to filter the road segment the waypoint will be placed on by direction and dictates the angle of approach. This option should always be used in conjunction with the radiuses parameter. The parameter takes two values per waypoint: the first is an angle clockwise from true north between 0 and 360. The second is the range of degrees the angle can deviate by. We recommend a value of 45° or 90° for the range, as bearing measurements tend to be inaccurate. This is useful for making sure we reroute vehicles on new routes that continue traveling in their current direction. A request that does this would provide bearing and radius values for the first waypoint and leave the remaining values empty. If provided, the list of bearings must be the same length as the list of waypoints, but you can skip a coordinate and show its position with the ; separator.

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

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

Example requests

# request an optimized car trip with no additional options
curl "https://api.mapbox.com/optimized-trips/v1/mapbox/driving/-122.42,37.78;-122.45,37.91;-122.48,37.73?access_token="

# request an optimized bicycle trip with steps and geojson response
curl "https://api.mapbox.com/optimized-trips/v1/mapbox/cycling/-122.42,37.78;-122.45,37.91;-122.48,37.73?steps=true&geometries=geojson&access_token="

Optimized trip response format

  • code: String indicating the state of the response. This is a separate code than the HTTP status code. On normal valid responses, the value will be Ok. See the errors section below for more information.
  • waypoints: Array of waypoint objects. Each waypoints is an input coordinate snapped to the road and path network. The waypoints appear in the array in the order of the input coordinates.
  • trips: Array of trip objects. This will at least contain one trip. If not all waypoints may be reached in one trip (for example because they are on different non-connected islands), several trips will be returned, each connecting the respectively reachable waypoints.

Waypoint object

An input coordinate snapped to the roads network.

  • name: String with the name of the way the coordinate snapped to
  • location: Array of [ longitude, latitude ] for the snapped coordinate
  • trips_index: Index to the trip object in the trips array that contains this waypoint
  • waypoint_index: Index of position of the waypoint within the trip

Trip object

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

Example response

{
    "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"
        }
    ]
}

Optimized trip errors

On error, the server responds with different HTTP status codes. For responses with HTTP status codes lower than 500, the JSON response body includes the code property, which may be used by client programs to manage control flow. The response body may also include a message property, with a human-readable explanation of the error. If a server error occurs, the HTTP status code will be 500 or higher and the response will not include a code property.

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

Analytics

This API is available for premium and enterprise plans.

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

Retrieve analytics

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

  • If the {resourceType} is tokens, the {id} is the complete token.
  • If the {resourceType} is styles, the {id} is the Style ID. Not to be confused with the Style URL, the id is the alphanumeric segment at the end of the style: the Style URL mapbox://styles/user/cimdoca6f00 contains the Style ID cimdoca6f00, so the analytics request would have the path /analytics/v1/styles/user/cimdoca6f00.
  • If the {resourceType} is tilesets, the {id} is a Map ID.
URL Parameter Description
resourceType The resource being requested. Valid resource types are accounts , tokens , tilesets or styles .
username The username for the account that owns the resource.
id
(optional)
The id for the resource. In the case of accounts this isn't required.
period
(optional)
2 comma separated dates as ISO formatted strings . The first date must be earlier than the second. The period is inclusive of dates provided. Defaults to last 90 days if not provided. The maximum period is 1 year. If the provided dates are more than 1 year apart, an error will be returned.

Responses include arrays of request counts per service.

Property Description
timestamps an array of dates as ISO formatted strings for each day included in the response.
period a 2 element array with start and end dates as ISO formatted strings for the response period.
services an object with a key per service the value of which is an array of request counts per day in the same sequence as timestamps .

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

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 & Tile services refer to the Static API. For tilesets, Static & Tile services refer to the Static (Classic) and Maps → Tiles APIs.

GET
/analytics/v1/{resourceType}/{username}/{id}?period={period}
analytics:read Token scope

Example Request

curl "https://api.mapbox.com/analytics/v1/tilesets/mapbox/mapbox.streets?period=2016-03-22T00:00:00.000Z,2016-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