Skip to content

Instantly share code, notes, and snippets.

@johannesboyne
Created May 22, 2013 09:04
Show Gist options
  • Save johannesboyne/5626235 to your computer and use it in GitHub Desktop.
Save johannesboyne/5626235 to your computer and use it in GitHub Desktop.
Test whether a point lies inside a polygon
// borrowd from http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
function pnpoly (points, test) {
var i, j, c = false;
for( i = 0, j = points.length-1; i < points.length; j = i++ ) {
if( ( ( points[i].y > test.y ) != ( points[j].y > test.y ) ) &&
( test.x < ( points[j].x - points[i].x ) * ( test.y - points[i].y ) / ( points[j].y - points[i].y ) + points[i].x ) ) {
c = !c;
}
}
return c;
}
// input:
// - pnpoly([{x: 0, y: 0}, {x: 10, y: 0}, {x: 10, y: 10}, {x: 0, y: 10}], {x: 5, y: 5});
// output:
// - true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment