Quick and dirty coordinate transforming using GeoTools.

Posted by – Monday 2012-08-13

In this post we will how to transform 2D coordinates from one coordinate reference system (CRS) to another one using the open source, Java library GeoTools.

In the first section a code snippet is shown, and in the second one the list of needed jars is given.

1. The code.

The following Java code snippet transforms a set of coordinates (x, y) expressed in the ETRS 89, UTM zone 29N (EPSG code 25829) coordinate system to WGS84 (EPSG code 4326). The source coordinates are stored in the variables x and y, and the result is left in the variables transX and transY.

import org.geotools.geometry.DirectPosition2D;

import org.geotools.referencing.CRS;

import org.opengis.referencing.crs.CoordinateReferenceSystem;

import org.opengis.referencing.operation.MathTransform;


CoordinateReferenceSystem sourceCrs = CRS.decode("EPSG:25829");
CoordinateReferenceSystem targetCrs = CRS.decode("EPSG:4326");

double x = (double) 636497.59434;
double y = (double) 4778964.017375;

boolean lenient = true;
MathTransform mathTransform 
    = CRS.findMathTransform(sourceCrs, targetCrs, lenient);

DirectPosition2D srcDirectPosition2D 
    = new DirectPosition2D(sourceCrs, x, y);
DirectPosition2D destDirectPosition2D 
    = new DirectPosition2D();
mathTransform.transform(srcDirectPostion2D, destDirectPosition2D);

double transX = destDirectPosition2D.x;
double transY = destDirectPosition2D.y;

The coordinate transform is actually done by the instance of the interface MathTransform. It must be noted that the transform is searched with the lenient (line #17) parameter set to true. This relaxes the accuracy of the calculations when transforming coordinates. In case lenient is set to false, the parameters required to calculate a Bursa-Wolf transformation [note 1] must be provided.

2. What jars are needed?

GeoTools is a huge piece of software made of several jars. As of version 2.7.4 of Geotools, the whole set of jars weight more than 43 MB. Thus, using just the needed jars is desirable.

The list of needed jars for the previous code snippet is the shown below:

  • gt-metadata-2.7.4.jar
  • gt-opengis-2.7.4.jar
  • gt-referencing-2.7.4.jar
  • jsr-275-1.0-beta-2.jar
  • vecmath-1.3.2.jar

And additional jar, not present in downloadable GeoTools package, is needed: jai_core.jar, which provides Java Advanced Image [note 2, 3].


[note 1] In the section 1.2.1 of “3D affine coordinate transformations” an explanation of this transformation can be found.

[note 2] The Java Advanced Imaging Core Library can be downloaded from http://goo.gl/p9o2v.

[note 3] It seems that this dependency will be removed in future versions of GeoTools.

0 Comments on Quick and dirty coordinate transforming using GeoTools.