How can I get geo_near max_distance results ordered by distance?
Opened this issue · 2 comments
What I'm trying to do is to sort mongoid geo_near(or within_circle) max_distance results by distance because I don't know why but it doesn't do that by default.
I have mongoid_geospatial, mongoid_spacial and rgeo in my Rails gem file. I know mongoid_spacial has this ability but I could not use it and it caused problems with gmaps4rails.
I'm trying on mongoid_geospatial(which uses mongoid libraries) with no success and I could not find any resource except this one MongoDB Aggregate geoNear maxdistance but I don't know how to convert mongo that to mongoid.
Any one had an experience on sorting geo_near or within_circle in mongoid? Any help will be greatly appreciated.
The code in my Controller
searchterm = session[:categoryid].to_s
radius = session[:distance].to_f / 10
@places = Provider.all.where(:category.to_s => /.*#{searchterm}.*/)
.geo_near([ session[:latitude].to_f,session[:longitude].to_f ]).max_distance(radius)
#@places = Provider.all.where(:category.to_s => /.*#{searchterm}.*/)
#.within_circle(location: [[ session[:latitude].to_f,session[:longitude].to_f ], radius ])
#.sort(:servicescore.desc).sort(:pricescore.desc)
The code in my model
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Paranoia
include Mongoid::Geospatial
include Mongoid::MultiParameterAttributes
include Mongoid::Slug
include Mongoid::Spacial::Document
include Gmaps4rails::ActsAsGmappable
acts_as_gmappable :lat => 'latitude', :lon => 'longitude', :process_geocoding => true,
:check_process => :prevent_geocoding,
:address => "business_address"
field :location, :type => Point
spatial_index :location
field :officialname
field :business_description
field :category#, :type => Array
field :business_type
field :tax_office
field :tax_number
field :pin
field :business_phone
field :web_site
field :business_address
field :latitude
field :longitude
Answer: Dont use GeoNear, use #near or #near_sphere:
Model.near(geom: [1, 1])
# or
Model.near_sphere(geom: ...
# same:
Model.where(:geom.near => ...
Also, GeoNear is limited in 100 results. There's no accessor for #limit (easy to monkeypatch anyway)
Btw:
Version 5 of mongoid and this gem should be out and working =D