Created
December 28, 2020 12:01
-
-
Save jhancock532/8335e95eb28edc8359ad955a76bb1065 to your computer and use it in GitHub Desktop.
JavaScript function to check if a point is in a polgyon
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function pointInPolygon(point, vs) { | |
// Taken from https://github.com/substack/point-in-polygon | |
// Nice explainer at https://observablehq.com/@tmcw/understanding-point-in-polygon | |
// ray-casting algorithm based on | |
// http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html | |
let x = point[0], y = point[1]; | |
let inside = false; | |
for (let i = 0, j = vs.length - 1; i < vs.length; j = i++) { | |
let xi = vs[i][0], yi = vs[i][1]; | |
let xj = vs[j][0], yj = vs[j][1]; | |
let intersect = ((yi > y) != (yj > y)) | |
&& (x < (xj - xi) * (y - yi) / (yj - yi) + xi); | |
if (intersect) inside = !inside; | |
} | |
return inside; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment