wottpal
2/10/2018 - 9:28 AM

isPointInPolygon(point, polygon)

exp-027

  • point is array of two coordinates
  • polygon is array of multiple points
  • returns true/false either if the point is inside the given polygon or not
// Source: https://github.com/substack/point-in-polygon
function isPointInPolygon(point, polygon) {
    var x = point[0], y = point[1];

    var inside = false;
    for (var i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
        var xi = polygon[i][0], yi = polygon[i][1];
        var xj = polygon[j][0], yj = polygon[j][1];

        var intersect = ((yi > y) != (yj > y))
            && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
        if (intersect) inside = !inside;
    }

    return inside;
}