Skip to content

Commit

Permalink
feat: update isPointInPolygon method
Browse files Browse the repository at this point in the history
  • Loading branch information
F-star committed May 19, 2024
1 parent 41fa25a commit 27dfc05
Showing 1 changed file with 5 additions and 15 deletions.
20 changes: 5 additions & 15 deletions packages/geo/src/geo/geo_polygon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export const isPointInConvexPolygon = (polygon: IPoint[], point: IPoint) => {
};

export const isPointInPolygon = (polygon: IPoint[], pt: IPoint): boolean => {
let count = 0;
let isIn = false;
for (let i = 0; i < polygon.length; i++) {
let a = polygon[i];
let b = polygon[(i + 1) % polygon.length];
Expand All @@ -68,25 +68,15 @@ export const isPointInPolygon = (polygon: IPoint[], pt: IPoint): boolean => {
}

if (a.y <= pt.y && b.y > pt.y) {
const crossProduct = cp(a, b, pt);
const crossProduct =
(pt.x - a.x) * (b.y - a.y) - (b.x - a.x) * (pt.y - a.y);
if (crossProduct === 0) {
return true;
} else if (crossProduct > 0) {
count++;
isIn = !isIn;
}
}
}

return count % 2 === 1;
};

/**
* cross product of "p1->p2" and "p1->p3"
*/
const cp = (p1: IPoint, p2: IPoint, p3: IPoint): number => {
const x1 = p2.x - p1.x;
const y1 = p2.y - p1.y;
const x2 = p3.x - p1.x;
const y2 = p3.y - p1.y;
return x1 * y2 - x2 * y1;
return isIn;
};

0 comments on commit 27dfc05

Please sign in to comment.