Specht
Specht

Reputation: 142

Typeorm Postgis order by nearest Point

I have a postgis database with a bunch of points and I would like to get the points in order of the distance to my own position (longitude and latitude).

So I want to do something like:

const markers = await this.markerRepo.find({
  where: {
    type: "test"
  },
  order: { position: 'ASC' },
});

But I want to order them in relation to my current position.

This id my table entity (Nestjs):

@Entity()
 export class Marker {
   @PrimaryGeneratedColumn()
   id: number;

   @Column({
     type: 'geography',
     spatialFeatureType: 'Point',
     srid: 4326,
     nullable: true,
   })
   position: Point;
 
   @Column()
   type: string;
 }

If you need any more information please let me know

Upvotes: 1

Views: 1934

Answers (1)

Specht
Specht

Reputation: 142

Turns out Typeorm does not support Postgis (Who would have thought)

The solution is to just send a SQL request like this:

const markers = await this.markerRepo.query(
  `SELECT * , ST_Distance(ST_MakePoint(${yourLatitude}, ${yourLongitude} ), position) AS dist FROM marker ORDER BY dist LIMIT 10;`,
);

Upvotes: 3

Related Questions