Dec 16

MapboxGL is not defined error solution

Some time it happens that we are using mapboxgl and reference it directly without includig its liberay files in headerand we are getting an error mapboxgl is not defined.

for ex: you are using below code in your website, but it throwss error mapboxgl is not defined

mapboxgl.accessToken = mapToken;
    const map = new mapboxgl.Map({
        container: 'map', // container ID
        style: 'mapbox://styles/mapbox/streets-v11', // style URL
        center: [-74.5, 40], // starting position [lng, lat]
        zoom: 9 // starting zoom
<div id='map' style='width: 400px; height: 300px;'></div>
Include mapbox-gl in your header
<script src=''></script>
<link href='' rel='stylesheet' />

now, this will load Mapbox script and script weill add mapboxgl reference in to global scope and your code will start using mapboxgl.

if your code is complex you can add your custom loader to load mapboxgl script and then run your code

Use custom script loader
// add loader function
    var JavaScript = {
        load: function(src, callback) {
            var script = document.createElement('script'),
            script.setAttribute('src', src);
            if (callback) {
              script.onreadystatechange = script.onload = function() {
                if (!loaded) {
                loaded = true;

    // use it
    JavaScript.load("", function() {

        // initialise your mapbox here    
        mapboxgl.accessToken = 'pk.<your_key>';
        var map = new mapboxgl.Map({
         container: mapParent,
         style: 'mapbox://styles/mapbox/streets-v9'

if you face such an issue and if this blog helps you to solve it please comment and share your experience.