Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum distance with Mongoid's Model.near method

I've been using the geo near queries for a while now, but I can't seem to figure out how to limit the results to within a certain radius. For example, how do I limit the search to within 20 miles in this query?

Place.near(:coordinates => location.reverse) 
# must reverse the resulting coordinates array because mongo stores them backwards [lng,lat]
like image 398
Avishai Avatar asked Dec 09 '22 05:12

Avishai


2 Answers

The length of an arcdegree of north-south latitude difference, is about 60 nautical miles, 111 kilometres or 69 statute miles at any latitude; You can read more about here in wikipedia or in mongo geospatial page The Earth is Round but Maps are Flat.

Divide distance by 69 or 111 when using mile or km respectively, so now you can query it like this

Place.where(:coordinates => {"$near" => location.reverse , '$maxDistance' => 20.fdiv(69)})
like image 57
RameshVel Avatar answered Dec 23 '22 10:12

RameshVel


MongoDB supports a maxDistance attribute (MongoDB Querying)

db.places.find( { loc : { $near : [50,50] , $maxDistance : 5 } } )

And the mongoid_geo extension has a within_box and within_center method.

like image 20
notyce Avatar answered Dec 23 '22 11:12

notyce