Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在MongoDB中查询半径内的位置_Mongodb_Mongodb Query - Fatal编程技术网

在MongoDB中查询半径内的位置

在MongoDB中查询半径内的位置,mongodb,mongodb-query,Mongodb,Mongodb Query,如果我有以下格式的文件: { pos: { lat: 0, lon: 30 } } 在集合用户中(请假装这些是真实的lat/lon:-) 获取某个半径(例如:50英里)内所有值的正确方法是什么?这是一个三步过程 步骤1)在文档中嵌入GeoJSON点 步骤2)使用2dsphere为点的路径编制索引 步骤3)使用$geointen和$centerSphere查询文档中的点 若要执行地理空间查询,需要更改文档结构以匹配点。 看起来像这样 loc : { type : "Poin

如果我有以下格式的文件:

{
    pos:  { lat: 0, lon: 30 }
}
在集合用户中(请假装这些是真实的lat/lon:-)

获取某个半径(例如:50英里)内所有值的正确方法是什么?

这是一个三步过程

  • 步骤1)在文档中嵌入GeoJSON点
  • 步骤2)使用
    2dsphere
    为点的路径编制索引
  • 步骤3)使用
    $geointen
    $centerSphere
    查询文档中的点
若要执行地理空间查询,需要更改文档结构以匹配点。 看起来像这样

loc : {
    type : "Point",
    coordinates : [lng, lat]
}
用于将集合转换为点格式的示例代码

// sample setup code.
// use test; 
// db.positions.drop();
// db.positions.insert({
    // pos : {
        // lat : 0,
        // lon : 30
    // }
// });
db.positions.find().forEach(function (doc) {
    var point = {
        _id : doc._id,
        loc : {
            type : "Point",
            coordinates : [doc.pos.lon, doc.pos.lat]
        }
    };
    db.positions.update(doc, point);
});
db.positions.find().pretty();
之后,您可以在查询中使用
$geointen
$near
运算符,如下面的示例所示

例子 安装程序 查询:查找5英里内的地标。 输出 更多信息:

使用MongoDB逐步进行径向位置查询 MongoDB非常适合使用地理空间数据计算地理位置 基本上,您可以在带有**2dsphere**索引的集合上使用“$geointen:”和“$centerSphere:”。但是让我们一步一步走。 场景:让我们假设一个用户正在浏览他所在地区的酒店。。。他想显示距离他当前位置50英里范围内的酒店,而你的数据库应用程序中充满了酒店数据。您可能会使用一些地图API将它们显示在地图上(如果这是您之后要做的,请务必查看底部的链接),但对于本例,我们只希望在MongoDB数据库中从酒店位置获取50英里范围内的酒店数据

首先创建测试文档集合“hotels” *您可能需要编辑
坐标,使其与您的
附近的位置,如果您希望此代码在没有任何更改的情况下工作
半径距离

然后用2dsphere索引
位置

db.places.createIndex( { location : "2dsphere" } )
现在根据里程和您的位置进行查询。 首先准备好工具:
// custom function - convert miles to radian
let milesToRadian = function(miles){
    var earthRadiusInMiles = 3963;
    return miles / earthRadiusInMiles;
};

// or custom function - convert km to radian
let kmToRadian = function(miles){
    var earthRadiusInMiles = 6378;
    return miles / earthRadiusInMiles;
};


// custom function - returns array with current user geolocation points - [latitude, longitude]
function getUserLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (position) {
      let geoPoints = [position.coords.latitude, position.coords.longitude];
      console.log(geoPoints);
      return geoPoints;
    });
  } else { 
    console.log("Geolocation is not supported by this browser.");
  }
}
现在,使用您的新工具为MongoDB地理空间数据创建查询

var query = {'location' : {$geoWithin: { $centerSphere:  getUserLocation(), milesToRadian(50) ]}}}

// MongoDB example query could look something like:
// {'location': {$geoWithin: { $centerSphere: [ [ 40.000000001, 5.000000001 ], 0.012616704516780217 ]}}}

db.hotels.find(query);
MongoDB返回距离用户位置50英里范围内的文档(酒店)列表。请记住,您的文档需要实现GeoJSON结构来存储位置,并且它需要是index2dsphere。结果将按距离用户-ASC的距离排序

输出 观看/阅读更多 MongoDB-地理空间查询: https://docs.mongodb.com/manual/geospatial-queries/ https://www.youtube.com/watch?v=3xP-gzh2ck0
再往前走! 把你的数据放到地图上。这里有一些非常酷的教程。 使用MapBox API打开街道地图:

使用谷歌JavaScript API的谷歌地图:

如果要将地址转换为地理编码点,可以使用gui或

例如,在浏览器中搜索“Poland Pultusk”,或通过添加到字符串参数
&format=json

另外,MapBox每月可免费下载5万次API调用,每1000次API调用可免费下载5美元。 谷歌每月为你提供200美元的免信用使用费,共计2.8万美元 免费API调用,然后7$/1000 API调用。拿起你的武器,玩得开心:>

工具:MongoDB Compass(*非社区版)

谢谢@Larry Battle,你知道它是如何按mongo排序的吗?谢谢,mongo 3.4仍然有效。刚刚添加了“kms”var kmsToRadian=函数(kms){var earthRadiusInkms=6371;返回kms/earthRadiusInkms;};
// Your 'hotels' collection could look something like this:
db.hotels.insertMany([
  {
    'name': 'Golebiewski',
    'address': 'Poland, Mikolajki',
    'location': { type: "Point", coordinates: [ 40, 5.000001 ] },
    'tel': '000 000 000'
  },
  {
    'name': 'Baltazar',
    'address': 'Poland, Pultusk 36',
    'location': { type: "Point", coordinates: [ 40, 5.000002 ] },
    'tel': '000 000 000'
  },
  {
    'name': 'Zamek',
    'address': 'Poland, Pultusk',
    'location': { type: "Point", coordinates: [ 40, 5.000003 ] },
    'tel': '000 000 000'
  },
])
db.places.createIndex( { location : "2dsphere" } )
// custom function - convert miles to radian
let milesToRadian = function(miles){
    var earthRadiusInMiles = 3963;
    return miles / earthRadiusInMiles;
};

// or custom function - convert km to radian
let kmToRadian = function(miles){
    var earthRadiusInMiles = 6378;
    return miles / earthRadiusInMiles;
};


// custom function - returns array with current user geolocation points - [latitude, longitude]
function getUserLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (position) {
      let geoPoints = [position.coords.latitude, position.coords.longitude];
      console.log(geoPoints);
      return geoPoints;
    });
  } else { 
    console.log("Geolocation is not supported by this browser.");
  }
}
var query = {'location' : {$geoWithin: { $centerSphere:  getUserLocation(), milesToRadian(50) ]}}}

// MongoDB example query could look something like:
// {'location': {$geoWithin: { $centerSphere: [ [ 40.000000001, 5.000000001 ], 0.012616704516780217 ]}}}

db.hotels.find(query);
{ "_id" : ObjectId("5d3130f810050424d26836d6"), "name" : "Golebiewski", "address" : "Poland, Mikolajki", "location" : { "type" : "Point", "coordinates" : [ 40, 5.000001 ] }, "tel" : "000 000 000" }
{ "_id" : ObjectId("5d3130f810050424d26836d7"), "name" : "Baltazar", "address" : "Poland, Pultusk 36", "location" : { "type" : "Point", "coordinates" : [ 40, 5.000002 ] }, "tel" : "000 000 000" }
{ "_id" : ObjectId("5d3130f810050424d26836d8"), "name" : "Zamek", "address" : "Poland, Pultusk", "location" : { "type" : "Point", "coordinates" : [ 40, 5.000003 ] }, "tel" : "000 000 000" }