用Ruby解析纬度和经度

我需要在Ruby下解析一些用户提交的包含纬度和经度的字符串。

结果应该是双倍的

例:

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 

根据您的问题的forms,您期望解决方案正确处理负坐标。 如果你不是,那么你会期望跟随纬度的N或S以及跟随经度的E或W.

请注意,接受的解决方案无法使用负坐标提供正确的结果 。 只有度数为负数,分数和秒数为正数。 在度数为负的情况下,分钟和秒将使坐标更接近0°而不是更远离0°。

哈里斯的第二个解决方案是更好的方法。

祝好运!