Exploring the Mapbox API with JavaScript

Mapbox is a popular mapping platform that offers a range of APIs for developers to integrate maps and location-based features into their applications. In this blog post, we'll take a closer look at some of the APIs offered by Mapbox and explore how to use them in JavaScript.

Getting Started

Before we can start using the Mapbox APIs, we need to sign up for a free account on the Mapbox website. Once we have an account, we can create a new project and generate an access token that we'll use to authenticate our API requests.

Mapbox GL JS

One of the most popular APIs offered by Mapbox is Mapbox GL JS, a JavaScript library for creating interactive, customizable maps. Let's take a look at some example code for creating a basic map using Mapbox GL JS:

<!DOCTYPE html>
<html>
<head>
  <meta charset='utf-8' />
  <title>Mapbox GL JS example</title>
  <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
  <script src='https://api.mapbox.com/mapbox-gl-js/v2.1.1/mapbox-gl.js'></script>
  <link href='https://api.mapbox.com/mapbox-gl-js/v2.1.1/mapbox-gl.css' rel='stylesheet' />
  <style>
    body { margin: 0; padding: 0; }
    #map { position: absolute; top: 0; bottom: 0; width: 100%; }
  </style>
</head>
<body>
  <div id='map'></div>
  <script>
    mapboxgl.accessToken = 'YOUR_ACCESS_TOKEN';
    var map = new mapboxgl.Map({
      container: 'map',
      style: 'mapbox://styles/mapbox/streets-v11',
      center: [-122.4194, 37.7749],
      zoom: 13
    });
  </script>
</body>
</html>

In this code, we first include the Mapbox GL JS library and stylesheet in the head of our HTML document. We then create a simple HTML layout for our map and add a <div> element with the id "map" where our map will be displayed.

In the JavaScript section of our code, we set our access token using the mapboxgl.accessToken property. We then create a new mapboxgl.Map object and pass in options for our map including the container where it will be displayed, the base style we want to use, the initial center coordinates, and the initial zoom level.

Mapbox Geocoding API

Another useful API offered by Mapbox is their Geocoding API, which allows us to convert addresses and place names to geographic coordinates (latitude and longitude) and vice versa. Here's an example of how to use the Geocoding API in JavaScript:

const accessToken = 'YOUR_ACCESS_TOKEN';

const geocodingEndpoint = 'https://api.mapbox.com/geocoding/v5/mapbox.places/';

const searchQuery = 'Los Angeles, CA';

const requestUrl = geocodingEndpoint + encodeURIComponent(searchQuery) + '.json?access_token=' + accessToken;

fetch(requestUrl)
  .then(response => response.json())
  .then(data => {
    const firstResult = data.features[0];
    const { center } = firstResult.geometry;
    console.log(`Latitude: ${center[1]} Longitude: ${center[0]}`);
  })
  .catch(error => console.error(error));

In this code, we first set our access token as a constant. We then construct the URL for our Geocoding API request by concatenating the base endpoint URL with our search query, encoded using the encodeURIComponent function, and our access token.

We then use the fetch function to make the API request and parse the response as JSON. We extract the latitude and longitude coordinates of the first result returned by the API using destructuring assignment and log them to the console.

Conclusion

In this blog post, we've explored two of the APIs offered by Mapbox and seen how to use them in JavaScript. With these APIs and many more available from Mapbox and other providers, the possibilities for creating engaging, location-based applications are nearly endless.

Related APIs