简体   繁体   English

如何使用Rails Geocoder获取place_id

[英]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.

相关问题 使用 geocoder gem for rails,我如何获得访问者的城市? - Using the geocoder gem for rails, how do i get the visitor's city? 存储和检索Google Place的place_id的最佳数据类型 - Best datatype to store and retrieve a Google Place's place_id 在Rails中使用AJAX进行DELETE请求时,如何从表单中获得不同的ID值? - How do I get different id values from a form when making a DELETE request using AJAX in Rails? Ruby on Rails - 限制地理编码器对城市的响应并获取ID - Ruby on Rails - Restrict geocoder response to city and get the ID 如何从Rails中的另一个控制器获取帖子的ID? - How do I get the ID of a post from another controller in Rails? 在Sidekiq中使用Geocoder Rails - Using Geocoder Rails with Sidekiq Rails Model.where如何获取ID? - Rails Model.where how do I get ID? 如何通过远距离以外的其他方式订购rails geocoder gem的结果 - How do I order the results of rails geocoder gem by something other than distance Rails:如何使用循环将ActiveRecord查询结果放入数组中? - Rails: How do I place ActiveRecord query results into an array using a loop? 如何在Rails中获得下一个可用的唯一ID,而不调用Model.last.id? - How do I get the next available unique ID in Rails without calling Model.last.id?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM