简体   繁体   中英

How to calculate distance between 2 users using mongoDB and mongoose

I have a user schema (mongoose) which has the field 'location'- it consists of an array of [longitude, latitude]

now, i wish to query the db, using the geospatial services, in order to find the distance from user1 to user2

How do i do that?

This should get you started

You need to define a property in your schema:

'location' : {
    type: { type: String },
    coordinates: []
},

And index the property as 2dsphere

yourSchema.index({'location' : "2dsphere"})

Than you can do the following:

//Model.geoNear(GeoJSON, options, [callback]) need a GeoJSON point to search in radius
    var point = { type : "Point", coordinates : [data.coordinates.long, data.coordinates.lat] };
        YourModel.geoNear(point, { maxDistance : data.distance /coordinatesUtils.earthRadius, spherical : true }, function(err, results, stats) {
            res.status(200);
            res.json(results);
        });

But there are a few things to note:

For spherical query operators to function properly, you must convert distances to radians, and convert from radians to the distances units used by your application.

To convert: distance to radians: divide the distance by the radius of the sphere (eg the Earth) in the same units as the distance measurement.

radians to distance: multiply the radian measure by the radius of the sphere (eg the Earth) in the units system that you want to convert the distance to.

The radius of the Earth is approximately 3,959 miles or 6,371 kilometers.

Taken from here

There was a bug in mongoose that strip the coordinate from the GeoJSON and send them like legacy pair to mongo which causes the near operation to work in radians instead of meters.

It might be fixed now but I am not sure.

You can also read in the document for geoNear in mongoose api site

You can read about GeoJson here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM