NullPointerException
NullPointerException

Reputation: 37577

How can I transform a GPS point from DDD MM.MMM (string) to decimal (latitude & longitude)?

I need to transform a GPS point from DDD MM.MMM (string) to decimal (two values: latitude & longitude) with Java.

For example, I have this String:

String a = "N 39° 28.941 W 0° 23.275"

I need to transform that string into these two values:

double lat= 39.48235
double lon= -0.38792

How can I do it with Java code?

Upvotes: 0

Views: 1772

Answers (1)

Christopher
Christopher

Reputation: 704

Parse the string for those six values:

  • N or S to determine the sign of of the latitude (plus or minus)
  • The degrees (39 - the part before the dot)
  • The double value (28.941 - the part after the dot)

... the same for longitude

Quick hack to do so:

public class CoordTest {

    private static String  coords = "N 39° 28.941 W 0° 23.275";

    public static void main(String[] args) {
        String[] cArray = coords.split(" ");
        String latSign = cArray[0];
        String latDegrees = cArray[1].substring(0, cArray[1].length()-1);
        String latSubdegrees = cArray[2];
        String lonSign = cArray[3];
        String lonDegrees = cArray[4].substring(0, cArray[4].length()-1);
        String lonSubdegrees = cArray[5];
        double lat = getSign(latSign) * (Integer.valueOf(latDegrees) + convertFromDegreesToDecimal(Double.valueOf(latSubdegrees)));
        double lon = getSign(lonSign) * (Integer.valueOf(lonDegrees) + convertFromDegreesToDecimal(Double.valueOf(lonSubdegrees)));
    }


    private static int getSign(String c){
        if (c.equals("N") || c.equals("E")){
            return 1;
        }
        return -1;
    }

    private static double convertFromDegreesToDecimal(Double value){
        double result = value/60d;
        return result;
    }
}

Upvotes: 2

Related Questions