2

I have a sequence of coordinates (lat,lng) defining a route.

How can I determine whether this route is self intersecting?

I am trying to implement a Java method for this, but I have been unsuccessful so far.

1 Answer 1

3

A JTS LineString will return false for isSimple() if it intersects.

For these 2 lines (good on the left, bad on the right) the following code prints:

valid: true simple: true
valid: true simple: false

enter image description here

import org.geotools.geometry.jts.WKTReader2;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.io.ParseException;

public class JTSSelfIntersection {
  public static void main(String[] args) throws ParseException {
    String good = "LineString (-1.47009569377990434 0.45454545454545459, -0.94138755980861233 0.65311004784688997, -0.61124401913875603 0.31100478468899528, -0.91985645933014348 -0.15789473684210531, -1.2380382775119616 0.23444976076555024, -1.47966507177033479 0.14593301435406703)";
    String bad = "LineString (-0.21172248803827753 0.72248803827751196, 0.17583732057416257 0.6004784688995215, -0.09449760765550241 0.11004784688995217, -0.19258373205741619 0.44976076555023925, 0.18540669856459346 0.34688995215311003)";

    WKTReader2 wktr = new WKTReader2();
    LineString gLine = (LineString) wktr.read(good);
    LineString bLine = (LineString) wktr.read(bad);
    System.out.println("valid: " + gLine.isValid() + " simple: " + gLine.isSimple());
    System.out.println("valid: " + bLine.isValid() + " simple: " + bLine.isSimple());
  }
}
2
  • Thanks Ian. Doesn't LineString expect cartesian coordinates x,y instead of lat,lon? I have been struggling with JTS today, but unfortunately with no success: stackoverflow.com/q/53853211/4828060 Dec 19, 2018 at 16:26
  • Well sort of, those are lat/lon coords I have given there. Technically you should probably reproject to a local cartesian plane for full accuracy but for a simple self intersection you should be fine
    – Ian Turton
    Dec 19, 2018 at 16:32

Not the answer you're looking for? Browse other questions tagged or ask your own question.