- Styles
- Static
- Uploads
- Datasets
- Tilequery
- Tilesets
- Geocoding
- Directions
- MapMatching
- Matrix
- Optimization
- Tokens
- Data structures
- Isochrone
- GeocodingV6
- Distribution
Styles API service.
Learn more about this service and its responses in the HTTP service documentation.
Get a style.
See the corresponding HTTP service documentation.
-
configObjectconfig.styleIdstringconfig.ownerIdstring?config.metadataboolean If true,mapbox:specific metadata will be preserved (optional, defaultfalse)config.draftboolean Iftruewill retrieve the draft style, otherwise will retrieve the published style. (optional, defaultfalse)config.freshboolean Iftrue, will bypass the cached version of the style. Fresh style requests have a lower rate limit than cached requests and may have a higher latency.fresh=trueshould never be used in production or high concurrency environments. (optional, defaultfalse)
stylesClient.getStyle({
styleId: 'style-id'
})
.send()
.then(response => {
const style = response.body;
});Returns MapiRequest
Create a style.
See the corresponding HTTP service documentation.
stylesClient.createStyle({
style: {
version: 8,
name: "My Awesome Style",
metadata: {},
sources: {},
layers: [],
glyphs: "mapbox://fonts/{owner}/{fontstack}/{range}.pbf"
}
})
.send()
.then(response => {
const style = response.body;
});Returns MapiRequest
Update a style.
See the corresponding HTTP service documentation.
-
configObject
stylesClient.updateStyle({
styleId: 'style-id',
style: {
version: 8,
name: 'My Awesome Style',
metadata: {},
sources: {},
layers: [],
glyphs: 'mapbox://fonts/{owner}/{fontstack}/{range}.pbf'
}
})
.send()
.then(response => {
const style = response.body;
});Returns MapiRequest
Delete a style.
stylesClient.deleteStyle({
styleId: 'style-id'
})
.send()
.then(response => {
// delete successful
});Returns MapiRequest
List styles in your account.
-
configObject?config.startstring? The style ID to start at, for paginated results.config.ownerIdstring?config.freshboolean Iftrue, will bypass the cached resource. Fresh requests have a lower rate limit than cached requests and may have a higher latency.fresh=trueshould never be used in high concurrency environments. (optional, defaultfalse)
stylesClient.listStyles()
.send()
.then(response => {
const styles = response.body;
});Returns MapiRequest
Add an icon to a style, or update an existing one.
-
configObjectconfig.styleIdstringconfig.iconIdstringconfig.fileUploadableFile An SVG file.config.ownerIdstring?
stylesClient.putStyleIcon({
styleId: 'foo',
iconId: 'bar',
// The string filename value works in Node.
// In the browser, provide a Blob.
file: 'path/to/file.svg'
})
.send()
.then(response => {
const newSprite = response.body;
});Returns MapiRequest
Remove an icon from a style.
-
configObject
stylesClient.deleteStyleIcon({
styleId: 'foo',
iconId: 'bar'
})
.send()
.then(response => {
// delete successful
});Returns MapiRequest
Get a style sprite's image or JSON document.
See the corresponding HTTP service documentation.
-
configObjectconfig.styleIdstringconfig.format("json"|"png") (optional, default"json")config.highResboolean? If true, returns spritesheet with 2x resolution.config.ownerIdstring?config.draftboolean Iftruewill retrieve the draft style sprite, otherwise will retrieve the published style sprite. (optional, defaultfalse)config.freshboolean Iftrue, will bypass the cached resource. Fresh requests have a lower rate limit than cached requests and may have a higher latency.fresh=trueshould never be used in high concurrency environments. (optional, defaultfalse)
stylesClient.getStyleSprite({
format: 'json',
styleId: 'foo',
highRes: true
})
.send()
.then(response => {
const sprite = response.body;
});stylesClient.getStyleSprite({
format: 'png',
styleId: 'foo',
highRes: true
})
.send()
.then(response => {
const sprite = response.body;
fs.writeFileSync('sprite.png', sprite, 'binary');
});Returns MapiRequest
Get a font glyph range.
See the corresponding HTTP service documentation.
-
configObject
stylesClient.getFontGlyphRange({
fonts: 'Arial Unicode',
start: 0,
end: 255
})
.send()
.then(response => {
const glyph = response.body;
});Returns MapiRequest
Get embeddable HTML displaying a map.
See the corresponding HTTP service documentation.
-
configObjectconfig.styleIdstringconfig.scrollZoomboolean Iffalse, zooming the map by scrolling will be disabled. (optional, defaulttrue)config.titleboolean Iftrue, the map's title and owner is displayed in the upper right corner of the map. (optional, defaultfalse)config.fallbackboolean Iftrue, serve a fallback raster map. (optional, defaultfalse)config.mapboxGLVersionstring? Specify a version of Mapbox GL JS to use to render the map.config.mapboxGLGeocoderVersionstring? Specify a version of the Mapbox GL geocoder plugin to use to render the map search box.config.ownerIdstring?config.draftboolean Iftruewill retrieve the draft style, otherwise will retrieve the published style. (optional, defaultfalse)
Static Images API service.
Learn more about this service and its responses in the HTTP service documentation.
Get a static map image.
If you just want the URL for the static map image, create a request
and get it's URL with MapiRequest#url. This is what prior versions of the
SDK returned.
-
configObjectconfig.ownerIdstring The owner of the map style.config.styleIdstring The map's style ID.config.widthnumber Width of the image in pixels, between 1 and 1280.config.heightnumber Height of the image in pixels, between 1 and 1280.config.position("auto"| Object) If"auto", the viewport will fit the bounds of the overlay(s). If an object, it could be either a bbox or a coordinate and a zoom as the required parameters.
bbox(required): Is an array of coordinate pairs, with the first coordinate pair referring to the southwestern corner of the box (the minimum longitude and latitude) and the second referring to the northeastern corner of the box (the maximum longitude and latitude). Otherwise the maps' position is described by an object with the following properties:coordinates(required):coordinatesfor the center of image.zoom(required): Between 0 and 20.bearing(optional): Between 0 and 360.pitch(optional): Between 0 and 60.config.paddingstring A string value that denotes the minimum padding per side of the image. This can only be used with auto or bbox. The value resembles the CSS specification for padding and accepts 1-4 integers without unitsconfig.overlaysArray<Overlay>? Overlays should be in z-index order: the first in the array will be on the bottom; the last will be on the top. Overlays are objects that match one of the following types:SimpleMarkerOverlay,CustomMarkerOverlay,PathOverlay,GeoJsonOverlayconfig.highResboolean (optional, defaultfalse)config.before_layerstring? The ID of the style layer that overlays should be inserted before.config.addlayerObject? Adds a Mapbox style layer to the map's style at render time. Can be combined with before_layer.config.setfilterArray? Applies a filter to an existing layer in a style using Mapbox's expression syntax. Must be used with layer_id.config.layer_idstring? Denotes the layer in the style that the filter specified in setfilter is applied to.config.attributionboolean Whether there is attribution on the map image. (optional, defaulttrue)config.logoboolean Whether there is a Mapbox logo on the map image. (optional, defaulttrue)
staticClient.getStaticImage({
ownerId: 'mapbox',
styleId: 'streets-v11',
width: 200,
height: 300,
position: {
coordinates: [12, 13],
zoom: 4
}
})
.send()
.then(response => {
const image = response.body;
});staticClient.getStaticImage({
ownerId: 'mapbox',
styleId: 'streets-v11',
width: 200,
height: 300,
position: {
// position as a bounding box
bbox: [-77.04,38.8,-77.02,38.91],
},
padding: '4'
})
.send()
.then(response => {
const image = response.body;
});staticClient.getStaticImage({
ownerId: 'mapbox',
styleId: 'streets-v11',
width: 200,
height: 300,
position: {
coordinates: [12, 13],
zoom: 3
},
overlays: [
// Simple markers.
{
marker: {
coordinates: [12.2, 12.8]
}
},
{
marker: {
size: 'large',
coordinates: [14, 13.2],
label: 'm',
color: '#000'
}
},
{
marker: {
coordinates: [15, 15.2],
label: 'airport',
color: '#ff0000'
}
},
// Custom marker
{
marker: {
coordinates: [10, 11],
url: 'https://upload.wikimedia.org/wikipedia/commons/6/6f/0xff_timetracker.png'
}
}
]
})
.send()
.then(response => {
const image = response.body;
});// To get the URL instead of the image, create a request
// and get its URL without sending it.
const request = staticClient
.getStaticImage({
ownerId: 'mapbox',
styleId: 'streets-v11',
width: 200,
height: 300,
position: {
coordinates: [12, 13],
zoom: 4
}
});
const staticImageUrl = request.url();
// Now you can open staticImageUrl in a browser.// Filter all buildings that have a height value that is less than 300 meters
const request = staticClient
.getStaticImage({
ownerId: 'mapbox',
styleId: 'streets-v11',
width: 200,
height: 300,
position: {
coordinates: [12, 13],
zoom: 4
},
setfilter: [">","height",300],
layer_id: 'building',
});
const staticImageUrl = request.url();
// Now you can open staticImageUrl in a browser.// Paint all the state and province level boundaries associated with the US worldview with a dashed line and insert it below the road-label layer
const request = staticClient
.getStaticImage({
ownerId: 'mapbox',
styleId: 'streets-v11',
width: 200,
height: 300,
position: {
coordinates: [12, 13],
zoom: 4
},
addlayer: {"id":"better-boundary","type":"line","source":"composite","source-layer":"admin","filter":["all",["==",["get","admin_level"],1],["==",["get","maritime"],"false"],["match",["get","worldview"],["all","US"],true,false]],"layout":{"line-join":"bevel"},"paint":{"line-color":"%236898B3","line-width":1.5,"line-dasharray":[1.5,1]}},
before_layer: 'road-label',
});
const staticImageUrl = request.url();
// Now you can open staticImageUrl in a browser.Returns MapiRequest
Uploads API service.
Learn more about this service and its responses in the HTTP service documentation.
List the statuses of all recent uploads.
See the corresponding HTTP service documentation.
-
configObject?config.reverseboolean? List uploads in chronological order, rather than reverse chronological order.
uploadsClient.listUploads()
.send()
.then(response => {
const uploads = response.body;
});Returns MapiRequest
Create S3 credentials.
See the corresponding HTTP service documentation.
const AWS = require('aws-sdk');
const getCredentials = () => {
return uploadsClient
.createUploadCredentials()
.send()
.then(response => response.body);
}
const putFileOnS3 = (credentials) => {
const s3 = new AWS.S3({
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
sessionToken: credentials.sessionToken,
region: 'us-east-1'
});
return s3.putObject({
Bucket: credentials.bucket,
Key: credentials.key,
Body: fs.createReadStream('/path/to/file.mbtiles')
}).promise();
};
getCredentials().then(putFileOnS3);Returns MapiRequest
Create an upload.
See the corresponding HTTP service documentation.
-
configObjectconfig.tilesetstring The tileset ID to create or replace, in the formatusername.nameoftileset. Limited to 32 characters (only-and_special characters allowed; limit does not include username).config.urlstring HTTPS URL of the S3 object provided bycreateUploadCredentialsconfig.namestring? The name of the tileset. Limited to 64 characters.
// Response from a call to createUploadCredentials
const credentials = {
accessKeyId: '{accessKeyId}',
bucket: '{bucket}',
key: '{key}',
secretAccessKey: '{secretAccessKey}',
sessionToken: '{sessionToken}',
url: '{s3 url}'
};
uploadsClient.createUpload({
tileset: `${myUsername}.${myTileset}`,
url: credentials.url,
name: 'my uploads name',
})
.send()
.then(response => {
const upload = response.body;
});Returns MapiRequest
Get an upload's status.
See the corresponding HTTP service documentation.
uploadsClient.getUpload({
uploadId: '{upload_id}'
})
.send()
.then(response => {
const status = response.body;
});Returns MapiRequest
Delete an upload.
See the corresponding HTTP service documentation.
uploadsClient.deleteUpload({
uploadId: '{upload_id}'
})
.send()
.then(response => {
// Upload successfully deleted.
});Returns MapiRequest
Datasets API service.
Learn more about this service and its responses in the HTTP service documentation.
List datasets in your account.
See the corresponding HTTP service documentation.
-
configObject?config.sortbystring Sort by eithermodifiedorcreated(default) dates. (optional, defaultcreated)
datasetsClient.listDatasets()
.send()
.then(response => {
const datasets = response.body;
});datasetsClient.listDatasets()
.eachPage((error, response, next) => {
// Handle error or response and call next.
});Returns MapiRequest
Create a new, empty dataset.
See the corresponding HTTP service documentation.
datasetsClient.createDataset({
name: 'example',
description: 'An example dataset'
})
.send()
.then(response => {
const datasetMetadata = response.body;
});Returns MapiRequest
Get metadata about a dataset.
See the corresponding HTTP service documentation.
datasetsClient.getMetadata({
datasetId: 'dataset-id'
})
.send()
.then(response => {
const datasetMetadata = response.body;
})Returns MapiRequest
Update user-defined properties of a dataset's metadata.
See the corresponding HTTP service documentation.
datasetsClient.updateMetadata({
datasetId: 'dataset-id',
name: 'foo'
})
.send()
.then(response => {
const datasetMetadata = response.body;
});Returns MapiRequest
Delete a dataset, including all features it contains.
See the corresponding HTTP service documentation.
datasetsClient.deleteDataset({
datasetId: 'dataset-id'
})
.send()
.then(response => {
// Dataset is successfully deleted.
});Returns MapiRequest
List features in a dataset.
This endpoint supports pagination. Use MapiRequest#eachPage or manually specify
the limit and start options.
See the corresponding HTTP service documentation.
-
configObject
datasetsClient.listFeatures({
datasetId: 'dataset-id'
})
.send()
.then(response => {
const features = response.body;
});Returns MapiRequest
Add a feature to a dataset or update an existing one.
See the corresponding HTTP service documentation.
-
configObject
datasetsClient.putFeature({
datasetId: 'dataset-id',
featureId: 'null-island',
feature: {
"type": "Feature",
"properties": { "name": "Null Island" },
"geometry": {
"type": "Point",
"coordinates": [0, 0]
}
}
})
.send()
.then(response => {
const feature = response.body;
});Returns MapiRequest
Get a feature in a dataset.
See the corresponding HTTP service documentation.
datasetsClient.getFeature({
datasetId: 'dataset-id',
featureId: 'feature-id'
})
.send()
.then(response => {
const feature = response.body;
});Returns MapiRequest
Delete a feature in a dataset.
See the corresponding HTTP service documentation.
datasetsClient.deleteFeature({
datasetId: 'dataset-id',
featureId: 'feature-id'
})
.send()
.then(response => {
// Feature is successfully deleted.
});Returns MapiRequest
Tilequery API service.
Learn more about this service and its responses in the HTTP service documentation.
List features within a radius of a point on a map (or several maps).
-
configObjectconfig.mapIdsArray<string> The maps being queried. If you need to composite multiple layers, provide multiple map IDs.config.coordinatesCoordinates The longitude and latitude to be queried.config.radiusnumber The approximate distance in meters to query for features. (optional, default0)config.limitnumber The number of features to return, between 1 and 50. (optional, default5)config.dedupeboolean Whether or not to deduplicate results. (optional, defaulttrue)config.geometry("polygon"|"linestring"|"point")? Queries for a specific geometry type.config.layersArray<string>? IDs of vector layers to query.
tilequeryClient.listFeatures({
mapIds: ['mapbox.mapbox-streets-v8'],
coordinates: [-122.42901, 37.80633],
radius: 10
})
.send()
.then(response => {
const features = response.body;
});Returns MapiRequest
Tilesets API service.
Learn more about this service and its responses in the HTTP service documentation.
List a user's tilesets.
-
configObject?config.ownerIdstring?config.type("raster"|"vector")? Filter results by tileset type, eitherrasterorvector.config.limitnumber The maximum number of tilesets to return, from 1 to 500. (optional, default100)config.sortBy("created"|"modified")? Sort the listings by theircreatedormodifiedtimestamps.config.startstring? The tileset after which to start the listing.config.visibility("public"|"private")? Filter results by visibility, eitherpublicorprivate
tilesetsClient.listTilesets()
.send()
.then(response => {
const tilesets = response.body;
});tilesetsClient.listTilesets()
.eachPage((error, response, next) => {
// Handle error or response and call next.
});Returns MapiRequest
Delete a tileset
-
configObjectconfig.tilesetIdstring ID of the tileset to be deleted in the formusername.tileset_id.
tilesetsClient.deleteTileset({
tilesetId: 'username.tileset_id'
})
.send()
.then(response => {
const deleted = response.statusCode === 204;
});Returns MapiRequest
Retrieve metadata about a tileset.
-
configObject?config.tilesetIdstring? Unique identifier for the tileset in the formatusername.id.
Returns MapiRequest
Create a tileset source
-
configObjectconfig.idstring ID of the tileset source to be created.config.fileUploadableFile Line-delimeted GeoJSON file.config.ownerIdstring?
tilesetsClient.createTilesetSource({
id: 'tileset_source_id',
// The string filename value works in Node.
// In the browser, provide a Blob.
file: 'path/to/file.geojson.ld'
})
.send()
.then(response => {
const tilesetSource = response.body;
});Returns MapiRequest
Retrieve a tileset source information
tilesetsClient.getTilesetSource({
id: 'tileset_source_id'
})
.send()
.then(response => {
const tilesetSource = response.body;
});Returns MapiRequest
List tileset sources
-
configObject?
tilesetsClient.listTilesetSources()
.send()
.then(response => {
const tilesetSources = response.body;
});Returns MapiRequest
Delete a tileset source
tilesetsClient.deleteTilesetSource({
id: 'tileset_source_id'
})
.send()
.then(response => {
const deleted = response.statusCode === 201;
});Returns MapiRequest
Create a tileset
-
configObjectconfig.tilesetIdstring ID of the tileset to be created in the formusername.tileset_name.config.recipeObject The tileset recipe to use in JSON format.config.namestring Name of the tileset.config.privateboolean A private tileset must be used with an access token from your account. (optional, defaulttrue)config.descriptionstring? Description of the tileset.
tilesetsClient.createTileset({
tilesetId: 'username.tileset_id',
recipe: {
version: 1,
layers: {
my_new_layer: {
source: "mapbox://tileset-source/{username}/{id}",
minzoom: 0,
maxzoom: 8
}
}
},
name: 'My Tileset'
})
.send()
.then(response => {
const message = response.body.message;
});Returns MapiRequest
Publish a tileset
-
configObjectconfig.tilesetIdstring ID of the tileset to publish in the formusername.tileset_name.
tilesetsClient.publishTileset({
tilesetId: 'username.tileset_id'
})
.send()
.then(response => {
const tilesetPublishJob = response.body;
});Returns MapiRequest
Update a tileset
tilesetsClient.updateTileset({
tilesetId: 'username.tileset_name',
name: 'Tileset Name',
private: true,
attribution: [
{
text: 'Source Name',
link: 'https://example.com'
}
]
})
.send()
.then(response => {
const updated = response.statusCode === 204;
});Returns MapiRequest
Retrieve the status of a tileset
tilesetsClient.tilesetStatus({
tilesetId: 'username.tileset_name'
})
.send()
.then(response => {
const tilesetStatus = response.body;
});Returns MapiRequest
Retrieve information about a single tileset job
-
configObject
tilesetsClient.tilesetJob({
tilesetId: 'username.tileset_name'
jobId: 'job_id'
})
.send()
.then(response => {
const tilesetJob = response.body;
});Returns MapiRequest
List information about all jobs for a tileset
-
configObjectconfig.tilesetIdstring ID of the tileset in the formusername.tileset_name.config.stage("processing"|"queued"|"success"|"failed")?config.limitnumber The maximum number of tilesets to return, from 1 to 500. (optional, default100)config.startstring? The tileset after which to start the listing.
tilesetsClient.listTilesetJobs({
tilesetId: 'username.tileset_name'
})
.send()
.then(response => {
const jobs = response.body;
});Returns MapiRequest
View Tilesets API global queue
tilesetsClient.getTilesetsQueue()
.send()
.then(response => {
const queue = response.body;
});Returns MapiRequest
Validate a recipe
-
configObjectconfig.recipeObject The tileset recipe to validate in JSON format.
tilesetsClient.validateRecipe({
recipe: {
version: 1,
layers: {
my_new_layer: {
source: "mapbox://tileset-source/{username}/{id}",
minzoom: 0,
maxzoom: 8
}
}
}
})
.send()
.then(response => {
const validation = response.body;
});Returns MapiRequest
Retrieve a recipe
tilesetsClient.getRecipe({
tilesetId: 'username.tileset_name'
})
.send()
.then(response => {
const recipe = response.body;
});Returns MapiRequest
Update a tileset recipe
-
configObjectconfig.tilesetIdstring ID of the tileset in the formusername.tileset_name.config.recipeObject The tileset recipe in JSON format.
tilesetsClient.updateRecipe({
tilesetId: 'username.tileset_name',
recipe: {
version: 1,
layers: {
my_new_layer: {
source: "mapbox://tileset-source/{username}/{id}",
minzoom: 0,
maxzoom: 8
}
}
}
})
.send()
.then(response => {
const updated = response.statusCode === 204;
});Returns MapiRequest
Geocoding API service.
Learn more about this service and its responses in the HTTP service documentation.
Search for a place.
See the public documentation.
-
configObjectconfig.querystring A place name.config.mode("mapbox.places"|"mapbox.places-permanent") Eithermapbox.placesfor ephemeral geocoding, ormapbox.places-permanentfor storing results and batch geocoding. (optional, default"mapbox.places")config.countriesArray<string>? Limits results to the specified countries. Each item in the array should be an ISO 3166 alpha 2 country code.config.proximity(Coordinates |"ip")? Bias local results based on a provided coordinate location or a user's IP address.config.typesArray<("country"|"region"|"postcode"|"district"|"place"|"locality"|"neighborhood"|"address"|"poi"|"poi.landmark")>? Filter results by feature types.config.autocompleteboolean Return autocomplete results or not. (optional, defaulttrue)config.bboxBoundingBox? Limit results to a bounding box.config.limitnumber Limit the number of results returned. (optional, default5)config.languageArray<string>? Specify the language to use for response text and, for forward geocoding, query result weighting. Options are IETF language tags comprised of a mandatory ISO 639-1 language code and optionally one or more IETF subtags for country or script.config.routingboolean Specify whether to request additional metadata about the recommended navigation destination. Only applicable for address features. (optional, defaultfalse)config.fuzzyMatchboolean Specify whether the Geocoding API should attempt approximate, as well as exact, matching. (optional, defaulttrue)config.worldviewString Filter results to geographic features whose characteristics are defined differently by audiences belonging to various regional, cultural, or political groups. (optional, default"us")config.session_tokenString? A unique session identifier generated by the client.
geocodingClient.forwardGeocode({
query: 'Paris, France',
limit: 2
})
.send()
.then(response => {
const match = response.body;
});// geocoding with proximity
geocodingClient.forwardGeocode({
query: 'Paris, France',
proximity: [-95.4431142, 33.6875431]
})
.send()
.then(response => {
const match = response.body;
});
// geocoding with countries
geocodingClient.forwardGeocode({
query: 'Paris, France',
countries: ['fr']
})
.send()
.then(response => {
const match = response.body;
});
// geocoding with bounding box
geocodingClient.forwardGeocode({
query: 'Paris, France',
bbox: [2.14, 48.72, 2.55, 48.96]
})
.send()
.then(response => {
const match = response.body;
});Returns MapiRequest
Search for places near coordinates.
See the public documentation.
-
configObjectconfig.queryCoordinates Coordinates at which features will be searched.config.mode("mapbox.places"|"mapbox.places-permanent") Eithermapbox.placesfor ephemeral geocoding, ormapbox.places-permanentfor storing results and batch geocoding. (optional, default"mapbox.places")config.countriesArray<string>? Limits results to the specified countries. Each item in the array should be an ISO 3166 alpha 2 country code.config.typesArray<("country"|"region"|"postcode"|"district"|"place"|"locality"|"neighborhood"|"address"|"poi"|"poi.landmark")>? Filter results by feature types.config.bboxBoundingBox? Limit results to a bounding box.config.limitnumber Limit the number of results returned. If using this option, you must provide a single item fortypes. (optional, default1)config.languageArray<string>? Specify the language to use for response text and, for forward geocoding, query result weighting. Options are IETF language tags comprised of a mandatory ISO 639-1 language code and optionally one or more IETF subtags for country or script.config.reverseMode("distance"|"score") Set the factors that are used to sort nearby results. (optional, default'distance')config.routingboolean Specify whether to request additional metadata about the recommended navigation destination. Only applicable for address features. (optional, defaultfalse)config.worldviewString Filter results to geographic features whose characteristics are defined differently by audiences belonging to various regional, cultural, or political groups. (optional, default"us")config.session_tokenString? A unique session identifier generated by the client.
geocodingClient.reverseGeocode({
query: [-95.4431142, 33.6875431]
})
.send()
.then(response => {
// GeoJSON document with geocoding matches
const match = response.body;
});Returns MapiRequest
Directions API service.
Learn more about this service and its responses in the HTTP service documentation.
Get directions.
Please read the full HTTP service documentation to understand all of the available options.
-
configObjectconfig.profile("driving-traffic"|"driving"|"walking"|"cycling") (optional, default"driving")config.waypointsArray<DirectionsWaypoint> An ordered array ofDirectionsWaypointobjects, between 2 and 25 (inclusive).config.alternativesboolean Whether to try to return alternative routes. (optional, defaultfalse)config.annotationsArray<("duration"|"distance"|"speed"|"congestion")>? Specify additional metadata that should be returned.config.bannerInstructionsboolean Should be used in conjunction withsteps. (optional, defaultfalse)config.continueStraightboolean? Sets the allowed direction of travel when departing intermediate waypoints.config.excludestring? Exclude certain road types from routing. See HTTP service documentation for options.config.geometries("geojson"|"polyline"|"polyline6") Format of the returned geometry. (optional, default"polyline")config.languagestring Language of returned turn-by-turn text instructions. See options listed in the HTTP service documentation. (optional, default"en")config.overview("simplified"|"full"|"false") Type of returned overview geometry. (optional, default"simplified")config.roundaboutExitsboolean Emit instructions at roundabout exits. (optional, defaultfalse)config.stepsboolean Whether to return steps and turn-by-turn instructions. (optional, defaultfalse)config.voiceInstructionsboolean Whether or not to return SSML marked-up text for voice guidance along the route. (optional, defaultfalse)config.voiceUnits("imperial"|"metric") Which type of units to return in the text for voice instructions. (optional, default"imperial")config.engine("electric_no_recharge"|"electric") Set to electric to enable electric vehicle routing. (optional, default"electric_no_recharge")config.ev_initial_chargenumber? Optional parameter to specify initial charge of vehicle in Wh (watt-hours) at the beginning of the route.config.ev_max_chargenumber? Required parameter that defines the maximum possible charge of vehicle in Wh (watt-hours).config.ev_connector_types("ccs_combo_type1"|"ccs_combo_type1"|"tesla")? Required parameter that defines the compatible connector-types for the vehicle.config.energy_consumption_curveString? Required parameter that specifies in pairs the energy consumption in watt-hours per kilometer at a certain speed in kph.config.ev_charging_curveString? Required parameter that specifies the maximum battery charging rate (W) at a given charge level (Wh) in a list of pairs.config.ev_unconditioned_charging_curveString? Optional parameter that specifies the maximum battery charging rate (W) at a given charge level (Wh) in a list of pairs when the battery is in an unconditioned state (eg: cold).config.ev_pre_conditioning_timenumber? Optional parameter that defines the time in minutes it would take for the vehicle's battery to condition.config.ev_max_ac_charging_powernumber? Optional parameter to specify maximum AC charging power(W) that can be delivered by the onboard vehicle charger.config.ev_min_charge_at_destinationnumber? Optional parameter to define the minimum battery charge required at the final route destination (Wh).config.ev_min_charge_at_charging_stationnumber? Optional parameter to define the minimum charge when arriving at the charging station (Wh).config.auxiliary_consumptionnumber? Optional parameter to define the measure of the continuous power draw of the auxiliary systems in watts (E.G heating or AC).config.maxHeightnumber Optional parameter to define the max vehicle height in meters. (optional, default1.6)config.maxWidthnumber Optional parameter to define the max vehicle width in meters. (optional, default1.9)config.maxWeightnumber Optional parameter to define the max vehicle weight in metric tons. (optional, default2.5)config.notificationsString Returns notification metadata associated with the route leg of the route object. (optional, default"all")config.departAtString? Optional parameter to define the departure time, formatted as a timestamp in ISO-8601 format in the local time at the route origin.config.arriveByString? Optional parameter to define the desired arrival time, formatted as a timestamp in ISO-8601 format in the local time at the route destination.
directionsClient.getDirections({
profile: 'driving-traffic',
waypoints: [
{
coordinates: [13.4301, 52.5109],
approach: 'unrestricted'
},
{
coordinates: [13.4265, 52.508]
},
{
coordinates: [13.4194, 52.5072],
bearing: [100, 60]
}
]
})
.send()
.then(response => {
const directions = response.body;
});Returns MapiRequest
Map Matching API service.
Learn more about this service and its responses in the HTTP service documentation.
Snap recorded location traces to roads and paths.
-
configObjectconfig.pointsArray<MapMatchingPoint> An ordered array ofMapMatchingPoints, between 2 and 100 (inclusive).config.profile("driving-traffic"|"driving"|"walking"|"cycling") A directions profile ID. (optional, defaultdriving)config.annotationsArray<("duration"|"distance"|"speed")>? Specify additional metadata that should be returned.config.geometries("geojson"|"polyline"|"polyline6") Format of the returned geometry. (optional, default"polyline")config.languagestring Language of returned turn-by-turn text instructions. See supported languages. (optional, default"en")config.overview("simplified"|"full"|"false") Type of returned overview geometry. (optional, default"simplified")config.stepsboolean Whether to return steps and turn-by-turn instructions. (optional, defaultfalse)config.tidyboolean Whether or not to transparently remove clusters and re-sample traces for improved map matching results. (optional, defaultfalse)
mapMatchingClient.getMatch({
points: [
{
coordinates: [-117.17283, 32.712041],
approach: 'curb'
},
{
coordinates: [-117.17291, 32.712256],
isWaypoint: false
},
{
coordinates: [-117.17292, 32.712444]
},
{
coordinates: [-117.172922, 32.71257],
waypointName: 'point-a',
approach: 'unrestricted'
},
{
coordinates: [-117.172985, 32.7126]
},
{
coordinates: [-117.173143, 32.712597]
},
{
coordinates: [-117.173345, 32.712546]
}
],
tidy: false,
})
.send()
.then(response => {
const matching = response.body;
})Returns MapiRequest
Map Matching API service.
Learn more about this service and its responses in the HTTP service documentation.
Get a duration and/or distance matrix showing travel times and distances between coordinates.
-
configObjectconfig.pointsArray<MatrixPoint> An ordered array ofMatrixPoints, between 2 and 100 (inclusive).config.profile("driving-traffic"|"driving"|"walking"|"cycling") A Mapbox Directions routing profile ID. (optional, defaultdriving)config.sources("all"| Array<number>)? Use coordinates with given index as sources.config.destinations("all"| Array<number>)? Use coordinates with given index as destinations.config.annotationsArray<("distance"|"duration")>? Used to specify resulting matrices.
matrixClient.getMatrix({
points: [
{
coordinates: [2.2, 1.1]
},
{
coordinates: [2.2, 1.1],
approach: 'curb'
},
{
coordinates: [3.2, 1.1]
},
{
coordinates: [4.2, 1.1]
}
],
profile: 'walking'
})
.send()
.then(response => {
const matrix = response.body;
});Returns MapiRequest
Optimization API service.
Learn more about this service and its responses in the HTTP service documentation.
Get a duration-optimized route.
Please read the full HTTP service documentation to understand all of the available options.
-
configObjectconfig.profile("driving"|"driving-traffic"|"walking"|"cycling") (optional, default"driving")config.waypointsArray<OptimizationWaypoint> An ordered array ofOptimizationWaypointobjects, with at least 2config.annotationsArray<("duration"|"distance"|"speed")>? Specify additional metadata that should be returned.config.destination("any"|"last") Returned route ends atanyorlastcoordinate. (optional, default"any")config.distributionsArray<Distribution>? An ordered array ofDistributionobjects, each of which includes apickupanddropoffproperty.pickupanddropoffproperties correspond to an index in the OptimizationWaypoint array.config.geometries("geojson"|"polyline"|"polyline6") Format of the returned geometries. (optional, default"polyline")config.languagestring Language of returned turn-by-turn text instructions. See options listed in the HTTP service documentation. (optional, default"en")config.overview("simplified"|"full"|"false") Type of returned overview geometry. (optional, default"simplified")config.roundtripboolean Specifies whether the trip should complete by returning to the first location. (optional, defaulttrue)config.source("any"|"first") To begin the route, start either from the first coordinate or let the Optimization API choose. (optional, default"any")config.stepsboolean Whether to return steps and turn-by-turn instructions. (optional, defaultfalse)
Returns MapiRequest
Tokens API service.
Learn more about this service and its responses in the HTTP service documentation.
List your access tokens.
See the corresponding HTTP service documentation.
tokensClient.listTokens()
.send()
.then(response => {
const tokens = response.body;
});Returns MapiRequest
Create a new access token.
See the corresponding HTTP service documentation.
-
configObject?config.notestring?config.scopesArray<string>?config.resourcesArray<string>?config.allowedUrlsArray<string>?config.allowedApplicationsArray<{platform: string, bundleId: string}>? This option restricts tokens with an Application Bundle ID. The feature is in beta and is only available to our selected customers. For more information, please contact sales.
tokensClient.createToken({
note: 'datasets-token',
scopes: ['datasets:write', 'datasets:read']
})
.send()
.then(response => {
const token = response.body;
});Returns MapiRequest
Create a new temporary access token.
See the corresponding HTTP service documentation.
tokensClient.createTemporaryToken({
scopes: ['datasets:write', 'datasets:read']
})
.send()
.then(response => {
const token = response.body;
});Returns MapiRequest
Update an access token.
See the corresponding HTTP service documentation.
-
configObjectconfig.tokenIdstringconfig.notestring?config.scopesArray<string>?config.resourcesArray<string>?config.allowedUrls(Array<string> | null)?config.allowedApplications(Array<{platform: string, bundleId: string}> | null)? This option restricts tokens with an Application Bundle ID. The feature is in beta and is only available to our selected customers. For more information, please contact sales.
tokensClient.updateToken({
tokenId: 'cijucimbe000brbkt48d0dhcx',
note: 'datasets-token',
scopes: ['datasets:write', 'datasets:read']
})
.send()
.then(response => {
const token = response.body;
});Returns MapiRequest
Get data about the client's access token.
See the corresponding HTTP service documentation.
tokensClient.getToken()
.send()
.then(response => {
const token = response.body;
});Returns MapiRequest
Delete an access token.
See the corresponding HTTP service documentation.
tokensClient.deleteToken({
tokenId: 'cijucimbe000brbkt48d0dhcx'
})
.send()
.then(response => {
// Token successfully deleted.
});Returns MapiRequest
List your available scopes. Each item is a metadata object about the scope, not just the string scope.
See the corresponding HTTP service documentation.
tokensClient.listScopes()
.send()
.then(response => {
const scopes = response.body;
});Returns MapiRequest
Data structures used in service method configuration.
Type: Object
coordinatesCoordinatesapproach("unrestricted"|"curb")? Used to indicate how requested routes consider from which side of the road to approach the waypoint.bearing[number, number]? 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 aradius. The first value is an angle clockwise from true north between 0 and 360, and the second is the range of degrees the angle can deviate by.radius(number |"unlimited")? Maximum distance in meters that the coordinate is allowed to move when snapped to a nearby road segment.waypointNamestring? Custom name for the waypoint used for the arrival instruction in banners and voice instructions.
Type: Object
coordinatesCoordinatesapproach("unrestricted"|"curb")? Used to indicate how requested routes consider from which side of the road to approach a waypoint.radiusnumber? A number in meters indicating the assumed precision of the used tracking device.isWaypointboolean? Whether this coordinate is waypoint or not. The first and last coordinates will always be waypoints.waypointNamestring? Custom name for the waypoint used for the arrival instruction in banners and voice instructions. Will be ignored unlessisWaypointistrue.timestamp(string | number | Date)? Datetime corresponding to the coordinate.
Type: Object
coordinatesCoordinates[longitude, latitude]approach("unrestricted"|"curb")? Used to indicate how requested routes consider from which side of the road to approach the point.
Type: Object
coordinatesCoordinatesapproach("unrestricted"|"curb")? Used to indicate how requested routes consider from which side of the road to approach the waypoint.bearing[number, number]? 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 aradius. The first value is an angle clockwise from true north between 0 and 360, and the second is the range of degrees the angle can deviate by.radius(number |"unlimited")? Maximum distance in meters that the coordinate is allowed to move when snapped to a nearby road segment.
A simple marker overlay.
Type: Object
-
markerObjectmarker.coordinates[number, number][longitude, latitude]marker.size("large"|"small")?marker.labelstring? Marker symbol. Options are an alphanumeric labelathroughz,0through99, or a valid Maki icon. If a letter is requested, it will be rendered in uppercase only.marker.colorstring? A 3- or 6-digit hexadecimal color code.
A marker overlay with a custom image.
Type: Object
A stylable line.
Type: Object
-
pathObjectpath.coordinatesArray<Coordinates> An array of coordinates describing the path.path.strokeWidthnumber?path.strokeColorstring?path.strokeOpacitynumber? Must be paired with strokeColor.path.fillColorstring? Must be paired with strokeColor.path.fillOpacitynumber? Must be paired with fillColor.
GeoJSON to overlay the map.
Type: Object
geoJsonObject Valid GeoJSON.
In Node, files must be ReadableStreams or paths pointing for the file in the filesystem.
In the browser, files must be Blobs or ArrayBuffers.
Type: (Blob | ArrayBuffer | string | ReadableStream)
[longitude, latitude]
[minLongitude, minLatitude, maxLongitude, maxLatitude]
Isochrone API service.
Learn more about this service and its responses in the HTTP service documentation.
Given a location and a routing profile, retrieve up to four isochrone contours
-
configObjectconfig.profile("driving"|"driving-traffic"|"walking"|"cycling") A Mapbox Directions routing profile ID. (optional, default"driving")config.coordinatesCoordinates A {longitude,latitude} coordinate pair around which to center the isochrone lines.config.minutesArray<number>? The times in minutes to use for each isochrone contour. You can specify up to four contours. Times must be in increasing order. The maximum time that can be specified is 60 minutes. Setting minutes and meters in the same time is an error.config.metersArray<number>? The distances in meters to use for each isochrone contour. You can specify up to four contours. Distances must be in increasing order. The maximum distance that can be specified is 100000 meters. Setting minutes and meters in the same time is an error.config.colorsArray<string>? The colors to use for each isochrone contour, specified as hex values without a leading # (for example, ff0000 for red). If this parameter is used, there must be the same number of colors as there are entries in contours_minutes or contours_meters. If no colors are specified, the Isochrone API will assign a default rainbow color scheme to the output.config.polygonsboolean? Specify whether to return the contours as GeoJSON polygons (true) or linestrings (false, default). When polygons=true, any contour that forms a ring is returned as a polygon.config.denoisenumber? A floating point value from 0.0 to 1.0 that can be used to remove smaller contours. The default is 1.0. A value of 1.0 will only return the largest contour for a given time value. A value of 0.5 drops any contours that are less than half the area of the largest contour in the set of contours for that same time value.config.generalizenumber? A positive floating point value in meters used as the tolerance for Douglas-Peucker generalization. There is no upper bound. If no value is specified in the request, the Isochrone API will choose the most optimized generalization to use for the request. Note that the generalization of contours can lead to self-intersections, as well as intersections of adjacent contours.
Returns MapiRequest
Geocoding API service.
Learn more about this service and its responses in the HTTP service documentation.
Search for a place.
See the public documentation.
-
configObjectconfig.querystring A place name.config.mode("standard"|"structured") Eitherstandardfor common forward geocoding, orstructuredfor increasing the accuracy of results. To use Structured Input, the query parameter must be dropped in favor of a separate parameter for individual feature components. (optional, default"standard")config.countries(Array<string> | string)? Limits results to the specified countries. Each item in the array should be an ISO 3166 alpha 2 country code. [OR] if used with input mode="structured" denotes single country in free form.config.proximity(Coordinates |"ip")? Bias local results based on a provided coordinate location or a user's IP address.config.typesArray<("street"|"country"|"region"|"postcode"|"district"|"place"|"locality"|"neighborhood"|"address"|"secondary_address")>? Filter results by feature types.config.bboxBoundingBox? Limit results to a bounding box.config.limitnumber Limit the number of results returned. (optional, default5)config.format("geojson"|"v5") Specify the desired response format of results (geojson, default) or for backwards compatibility (v5). (optional, default'geojson')config.languageString? Specify the language to use for response text and, for forward geocoding, query result weighting. Options are IETF language tags comprised of a mandatory ISO 639-1 language code and optionally one or more IETF subtags for country or script.config.address_line1String? A string including address_number and street. These values can alternatively be provided as separate parameters. (Stuctured Input specific field)config.address_numberString? The number associated with the house (Stuctured Input specific field)config.streetString? The name of the street in the address (Stuctured Input specific field)config.blockString? In some countries like Japan, the block is a component in the address (Stuctured Input specific field)config.placeString? Typically these are cities, villages, municipalities, etc. (Stuctured Input specific field)config.regionString? Top-level sub-national administrative features, such as states in the United States or provinces in Canada or China. (Stuctured Input specific field)config.neighborhoodString? Colloquial sub-city features often referred to in local parlance (Stuctured Input specific field)config.postcodeString? Postal codes used in country-specific national addressing systems. (Stuctured Input specific field)config.localityString? Official sub-city features (Stuctured Input specific field)config.autocompleteboolean Return autocomplete results or not. (optional, defaulttrue)config.permanentboolean Specify whether you intend to store the results of the query (true) or not (false, default). Temporary results are not allowed to be cached, while Permanent results are allowed to be cached and stored indefinitely. (optional, defaultfalse)config.worldviewString Filter results to geographic features whose characteristics are defined differently by audiences belonging to various regional, cultural, or political groups. (optional, default"us")config.session_tokenString? A unique session identifier generated by the client.
geocodingClient.forwardGeocode({
query: 'Paris, France',
limit: 2
})
.send()
.then(response => {
const match = response.body;
});// geocoding in structured input mode
geocodingClient.forwardGeocode({
mode: 'structured',
address_number: '12',
street: 'Main str.'
})
.send()
.then(response => {
const match = response.body;
});// geocoding with proximity
geocodingClient.forwardGeocode({
query: 'Paris, France',
proximity: [-95.4431142, 33.6875431]
})
.send()
.then(response => {
const match = response.body;
});
// geocoding with countries
geocodingClient.forwardGeocode({
query: 'Paris, France',
countries: ['fr']
})
.send()
.then(response => {
const match = response.body;
});
// geocoding with bounding box
geocodingClient.forwardGeocode({
query: 'Paris, France',
bbox: [2.14, 48.72, 2.55, 48.96]
})
.send()
.then(response => {
const match = response.body;
});Returns MapiRequest
Search for places near coordinates.
See the public documentation.
-
configObjectconfig.longitudenumber longitude coordinate at which features will be searched.config.latitudenumber latitude coordinate at which features will be searched.config.countriesArray<string>? Limits results to the specified countries. Each item in the array should be an ISO 3166 alpha 2 country code.config.typesArray<("street"|"country"|"region"|"postcode"|"district"|"place"|"locality"|"neighborhood"|"address")>? Filter results by feature types.config.bboxBoundingBox? Limit results to a bounding box.config.limitnumber Limit the number of results returned. If using this option, you must provide a single item fortypes. (optional, default1)config.languagestring? Specify the language to use for response text and, for forward geocoding, query result weighting. Options are IETF language tags comprised of a mandatory ISO 639-1 language code and optionally one or more IETF subtags for country or script.config.permanentboolean Specify whether you intend to store the results of the query (true) or not (false, default). Temporary results are not allowed to be cached, while Permanent results are allowed to be cached and stored indefinitely. (optional, defaultfalse)config.worldviewString Filter results to geographic features whose characteristics are defined differently by audiences belonging to various regional, cultural, or political groups. (optional, default"us")config.session_tokenString? A unique session identifier generated by the client.
geocodingClient.reverseGeocode({
longitude: -73.990593,
latitude: 40.740121
})
.send()
.then(response => {
// GeoJSON document with geocoding matches
const match = response.body;
});Returns MapiRequest
Type: Object