【问题标题】:Use Ruby Geocoder gem to create Location object使用 Ruby Geocoder gem 创建 Location 对象
【发布时间】:2020-04-10 20:33:56
【问题描述】:

我需要使用 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

LocationController#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

【问题讨论】:

    标签: ruby-on-rails ruby activerecord geocoder


    【解决方案1】:

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

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

    搜索函数也可以取一个包含经度和纬度的两个数组:

    Geocoder.search([lat, lng])
    

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

        @location = Location.new(location_params)
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-14
      • 2015-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多