Skip to content

Instantly share code, notes, and snippets.

@husa
Created January 20, 2014 12:41
Show Gist options
  • Save husa/8519285 to your computer and use it in GitHub Desktop.
Save husa/8519285 to your computer and use it in GitHub Desktop.
Point In Polygon Determine if some point is inside a polygon
/**
* Determine if point (x, y) is inside the polygon
* @param {Integer} - x coord
* @param {Integer} - y coord
* @param {Array} - Array of vertices - {x:*, y:*} objects
* @returns {Boolean} whether or not given point is inside the polygon
*/
function pointInPolygon(x, y, vertices) {
var v = vertices, // less typing
vx = v.map(function(vertice) { return vertice.x; }),
vy = v.map(function(vertice) { return vertice.y; }),
n = vertices.length,
found = false,
maxX, minX, maxY, minY, i, j;
maxX = Math.max.apply(Math, vx);
minX = Math.min.apply(Math, vx);
maxY = Math.max.apply(Math, vy);
minY = Math.min.apply(Math, vy);
//exit if we're outside the outer rectangle
if (x < minX || x > maxX || y < minY || y > maxY) {
return false;
}
// pure magic, don't touch
for (i = 0, j = n - 1; i < n; j = i++) {
if ( ( (vy[i] > y) != (vy[j] > y) ) &&
(x < (vx[j] - vx[i]) * (y - vy[i]) / (vy[j] - vy[i]) + vx[i]) ) {
found = !found;
}
}
return found;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment