通过过滤按最接近的地理位置对数据进行排序

use*_*038 1 javascript jquery

我正在尝试找到有人正在使用我的应用程序的正确建筑物。现在我已经设法进行了相当糟糕的过滤,我需要改进它。

我的目标是通过过滤将最近的建筑物返回给使用该应用程序的人,因此在同一建筑物中移动时尽可能好地过滤它,而不会产生错误。

我的 fetch 返回一个 api JSON 数组,如下所示:

{
"data": [
{
  "id": 1,
  "city": "CITY",
  "building_name": "Building 1",
  "building_address": "Address 123",
  "latitude":  "57.7052809",
  "longitude": "16.9367817"
},
{
  "id": 2,
  "city": "CITY",
  "building_name": "Building 2",
  "building_address": "Address 456",
  "latitude":  "35.7054509",
  "longitude": "16.9366141"
}
],
}
Run Code Online (Sandbox Code Playgroud)

这是我的代码

fetch('http://localhost:8888/api/buildings')
.then(response => response.json())
.then(data => {

  userCoordinates = {
    latitude:  35.7053509,
    longitude: 16.9362301
  }


  const returnedBuilding = Object.entries(data.data).map(([inst, key]) => key)
  .filter(thing => (thing.latitude > userCoordinates.latitude - .5 &&
     thing.latitude < userCoordinates.latitude + .5) &&
      (thing.longitude > userCoordinates.longitude -.5 &&
       thing.longitude < userCoordinates.longitude + .5));

       console.log(returnedBuilding);

})
Run Code Online (Sandbox Code Playgroud)

nhu*_*ann 7

我强烈建议考虑更改数据模型以利用存储在 mongoDB 数据库中的GeoJSON点。这将使您能够利用 mongoDB 强大的内置地理空间查询。使用上面的现有数据模型作为起点,您的新数据模型可能如下所示:

{
  "id": 1,
  "city": "CITY",
  "building_name": "Building 1",
  "building_address": "Address 123",
  "location": {
    "type": "Point",
    "coordinates": [ // IMPORTANT: note the order is longitude, latitude
      16.9367817, // longitude
      57.7052809, // latitude
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

上面对象中的位置属性是 GeoJSON 点。现在,您无需从数据库中获取每个位置并在客户端中自行进行计算,而是可以在建筑物数据库中查询距离用户位置最近的建筑物。假设用户坐标为latitude: 35.7053509, longitude: 16.9362301,您的查询可能如下所示(通过 GET 请求):

http://localhost:8888/api/buildings?lat=35.7053509&lng=16.9362301&maxDistance=2000

mongoDB 文档提供了如何处理地理空间查询的示例。此示例取自文档,是您的 api 如何处理请求的:

// If you're using express.js, pull the params off the query object
const { lat, lng, maxDistance } = req.query;
const buildings = db.buildings.find(
  {
    location:
      {
        $near:
          {
            $geometry: { type: "Point", coordinates: [lng, lat] },
            $maxDistance: maxDistance
          }
      }
  }
)
  .then(buildings => res.json({ buildings })) // respond to the client
  .catch(err => console.log(err)) // do something with the error
Run Code Online (Sandbox Code Playgroud)

来自服务器的响应将是指定范围内的所有建筑物的列表maxDistance,按距用户位置的距离(从最近到最远)排序。MongoDB 地理空间查询的速度和性能令人难以置信。如果您的客户只需要单个结果,您甚至可以对操作的第db.find一个结果进行切片,并从 api 返回单个构建。

希望这是有道理的并且有帮助!如果您没有使用过 mongoDB 和/或 geoJSON 对象,一开始可能看起来有点令人畏惧,但相信我,这会让您的生活变得更加轻松。当您设置数据库和集合时,可能会出现另一个小问题。您需要确保添加建筑物集合的索引以支持地理空间查询。从文档中:

db.buildings.createIndex( { location: "2dsphere" } )

然后创建您的集合并向其中添加您的建筑文档。

如果您需要任何澄清,请随时跟进。我建议阅读 mongoDB 的文档并在线搜索更多示例。