[英]How do I get place_id by using rails Geocoder
I'm using rails gem ' geocoder ' on my rails application. 我在rails应用程序上使用rails gem'geocoder '。 Here is the code: 这是代码:
test.rb 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 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; 在Rails控制台中创建测试模型后;
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 会生成以下Google Maps API: http : //maps.googleapis.com/maps/api/geocode/json?language=zh-CN&latlng=49.0%2C101.0&sensor=false
From there I can see that it has place_id. 从那里我可以看到它具有place_id。
"place_id" : "ChIJnasu3tKddF0RqAvcjn5EhBE", “ place_id”:“ ChIJnasu3tKddF0RqAvcjn5EhBE”,
If I add this code to test.rb just below obj.country, 如果我将此代码添加到obj.country下面的test.rb中,
obj.place_id = geo.place_id
it returns NoMethodError: undefined method `place_id' for # 它返回NoMethodError:#的未定义方法`place_id'
So, how could i get that place_id by adding some code to my Test.rb? 那么,如何通过在Test.rb中添加一些代码来获取place_id?
First, parse the JSON from Google API 首先,从Google API解析JSON
parsed_response = JSON.parse(results.to_json)
Then, get the value from place_id 然后,从place_id获取值
obj.place_id = parsed_response[0]["data"]["place_id"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.