Sequelize geospatial query: find “n” closest points to a location

后端 未结 3 652
旧时难觅i
旧时难觅i 2020-12-16 18:13

Using Sequelize and geospatial queries, if I want to find the \"n\" closest points to a certain location, how should the Sequelize query be?

Assume I have a model th

3条回答
  •  情话喂你
    2020-12-16 18:51

    Building off @Edudjr's answer, this is what I did to get it to work in my project:

    const location = sequelize.literal(`ST_GeomFromText('POINT(${ startLongitude } ${  startLatitude })')`)
    const distance = sequelize.fn('ST_Distance_Sphere', sequelize.col('location'), location)
    
    const inRadius = await Position.findAll({
        order: distance,
        where: sequelize.where(distance, { $lte: radius }),
        logging: console.log
    })
    

    where Position is defined as:

    sequelize.define('Position', {
        location: DataTypes.GEOMETRY('POINT')
    })
    

    Note that Point requires the coordinates in the format of (longitude latitude)

    https://gis.stackexchange.com/questions/209008/incorrect-arguments-to-st-distance-sphere-in-special-cases

    https://dba.stackexchange.com/questions/33410/whats-the-difference-between-pointx-y-and-geomfromtextpointx-y

提交回复
热议问题