Mapbox SDK for JavaScript
repository·main·Indexed 20 days ago
https://github.com/mapbox/mapbox-sdk-jsA JavaScript SDK for interacting with Mapbox APIs, compatible with Node.js, the browser, and React Native. Version 0.16.3 provides a structured way to create clients and services to manage Mapbox resources such as styles and tilesets. It features a request-based system using MapiRequest for handling asynchronous calls, pagination via eachPage(), and detailed error handling through MapiError.
What's inside @mapbox/mapbox-sdk
- The Tilesets API service allows you to manage the lifecycle of Mapbox tilesets, including listing, creating, updating, deleting, and publishing them. You can also manage the underlying tileset sources and validate the recipes used to generate tilesets.
Manage Datasets with the Datasets API
mainThe Datasets API service allows you to create, list, retrieve, update, and delete datasets and their individual features. Most methods return anMapiRequestwhich must be followed by.send()to execute the request.Manage Mapbox Styles with stylesClient
mainThe Styles API service allows you to create, retrieve, update, and delete Mapbox styles, as well as manage icons and sprites. Most methods return anMapiRequestwhich must be followed by.send()to execute the request.How MapiResponse works
mainAn
MapiResponseis the object returned when anMapiRequest.send()Promise resolves. It contains the parsed API response and metadata.Key properties and methods:
MapiResponse.body: The parsed JSON body of the API response.MapiResponse.headers: The parsed HTTP headers.MapiResponse#hasNextPage(): Returns a boolean indicating if more results are available.MapiResponse#nextPage(): Returns a newMapiRequestfor the next page of results.
Example: Reading body and pagination
// Read response body stylesService.getStyle({..}) .send() .then(resp => { const style = resp.body; }); // Handle pagination tilesetsService.listTilesets() .send() .then(resp => { if (resp.hasNextPage()) { const nextPageReq = resp.nextPage(); nextPageReq.send().then(..); } });How MapiRequest works
mainService methods return
MapiRequestobjects. Calling.send()on anMapiRequestreturns a Promise that resolves with anMapiResponseor rejects with anMapiError.Key features of
MapiRequest:MapiRequest#abort(): Aborts the request.MapiRequest#eachPage(callback): Executes a callback for each page of a paginated response. The callback receives(error, response, next).MapiRequest.emitter: An event emitter for progress events likedownloadProgressanduploadProgress.
Example: Aborting and Paginating
// Abort a request const req = tilesetsService.listTilesets(); req.send().then(response => { ... }, error => { ... }); req.abort(); // Paginate through a response tilesetsService.listTilesets().eachPage((error, response, next) => { // Do something with the page if (!response.hasNextPage()) { /* last page reached */ } next(); // Call next() to fetch the next page }); // Listen for upload progress const uploadReq = stylesService.createStyleIcon({..}); uploadReq.on('uploadProgress', event => { // Handle progress }); uploadReq.send();How MapiError works
mainAn
MapiErroris returned when anMapiRequest.send()Promise rejects. This happens if the server returns an error or if the request is aborted.Key properties:
MapiError.type: The type of error (e.g.,'RequestAbortedError').MapiError.statusCode: The HTTP status code (for server errors).MapiError.body: The parsed JSON body of the error response.MapiError.message: A human-readable error message.
Example: Error handling
stylesService.getStyle({..}) .send() .then(response => { ... }, error => { if (error.type === 'RequestAbortedError') { return; } console.error(error.message); });Configure Electric Vehicle routing in Directions API
mainThe Directions API supports electric vehicle routing by setting the
engineparameter to"electric". When using this mode, you must provide several parameters to calculate energy consumption and charging needs:ev_max_charge: Required. Maximum possible charge in Wh.ev_connector_types: Required. Compatible connector types (e.g.,"ccs_combo_type1","tesla").ev_initial_charge: Optional. Initial charge in Wh.energy_consumption_curve: Required. Energy consumption in Wh/km at specific speeds.ev_charging_curve: Required. Maximum battery charging rate (W) at given charge levels.ev_unconditioned_charging_curve: Optional. Charging rate when the battery is unconditioned (e.g., cold).ev_pre_conditioning_time: Optional. Time in minutes for battery conditioning.ev_min_charge_at_destination: Optional. Minimum charge required at the final destination.ev_min_charge_at_charging_station: Optional. Minimum charge required when arriving at a station.auxiliary_consumption: Optional. Continuous power draw of auxiliary systems in watts.
Manage uploads with the Uploads API service
mainThe Uploads service allows you to manage the lifecycle of tileset uploads to Mapbox. The typical workflow involves:
createUploadCredentials: Request S3 credentials (access keys, bucket, and key) to upload your files directly to an S3 bucket.- Upload to S3: Use the provided credentials to upload your data (e.g.,
.mbtilesfiles) to the specified S3 location. createUpload: Notify Mapbox of the upload by providing the tileset ID and the S3 URL of the object you just uploaded.getUpload: Monitor the status of the upload process.listUploads: View the status of all recent uploads.deleteUpload: Remove an upload.
Service method naming conventions
mainWhen implementing service methods, follow these naming conventions to ensure consistency:
- Each method name must contain a verb and the object of that verb.
- Use specific verbs based on the HTTP method:
getandlistforGETrequestscreateforPOSTrequestsupdateforPATCHrequestsputforPUTrequestsdeleteforDELETErequests
- Only use special verbs if a clear title cannot be constructed using the standard verbs above.
Install @mapbox/mapbox-sdk
mainInstall the Mapbox SDK using npm. If you are targeting older browsers, ensure you provide a Promise polyfill (such as
es6-promise).npm install @mapbox/mapbox-sdkHow to use @mapbox/mapbox-sdk
mainUsing the SDK involves three main steps: 1. Create a client, 2. Create a request via a service, and 3. Send the request.
const mbxClient = require('@mapbox/mapbox-sdk'); const mbxStyles = require('@mapbox/mapbox-sdk/services/styles'); const mbxTilesets = require('@mapbox/mapbox-sdk/services/tilesets'); // 1. Create a base client const baseClient = mbxClient({ accessToken: MY_ACCESS_TOKEN }); // 2. Create service clients using the base client const stylesService = mbxStyles(baseClient); const tilesetsService = mbxTilesets(baseClient); // 3. Create and send a request stylesService.createStyle({..}) .send() .then(response => { /* handle success */ }, error => { /* handle error */ }); // Example: List tilesets tilesetsService.listTilesets() .send() .then(response => { /* handle success */ }, error => { /* handle error */ });Check test coverage with Jest
mainTo view test coverage, run Jest with the
--coverageflag.Single run:
npx jest --coverageWatch mode:
npx jest --watchAll --coverageCoverage data is printed to the console and saved to the
coverage/directory. You can view a detailed HTML report by running:open coverage/index.html