首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用最大距离属性反向查询Rails-Geocoder中的位置

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

Stack Overflow用户
提问于 2018-01-20 20:53:33
回答 3查看 599关注 0票数 1

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

代码语言:javascript
复制
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字段范围内的所有位置。

代码语言:javascript
复制
lat = 37.792
lng = -122.393

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

我一直在找地理编码器和Geo-Kit gem文档,但没有找到任何这样的功能。

如果上面的gem不支持这个功能,有没有人可以提出另一种方法来解决这个问题?

谢谢

EN

回答 3

Stack Overflow用户

发布于 2018-01-20 21:29:02

我认为Geocoder的near函数可以满足您的需求。

代码语言:javascript
复制
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

票数 1
EN

Stack Overflow用户

发布于 2018-03-01 04:44:05

我认为下面的补丁可以解决这个问题。

创建以下文件config/initializers/geokit_rails_patch.rb

代码语言:javascript
复制
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])

票数 1
EN

Stack Overflow用户

发布于 2018-01-20 22:30:28

很抱歉,我将此作为答案发布,但在评论区发布代码示例时,格式设置已关闭。

……

我的意思是拥有latitudelongitudemax_distance属性,因为如果是这样的话,您可能只需要

代码语言:javascript
复制
class Place < AR::Base
  ...
  def nearby_places
    Place.where.not(id: id).near([latitude, longitude], max_distance)
  end
  ...
end

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

代码语言:javascript
复制
place = Place.first
nearby_places = place.nearby_places
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48356373

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档