Mapbox queryRenderedFeatures does not work as expected with bbox

Viewed 227

I would like to get all features within a drawn polygon. In order to avoid iterating over all features of my layer, I constrain the queried features with a bbox. I calculate the bbox with the turf library.

However, the returned features do not correspond to the required bbox.

Attached you can see in the picture:

  • In blue: the calculated bbox
  • in red: the returned features from the queryRenderedFeatures() query.

Selected Features in bbox

import bbox from '@turf/bbox';

const bboxGeom = bbox(drawGeometry);

// convert to pixels for queryRenderedFeatures()
const southWest = map.project([bboxGeom[0], bboxGeom[1]]);
const northEast = map.project([bboxGeom[2], bboxGeom[3]]);
const box = [[southWest.x, southWest.y], [northEast.x, northEast.y]];
const features = map.queryRenderedFeatures(
   box, { layers: ['myLayer'] },
);
1 Answers

My guess is that your box is interpreted as a line, from the bottom left to the top right corner. Try to project and supply all coordinates of bboxGeom instead.

Related