user4523968 user4523968 - 1 month ago 8
Ruby Question

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

I have a Ruby on Rails project with the

users
table and I need to store the
location_id
from the user input.


  • If user types
    Buckingham Palace
    then the location_id should be the
    london_id

  • If user types
    Wall Street
    then the location_id should be the
    new_york_id

  • If user types
    Statue of Liberty
    then the location_id should be the
    new_york_id

  • If user types
    United States
    then the location_id should be
    nil



I am using
geocoder
gem, but I'm failing retrieving the city ID. For instance:

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


I need both to be
ChIJdd4hrwug2EcRmSrV3Vo6llI
(the London ID)

Answer

Here you go :

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

It outputs :

ChIJdd4hrwug2EcRmSrV3Vo6llI
ChIJdd4hrwug2EcRmSrV3Vo6llI
ChIJOwg_06VPwokRYv534QaPC8g
ChIJOwg_06VPwokRYv534QaPC8g

I didn't find a way to get it directly in one search, though.

Comments