【问题标题】:Rails Geocoding Distance Calulations are IncorrectRails 地理编码距离计算不正确
【发布时间】:2021-07-25 20:49:51
【问题描述】:

我对地理编码的以下结果感到很困惑。
前两个是正确的。最后一个显然是错误的。这些计算之间的代码没有任何改变。关于如何调试的任何想法?

Geocoder::Calculations.distance_between("allentown,pa","scranton,pa")
#=> 56.604020682719295

Geocoder::Calculations.distance_between("allentown,pa","harrisburg,pa")
#=> 77.94099956445362

Geocoder::Calculations.distance_between("allentown,pa","bethlehem,pa")
#=> 3365.993496166768 

【问题讨论】:

    标签: ruby-on-rails ruby geocoding


    【解决方案1】:

    “bethlehem,pa”有多个搜索结果

    results = Geocoder.search("bethlehem,pa")
    results.size # => 8
    

    并非所有这些结果都在美国

    results.map { |r| r.country_code }
     => ["br", "us", "us", "us", "us", "us", "us", "us"]
    

    首先是来自巴西的打击。如果结果不明确,则采用此结果(请参见下面的代码)。 我假设巴西伯利恒排在第一位,因为该州被称为“pará”,它与“pa”比“pennsylvania”更接近(使用任何度量标准的字符串距离)

    distance_between

    https://github.com/alexreisner/geocoder/blob/f7a83fac8cf8564b79d017091004cbb9d406e4ae/lib/geocoder/calculations.rb#L84

    最终会调用coordinates

    https://github.com/alexreisner/geocoder/blob/f7a83fac8cf8564b79d017091004cbb9d406e4ae/lib/geocoder.rb#L28

    看起来像这样:

    def self.coordinates(address, options = {})
      if (results = search(address, options)).size > 0
        results.first.coordinates
      end
    end
    

    因此,按国家/地区扩充您的位置字符串,您会得到不同的结果:

    Geocoder::Calculations.distance_between("allentown,pa, USA","bethlehem,pa, USA")
    # => 4.97795894130203
    

    归结为字符串的位置描述通常不是唯一的。有多个巴黎、伯尔尼,当然还有伯利恒:-)

    所以毫不奇怪还有多个阿伦敦:

    require "geocoder"
    
    allentowns = Geocoder.search("allentown,pa")
    bethlehems = Geocoder.search("bethlehem,pa")
    
    
    allentowns.each do |allentown|
      bethlehems.each do |bethlehem|
        distance = Geocoder::Calculations.distance_between([allentown.latitude, allentown.longitude], [bethlehem.latitude, bethlehem.longitude])
        puts "#{allentown.address} -> #{bethlehem.address}: #{distance}"
      end
    end
    

    显示有美国宾夕法尼亚州利哈伊县阿伦敦美国宾夕法尼亚州阿勒格尼县匹兹堡阿伦敦

    【讨论】:

    • 非常感谢!你的血是值得装瓶的。
    • 感谢您的称赞,很高兴我能提供帮助。
    猜你喜欢
    • 2016-05-30
    • 1970-01-01
    • 2012-12-25
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多