简体   繁体   English

如何使用mongoDB和mongoose计算2个用户之间的距离

[英]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 现在,我希望使用地理空间服务查询数据库,以查找从user1到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 并将属性索引为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. 地球半径约为3959英里(6371公里)。

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. 猫鼬中有一个错误 ,该错误将GeoJSON中的坐标剥离,并将它们像旧对一样发送到mongo,这导致近距离运算以弧度而不是米为单位。

It might be fixed now but I am not sure. 现在可能已修复,但我不确定。

You can also read in the document for geoNear in mongoose api site 您还可以在猫鼬api网站中阅读geoNear的文档

You can read about GeoJson here 您可以在此处阅读有关GeoJson的信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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