Maximum distance using the Mongoid Model.near method

I have been using geopolar queries for some time, but I cannot figure out how to limit the results within a certain radius. For example, how can I limit my search to 20 miles in this query?

Place.near(:coordinates => location.reverse) # must reverse the resulting coordinates array because mongo stores them backwards [lng,lat] 
+4
source share
4 answers

The length of the arc with the difference of latitudes from north to south is about 60 nautical miles, 111 kilometers or 69 miles at any latitude; You can learn more about it here on Wikipedia or the geospatial page of the Mongo Earth Round, but the Maps are flat .

Divide the distance by 69 or 111 when using miles or km respectively, so now you can request it like this:

 Place.where(:coordinates => {"$near" => location.reverse , '$maxDistance' => 20.fdiv(69)}) 
+10
source

MongoDB supports the maxDistance attribute ( MongoDB request )

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

And the mongoid_geo extension has an inside_box and inside_center method .

+3
source

:

 lng, lat, dis = params[:lng], params[:lat], params[:dis] page, per_page = params[:page] || 1 , params[:per_page] || 30 sms = SideMongo.geo_near([lng.to_f,lat.to_f], max_distance: dis.to_i, unit: "km".to_sym, spherical: true).sort_by!{|r| r.geo[:distance] } page_sms = sms.per(per_page).page(page) 
+1
source

Try it...

The $ maxDistance value required by Mongo is in radians, so you need to convert the distance on the earth's surface to the latitude / longitude angle.

https://en.wikipedia.org/wiki/Arc_(geometry)

http://docs.mongodb.org/manual/tutorial/calculate-distances-using-spherical-geometry-with-2d-geospatial-indexes/

angle (radians) = distance_at_surface / radius_of_earth

angle = 10 km / 6371 km

angle = 10sm / 3960sm

0
source

All Articles