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

<script>
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
    });
</script>
<div id='map' style='width: 400px; height: 300px;'></div>
Include mapbox-gl in your header
<script src='https://api.mapbox.com/mapbox-gl-js/v2.6.0/mapbox-gl.js'></script>
<link href='https://api.mapbox.com/mapbox-gl-js/v2.6.0/mapbox-gl.css' 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
<script>
    var JavaScript = {
        load: function(src, callback) {
            var script = document.createElement('script'),
                loaded;
            script.setAttribute('src', src);
            if (callback) {
              script.onreadystatechange = script.onload = function() {
                if (!loaded) {
                  callback();
                }
                loaded = true;
              };
            }
            document.getElementsByTagName('head')[0].appendChild(script);
        }
    };

    // use it
    JavaScript.load("https://api.mapbox.com/mapbox-gl-js/v0.39.1/mapbox-gl.js", function() {

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

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

Ad
Ad