# Check if line crosses a polygon

What I'm trying to do is with JSTS to check with `lineGeom.crosses(polygonGeom)` function if a line is crossing completely a polygon.

The problem is that both cases from the picture returns true. I don't know why. Is there another way to check only the first case with line 1.

-
Try if you can split your polygon with a linestring. I am not sure if JTS:intersesction could be used for that tsusiatsoftware.net/jts/javadoc/com/vividsolutions/jts/geom/… – user30184 Jul 26 '14 at 11:53

You need to understand the definition of the spatial predicates. What you're really want is to know if a line traverses the polygon (and not simply cross it)

Using the JTS Topology Suite, you can see that in both cases the predicates are the same: the two lines intersects and crosses the polygon:

and

With the JTS Topology Suite, you can use the Dimensionally Extended nine-Intersection Model (DE-9IM) and the Clementini Matrix:

In the first case it is
1 F 2
0 F 1

And in the second, it is
1 0 2
0 F 1

What does that really mean:

• in the second case the result of the intersection of the boundary of the polygon and the boundary of the line has a dimension of 0 (must obligatorily be one Point, and only one)
• in the first case the result of the intersection of the boundary of the polygon and the boundary of the line has a dimension of F (is not important, 2 Point here)

Therefore you are able to discriminate between the two cases.

``````line.intersection(LinearRing(polygon)) = 1 Point
``````

or

``````line.intersection(LinearRing(polygon)) = 2 Points
``````

### New: if the polygon has holes:

You need to understand the topological definitions of interior, exterior and boundary of a geometry: this is fundamental if you work with JSTS, JTS or GEOS.

1) the polygon

2) the boundary of the polygon in red (LinearRing)

!

3) The result of the intersection of the line and the boundary of the polygon because the holes lie within the interior of the polygon

And the resulting DE-9IM matrix change:

-
What if the polygon has holes? Is it right to think that if number of intersecting points is odd (1,3,5,...) the line does not go trough the whole polygon and represents thus case 2? – user30184 Jul 26 '14 at 14:38
The example given is for your particular case. If the polygon as holes, look above – gene Jul 26 '14 at 15:51
It was not my question. I am just an innocent and curious bystander but thank you for the edited answer anyway. – user30184 Jul 26 '14 at 19:19
The answer of your question is no, because only the boundary of the polygon is concerned. If the number of intersecting points is > 1 (2,3,5), the line go trough the whole polygon at least once. – gene Jul 26 '14 at 20:04
But in practice, the answer is yes for one of the segments of the line (1,3,5,7,...) – gene Jul 26 '14 at 20:16