Skip to content

Commit d31f20a

Browse files
refactor: use maplibre method to find current division
1 parent 938ac60 commit d31f20a

File tree

1 file changed

+11
-27
lines changed

1 file changed

+11
-27
lines changed

src/components/map/divisionUtils.js

Lines changed: 11 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -30,38 +30,22 @@ export function debounce(fn, delay = 300) {
3030
}
3131
}
3232

33-
// Find division that contains the given coordinates
33+
// Find division that contains the given coordinates using MapLibre's queryRenderedFeatures
3434
export function findDivisionByCoordinates(map, lngLat) {
35-
if (!map || !map.getSource('divisions') || !map.getSource('divisions')._data) {
35+
if (!map) {
3636
return null;
3737
}
3838

39-
const point = [lngLat.lng, lngLat.lat];
40-
const features = map.getSource('divisions')._data.features;
39+
// Query features at the point
40+
const features = map.queryRenderedFeatures(
41+
map.project([lngLat.lng, lngLat.lat]),
42+
{ layers: ['divisions-fill'] }
43+
);
4144

42-
// Find the first division polygon that contains the point
43-
const containingFeature = features.find(feature => {
44-
if (feature.geometry.type !== 'Polygon') return false;
45-
return pointInPolygon(point, feature.geometry.coordinates[0]);
46-
});
47-
48-
return containingFeature ? containingFeature.properties.DIVISION_NUM : null;
49-
}
50-
51-
// Helper function to check if a point is inside a polygon
52-
function pointInPolygon(point, polygon) {
53-
const [x, y] = point;
54-
let inside = false;
55-
56-
for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
57-
const [xi, yi] = polygon[i];
58-
const [xj, yj] = polygon[j];
59-
60-
const intersect = ((yi > y) !== (yj > y)) &&
61-
(x < (xj - xi) * (y - yi) / (yj - yi) + xi);
62-
63-
if (intersect) inside = !inside;
45+
// Return the division number of the first matching feature
46+
if (features.length > 0) {
47+
return features[0].properties.DIVISION_NUM;
6448
}
6549

66-
return inside;
50+
return null;
6751
}

0 commit comments

Comments
 (0)