Created
January 20, 2014 12:41
-
-
Save husa/8519285 to your computer and use it in GitHub Desktop.
Point In Polygon
Determine if some point is inside a polygon
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
/** | |
* 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