Editing a source in a Layer

Hi, I am having some troubles changing the source in a layer.
If I initialize my layer as:

routeLayer = map.addLayer({
‘id’ : ‘route’,
‘type’ : ‘line’,
‘source’ : {},
‘paint’ : {
‘line-color’ : ‘blue’,
‘line-width’ : 4,
}
});

What should I do in order to change the source to something like {type: ‘geojson’, data: geodata}

Hello! Thanks for using our Web SDK :slight_smile:

I’m not exactly sure what is your use case, but in general, if you want to change the source of the layer, you need to remove it from the map, change its source, and add it back.

Here’s the example of such operation:

// save a reference to the layer's object - it will make manipulation easier
var route = {
	‘id’ : ‘route’,
	‘type’ : ‘line’,
	‘source’ : {},
	‘paint’ : {
		‘line-color’ : ‘blue’,
		‘line-width’ : 4,
	}
};

// add the layer to the map
map.addLayer(route);

// if you want to change the source, you need to remove the layer first
map.removeLayer('route');

// change the layer's source, by mutating "source" property layer's object
route.source = YOUR_NEW_SOURCE_GOES_HERE;

// add the layer back
map.addLayer(route);

One extra remark - map.addLayer() method does not return the layer instance - it returns the map object (for methods chaining purposes).

Hope it helps :slight_smile: