how to convert latitude and longitude to northing and easting in Java?
I'm assuming you mean UK OSGB easting and northings. The trigonometry behind this one is hilarious, but you can use the JCoord library for this, it makes it easy (if quite CPU intensive).
To follow up on @DD's comments below, there is a gotcha with JCoord, in that you have to make sure you're using the correct datum when converting from Easting/Northing to Lat/Long, and vice versa.
Take @DD's code:
LatLng latLng = new OSRef(394251,806376).toLatLng();
This will return a Lat/Long which uses the OSGB36 datum, i.e. the "flat earth" approximation used on UK maps. This is substantially different to the WSG84 datum used in most applications (including Streetmap), which models the world as a sphere (more or less).
In order to convert to a WGS84 lat/long, you need to make it explicit:
LatLng latLng = new OSRef(394251,806376).toLatLng();
latLng.toWGS84();
This will adjust the lat-long to the correct datum.
Note that the javadoc for OsRef.toLatLng()
is very clear about this:
Convert this OSGB grid reference to a latitude/longitude pair using the OSGB36 datum. Note that, the LatLng object may need to be converted to the WGS84 datum depending on the application
Conversion between coordinate datum is not simple. If it looks simple, you're likely doing it wrong.