我需要在Ruby中解析一些包含纬度和经度的用户提交字符串。
结果应该以double类型给出。
例如:
08º 04' 49'' 09º 13' 12''
结果:
8.080278 9.22
我查看了Geokit和GeoRuby,但都没有找到解决方案。有什么提示吗?
我需要在Ruby中解析一些包含纬度和经度的用户提交字符串。
结果应该以double类型给出。
例如:
08º 04' 49'' 09º 13' 12''
结果:
8.080278 9.22
我查看了Geokit和GeoRuby,但都没有找到解决方案。有什么提示吗?
"08° 04' 49'' 09° 13' 12''".gsub(/(\d+)° (\d+)' (\d+)''/) do
$1.to_f + $2.to_f/60 + $3.to_f/3600
end
#=> "8.08027777777778 9.22"
编辑:或者将结果作为浮点数数组获取:
"08° 04' 49'' 09° 13' 12''".scan(/(\d+)° (\d+)' (\d+)''/).map do |d,m,s|
d.to_f + m.to_f/60 + s.to_f/3600
end
#=> [8.08027777777778, 9.22]
def latlong(dms_pair)
match = dms_pair.match(/(\d\d)º (\d\d)' (\d\d)'' (\d\d)º (\d\d)' (\d\d)''/)
latitude = match[1].to_f + match[2].to_f / 60 + match[3].to_f / 3600
longitude = match[4].to_f + match[5].to_f / 60 + match[6].to_f / 3600
{:latitude=>latitude, :longitude=>longitude}
end
def dms_to_degrees(d, m, s)
degrees = d
fractional = m / 60 + s / 3600
if d > 0
degrees + fractional
else
degrees - fractional
end
end
def latlong(dms_pair)
match = dms_pair.match(/(-?\d+)º (\d+)' (\d+)'' (-?\d+)º (\d+)' (\d+)''/)
latitude = dms_to_degrees(*match[1..3].map {|x| x.to_f})
longitude = dms_to_degrees(*match[4..6].map {|x| x.to_f})
{:latitude=>latitude, :longitude=>longitude}
end