5

I'm using MongoDB geospatial queries -- $near, geoNear, etc. -- and I'd like to know how to turn the dis result of the geoNear command as well as the radius argument for $within queries to/from readable units like miles or kilometers.

yprez
  • 14,854
  • 11
  • 55
  • 70
Chris Forrette
  • 3,194
  • 2
  • 28
  • 37

3 Answers3

19

Using geoNear command for a dis value in kilometers add the parameter:

distanceMultiplier: (6371 * Math::PI / 180.0)
Dex
  • 12,527
  • 15
  • 69
  • 90
tandem
  • 199
  • 2
  • 3
4

if your data is in geographic coordinates (i.e. 30.47921 N -121.45724 W) then you need to convert your underlying projection with the units you want (choose a projection that preserves distance) or you need to convert the distance in coordinates to something like miles.

Use the Haversine formula for calculations http://www.movable-type.co.uk/scripts/latlong.html

TheSteve0
  • 3,530
  • 1
  • 19
  • 25
  • Thanks for your answer! My data is indeed latitude/longitude points, and I was able to use the Haversine formula to calculate distance between the results and origin point by plugging in both sets of lat/lon points, but I'm still not sure what to do specifically with 'dis' and 'radius'. Could you clarify what you meant by "convert your underlying projection"? Seems like it might be simpler to convert 'dis' than to plug in both lat/lon sets, no? Would I need to rearrange the Haversine formula to fit my needs here? If so, what variable(s) in the equation might 'dis'/'radius' plug into? – Chris Forrette Aug 16 '10 at 01:05
  • 1
    Hi Chris, I had a similar question (http://stackoverflow.com/questions/3878702/mongodb-bound-queries-how-do-i-convert-mile-to-radian). If you guys don't mind, can you explain in more detail the solution? Do you have to use map/reduce? Thanks again! – Abe Oct 07 '10 at 07:44
  • If you guys are using Mongo > 1.8 you can use the spherical model: http://www.mongodb.org/display/DOCS/Geospatial+Indexing#GeospatialIndexing-TheEarthisRoundbutMapsareFlat – TheSteve0 Apr 18 '12 at 16:24
1

Note if you're using Mongodb version 2.6.0 there is a bug which always enables the new behavior for spherical coordinate systems to return distance in meters (based on WGS84 coordinates).

The documentation states that giving the $near parameter in legacy coordinates rather than GeoJSON should still return radians. This has been fixed in newer versions.

The bug report: Bug #13540

jlapoutre
  • 1,767
  • 18
  • 22