使用Ruby Geocoder gem创建Location对象



我需要使用Ruby Geocoder gem来创建一个使用地址搜索查询返回的属性的对象。我希望从Geocoder结果中接收到的数据中创建一个新的位置,并创建一个具有迁移属性的新对象。我已经在网上搜索了资源,看看如何从结果中创建对象,但我需要知道如何从经度和纬度坐标中获得位置属性。

预期的示例搜索查询:"Wall St,NY"=> {address: "Wall Street", city: "New York, state: "New York", country: "United States of America"

位置模型

class Location < ApplicationRecord
has_many :users
geocoded_by :address
after_validation :geocode, if: ->(obj){ obj.address.present? and obj.address_changed? }
end

LocationController#创建

def create
@location = Location.new(location_params)
if @location.save
flash[:success] = "location added!"
redirect_to location_path(@location)
else
render 'new'
end
end

迁移

class CreateLocations < ActiveRecord::Migration[6.0]
def change
create_table :locations do |t|
t.string :address
t.string :city
t.string :state
t.string :country
t.float :longitude
t.float :latitude
end
end
end

预期的示例搜索查询:'Wall St,NY'=>{address:"Wall街道",城市:"纽约,州:"纽约",国家:"美国美国

您可以使用#search函数:

Geocoder.serach("Wall ST, NY")

这将返回一组结果。例如,第一个看起来是这样的:

#=>  => #<Geocoder::Result::Nominatim:0x00007ffc62aa37d0 @data={"place_id"=>184441192, "licence"=>"Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright", "osm_type"=>"way", "osm_id"=>447018423, "boundingbox"=>["40.7051753", "40.706379", "-74.009502", "-74.0074038"], "lat"=>"40.7060194", "lon"=>"-74.0088308", "display_name"=>"Wall Street, Financial District, Manhattan Community Board 1, Manhattan, New York County, New York, 10005, United States of America", "class"=>"highway", "type"=>"residential", "importance"=>0.758852318921325, "address"=>{"road"=>"Wall Street", "suburb"=>"Financial District", "city"=>"Manhattan Community Board 1", "county"=>"New York County", "state"=>"New York", "postcode"=>"10005", "country"=>"United States of America", "country_code"=>"us"}}, @cache_hit=nil> 

您可以获取所需的值,并将它们指定给新的"位置"对象。

搜索功能还可以采用经度和纬度为两个的数组:

Geocoder.search([lat, lng])

不幸的是,如果我理解正确,并且location_params是查询的结果,我认为你不能这样做:

@location = Location.new(location_params)

您必须首先从搜索查询的结果中提取必要的属性,然后将它们提供给Location#new方法。

最新更新