0

I'm trying to use Mapbox Static API through their Javascript SDK. I want to upload an external geojson source to my map. I can't figure out a way to do it. I tried following a Mapbox tutorial called Using style parameters with Static Images API.

Here is my code

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Demo: 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>
    const mapboxClient = mapboxSdk({ accessToken: 'API TOKEN' });

    const addLayerStyle = {
      'id': 'traffic',
      'type': 'line',
      'source': {
        'type': 'geojson',
        //'url': 'mapbox://mapbox.mapbox-traffic-v1'
        //'url': 'https://raw.githubusercontent.com/zaynaib/chicago-elections/main/election_leaflet/data/chicago-wards.geojson'
      },
      'source-layer': 'traffic'
     
    };

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

    document.getElementById('traffic').src = staticImageUrl;
  </script>
</html>
Zaynaib Giwa
  • 5,366
  • 7
  • 21
  • 26

1 Answers1

1

From the docs, "source.url must be a mapbox:// tileset URL, and must be accessible to the access token used in the request. source.type must be either raster or vector"

One solution would be to convert your data to a vector tilest using Tippecanoe then upload your vector file in Mapbox Studio to generate a link that starts with mapbox://

Another option would be to add the GeoJSON to the image as an overlay

dr541
  • 36
  • 2
  • Thank you for your reply. I kind of went into a rabbit whole going through the docs. So I converted my geojson data into a vector tilest using mapbox tiling services (MTS) changing my url to -> 'url': 'mapbox://olad95.chicago_precinct_layer/' . But I got a 422 status code error – Zaynaib Giwa Feb 15 '23 at 20:19
  • I would double check that you're using the correct id. The url should be in the format `mapbox://[YOUR_USERNAME].[TILESET_ID]` it looks like you may be using the tileset name and not the id. The id can be found if you click the 3 dots in studio as well as the studio url https://studio.mapbox.com/tilesets/[YOUR_USERNAME].[TILESET_ID] you'll also want to make sure the `source-layer` is set the the layer name, which can be found in Studio under "Vector layers" – dr541 Feb 15 '23 at 21:52