Skip to content

Latest commit

 

History

History
2653 lines (1873 loc) · 64.2 KB

services.md

File metadata and controls

2653 lines (1873 loc) · 64.2 KB

Table of Contents

Styles

Styles API service.

Learn more about this service and its responses in the HTTP service documentation.

getStyle

Get a style.

See the corresponding HTTP service documentation.

Parameters

  • config Object
    • config.styleId string
    • config.ownerId string?
    • config.metadata boolean If true, mapbox: specific metadata will be preserved (optional, default false)
    • config.draft boolean If true will retrieve the draft style, otherwise will retrieve the published style. (optional, default false)
    • config.fresh boolean If true, 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=true should never be used in production or high concurrency environments. (optional, default false)

Examples

stylesClient.getStyle({
  styleId: 'style-id'
})
  .send()
  .then(response => {
    const style = response.body;
  });

Returns MapiRequest

createStyle

Create a style.

See the corresponding HTTP service documentation.

Parameters

Examples

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

updateStyle

Update a style.

See the corresponding HTTP service documentation.

Parameters

  • config Object
    • config.styleId string
    • config.style Object Stylesheet JSON object.
    • config.lastKnownModification (string | number | Date)? Datetime of last known update. Passed as 'If-Unmodified-Since' HTTP header.
    • config.ownerId string?

Examples

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

deleteStyle

Delete a style.

Parameters

Examples

stylesClient.deleteStyle({
  styleId: 'style-id'
})
  .send()
  .then(response => {
    // delete successful
  });

Returns MapiRequest

listStyles

List styles in your account.

Parameters

  • config Object?
    • config.start string? The style ID to start at, for paginated results.
    • config.ownerId string?

Examples

stylesClient.listStyles()
  .send()
  .then(response => {
    const styles = response.body;
  });

Returns MapiRequest

putStyleIcon

Add an icon to a style, or update an existing one.

Parameters

Examples

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

deleteStyleIcon

Remove an icon from a style.

Parameters

  • config Object
    • config.styleId string
    • config.iconId string
    • config.ownerId string?
    • config.draft boolean If true will remove the icon from the draft style, otherwise will remove the icon from the published style. (optional, default false)

Examples

stylesClient.deleteStyleIcon({
  styleId: 'foo',
  iconId: 'bar'
})
  .send()
  .then(response => {
    // delete successful
  });

Returns MapiRequest

getStyleSprite

Get a style sprite's image or JSON document.

See the corresponding HTTP service documentation.

Parameters

  • config Object
    • config.styleId string
    • config.format ("json" | "png") (optional, default "json")
    • config.highRes boolean? If true, returns spritesheet with 2x resolution.
    • config.ownerId string?
    • config.draft boolean If true will retrieve the draft style sprite, otherwise will retrieve the published style sprite. (optional, default false)

Examples

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

getFontGlyphRange

Get a font glyph range.

See the corresponding HTTP service documentation.

Parameters

  • config Object
    • config.fonts (string | Array<string>) An array of font names.
    • config.start number Character code of the starting glyph.
    • config.end number Character code of the last glyph, typically equivalent toconfig.start + 255.
    • config.ownerId string?

Examples

stylesClient.getFontGlyphRange({
  fonts: 'Arial Unicode',
  start: 0,
  end: 255
})
  .send()
  .then(response => {
    const glyph = response.body;
  });

Returns MapiRequest

getEmbeddableHtml

Get embeddable HTML displaying a map.

See the corresponding HTTP service documentation.

Parameters

  • config Object
    • config.styleId string
    • config.scrollZoom boolean If false, zooming the map by scrolling will be disabled. (optional, default true)
    • config.title boolean If true, the map's title and owner is displayed in the upper right corner of the map. (optional, default false)
    • config.fallback boolean If true, serve a fallback raster map. (optional, default false)
    • config.mapboxGLVersion string? Specify a version of Mapbox GL JS to use to render the map.
    • config.mapboxGLGeocoderVersion string? Specify a version of the Mapbox GL geocoder plugin to use to render the map search box.
    • config.ownerId string?
    • config.draft boolean If true will retrieve the draft style, otherwise will retrieve the published style. (optional, default false)

Static

Static Images API service.

Learn more about this service and its responses in the HTTP service documentation.

getStaticImage

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.

Parameters

  • config Object
    • config.ownerId string The owner of the map style.
    • config.styleId string The map's style ID.
    • config.width number Width of the image in pixels, between 1 and 1280.
    • config.height number 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). Otherwise, the maps' position is described by an object with the following properties: coordinates (required): coordinates for the center of image. zoom (required): Between 0 and 20. bearing (optional): Between 0 and 360. pitch (optional): Between 0 and 60.
    • config.overlays Array<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, GeoJsonOverlay
    • config.highRes boolean (optional, default false)
    • config.before_layer string? The ID of the style layer that overlays should be inserted before.
    • config.addlayer Object? Adds a Mapbox style layer to the map's style at render time. Can be combined with before_layer.
    • config.setfilter Array? Applies a filter to an existing layer in a style using Mapbox's expression syntax. Must be used with layer_id.
    • config.layer_id string? Denotes the layer in the style that the filter specified in setfilter is applied to.
    • config.attribution boolean Whether there is attribution on the map image. (optional, default true)
    • config.logo boolean Whether there is a Mapbox logo on the map image. (optional, default true)

Examples

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: {
    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

Uploads API service.

Learn more about this service and its responses in the HTTP service documentation.

listUploads

List the statuses of all recent uploads.

See the corresponding HTTP service documentation.

Parameters

  • config Object?
    • config.reverse boolean? List uploads in chronological order, rather than reverse chronological order.

Examples

uploadsClient.listUploads()
  .send()
  .then(response => {
    const uploads = response.body;
  });

Returns MapiRequest

createUploadCredentials

Create S3 credentials.

See the corresponding HTTP service documentation.

Examples

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

createUpload

Create an upload.

See the corresponding HTTP service documentation.

Parameters

  • config Object
    • config.tileset string The tileset ID to create or replace, in the format username.nameoftileset. Limited to 32 characters (only - and _ special characters allowed; limit does not include username).
    • config.url string HTTPS URL of the S3 object provided by createUploadCredentials
    • config.name string? The name of the tileset. Limited to 64 characters.
    • config.private boolean A boolean that describes whether the tileset must be used with an access token from your Mapbox account. Default is true. (optional, default true)

Examples

// Response from a call to createUploadCredentials
const credentials = {
  accessKeyId: '{accessKeyId}',
  bucket: '{bucket}',
  key: '{key}',
  secretAccessKey: '{secretAccessKey}',
  sessionToken: '{sessionToken}',
  url: '{s3 url}'
};
uploadsClient.createUpload({
  titleset: `${myUsername}.${myTileset}`,
  url: credentials.url,
  name: 'my uploads name',
  private: true
})
  .send()
  .then(response => {
    const upload = response.body;
  });

Returns MapiRequest

getUpload

Get an upload's status.

See the corresponding HTTP service documentation.

Parameters

Examples

uploadsClient.getUpload({
  uploadId: '{upload_id}'
})
  .send()
  .then(response => {
    const status = response.body;
  });

Returns MapiRequest

deleteUpload

Delete an upload.

See the corresponding HTTP service documentation.

Parameters

Examples

uploadsClient.deleteUpload({
  uploadId: '{upload_id}'
})
.send()
.then(response => {
  // Upload successfully deleted.
});

Returns MapiRequest

Datasets

Datasets API service.

Learn more about this service and its responses in the HTTP service documentation.

listDatasets

List datasets in your account.

See the corresponding HTTP service documentation.

Parameters

  • config Object?
    • config.sortby string Sort by either modified or created (default) dates. (optional, default created)

Examples

datasetsClient.listDatasets()
  .send()
  .then(response => {
    const datasets = response.body;
  });
datasetsClient.listDatasets()
  .eachPage((error, response, next) => {
    // Handle error or response and call next.
  });

Returns MapiRequest

createDataset

Create a new, empty dataset.

See the corresponding HTTP service documentation.

Parameters

Examples

datasetsClient.createDataset({
  name: 'example',
  description: 'An example dataset'
})
  .send()
  .then(response => {
    const datasetMetadata = response.body;
  });

Returns MapiRequest

getMetadata

Get metadata about a dataset.

See the corresponding HTTP service documentation.

Parameters

Examples

datasetsClient.getMetadata({
  datasetId: 'dataset-id'
})
  .send()
  .then(response => {
    const datasetMetadata = response.body;
  })

Returns MapiRequest

updateMetadata

Update user-defined properties of a dataset's metadata.

See the corresponding HTTP service documentation.

Parameters

Examples

datasetsClient.updateMetadata({
  datasetId: 'dataset-id',
  name: 'foo'
})
  .send()
  .then(response => {
    const datasetMetadata = response.body;
  });

Returns MapiRequest

deleteDataset

Delete a dataset, including all features it contains.

See the corresponding HTTP service documentation.

Parameters

Examples

datasetsClient.deleteDataset({
  datasetId: 'dataset-id'
})
  .send()
  .then(response => {
    // Dataset is successfully deleted.
  });

Returns MapiRequest

listFeatures

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.

Parameters

  • config Object
    • config.datasetId string
    • config.limit number? Only list this number of features.
    • config.start string? The ID of the feature from which the listing should start.

Examples

datasetsClient.listFeatures({
  datasetId: 'dataset-id'
})
  .send()
  .then(response => {
    const features = response.body;
  });

Returns MapiRequest

putFeature

Add a feature to a dataset or update an existing one.

See the corresponding HTTP service documentation.

Parameters

  • config Object
    • config.datasetId string
    • config.featureId string
    • config.feature Object Valid GeoJSON that is not a FeatureCollection. If the feature has a top-level id property, it must match the featureId you specify.

Examples

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

getFeature

Get a feature in a dataset.

See the corresponding HTTP service documentation.

Parameters

Examples

datasetsClient.getFeature({
  datasetId: 'dataset-id',
  featureId: 'feature-id'
})
  .send()
  .then(response => {
    const feature = response.body;
  });

Returns MapiRequest

deleteFeature

Delete a feature in a dataset.

See the corresponding HTTP service documentation.

Parameters

Examples

datasetsClient.deleteFeature({
  datasetId: 'dataset-id',
  featureId: 'feature-id'
})
  .send()
  .then(response => {
    // Feature is successfully deleted.
  });

Returns MapiRequest

Tilequery

Tilequery API service.

Learn more about this service and its responses in the HTTP service documentation.

listFeatures

List features within a radius of a point on a map (or several maps).

Parameters

  • config Object
    • config.mapIds Array<string> The maps being queried. If you need to composite multiple layers, provide multiple map IDs.
    • config.coordinates Coordinates The longitude and latitude to be queried.
    • config.radius number The approximate distance in meters to query for features. (optional, default 0)
    • config.limit number The number of features to return, between 1 and 50. (optional, default 5)
    • config.dedupe boolean Whether or not to deduplicate results. (optional, default true)
    • config.geometry ("polygon" | "linestring" | "point")? Queries for a specific geometry type.
    • config.layers Array<string>? IDs of vector layers to query.

Examples

tilequeryClient.listFeatures({
  mapIds: ['mapbox.mapbox-streets-v8'],
  coordinates: [-122.42901, 37.80633],
  radius: 10
})
  .send()
  .then(response => {
    const features = response.body;
  });

Returns MapiRequest

Tilesets

Tilesets API service.

Learn more about this service and its responses in the HTTP service documentation.

listTilesets

List a user's tilesets.

Parameters

  • config Object?
    • config.ownerId string?
    • config.type ("raster" | "vector")? Filter results by tileset type, either raster or vector.
    • config.limit number The maximum number of tilesets to return, from 1 to 500. (optional, default 100)
    • config.sortBy ("created" | "modified")? Sort the listings by their created or modified timestamps.
    • config.start string? The tileset after which to start the listing.
    • config.visibility ("public" | "private")? Filter results by visibility, either public or private

Examples

tilesetsClient.listTilesets()
  .send()
  .then(response => {
    const tilesets = response.body;
  });
tilesetsClient.listTilesets()
  .eachPage((error, response, next) => {
    // Handle error or response and call next.
  });

Returns MapiRequest

deleteTileset

Delete a tileset

Parameters

  • config Object
    • config.tilesetId string ID of the tileset to be deleted in the form username.tileset_id.

Examples

tilesetsClient.deleteTileset({
    tilesetId: 'username.tileset_id'
  })
  .send()
  .then(response => {
    const deleted = response.statusCode === 204;
  });

Returns MapiRequest

tileJSONMetadata

Retrieve metadata about a tileset.

Parameters

  • config Object?
    • config.tilesetId string? Unique identifier for the tileset in the format username.id.

Returns MapiRequest

createTilesetSource

Create a tileset source

Parameters

Examples

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

getTilesetSource

Retrieve a tileset source information

Parameters

Examples

tilesetsClient.getTilesetSource({
     id: 'tileset_source_id'
  })
  .send()
  .then(response => {
    const tilesetSource = response.body;
  });

Returns MapiRequest

listTilesetSources

List tileset sources

Parameters

  • config Object?
    • config.ownerId string?
    • config.limit number The maximum number of tilesets to return, from 1 to 500. (optional, default 100)
    • config.start string? The tileset after which to start the listing.

Examples

tilesetsClient.listTilesetSources()
  .send()
  .then(response => {
    const tilesetSources = response.body;
  });

Returns MapiRequest

deleteTilesetSource

Delete a tileset source

Parameters

  • config Object
    • config.id string ID of the tileset source to be deleted.
    • config.ownerId string?

Examples

tilesetsClient.deleteTilesetSource({
    id: 'tileset_source_id'
  })
  .send()
  .then(response => {
    const deleted = response.statusCode === 201;
  });

Returns MapiRequest

createTileset

Create a tileset

Parameters

  • config Object
    • config.tilesetId string ID of the tileset to be created in the form username.tileset_name.
    • config.recipe Object The tileset recipe to use in JSON format.
    • config.name string Name of the tileset.
    • config.private boolean A private tileset must be used with an access token from your account. (optional, default true)
    • config.description string? Description of the tileset.

Examples

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

publishTileset

Publish a tileset

Parameters

  • config Object
    • config.tilesetId string ID of the tileset to publish in the form username.tileset_name.

Examples

tilesetsClient.publishTileset({
    tilesetId: 'username.tileset_id'
  })
  .send()
  .then(response => {
    const tilesetPublishJob = response.body;
  });

Returns MapiRequest

updateTileset

Update a tileset

Parameters

Examples

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

tilesetStatus

Retrieve the status of a tileset

Parameters

  • config Object
    • config.tilesetId string ID of the tileset in the form username.tileset_name.

Examples

tilesetsClient.tilesetStatus({
    tilesetId: 'username.tileset_name'
  })
  .send()
  .then(response => {
    const tilesetStatus = response.body;
  });

Returns MapiRequest

tilesetJob

Retrieve information about a single tileset job

Parameters

  • config Object
    • config.tilesetId string ID of the tileset in the form username.tileset_name.
    • config.jobId string The publish job's ID.

Examples

tilesetsClient.tilesetJob({
    tilesetId: 'username.tileset_name'
    jobId: 'job_id'
  })
  .send()
  .then(response => {
    const tilesetJob = response.body;
  });

Returns MapiRequest

listTilesetJobs

List information about all jobs for a tileset

Parameters

  • config Object
    • config.tilesetId string ID of the tileset in the form username.tileset_name.
    • config.stage ("processing" | "queued" | "success" | "failed")?
    • config.limit number The maximum number of tilesets to return, from 1 to 500. (optional, default 100)
    • config.start string? The tileset after which to start the listing.

Examples

tilesetsClient.listTilesetJobs({
    tileset: 'username.tileset_name'
  })
  .send()
  .then(response => {
    const jobs = response.body;
  });

Returns MapiRequest

getTilesetsQueue

View Tilesets API global queue

Examples

tilesetsClient.getTilesetsQueue()
  .send()
  .then(response => {
    const queue = response.body;
  });

Returns MapiRequest

validateRecipe

Validate a recipe

Parameters

Examples

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

getRecipe

Retrieve a recipe

Parameters

  • config Object
    • config.tilesetId string ID of the tileset in the form username.tileset_name.

Examples

tilesetsClient.getRecipe({
    tilesetId: 'username.tileset_name'
  })
  .send()
  .then(response => {
    const recipe = response.body;
  });

Returns MapiRequest

updateRecipe

Update a tileset recipe

Parameters

Examples

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

Geocoding API service.

Learn more about this service and its responses in the HTTP service documentation.

forwardGeocode

Search for a place.

See the public documentation.

Parameters

  • config Object
    • config.query string A place name.
    • config.mode ("mapbox.places" | "mapbox.places-permanent") Either mapbox.places for ephemeral geocoding, or mapbox.places-permanent for storing results and batch geocoding. (optional, default "mapbox.places")
    • config.countries Array<string>? Limits results to the specified countries. Each item in the array should be an ISO 3166 alpha 2 country code.
    • config.proximity Coordinates? Bias local results based on a provided location.
    • config.types Array<("country" | "region" | "postcode" | "district" | "place" | "locality" | "neighborhood" | "address" | "poi" | "poi.landmark")>? Filter results by feature types.
    • config.autocomplete boolean Return autocomplete results or not. (optional, default true)
    • config.bbox BoundingBox? Limit results to a bounding box.
    • config.limit number Limit the number of results returned. (optional, default 5)
    • config.language Array<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.routing boolean Specify whether to request additional metadata about the recommended navigation destination. Only applicable for address features. (optional, default false)

Examples

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

reverseGeocode

Search for places near coordinates.

See the public documentation.

Parameters

  • config Object
    • config.query Coordinates Coordinates at which features will be searched.
    • config.mode ("mapbox.places" | "mapbox.places-permanent") Either mapbox.places for ephemeral geocoding, or mapbox.places-permanent for storing results and batch geocoding. (optional, default "mapbox.places")
    • config.countries Array<string>? Limits results to the specified countries. Each item in the array should be an ISO 3166 alpha 2 country code.
    • config.types Array<("country" | "region" | "postcode" | "district" | "place" | "locality" | "neighborhood" | "address" | "poi" | "poi.landmark")>? Filter results by feature types.
    • config.bbox BoundingBox? Limit results to a bounding box.
    • config.limit number Limit the number of results returned. If using this option, you must provide a single item for types. (optional, default 1)
    • config.language Array<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.routing boolean Specify whether to request additional metadata about the recommended navigation destination. Only applicable for address features. (optional, default false)

Examples

geocodingClient.reverseGeocode({
  query: [-95.4431142, 33.6875431]
})
  .send()
  .then(response => {
    // GeoJSON document with geocoding matches
    const match = response.body;
  });

Returns MapiRequest

Directions

Directions API service.

Learn more about this service and its responses in the HTTP service documentation.

getDirections

Get directions.

Please read the full HTTP service documentation to understand all of the available options.

Parameters

  • config Object
    • config.profile ("driving-traffic" | "driving" | "walking" | "cycling") (optional, default "driving")
    • config.waypoints Array<DirectionsWaypoint> An ordered array of DirectionsWaypoint objects, between 2 and 25 (inclusive).
    • config.alternatives boolean Whether to try to return alternative routes. (optional, default false)
    • config.annotations Array<("duration" | "distance" | "speed" | "congestion")>? Specify additional metadata that should be returned.
    • config.bannerInstructions boolean Should be used in conjunction with steps. (optional, default false)
    • config.continueStraight boolean? Sets the allowed direction of travel when departing intermediate waypoints.
    • config.exclude string? 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.language string 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.roundaboutExits boolean Emit instructions at roundabout exits. (optional, default false)
    • config.steps boolean Whether to return steps and turn-by-turn instructions. (optional, default false)
    • config.voiceInstructions boolean Whether or not to return SSML marked-up text for voice guidance along the route. (optional, default false)
    • config.voiceUnits ("imperial" | "metric") Which type of units to return in the text for voice instructions. (optional, default "imperial")

Examples

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

MapMatching

Map Matching API service.

Learn more about this service and its responses in the HTTP service documentation.

getMatch

Snap recorded location traces to roads and paths.

Parameters

  • config Object
    • config.points Array<MapMatchingPoint> An ordered array of MapMatchingPoints, between 2 and 100 (inclusive).
    • config.profile ("driving-traffic" | "driving" | "walking" | "cycling") A directions profile ID. (optional, default driving)
    • config.annotations Array<("duration" | "distance" | "speed")>? Specify additional metadata that should be returned.
    • config.geometries ("geojson" | "polyline" | "polyline6") Format of the returned geometry. (optional, default "polyline")
    • config.language string 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.steps boolean Whether to return steps and turn-by-turn instructions. (optional, default false)
    • config.tidy boolean Whether or not to transparently remove clusters and re-sample traces for improved map matching results. (optional, default false)

Examples

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

Matrix

Map Matching API service.

Learn more about this service and its responses in the HTTP service documentation.

getMatrix

Get a duration and/or distance matrix showing travel times and distances between coordinates.

Parameters

  • config Object
    • config.points Array<MatrixPoint> An ordered array of MatrixPoints, between 2 and 100 (inclusive).
    • config.profile ("driving-traffic" | "driving" | "walking" | "cycling") A Mapbox Directions routing profile ID. (optional, default driving)
    • 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.annotations Array<("distance" | "duration")>? Used to specify resulting matrices.

Examples

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

Optimization API service.

Learn more about this service and its responses in the HTTP service documentation.

getOptimization

Get a duration-optimized route.

Please read the full HTTP service documentation to understand all of the available options.

Parameters

  • config Object
    • config.profile ("driving" | "driving-traffic" | "walking" | "cycling") (optional, default "driving")
    • config.waypoints Array<OptimizationWaypoint> An ordered array of OptimizationWaypoint objects, between 2 and 12 (inclusive).
    • config.annotations Array<("duration" | "distance" | "speed")>? Specify additional metadata that should be returned.
    • config.destination ("any" | "last") Returned route ends at any or last coordinate. (optional, default "any")
    • config.distributions Array<Distribution>? An ordered array of Distribution objects, each of which includes a pickup and dropoff property. pickup and dropoff properties correspond to an index in the OptimizationWaypoint array.
    • config.geometries ("geojson" | "polyline" | "polyline6") Format of the returned geometries. (optional, default "polyline")
    • config.language string 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.roundtrip boolean Specifies whether the trip should complete by returning to the first location. (optional, default true)
    • config.source ("any" | "first") To begin the route, start either from the first coordinate or let the Optimization API choose. (optional, default "any")
    • config.steps boolean Whether to return steps and turn-by-turn instructions. (optional, default false)

Returns MapiRequest

Tokens

Tokens API service.

Learn more about this service and its responses in the HTTP service documentation.

listTokens

List your access tokens.

See the corresponding HTTP service documentation.

Examples

tokensClient.listTokens()
  .send()
  .then(response => {
    const tokens = response.body;
  });

Returns MapiRequest

createToken

Create a new access token.

See the corresponding HTTP service documentation.

Parameters

Examples

tokensClient.createToken({
  note: 'datasets-token',
  scopes: ['datasets:write', 'datasets:read']
})
  .send()
  .then(response => {
    const token = response.body;
  });

Returns MapiRequest

createTemporaryToken

Create a new temporary access token.

See the corresponding HTTP service documentation.

Parameters

Examples

tokensClient.createTemporaryToken({
  scopes: ['datasets:write', 'datasets:read']
})
  .send()
  .then(response => {
    const token = response.body;
  });

Returns MapiRequest

updateToken

Update an access token.

See the corresponding HTTP service documentation.

Parameters

Examples

tokensClient.updateToken({
  tokenId: 'cijucimbe000brbkt48d0dhcx',
  note: 'datasets-token',
  scopes: ['datasets:write', 'datasets:read']
})
  .send()
  .then(response => {
    const token = response.body;
  });

Returns MapiRequest

getToken

Get data about the client's access token.

See the corresponding HTTP service documentation.

Examples

tokensClient.getToken()
  .send()
  .then(response => {
    const token = response.body;
  });

Returns MapiRequest

deleteToken

Delete an access token.

See the corresponding HTTP service documentation.

Parameters

Examples

tokensClient.deleteToken({
  tokenId: 'cijucimbe000brbkt48d0dhcx'
})
  .send()
  .then(response => {
    // Token successfully deleted.
  });

Returns MapiRequest

listScopes

List your available scopes. Each item is a metadata object about the scope, not just the string scope.

See the corresponding HTTP service documentation.

Examples

tokensClient.listScopes()
  .send()
  .then(response => {
    const scopes = response.body;
  });

Returns MapiRequest

Data structures

Data structures used in service method configuration.

DirectionsWaypoint

Type: Object

Properties

  • coordinates Coordinates
  • approach ("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 a radius. 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.
  • waypointName string? Custom name for the waypoint used for the arrival instruction in banners and voice instructions.

MapMatchingPoint

Type: Object

Properties

  • coordinates Coordinates
  • approach ("unrestricted" | "curb")? Used to indicate how requested routes consider from which side of the road to approach a waypoint.
  • radius number? A number in meters indicating the assumed precision of the used tracking device.
  • isWaypoint boolean? Whether this coordinate is waypoint or not. The first and last coordinates will always be waypoints.
  • waypointName string? Custom name for the waypoint used for the arrival instruction in banners and voice instructions. Will be ignored unless isWaypoint is true.
  • timestamp (tring | number | Date)? Datetime corresponding to the coordinate.

MatrixPoint

Type: Object

Properties

  • coordinates Coordinates [longitude, latitude]
  • approach ("unrestricted" | "curb")? Used to indicate how requested routes consider from which side of the road to approach the point.

OptimizationWaypoint

Type: Object

Properties

  • coordinates Coordinates
  • approach ("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 a radius. 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.

SimpleMarkerOverlay

A simple marker overlay.

Type: Object

Properties

  • marker Object
    • marker.coordinates [number, number] [longitude, latitude]
    • marker.size ("large" | "small")?
    • marker.label string? Marker symbol. Options are an alphanumeric label a through z, 0 through 99, or a valid Maki icon. If a letter is requested, it will be rendered in uppercase only.
    • marker.color string? A 3- or 6-digit hexadecimal color code.

CustomMarkerOverlay

A marker overlay with a custom image.

Type: Object

Properties

PathOverlay

A stylable line.

Type: Object

Properties

  • path Object
    • path.coordinates Array<Coordinates> An array of coordinates describing the path.
    • path.strokeWidth number?
    • path.strokeColor string?
    • path.strokeOpacity number? Must be paired with strokeColor.
    • path.fillColor string? Must be paired with strokeColor.
    • path.fillOpacity number? Must be paired with fillColor.

GeoJsonOverlay

GeoJSON to overlay the map.

Type: Object

Properties

  • geoJson Object Valid GeoJSON.

UploadableFile

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)

Coordinates

[longitude, latitude]

Type: Array<number>

BoundingBox

[minLongitude, minLatitude, maxLongitude, maxLatitude]

Type: Array<number>

Isochrone

Isochrone API service.

Learn more about this service and its responses in the HTTP service documentation.

getContours

Given a location and a routing profile, retrieve up to four isochrone contours

Parameters

  • config Object
    • config.profile ("driving" | "walking" | "cycling") A Mapbox Directions routing profile ID. (optional, default "driving")
    • config.coordinates Coordinates A {longitude,latitude} coordinate pair around which to center the isochrone lines.
    • config.minutes Array<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.
    • config.colors Array<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. If no colors are specified, the Isochrone API will assign a default rainbow color scheme to the output.
    • config.polygons boolean? 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.denoise number? 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.generalize number? 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

Distribution

Type: Object

Properties

  • pickup number Array index of the item containing coordinates for the pick-up location in the OptimizationWaypoint array.
  • dropoff number Array index of the item containing coordinates for the drop-off location in the OptimizationWaypoint array.