【问题标题】:how can i search database table with latitude and longitude using sequelize我如何使用 sequelize 搜索具有纬度和经度的数据库表
【发布时间】:2020-01-09 01:01:14
【问题描述】:

我有一个存储表,其中包含一个 lat_long 列,它将每个存储纬度/经度存储为 sequelize 中的几何点。我想根据来自前端的请求正文的纬度/经度的接近度来搜索商店。已尝试在 Stackoverflow 中利用与此相关的许多相关主题(答案),但了解到查询可以这样编写。

const location = sequelize.literal(`ST_GeomFromText('POINT(${lng} ${lat})', 4326)`);

    User.findAll({
      attributes: [[sequelize.fn('ST_Distance_Sphere', sequelize.literal('geolocation'), location),'distance']],
      order: 'distance',
      limit: 10,
      logging: console.log
    })
    .then(function(instance){
      console.log(instance);
    })

试过了,效果很好,但面临的挑战是;在这个例子和我目前看到的几乎所有样本中,他们使用了只返回距离但我想返回表中所有字段的属性。然后我尝试删除该属性,然后我得到的响应没有根据几何(距离)搜索,我也尝试使用 where 但出现错误。

下面显示的是我最新的查询,它返回错误,请问我该怎么做?谢谢。

export const getNearestStoreWithCategory = async (lat, long) => {
  try {
    const location = sequelize.literal(`ST_GeomFromText('POINT(${lat} ${long})')`);
    const distance = sequelize.fn('ST_Distance_Sphere', sequelize.literal('lat_long'), location)
    const storeArr = await Store.findAll({
      order: distance,
      where: sequelize.where(distance),
      limit: 20
    })
    return storeArr
  } catch (error) {
    return error
  }
}

【问题讨论】:

  • 请我仍然需要对此的答案或其他方法来解决它

标签: node.js geolocation sequelize.js


【解决方案1】:

https://sequelize.org/v4/manual/tutorial/querying.html 的文档中,我猜您在示例代码中缺少的是包含到要作为数据库响应返回的字段的距离,而不是仅计算距离并返回;

const location = sequelize.literal(`ST_GeomFromText('POINT(${lng} ${lat})', 4326)`);

User.findAll({
    attributes: {
        include: [[sequelize.fn('ST_Distance_Sphere', sequelize.literal('geolocation'), location),'distance']]
    },
    order: 'distance',
    limit: 10,
    logging: console.log
})
    .then(function(instance){
        console.log(instance);
    })

这应该给出一个类似的查询; SELECT id, OTHER_FIELDS_OF_THIS_TABLE, ST_Distance_Sphere(geolocation) AS distance ...

现在,这是未经测试的代码,但您可以试一试并评论是否有帮助。

【讨论】:

  • 谢谢@Orelongz 这真的很有帮助。它返回了我想要的。谢谢你,我非常高兴、赞赏和尊重你的知识。
猜你喜欢
  • 2023-03-31
  • 2010-10-05
  • 2012-05-24
  • 2013-11-21
  • 2016-12-10
  • 1970-01-01
  • 2019-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多