简体   繁体   English

通过街道地址,通过Geocoder gem地理编码更新经度/纬度

[英]Update longitude / latitude with geocoder gem geocode by street address

How can I update the latitude and longitude coordinates using geocoder gem given the following models and relationship. 给定以下模型和关系,如何使用geocoder gem更新纬度和经度坐标。 I have a Location model with latitude and longitude attributes that belong to my Event model. 我有一个Location模型,该模型具有属于我的Event模型的latitudelongitude属性。 The latitude and longitude automatically get fetched and stored in latitude and longitude attributes of my Location model. 纬度和经度会自动获取并存储在我的Location模型的latitudelongitude属性中。 My Event model has a field venue_address which is what I geocode by. 我的Event模型有一个场venue_address地址,这是我venue_address进行地理编码的地址。

class Location < ActiveRecord::Base
  belongs_to :event
    geocoded_by :venue_address
    after_validation :geocode
end

AND this is my Event model with has_one :location relation 这是我的具有has_one :location关系的Event模型

class Event < ActiveRecord::Base
    has_one     :location,  dependent: :destroy
end 

Next is my Event create method where I build the relationship. 接下来是建立关系的我的事件创建方法。

class EventsController < ApplicationController
  def create
    @event = Event.new(event_params)
    # Builds longitude and latitude coordinates based on a valid street address
    # and saves it to Location table
    @event.build_location
...
  end 
end 

When I update the address of an event I would like to geocode the new coordinates and save the coordinates to their respective field in Location model. 更新事件的地址时,我想对新坐标进行地理编码并将坐标保存到“ Location模型中的相应字段中。

I am having trouble accomplishing this. 我很难做到这一点。 Any ideas or suggestions? 有什么想法或建议吗?

Try something like this 试试这个

class Location < ActiveRecord::Base
  belongs_to :event
  geocoded_by :event_venue_address
  after_validation :geocode

  def event_venue_address
    event.venue_address
  end

end

or just delegate to event model 或仅委托给事件模型

delegate :venue_address, to: event, prefix: true

Here is the example for the readme 这是自述文件的示例

If your model has street, city, state, and country attributes you might do something like this:

geocoded_by :address

def address
  [street, city, state, country].compact.join(', ')
end

Hope that helps 希望能有所帮助

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

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