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]
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)})
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With