Point Inside A Polygon //JavaScript Repository

Description

Checks whether a point is inside a polygon. Adapted from: [http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html]
Created: 2008.03.14

Code (Download)

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/math/is-point-in-poly [rev. #0]

function isPointInPoly(poly, pt){
    for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i)
        ((poly[i].y <= pt.y && pt.y < poly[j].y) || (poly[j].y <= pt.y && pt.y < poly[i].y))
        && (pt.x < (poly[j].x - poly[i].x) * (pt.y - poly[i].y) / (poly[j].y - poly[i].y) + poly[i].x)
        && (c = !c);
    return c;
}

Example (Example)

Click inside and outside of the polygon.

<script type="text/javascript" src="/js/graphical-plotter.js"></script>
<script type="text/javascript">
//<![CDATA[

var length = 50,
points = [
    {x: 0, y: 0},
    {x: 0, y: length},
    {x: length, y: 10},
    {x: -length, y: -10},
    {x: 0, y: -length},
    {x: 0, y: 0}
];

var canvas = new Canvas;
canvas.pen.color = "#f00";
canvas.pixelSize = 5;

canvas.moveTo(length, length);
for(var i = points.length; i--; canvas.lineTo(length + points[i].x, length + points[i].y));

document.onclick = function(e){
    function getMouse(e){
        var w = window, b = document.body;
        return {x: e.clientX + (w.scrollX || b.scrollLeft || b.parentNode.scrollLeft || 0),
        y: e.clientY + (w.scrollY || b.scrollTop || b.parentNode.scrollTop || 0)};
    }
    var m = getMouse(e || event);
    alert(isPointInPoly(points, {x: m.x / canvas.pixelSize - length, y: m.y / canvas.pixelSize - length}) ? "In" : "Out");
}

//]]>
</script>

Help

isPointInPoly(polygon: Array, point: Object): Boolean
Checks whether the point is inside the polygon.
polygon
array of points, each element must be an object with two properties (x and y)
point
point, object with two properties (x and y)

Rank (Votes: 1574)

4.96