thakare
thakare

Reputation: 101

Converting GPS coordinates (latitude and longitude) to decimal

I am getting the latitude and longitude from GPS device. They look like 21081686N,079030977E

If I manually convert them to 21°08'16.86"N, 79°03'09.77"E and check on Google maps, the location is almost correct.

How do I convert these values in java and convert them to decimal accurately? Any JAVA libraries?

Thanks,

Upvotes: 2

Views: 6602

Answers (1)

acraig5075
acraig5075

Reputation: 10756

You shouldn't need a library, but rather just break up the strings into their component parts. Perhaps this will help. Please note I'm not a Java programmer so this syntax could very well be wrong. (Perhaps retag your question to Java)

By decimal I presume you mean decimal degrees and not ddd.mmss

// Object for Lat/Lon pair
public class LatLonDecimal
{
    public float lat = 0.0;
    public float lon = 0.0;
}

// Convert string e.g. "21081686N,079030977E" to Lat/Lon pair
public LatLonDecimal MyClass::convert(String latlon)
{
    String[] parts = latlon.split(",");

    LatLonDecimal position = new LatLonDecimal();
    position.lat = convertPart(parts[0]);
    position.lon = convertPart(parts[1]);
    return position;
}

// Convert substring e.g. "21081686N" to decimal angle
private float MyClass::convertPart(String angle)
{
    while (angle.length() < 10)
        angle = StringBuffer(angle).insert(0, "0").toString();

    int deg = Integer.parseInt( angle.substring(0,2) );
    int min = Integer.parseInt( angle.substring(3,4) );
    int sec = Integer.parseInt( angle.substring(5,6) );
    int sub = Integer.parseInt( angle.substring(7,8) );
    String hem = angle.substring(9);

    float value = deg + min / 60.0f + sec / 3600.0f + sub / 360000.0f;
    float sign = (hem == "S") ? -1.0 : 1.0; // negative southern hemisphere latitudes
    return sign * value;
}

Upvotes: 1

Related Questions