PostGIS 기초 사용법

PostGIS의 사용법은 그리 어려울게 없다.

그냥 데이터를 사용하기 위한 기반 지식이 많이 필요하다.

기술적으로 알아야 할 것은 geometry 인덱싱, st_프로시저 정도로 많지 않고 지도 데이터, 좌표계 변환 등의 지식을 많이 알아야한다.

설치

http://postgis.net/install/

-- Enable PostGIS (includes raster)
CREATE EXTENSION postgis;
-- Enable Topology
CREATE EXTENSION postgis_topology;
-- Enable PostGIS Advanced 3D 
-- and other geoprocessing algorithms
-- sfcgal not available with all distributions
CREATE EXTENSION postgis_sfcgal;
-- fuzzy matching needed for Tiger
CREATE EXTENSION fuzzystrmatch;
-- rule based standardizer
CREATE EXTENSION address_standardizer;
-- example rule data set
CREATE EXTENSION address_standardizer_data_us;
-- Enable US Tiger Geocoder
CREATE EXTENSION postgis_tiger_geocoder;

 

인덱싱

 

ST_프로시저

많이 사용되는 것만 대강 기억하고 PostGIS doc를 찾아서 쓰면 된다.

https://postgis.net/docs/reference.html

폴리곤 문자열 좌표계로 변환
select st_geomfromtext('POLYGON ((206150.488 464470.391000001,206220.011 464532.584000001,206341.442 464351.384, 206150.488 464470.391000001))', 5174)
좌표계와 겹치는 좌표계 검색
select st_astext(geom) from t_mapdata from st_intersects(st_geomfromtext('POLYGON ((206150.488 464470.391000001,206220.011 464532.584000001,206341.442 464351.384, 206150.488 464470.391000001))', 5174));
지도의 좌표계를 4243좌표로 변환
select st_transform(geom, 4243) from t_mapdata;

 

ST_Intersects – 겹침

ST_Within – 완전포함

ST_Contains – 포함 within하고 비슷한데 확인필요

ST_Area – 넓이 구하기

ST_Buffer – 좀 넓게 잡기

초기데이터 설정

insert into public.spatial_ref_sys (srid, auth_name, auth_srid, srtext, proj4text) values(
105188,'USER',105188,'PROJCS["Korea 2000 / East Sea Belt 2010",GEOGCS["Korea 2000",DATUM["Geocentric_datum_of_Korea",SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6737"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4737"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",38],PARAMETER["central_meridian",131],PARAMETER["scale_factor",1],PARAMETER["false_easting",200000],PARAMETER["false_northing",600000],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","5188"]]','+proj=tmerc +lat_0=38 +lon_0=131 +k=1 +x_0=200000 +y_0=600000 +ellps=GRS80 +units=m +no_defs'
);

insert into public.spatial_ref_sys (srid, auth_name, auth_srid, srtext, proj4text) values(
105187,'USER',105187,'PROJCS["Korea 2000 / East Belt 2010",GEOGCS["Korea 2000",DATUM["Geocentric_datum_of_Korea",SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6737"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4737"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",38],PARAMETER["central_meridian",129],PARAMETER["scale_factor",1],PARAMETER["false_easting",200000],PARAMETER["false_northing",600000],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","5187"]]','+proj=tmerc +lat_0=38 +lon_0=129 +k=1 +x_0=200000 +y_0=600000 +ellps=GRS80 +units=m +no_defs'
);

insert into public.spatial_ref_sys (srid, auth_name, auth_srid, srtext, proj4text) values(
105186, 'USER', 105186 ,'PROJCS["Korea 2000 / Central Belt 2010",GEOGCS["Korea 2000",DATUM["Geocentric_datum_of_Korea",SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6737"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4737"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",38],PARAMETER["central_meridian",127],PARAMETER["scale_factor",1],PARAMETER["false_easting",200000],PARAMETER["false_northing",600000],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","5186"]]','+proj=tmerc +lat_0=38 +lon_0=127 +k=1 +x_0=200000 +y_0=600000 +ellps=GRS80 +units=m +no_defs'
);

insert into public.spatial_ref_sys (srid, auth_name, auth_srid, srtext, proj4text) values(
105185, 'USER', 105185, 'PROJCS["Korea 2000 / West Belt 2010",GEOGCS["Korea 2000",DATUM["Geocentric_datum_of_Korea",SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6737"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4737"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",38],PARAMETER["central_meridian",125],PARAMETER["scale_factor",1],PARAMETER["false_easting",200000],PARAMETER["false_northing",600000],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","5185"]]',
'+proj=tmerc +lat_0=38 +lon_0=125 +k=1 +x_0=200000 +y_0=600000 +ellps=GRS80 +units=m +no_defs'
);

 

 

GIS 분석 인프라 구성 – Ubuntu16.04, Postgresql9.5, PostGIS2.2

설치

sudo apt install -y postgresql postgis postgresql-9.5-dbg postgresql-common postgresql-9.5-postgis-2.2 postgresql-9.5-postgis-scripts

설치는 별거 손댈게 없다.

서버에서 스크립트를 돌릴 일이 있을 수 있으니

sudo apt install python3 python3-dbg python3-dev python3-dbf python3-pip
pip3 install psycopg2

설정

Postgresql

원격접속 가능하게 설정 – 필요한 경우

postgresql.conf

listen_addresses = 'localhost'

pg_hba.conf

postgres    all    all  0.0.0.0/24    md5

개발테스트용이 아닌 서비스용이라면 초기 설정할 때만 오픈해놨다가 접근권한을 127.0.0.1이나 허용된 서버만으로 제한하도록 한다.

계정 설정

root 생성

sudo -u postgres psql -U postgres
alter user postgres with encrypted password 'dkfldk3$';
\q

Postgis

디비 생성후

create database gis_db;
\connect gis_db;
create extension postgis;

postgis 설치가 완료되면

gis_db.public.spatial_ref_sys 테이블이 생성된다.

확인

select * from pg_catalog.pg_tables;

초기 데이터 준비

spatial_ref_sys에 표준 좌표계는 다 입력되어 있는편인데

공공기관에서 제공해주는 변태좌표계에 필요한 설정을 넣어준다.

id값이 충돌하지 않도록 주의.

 

GIS 너무 쉬운거 아니야?

아직 지옥문을 막 열었을 뿐.. 문이 닫히기 전에 돌아가라

 

RAW데이터를 수집해야한다.

 

공공기관의 데이터

정권이 바뀔때마다 지들 기분날 때 마다 데이터의 제공주체나 생산주체 담당자가 수시로 바뀌니 그때그때 확인을 해 봐야한다.

데이터 포맷 정보가 없는 경우도 많고 통일성도 없다.

따져도 소용없다. 그 사람들도 문제의식은 가지고 있는데.. 이게 장관급에서 프로젝트가 내려오지 않으면 어쩔 수 없는 부분이 있다. 여러 기관이 얽히고 얽혀서

데이터 제공 기관

행정표준코드 관리시스템 : https://www.code.go.kr/jsp/index.jsp

환경공간정보서비스 : https://egis.me.go.kr
생태자연도

국립생태원 : http://www.nie.re.kr/

국토환경정보센터 : http://www.neins.go.kr

국토지리원 : http://www.ngii.go.kr
수치지도, DEM(래스터)

국가공간정보포털 : http://www.nsdi.go.kr
연속지적도, 개별공시지가, 토지등급, 건물정보 …

주소, 행정동, 지적도, 건물정보, 등 넣어줘야하는데

국가교통정보센터 : http://www.its.go.kr/

교통정보공개서비스 : http://openapi.its.go.kr

기상청 : http://www.kma.go.kr

NASA 수치 데이터 : 한국 데이터는 없다고도 하고 잘 못 찾겠다.

Ubuntu12.04 postgresql with postgis

현재 우분투 버전 13.04 postgis설치시에 apt-get 기본패키지로 postgresql 9.1과 그에 딸린  postgis설치하면 제대로 동작을 하지않는다.

정확한 패키지명.. postgresql-9.1-postgis

 

2.x버전을 설치해야 제대로 동작한다고한다.

관련 페이지.

http://trac.osgeo.org/postgis/wiki/UsersWikiPostGIS20Ubuntu1210src

http://docs.geonode.org/en/latest/tutorials/admin/install/install_postgis.html

http://postgis.net/docs/postgis_installation.html#make_install_postgis_extensions

삭제되는경우를 대비하여 복사.

How to install PostGIS 2.0 on Ubuntu 12.10 (quantal) from source
Prerequisites

Several components are needed, which can either be built from source or installed from pre-built packages, as shown below.

Install prerequisite packages using:

sudo apt-get install build-essential postgresql-9.1 postgresql-server-dev-9.1 libgeos-c1 libxml2-dev libproj-dev libjson0-dev xsltproc docbook-xsl docbook-mathml
Optional package for raster support (this is required if you want to build the PostgreSQL extensions):

sudo apt-get install libgdal1-dev
Build PostGIS

wget http://download.osgeo.org/postgis/source/postgis-2.0.4.tar.gz
tar xfz postgis-2.0.4.tar.gz
cd postgis-2.0.4
PostGIS 2.0 can be configured to disable topology or raster components, using the configure flags --without-raster and/or --without-topology. The default is to build both. Note that raster is required for the extension installation method for PostgreSQL.

./configure
make
sudo make install
sudo ldconfig
sudo make comments-install
Lastly, enable the command-line tools to work from your shell:

sudo ln -sf /usr/share/postgresql-common/pg_wrapper /usr/local/bin/shp2pgsql
sudo ln -sf /usr/share/postgresql-common/pg_wrapper /usr/local/bin/pgsql2shp
sudo ln -sf /usr/share/postgresql-common/pg_wrapper /usr/local/bin/raster2pgsql
Spatially enabling a database

With PostgreSQL 9.1, there are two methods to add PostGIS functionality to a database: using extensions, or using enabler scripts.

PostGIS Extension for PostgreSQL

Spatially enabling a database using extensions is a new feature of PostgreSQL 9.1.

Connect to your database using pgAdmin or psql, and run the following commands. To add postgis with raster support:

CREATE EXTENSION postgis;
To add topology support, a second extension can be created on the database:

CREATE EXTENSION postgis_topology;
Enabler Scripts / Template

Enabler scripts can be used to either build a template, or directly spatially enable a database. This method is older than the extension method, but is required if the raster support is not built.

The following example creates a template, which can be re-used for creating multiple spatially-enabled databases. Or if you just want to make one spatially enabled database, you can modify the commands for your needs.

PostGIS:

sudo -u postgres createdb template_postgis
sudo -u postgres psql -d template_postgis -c "UPDATE pg_database SET datistemplate=true WHERE datname='template_postgis'"
sudo -u postgres psql -d template_postgis -f /usr/share/postgresql/9.1/contrib/postgis-2.0/postgis.sql
sudo -u postgres psql -d template_postgis -f /usr/share/postgresql/9.1/contrib/postgis-2.0/spatial_ref_sys.sql
sudo -u postgres psql -d template_postgis -f /usr/share/postgresql/9.1/contrib/postgis-2.0/postgis_comments.sql
with raster support:

sudo -u postgres psql -d template_postgis -f /usr/share/postgresql/9.1/contrib/postgis-2.0/rtpostgis.sql
sudo -u postgres psql -d template_postgis -f /usr/share/postgresql/9.1/contrib/postgis-2.0/raster_comments.sql
with topology support:

sudo -u postgres psql -d template_postgis -f /usr/share/postgresql/9.1/contrib/postgis-2.0/topology.sql
sudo -u postgres psql -d template_postgis -f /usr/share/postgresql/9.1/contrib/postgis-2.0/topology_comments.sql
See also

 https://help.ubuntu.com/community/PostgreSQL