Skip to content

Commit

Permalink
refactor: use maplibre method to find current division
Browse files Browse the repository at this point in the history
  • Loading branch information
themightychris committed Nov 11, 2024
1 parent 938ac60 commit d31f20a
Showing 1 changed file with 11 additions and 27 deletions.
38 changes: 11 additions & 27 deletions src/components/map/divisionUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

0 comments on commit d31f20a

Please sign in to comment.