繁体   English   中英

如何使用Rails Geocoder获取place_id

[英]How do I get place_id by using 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=zh-CN&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?

首先,从Google API解析JSON

parsed_response = JSON.parse(results.to_json)

然后,从place_id获取值

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM