【问题标题】:Parsing latitude and longitude with Ruby用 Ruby 解析经纬度
【发布时间】:2010-11-21 23:26:56
【问题描述】:

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

结果应该以双精度形式给出

例子:

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

结果:

8.080278 9.22

我查看了 Geokit 和 GeoRuby,但没有找到解决方案。有什么提示吗?

【问题讨论】:

    标签: ruby geolocation geospatial latitude-longitude


    【解决方案1】:
    "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]
    

    【讨论】:

    • 谢谢!我会接受这个优雅的答案!但是,我期待某种能够解析其他格式或变体的库。对正则表达式稍作调整就可以了!再次感谢您!
    【解决方案2】:

    使用正则表达式怎么样?例如:

    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
    

    【讨论】:

      【解决方案3】:

      根据您的问题形式,您期望解决方案能够正确处理负坐标。如果你不是,那么你会期待一个 N 或 S 跟随纬度和一个 E 或 W 跟随经度。

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

      Will Harris 的第二个解决方案是更好的选择。

      祝你好运!

      【讨论】:

        猜你喜欢
        • 2020-06-28
        • 2013-03-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-09
        • 2020-07-20
        • 1970-01-01
        • 2021-08-08
        • 1970-01-01
        相关资源
        最近更新 更多