Created
October 3, 2011 00:16
-
-
Save zz85/1258163 to your computer and use it in GitHub Desktop.
Point in Polgon
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
// https://github.com/zz85/ | |
// implements Point - in - Polygon | |
// described in "A Winding Number and Point-in-Polygon Algorithm" | |
// returns 0 if point is not in polygon | |
// returns n > 0 if contour winds around point in counter-clockwise manner n times | |
// returns n < 0 if contour winds around point in clockwise manner -n times | |
function pointInPolygon(point, contour) { | |
// Creates a copy of contour | |
var adjustedContour = []; | |
var i,il; | |
for (i=0, il=contour.length; i<il; i++ ) { | |
adjustedContour[i] = contour.clone().subSelf(point); | |
} | |
var w = 0; // Init winding number to 0; | |
var j; | |
for (i=0, j=1;i<il;i++,j++) { | |
if (j==il) { | |
j = 0; | |
} | |
var v1 = adjustedContour[i]; | |
var v2 = adjustedContour[j]; | |
if (v1.y * v2.y < 0) { | |
// line crosses x axis | |
var r = v1.x + v1.y * (v2.x - v1.x)/(v1.y - v2.y); | |
// r is x-coordinate intersection of v1-v2 with x axis | |
if (r>0) { | |
// line cross positive x-axis | |
if (v1.y<0) { | |
w++; | |
} else { | |
w--; | |
} | |
} | |
} else if ((v1.y==0) && (v1.x > 0)) { | |
// v1 is on positive x axis | |
if (v2.y > 0 ) { | |
w += 0.5; | |
} else { | |
w -= 0.5; | |
} | |
} else if ((v2.y==0) && (v2.x>0)) { | |
// v2 is on the positive x axis | |
if (v1.y < 0) { | |
w += 0.5; | |
} else { | |
w -= 0.5; | |
} | |
} | |
} | |
return w; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment