Algorithm to determine whether a point is inside a polygon
Copy the pointIsInsidePolygon function code from point-is-inside-polygon.js and include it in your code.
const point = {x: 100, y: 100};
const polygon = [
{x: 20, y: 125},
{x: 12, y: 100},
{x: 75, y: 30}
];
const position = pointIsInsidePolygon(point, polygon);
-
point: An object with 2 keys:
- x: X-coordinate of the point.
- y: Y-coordinate of the point.
-
polygon: An array of the polygon's points. Each point is an object with 2 keys:
- x: X-coordinate of the point.
- y: Y-coordinate of the point.
- If the first argument point was not provided correctly it will return this error object:
{error: 'First argument should be a point with (x & y) coordinates'}
- If the second argument polygon was not provided correctly it will return this error object:
{error: 'Second argument should be an array of at least 3 points with (x & y) coordinates'}
-
If both arguments were provided correctly it will return an object with 3 keys:
- isInside (boolean):
true
if the point was inside the polygon, andfalse
if not. - isOutside (boolean):
true
if the point was outside the polygon, andfalse
if not. - isOnBorder (boolean):
true
if the point was on the border of the polygon, andfalse
if not.
- isInside (boolean):
{isInside: boolean, isOutside: boolean, isOnBorder: boolean}
The relative position of the point to the polygon will be determined based on number of intersections between the polygon & the horizontal line drawn starting from the point toward increasing the x-axis.
-
If number of intersections was odd, then the point is inside the polygon.
-
If number of intersections was even, then the point is outside the polygon.
Clone the repository and run index.html in your browser to test it.
Yaser Somaf https://github.com/yasershomaf yasershomaf@gmail.com |