让GeoKit与我的Address类很好地配合

时间:2009-07-17 15:23:44

标签: ruby-on-rails geocoding geokit

我的Address类有一个geocode类方法,它返回一个地址对象数组,这些地址对象是通过对方法参数进行地理编码而得到的(如果地理编码导致完全匹配,则数组将有一个元素)。

编写此方法的一个令人讨厌的部分是将GeoKit地址对象转换为我的地址对象(例如,“street_address” - >“address1”)。有更好的方法吗?

class Address < ActiveRecord::Base
  def self.geocode(string)
    return nil if string.nil?

    results = Geokit::Geocoders::GoogleGeocoder.geocode(string)

    address_objects = Array.new

    results.all.each do |r|
      params = Hash.new

      params['address1'] = r.street_address
      params['city'] = r.city
      params['zipcode'] = r.zip
      params['state'] = State.find_by_abbr(r.state)
      params['country'] = Country.find_by_iso(r.country_code)

      new_address = Address.new(params)
      new_address.single_line_address = r.full_address

      address_objects << new_address    
    end

    return address_objects
  end
end

1 个答案:

答案 0 :(得分:5)

以下

class Address < ActiveRecord::Base
  def self.geocode(string)
    return if string.nil?

    results = Geokit::Geocoders::GoogleGeocoder.geocode(string)
    results.all.map do |r|
      Address.new do |address|
        address.address1  = r.street_address
        address.city      = r.city
        address.zipcode   = r.zip
        address.state     = State.find_by_abbr(r.state)
        address.country   = Country.find_by_iso(r.country_code)
        address.single_line_address = r.full_address
      end
    end
  end
end