ImClarky
ImClarky

Reputation: 1953

How can I use a custom font in Mapbox GL JS?

I am using Mapbox GL JS (v2.8.0) to programmatically add a Style layer to my map, and I am trying to use a set of fonts that I have uploaded to my map via the Mapbox Studio.

I currently have this inside my code for my Style layer:

const layer = {
    id: this.getLayerId(),
    type: 'symbol',
    layout: {
        'text-field': ['get', 'name'],
        'text-font': [
            "Chakra Petch Italic", // My custom font inside Mapbox
            "Arial Unicode MS Regular" // Fallback font
        ]
    },
    paint: {
        'text-color': '#ffffff',
    }
}

However when it comes to rendering my map, I am getting 404 errors in relation to trying to fetch my font.

It is trying to fetch the font from the following url:

https://api.mapbox.com/fonts/v1/mapbox/Chakra%20Petch%20Italic,Arial%20Unicode%20MS%20Regular/0-255.pbf?access_token={access_token} 

And I believe this issue here is that instead of /mapbox/ it should be /{username}/ as when I go to the following url in the browser:

https://api.mapbox.com/fonts/v1/{username}/Chakra%20Petch%20Italic,Arial%20Unicode%20MS%20Regular/0-255.pbf?access_token={access_token} 

I correctly get the .pbf data.

How am I able to specify that it should look under my username, rather than the public mapbox user, in my style layer json?


Additionally, as a test, if I create a simple layer inside Mapbox Studio - and set a label to use the custom font, in the Network tab in devtools I can see it fetching the font using the username url above. And unfortunately the "code inspector" in the Studio for this label shows the same two string array as I have inside my code.

Upvotes: 4

Views: 4654

Answers (1)

Steve Bennett
Steve Bennett

Reputation: 126355

You need to set the glyphs property of your style:

   }, glyphs: 'mapbox://fonts/yourusername/{fontstack}/{range}.pbf'
}

More info: https://docs.mapbox.com/mapbox-gl-js/style-spec/glyphs/

Upvotes: 3

Related Questions