From d31f20aead71a14850ac83bf828d22d1f252aade Mon Sep 17 00:00:00 2001 From: Chris Alfano Date: Mon, 11 Nov 2024 02:03:20 -0500 Subject: [PATCH] refactor: use maplibre method to find current division --- src/components/map/divisionUtils.js | 38 +++++++++-------------------- 1 file changed, 11 insertions(+), 27 deletions(-) diff --git a/src/components/map/divisionUtils.js b/src/components/map/divisionUtils.js index 35d26ea..aadbb39 100644 --- a/src/components/map/divisionUtils.js +++ b/src/components/map/divisionUtils.js @@ -30,38 +30,22 @@ export function debounce(fn, delay = 300) { } } -// Find division that contains the given coordinates +// Find division that contains the given coordinates using MapLibre's queryRenderedFeatures export function findDivisionByCoordinates(map, lngLat) { - if (!map || !map.getSource('divisions') || !map.getSource('divisions')._data) { + if (!map) { return null; } - const point = [lngLat.lng, lngLat.lat]; - const features = map.getSource('divisions')._data.features; + // Query features at the point + const features = map.queryRenderedFeatures( + map.project([lngLat.lng, lngLat.lat]), + { layers: ['divisions-fill'] } + ); - // Find the first division polygon that contains the point - const containingFeature = features.find(feature => { - if (feature.geometry.type !== 'Polygon') return false; - return pointInPolygon(point, feature.geometry.coordinates[0]); - }); - - return containingFeature ? containingFeature.properties.DIVISION_NUM : null; -} - -// Helper function to check if a point is inside a polygon -function pointInPolygon(point, polygon) { - const [x, y] = point; - let inside = false; - - for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { - const [xi, yi] = polygon[i]; - const [xj, yj] = polygon[j]; - - const intersect = ((yi > y) !== (yj > y)) && - (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - - if (intersect) inside = !inside; + // Return the division number of the first matching feature + if (features.length > 0) { + return features[0].properties.DIVISION_NUM; } - return inside; + return null; }