Check if Point Is Inside A Polygon Check if Point Is Inside A Polygon javascript javascript

Check if Point Is Inside A Polygon


There is a project on Github with code: https://github.com/substack/point-in-polygon (MIT license):

function inside(point, vs) {    // ray-casting algorithm based on    // https://wrf.ecse.rpi.edu/Research/Short_Notes/pnpoly.html/pnpoly.html        var x = point[0], y = point[1];        var inside = false;    for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) {        var xi = vs[i][0], yi = vs[i][1];        var xj = vs[j][0], yj = vs[j][1];                var intersect = ((yi > y) != (yj > y))            && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);        if (intersect) inside = !inside;    }        return inside;};

Usage:

// array of coordinates of each vertex of the polygonvar polygon = [ [ 1, 1 ], [ 1, 2 ], [ 2, 2 ], [ 2, 1 ] ];inside([ 1.5, 1.5 ], polygon); // true

The test function is here: https://github.com/substack/point-in-polygon/blob/master/index.js

Note: This code doesn't work reliably when the point is a corner of the polygon or on an edge. There is an improved version here: https://github.com/mikolalysenko/robust-point-in-polygon


Your polygon array looks like coordinates array in GeoJSON polygon structure (read more at https://macwright.org/2015/03/23/geojson-second-bite.html and http://geojson.org).So maybe you can use libraries which are working with geoJSON data? Look at answer and comments to OP in Is it possible to determine if a GeoJSON point is inside a GeoJSON polygon using JavasScript?

In short, my day was saved by turf (https://github.com/turfjs/turf)There is also d3 (https://github.com/d3/d3-geo#geoContains) but i had issues with it.

UPD:I noticed turf is giving inconsistent results when point is on 'edge' of polygon. I created issue and i am waiting for answer from developers.

UPD2:'Boundary points' issue is resolved by using latest version of turf (i used 3.0.14 instead of 4.6.1). It's all right now.


Here is the function I finally got working. I got it by adopting C code to javascript from here (with explanation).

function checkcheck (x, y, cornersX, cornersY) {    var i, j=cornersX.length-1 ;    var odd = false;    var pX = cornersX;    var pY = cornersY;    for (i=0; i<cornersX.length; i++) {        if ((pY[i]< y && pY[j]>=y ||  pY[j]< y && pY[i]>=y)            && (pX[i]<=x || pX[j]<=x)) {              odd ^= (pX[i] + (y-pY[i])*(pX[j]-pX[i])/(pY[j]-pY[i])) < x;         }        j=i;     }return odd;}

Where cornersX = array with x or latitude vertices array, cornersY = array with y or longitude array. X, Y - latitude and longitude of tested point.