【问题标题】:Not able to get location with mongodb geowithin and centersphere无法使用 mongodb geowithin 和 centersphere 获取位置
【发布时间】:2022-06-15 18:52:50
【问题描述】:

我正在尝试获取用户坐标半径 5 公里内的位置,但每次我尝试时,它都显示为空。

在我的代码下方,用于定位。

const { latitude, longitude } = req.body;
const options = {
    location: {
      $geoWithin: { $centerSphere: [[latitude, longitude], 10 / 3963.2] },
    },
  };

  try {
    console.log(getocationAre);
    res.json({
      msg: "data",
      size: getocationAre.length,
      data: getocationAre,
    });
  } catch (e) {
    res.json({
      msg: "Error",
      data: e,
    });
  }

【问题讨论】:

  • 为此,您应该使用$geoNear,而不是$geoWithin
  • @nimrodserok 仍然无法正常工作
  • 第一:10/3963.2 表示 10 英里,因此大约 16 公里,而不是 5。第二:您已反转纬度/经度。试试{ $centerSphere: [[longitude, latitude], ... 最后:$geoWithin 在这里可以用。
  • 所以我也必须在数据库中更改它[经度,纬度] ??
  • 是的!确保将坐标点存储为 [long,lat] 例如[x,y]。我很惊讶您在插入时没有收到无效的数据范围错误,但显然有许多坐标对在其中互换 long 和 lat still 会产生有效(尽管是错误的)位置。参考:mongodb.com/docs/manual/reference/operator/query/centerSphere

标签: mongodb geolocation


【解决方案1】:

由于您已包含 10/3963.2,因此您正在搜索 10 英里范围内的内容。如果该范围内没有文档,则不会显示任何内容。如果要在半径 5Km 范围内搜索,请改为包含 3.10/3963.2。如果您愿意,可以使用此代码来帮助您动态获取距离。

const radius = unit === 'mi' ? distance / 3963.2 : distance / 6378.1; /*63.78 is for Kilometer*/

那么,

{ 
locResults: { $geoWithin: 
  { $centerSphere: [[longtitude, latitude], radius] } 
} }

另外,请始终先使用经度。希望能帮助您解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-12
    • 1970-01-01
    • 2013-06-29
    • 2017-07-03
    • 1970-01-01
    • 2014-10-26
    相关资源
    最近更新 更多