如何使用 mongoDB 和 mongoose 计算两个用户之间的距离
How to calculate distance between 2 users using mongoDB and mongoose
我有一个用户模式 (mongoose),它有字段 'location'- 它由一个 [longitude, latitude]
数组组成
现在,我想使用地理空间服务查询数据库,以便找到从用户 1 到用户 2 的距离
我该怎么做?
这应该可以帮助您入门
您需要在架构中定义 属性:
'location' : {
type: { type: String },
coordinates: []
},
并将 属性 索引为 2dsphere
yourSchema.index({'location' : "2dsphere"})
您可以执行以下操作:
//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);
});
但是有几点需要注意:
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 (e.g. the Earth) in the same units as the distance
measurement.
radians to distance: multiply the radian measure by the radius of the
sphere (e.g. 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.
取自here
在 mongoose 中有一个 bug 从 GeoJSON 中剥离坐标并将它们像传统对一样发送到 mongo 这导致近距离操作以弧度而不是弧度工作米.
现在可能已修复,但我不确定。
您还可以阅读 geoNear in mongoose api site
的文档
您可以阅读 GeoJson here
我有一个用户模式 (mongoose),它有字段 'location'- 它由一个 [longitude, latitude]
数组组成现在,我想使用地理空间服务查询数据库,以便找到从用户 1 到用户 2 的距离
我该怎么做?
这应该可以帮助您入门
您需要在架构中定义 属性:
'location' : {
type: { type: String },
coordinates: []
},
并将 属性 索引为 2dsphere
yourSchema.index({'location' : "2dsphere"})
您可以执行以下操作:
//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);
});
但是有几点需要注意:
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 (e.g. the Earth) in the same units as the distance measurement.
radians to distance: multiply the radian measure by the radius of the sphere (e.g. 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.
取自here
在 mongoose 中有一个 bug 从 GeoJSON 中剥离坐标并将它们像传统对一样发送到 mongo 这导致近距离操作以弧度而不是弧度工作米.
现在可能已修复,但我不确定。
您还可以阅读 geoNear in mongoose api site
的文档您可以阅读 GeoJson here