【问题标题】:Ruby on Rails - Restrict geocoder response to city and get the IDRuby on Rails - 限制地理编码器对城市的响应并获取 ID
【发布时间】:2016-10-20 07:31:56
【问题描述】:

我有一个带有users 表的Ruby on Rails 项目,我需要存储来自用户输入的location_id

  • 如果用户输入Buckingham Palace,那么location_id 应该是london_id

  • 如果用户输入Wall Street,那么location_id 应该是new_york_id

  • 如果用户输入Statue of Liberty,那么location_id 应该是new_york_id

  • 如果用户键入 United States,则 location_id 应为 nil

我正在使用geocoder gem,但我无法检索城市 ID。例如:

Geocoder.search("London").first.place_id # => ChIJdd4hrwug2EcRmSrV3Vo6llI
Geocoder.search("Buckingham Palace").first.place_id # => ChIJtV5bzSAFdkgRpwLZFPWrJgo

我需要两者都是 ChIJdd4hrwug2EcRmSrV3Vo6llI(伦敦 ID)

【问题讨论】:

  • 你在使用geocoder gem吗?
  • 是的,如问题中所述

标签: ruby-on-rails ruby geocoding geocode rails-geocoder


【解决方案1】:

这是我的更新答案。它集成在Geocoder结构中,如果查询的是城市名称,只需一次搜索:

require 'geocoder'

module Geocoder
  # Returns the Google ID of the city containing the queried location. Returns nil if nothing found or if location contains multiple cities.
  def self.get_city_id(query, options={})
    results = search(query, options)
    unless results.empty?
      result = results.first
      city = result.city
      if city then
        if city == query then
          result.place_id
        else
          sleep(1)
          search(city,options).first.place_id
        end
      end
    end
  end
end

Geocoder::Configuration.timeout = 15

["London", "Buckingham Palace", "Wall Street", "Statue of Liberty Monument", "United States", "WEIRDqueryWithNoResult"].each{|query|
  puts query
  puts Geocoder.get_city_id(query).inspect
  sleep(1)
}

它输出:

London
"ChIJdd4hrwug2EcRmSrV3Vo6llI"
Buckingham Palace
"ChIJdd4hrwug2EcRmSrV3Vo6llI"
Wall Street
"ChIJOwg_06VPwokRYv534QaPC8g"
Statue of Liberty Monument
"ChIJOwg_06VPwokRYv534QaPC8g"
United States
nil
WEIRDqueryWithNoResult
nil

出于文档目的,这是我的原始答案:

require 'geocoder'


def get_city(search_term)
  Geocoder.search(search_term).first.city
end

def get_place_id(search_term)
  Geocoder.search(search_term).first.place_id
end

["London", "Buckingham Palace", "Wall Street", "Statue of Liberty Monument", "United States"].each{|term|
  puts (city=get_city(term)) && sleep(1) && get_place_id(city)
  sleep(1)
}

【讨论】:

  • 我认为您必须在搜索中添加边界参数才能更精确。想想像柏林和巴黎这样的城市(法国巴黎;美国德克萨斯州巴黎/德国柏林;美国马里兰州柏林;美国康涅狄格州柏林)的边缘案例(例如来自自述文件Geocoder.search("Paris", :bounds => [[32.1,-95.9], [33.9,-94.3]])github.com/alexreisner/geocoder .您可以根据第一个搜索结果中给出的纬度/经度来近似范围。
  • 是的。但不确定性也来自第一次搜索:Geocoder.search('Statue of liberty').first.city 返回“Sandpoint” 当第一次搜索可能已经完全错误时,尝试进行更准确的第二次搜索可能没有意义。
  • 确实如此。可能需要一些用户确认。
  • 这会起作用,尽管我一直在寻找内置或单步功能。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-14
  • 1970-01-01
  • 2012-01-13
相关资源
最近更新 更多