如何使用rails Geocoder获取place_id

时间:2015-08-06 03:38:48

标签: ruby-on-rails rails-geocoder

我在rails应用程序中使用rails gem'geocoder'。这是代码:

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

在rails控制台中创建测试模型之后;

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

它会生成此Google Maps API:http://maps.googleapis.com/maps/api/geocode/json?language=en&latlng=49.0%2C101.0&sensor=false

从那里我可以看到它有place_id。

  

“place_id”:“ChIJnasu3tKddF0RqAvcjn5EhBE”,

如果我将此代码添加到obj.country下面的test.rb,

obj.place_id = geo.place_id

它返回NoMethodError:#

的未定义方法`place_id'

那么,我怎样才能通过在Test.rb中添加一些代码来获得place_id?

1 个答案:

答案 0 :(得分:1)

首先,从Google API解析JSON

parsed_response = JSON.parse(results.to_json)

然后,从place_id获取值

obj.place_id = parsed_response[0]["data"]["place_id"]
相关问题