首页 > 解决方案 > 我如何在 typeorm 和 postgres 中使用经度和纬度

问题描述

我当前的实体如下所示:

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

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

    @Column()
    longitude: number 

    @Column()
    latitude: number 
}

但我想知道是否有更好的方法来做到这一点,使用特殊的 postgres 类型,它适用于 typeorm。

标签: postgresqlnestjstypeorm

解决方案


您将要查看 Typeorm 中的 PostGIS 和 Spatial Column 支持:

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

PostGIS 是一个扩展,您可以在 postgres 数据库中启用以处理空间数据类型。安装 PostGIS 后,您可以在 Typeorm 查询构建器中使用其特殊的空间数据函数,就像使用由 GeoJSON 支持的任何其他 PG 函数一样。

Typeorm 的 postgres 驱动程序在内部使用 GeoJSON 与 PostGIS 一起工作,因此当您定义 Typeorm 模型时,您需要添加@types/geojson,这将使您可以按照您的要求正确键入您的 Typeorm 列。

例如,您可以导入Geometry类型定义并按如下方式键入您的列:

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

在您的情况下,您可能希望将您的latitudelongitude列组合成一个列location——它可以使用该point()函数将纬度和经度组合成一个Geometry类型。

作为一个人为的示例,您可以执行以下操作:

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

这会将locationcustomers表上的列(作为示例)设置为geometry(point)与旧金山的纬度/经度位置相对应的列类型。

如果您想将 lat/lon 的现有双精度列值(这是您应该自行存储 lat/lon 的方式)迁移到locationtype 的单个列geometry(point),您可以使用ST_MakePointPostGIS 开箱即用的函数。

IE

-- 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;

推荐阅读