Home > Software design >  Sequelize – finding point in range
Sequelize – finding point in range

Time:12-09

I have an Address model that has a point attribute of type geometry defined. I want to create a function when I pass latitude, longitude and range and it returns all of the addresses within that range (in meters). I tried to follow what has been written here but I'm getting:

DatabaseError [SequelizeDatabaseError]: LWGEOM_dwithin: Operation on mixed SRID geometries (Point, 4326) != (Point, 0)

This is how I defined by point in the Address model:

point: {
   type: DataTypes.GEOMETRY('Point'),
   allowNull: true,
},

And this is the function I'm trying to write:

const findInRangeFrom = (latitude, longitude, range) => {
  return Address.findAll({
    attributes: {
      include: [[
        Sequelize.fn(
          'ST_Distance',
          Sequelize.col('point'),
          Sequelize.fn('ST_MakePoint', longitude, latitude),
        ),
        'distance',
      ]],
    },
    where: Sequelize.where(
      Sequelize.fn(
        'ST_DWithin',
        Sequelize.col('point'),
        Sequelize.fn('ST_MakePoint', longitude, latitude),
        range,
      ),
      true,
    ),
    order: Sequelize.literal('distance ASC'),
  });
};

How can I make this work?

CodePudding user response:

If geometries in DB are stored in the SRID 4326, then you need to set the same SRID for your test point like this:

Sequelize.fn('ST_SetSRID', Sequelize.fn('ST_MakePoint', longitude, latitude), 4326)

If vice versa then you need to indicate SRID 4326 for the point column:

Sequelize.fn('ST_SetSRID', Sequelize.col('point'), 4326)
  • Related