I need to convert GPS coordinates from WGS84 to decimal using Lua.
I am sure it's been done before, so I am looking for a hint to a code snippet.
corrected question: Code to convert DMS (Degress Minutes Seconds) to DEG ((decimal) Degrees) in Lua?
examples: Vienna: dms: 48°12'30" N 16°22'28" E or Zurich: dms: 47°21'7" N 8°30'37" E
The difficulty I find is to get the numbers out of these strings. Especially how to handle the signs for degree (°) minutes (') and seconds ("). So that I would have for example a table coord{} per coordinate to deal with.
coord {1} [48]
coord {2} [12]
coord {3} [30]
coord {4} [N]
coord {5} [16]
coord {6} [22]
coord {7} [28]
coord {8} [E]
Suggestions are appreciated, thanks.
Parse the string latlon = '48°12'30" N 16°22'28" E' into DMS+heading components:
This is your string (note the escaped single-quote):
latlon = '48°12\'30" N 16°22\'28" E'
Break it down into two steps: the lat/lon, then components of each. You need captures "()", ignore spaces around the heading (N and E) with "%s*":
lat, ns, lon, ew = string.match(latlon, '(.*)%s*(%a)%s*(.*)%s*(%a)')
The lat is now 48°12'30", ns is 'N', lon is 16°22'28", ew is 'E'. For components of lat, step by step:
-- string.match(lat, '48°12'30"') -- oops the ' needs escaping or us -- string.match(lat, '48°12\'30"') -- ready for the captures: -- string.match(lat, '(48)°(12)\'(30)"') -- ready for generic numbers d1, m1, s1 = string.match(lat, '(%d+)°(%d+)\'(%d+)"') d2, m2, s2 = string.match(lon, '(%d+)°(%d+)\'(%d+)"')
Now that you know (d1, m1, s1, ns) and (d2, m2, s2, ew), you have:
sign = 1 if ns=='S' then sign = -1 end decDeg1 = sign*(d1 + m1/60 + s1/3600) sign = 1 if ew=='W' then sign = -1 end decDeg2 = sign*(d2 + m2/60 + s2/3600)
For your values of lat, you get decDeg1 = 48.208333 which is the correct value according to online calculators (like http://www.satsig.net/degrees-minutes-seconds-calculator.htm).
来源:https://stackoverflow.com/questions/19085239/how-to-convert-gps-coordinates-to-decimal-in-lua