簡體   English   中英

Ruby on Rails - 限制地理編碼器對城市的響應並獲取ID

[英]Ruby on Rails - Restrict geocoder response to city and get the ID

我有一個帶有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結構中,如果查詢是城市名稱,則只需要一次搜索:

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)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM