I understand it's an old post but putting the notes for someone it can help!
So, how do I get the source
for querySourceFeatures()?
Here's the one-liner:
map.querySourceFeatures('composite', {sourceLayer: 'source-name', filter: [filters]})
So - what is composite
, what is sourceLayer
, what is filter
?
Well first, we need to get to the composite
source id and pass that to source
param. Then we get the tileset id
of the layer we are working on and pass that to sourceLayer
param. And finally, get the applied filters on the layer we are working on and pass that to filter
param.
To start with, we need to have the composite source id from the layer or the layer that you are working with:
// get the source from the layer, `mapLayerId` is the layer id
// this can be found in Mapbox Studio's styles editor
// or use your layer id if you created in the code
var compositeSource = map.getLayer(mapLayerId.toString()).source;
Then to get the tileset id
, we need to get what it's called the vectorlayer from that source, so:
console.log(map.getSource(compositeSource).vectorLayers);
The vectorslayers
is essentially an JS object and contains all the tilesets that we have in Mapbox Studio.
Now, if we are dealing with only the latest
vector layer, like me - because in my Mapbox Studio that's the tileset I created and all other tilesets are default ones and I am not using them, it will appear on the last element of the object. In this case, we can grab the last element of the returned object of vectorslayers
and get its id
, this id is the actual tileset id
.
var compositeVectorLayerLength = map.getSource(compositeSource).vectorLayers.length - 1;
console.log(compositeVectorLayerLength);
// sourceId === tileset id which is known as vector layer id
var sourceId = map.getSource(compositeSource).vectorLayers[compositeVectorLayerLength].id;
We then get all the filters that were already applied on the layer we are working with:
var appliedFilters = map.getFilter(mapLayerId.toString());
console.log(appliedFilters);
Now, we call querySourceFeatures() passing all these values:
var resultFeatures = map.querySourceFeatures(compositeSource, {sourceLayer: sourceId, filter: appliedFilters});
The resultFeatures
will be a JS object which will have all the features on the map.