Postgis随笔


一、Geometry 与 Geography 的区别,以及如何选择?

geometry: 几何类型,平面。两个点之间的最短路径是一条直线。
geography: 地理类型,球体。在球体上两点之间的最短路径是一个大圆弧线。
必读:
http://postgis.net/docs/using_postgis_dbmanagement.html#PostGIS_Geography
http://postgis.net/docs/using_postgis_dbmanagement.html#PostGIS_GeographyVSGeometry

二、Geometry的几种类型:

POINT:点
LINESTRING:线
POLYGON:面
MULTIPOINT:多点
MULTILINESTRING:多线
MULTIPOLYGON:多面
参考:http://postgis.net/docs/using_postgis_dbmanagement.html#OGC_Validity

三、WKB 与 WKB

WKT:the Well-Known Text,使用 ST_AsText 可以转为这个格式。
WKB:the Well-Known Binary, 使用 ST_AsBinary 可以转为这个格式。
如何从 WKT、WKB转为 Geometry类型呢? 答案就是使用ST_GeometryFromText、ST_GeomFromWKB函数。
参考:http://postgis.net/docs/using_postgis_dbmanagement.html#OpenGISWKBWKT

如何存储行政边界。

一、数据库表创建:

CREATE TABLE testgeom(gid serial PRIMARY KEY, the_geom geometry(MULTIPOLYGON, 4326));

如果是已有表,添加字段可以用AddGeometryColumn: http://postgis.net/docs/AddGeometryColumn.html

二、数据插入:

INSERT INTO testgeom(the_geom) VALUES (‘SRID=4326;MULTIPOLYGON(((120.5311 31.3652,120.5578 31.3390,120.5623 31.3383,120.5923 31.2795,120.5949 31.2685,120.606803 31.2659,120.6066 31.2707,120.6143 31.2711,120.6178 31.2846,120.63531 31.2870,120.6372 31.2837,120.64341 31.2892,120.653707 31.28808,120.6587 31.2859,120.660157 31.288142,120.661709 31.298719,120.655937 31.3194,120.654671 31.32327,120.648623 31.334765,120.6525 31.3399,120.6469 31.3422,120.6545 31.3430,120.6462 31.3426,120.6373 31.3529,120.6226 31.3525,120.6122 31.3627,120.5937 31.3667,120.5869 31.3618,120.5809 31.3627,120.5745 31.3767,120.5599 31.3852,120.5311 31.3652)))’);

注意:插入数据时,如果不指定“SRID=4326”,报错:ERROR: Geometry SRID (0) does not match column SRID (4326)

三、测试某个点是否在这个区域内。

市政府:
SELECT ST_Contains(the_geom, ST_SetSRID(ST_Point(120.591482,31.307665), 4326)) from testgeom where gid = 1;
-> true

东环路西:
SELECT ST_Contains(the_geom, ST_SetSRID(ST_Point(120.656411,31.317506), 4326)) from testgeom where gid = 1;
-> true

东环路东:
SELECT ST_Contains(the_geom, ST_SetSRID(ST_Point(120.657489,31.317013), 4326)) from testgeom where gid = 1;
-> false

查询时,如果不使用ST_SetSRID指定4326,报错:ERROR: Operation on mixed SRID geometries

四、制作Shapefile(可选)

pgsql2shp -f gusu -h localhost -u postgres -P password database “SELECT * FROM testgeom WHERE gid = 1”

制作后可以在 http://www.mapshaper.org/ 尝试打开。

转载自:https://blog.csdn.net/feng88724/article/details/52153954

You may also like...