PostGIS 是PostgreSQL数据库一个空间数据库扩展,它添加了对地理对象的支持,允许在 SQL 中运行空间查询
PostGIS官网:About PostGIS | PostGIS
PostGIS官方教程:PostGIS 简介 — Introduction to PostGIS
PostGIS相关教程:文章目录汇总 - 知乎 (zhihu.com)
本文基于官方教程描述PostGIS中的Geometry
创建空间表test
:
CREATE TABLE test(
id SERIAL PRIMARY KEY,
name VARCHAR(64),
geom geometry
);
设置坐标系WGS-84
,代码4326
:
SELECT UpdateGeometrySRID('test','geom',4326);
使用SQL插入数据:
INSERT INTO test VALUES(0, 'Point', 'POINT(0 0)'),
(1, 'Linestring', 'LINESTRING(0 0, 1 1, 2 1, 2 2)'),
(2, 'Polygon', 'POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))'),
(3, 'PolygonWithHole', 'POLYGON((0 0, 10 0, 10 10, 0 10, 0 0),(1 1, 1 2, 2 2, 2 1, 1 1))'),
(4, 'Collection', 'GEOMETRYCOLLECTION(POINT(2 0),POLYGON((0 0, 1 0, 1 1, 0 1, 0 0)))');
查询数据:
SELECT * FROM test;
使用几何查看器查看:
查询几何类型、维数、空间坐标系代码
SELECT id, name, ST_GeometryType(geom), ST_NDims(geom), ST_SRID(geom)
FROM test;
查询点的X、Y坐标:
SELECT id, name, ST_X(geom), ST_Y(geom)
FROM test WHERE name = 'Point';
查询LineString属性的的函数主要有:
SELECT id, name, ST_Length(geom), ST_StartPoint(geom), ST_EndPoint(geom), ST_NPoints(geom)
FROM test WHERE ST_GeometryType(geom) = 'ST_LineString';
查询Polygon属性的函数主要有:
SELECT id, name, ST_Area(geom), ST_NRings(geom), ST_AsText(ST_ExteriorRing(geom)),
ST_InteriorRingN(geom, 1), ST_Perimeter(geom)
FROM test WHERE ST_GeometryType(geom) = 'ST_Polygon';
Collection包含:
查询Collection属性的函数主要有:
SELECT id, name, ST_NumGeometries(geom), ST_GeometryN(geom, 1), ST_Area(geom), ST_Length(geom)
FROM test WHERE ST_GeometryType(geom) = 'ST_GeometryCollection';
PostGIS支持Well-known text(WKT),主要函数有:
SELECT ST_GeomFromText('Point(1 0)',4326), ST_AsText(geom), ST_AsEWKT(geom)
FROM test WHERE ST_GeometryType(geom) = 'ST_Point';
Well-known binary(WKB)
SELECT ST_AsBinary(geom), ST_AsEWKB(geom), ST_GeomFromWKB(ST_AsBinary(geom))
FROM test WHERE ST_GeometryType(geom) = 'ST_Point';
Geographic Mark-up Language(GML)
Keyhole Mark-up Language(KML)
Scalable Vector Graphics(SVG)
SELECT ST_AsGML(geom), ST_AsKML(geom), ST_AsGeoJson(geom), ST_AsSVG(geom)
FROM test WHERE ST_GeometryType(geom) = 'ST_Point';
[1]9. 几何(Geometries) — Introduction to PostGIS