javascriptmapboxmapbox-gl-jsturfjs

Turf booleanPointInPolygon always returns false


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.


Solution

  • 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)