How to convert GPS coordinates to decimal in Lua?

自古美人都是妖i 提交于 2019-12-02 05:50:54

Parse the string latlon = '48°12'30" N 16°22'28" E' into DMS+heading components:

  1. This is your string (note the escaped single-quote):

    latlon = '48°12\'30" N 16°22\'28" E'
    
  2. 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)')
    
  3. 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+)"')
    
  4. 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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!