我将餐厅的地理坐标存储在MongoDB数据库中。
现在,我需要创建一个循环来获取所有餐馆的地理坐标和用户地理坐标,以获得最近的5家餐馆。我不知道如何循环和匹配用户的地理坐标。
我想要恰好有5家餐厅在我附近,因为Google place API集成在前端,所以我只能获得我需要匹配的地理坐标,以便在我附近获得确切的餐厅。
nearby_restro: (req, res) => {var user_id = req.user;var reqdata = req.body;var lat = reqdata.lat;
var long = reqdata.long;
locationModel.find({
"loc": {$near: [longitude = long, latitude = lat]}}, (err, data) => {console.log(err)
console.log(data)})
model
userId :{ type: mongoose.Schema.Types.ObjectId, required: true, auto: true},
loc: {
type: {
type: String, // Don't do `{ location: { type: String } }`
enum: ['Point'], // 'location.type' must be 'Point'
},
cordinates:[{
longitude:{type:String },
latitude:{type:String },
}],我希望通过使用restro和用户在long和lat中的坐标来获得用户的所有附近餐厅。我使用的是用户坐标,但这个查询对我不起作用。
发布于 2021-09-10 07:44:39
MongoDB地理空间使用geoJSON。下面是模式应该是什么样子。请注意,geo字段是使用2dsphere建立索引的。
const productSchema = new Schema({
name: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
geo: {
type: {
type: String, // Don't do `{ location: { type: String } }`
enum: ['Point'], // 'location.type' must be 'Point'
default: 'Point',
},
coordinates: [
{ type: Number },
],
},
}, { timestamps: true });
productSchema.index({ geo: '2dsphere', name: 'text' });要查询产品集合,我们将使用MongoDB $geoNear查询
const products = ProductModel.aggregate([
{
$geoNear: {
near: { type: 'Point', coordinates: [<lat>, <lng>] },
key: 'geo',
distanceField: 'dist.calculated',
spherical: true,
},
},
{ $limit: 10 },
]);distanceField将返回一个数字,显示项目和传递的坐标之间的距离。
https://stackoverflow.com/questions/69112197
复制相似问题