【问题标题】:Can you geocode_by two different locations in model?您可以通过模型中的两个不同位置进行地理编码吗?
【发布时间】:2015-07-24 11:00:42
【问题描述】:

所以我的模型有两个位置 - 'from' 和'to' 位置。我如何通过这两个 geocode_by 获得两组经度和纬度。这就是我正在尝试的,但它只有 geocodes_by 'to' 位置和 from_lat 和 from_long 列是 nil - 可能只是因为 'to' 位置在 'from' 位置之后。

class Post < ActiveRecord::Base
  belongs_to :user

  geocoded_by :from_address, :latitude => :from_lat, :longitude => :from_long
  geocoded_by :to_address, :latitude => :to_lat, :longitude => :to_long
  after_validation :geocode

  def from_address
    [fromstreet, fromcity, fromstate].compact.join(', ')
  end

  def to_address
    [tostreet, tocity, tostate].compact.join(', ')
  end
end

【问题讨论】:

    标签: ruby-on-rails geocoding


    【解决方案1】:

    如果有人好奇,想办法做到这一点:

    基本上只是添加了一个名为 from_address_coords 的新方法并将其称为 before_save,因为 geocoder gem 只会保存一组坐标 - 在这种情况下,from_address 没有被保存。

    class Post < ActiveRecord::Base
      belongs_to :user
    
      geocoded_by :to_address,   :latitude   => :to_lat,   :longitude => :to_long
    
      def to_address
        [tostreet, tocity, tostate].compact.join(', ')
      end
    
      def from_address
        [fromstreet, fromcity, fromstate].compact.join(', ')
      end
    
      def from_address_coords
        coords = Geocoder.coordinates(self.from_address)
        self.from_lat = coords[0]
        self.from_long = coords[1]
      end
    
      before_save :from_address_coords
      after_validation :geocode
    
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多