Search code examples
mapbox-gl-js

How do you retrieve a static map image with an added style layer with a geojson source using Mapbox?


Here is my defined layer and this works perfectly adding the geojson layer to my map. But I want a static image of the map with the geosjson layer using the mapbox static api. I have been trying to understand these docs from mapbox https://docs.mapbox.com/api/maps/static-images/

My code:

//Source

map.addSource('geojson', {
            type: 'geojson',
            // Use a URL for the value for the `data` property.
            data: 'https://raw.githubusercontent.com/visgl/deck.gl-data/master/examples/geojson/vancouver-blocks.json'
        });

//Layer

 let addLayerStyle = {
            'id': 'geojson-layer',
            'type': 'circle',
            'source': 'geojson',
            'paint': {
                'circle-opacity': 0.05,
// Make circles larger as the user zooms from z12 to z22.
                'circle-radius': {
                    'base': 1.75,
                    'stops': [
                        [12, 2],
                        [22, 180]
                    ]
                },
// Color circles by ethnicity, using a `match` expression.
                'circle-color': [
                    'match',
                    ['get', 'id'],
                    'relation/3824359',
                    '#fbb03b',
                    'relation/3834297',
                    '#223b53',
                    'relation/3871090',
                    '#e55e5e',
                    'relation/3871091',
                    '#3bb2d0',
                    /* other */ '#ccc'
                ]
            }
        }
        map.addLayer(addLayerStyle)

This works fine on my map as shown in the attached image.

enter image description here

According to the docs I should be able to add url parameter called addlayer

Here is my url

        let mylayer = JSON.stringify(addLayerStyle)
        console.log(mylayer)
        let url = 'https://api.mapbox.com/styles/v1/mapbox/streets-v12/static/-123.0249569,49.2407190,11/500x300?access_token=pk.D_ngzR7j4vU1CILtpNLg4Q&addlayer=' + mylayer

I am getting an error msg "message": "Invalid layer passed to addlayer. Unable to parse JSON."

Also, I do not understand how this would work since it does not appear to be passing the actual source with the geojson to the request.


Solution

  • You have to encode the string before you append it to the URL.

    The # from the color strings breaks the URL.

    # needs to be encoded as %23 in the URL making #223b53 become %23223b53