views:

2409

answers:

3

I have GPS information presented in the form:

36°57'9" N 110°4'21" W

I can use the javascript functions of Chris Veness to convert degrees, minutes and seconds to numeric degrees, but first need to parse the GPS info into the individual latitude and longitude strings (with NSEW suffixes). I have read related posts on stackoverflow, but am not a regex expert (nor a programmer) and need some help with the parsing function. What's the best way to parse this string into latitude and longitude for use in the conversion function?

The result of all this will be a Web link that one can click on to see a Google map representation of location.

+4  A: 

To parse your input use the following.

function ParseDMS(input) {
    var parts = input.split(/[^\d\w]+/);
    var lat = ConvertDMSToDD(parts[0], parts[1], parts[2], parts[3]);
    var lng = ConvertDMSToDD(parts[4], parts[5], parts[6], parts[7]);
}

The following will convert your DMS to DD

function ConvertDMSToDD(days, minutes, seconds, direction) {
    var dd = days + minutes/60 + seconds/(60*60);

    if (direction == "S" || direction == "W") {
        dd = dd * -1;
    } // Don't do anything for N or E
    return dd;
}

So your input would produce the following:

36°57'9" N  = 36.9525000
110°4'21" W = -110.0725000

Decimal coordinates can be fed into google maps to get points via GLatLng(lat, lng) (Google Maps API)

Gavin Miller
Perhaps a little better: var parts = input.split(/[^\d\w]+/). Adjust offsets by -1.
Inshallah
@Inshalla - thanks!
Gavin Miller
That should work! I'll give it a try tonight. Thanks to all who responded. This site is the best!
I'm dealing with this issue to, though have to cater for some alternative HMS representations: `2°28’14”N`, `50 44.63N`, `S 038° 18.429’`. I only show these here in case others need to think about them too.
Drew Noakes
+1  A: 

Joe, the script you've mentioned already did what do you want. With it you can convert lat and long and put it into link to see location in Google map:

var url = "http://maps.google.com/maps?f=q&source=s_q&q=&vps=3&jsv=166d&sll=" + lat.parseDeg() + "," + longt.parseDeg()
Alex Pavlov
A: 

I got some NaN's on this function and needed to do this (don't ask me why)

function ConvertDMSToDD(days, minutes, seconds, direction) {
    var dd = days + (minutes/60) + seconds/(60*60);
    dd = parseFloat(dd);
    if (direction == "S" || direction == "W") {
        dd *= -1;
    } // Don't do anything for N or E
    return dd;
}
Peter Childs