Ruby on Rails - 限制地理编码器对城市的响应并获取ID

时间:2016-10-20 07:31:56

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

我有一个带有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(伦敦身份证)

1 个答案:

答案 0 :(得分:0)

这是我更新的答案。它集成在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)
}