1 创建postgis数据库
\c demo; -- 切换到目标数据库
create extension postgis; -- 启用postgis(包括raster),pg版本10.1,postgis版本2.4
create table cities (id int4, city varchar(50)); -- 创建表
select AddGeometryColumn('cities', 'geom_pt', 4326, 'point', 2); -- 添加geometry列
insert into cities (id,city,geom_pt) values(1, 'beijing', st_GeomFromText('point(116 40)', 4326));
select st_AsText(geom_pt) from cities;
2 常用函数
- ST_AsText ST_AsGeojson ST_GeomFromText ST_GeomFromGeojson
let strGeojson = '{"type": "LineString",
"coordinates": [[115, 39], [116, 39], [116, 40], [115, 39]]}'
let strText = 'LineString(115 39, 116 39, 116 40, 115 39)'
select ST_AsText(ST_GeomFromGeojson(strGeojson)) -- strText
select ST_AsGeojson(ST_GeomFromText(strText)) -- strGeojson
- ST_PointFromText ST_LineFromText ST_PolyFromText
-- 点线面的wkt写法
let pt = 'point(115.39)'
let ls = 'linestring(115 39, 116 39, 116 40, 115 39)'
let pg = 'polygon((115 39, 116 39, 116 40, 115 39))'
- ST_MakePoint ST_MakeLine ST_MakePolygon
- ST_Point ST_Polygon
-- st_point(x, y)遵循OGC标准,是st_makepoint的OGC别名,st_makepoint(x, y, z?, m?)不遵循OGC标准
-- 结果相同
ST_Point(116, 40)
ST_MakePoint(116, 40)
// 转为geography,结果相同
SELECT ST_Point(116, 40)::geography;
SELECT ST_SetSRID(ST_Point(116, 40),4326)::geography;
SELECT CAST(ST_SetSRID(ST_Point(116, 40),4326) As geography);
- 计算面积st_area
-- 平面/球面/椭球面的面积
select st_area(geom), st_area(geog), st_area(geog, false) from counties where name = '阿荣旗';
-- geometry和geography转换,前2相等,后3相等
select st_area(geom), st(geog :: geometry), st_area(geog), st_area(geom :: geography),
st_area(st_setsrid(geom, 4326) :: geography) from counties where name = '阿荣旗';
- 空间关系计算(Geometry Processing)
-- 包含关系,ST_Contains(geomA, geomB),注意不支持geog的运算
ST_Contains(geom, ST_Point(113.5, 33.6))
-- 相交,支持geog
ST_Intersection(geom,
ST_MakeBox2D(
ST_Point(113, 30),
ST_Point(114, 40)
))
3 疑问
- Which data store should I use geometry or geography
-- 在线帮助
http://postgis.net/docs/manual-2.4/PostGIS_FAQ.html#idm1062
-- 本地帮助, Chapter 3. PostGIS Frequently Asked Questions
-- 3.7 I'm all confused. Which data store should I use geometry or geography?
-- geom和geog转换成wkt和geojson后输出相同
select ST_AsText(geom), ST_AsText(geog),
ST_AsGeojson(geom), ST_AsGeojson(geog) from counties where name = '阿荣旗';
参考:
http://postgis.net/docs/manual-2.4/
http://live.osgeo.org/zh/quickstart/postgis_quickstart.html