gpt4 book ai didi

node.js - Mongoose 按半径查找地理点

转载 作者:太空宇宙 更新时间:2023-11-03 23:05:13 30 4
gpt4 key购买 nike

我尝试按半径找到地理点,我找到了教程解释如何做到这一点。

教程片段:

首先我们需要创建一个架构。这些文档为我们提供了一些有关如何存储地理空间数据的示例。我们将在我们的示例中使用旧格式。建议将经度和纬度存储在数组中。该文档警告使用值的顺序,经度排在第一位。

var LocationSchema = new Schema({  
name: String,
loc: {
type: [Number], // [<longitude>, <latitude>]
index: '2d' // create the geospatial index
}
});

首先,您可以在 Controller 中创建一个如下所示的方法:

findLocation: function(req, res, next) {  
var limit = req.query.limit || 10;

// get the max distance or set it to 8 kilometers
var maxDistance = req.query.distance || 8;

// we need to convert the distance to radians
// the raduis of Earth is approximately 6371 kilometers
maxDistance /= 6371;

// get coordinates [ <longitude> , <latitude> ]
var coords = [];
coords[0] = req.query.longitude;
coords[1] = req.query.latitude;

// find a location
Location.find({
loc: {
$near: coords,
$maxDistance: maxDistance
}
}).limit(limit).exec(function(err, locations) {
if (err) {
return res.json(500, err);
}

res.json(200, locations);
});
}

引用教程: How to use Geospatial Indexing in MongoDB with Express and Mongoose

将教程中的源代码实现到我的项目后,我没有从数据库中收到正确的半径点(点不在半径内)。

我的问题是如何按半径接收地理点(公里或米不重要)?

谢谢,迈克尔。

最佳答案

我不久前在自己的数据库中处理过类似的问题。四处挖掘并找到答案很棘手,所以我将在这里分享。 Mongoose 的 DB 包的地理空间元素没有很好的文档记录。

.find 查询中,您需要使用比上面更复杂的对象。我发现以下构建工程,其中 maxDistance 的单位是米,coords 是[经度,纬度]的数组。

Location.find({
loc: {
$near: {
$geometry: {
type: "Point",
coordinates: coords
},
$maxDistance: maxDistance
}
}
}).then((err, locations) => {
// do what you want here
})

这消除了处理地球圆周和所有困惑的需要。现在,这种查询风格是 Mongoose 原生的。我发现下面的函数有助于快速进行这些查询,因此您不必每次都处理那么多的格式。

var locQuery = (coords, distance) => {
return { loc: { $near: { $geometry: { type: "Point", coordinates: coords }, $maxDistance: parseInt(distance)}}}
}

关于node.js - Mongoose 按半径查找地理点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36190373/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com