Avoid queryRenderedFeatures erroring out on non existing layers

226 Views Asked by At

I have upgraded an app to the last version of mapbox-gl-js and it broke it.

queryRenderedFeatures has changed and now it errors out on non existing layers.

For multiple reasons, we cannot predict which layers will exist at this point (some are built dynamically).

Is there any way to work around this behaviour ?

Basically we'd like to be able to do the below (one of the layers is there on not) and still get a result.

Thx, JM

features = map.queryRenderedFeatures([{
    x: x1,
    y: y1
}, {
    x: x2,
    y: y2
}], {
    layers: [
        'Layer A',
        'Possibly non existing Layer B',
        'Layer C'
    ]
});
1

There are 1 best solutions below

1
On BEST ANSWER

You could could filter out layers that don't exist like this:

features = map.queryRenderedFeatures(
    [{x: x1, y: y1}, {x: x2, y: y2}], 
    {layers: 
       ['Layer A', 'Possibly non existing Layer B', 'Layer C']
       .filter((layer)=>{map.getLayer(layer)})]
});

That should avoid triggering an error

https://jsfiddle.net/o8fLvh7e/