I am using GeoTools to convert X and Y coordinates into points and get the distance between two points. I know that my coordinates are EPSG:32630 Name:WGS 84 / UTM zone 30N (https://epsg.io/32630). Then I created this small test to check the distance between two points. I am not sure if I am converting the X and Y coordinates correctly. And when I transform it to Points it throws an exception.
Coordinate coordRad01 = new Coordinate(729664.353, 4373064.801);
Coordinate coordRad02 = new Coordinate(730021.116, 4373070.406);
Coordinate coordPoi01 = null;
Coordinate coordPoi02 = null;
MathTransform transformRadiusToPoint;
try {
CoordinateReferenceSystem radiusCRS = CRS.decode("EPSG:32630", true);
CoordinateReferenceSystem pointCRS = CRS.decode("EPSG:4326", true);
DirectPosition dp01 = JTS.toDirectPosition(coordRad01, radiusCRS);
DirectPosition dp02 = JTS.toDirectPosition(coordRad02, radiusCRS);
System.out.println("DirectPosition dp01: " + dp01 + " dp02: " + dp02);
Double distance = JTS.orthodromicDistance(coordRad01, coordRad02, radiusCRS);
System.out.println("Distance: " + distance + " meters");
transformRadiusToPoint = CRS.findMathTransform(pointCRS, radiusCRS);
coordPoi01 = JTS.transform(coordRad01, coordPoi01, transformRadiusToPoint);
coordPoi02 = JTS.transform(coordRad02, coordPoi02, transformRadiusToPoint);
distance = JTS.orthodromicDistance(coordPoi01, coordPoi02, pointCRS);
System.out.println("Distance: " + distance + " meters");
} catch (NoSuchAuthorityCodeException e) {
e.printStackTrace();
} catch (FactoryException e) {
e.printStackTrace();
} catch (TransformException e) {
e.printStackTrace();
}
error:
DirectPosition dp01: JTS.[729664.353, 4373064.801] dp02: JTS.[730021.116, 4373070.406]
Distance: 356.7176800591084 meters
Jul 23, 2019 12:40:26 PM org.geotools.referencing.operation.projection.TransverseMercator transform
WARNING: Possible use of "Transverse_Mercator" projection outside its valid area.
Longitude 729304°21.2'E is out of range (±180°).
Latitude 4372704°48.0'N is out of range (±90°).
Exception in thread "main" java.lang.IllegalArgumentException: Longitude 5449761°17.2'E is out of range (±180°).
at org.geotools.referencing.GeodeticCalculator.checkLongitude(GeodeticCalculator.java:406)
at org.geotools.referencing.GeodeticCalculator.setStartingGeographicPoint(GeodeticCalculator.java:549)
at org.geotools.referencing.GeodeticCalculator.setStartingPosition(GeodeticCalculator.java:591)
at org.geotools.geometry.jts.JTS.orthodromicDistance(JTS.java:635)
at org.sense.flink.pojo.Point.main(Point.java:105)
Best Answer
TLDR; You have your transform backwards, you want to go from transverse mercator to WGS84 so it needs to be:
But you shouldn't need to convert to a geographic projection just to get the distance if your points are already in a planar/projected projection (CRS). I would simply use Pythagoras:
This then gives:
Which all agree nicely.