Warm tip: This article is reproduced from serverfault.com, please click

How can i use longitude and latitude with typeorm and postgres

发布于 2020-11-27 17:35:45

My current entity looks like this:

import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class Landmark extends BaseEntity {
    @PrimaryGeneratedColumn('uuid')
    id: string;

    @Column()
    longitude: number 

    @Column()
    latitude: number 
}

But i wonder if there is a better way to do this, with a special postgres type, that works with typeorm.

Questioner
Yassine Bridi
Viewed
0
JosephHall 2020-11-28 12:29:37

You're going to want to look into PostGIS and Spatial Column support in Typeorm:

https://github.com/typeorm/typeorm/blob/master/docs/entities.md#spatial-columns

PostGIS is an extension you can enable in your postgres database for dealing with spatial datatypes. Once you have PostGIS installed, you can use its special spatial data functions inside of a Typeorm query builder as you would any other PG function, backed up by GeoJSON.

Typeorm's postgres driver uses GeoJSON internally to work with PostGIS, so when you're defining Typeorm models, you need to add @types/geojson, which will let you correctly type your Typeorm columns as you asked.

For instance, you can import the Geometry type definition and type your column as so:

import { Geometry } from 'geojson';
...
@Column
location: Geometry

In your case, you might want to combine your latitude and longitude columns into a single column -- location -- which can use the point() function to combine latitude and longitude into a single Geometry type.

As a contrived example, you could do something like:

UPDATE customers SET location = 'point(37.7, 122.4)' where id = 123;

This would set the location column on your customers table (as an example) to a geometry(point) column type corresponding to the lat/lon position of San Francisco.

If you wanted to migrate existing double precision column values for lat/lon (which is how you should store lat/lon on their own) to a single location column of type geometry(point), you could use the ST_MakePoint function that comes out of the box with PostGIS.

i.e.

-- Assuming you have a lat and lon columns on the `customers` table that you are migrating to the PostGIS geometry(point) type
UPDATE customers SET location = ST_MakePoint(lat, lon) where id = 123;