Using style parameters with the Static Images API

intermediate
JavaScript
Prerequisite

Familiarity with front-end development concepts.

This tutorial demonstrates how you can use style parameters to apply custom styles to a map from the Mapbox Static Images API.

Getting started

To complete this tutorial, you will need:

Using the Static Images API

The Static Images API returns static map images generated from styles. The API accepts parameters that define the way your static image will look. One optional parameter, addLayer, allows you to add a layer to the static image at render time. One advantage of adding a layer at render time is styling it based on data. You may want to use addLayer when your data is dynamic and you want the map to reflect the state of that data at any given time.

Create the example HTML page

In this tutorial, you will build a webpage that displays an image of current traffic conditions around New York City. The page uses JavaScript to assemble a Static Images API request, and inserts that request URL into the image src. The basic structure is:

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="robots" content="noindex, nofollow" />
    <meta
      name="viewport"
      content="initial-scale=1,maximum-scale=1,user-scalable=no"
    />
    <title>Static images with style parameters</title>
    <script src="https://unpkg.com/@mapbox/mapbox-sdk/umd/mapbox-sdk.min.js"></script>
    <style>
      .container {
        text-align: center;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <img id="traffic" src="" alt="Mapbox traffic map" />
    </div>  
</body>
<script></script>
</html>

Using your text editor, create a new HTML file and paste the code snippet above into the file. This template code loads Mapbox SDK JS and provides the structure for your page, including an <img> element that you will use later on to add your static image to the page. The <script> tag at the bottom is where you will use JavaScript to assemble the API request.

The aim of the script in this tutorial is to request a static image that adds the traffic layer from the Mapbox traffic tileset to the Mapbox Light style. The resulting image will change slightly every time the traffic data is updated. Whenever the webpage loads, the latest traffic will be displayed. The addLayer parameter allows you to create static images with dynamic data.

Initialize the Mapbox JavaScript SDK

This webpage loads the Mapbox JavaScript SDK in the <head>. This SDK helps build and send requests to Mapbox APIs. It also includes functions to handle responses from those Mapbox APIs. To initialize the SDK, you first need to create a service client to handle authentication and allow you to interact with various Mapbox services. Add the following line insde the <script> tag to create a service client:

var mapboxClient = mapboxSdk({ accessToken: 'YOUR_MAPBOX_ACCESS_TOKEN' });

Define the style of the traffic layer

The next step is to define the traffic layer. This is done in a similar way that you would add a layer using map.addLayer() in Mapbox GL JS.

    var addLayerStyle = {
      'id': 'traffic',
      'type': 'line',
      'source': {
        'type': 'vector',
        'url': 'mapbox://mapbox.mapbox-traffic-v1'
      },
      'source-layer': 'traffic',
      'paint': {
        'line-color': [
          'match',
          ['get', 'congestion'],
          'heavy',
          '#2c7fb8',
          'moderate',
          '#7fcdbb',
          'low',
          '#edf8b1',
          'white'
        ],
        'line-width': 3
      }
    };

When using the addLayer parameter, your layer can come from one of two places: your style or an external source. When referencing an external source, you can use your own tileset or any other tileset that you can access with your account. In this tutorial, you will add a layer from the Mapbox Traffic v1 tileset, which is available to all Mapbox users.

Any time you use the addLayer parameter, you will need to supply a source-layer. If the layer is already in your style, the source would normally be composite, and the source-layer would be the name of the layer in Studio. If the layer does not exist in the style already, the source-layer can be found on the tileset's information page in Mapbox Studio. To add an external source, follow this pattern:

      'source': {
        'type': 'vector',
        'url': 'mapbox://{username}.{tileset_id}'
      }

The paint properties define how the layer should look. In this case, the paint properties determine what color the line should be based on its attribute data using data-driven styling and a match expression.

Prepare the API request

Use the mapboxClient you created when initializing the JS SDK to prepare and send the request.

    var request = mapboxClient.static
      .getStaticImage({
        ownerId: 'mapbox',
        styleId: 'light-v10',
        width: 500,
        height: 350,
        position: {
          coordinates: [-73.99, 40.73],
          zoom: 12
        },
        addlayer: addLayerStyle,
      before_layer: 'road-label',
      });
    var staticImageUrl = request.url();

This code uses the getStaticImage method of the static client service to assemble the API request. The parameters of that method define:

  • the user account
  • the map style
  • the size of the image
  • the position of the map
  • the layer object you want to add
  • the layer's position in the drawing order of the map layers

After the request is defined, assign the request .url to a new variable.

Set the image source to be the request URL

Finally, assign the image source with the encoded request URL.

  document.getElementById('traffic').src = staticImageUrl;

The final HTML file will look like the following:

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="robots" content="noindex, nofollow" />
    <meta
      name="viewport"
      content="initial-scale=1,maximum-scale=1,user-scalable=no"
    />
    <title>Static images with style parameters</title>
    <script src="https://unpkg.com/@mapbox/mapbox-sdk/umd/mapbox-sdk.min.js"></script>
    <style>
      .container {
        text-align: center;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <img id="traffic" src="" alt="Mapbox traffic map" />
    </div>
  </body>
  <script>
    var mapboxClient = mapboxSdk({ accessToken: 'YOUR_MAPBOX_ACCESS_TOKEN' });

    var addLayerStyle = {
      'id': 'traffic',
      'type': 'line',
      'source': {
        'type': 'vector',
        'url': 'mapbox://mapbox.mapbox-traffic-v1'
      },
      'source-layer': 'traffic',
      'paint': {
        'line-color': [
          'match',
          ['get', 'congestion'],
          'heavy',
          '#2c7fb8',
          'moderate',
          '#7fcdbb',
          'low',
          '#edf8b1',
          'white'
        ],
        'line-width': 3
      }
    };

    var request = mapboxClient.static
      .getStaticImage({
        ownerId: 'mapbox',
        styleId: 'light-v10',
        width: 500,
        height: 350,
        position: {
          coordinates: [-73.99, 40.73],
          zoom: 12
        },
        addlayer: addLayerStyle,
      before_layer: 'road-label',
      });
    var staticImageUrl = request.url();

    document.getElementById('traffic').src = staticImageUrl;
  </script>
</html>

Was this page helpful?