1

I want to check if a point is in a polygon:

if (turf.booleanPointInPolygon(pt, poly_coordinates)) {
    console.log("INSIDE");
} else {
    console.log("OUTSIDE");
}

JSON.stringify(console.log(pt)) displays:

{"type":"Feature","properties":{},"geometry":{"type":"Point","coordinates":[2.1362996,41.391026000000004]}}

JSON.stringify(console.log(poly_coordinates)) displays:

[[[2.1666008868967594,41.420742231455876],[2.1423966327457435,41.39486355482066],[2.159906093195218,41.38185595077573],[2.1666008868967594,41.420742231455876]]]

NOTE: Everything is in longitude,latitude format.

Why is it booleanPointInPolygon returning false? This particular case is just an example point and an example polygon which might be outside the polygon. However, it doesn't matter if the polygon contains the entire world, booleanPointInPolygon still returns false for any point.

fbu_94
  • 19
  • 6

2 Answers2

2

If that's your code, then the problem is that poly_coordinates is not a polygon, it's just the coordinates part of one.

You should have something like:

const poly = { type: 'Polygon', coordinates: poly_coordinates }
turf.booleanPointInPolygon(pt, poly)
Steve Bennett
  • 114,604
  • 39
  • 168
  • 219
  • That solved it. Nevertheless, I want to understand why my attempt did not work. My coordinates for the polygon have exactly the same format as the example in the [documentation](https://www.npmjs.com/package/@turf/boolean-point-in-polygon) of `booleanPointInPolygon`. – fbu_94 Apr 26 '20 at 16:11
  • In that example, the array is first being passed to `turf.polygon()` which does the same thing as I added. – Steve Bennett Apr 26 '20 at 16:41
2

Hi you can also use this

var pt = turf.point([1, 1]);
var poly = turf.polygon([
    [
        [-1, -1],
        [-1, 1],
        [1, 1],
        [-1, -1]
    ]
]);

var inside = turf.pointsWithinPolygon(pt, poly);
Robert S
  • 626
  • 6
  • 13