Search code examples
ruby-on-railsrails-geocoder

How do I get place_id by using rails Geocoder


I'm using rails gem 'geocoder' on my rails application. Here is the code:

test.rb

class Test < ActiveRecord::Base

  reverse_geocoded_by :latitude, :longitude do |obj,results|
    if geo = results.first
        obj.street = geo.street_address
        obj.city    = geo.city
        obj.state = geo.state
        obj.country = geo.country
    end
  end

  after_validation :reverse_geocode
end

schema.rb

  create_table "tests", force: :cascade do |t|
    t.string    "street"
    t.string    "city"
    t.string    "state"
    t.string    "country"
    t.string    "place_id"
  end

After I create a Test model in rails console;

testLoc = Test.create(latitude: "49", longitude: "101")

it generates this Google Maps API: http://maps.googleapis.com/maps/api/geocode/json?language=en&latlng=49.0%2C101.0&sensor=false

From there I can see that it has place_id.

"place_id" : "ChIJnasu3tKddF0RqAvcjn5EhBE",

If I add this code to test.rb just below obj.country,

obj.place_id = geo.place_id

it returns NoMethodError: undefined method `place_id' for #

So, how could i get that place_id by adding some code to my Test.rb?


Solution

  • First, parse the JSON from Google API

    parsed_response = JSON.parse(results.to_json)
    

    Then, get the value from place_id

    obj.place_id = parsed_response[0]["data"]["place_id"]