Mapbox-gl-js: Method to change a layer's source

Created on 13 Nov 2015  路  4Comments  路  Source: mapbox/mapbox-gl-js

Need a method for changing a layer's source. Currently, we need to remove and re-add the layer with the new source.

feature

Most helpful comment

In case anyone else finds this, here's some code for you:

function setLayerSource (layerId, source, sourceLayer) {
    const oldLayers = map.getStyle().layers;
    const layerIndex = oldLayers.findIndex(l => l.id === layerId);
    const layerDef = oldLayers[layerIndex];
    const before = oldLayers[layerIndex + 1] && oldLayers[layerIndex + 1].id;
    layerDef.source = source;
    if (sourceLayer) {
        layerDef['source-layer'] = sourceLayer;
    }
    map.removeLayer(layerId);
    map.addLayer(layerDef, before);
}

It's included in mapbox-gl-utils.

All 4 comments

I think you should just remove and re-add the layer. Any implementation inside gl-js would do just that.

In case anyone else finds this, here's some code for you:

function setLayerSource (layerId, source, sourceLayer) {
    const oldLayers = map.getStyle().layers;
    const layerIndex = oldLayers.findIndex(l => l.id === layerId);
    const layerDef = oldLayers[layerIndex];
    const before = oldLayers[layerIndex + 1] && oldLayers[layerIndex + 1].id;
    layerDef.source = source;
    if (sourceLayer) {
        layerDef['source-layer'] = sourceLayer;
    }
    map.removeLayer(layerId);
    map.addLayer(layerDef, before);
}

It's included in mapbox-gl-utils.

try:
const U = require('mapbox-gl-utils').init(map);
map.U.setData('mysource', data);
this worked for me, thanks to @stevage

Oh, the method I was referring to is the setLayerSource one:

map.U.setLayerSource('mylayer', 'mynewsource')

Was this page helpful?
0 / 5 - 0 ratings

Related issues

samanpwbb picture samanpwbb  路  3Comments

foundryspatial-duncan picture foundryspatial-duncan  路  3Comments

rasagy picture rasagy  路  3Comments

aaronlidman picture aaronlidman  路  3Comments

yoursweater picture yoursweater  路  3Comments