Search code examples
lua

How do I convert 52°52'16.9"N 0°46'43.5"W to DMS (Degress Minutes Seconds) to DEG ((decimal) Degrees) in Lua?


There is a great explanation of how to do this with 48°12'30" N 16°22'28" E or Zurich: dms: 47°21'7" N 8°30'37" E At How to convert GPS coordinates to decimal in Lua? However, I cannot work out how to trap to include the decimal value, as in 52°52'16.9"N 0°46'43.5"W.


Solution

  • Use the \' to escape the sequence:

    local dms = '52°52\'16.9"N'
    print (dms)
    local degrees, minutes, seconds, direction = dms:match('(%d+)%D+(%d+)%D+(%d+%.?%d*)%D*([NSEW])')
    print (degrees, minutes, seconds, direction)
    local decimal = tonumber(degrees) + tonumber(minutes) / 60 + tonumber(seconds) / 60^2
    
    if direction == 'S' or direction == 'W' then
        print (-decimal)
    else
        print (decimal) -- positive
    end
    
    52°52'16.9"N
    52  52  16.9    N
    52.871361111111