在给定坐标和最大距离的情况下找到某个点的最近点 - 使用具有MEAN堆栈的Mongoose未定义查询结果

And*_*M16 13 javascript mongoose mongodb node.js mongodb-query

我有一个问题,在某些日子里我无法解决,甚至查看相关的Stack Overflow Q/A.

我正在开发一个应用程序重用Scotch的创建一个MEAN堆栈谷歌地图应用程序教程由艾哈迈德哈克方法.

我正在尝试实现一个使用Google Maps API绘制的应用程序Points,LineStrings以及Polygons哪些坐标包含在存储在MongoDB实例中的GeoJson文件中.

我正在使用Mongoose为我的数据构建S​​chema并查询我的MongoDB数据库.

我想找到 给定CP某个点的最近点,并给出用于找到感兴趣点的最大半径 .P0P0's latitude and longitudedistance

在此输入图像描述

鉴于图像结束,我想,例如,如果我插入2000(公里),我的查询将找到距离P0最远2000公里的所有点.在这个例子中,它应该给我P1和P2.

当我只有点数时,我能够做到这一点Mongoose Schema.

Schema只有标记(点):

// Pulls Mongoose dependency for creating schemas
var mongoose    = require('mongoose');
var Schema      = mongoose.Schema;

// Creates a User Schema. 
var MarkerSchema = new Schema({
    username: {type: String, required: true},
    location: {type: [Number], required: true}, // [Long, Lat]
    created_at: {type: Date, default: Date.now},
    updated_at: {type: Date, default: Date.now}
});

// Indexes this schema in 2dsphere format
MarkerSchema.index({location: '2dsphere'});

module.exports = mongoose.model('mean-markers', MarkerSchema);
Run Code Online (Sandbox Code Playgroud)

这是我的Old Query for only Markers:

var User = require('./model.js');

app.post('/query/', function(req, res) {

        // Grab all of the query parameters from the body.
        var lat = req.body.latitude;
        var long = req.body.longitude;
        var distance = req.body.distance;
        var reqVerified = req.body.reqVerified;

        // Opens a generic Mongoose Query
        var query = User.find({});

        // ...include filter by Max Distance (converting miles to meters)
        if (distance) {

            // Using MongoDB's geospatial querying features
            query = query.where('location').near({
                center: {
                    type: 'Point',
                    coordinates: [long, lat]
                },

                // Converting meters to miles
                maxDistance: distance * 1609.34,
                spherical: true
            });
        }
});
Run Code Online (Sandbox Code Playgroud)

它工作得非常好,我能够获得接近的分数.

然后,我改变了我的Schema动态,也支持Polylines and Polygons.

我可以使用以下内容插入和绘制新的点,折线和多边形Schema:

var mongoose = require('mongoose');
var GeoJSON  = require('geojson');
var Schema   = mongoose.Schema;

// Creates a Location Schema.
var LocationSchema = new Schema({
                                    name: {type: String, required: true},
                                    location: {
                                      type: {type : String, required: true},
                                      coordinates : [Schema.Types.Mixed]
                                    },
                                    created_at: {type: Date, default: Date.now},
                                    updated_at: {type: Date, default: Date.now}
});

LocationSchema.index({location: '2dsphere'});
module.exports = mongoose.model('mean-locations', LocationSchema);
Run Code Online (Sandbox Code Playgroud)

这是我的Mongoose Query:

var GeoObjects = require('./model.js');

app.post('/query/', function(req, res) {

    // Grab all of the query parameters from the body.
    var lat = req.body.latitude;
    var long = req.body.longitude;
    var distance = req.body.distance;

    var query;

    if (distance) {
        query = GeoObjects.find({'location.type':'Point'})
                    .where('location.coordinates').near({
                      center: {
                        type: 'Point',
                        coordinates: [lat, long]
                      },
                      // Converting meters to miles
                      maxDistance: distance * 1609.34,
                      spherical: true
        });
    }

    // Execute Query and Return the Query Results
    query.exec(function(err, users) {
        if (err)
            res.send(err);
        console.log(users);
        // If no errors, respond with a JSON of all users that meet the criteria
        res.json(users);
    });
});
Run Code Online (Sandbox Code Playgroud)

console.log(users); 给我 undefined.

queryCtrl.js中记录查询结果给出了以下错误消息:

name: "MongoError", message: "error processing query: ns=MeanMapApp.mean-locatio…ed error: unable to find index for $geoNear query", waitedMS: 0, ok: 0, errmsg: "error processing query: ns=MeanMapApp.mean-locatio…ed error: unable to find index for $geoNear query"

同样有点变化:

app.post('/query/', function(req, res) {

    // Grab all of the query parameters from the body.
    var lat = req.body.latitude;
    var long = req.body.longitude;
    var distance = req.body.distance;

    console.log(lat,long,distance);

    var points = GeoObjects.find({'location.type':'Point'});

    var loc = parseFloat(points.location.coordinates);
    console.log(JSON.stringify(loc));

    if (distance) {
        var query = points.near(loc, {
                      center: {
                        type: 'Point',
                        coordinates: [parseFloat(lat), parseFloat(long)]
                      },
                      // Converting meters to miles
                      maxDistance: distance * 1609.34,
                      spherical: true
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

这是一个标记的示例:

{
  "name": "user01",
  "location": {
                "type":"Point",
                "coordinates": [102.0, 0.0]

  }
}
Run Code Online (Sandbox Code Playgroud)

$ near运算符如何使用distance和maxDistance:

来自苏格兰威廉姆斯的制作MEAN应用程序和谷歌地图(第二部分)

MongoDB搜索参数$ near及其相关属性maxDistance和spherical指定我们想要覆盖的范围.我们将查询体的距离乘以1609.34,因为我们想要获取用户的输入(以英里为单位)并将其转换为MongoDB期望的单位(以米为单位).

  1. 我为什么得到undefined
  2. 这个问题是否可能是由我的架构引起的?
  3. 我怎样才能解决这个问题?

如果您想收到一些澄清,请在下面发表评论.

提前致谢.

Sol*_*tos 5

我不明白你的所有代码下面是什么,但我知道一件事:
如果你使用谷歌的雷达搜索,你必须考虑到

允许的最大半径为50 000米.

只需看看他们的文档

这意味着如果你尝试更高的半径,结果可能是零


And*_*M16 1

我终于设法解决了这个问题。

本质上,该问题是由架构引起的,因为2dIndex引用了错误的字段(type and coordinates)

我使用以下架构解决了:

var mongoose = require('mongoose');
var GeoJSON  = require('geojson');
var Schema   = mongoose.Schema;

var geoObjects = new Schema({
                               name : {type: String},
                               type: {
                                       type: String,
                                       enum: [
                                               "Point",
                                               "LineString",
                                               "Polygon"
                                             ]
                                      },
                                coordinates: [Number],
                                created_at: {type: Date, default: Date.now},
                                updated_at: {type: Date, default: Date.now}
});

// Sets the created_at parameter equal to the current time
geoObjects.pre('save', function(next){
   now = new Date();
   this.updated_at = now;
   if(!this.created_at) {
      this.created_at = now
   }
   next();
});

geoObjects.index({coordinates: '2dsphere'});

module.exports = mongoose.model('geoObjects', geoObjects);
Run Code Online (Sandbox Code Playgroud)

以及以下查询

app.post('/query/', function(req, res) {

        // Grab all of the query parameters from the body.
        var lat = req.body.latitude;
        var long = req.body.longitude;
        var distance = req.body.distance;

        var query = GeoObjects.find({'type':'Point'});

        // ...include filter by Max Distance 
        if (distance) {

            // Using MongoDB's geospatial querying features. 
            query = query.where('coordinates').near({
                center: {
                    type: 'Point',
                    coordinates: [lat, long]
                },

                // Converting meters to miles
                maxDistance: distance * 1609.34,
                spherical: true
            });
        }

        // Execute Query and Return the Query Results
        query.exec(function(err, geoObjects) {
            if (err)
                res.send(err);

            // If no errors, respond with a JSON 
            res.json(geoObjects);
        });
    });
Run Code Online (Sandbox Code Playgroud)

我希望它能帮助别人!

编辑

LineStrings我放置的模式会导致和出现一些问题Polygons

这是允许使用的正确模式geoQueries

linestring-model.js:

var mongoose = require('mongoose');
var Schema   = mongoose.Schema;

// Creates a LineString Schema.
var linestrings = new Schema({
    name: {type: String, required : true},
    geo : {
        type : {type: String,
            default: "LineString"},
        coordinates : Array
    },
    created_at: {type: Date, default: Date.now},
    updated_at: {type: Date, default: Date.now}
});

// Sets the created_at parameter equal to the current time
linestrings.pre('save', function(next){
    now = new Date();
    this.updated_at = now;
    if(!this.created_at) {
        this.created_at = now
    }
    next();
});

linestrings.index({geo : '2dsphere'});
module.exports = mongoose.model('linestrings', linestrings);
Run Code Online (Sandbox Code Playgroud)

多边形模型.js

var mongoose = require('mongoose');
var Schema   = mongoose.Schema;

// Creates a Polygon Schema.
var polygons = new Schema({
    name: {type: String, required : true},
    geo : {
        type : {type: String,
            default: "Polygon"},
        coordinates : Array
    },
    created_at: {type: Date, default: Date.now},
    updated_at: {type: Date, default: Date.now}
});

// Sets the created_at parameter equal to the current time
polygons.pre('save', function(next){
    now = new Date();
    this.updated_at = now;
    if(!this.created_at) {
        this.created_at = now
    }
    next();
});

polygons.index({geo : '2dsphere'});
module.exports = mongoose.model('polygons', polygons);
Run Code Online (Sandbox Code Playgroud)

线串插入

{  
    "name" : "myLinestring", 
    "geo" : {
        "type" : "LineString", 
        "coordinates" : [
            [
                17.811, 
                12.634
            ], 
            [
                12.039, 
                18.962
            ], 
            [
                15.039, 
                18.962
            ], 
            [
                29.039, 
                18.962
            ]
        ]
    }
}
Run Code Online (Sandbox Code Playgroud)

多边形插入:

{  
    "name" : "Poly", 
    "geo" : {
        "type" : "Polygon", 
        "coordinates" :  [
                           [ 
                             [25.774, -80.190], [18.466, -66.118], 
                             [32.321, -64.757], [25.774, -80.190] 
                           ]
                         ]
    }
}
Run Code Online (Sandbox Code Playgroud)