The code from the previous question does in fact solve this problem once you have explored the issue a bit.
Basically your line doesn't have enough points so it "cuts" the corner across the more localised projection that is used to allow JTS to proceed as if the Earth is flat. This needs one additional line of code:
route = (LineString) Densifier.densify(route, .01);
The brown line is your original 3 point line and the blue line is a densified line (that has points added so it projects properly), shown in a local projection (EPSG:2470). As you can see the distance to the brown line to the point is much shorter than it should be.
So here is some suitably modified code:
public double getDistance(Point point, LineString line) {
double dist = -1.0;
try {
String code = "AUTO:42001," + point.getX() + "," + point.getY();
CoordinateReferenceSystem auto = CRS.decode(code);
// auto = CRS.decode("epsg:2470");
MathTransform transform = CRS.findMathTransform(DefaultGeographicCRS.WGS84, auto);
Geometry g3 = JTS.transform(line, transform);
Geometry g4 = JTS.transform(point, transform);
Coordinate[] c = DistanceOp.nearestPoints(g4, g3);
Coordinate c1 = new Coordinate();
//System.out.println(c[1].distance(g4.getCoordinate()));
JTS.transform(c[1], c1, transform.inverse());
//System.out.println(geometryFactory.createPoint(c1));
dist = JTS.orthodromicDistance(point.getCoordinate(), c1, DefaultGeographicCRS.WGS84);
} catch (Exception e) {
e.printStackTrace();
}
return dist;
}
And incase you are wondering about the difference between the "flat distance" (c[1].distance(g4.getCoordinate())
) is 760.731km and the "curved distance" (JTS.orthodromicDistance(point.getCoordinate(), c1, DefaultGeographicCRS.WGS84);
) is 760.980km. For reference the distance tool in QGIS gives 760.919 km.
Best Answer
JTS's DistanceOP#nearestPoints might be an easy way. I have not tested it.
http://tsusiatsoftware.net/jts/javadoc/com/vividsolutions/jts/operation/distance/DistanceOp.html#nearestPoints%28com.vividsolutions.jts.geom.Geometry,%20com.vividsolutions.jts.geom.Geometry%29