如何在Lua中转换含小数秒的DMS坐标为十进制度数
DMS格式GPS坐标转十进制度数的Lua实现(支持小数秒)
核心转换逻辑
DMS转十进制度数的通用公式不受秒数是否为小数影响,公式为:十进制度数 = 度数 + 分数/60 + 秒数/3600
再根据方向调整正负:北纬(N)、东经(E)为正,南纬(S)、西经(W)为负。
实现代码
以下Lua函数可处理包含小数秒的DMS坐标:
function dms_to_decimal(dms_str) -- 匹配度、分、秒、方向,兼容整数/小数秒 local degrees, minutes, seconds, direction = dms_str:match("(%d+)°(%d+)'([%d%.]+)\"([NSEW])") if not degrees then return nil end -- 匹配失败返回空值 -- 转换为数值类型 degrees = tonumber(degrees) minutes = tonumber(minutes) seconds = tonumber(seconds) -- 计算十进制度数 local decimal = degrees + minutes/60 + seconds/3600 -- 根据方向调整正负 if direction == 'S' or direction == 'W' then decimal = -decimal end return decimal end
测试示例
-- 整数秒坐标测试 print(dms_to_decimal("48°12'30\"N")) -- 输出:48.208333333333 print(dms_to_decimal("16°22'28\"E")) -- 输出:16.374444444444 -- 小数秒坐标测试 print(dms_to_decimal("52°52'16.9\"N")) -- 输出:52.871361111111 print(dms_to_decimal("0°46'43.5\"W")) -- 输出:-0.77875
关键说明
正则表达式中的([%d%.]+)用于捕获秒数,既支持整数也支持带小数点的小数秒;Lua的数值运算天然支持浮点数,因此无需额外处理小数秒的特殊逻辑,直接套用通用公式即可完成转换。
内容的提问来源于stack exchange,提问作者Hunt
相关产品推荐
相关产品推荐

