Search code examples
mongodbgpsdistancegeospatialgeojson

MongoDB geoNear command result distance in kilometer


I am using mongoDB to store GPS locations data as this GeoJSON document

{"type" : "Point", "coordinates" : [33.313183, 44.465632]}

{"type" : "Point", "coordinates" : [33.2926487, 44.4159651]}

Update: I also ensured 2dspher index like follow

db.test.ensureIndex( { loc : "2dsphere" } )

I got the coordinates from Google maps Now if I search using this command I cant convert the distances in result to kilometers

db.runCommand({geoNear: 'test', spherical: true, near: {type: "Point" , coordinates: [33.2926487, 44.4159651]}})

the result is as follow

"results" : [
    {
        "dis" : 0.0033427770982422957,
        "obj" : {
            "_id" : ObjectId("54a96f348fa05fcaed637a22"),
            "loc" : {
                "type" : "Point",
                "coordinates" : [
                    33.2926487,
                    44.4159651
                ]
            }
        }
    },
    {
        "dis" : 5764.7060911604085,
        "obj" : {
            "_id" : ObjectId("54a96f4c8fa05fcaed637a23"),
            "loc" : {
                "type" : "Point",
                "coordinates" : [
                    33.313183,
                    44.465632
                ]
            }
        }
    }
]

the first result is expected to be Zero since its the same point that I want to get the distance from source = destination coordinates, but still has value.

the second value I cant convert to Kilometers, in Google distance calculator is about 5.26KM.


Solution

  • The distances are being returned in meters. To convert to kilometers, divide by 1000. You can have MongoDB do this using the distanceMultiplier option:

    db.runCommand({ "geoNear" : "test", "spherical" : true, "distanceMultiplier" : 0.001, "near" : { "type" : "Point" , "coordinates" : [33.2926487, 44.4159651] } })