Check if one polygon crosses another polygon in Turf.js

Viewed 1785

I'm using Turf.js for advanced geospatial analysis in my application, but can not find a method which checks if two polygons cross one another. Intersect method is not what I want, since if I have a tiny polygon and want to find polygon that crosses this tiny polygon, this method will return big overlapping polygons, that contain this smaller polygon.

Let me explain it visually. So, this is the polygon, that I have:

enter image description here

In this case, polygons intersect each other:

enter image description here

And in this case, I consider, that they do not intersect:

enter image description here

In the last case, the border of the green polygon does not cross the smaller polygon, so they do not intersect.

And my question is, if it is possible to implement this kind of intersection function in Turf.js?

4 Answers

You just need to check if the red polygon is contain to the green polygon, if it's true put intersection to false.

You can additionally check this turf.booleanContains(poly1, poly2)

const poly1 = turf.polygon(polygon1)
const poly2 = turf.polygon(polygon2)
intersected = turf.booleanWithin(poly1, poly2)

It will return true if poly1 {in your case it is red polygon} is completely inside poly2 {In your case it is green polygon}. If they just intersect and do not contain by parent poly then it will return false.

Check This turf doc for more details

For anyone looking for a solution to this problem. You can use booleanOverlap to determine whether two polygons intersect.

const p0 = turf.polygon([[
  [0, 0],
  [0, 1],
  [1, 1],
  [1, 0],
  [0, 0]
]]);

const p1 = turf.polygon([[
  [0, 0],
  [0, 2],
  [0.5, 2],
  [0.5, 0],
  [0, 0]
]])

const p2 = turf.polygon([[
  [-2, -2],
  [-2, 2],
  [2, 2],
  [2, -2],
  [-2, -2]
]])

const p3 = turf.polygon([[
  [10, 10],
  [10, 11],
  [11, 11],
  [12, 12],
  [11, 10],
  [10, 10]
]]);

console.log(turf.booleanOverlap(p0, p0)); // false
console.log(turf.booleanOverlap(p0, p1)); // ture
console.log(turf.booleanOverlap(p0, p2)); // false
console.log(turf.booleanOverlap(p0, p3)); // false


Related