Mapbox SDK for JavaScript

repository·main·Indexed 20 days ago

https://github.com/mapbox/mapbox-sdk-js

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

Tokens
18.2K
Snippets
59
Records
81
Agent score
72%

What's inside @mapbox/mapbox-sdk

  1. Manage Tilesets with the Tilesets API

    main
    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.
  2. How MapiResponse works

    main

    An MapiResponse is the object returned when an MapiRequest.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 new MapiRequest for 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(..);
        }
      });
  3. How MapiRequest works

    main

    Service methods return MapiRequest objects. Calling .send() on an MapiRequest returns a Promise that resolves with an MapiResponse or rejects with an MapiError.

    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 like downloadProgress and uploadProgress.

    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();
  4. How MapiError works

    main

    An MapiError is returned when an MapiRequest.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);
      });
  5. Configure Electric Vehicle routing in Directions API

    main

    The Directions API supports electric vehicle routing by setting the engine parameter 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.
  6. Manage uploads with the Uploads API service

    main

    The Uploads service allows you to manage the lifecycle of tileset uploads to Mapbox. The typical workflow involves:

    1. createUploadCredentials: Request S3 credentials (access keys, bucket, and key) to upload your files directly to an S3 bucket.
    2. Upload to S3: Use the provided credentials to upload your data (e.g., .mbtiles files) to the specified S3 location.
    3. createUpload: Notify Mapbox of the upload by providing the tileset ID and the S3 URL of the object you just uploaded.
    4. getUpload: Monitor the status of the upload process.
    5. listUploads: View the status of all recent uploads.
    6. deleteUpload: Remove an upload.
  7. Service method naming conventions

    main

    When 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:
      • get and list for GET requests
      • create for POST requests
      • update for PATCH requests
      • put for PUT requests
      • delete for DELETE requests
    • Only use special verbs if a clear title cannot be constructed using the standard verbs above.
  8. How to use @mapbox/mapbox-sdk

    main

    Using 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 */ });
  9. Check test coverage with Jest

    main

    To view test coverage, run Jest with the --coverage flag.

    Single run:

    npx jest --coverage

    Watch mode:

    npx jest --watchAll --coverage

    Coverage 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