### Complete Upload Workflow Example Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/uploads.md A comprehensive example demonstrating the full workflow: obtaining S3 credentials, uploading an MBTiles file to S3, creating an upload from the S3 URL, and monitoring its progress. ```javascript const fs = require('fs'); let s3Credentials; let uploadId; // Step 1: Get S3 credentials uploadsClient.createUploadCredentials() .send() .then(response => { s3Credentials = response.body; // Step 2: Upload file to S3 const AWS = require('aws-sdk'); const s3 = new AWS.S3({ accessKeyId: s3Credentials.accessKeyId, secretAccessKey: s3Credentials.secretAccessKey, sessionToken: s3Credentials.sessionToken, region: 'us-east-1' }); return s3.putObject({ Bucket: s3Credentials.bucket, Key: s3Credentials.key, Body: fs.createReadStream('data.mbtiles') }).promise(); }) // Step 3: Create upload from S3 URL .then(() => { return uploadsClient.createUpload({ url: s3Credentials.url, tileset: 'myuser.my-data', name: 'My Data Tileset' }).send(); }) // Step 4: Monitor upload progress .then(response => { uploadId = response.body.id; function checkStatus() { return uploadsClient.getUpload({ uploadId: uploadId }) .send() .then(response => { const upload = response.body; console.log(`Upload status: ${upload.status}`); if (upload.status === 'complete') { console.log('Upload complete!'); return upload; } else if (upload.status === 'failed') { throw new Error('Upload failed'); } else { // Poll every 10 seconds return new Promise(resolve => { setTimeout(() => resolve(checkStatus()), 10000); }); } }); } return checkStatus(); }); ``` -------------------------------- ### Get Route with Details Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/optimization.md This example shows how to request additional route details such as distance, duration, geometry in GeoJSON format, and turn-by-turn steps. ```javascript optimizationClient.getOptimization({ waypoints: [ { coordinates: [-122.4194, 37.7749] }, { coordinates: [-122.42, 37.78] }, { coordinates: [-122.45, 37.82] }, { coordinates: [-122.40, 37.80] } ], profile: 'driving', source: 'first', destination: 'first', annotations: ['distance', 'duration'], geometries: 'geojson', steps: true }) .send() .then(response => { const route = response.body.routes[0]; console.log('Route geometry:', route.geometry); console.log('Leg details:', route.legs); console.log('Step-by-step instructions:', route.steps); }); ``` -------------------------------- ### Get Multiple Deliveries Route Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/optimization.md This example demonstrates how to plan a route for multiple deliveries, specifying pickup and dropoff points for each delivery using the 'distributions' parameter. ```javascript optimizationClient.getOptimization({ waypoints: [ { coordinates: [-122.4194, 37.7749] }, // 0: Warehouse { coordinates: [-122.42, 37.78] }, // 1: Customer A pickup { coordinates: [-122.421, 37.781] }, // 2: Customer A dropoff { coordinates: [-122.45, 37.82] }, // 3: Customer B pickup { coordinates: [-122.451, 37.821] } // 4: Customer B dropoff ], source: 'first', destination: 'first', distributions: [ { pickup: 1, dropoff: 2 }, // A's delivery { pickup: 3, dropoff: 4 } // B's delivery ] }) .send() .then(response => { const waypoints = response.body.waypoint_indices; console.log('Optimized sequence:', waypoints); }); ``` -------------------------------- ### Installation Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/README.md Install the Mapbox SDK for JavaScript using npm. ```APIDOC ## Installation ### Description Install the Mapbox SDK for JavaScript using npm. ### Command ```bash npm install @mapbox/mapbox-sdk ``` ``` -------------------------------- ### Install Mapbox SDK Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/README.md Install the @mapbox/mapbox-sdk package using npm. A Promise polyfill may be required for older browsers. ```bash npm install @mapbox/mapbox-sdk ``` -------------------------------- ### Create Tileset Source (Browser) Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/tilesets.md Create a tileset source from a GeoJSON file in a browser environment. This example uses a file input element to get the Blob. ```javascript const fileInput = document.querySelector('input[type="file"]'); tilesetsClient.createTilesetSource({ id: 'my-source', file: fileInput.files[0] // Blob }) .send() .then(response => { console.log('Source created:', response.body.id); }); ``` -------------------------------- ### Example Usage of tryServiceMethod Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/test/try-browser/index.html An example demonstrating how to set a global access token and call `tryServiceMethod` to retrieve a specific map style. Ensure only public or temporary access tokens are used. ```javascript MAPBOX_ACCESS_TOKEN = 'pk....'; tryServiceMethod('styles', 'getStyle', { styleId: 'cjgzfhs7k00072rnkgjlcuxsu' }); ``` -------------------------------- ### Example DirectionsWaypoint Usage Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/types.md Shows how to configure waypoints with approach, bearing, and radius for directions requests. ```javascript directionsClient.getDirections({ waypoints: [ { coordinates: [13.4301, 52.5109], approach: 'unrestricted' }, { coordinates: [13.4194, 52.5072], bearing: [100, 60], radius: 50 } ] }); ``` -------------------------------- ### List All Tilesets Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/tilesets.md List all tilesets in the user's account. This example shows how to fetch and log the names and IDs of all tilesets. ```javascript tilesetsClient.listTilesets() .send() .then(response => { response.body.forEach(tileset => { console.log(`${tileset.name} (${tileset.id})`); }); }); ``` -------------------------------- ### Retrieve Tileset Source Information Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/tilesets.md Get information about a tileset source using its ID. This example logs the current status of the source. ```javascript tilesetsClient.getTilesetSource({ id: 'my-source' }) .send() .then(response => { console.log('Source status:', response.body.status); }); ``` -------------------------------- ### Example MatrixPoint Usage Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/types.md Illustrates configuring points for the Matrix API, including specifying the 'curb' approach. ```javascript matrixClient.getMatrix({ points: [ { coordinates: [2.2, 1.1], approach: 'curb' }, { coordinates: [3.2, 1.1] }, { coordinates: [4.2, 1.1] } ] }); ``` -------------------------------- ### Create Dataset and Add Feature Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/datasets.md This example demonstrates creating a new dataset and then adding the first feature to it. It's a common pattern for initializing new data collections. ```javascript // Create a dataset for points of interest datasetsClient.createDataset({ name: 'Live POIs', description: 'Real-time business locations' }) .send() .then(response => { const datasetId = response.body.id; // Add a feature return datasetsClient.putFeature({ datasetId: datasetId, featureId: 'store-123', feature: { type: 'Feature', properties: { name: 'Downtown Store', hours: '9am-6pm' }, geometry: { type: 'Point', coordinates: [-122.4194, 37.7749] } } }).send(); }); ``` -------------------------------- ### Create Tileset Source with File Path (Node.js) Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/types.md Example of creating a tileset source using a file path string in a Node.js environment. ```javascript const fs = require('fs'); tilesetsClient.createTilesetSource({ file: 'data/features.geojson.ld' // File path }); ``` -------------------------------- ### Example Distribution Usage Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/types.md Shows how to model delivery operations using waypoints and distribution pairs for the Optimization API. ```javascript optimizationClient.getOptimization({ waypoints: [depot, pickup1, drop1, pickup2, drop2], distributions: [ { pickup: 1, dropoff: 2 }, { pickup: 3, dropoff: 4 } ] }); ``` -------------------------------- ### PathOverlay Example Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/types.md Example of using PathOverlay for a static map image. Defines a line with specified coordinates, stroke width, color, and fill opacity. ```javascript staticClient.getStaticImage({ overlays: [ { path: { coordinates: [[-122.4, 37.8], [-122.45, 37.82]], strokeWidth: 2, strokeColor: '0000ff', fillOpacity: 0.3 } } ] }); ``` -------------------------------- ### Get Directions with Bearing and Radius Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/directions.md Calculate a route using the getDirections method. This example demonstrates how to specify approach directions using bearing and radius for waypoints, allowing for more precise route snapping and guidance. ```javascript directionsClient.getDirections({ waypoints: [ { coordinates: [13.4301, 52.5109], bearing: [100, 60] // Approach from 100° ±60° }, { coordinates: [13.4194, 52.5072], bearing: [200, 45], radius: 50 // Snap to road within 50m } ] }) .send() .then(response => { console.log('Route:', response.body.routes[0]); }); ``` -------------------------------- ### Example BoundingBox Usage Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/types.md Demonstrates using a BoundingBox with the forwardGeocode API to limit search results. ```javascript const sanFranciscoBay = [-122.6, 37.7, -122.4, 37.8]; geocodingClient.forwardGeocode({ query: 'coffee', bbox: sanFranciscoBay }); ``` -------------------------------- ### Example Coordinates Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/types.md Illustrates the usage of the Coordinates type with sample San Francisco and London coordinates. ```javascript const sanFrancisco = [-122.4194, 37.7749]; const london = [-0.1276, 51.5074]; ``` -------------------------------- ### Create Tileset Source with ReadStream (Node.js) Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/types.md Example of creating a tileset source using a ReadStream in a Node.js environment. ```javascript // Or with ReadStream: tilesetsClient.createTilesetSource({ file: fs.createReadStream('data/features.geojson.ld') }); ``` -------------------------------- ### Example SimpleMarkerOverlay Usage Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/types.md Demonstrates adding a custom marker to a static map image with specified color, label, and size. ```javascript staticClient.getStaticImage({ overlays: [ { marker: { coordinates: [-122.4, 37.8], color: 'ff0000', label: 'A', size: 'large' } } ] }); ``` -------------------------------- ### Create Tileset Source with Blob (Browser) Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/types.md Example of creating a tileset source using a Blob object obtained from a file input in a browser environment. ```javascript const fileInput = document.querySelector('input[type="file"]'); tilesetsClient.createTilesetSource({ file: fileInput.files[0] // Blob }); ``` -------------------------------- ### GeoJSONOverlay Example Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/types.md Example of using GeoJSONOverlay for a static map image. Includes a GeoJSON FeatureCollection with a Point feature. ```javascript staticClient.getStaticImage({ overlays: [ { geojson: { type: 'FeatureCollection', features: [ { type: 'Feature', geometry: { type: 'Point', coordinates: [-122.4, 37.8] }, properties: {} } ] } } ] }); ``` -------------------------------- ### Basic Trace Matching Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/map-matching.md Snap a basic location trace to the driving profile. This example demonstrates the minimal configuration required for the `getMatch` method. ```javascript mapMatchingClient.getMatch({ points: [ { coordinates: [-122.4194, 37.7749] }, { coordinates: [-122.4164, 37.7749] }, { coordinates: [-122.4130, 37.7750] }, { coordinates: [-122.4095, 37.7753] } ], profile: 'driving' }) .send() .then(response => { const matching = response.body; console.log('Matched geometry:', matching.geometry); console.log('Confidence:', matching.confidence); }); ``` -------------------------------- ### Retrieve Tileset Recipe Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/docs/services.md Get the recipe for a specific tileset. This is useful for reviewing or reusing existing tileset configurations. ```javascript tilesetsClient.getRecipe({ tilesetId: 'username.tileset_name' }) .send() .then(response => { const recipe = response.body; }); ``` -------------------------------- ### Generate Basic Static Map Image Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/static.md A basic example of generating a static map image with specified owner, style, dimensions, and coordinates. ```javascript staticClient.getStaticImage({ ownerId: 'mapbox', styleId: 'streets-v11', width: 400, height: 300, position: { coordinates: [-122.4194, 37.7749], zoom: 12 } }) .send() .then(response => { const image = response.body; // Save to file or send to client }); ``` -------------------------------- ### Get Route with Flexible Start/End Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/optimization.md Use this snippet to find an optimal route where the starting and ending points can be any of the provided waypoints, without necessarily returning to the start. ```javascript optimizationClient.getOptimization({ waypoints: [ { coordinates: [-122.42, 37.78] }, { coordinates: [-122.45, 37.82] }, { coordinates: [-122.40, 37.80] } ], profile: 'driving', source: 'any', // Start from best waypoint destination: 'any', // End at best waypoint roundtrip: false // Don't return to start }) .send() .then(response => { const indices = response.body.waypoint_indices; console.log(`Optimal start: ${indices[0]}`); console.log(`Optimal end: ${indices[indices.length - 1]}`); }); ``` -------------------------------- ### Initialize Mapbox Client with UMD Build Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/README.md Demonstrates how to initialize the Mapbox client using the UMD build and access services globally. This example shows initializing the client with an access token and then using services like `styles` and `tilesets`. ```html ``` -------------------------------- ### Generate Static Map Image With Path Overlay Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/static.md Example of drawing a path on a static map image using the 'overlays' parameter with path coordinates and styling. ```javascript staticClient.getStaticImage({ ownerId: 'mapbox', styleId: 'streets-v11', width: 400, height: 300, position: { coordinates: [0, 0], zoom: 2 }, overlays: [ { path: { coordinates: [ [-122.4, 37.8], [-122.45, 37.82], [-122.42, 37.78] ], strokeWidth: 2, strokeColor: '#0000ff', fillColor: '#0000ff', fillOpacity: 0.3 } } ] }) .send() .then(response => { console.log('Map with path generated'); }); ``` -------------------------------- ### Get Walking Route with French Instructions Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/directions.md Request walking directions with step-by-step instructions in French. This snippet demonstrates setting the language parameter for instructions. ```javascript directionsClient.getDirections({ profile: 'walking', waypoints: [ { coordinates: [2.3522, 48.8566] }, { coordinates: [2.2945, 48.8583] } ], language: 'fr', steps: true }) .send() .then(response => { const instructions = response.body.routes[0].legs[0].steps; instructions.forEach(step => { ``` -------------------------------- ### Get Simple Delivery Route Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/optimization.md Use this snippet to calculate a duration-optimized route for a simple delivery scenario, starting and ending at the same depot. ```javascript optimizationClient.getOptimization({ waypoints: [ { coordinates: [-122.4194, 37.7749] }, // Depot { coordinates: [-122.42, 37.78] }, // Stop 1 { coordinates: [-122.45, 37.82] }, // Stop 2 { coordinates: [-122.40, 37.80] } // Stop 3 ], profile: 'driving', source: 'first', // Start from depot destination: 'first', // Return to depot roundtrip: true }) .send() .then(response => { const route = response.body; console.log('Optimized order:', route.waypoint_indices); console.log('Total distance:', route.routes[0].distance); console.log('Total duration:', route.routes[0].duration); }); ``` -------------------------------- ### Query Custom Tilesets Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/tilequery.md Query your own uploaded tilesets to find specific features like hazards. This example demonstrates querying a custom tileset with a specified radius and limit. ```javascript // Query your own uploaded tilesets tilequeryClient.listFeatures({ mapIds: ['myuser.custom-hazards'], coordinates: [-122.4194, 37.7749], radius: 1000, limit: 20 }) .send() .then(response => { const hazards = response.body.features; hazards.forEach(hazard => { console.log(`Hazard: ${hazard.properties.type}`); }); }); ``` -------------------------------- ### Get Static Image with Filter Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/docs/services.md Generates a static map image with a filter applied to a specific layer. This example filters buildings by height. ```javascript // 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. ``` -------------------------------- ### Create a Minimal Fake Service Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/docs/development.md This example demonstrates how to create a minimal fake service prototype and register it with `createServiceFactory`. It includes methods for listing and deleting animals, showcasing request creation with different HTTP methods and parameters. ```javascript var createServiceFactory = require('../path/to/service-helpers/create-service-factory'); var Animals = {}; Animals.listAnimals = function() { return this.client.createRequest({ method: 'GET', path: '/animals/v1/:ownerId' }); }; Animals.deleteAnimal = function(config) { // Here you can make assertions against config. return this.client.createRequest({ method: 'DELETE', path: '/animals/v1/:ownerId/:animalId', params: { animalId: config.animalId } }); }; var AnimalsService = createServiceFactory(Animals); ``` -------------------------------- ### Batch Update Features in a Dataset Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/datasets.md This example demonstrates how to update multiple features in a dataset concurrently using `Promise.all`. It's efficient for bulk data modifications. ```javascript const datasetId = 'clxyz123'; const features = [ { id: 'feature-1', data: {...} }, { id: 'feature-2', data: {...} }, { id: 'feature-3', data: {...} } ]; // Update all features Promise.all( features.map(f => datasetsClient.putFeature({ datasetId: datasetId, featureId: f.id, feature: f.data }).send() ) ) .then(() => { console.log('All features updated'); }); ``` -------------------------------- ### Generate Static Map Image Using Bounding Box Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/static.md Example of generating a static map image using a bounding box for positioning and applying padding. ```javascript staticClient.getStaticImage({ ownerId: 'mapbox', styleId: 'outdoors-v12', width: 500, height: 300, position: { bbox: [-77.04, 38.8, -77.02, 38.91] }, padding: '20' }) .send() .then(response => { console.log('Image generated'); }); ``` -------------------------------- ### Import Styles Service Module Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/styles.md Import the Styles service module and initialize a client with an access token or a base client. ```javascript const mbxStyles = require('@mapbox/mapbox-sdk/services/styles'); const stylesClient = mbxStyles({ accessToken: 'YOUR_TOKEN' }); // Or with shared client: const stylesClient = mbxStyles(baseClient); ``` -------------------------------- ### Import Optimization Service Client Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/optimization.md Import the Optimization service module and initialize a client. You can either provide an access token directly or use a pre-configured base client. ```javascript const mbxOptimization = require('@mapbox/mapbox-sdk/services/optimization'); const optimizationClient = mbxOptimization({ accessToken: 'YOUR_TOKEN' }); ``` ```javascript // Or with shared client: const optimizationClient = mbxOptimization(baseClient); ``` -------------------------------- ### Initialize MapiClient Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/mapi-client.md Shows how to initialize the MapiClient using require or the Node client factory. Ensure you provide a valid Mapbox access token. ```javascript const MapiClient = require('@mapbox/mapbox-sdk').MapiClient; // Or through Node client factory: const client = require('@mapbox/mapbox-sdk')({ accessToken: 'YOUR_TOKEN' }); ``` -------------------------------- ### Get Distance-Based Isochrone Contours Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/isochrone.md Retrieve isochrone contours based on travel distance in meters. This example calculates contours for 500, 1000, and 2000 meters using the 'walking' profile. ```javascript isochroneClient.getContours({ coordinates: [-122.4194, 37.7749], profile: 'walking', meters: [500, 1000, 2000] }) .send() .then(response => { const features = response.body.features; console.log('Walking distance contours:', features.length); }); ``` -------------------------------- ### Get Driving with Traffic Directions Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/directions.md Request driving directions considering real-time traffic. This example also enables alternative routes, step-by-step instructions, banner instructions, and voice guidance. ```javascript directionsClient.getDirections({ profile: 'driving-traffic', waypoints: [ { coordinates: [-122.4194, 37.7749] }, { coordinates: [-118.2437, 34.0522] } ], alternatives: true, steps: true, bannerInstructions: true, voiceInstructions: true }) .send() .then(response => { response.body.routes.forEach((route, i) => { console.log(`Route ${i + 1}: ${route.distance}m in ${route.duration}s`); if (route.steps) { route.steps.forEach(step => { console.log(`- ${step.maneuver.instruction}`); }); } }); }); ``` -------------------------------- ### Import Matrix Service Client Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/matrix.md Import the Matrix service client and initialize it with an access token or a base client. ```javascript const mbxMatrix = require('@mapbox/mapbox-sdk/services/matrix'); const matrixClient = mbxMatrix({ accessToken: 'YOUR_TOKEN' }); // Or with shared client: const matrixClient = mbxMatrix(baseClient); ``` -------------------------------- ### Get Colored Isochrone Polygons Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/isochrone.md Generate isochrone contours as polygons with custom colors. This example shows contours for 10, 20, and 30 minutes in Paris, with specified hex colors and denoising. ```javascript isochroneClient.getContours({ coordinates: [2.3522, 48.8566], // Paris profile: 'walking', minutes: [10, 20, 30], colors: ['ff0000', '00ff00', '0000ff'], // Red, green, blue polygons: true, denoise: 0.8 }) .send() .then(response => { const polygons = response.body.features; polygons.forEach(feature => { console.log(`Polygon for ${feature.properties.contour} minutes`); }); }); ``` -------------------------------- ### Get Time-Based Isochrone Contours Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/isochrone.md Retrieve isochrone contours based on travel time in minutes. This example shows contours for 5, 10, 15, and 20 minutes using the 'driving' profile. ```javascript isochroneClient.getContours({ coordinates: [-122.4194, 37.7749], profile: 'driving', minutes: [5, 10, 15, 20] }) .send() .then(response => { // GeoJSON FeatureCollection with isochrone contours const features = response.body.features; features.forEach(feature => { console.log(`Contour for ${feature.properties.contour} minutes`); }); }); ``` -------------------------------- ### Get Static Image with Layer Addition Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/docs/services.md Adds a custom layer to a static map image and specifies its placement relative to existing layers. This example adds a dashed boundary layer below the road-label layer. ```javascript // 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. ``` -------------------------------- ### Get Isochrone Contours with Denoising Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/isochrone.md Retrieve isochrone contours with denoising applied to remove smaller contours. This example calculates cycling contours for 15, 30, and 45 minutes with a denoise factor of 0.5. ```javascript isochroneClient.getContours({ coordinates: [-122.4194, 37.7749], profile: 'cycling', minutes: [15, 30, 45], denoise: 0.5 // Drop contours less than 50% of largest }) .send() .then(response => { console.log('Denoised contours:', response.body.features.length); }); ``` -------------------------------- ### Get Isochrone Contours with Traffic Data Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/isochrone.md Retrieve isochrone contours considering real-time traffic conditions. This example calculates driving contours for 10, 20, and 30 minutes, departing at a specific time to account for peak hours. ```javascript isochroneClient.getContours({ coordinates: [-122.4194, 37.7749], profile: 'driving-traffic', minutes: [10, 20, 30], depart_at: '2024-06-15T08:00:00' // Peak morning hours }) .send() .then(response => { console.log('Reachability during peak traffic'); }); ``` -------------------------------- ### Initialize Mapbox SDK via CDN Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/configuration.md Include the Mapbox SDK using a script tag from unpkg. A global `mapboxSdk` function becomes available for client initialization. ```html ``` -------------------------------- ### Basic Mapbox SDK Usage Pattern Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/README.md Demonstrates the fundamental pattern for using the Mapbox SDK, including client creation, service instantiation, request configuration, and sending the request with error handling. ```javascript // 1. Create a client const mbxClient = require('@mapbox/mapbox-sdk'); const client = mbxClient({ accessToken: 'YOUR_TOKEN' }); // 2. Create a service const mbxStyles = require('@mapbox/mapbox-sdk/services/styles'); const stylesService = mbxStyles(client); // 3. Create a request const request = stylesService.getStyle({ styleId: 'my-style' }); // 4. Send the request request.send() .then(response => { console.log('Success:', response.body); }) .catch(error => { console.error('Error:', error.message); }); ``` -------------------------------- ### Import Mapbox Tilequery Service Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/tilequery.md Import the Tilequery service module and initialize a client. You can either provide an access token directly or use a pre-initialized base client. ```javascript const mbxTilequery = require('@mapbox/mapbox-sdk/services/tilequery'); const tilequeryClient = mbxTilequery({ accessToken: 'YOUR_TOKEN' }); // Or with shared client: const tilequeryClient = mbxTilequery(baseClient); ``` -------------------------------- ### CustomMarkerOverlay Example Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/types.md Example of how to use the CustomMarkerOverlay type when requesting a static map image. Specifies marker coordinates and image URL. ```javascript staticClient.getStaticImage({ overlays: [ { marker: { coordinates: [-122.4, 37.8], url: 'https://example.com/marker.png' } } ] }); ``` -------------------------------- ### Get Basic Route Directions Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/directions.md Use this snippet to get basic route information between waypoints. It logs the distance and duration of the primary route. ```javascript directionsClient.getDirections({ waypoints: [ { coordinates: [13.4301, 52.5109] }, { coordinates: [13.4265, 52.508] }, { coordinates: [13.4194, 52.5072] } ] }) .send() .then(response => { const route = response.body.routes[0]; console.log(`Distance: ${route.distance}m`); console.log(`Duration: ${route.duration}s`); }); ``` -------------------------------- ### Create MapiClient Instance (Node.js) Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/mapi-client.md Demonstrates creating a MapiClient instance with an access token and sharing its configuration with multiple Mapbox services like Styles and Tilesets. ```javascript const mbxClient = require('@mapbox/mapbox-sdk'); const baseClient = mbxClient({ accessToken: 'pk.eyJ1IjoiZXhhbXBsZSIsImEiOiJjbGV4YW1wbGUifQ' }); // Share configuration with multiple services const stylesService = require('@mapbox/mapbox-sdk/services/styles')(baseClient); const tilesetsService = require('@mapbox/mapbox-sdk/services/tilesets')(baseClient); ``` -------------------------------- ### Importing the Directions Service Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/directions.md Demonstrates how to import and initialize the Directions Service client. You can either provide an access token directly or use a pre-configured base client. ```javascript const mbxDirections = require('@mapbox/mapbox-sdk/services/directions'); const directionsClient = mbxDirections({ accessToken: 'YOUR_TOKEN' }); ``` ```javascript // Or with shared client: const directionsClient = mbxDirections(baseClient); ``` -------------------------------- ### Import Isochrone Service Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/isochrone.md Import the Isochrone service module and initialize a client. You can use a personal access token or a shared client instance. ```javascript const mbxIsochrone = require('@mapbox/mapbox-sdk/services/isochrone'); const isochroneClient = mbxIsochrone({ accessToken: 'YOUR_TOKEN' }); // Or with shared client: const isochroneClient = mbxIsochrone(baseClient); ``` -------------------------------- ### Import Mapbox Tilesets Module Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/tilesets.md Import the Tilesets module and initialize a client. You can use a personal access token or a pre-configured base client. ```javascript const mbxTilesets = require('@mapbox/mapbox-sdk/services/tilesets'); const tilesetsClient = mbxTilesets({ accessToken: 'YOUR_TOKEN' }); // Or with shared client: const tilesetsClient = mbxTilesets(baseClient); ``` -------------------------------- ### Mapbox Client Initialization with Custom Origin Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/configuration.md Demonstrates initializing the Mapbox client to use custom API endpoints for staging or internal environments. ```javascript // Default production const client = mbxClient({ accessToken: 'pk.eyJ...', origin: 'https://api.mapbox.com' }); // Custom staging environment const stagingClient = mbxClient({ accessToken: 'pk.eyJ...', origin: 'https://api-staging.mapbox.com' }); // Proxy or internal endpoint const proxyClient = mbxClient({ accessToken: 'pk.eyJ...', origin: 'https://internal-api.company.com' }); ``` -------------------------------- ### url() Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/mapi-request.md Gets the URL for the request without sending it. This is useful for debugging or when you need the URL for other purposes. ```APIDOC ## url() ### Description Gets the URL for the request without sending it. This is useful for debugging or when you need the URL for other purposes. ### Returns `string` — The URL for the request ### Example ```javascript const request = staticClient.getStaticImage({ ownerId: 'mapbox', styleId: 'streets-v11', width: 200, height: 300, position: { coordinates: [12, 13], zoom: 4 } }); // Get URL without sending const imageUrl = request.url(); console.log(imageUrl); // Output: https://api.mapbox.com/styles/v1/mapbox/streets-v11/static/12,13,4/200x300?access_token=... ``` ``` -------------------------------- ### Basic Usage Pattern Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/README.md Demonstrates the fundamental pattern for using the Mapbox SDK, including client creation, service instantiation, request creation, and sending the request. ```APIDOC ## Basic Usage Pattern ### Description Demonstrates the fundamental pattern for using the Mapbox SDK, including client creation, service instantiation, request creation, and sending the request. ### Example ```javascript // 1. Create a client const mbxClient = require('@mapbox/mapbox-sdk'); const client = mbxClient({ accessToken: 'YOUR_TOKEN' }); // 2. Create a service const mbxStyles = require('@mapbox/mapbox-sdk/services/styles'); const stylesService = mbxStyles(client); // 3. Create a request const request = stylesService.getStyle({ styleId: 'my-style' }); // 4. Send the request request.send() .then(response => { console.log('Success:', response.body); }) .catch(error => { console.error('Error:', error.message); }); ``` ``` -------------------------------- ### Get Tileset Status Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/docs/services.md Retrieve the status of a specific tileset. This is useful for monitoring the progress of tileset processing. ```javascript tilesetsClient.tilesetStatus({ tilesetId: 'username.tileset_name' }) .send() .then(response => { const tilesetStatus = response.body; }); ``` -------------------------------- ### Import Mapbox Uploads Service Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/uploads.md Import the uploads service module and initialize a client with an access token or a base client. ```javascript const mbxUploads = require('@mapbox/mapbox-sdk/services/uploads'); const uploadsClient = mbxUploads({ accessToken: 'YOUR_TOKEN' }); // Or with shared client: const uploadsClient = mbxUploads(baseClient); ``` -------------------------------- ### Importing the Static Images Service Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/static.md Import the Static Images service module and initialize a client. You can either provide an access token directly or use a shared base client. ```javascript const mbxStatic = require('@mapbox/mapbox-sdk/services/static'); const staticClient = mbxStatic({ accessToken: 'YOUR_TOKEN' }); // Or with shared client: const staticClient = mbxStatic(baseClient); ``` -------------------------------- ### Get a Feature from a Dataset Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/docs/services.md Retrieves a specific feature from a dataset using its dataset ID and feature ID. ```javascript datasetsClient.getFeature({ datasetId: 'dataset-id', featureId: 'feature-id' }) .send() .then(response => { const feature = response.body; }); ``` -------------------------------- ### Get Dataset Metadata Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/docs/services.md Retrieves the metadata for a specific dataset using its ID. This includes user-defined properties. ```javascript datasetsClient.getMetadata({ datasetId: 'dataset-id' }) .send() .then(response => { const datasetMetadata = response.body; }) ``` -------------------------------- ### Importing the Tokens Module Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/tokens.md Import the Tokens service module and initialize a client. You can either provide an access token directly or use a shared client instance. ```javascript const mbxTokens = require('@mapbox/mapbox-sdk/services/tokens'); const tokensClient = mbxTokens({ accessToken: 'YOUR_TOKEN' }); // Or with shared client: const tokensClient = mbxTokens(baseClient); ``` -------------------------------- ### Get Token Details Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/tokens.md Retrieves details for a specific token using its ID. The token ID is required. ```javascript tokensClient.getToken('cijucimbe000brbkt48d0dhcx') .send() .then(response => { const token = response.body; console.log(`Token scopes: ${token.scopes.join(', ')}`); }); ``` -------------------------------- ### MapiClient.origin Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/mapi-client.md Gets the API origin URL used for all requests created by this client. Defaults to `https://api.mapbox.com`. ```APIDOC ## MapiClient.origin ### Description The API origin URL used for all requests created by this client. Defaults to `https://api.mapbox.com`. ### Type `string` ### Example ```javascript const client = mbxClient({ accessToken: 'pk.eyJ...', origin: 'https://api.mapbox.com' // default }); ``` ``` -------------------------------- ### Import Mapbox Datasets Client Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/datasets.md Import the Datasets module and initialize the client with an access token or a shared client. ```javascript const mbxDatasets = require('@mapbox/mapbox-sdk/services/datasets'); const datasetsClient = mbxDatasets({ accessToken: 'YOUR_TOKEN' }); // Or with shared client: const datasetsClient = mbxDatasets(baseClient); ``` -------------------------------- ### Service Initialization with Configuration Object Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/configuration.md Initialize a Mapbox service by passing a configuration object containing the access token to its factory function. ```javascript const serviceFactory = require('@mapbox/mapbox-sdk/services/{service}'); // Option 1: Pass configuration object const service = serviceFactory({ accessToken: 'pk.eyJ...' }); ``` -------------------------------- ### Get Upload Status Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/docs/services.md Retrieves the status of a specific upload using its ID. This is useful for monitoring the progress of an upload. ```javascript uploadsClient.getUpload({ uploadId: '{upload_id}' }) .send() .then(response => { const status = response.body; }); ``` -------------------------------- ### MapiClient.accessToken Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/mapi-client.md Gets the Mapbox access token assigned to this client. This token is used to authenticate requests made by the client. ```APIDOC ## MapiClient.accessToken ### Description The Mapbox access token assigned to this client. Extracted from the token during initialization and used to authenticate requests. ### Type `string` ### Example ```javascript const client = mbxClient({ accessToken: 'pk.eyJ...' }); console.log(client.accessToken); // 'pk.eyJ...' ``` ``` -------------------------------- ### Delivery Route Planning Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/optimization.md Plan optimal routes for a fleet of drivers, starting from a warehouse and visiting customer locations. ```APIDOC ## getOptimization Delivery Route Planning ### Description Plans optimal routes for a fleet of drivers, starting from a warehouse and visiting customer locations. ### Method `POST` (inferred from SDK usage) ### Endpoint `/optimization` (inferred from SDK usage) ### Parameters #### Request Body - **waypoints** (array) - Required - An array of stop objects, each with `coordinates`. - **profile** (string) - Required - The routing profile to use (e.g., 'driving'). - **source** (string) - Required - Specifies if the route must start from the first waypoint ('first') or can start from any waypoint ('any'). - **destination** (string) - Required - Specifies if the route must end at the last waypoint ('last') or can end at any waypoint ('any'). - **roundtrip** (boolean) - Optional - If true, creates a roundtrip route. ### Request Example ```json { "waypoints": [ { "coordinates": [-122.4194, 37.7749] }, // Customer locations... ], "profile": "driving", "source": "first", "destination": "first", "roundtrip": true } ``` ### Response #### Success Response (200) - **waypoint_indices** (array) - An array of indices representing the optimized order of waypoints. ``` -------------------------------- ### Delivery Route Optimization Example Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/matrix.md Demonstrates using the Matrix API to obtain duration data for multiple waypoints, which can then be used to calculate the most efficient delivery route. This snippet focuses on fetching the duration matrix. ```javascript // Find fastest delivery route among multiple destinations const waypoints = [ { coordinates: [-122.42, 37.78] }, // Start { coordinates: [-122.45, 37.82] }, { coordinates: [-122.40, 37.80] }, { coordinates: [-122.43, 37.77] } ]; matrixClient.getMatrix({ points: waypoints, profile: 'driving', annotations: ['duration'] }) .send() .then(response => { const durations = response.body.durations; // Use durations to find optimal route }); ``` -------------------------------- ### Mapbox SDK Pagination - Manual and Automatic Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/README.md Demonstrates two methods for handling paginated results: manual pagination using `hasNextPage()` and `nextPage()`, and automatic pagination with `eachPage()` for simplified iteration. ```javascript // Option 1: Manual pagination service.listEndpoint() .send() .then(response => { if (response.hasNextPage()) { return response.nextPage().send(); } }); // Option 2: Automatic pagination service.listEndpoint() .eachPage((error, response, next) => { if (error) { console.error(error); return; } console.log(`Page: ${response.body.length} items`); next(); // Fetch next page }); ``` -------------------------------- ### Importing the Geocoding Module Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/_autodocs/api-reference/geocoding.md Import the Geocoding service and initialize a client with an access token or a shared base client. ```javascript const mbxGeocoding = require('@mapbox/mapbox-sdk/services/geocoding'); const geocodingClient = mbxGeocoding({ accessToken: 'YOUR_TOKEN' }); // Or with shared client: const geocodingClient = mbxGeocoding(baseClient); ``` -------------------------------- ### Get Map Match Source: https://github.com/mapbox/mapbox-sdk-js/blob/main/docs/services.md Snaps recorded location traces to roads. Supports options for tidying traces and specifying points. ```javascript 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; }) ```