Skip to content

Instantly share code, notes, and snippets.

@msimpson
Created January 9, 2012 21:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msimpson/1585061 to your computer and use it in GitHub Desktop.
Save msimpson/1585061 to your computer and use it in GitHub Desktop.
Point Inside Polygon
var data = {
polygon: [[0,0], [0,2], [1,3], [2,1], [3,2], [4,0], [3,1], [2,0], [1,1]],
a: [2, 2],
b: [1, 2]
};
function pointInPolygon(polygon, point) {
var len = polygon.length,
x = point[0], y = point[1],
j = len - 1, i = 0, c = 0;
for (i, j; i < len; j = i++) {
y_st = (polygon[i][1] <= y && y < polygon[j][1]) || (polygon[j][1] <= y && y < polygon[i][1]);
x_st = x < (polygon[j][0] - polygon[i][0]) * (y - polygon[i][1]) / (polygon[j][1] - polygon[i][1]) + polygon[i][0];
if (y_st && x_st) c = !c;
}
return c;
}
document.write(pointInPolygon(data.polygon, data.b));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment