postgis基本用法

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章