举个例子,我有一个这样的模型
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 我一直在找地理编码器和Geo-Kit gem文档,但没有找到任何这样的功能。
如果上面的gem不支持这个功能,有没有人可以提出另一种方法来解决这个问题?
谢谢
发布于 2018-01-20 21:29:02
我认为Geocoder的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
发布于 2018-03-01 04:44:05
我认为下面的补丁可以解决这个问题。
创建以下文件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])
发布于 2018-01-20 22:30:28
很抱歉,我将此作为答案发布,但在评论区发布代码示例时,格式设置已关闭。
……
我的意思是拥有latitude、longitude、max_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_placeshttps://stackoverflow.com/questions/48356373
复制相似问题