[GIS] Calculate distance with JTS

javajts-topology-suitepostgis

I'm trying to get the distance between two points with JTS.
The problem is that this function with JTS

new Coordinate(Lon1,Lat1).distance(new Coordinate(Lon2,Lat2))

Is giving a different result from this function used in postgis(wich provides the good distance)

ST_Distance_Sphere(point1,point2)

Best Answer

The short answer is you can't do that unless your points are very close together and you want the answer in degrees. JTS knows nothing about units or the curvature of the earth. So you need to pull in some GeoTools jars that do know about such things. Then you can create a method like:

private void calculateDistance(CoordinateReferenceSystem crs, Point[] points) {
    if (crs == null) {
        crs = default_crs;
    }

    double distance = 0.0;
    try {
        distance = JTS.orthodromicDistance(
            points[0].getCoordinate(),
            points[1].getCoordinate(),
            crs
        );
    } catch (TransformException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Measure<Double, Length> dist = Measure.valueOf(distance, SI.METER);
    System.out.println(dist.doubleValue(SI.KILOMETER) + " Km");
    System.out.println(dist.doubleValue(NonSI.MILE) + " miles");
}

Which will take care of all the hard maths for you. The full example program can be seen here.