3

sorry for my english but i'm italian... i would like to create a code that calculate if point (with two coordinates) is inside polygon with concave and convex angles. I tried few codes because is too difficult..

 var polygon = [ 
  [71.99999994,38.999999714],
  [71.000000057,38.999999714],
  [69.999999998,38.999999714],
  [69.999999998,38.000000007],
  [68.999999939,38.000000007],
  [67.99999988,38.000000007],
  [67.99999988,38.999999714],
  [67.99999988,39.999999597],
  [68.999999939,39.999999597],
  [68.999999939,41.000000008],
  [69.999999998,41.000000008],
  [71.000000057,41.000000008],
  [71.99999994,41.000000008],
  [71.99999994,39.999999597],
  [71.99999994,38.999999714]
 ];

  var point= [68,38.5];

I hope that you can help me...

Thanks a lot

Borja
  • 3,359
  • 7
  • 33
  • 66
  • Possible duplicate of [How can I determine whether a 2D Point is within a Polygon?](http://stackoverflow.com/questions/217578/how-can-i-determine-whether-a-2d-point-is-within-a-polygon) – pablochan Feb 25 '17 at 15:25

1 Answers1

5

The algo is based on this site: http://alienryderflex.com/polygon/
It is superfast and handle various polygon types. I have tuned it to javascript and to your data structure.

    function IsPointInPolygon(poly_array, test_point) {
        var inside = false;
        var test_x = test_point[0];
        var test_y = test_point[1];
        for(var i=0; i<(poly_array.length-1); i++) {
            var p1_x = poly_array[i][0];
            var p1_y = poly_array[i][1];
            var p2_x = poly_array[i+1][0];
            var p2_y = poly_array[i+1][1];
            if((p1_y<test_y && p2_y>=test_y) || (p2_y<test_y && p1_y>=test_y)) { // this edge is crossing the horizontal ray of testpoint
                if((p1_x+(test_y-p1_y)/(p2_y-p1_y)*(p2_x-p1_x)) < test_x) { // checking special cases (holes, self-crossings, self-overlapping, horizontal edges, etc.)
                    inside=!inside;
                }
            }
        }
        return inside;
    }

You can call it directly with your variables:

    if(IsPointInPolygon(polygon, point)) {
        alert('Inside');
    }
    else {
        alert('Outside');
    }
Geza Boehm
  • 116
  • 7
  • It works very well.... i have only one doubt "test_point[0]" and "poly_array[i][0]" is longitude and than the other ([1]) latitude...true? – Borja Feb 28 '17 at 15:17
  • You wrote the coordinates in arrays, like `testpoint = [68,38.5];` So the testpoint[0] will be 68, testpoint[1] will be 38.5 and I do not know what you meant with these values. Anyway, even if you swap coordinates, the polygon inclusion will work. Just use one of them (for example longitude) in the 0 index, while the other (latitude) will be in index 1 – Geza Boehm Feb 28 '17 at 18:11