[GIS] GeoToolKit conversion from lat/long to UTM

coordinate systemjava

What is the proper way to convert lat/longs to a UTM coordinate system using the Java geotoolkit API? I have not worked with GIS software before, so maybe what I am trying to do is not directly possible. I found a few tutorials, but nothing with the full solution.

Best Answer

I figured it out. Here is the solution in case anyone else is interested. UTM is not a single projection, but actually a set of 120 different UTM zones. The zones are divided in 6 deg increments starting at -180 deg longitude, continuing to 180 deg longitude. This creates 60 zones, and since there is a northern and southern zone for each range, the total becomes 120.

Update: As mentioned below, this is a simplification of the UTM standard, and will not be accurate for a few unique regions around Norway.

The next hurdle is then converting the UTM zone to the EPSG database code, so it can be retrieved using the geotoolkit API. The code makes it clear how the EPSG code can be reached, once you've figured out the UTM zone.

private static int utm_zone( double _long ){
  assert _long > -180.0 && _long < 180.0;
  return (int)(Math.ceil((180 + _long)/6.0));
}

public void asUTMCoordinates( double longitude, double latitude) throws
     MismatchedDimensionException, TransformException {

  Point p = FactoryFinder.getPrimitiveFactory(null).createPoint( new double[] {longitude,latitude} );

  // define base EPSG code value of all UTM zones;
  int epsg_code = 32600;
  // add 100 for all zones in southern hemisphere
  if (this.getLatitudeInDeg() < 0) {
     epsg_code += 100;
  }
  // finally, add zone number to code
  final int zone = utm_zone( longitutde );
  epsg_code += zone;

  MathTransform crs_transform;
  try {
     CoordinateReferenceSystem wgs84  = DefaultGeographicCRS.WGS84; // EPSG:4326
     CoordinateReferenceSystem utm    = CRS.decode("EPSG:"+epsg_code);
     crs_transform = CRS.findMathTransform(wgs84,utm);
  } catch (NoSuchAuthorityCodeException e) {
     throw new RuntimeException(e);
  } catch (FactoryException e) {
     throw new RuntimeException(e);
  }
  DirectPosition p2 = crs_transform.transform( p.getDirectPosition(), null );
  double[] c = p2.getCoordinate();
  System.out.println( String.format("%d, %f, %f", zone, c[0], c[1]) );
}
Related Question