1

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

预期的示例搜索查询:“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

位置控制器#create

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
4

1 回答 1

1

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

您可以使用以下#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> 

您可以获取所需的值并将它们分配给新的 Location 对象。

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

Geocoder.search([lat, lng])

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

    @location = Location.new(location_params)

您必须首先从搜索查询的结果中提取必要的属性,然后将它们提供#newLocation.

于 2020-04-10T21:44:35.173 回答