[GIS] MapBox GL API: Add ‘property’ to ‘source’ to update map feature colors with dynamic data

choroplethmapboxmapbox-gl-js

SUMMARY: I need to color code lines based on information not attached to the dataset in the style. How do I do this? Below is a suggested path, but apparently it may be the wrong direction to solve my problem.

DETALS:
I'd like to color-code a layer in the map with data that is not already attached to the source; it is coming from somewhere else.

I'd like to use similar code below to dynamically add a new 'property', i.e. newPopulation, that does not already exist in the source, i.e. populationSource.

How do I add a new property and values to a source, i.e. populationSource.

map.addLayer({
    'id': 'state-population',
    'source': 'populationSource',
    'source-layer': 'state_county_population_2014_cen',
    'maxzoom': zoomThreshold,
    'type': 'fill',
    'filter': ['==', 'isState', true],
    'paint': {
        'fill-color': {
            property: 'newPopulation',
            stops: [
                [0, '#F2F12D'],
                [500000, '#EED322'],
                [750000, '#E6B71E'],
                [1000000, '#DA9C20'],
                [2500000, '#CA8323'],
                [5000000, '#B86B25'],
                [7500000, '#A25626'],
                [10000000, '#8B4225'],
                [25000000, '#723122']
            ]
        },
        'fill-opacity': 0.75
    }
}, 'waterway-label');

Best Answer

Consider the following after map loads - the event is "moveend"

Ex:

map.on('moveend', function() {

    $.ajax({
        type : 'GET',
        url : urlz,
        async : false,

        dataType : 'json',
        success : function(data2) {
            console.log(data2);
            // SET THE DATA AGAIN FROM AJAX CALL
            map.getSource('populationSource').setData(data2);
        },
        error : function(e) {
            alert('error');
            console.log(e);
        }
    })
})

Basically, when the map is zoomed or moved , the above will AJAX get call a .json file from a url and will UPDATE the mapsource with the new data and will re-render the map - you could also do this in an AJAX post way that queries a stored procedure that would dynamically return the data you need to redraw the map.

Related Question