Thursday, 31 May 2018

geotools - Coordinate conversion (EPSG:3857 to EPSG:4326) using OpenGIS/JTS too slow


I am using the Java based libraries of OpenGIS and JTS to convert coordinates from EPSG:3857 to EPSG:4326 to proceed to compute the distance using the Haversine formula. The distance features in a constraint on whether to zoom in further on a map or not.


We are using a tangible user interface and depend on the reactivity of the system. Unfortunately, the conversion is quite slow which induces even more delay than loading the map from a server. Would there be a less costly way to proceed with the conversion using local resources?


        CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:4326");
CoordinateReferenceSystem sourceCRS = CRS.decode("EPSG:3857");
MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS, false);
GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), 3857);
Point minPoint = geometryFactory.createPoint(new Coordinate(xMin, yMin));
Point minTargetPoint = (Point) JTS.transform(minPoint, transform);

Point maxPoint = geometryFactory.createPoint(new Coordinate(xMax, yMax));
PointmaxTargetPoint = (Point) JTS.transform(maxPoint, transform);

Answer



You can use the GeodeticCalculator which should be faster. Something like:


package com.envitia.spike;

import org.geotools.geometry.DirectPosition2D;
import org.geotools.referencing.CRS;
import org.geotools.referencing.GeodeticCalculator;
import org.opengis.referencing.FactoryException;

import org.opengis.referencing.NoSuchAuthorityCodeException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.TransformException;

public class ZoomChecker {

CoordinateReferenceSystem sourceCRS;

GeodeticCalculator calc;


public ZoomChecker() throws NoSuchAuthorityCodeException, FactoryException {
this("EPSG:3857");
}

public ZoomChecker(String code) throws NoSuchAuthorityCodeException, FactoryException {

sourceCRS = CRS.decode(code);
calc = new GeodeticCalculator(sourceCRS);

}


public double check(final double minX, final double minY, double maxX, double maxY)
throws TransformException {

calc.setStartingPosition(new DirectPosition2D(minX, minY));
calc.setDestinationPosition(new DirectPosition2D(maxX, maxY));
return calc.getOrthodromicDistance();
}

public static void main(String[] args) throws NoSuchAuthorityCodeException, FactoryException,

TransformException {
ZoomChecker checker = new ZoomChecker("EPSG:27700");
double d = checker.check(0.0, 0.0, 0.0, 10000.0);
System.out.println(d);
d = checker.check(0.0, 0.0, 10000.0, 0.0);
System.out.println(d);
}
}

This gives a reasonable distance calculation of 9984m over the 10km in the test.



No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...