在 Rails-Geocoder 中使用最大距离属性反向查询位置



举个例子,我有一个这样的模型

class Place < ActiveRecord::Base
    # has a "latitude" & "longitude" field
    # notice it has "max_distance" field (meter), will be different on each record
end

如何实现给定坐标点的查询,将获取距离坐标点和max_distance字段之间范围内的所有位置。

lat = 37.792
lng = -122.393
Place.query_in_range_by_point([lat, lng])
# will get nearest places within range "max_distance" field 

我一直在查找Geocoder和Geo-Kit宝石文档,但没有找到任何类似的功能。

如果上面的 gem 不支持该功能,任何人都可以建议另一种可以解决问题的方法吗?

谢谢

我认为地理编码器的near功能可以满足您的要求。

class Place < ActiveRecord::Base
  def self.query_in_range_by_point(lat, lng)
    self.near([lat, lng], self.max_distance)
  end
end

地理编码器文档引用了以下函数: https://github.com/alexreisner/geocoder#for-activerecord-models

我认为以下补丁可以解决问题。

创建以下文件配置/初始值设定项/geokit_rails_patch.rb

module Geokit::ActsAsMappable
  module ClassMethods
    def query_in_range_by_point(options = {})
      sql = build_distance_sql(options)
      where("#{sql} <= #{table_name}.max_distance")
    end
    private
    def build_distance_sql(options)
      origin = extract_origin_from_options(options)
      units = extract_units_from_options(options)
      formula = extract_formula_from_options(options)
      distance_sql(origin, units, formula)
    end
  end
end

然后你可以像

Place.query_in_range_by_point(origin: [-23.5062855, -55.0919171])

抱歉,

我将其作为答案发布,但是在评论部分发布代码示例时格式已关闭。

....

通过位置,我的意思是拥有latitudelongitudemax_distance属性,因为如果是这种情况,那么您可能只需要

class Place < AR::Base
  ...
  def nearby_places
    Place.where.not(id: id).near([latitude, longitude], max_distance)
  end
  ...
end

要访问这些附近的地方,只需执行以下操作:

place = Place.first
nearby_places = place.nearby_places

最新更新