In MapLibre GL JS, to search for features on a specific layer, you typically use the queryRenderedFeatures or querySourceFeatures methods on the map object.
1. queryRenderedFeatures
This method returns features that are currently rendered in the visible viewport.
You can filter by layer and by a bounding box or point.
It only returns features that are currently visible on the map (i.e., within the viewport and rendered).
Example:
js
// Query features rendered in the current viewport on a specific layer
const features = map.queryRenderedFeatures({
layers: ['your-layer-id']
});
console.log(features);
Or query features at a specific point or bounding box:
js
// Query features at a point (e.g., mouse click)
const featuresAtPoint = map.queryRenderedFeatures([x, y], {
layers: ['your-layer-id']
});
2. querySourceFeatures
This method queries features directly from the source, regardless of whether they are currently rendered or visible.
It can return all features in the source, but only if the source supports it (e.g., vector tile sources).
It does not take a viewport or geometry parameter, but you can filter by source layer and filter expressions.
queryRenderedFeatures: Returns features currently visible/rendered on the map. You can filter by layer and geometry.
querySourceFeatures: Returns features directly from the source, potentially all features, but only for vector tile sources and with some limitations.
Will it give all features?
queryRenderedFeatureswill NOT give all features if some are outside the viewport or not rendered.
querySourceFeaturescan give all features from the source layer, but only if the source supports it (e.g., vector tiles). It does not work for GeoJSON sources or raster sources.
If you want to search all features in a GeoJSON source, you would typically access the GeoJSON data directly (e.g., from your source data object) rather than using these query methods.
If you want, I can provide a code snippet tailored to your specific use case!