What is @mapbox/mapbox-sdk?
@mapbox/mapbox-sdk is a JavaScript library that provides a set of tools for interacting with Mapbox APIs. It allows developers to integrate various Mapbox services such as maps, geocoding, directions, and more into their applications.
What are @mapbox/mapbox-sdk's main functionalities?
Static Maps
This feature allows you to generate static map images. The code sample demonstrates how to create a static map image centered on specific coordinates.
const mbxClient = require('@mapbox/mapbox-sdk');
const mbxStatic = require('@mapbox/mapbox-sdk/services/static');
const baseClient = mbxClient({ accessToken: 'YOUR_MAPBOX_ACCESS_TOKEN' });
const staticClient = mbxStatic(baseClient);
staticClient.getStaticImage({
ownerId: 'mapbox',
styleId: 'streets-v11',
width: 600,
height: 400,
position: { coordinates: [-122.42, 37.78], zoom: 14 }
}).send().then(response => {
const image = response.body;
// Do something with the image
});
Geocoding
This feature allows you to convert addresses into geographic coordinates. The code sample demonstrates how to perform forward geocoding to get coordinates for a given address.
const mbxClient = require('@mapbox/mapbox-sdk');
const mbxGeocoding = require('@mapbox/mapbox-sdk/services/geocoding');
const baseClient = mbxClient({ accessToken: 'YOUR_MAPBOX_ACCESS_TOKEN' });
const geocodingClient = mbxGeocoding(baseClient);
geocodingClient.forwardGeocode({
query: '1600 Pennsylvania Ave NW, Washington, DC 20500',
limit: 2
}).send().then(response => {
const match = response.body;
// Do something with the geocoding result
});
Directions
This feature allows you to get driving, walking, or cycling directions between multiple waypoints. The code sample demonstrates how to get driving directions between two sets of coordinates.
const mbxClient = require('@mapbox/mapbox-sdk');
const mbxDirections = require('@mapbox/mapbox-sdk/services/directions');
const baseClient = mbxClient({ accessToken: 'YOUR_MAPBOX_ACCESS_TOKEN' });
const directionsClient = mbxDirections(baseClient);
directionsClient.getDirections({
profile: 'driving',
waypoints: [
{ coordinates: [-122.42, 37.78] },
{ coordinates: [-77.03, 38.91] }
]
}).send().then(response => {
const directions = response.body;
// Do something with the directions
});
Other packages similar to @mapbox/mapbox-sdk
leaflet
Leaflet is an open-source JavaScript library for interactive maps. While it does not provide direct API services like geocoding or directions, it is highly customizable and can be integrated with various mapping services, including Mapbox. It is more focused on rendering and interacting with maps in the browser.
openlayers
OpenLayers is another open-source JavaScript library for displaying map data in web browsers. It supports a wide range of map services and formats. Unlike @mapbox/mapbox-sdk, it does not provide direct API services but is highly flexible for creating custom map applications.
@mapbox/mapbox-sdk
A JS SDK for working with Mapbox APIs.
Works in Node, the browser, and React Native.
As of 6/11/18, the codebase has been rewritten and a new npm package released.
The mapbox
package is deprecated in favor of the new @mapbox/mapbox-sdk
package.
Please read the documentation and open issues with questions or problems.
Table of contents
Installation
npm install @mapbox/mapbox-sdk
If you are supporting older browsers, you will need a Promise polyfill.
es6-promise is a good one, if you're uncertain.
The documentation below assumes you're using a JS module system.
If you aren't, read "Pre-bundled files on unpkg.com".
Usage
There are 3 basic steps to getting an API response:
- Create a client.
- Create a request.
- Send the request.
Creating clients
To create a service client, import the service's factory function from '@mapbox/mapbox-sdk/services/{service}'
and provide it with your access token.
The service client exposes methods that create requests.
const mbxStyles = require('@mapbox/mapbox-sdk/services/styles');
const stylesService = mbxStyles({ accessToken: MY_ACCESS_TOKEN });
You can also share one configuration between multiple services.
To do that, initialize a base client and then pass that into service factory functions.
const mbxClient = require('@mapbox/mapbox-sdk');
const mbxStyles = require('@mapbox/mapbox-sdk/services/styles');
const mbxTilesets = require('@mapbox/mapbox-sdk/services/tilesets');
const baseClient = mbxClient({ accessToken: MY_ACCESS_TOKEN });
const stylesService = mbxStyles(baseClient);
const tilesetsService = mbxTilesets(baseClient);
Creating and sending requests
To create a request, invoke a method on a service client.
Once you've created a request, send the request with its send
method.
It will return a Promise that resolves with a MapiResponse
.
const mbxClient = require('@mapbox/mapbox-sdk');
const mbxStyles = require('@mapbox/mapbox-sdk/services/styles');
const mbxTilesets = require('@mapbox/mapbox-sdk/services/tilesets');
const baseClient = mbxClient({ accessToken: MY_ACCESS_TOKEN });
const stylesService = mbxStyles(baseClient);
const tilesetsService = mbxTilesets(baseClient);
stylesService.createStyle({..})
.send()
.then(response => {..}, error => {..});
tilesetsService.listTilesets()
.send()
.then(response => {..}, error => {..})
Overview of requests, responses, and errors
For more details, please read the full classes documentation.
MapiRequest
Service methods return MapiRequest
objects.
Typically, you'll create a MapiRequest
then send
it.
send
returns a Promise
that resolves with a MapiResponse
or rejects with a MapiError
.
MapiRequest
s also expose other properties and methods that you might use from time to time.
For example:
MapiRequest#abort
aborts the request.MapiRequest#eachPage
executes a callback for each page of a paginated API response.MapiRequest.emitter
exposes an event emitter that fires events like downloadProgress
and uploadProgress
.
For more details, please read the full MapiRequest
documentation.
stylesService.createStyle({..})
.send()
.then(response => {..}, error => {..});
const req = tilesetsService.listTilesets();
req.send().then(response => {..}, error => {
});
req.abort();
tilesetsService.listTilesets().eachPage((error, response, next) => {
if (!response.hasNextPage()) {..}
});
const req = stylesService.createStyleIcon({..});
req.on('uploadProgress', event => {
});
req.send().then(response => {..}, error => {..});
MapiResponse
When you send
a MapiRequest
, the returned Promise
resolves with a MapiResponse
.
Typically, you'll use MapiResponse.body
to access the parsed API response.
MapiResponse
s also expose other properties and methods.
For example:
MapiResponse#hasNextPage
indicates if there is another page of results.- If there is another page,
MapiResponse#nextPage
creates a MapiRequest
that you can send
to get that next page. MapiResponse.headers
exposes the parsed HTTP headers from the API response.
For more details, please read the full MapiResponse
documentation.
stylesService.getStyle({..})
.send()
.then(resp => {
const style = resp.body;
}, err => {..});
tilesetsService.listTilesets()
.send()
.then(resp => {
if (resp.hasNextPage()) {
const nextPageReq = resp.nextPage();
nextPageReq.send().then(..);
}
}, err => {..});
tilesetsService.listTilesets()
.send()
.then(resp => {
console.log(resp.headers);
}, err => {..});
MapiError
If the server responds to your MapiRequest
with an error, or if you abort the request, the Promise
returned by send
will reject with a MapiError
.
MapiError
s expose the information you'll need to handle and respond to the error.
For example:
MapiError.type
exposes the type of error, so you'll know if it was an HTTP error from the server or the request was aborted.MapiError.statusCode
exposes the status code of HTTP errors.MapiError.body
exposes the body of the HTTP response, parsed as JSON if possible.MapiError.message
tells you what went wrong.
For more details, please read the full MapiError
documentation.
stylesService.getStyle({..})
.send()
.then(response => {..}, error => {
if (err.type === 'RequestAbortedError') {
return;
}
console.error(error.message);
});
Services
Please read the full documentation for services.
Pre-bundled files on unpkg.com
If you aren't using a JS module system, you can use a <script>
tag referencing pre-bundled files on the CDN unpkg.com.
<script src="https://unpkg.com/@mapbox/mapbox-sdk/umd/mapbox-sdk.js"></script>
<script src="https://unpkg.com/@mapbox/mapbox-sdk/umd/mapbox-sdk.min.js"></script>
These files are a UMD build of the package, exposing a global mapboxSdk
function that creates a client, initializes all the services, and attaches those services to the client.
Here's how you might use it.
<script src="https://unpkg.com/@mapbox/mapbox-sdk/umd/mapbox-sdk.min.js"></script>
<script>
var mapboxClient = mapboxSdk({ accessToken: MY_ACCESS_TOKEN });
mapboxClient.styles.getStyle(..)
.send()
.then(..);
mapboxClient.tilesets.listTilesets(..)
.send()
.then(..);
</script>
Development
Please read ./docs/development.md
.