当前位置: 首页 > 面试题库 >

在给定坐标和最大距离的情况下找到最接近某个点的点-使用带有MEAN Stack的Mongoose查询结果不确定

丁沛
2023-03-14
问题内容

我有一个问题,即使在查看相关的Stack Overflow Q / A之后,也无法解决。

我正在使用Ahmed Haque方法重用Scotch的“创建MEAN Stack Google Map
App教程”
开发应用程序

我试图实现使用的应用程序 谷歌地图API 绘制PointsLineStrings并且Polygons其坐标被包含在
以GeoJSON 存储在一个文件中 的MongoDB 实例。

我正在使用Mongoose数据构建架构并查询MongoDB数据库。

我想找到最接近的点CP到一定点数P0 给定P0's latitude and longitude,并给予最大半径
distance用来寻找感兴趣点。

在此处输入图片说明

给定图像,例如,如果我插入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);

这是我的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
            });
        }
});

它运行得非常好,而且我可以得出一些要点。

然后,我更改了自己的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);

这是我的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);
    });
});

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
        });
    }
});

这是标记的示例:

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

  }
}

$ near运算符如何与distance和maxDistance一起工作:

摘自Ahmed
Haque的Scotch用Google地图制作MEAN应用(第二部分)

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

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

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

提前致谢。


问题答案:

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

本质上,此问题是由模式引起的,因为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);

和以下 查询

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);
        });
    });

希望对您有所帮助!

编辑

我提出的模式会给LineStringsand 带来一些问题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);

多边形模型

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);

LineString插入

{  
    "name" : "myLinestring", 
    "geo" : {
        "type" : "LineString", 
        "coordinates" : [
            [
                17.811, 
                12.634
            ], 
            [
                12.039, 
                18.962
            ], 
            [
                15.039, 
                18.962
            ], 
            [
                29.039, 
                18.962
            ]
        ]
    }
}

多边形插入:

{  
    "name" : "Poly", 
    "geo" : {
        "type" : "Polygon", 
        "coordinates" :  [
                           [ 
                             [25.774, -80.190], [18.466, -66.118], 
                             [32.321, -64.757], [25.774, -80.190] 
                           ]
                         ]
    }
}


 类似资料:
  • 给定一定数量的节点,是否有公式计算AVL树的最大和最小高度? 例如: 教科书中的问题: 一棵包含3个节点、5个节点和7个节点的AVL树的最大/最小高度是多少<教科书式答案: 3个节点的AVL树的最大/最小高度为2/2,5个节点为3/3,7个节点为4/3 我不知道他们是否通过一些神奇的公式计算出来,或者他们是否画出了每个给定高度的AVL树并以这种方式确定。

  • 我有一段代码,它显示了随机矩阵中的最小值和最大值,而不使用min/max命令: 如何找到最小和最大坐标/位置?我只需要使用for或loop函数,我使用的是matlab版本2018a

  • 我正在学习CLR中的一节,它描述了使用分而治之的方法,使用两点之间的欧几里德距离来找到最近的点对。 有一个问题,要求找到最近的点对之间的manhatten距离,使用类似的方法。但是,我不能把握两者之间的区别。以下是我能想到的: 3)递归到我们的点子集<=3为止(在这种情况下使用蛮力) 4)最小距离可以是从任何一个递归调用返回的距离--称它为D。 5)找到线“L”周围2D宽度内所有点,然后对于每个这

  • 我想查询表A中每个点(id)到表B中每个多边形(id)的距离。对于距离计算,我使用ST_距离。但是,ST_Distance(显然)返回到每个多边形的距离。但我只需要每个点的“最接近”结果。到目前为止,我尝试了下面的查询,它返回了正确的结果,但是(当然)只返回了一个点。 结果应该是这样的: 你有什么提示吗?非常感谢你。 更新1 运行上述查询(3h 24m)后,返回的结果为空。然而,应该有一个结果。括

  • 问题内容: 有一条折线,其中折线的顶点列表为[[x1,y1),(x2,y2),(x3,y3),…]和一个点(x,y)。在Shapely中,返回两个几何之间的最短距离。 但是我还需要找到最接近点(x,y)的线上的点的坐标。在上面的示例中,这是距离1.4142135623730951单位的对象上的点的坐标。计算距离时,该方法应具有坐标。有什么方法可以从此方法返回它吗? 问题答案: 您正在描述的GIS术

  • 问题内容: 我有两个2d numpy数组:x_array包含x方向上的位置信息,y_array包含y方向上的位置。 然后,我有一长串x,y点。 对于列表中的每个点,我需要找到最接近该点的位置(在数组中指定)的数组索引。 我已经根据这个问题天真的产生了一些有效的代码: 在numpy数组中找到最接近的值 即 我正在大型数据集上执行此操作,并且真的想加快速度。谁能优化这个? 谢谢。 更新:根据@silv