Ale*_*lex 1 ruby-on-rails geospatial mongodb mongoid ruby-on-rails-3
我在使用 MongoDB / Rails 查询地理空间索引时遇到问题。我正在使用这个 gem - https://github.com/kristianmandrup/mongoid_geospatial
这是我相当基本的模型:
class Company
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Geospatial
field :name, type: String
field :location, type: Array, spatial: true
spatial_index :location
validates :location, location: true
end
Run Code Online (Sandbox Code Playgroud)
然后,在我的控制器中,我有这个
#@vendors = Vendor.where(:location.near => {:point => [-2.1294761000000335,57.0507625], :max => 5})
Run Code Online (Sandbox Code Playgroud)
然而,这并没有返回预期的结果(即,它返回来自各地的东西,而不仅仅是靠近特定的经度/纬度)
另外,我将如何对此进行 geoNear 呢?
这样我就可以得到每个结果到中心点的距离?
注意 写完这个问题后,我看到 gem 已更新,但我不确定是否有更好的替代方案..?
您不需要mongoid_geospatialgem 来执行geoNear查询:mongoid已经支持它(至少在版本 3 中)。
将您的模型更改为:
class Company
include Mongoid::Document
include Mongoid::Timestamps
field :name, type: String
field :location, type: Array
index({location: "2d"})
validates :location, location: true
end
Run Code Online (Sandbox Code Playgroud)
并将您的查询运行为:
@vendors = Vendor.geo_near([-2.1294761000000335,57.0507625]).max_distance(5)
Run Code Online (Sandbox Code Playgroud)