I’m facing an issue where, when clicking on a feature on a Mapbox map, it selects the wrong feature, even though the cursor is visually placed over the correct feature. This happens even when I haven’t interacted with the zoom level or made any map changes.
When I click on a feature (e.g., a region or point of interest), the modal opens with data from a feature that is nearby, not the one under the cursor. The cursor appears visually on the correct feature, but the selected feature is incorrect.
This issue is happening even when I don’t zoom in or out — simply by clicking on a feature after loading the map.
const zoomLevel = map.getZoom();
if (zoomLevel > 9) return; // Restrict action for zoom levels greater than 9
// Get features under the cursor
const features = map.queryRenderedFeatures(event.point, {
layers: ['epci']
});
if (features.length === 0) return;
const clickedFeature = features[0];
const epciCode = clickedFeature.properties.code;
const epciName = formatEpciName(clickedFeature.properties.nom);
console.log(`Clicked on feature: ${epciName}, Code: ${epciCode}`);
});
I want to make sure that when I click on a feature, I’m selecting the feature directly under the cursor, not a nearby feature. The issue seems to be with the way the position is being captured, but I am not sure how to address it.
Is there a better way to ensure that the feature selected corresponds accurately to the cursor position on the map, even if it appears shifted?
Thank you
Using map.queryRenderedFeatures(event.point) to capture the features under the cursor.
The problem occurs whether I zoom or not — even after just loading the map and clicking on a feature.
I’ve tried adjusting the zoom level but the issue still persists.
Frame is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.