我可以在模型中同时使用reverse_geocoded_by和geocoded_by吗?轨道

时间:2018-03-13 18:51:21

标签: ruby-on-rails ruby geocoder

我希望 full_street_address reverse_geocoded_by :latitude 和<允许我的模型地理编码 em>:经度以便我可以调用Address.near并通过其中一种方式获取它们。

这似乎有效,但这种方法可能导致潜在问题还是正确?

这是我的代码:

class Address < ApplicationRecord
  geocoded_by :full_street_address
  after_validation :geocode
  reverse_geocoded_by :latitude, :longitude

  def full_street_address
    self.street + self.city + self.country
  end
end

2 个答案:

答案 0 :(得分:3)

是的,您可以使用它,默认情况下,如果提供地址和lat / lng地址,它将覆盖。

您可以分成两个类,并在保存后调用Address.near([:lat, :lng])

模型

- /model/address.rb
   class Address < ApplicationRecord
      #any association/validations here

      geocoded_by :full_street_address

      #by default it will save full address to address field. 
      reverse_geocoded_by :latitude, :longitude do |obj,results|
        if geo = results.first
            #customize as you want
              obj.street  = geo.address.split(',')[0]
              obj.city    = geo.city
              obj.zip     = geo.postal_code
              obj.state   = geo.state
        end
      end

      def full_street_address
         self.street + self.city + self.country
      end
   end

- /model/address/with_address.rb
   class Address::WithAddress < Address
      after_validation :geocode
   end

- /model/address/with_lat_lng.rb
   class Address::WithLatLng < Address
     after_validation :reverse_geocode
   end

控制器

   address = Address::WithLatLng.create(latitude: 40.5236803, longitude: -80.2249546)
   # returns: will save lat/lng and address/city/state/zip fields saved from api
   address.full_street_address
   #or
   address = Address::WithAddress.create(address: "601 fake st.", city: "brooklyn", state: "ny", zip: "11220")
   # returns: will save address and latitude:, longitude: will fetch from api.
   address.full_street_address

答案 1 :(得分:1)

它有效,但它是多余的。这是因为geocoded_by使用完整的街道地址并获得纬度和经度,这是您的情况。但reverse_geocoded_by允许您从纬度和经度中获取地址,但您已经拥有它。

只需删除reverse_geocoded_by,如果您想使用纬度和经度,只需调用数据库中的字段:self.latitudeself.longitude,例如,您应该定义的字段(并为您填写地理编码服务。)