简体   繁体   English

sequelize&postgis按点距离排序

[英]sequelize & postgis sort by distance from point

I have a problem with search including sort by distance from some point. 我有一个搜索问题,包括从某个点到距离的排序。 Here is my code and what I'm trying to do. 这是我的代码和我正在尝试做的事情。 Thanks for help 感谢帮助

const Sequelize = require('sequelize');

var Flat = db.define('flat', {
    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true
    }
});

var FlatAddress = db.define('flat_address', {
    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    flat_id: {
        type: Sequelize.INTEGER,
        foreignKey:true,
        allowNull:false,
        references: {
            model:'flats',
            key: 'id'
        }
    },
    city: {
        type: Sequelize.STRING(50) //post_town
    },
    location: {
        type: Sequelize.GEOMETRY('POINT')
    }
});

Flat.hasOne(FlatAddress, { as: 'Address', foreignKey: 'flat_id', otherKey: 'id', onDelete: 'cascade' });

FlatAddress.belongsTo(Flat, { foreignKey: 'id', otherKey: 'flat_id', onDelete: 'cascade' });

and i want to do something like this 我想做这样的事情

var POINT = {lat, lng} ?? 
Flats.findAndCountAll({
        where: filter,
        order:  [
                [ { model: FlatAddresses, as: 'Address' },
 '//here should be something like distance from POINT//', 'ACS']
        ],
        include: [
            { model: FlatAddresses, as: 'Address'}
        ],
        offset,
        limit
    })

I didn't find examples or docs for my case. 我没有为我的案例找到示例或文档。 thanks 谢谢

The following statement will find Flats within your latitude and longitude, include a field called distance in the payload, and order it by distance . 以下语句将在您的纬度和经度中找到Flats ,包括在有效载荷中称为distance的字段,并按distance对其进行排序。

const myDistance = 10000; // e.g. 10 kilometres
Flats.findAll({
  attributes: {
    include: [
      [
        Sequelize.fn(
          'ST_Distance',
          Sequelize.col('location'),
          Sequelize.fn('ST_MakePoint', longitude, latitude)
        ),
        'distance'
      ]
    ]
  },
  where: Sequelize.where(
    Sequelize.fn(
      'ST_DWithin',
      Sequelize.col('location'),
      Sequelize.fn('ST_MakePoint', longitude, latitude),
      myDistance
    ),
    true
  ),
  order: Sequelize.literal('distance ASC')
});

Please keep in mind: I do not know which SRID you are using. 请记住:我不知道您使用的是哪个SRID。 Therefore, I'm using metres to measure distance though you may have to convert metres to radius in your code. 因此,虽然您可能需要在代码中将米转换为半径,但我使用米来测量距离。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM