我需要解析含有红宝石下的纬度和经度,一些用户提交的字符串。

结果应在给予双

示例:

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
根据你的问题的形式

,您所期待的解决方案,以正确处理负坐标。如果不是,那么你会期望的N或S以下纬度和E或W以下经度。

请注意,所接受的解决方案将<强>不能提供正确的结果具有负坐标。只有度将是负数,分和秒将是积极的。在那些其中度为负的情况下,分和秒将移动坐标越接近0°,而不是从0°更远。

威尔哈里斯的第二解决方案是更好的方式去。

祝你好运!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top