2016-10-20 4 views
1

나는 users 테이블을 가진 Ruby on Rails 프로젝트를 가지고 있으며 사용자 입력으로부터 location_id을 저장해야합니다.Ruby on Rails - 도시로의 지오 코더 응답을 제한하고 ID를 얻으십시오

  • 사용자 유형 Buckingham Palace 다음 location_id 같아야 경우 london_id

  • 사용자 유형 Wall Street 다음 location_id 같아야 경우 new_york_id

  • 사용자 유형 Statue of Liberty 다음 location_id는 new_york_id되어야 하는지를

  • 사용자 유형이인 경우다음 location_id 내가 geocoder 보석을 사용하고,하지만 난 도시의 ID를 검색 실패하고있어 nil

해야한다. 예를 들어 :

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

나는 여기 내 업데이트 된 대답이 모두 ChIJdd4hrwug2EcRmSrV3Vo6llI (런던 ID)

+0

지오 코드 보석을 사용하고 있습니까? –

+0

예, 질문에 설명 된대로 – user4523968

답변

0

해야합니다. 그것은 지오 코더 구조에 통합하고, 쿼리가 도시 이름 인 경우 하나 개의 검색을 필요로한다 :

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

나는 바운드 params를 검색에 더 정확하게 추가해야한다고 생각합니다. 베를린과 파리 (파리, 프랑스, ​​파리, 텍사스, 미국/베를린, 독일, 베를린, 미국, 베를린, CT, 미국)의 도시 (예 : readme Geocoder.search ("Paris ", : bounds => [[32.1, -95.9], [33.9, -94.3]])) https://github.com/alexreisner/geocoder. 첫 번째 검색 결과에 제공된 위도/경도에서 경계를 근사 할 수 있습니다. – jphager2

+0

참. 그러나 불확실성은 또한 첫 번째 검색에서 비롯됩니다. 'Geocoder.search ('자유의 여신상'). first.city'는 "Sandpoint"를 반환합니다. 첫 번째 검색에서 더 정확한 두 번째 검색을 시도하는 것이 바람직하지 않을 수 있습니다. 이미 완전히 틀릴 수도 있습니다. –

+0

사실입니다. 일부 사용자의 확인이 필요할 수 있습니다. – jphager2