Skip to content

Instantly share code, notes, and snippets.

@jhancock532
Created December 28, 2020 12:01
Show Gist options
  • Save jhancock532/8335e95eb28edc8359ad955a76bb1065 to your computer and use it in GitHub Desktop.
Save jhancock532/8335e95eb28edc8359ad955a76bb1065 to your computer and use it in GitHub Desktop.
JavaScript function to check if a point is in a polgyon
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