2009-08-22 32 views
5

我需要在Ruby下解析一些用戶提交的包含緯度和經度的字符串。用Ruby解析經緯度

結果應該在雙

爲例進行說明:

08º 04' 49'' 09º 13' 12'' 

結果:

8.080278 9.22 

我看着這兩個Geokit和GeoRuby但還沒有找到一個解決方案。任何提示?

回答

11
"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] 
+0

謝謝!我會接受這個優雅的答案!但是,我期待某種能夠解析其他格式或變體的庫。對正則表達式做一點調整就行了!再次感謝你! – rubenfonseca 2009-08-23 14:47:49

4

有關使用正則表達式如何?例如:

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 
+0

也是很好的解決方案。謝謝! – rubenfonseca 2009-08-23 14:50:11

1

根據你的問題的形式,您所期待的解決方案,以正確處理負座標。如果你不是,那麼你會期望緯度爲N或S,經度爲E或W。

請注意,接受的解決方案將不提供正確的結果與負座標。只有度數是負值,分和秒纔是正值。在度數爲負數的情況下,分和秒將使座標移近0°,而不是遠離0°。

Will Harris的第二個解決方案是更好的方法。

祝你好運!