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

问题描述 投票:1回答:3

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

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文档,但没有找到任何类似的功能。

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

谢谢

ruby-on-rails postgresql gis geokit geocoder
3个回答
1
投票

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

创建以下文件config / initializers / 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])


0
投票

我认为Geocoder的near功能可以满足您的要求。

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

Geocoder文档引用此函数:https://github.com/alexreisner/geocoder#for-activerecord-models


0
投票

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

....

按地方,我的意思是有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
© www.soinside.com 2019 - 2024. All rights reserved.