Friday, October 12, 2012

Convert Lat, Lon to MGRS (vice versa) in Java


Need to convert between MGRS and Latitude, Longitude pairs in Java. 

There are a couple of libraries out there, but they have unfriendly open source licenses (no redistribute unless your project is same license, requires commercial license in production, etc.).


NASA has converted the old NGA GDAL libraries written in C to Java embedded in NASA's World Wind application.  Unfortunately, that library is huge and littered with dependencies on AWT, graphics libraries, etc.  World Wind also has it's own logging facade embedded in the implementation.

On the other hand, the World Wind project has a very nice license:  NASA Open Source Agreement v1.3.


1.  Rip out all the unnecessary code out of World Wind.
2.  Attribute the code.
3.  Provide the changes to the world:
4.  Move on and do more important things.


package com.berico.coords;

public class Example 
  public static void main( String[] args )
      String mgrs = Coordinates.mgrsFromLatLon(37.10, -112.12);
      double[] latLon = Coordinates.latLonFromMgrs(mgrs);
        String.format("%s, %s", latLon[0], latLon[1]));

Which prints...
12SVG 00476 06553
37.10000369375159, -112.1199968717142

Get it on GitHub: