2

I have built a website using Mapbox GL JS to display a number of layered routes and points on a map to track different teams progress on a route. However when testing on a large number of page reloads the tracks on the map along with a number of other page elements sometimes don't load and I get a Style is not done loading error.

Code Extract:

var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/outdoors-v11',
center: [15, 50],
zoom: 4 // zoom range is 0 (the whole world) to 22 (street level)
});

var distanceContainer = document.getElementById('distance');

// GeoJSON object to hold our measurement features
var geojson = {
'type': 'FeatureCollection',
'features': []
};
var finishPoint = {
'type': 'FeatureCollection',
'features': []
};
var progressLine = {
'type': 'FeatureCollection',
'features': []
};

map.on('load', function () {
var routeLineString = getRoute();

var line = routeLineString;

var options = {units: 'kilometers'};
var endPoint = turf.along(line, turf.length(line), options);

map.addSource('route-source', {
    'type': 'geojson',
    'data': line
});

// Add styles to the map. Style layer: A style layer ties together the source and image and specifies how they are displayed on the map.
// 'line-color': '#0C7CBB', // dark cyan
// NHS blue: 005EB8
map.addLayer({
    'id': 'route',
    'type': 'line',
    'source': 'route-source',
    'layout': {
        'line-join': 'round',
        'line-cap': 'round'
    },
    'paint': {
        'line-color': '#000000',
        'line-width': 3
    }
},"team1RouteProgress");  // placement of this line below the progress line layer

// destination marker
map.loadImage("https://i.imgur.com/MK4NUzI.png", function (error, image) {
    if (error) throw error;
    map.addImage("finish-flag", image);
    map.addSource('finish-source', {
        'type': 'geojson',
        'data': finishPoint
    }); 
    map.addLayer({
        id: 'finish',
        type: 'symbol',
        source: 'finish-source',
        layout: {
            "icon-image": "finish-flag",
            'icon-anchor': "bottom"
        }
    });
}); 

finishPoint.features.push(endPoint);
//map.getSource('geojson').setData(geojson);

});

$(document).ready(function() {
// Clear the Distance container to populate it with a new value
distanceContainer.innerHTML = '';

var line = getRoute();
var options = {units: 'kilometers'};


$.ajax({    //create an ajax request to getProgress.php
    type: "GET",
    url: "./php/getTeamProgress.php",
    dataType: "json",   //expect json to be returned
    data: {
        //access_key: access_key,
    },
    success: function (response) {
        var Teams_arr = [];
        var dist_arr = [];
        var colour_arr = [];
        response.data.forEach(function (dat) {
            Teams_arr.push(dat.team);
            dist_arr.push(dat.distance);
            //Colour Setting
            if(dat.team === "Typhoon Squadron"){
                colour_arr.push("purple");
            }else if (dat.team === "Gloucester Penguins; for Ben"){
                colour_arr.push("red");
            }else if (dat.team === "Community"){
                colour_arr.push("yellow");
            }else if(dat.team === "HMS Grimsby"){
                colour_arr.push("navy");
            }else if(dat.team === "Thunderer Squadron"){
                colour_arr.push("blue");
            }else{
                colour_arr.push("grey");
            }

        });

        //alert(response.totaldist);
        var distStart = 0;

        //Team 1
        var team1DistAlongRoute = dist_arr[0]
        var team1Along = turf.along(line, team1DistAlongRoute, options);
        if (team1DistAlongRoute<0.1) {
            team1DistAlongRoute = 0.1; // prevent error in lineSliceAlong if dist = 0
        }
        var team1SliceLine = turf.lineSliceAlong(line, distStart, team1DistAlongRoute, {units: 'kilometers'});

        map.addSource('team1progress-source', {
            'type': 'geojson',
            'data': team1SliceLine
        });
        map.addLayer({
            'id': 'team1RouteProgress',
            'type': 'line',
            'source': 'team1progress-source',
            'layout': {
                'line-join': 'round',
                'line-cap': 'round'
            },
            'paint': {
                'line-color': colour_arr[0],
                'line-width': 5
            }
        });

        // Progress marker- Purple
        // Image: An image is loaded and added to the map.

        map.loadImage("./assets/black.png", function (error, image) {
            if (error) throw error;
            map.addImage("team1custom-marker", image);
            map.addSource('geojson', {
                'type': 'geojson',
                'data': geojson
            });
            map.addLayer({
                id: 'team1Progress',
                type: 'symbol',
                source: 'geojson',
                layout: {
                    "icon-image": "team1custom-marker",
                    'icon-anchor': "bottom"
                }
            });
        });

        geojson.features.push(team1Along);
        progressLine.features.push(team1SliceLine);

        //Team 2

        var team2DistAlongRoute = dist_arr[1]
        var team2Along = turf.along(line, team2DistAlongRoute, options);
        if (team2DistAlongRoute<0.1) {
            team2DistAlongRoute = 0.1; // prevent error in lineSliceAlong if dist = 0
        }
        var team2SliceLine = turf.lineSliceAlong(line, distStart, team2DistAlongRoute, {units: 'kilometers'});

        map.addSource('team2progress-source', {
            'type': 'geojson',
            'data': team2SliceLine
        });
        map.addLayer({
            'id': 'team2RouteProgress',
            'type': 'line',
            'source': 'team2progress-source',
            'layout': {
                'line-join': 'round',
                'line-cap': 'round'
            },
            'paint': {
                'line-color': colour_arr[1],
                'line-width': 5
            }
        });

        geojson.features.push(team2Along);
        progressLine.features.push(team2SliceLine);

etc etc

3 Answers 3

2

The quick fix:

map = new Mapboxgl.map({ ... })
map.on('load', () => {
   ...add all your `addSource()`, `addLayer()` etc here.
});
Sign up to request clarification or add additional context in comments.

Comments

1

The 'Style is not done loading' error is thrown by the _checkLoaded method in Mapbox GL JS's style.js. This method is called each time a modification is made to the style -- for example when the Map#addSource and Map#addLayer methods are called. In addition to making use of the map#on('load', function() {}) listener to ensure that all necessary map resources are loaded before attempting to make a modification to the map's style, you could also take a look at some of these examples from our documentation, which demonstrate strategies for updating map sources and layers dynamically:

  1. Update a feature in realtime.
  2. Add live realtime data.
  3. Using the GeoJSONSource#setData method to update an existing source's data and re-render the map.
  4. Change a layer's color with buttons.

Comments

0

Since this question is 3yrs old, the solution may have changed - was able to get the styles to update/change by adding the following wrapper (note the addition of 'style.' before the load):

map.on('style.load', function() {
    // Modify layout property
    map.setLayoutProperty('topcities', 'visibility', 'none');
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.