공간정보거점대학 postgis 고급과정

70
2014 년 1 년 20 년 년년년년년 년년년년 년년년년 년년 년년 GIS 년년 년년 년년년년 년년년 ([email protected]) PostGIS 년년 한한한 한한

Upload: junghwan-yun

Post on 24-Jun-2015

5.960 views

Category:

Technology


8 download

DESCRIPTION

1월21일 공간정보거점대학 오픈소스GIS 프로그래밍과정 PostGIS

TRANSCRIPT

Page 1: 공간정보거점대학 PostGIS 고급과정

2014 년 1 월 20 일 국토교통부 공간정보 거점대학

오픈 소스 GIS 심화 과정

㈜엔지스윤정환 ([email protected])

PostGIS 고급

한국어 지부

Page 2: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

목차

I. PostGIS 설치 및 환경설정 I-1. PostGIS 개요 I-2. PostGIS 설치하기 I-3. PostGIS 환경설정 I-4. pgAdmin & Query Tool 사용하기

II. 공간데이터베이스 관리 II-1. 공간 데이터베이스 생성 II-2. 공간 데이터 생성 & 로딩 & 추출 II-3. 래스터 데이터 생성 & 로딩

III. 공간함수 사용하기 III-1. Geometry

III-2. Spatial Relationships / Joins / Indexing / Projection

III-3. Geography

III-4. Geometry Constructing Functions

III-5. More Spatial Joins

IV. 어플리케이션을 이용한 PostGIS 사용하기 IV-1. 프로그램 설치하기 IV-2. QGIS 이용한 PostGIS 사용하기 IV-3. OpenJump 이용한 PostGIS 사용하기 IV-4. uDig 이용한 PostGIS 사용하기 IV-5. JDBC Driver 이용한 PostGIS 이용하기 IV-6. .NET Driver 이용한 PostGIS 이용하기

V. PostGIS 그밖의 기능 V-1. Tuning PostgreSQL for Spatial

V-2. Query Plans

V-3. 백업 & 복원 V-4. pgRouting 소개 V-5. Reference

Page 3: 공간정보거점대학 PostGIS 고급과정

I. PostGIS 설치 및 환경설정

- 일러두기 -

• 본 자료는 모두 Creative Commons License CC-BY-NC 을 따릅니다 .

• 본 교재에서는 교육의 편의상 Windows 32 비트 기반의 프로그램들을 위주로 설명합니다 .

• 본 교재에서 사용하는 샘플 데이터 셋은 실제 정보와 다르므로 교육용 이외에는 사용할 수 없습니다 .

Page 4: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

PostGIS 란 ?

I-1. PostGIS 개요

PostgreSQL 기반 spatial types, indexes, functions 의 3 가지 기능을 추가한 공간 데이터베이스

Spatial databases store/manipulate spa-tial objects– data types, indexes, and functions

Spatial data types– shapes - point, line, polygon

Spatial indexing – efficient processing of spatial operations

Spatial functions, – querying of spatial properties and relation-

ships.

http://www.postgis.net/

1

Page 5: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

I-2. PostGIS 설치하기

① http://www.postgresql.org/download/에 접속하여 PostgreSQL 최신버전 (PostgreSQL 9.3.2) 을 내려 받음② http://download.osgeo.org/postgis/windows/에 접속하여 PostGIS 최신버전 (PostGIS 2.1.1) 을 내려받음③ [ 설치프로그램 \postgis] 경로로 이동하여 PostgreSQL, PostGIS 최신버전을 설치

– DBMS 설치 : postgresql-9.3.2-1-windows– Spatial Extension 설치 : postgis-bundle-pg93x32-setup-2.1.1-1

④ PostgreSQL, PostGIS 기본적인 설정에 따라 설치를 완료 ⑤ [ 시작메뉴 ] – [PostgreSQL 9.3] – [pgAdmin] 을 실행

PostgreSQL 단독설치 (Application Stack Builder)

PostgreSQL 설치 PostGIS 설치 pgAdmin 실행

2

Page 6: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

I-2. PostGIS 설치하기

① http://boundlessgeo.com/에 접속하여 OpenGeo Suite 최신버전을 내려받음② [ 설치프로그램 \postgis] 경로로 이동하여 OpenGeo Suite 3.0.2 버전을 복사③ OpenGeo Suite 기본적인 설정에 따라 설치를 완료 ④ [ 시작메뉴 ] – [OpenGeo Suite 3.0.2] – [OpenGeo Suite Dashboard] 를 실행 ⑤ OpenGeo Suite Dashboard 화면 우측 상단 [Start] 버튼을 선택⑥ [Components] – [PostGIS] – [manage] 를 선택하여 pgAdmin 을 실행⑦ Tip : 사용자 컴퓨터의 등록정보를 확인하여 컴퓨터 이름 또는 사용자 이름이 한글일 경우 오류가 발생할 수

있으므로 변경 후 설치 권장

OpenGeo Suite 설치

OpenGeo Suite 설치 OpenGeo Suite Dashboard 실행 pgAdmin 실행

3

Page 7: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

I-3. PostGIS 환경설정

OpenGeoSuite Dashbord 환결설정

① OpenGeo Suite Dashboard 화면 선택② Preferences 를 선택하고 , [PostGIS] 메뉴에 Port 번호 “ 54321” 을 확인

pgAdmin 환경설정

① OpenGeo Suite Dashboard 화면 선택 ② [Components] – [PostGIS] – [manage] 를 선택하여 pgAdmin 을 실행 ③ pgAdmin 의 [File] – [Options] 메뉴를 선택 ④ [General tab] – [user language] 의 Default 를 확인 ⑤ [Preferences tab] – [Font] 선택하여 “돋움 , 9” 로 변경

4

Page 8: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

I-4. pgAdmin & Query Tool 사용하기

pgAdmin Server 구성하기

① OpenGeo Suite Dashboard 화면에서 [Components] – [PostGIS] – [manage] 를 선택하여 pgAdmin 을 실행② [File] – [Add Server] & 툴바 아이콘을 선택③ New Server Registration 화면에 Name, Host, Password 를 입력 후 [ok] 선택

5

postgis

Page 9: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

I-4. pgAdmin & Query Tool 사용하기

pgAdmin 사용하기

6

도구 설명

pgAdmin 도구에 새로운 서버를 추가합니다 .

객체의 정보를 생성 , 수정 , 갱신 , 삭제 후 새로고침 합니다 .

테이블 등의 객체의 등록정보를 확인하거나 수정합니다 .

선택된 객체와 같은 형태의 새로운 객체를 생성합니다 .

선택된 객체를 삭제합니다 .

SQL 을 실행할 수 있는 Query 도구를 불러옵니다 .

선택된 테이블을 편집할 수 있는 테이블 편집기를 불러옵니다 .

필터를 적용해서 테이블을 편집할 수 있는 테이블 편집기를 불러옵니다 .

Vacuum, Analyze 등 테이블 유지에 필요한 도구를 불러옵니다 .

Page 10: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

I-4. pgAdmin & Query Tool 사용하기

Query Tool 사용하기

7

① pgAdmin Tool 툴바 아이콘을 선택 Query Tool 실행② 샘플데이터 폴더의 postgis_korea_epsg_towgs84.sql 을 열기③ [F5] 선택 Query 실행 시킴 , 한국 주요 좌표계 적용

Page 11: 공간정보거점대학 PostGIS 고급과정

II. 공간데이터베이스 관리

- 일러두기 -

• 본 자료는 모두 Creative Commons License CC-BY-NC 을 따릅니다 .

• 본 교재에서는 교육의 편의상 Windows 32 비트 기반의 프로그램들을 위주로 설명합니다 .

• 본 교재에서 사용하는 샘플 데이터 셋은 실제 정보와 다르므로 교육용 이외에는 사용할 수 없습니다 .

Page 12: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

II-1. 공간데이터베이스 생성

① [ 시작메뉴 ] – [PostgreSQL 9.3] – [pgAdmin] 을 실행② [Databases] 오른쪽 마우스 선택 후 [New Database] 를 선택③ [Name] – nyc 입력 ④ [Owner] – postgres 선택 , [ok] 선택 ⑤ [ ] 선택 , Query Tool 실행 ⑦ CREATE EXTENSION postgis; 입력 , [F5] 실행 ⑧ CREATE EXTENSION postgis_topology; 입력 , [F5] 실행 ⑨ SELECT postgis_full_version(); 입력 , [F5] 실행

GUI 를 이용한 공간데이터베이스 생성

8

Page 13: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

II-2. 공간데이터 생성 & 로딩 & 추출

공간데이터 로딩 - nyc

9

① [ 시작메뉴 ] – [PostGIS 2.1 bundle for PostgreSQL 9.3 ] – [PostGIS Shapefile and DBF Loader Ex-porter] 을 실행② [ 시작메뉴 ] – [OpenGeo Suite 3.0.2] – [pgShapeLoader] 를 실행③ [PostGIS Connection ] – [View connenction details] 선택 후 아래의 내용 입력 - Username : postgres / Password : postgis /Database : korea

④ [Options] - UTF-8 확인 후 [ok] 선택 ⑤ [Add File] – [02_ 실습예제 \02_PostGIS\data\nyc] 폴더의 Shape 파일 추가 ⑦ Import List [SRID] 컬럼 26918 로 변경 입력 ⑧ [Import] 선택 Shape 파일 추가

Page 14: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

II-2. 공간데이터 생성 & 로딩 & 추출

공간데이터 로딩 - korea

10

① [ 시작메뉴 ] – [PostGIS 2.1 bundle for PostgreSQL 9.3 ] – [PostGIS Shapefile and DBF Loader Ex-porter] 을 실행② [ 시작메뉴 ] – [OpenGeo Suite 3.0.2] – [pgShapeLoader] 를 실행③ [PostGIS Connection ] – [View connenction details] 선택 후 아래의 내용 입력 - Username : postgres / Password : postgis /Database : korea

④ [Options] – encoding CP949 or EUC-KR 변경 입력 후 [ok] 선택 ⑤ [Add File] – [02_ 실습예제 \02_PostGIS\data\seoul] 폴더의 Shape 파일 추가 ⑦ Import List [SRID] 컬럼 5174 로 변경 입력 ⑧ [Import] 선택 Shape 파일 추가

Page 15: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

II-2. 공간데이터 생성 & 로딩 & 추출

공간데이터 추출

11

① [ 시작메뉴 ] – [PostGIS 2.1 bundle for PostgreSQL 9.3 ] – [pgAdmin III] 을 실행② [ 시작메뉴 ] – [OpenGeo Suite 3.0.2] – [pgAdmin] 를 실행③ OpenGeo Suit Dashboard 의 PostGIS [Manage] 선택 실행④ nyc 의 Query Tool 을 선택 ⑤ nyc_neighborhoods 테이블을 이용하여 다음 쿼리 문을 작성해 보시기 바랍니다 .

- 브루클린에 있는 모든 지역의 이름 (name) 은 ?

- 브루클린에 있는 모든 지역의 이름에 있는 문자의 수는 ?

- 브루클린에 있는 모든 지역의 이름에 있는 문자의 평균과 표준편차는 ?

⑥ Function List

- avg(expression)

- char_lengtth(string)

- stddev(string)

Page 16: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

II-2. 공간데이터 생성 & 로딩 & 추출

공간데이터 추출

12

① [ 시작메뉴 ] – [PostGIS 2.1 bundle for PostgreSQL 9.3 ] – [pgAdmin III] 을 실행② [ 시작메뉴 ] – [OpenGeo Suite 3.0.2] – [pgAdmin] 를 실행③ OpenGeo Suit Dashboard 의 PostGIS [Manage] 선택 실행④ korea 의 Query Tool 을 선택 ⑤ admin_emd 테이블과 pop2007, pop2008 컬럼을 이용하여 다음 쿼리 문을 작성해 보시기 바랍니다 .

- 서울특별시 2007, 2008 각 년도 인구수 총 합은 ?

- 서울특별시 종로구 , 서대문구 , 강남구 2007, 2008 각년도 인구수의 총 합은 ?

- 2008 년 인구 중 종로구내 각 동의 인구비율은 백분율로 표시 ?

⑥ Function List

- avg(expression)

- count(expression)

- sum(expression)

Page 17: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

II-3. 래스터 데이터 생성 & 로딩

레스터 데이터 생성

13

① [ 시작메뉴 ] – [PostGIS 2.1 bundle for PostgreSQL 9.3 ] – [pgAdmin III] 을 실행② [ 시작메뉴 ] – [OpenGeo Suite 3.0.2] – [pgAdmin] 를 실행③ OpenGeo Suit Dashboard 의 PostGIS [Manage] 선택 실행④ nyc 의 Query Tool 을 선택 ⑤ PostGIS 래스터 공간함수를 사용한 래스터 테이블 생성 - CREATE TABLE myrasters(rid serial primary key, rast raster);

- CREATE INDEX myrasters_rast_st_convexhull_idx ON

myrasters USING gist( ST_ConvexHull(rast) );

Page 18: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

II-3. 래스터 데이터 생성 & 로딩

레스터 데이터 로딩

14

① 윈도우 cmd 화면을 실행 ([ 시작메뉴 ] – [ 실행 ] – [cmd] 선택 )

② OpenGeo Suit 설치경로 이동 or PostgreSQL 설치경로 이동③ raster2pgsql –G 입력 실행④ 실행 예제

⑤ http://postgis.net/docs/manual-2.1/using_raster_dataman.html#RT_Raster_Loader

⑥ C:\OpenGISEdu\postgis\data\seoul_raster\ 경로 raster 파일 올리기

Raster2pgsql raster_options_go_here raster_file someschema.sometable > out.sql

Page 19: 공간정보거점대학 PostGIS 고급과정

III. 공간함수 사용하기

- 일러두기 -

• 본 자료는 모두 Creative Commons License CC-BY-NC 을 따릅니다 .

• 본 교재에서는 교육의 편의상 Windows 32 비트 기반의 프로그램들을 위주로 설명합니다 .

• 본 교재에서 사용하는 샘플 데이터 셋은 실제 정보와 다르므로 교육용 이외에는 사용할 수 없습니다 .

Page 20: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

III-1. Geometry

Geometry

15

① nyc 의 Query Tool 실행CREATE TABLE geometries (name varchar, geom geometry);

INSERT INTO geometries VALUES

('Point', 'POINT(0 0)'),

('Linestring', 'LINESTRING(0 0, 1 1, 2 1, 2 2)'),

('Polygon', 'POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))'),

('PolygonWithHole', 'POLYGON((0 0, 10 0, 10 10, 0 10, 0 0),(1 1, 1 2, 2 2, 2 1, 1 1))'),

('Collection', 'GEOMETRYCOLLECTION(POINT(2 0),POLYGON((0 0, 1 0, 1 1, 0 1, 0 0)))');

SELECT name, ST_AsText(geom) FROM geometries;

② Spatial Type

SELECT name, ST_GeometryType(geom), ST_NDims(geom),

ST_SRID(geom) FROM geometries;

Page 21: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

III-1. Geometry

Geometry

16

③ Spatial Type

SELECT name, ST_GeometryType(geom), ST_NDims(geom), ST_SRID(geom) FROM geometries;

④ Point

SELECT ST_AsText(geom) FROM geometries WHERE name = 'Point';

SELECT ST_X(geom), ST_Y(geom) FROM geometries WHERE name = 'Point';

SELECT name, ST_AsText(geom) FROM nyc_subway_stations LIMIT 1;

⑤ Linestrings

SELECT ST_AsText(geom) FROM geometries WHERE name = 'Linestring';

SELECT ST_Length(geom) FROM geometries WHERE name = 'Linestring';

Page 22: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

III-1. Geometry

Geometry

17

⑥ Polygons

SELECT ST_AsText(geom) FROM geometries WHERE name LIKE 'Polygon%';

SELECT name, ST_Area(geom) FROM geometries WHERE name LIKE 'Polygon%

⑦ Collections – MultiPoint, MultiLineString, MultiPolygon, GeometryCollection

SELECT name, ST_AsText(geom) FROM geometries WHERE name = 'Collection';

⑧ Geometry Input and Output

SELECT encode( ST_AsBinary(ST_GeometryFromText('LINESTRING(0 0 0,1 0 0,1 1 2)')), 'hex');

SELECT ST_AsEWKT(ST_GeometryFromText('LINESTRING(0 0 0,1 0 0,1 1 2)'));

SELECT encode(ST_AsEWKB(ST_GeometryFromText( 'LINESTRING(0 0 0,1 0 0,1 1 2)')), 'hex');

SELECT ST_AsGeoJSON(ST_GeomFromGML('<gml:Point><gml:coordinates>1,1</gml:coordinates></gml:Point>'));

⑨ Casting from Text

SELECT 0.9::text; SELECT 'POINT(0 0)'::geometry; SELECT 'SRID=4326;POINT(0 0)'::geometry;

Page 23: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

III-1. Geometry

Geometry 연습문제 사용할 공간함수

18

sum(expression) aggregate to return a sum for a set of records

count(expression) aggregate to return the size of a set of records

ST_GeometryType(geometry) returns the type of the geometry

ST_NDims(geometry) returns the number of dimen-sions of the geometry

ST_SRID(geometry) returns the spatial reference iden-tifier number of the geometry

ST_X(point) returns the X ordinate ST_Y(point) returns the Y ordinate ST_Length(linestring) returns the length of the

linestring ST_StartPoint(geometry) returns the first coordinate

as a point ST_EndPoint(geometry) returns the last coordinate as

a point ST_NPoints(geometry) returns the number of coordi-

nates in the linestring ST_Area(geometry) returns the area of the polygons ST_NRings(geometry) returns the number of rings

(usually 1, more if there are holes) ST_ExteriorRing(polygon) returns the outer ring as a

linestring

ST_InteriorRingN(polygon, integer) returns a speci-fied interior ring as a linestring

ST_Perimeter(geometry) returns the length of all the rings

ST_NumGeometries(multi/geomcollection) returns the number of parts in the collection

ST_GeometryN(geometry, integer) returns the speci-fied part of the collection

ST_GeomFromText(text) returns geometry ST_AsText(geometry) returns WKT text ST_AsEWKT(geometry) returns EWKT text ST_GeomFromWKB(bytea) returns geometry ST_AsBinary(geometry) returns WKB bytea ST_AsEWKB(geometry) returns EWKB bytea ST_GeomFromGML(text) returns geometry ST_AsGML(geometry) returns GML text ST_GeomFromKML(text) returns geometry ST_AsKML(geometry) returns KML text ST_AsGeoJSON(geometry) returns JSON text ST_AsSVG(geometry) returns SVG text

Page 24: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

III-1. Geometry

Geometry 연습문제

19

Nyc 데이터베이스 사용 , 사용 테이블 nyc_census_blocks

– blkid, popn_total, boroname, geom nyc_streets

– name, type, geom nyc_subway_stations

– name, geom nyc_neighborhoods

– name, boroname, geom

① ‘West Village’ 지역 (neighborhood) 의 면적은 ?

- nyc_neighborhoods

② ‘Manhattan’ 의 면적은 km 표기 ?( 기본단위 m)

- nyc_neighborhoods, nyc_census_blocks

③ 뉴욕시의 얼마나 많은 인구조사 블록 (hole) 이 있는가 ?

- nyc_census_blocks

④ 뉴욕시의 총 도로의 길이는 km 표기 ?

- nyc_streets

⑤ ‘Columbus Cir’ 도로의 길이는 ?

- nyc_streets

⑥ ‘West Village’ 의 boundary 를 JSON 으로 표현 ?

- nyc_neighborhoods

⑦ ‘West Village’ 다중 폴리곤 (Multipolygon) 몇 개 ?

- nyc_neighborhoods

⑧ 뉴욕시의 도로타입별 총 길이는 ?

- nyc_streets

Page 25: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

III-2. Spatial Relationships / Joins / Indexing / Projecting Spatial Relationships

20

① ST_Equals

- SELECT name, geom, ST_AsText(geom) FROM nyc_subway_stations WHERE name = 'Broad St';

- SELECT name FROM nyc_subway_stations WHERE ST_Equals(geom, '0101000020266900000EEB-D4CF27CF2141BC17D69516315141');

② ST_Intersects

- SELECT name, ST_AsText(geom) FROM nyc_subway_stations WHERE name = 'Broad St';

- SELECT name, boroname FROM nyc_neighborhoods WHERE ST_Intersects(geom, ST_GeomFromText('POINT(583571 4506714)',26918));

Page 26: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

III-2. Spatial Relationships / Joins / Indexing / Projecting Spatial Relationships

21

③ ST_Disjoint

④ ST_Crosses

Page 27: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

III-2. Spatial Relationships / Joins / Indexing / Projecting Spatial Relationships

22

⑤ ST_Overlaps

⑥ ST_Touches

Page 28: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

III-2. Spatial Relationships / Joins / Indexing / Projecting Spatial Relationships

23

⑦ ST_Within and ST_Contains

⑧ ST_Distance and ST_Dwithin

- SELECT ST_Distance( ST_GeometryFromText('POINT(0 5)'), ST_GeometryFromText('LINESTRING(-2 2, 2 2)'));

- SELECT name FROM nyc_streets WHERE ST_DWithin( geom, ST_GeomFromText('POINT(583571 4506714)',26918), 10 );

Page 29: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

III-2. Spatial Relationships / Joins / Indexing / Projecting Spatial Relationships 연습문제 사용할 공간함수

24

sum(expression) aggregate to return a sum for a set of records

count(expression) aggregate to return the size of a set of records

ST_Contains(geometry A, geometry B) returns true if geometry A contains geometry B

ST_Crosses(geometry A, geometry B) returns true if geometry A crosses geometry B

ST_Disjoint(geometry A , geometry B) returns true if the geometries do not “spatially intersect”

ST_Distance(geometry A, geometry B) returns the minimum distance between geometry A and geometry B

ST_DWithin(geometry A, geometry B, radius) returns true if geometry A is radius distance or less from geometry B

ST_Equals(geometry A, geometry B) returns true if geometry A is the same as geometry B

ST_Intersects(geometry A, geometry B) returns true if geometry A intersects geometry B

ST_Overlaps(geometry A, geometry B) returns true if geometry A and geometry B share space, but are not completely contained by each other.

ST_Touches(geometry A, geometry B) returns true if the boundary of geometry A touches geometry B

ST_Within(geometry A, geometry B) returns true if geometry A is within geometry B

Page 30: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

Spatial Relationships 연습문제

25

Nyc 데이터베이스 사용 , 사용 테이블 nyc_census_blocks

– name, popn_total, boroname, geom nyc_streets

– name, type, geom nyc_subway_stations

– name, routes, geom nyc_neighborhoods

– name, boroname, geom

① ‘Atlantic Commons’ 이름의 도로의 Geometry 값은 ?

- nyc_streets

② ‘Atlantic Commons’d 의 지역 , 자치구는 ?

- nyc_neighborhoods

③ ‘Atlantic Commons’ 도로와 만나는 도로의 이름은 ?

- nyc_streets

④ ‘Atlantic Commons’ 반경 50m 이내의 인구수 ?

- nyc_census_blocks

III-2. Spatial Relationships / Joins / Indexing / Projecting

Page 31: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

III-2. Spatial Relationships / Joins / Indexing / Projecting Spatial Joins

26

① Join

SELECT

subways.name AS subway_name,

neighborhoods.name AS neighborhood_name,

neighborhoods.boroname AS borough

FROM nyc_neighborhoods AS neighborhoods

JOIN nyc_subway_stations AS subways

ON ST_Contains(neighborhoods.geom, subways.-geom) WHERE subways.name = 'Broad St';

② Join and Summarize

‘Manhattan 지역의 총 인구수와 백인 / 흑인의 비율 ?

SELECT

neighborhoods.name AS neighborhood_name, Sum(census.popn_total) AS population,

Round(100.0 * Sum(census.popn_white) / Sum(census.popn_total),1) AS white_pct,

Round(100.0 * Sum(census.popn_black) / Sum(census.popn_total),1) AS black_pct

FROM nyc_neighborhoods AS neighborhoods

JOIN nyc_census_blocks AS census

ON ST_Intersects(neighborhoods.geom, census.-geom) WHERE neighborhoods.boroname = 'Manhattan' GROUP BY neighborhoods.name

ORDER BY white_pct DESC;

Page 32: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

III-2. Spatial Relationships / Joins / Indexing / Projecting Spatial Joins

27

③ Join and Summarize

A 지하철의 반경 200m 이내의 총인구 , 인종별 비율 ?

SELECT

100.0 * Sum(popn_white) / Sum(popn_total) AS white_pct,

100.0 * Sum(popn_black) / Sum(popn_total) AS black_pct,

Sum(popn_total) AS popn_total

FROM nyc_census_blocks AS census

JOIN nyc_subway_stations AS subways

ON ST_DWithin(census.geom, subways.geom, 200) WHERE strpos(subways.routes,'A') > 0;

Spatial Joins 연습문제 사용할 공간함수

sum(expression): aggregate to return a sum for a set of records

count(expression): aggregate to return the size of a set of records

ST_Area(geometry) returns the area of the polygons ST_AsText(geometry) returns WKT text ST_Contains(geometry A, geometry B) returns the

true if geometry A contains geometry B ST_Distance(geometry A, geometry B) returns the

minimum distance between geometry A and geometry B ST_DWithin(geometry A, geometry B,

radius) returns the true if geometry A is radius distance or less from geometry B

ST_GeomFromText(text) returns geometry ST_Intersects(geometry A, geometry B) returns the

true if geometry A intersects geometry B ST_Length(linestring) returns the length of the

linestring ST_Touches(geometry A, geometry B) returns the

true if the boundary of geometry A touches geometry B ST_Within(geometry A, geometry B) returns the true

if geometry A is within geometry B

Page 33: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

Spatial Joins 연습문제

28

Nyc 데이터베이스 사용 , 사용 테이블 nyc_census_blocks

– name, popn_total, boroname, geom nyc_streets

– name, type, geom nyc_subway_stations

– name, routes, geom nyc_neighborhoods

– name, boroname, geom

① ‘Little Italy’ 무슨 역이고 , 어떤 노선 인가 ?

- nyc_subway_stations, nyc_subway_stations

② 6-train 지나는 모든 지역은 어디인가 ?

- nyc_subway_stations, nyc_subway_stations

③ ‘Battery Park’ 의 총인구 ?

- nyc_subway_stations, nyc_subway_stations

④ ‘Upper West Side’, ‘Upper East Side’ 인구밀도는 ?

- nyc_subway_stations, nyc_subway_stations

III-2. Spatial Relationships / Joins / Indexing / Projecting

Page 34: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

Spatial Indexing

29

① Spatial Indexing 테스트 - DROP INDEX nyc_census_blocks_geom_gist;

- SELECT

blocks.blkid

FROM nyc_census_blocks blocks

JOIN nyc_subway_stations subways

ON ST_Contains(blocks.geom, subways.geom)

WHERE subways.name = 'Broad St';

- Query 시간 확인 - CREATE INDEX nyc_census_blocks_geom_gist

ON nyc_census_blocks USING GIST (geom);

- 위의 Select 문을 실행 시켜 Query 시간을 확인

② Index-Only Queris

- PostGIS index 내장 공간함수 제공 (ST_Contains, ST_Intersects, ST_DWithin, etc)

- Index 와 ‘ &&’ 연산자SELECT

Sum(popn_total)

FROM nyc_neighborhoods neighborhoods

JOIN nyc_census_blocks blocks

ON neighborhoods.geom && blocks.geom

WHERE neighborhoods.name = 'West Village';

SELECT

Sum(popn_total)

FROM nyc_neighborhoods neighborhoods

JOIN nyc_census_blocks blocks

ON ST_Intersects(neighborhoods.geom, blocks.-geom)

WHERE neighborhoods.name = 'West Village';

III-2. Spatial Relationships / Joins / Indexing / Projecting

Page 35: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

III-2. Spatial Relationships / Joins / Indexing / Projecting Projecting 연습문제 사용할 공간함수

30

sum(expression) aggregate to return a sum for a set of records

ST_Length(linestring) returns the length of the linestring

ST_SRID(geometry, srid) returns the SRID of the geometry

ST_Transform(geometry, srid) converts ge-ometries into different spatial reference systems

ST_GeomFromText(text) returns geometry ST_AsText(geometry) returns WKT text ST_AsGML(geometry) returns GML text

Nyc 데이터베이스 사용 , 사용 테이블 nyc_census_blocks

– name, popn_total, boroname, geom nyc_streets

– name, type, geom nyc_subway_stations

– name, geom nyc_neighborhoods

– name, boroname, geom

① 뉴욕시 모든 도로 길이는 ?

- nyc_streets

② SRID 2831 로 변환된 뉴욕시 모든 도로 길이는 ?

- nyc_streets

③ ‘Broad St’ subway station 을 KML 표시 ?

- nyc_subway_stations

Projecting 연습문제

Page 36: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

III-3. Geograpy

Gemotry & Geograpy

31

① 거리 구하기- SELECT ST_Distance(

ST_GeometryFromText('POINT(-118.4079 33.9434)', 4326), -- Los Angeles (LAX)

ST_GeometryFromText('POINT(2.5559 49.0083)', 4326) -- Paris (CDG) );

- SELECT ST_Distance(

ST_GeographyFromText('POINT(-118.4079 33.9434)'), -- Los Angeles (LAX)

ST_GeographyFromText('POINT(2.5559 49.0083)') -- Paris (CDG) );

SELECT ST_Distance(

ST_GeographyFromText('LINESTRING(-118.4079 33.9434, 2.5559 49.0083)'), -- LAX-CDG

ST_GeographyFromText('POINT(-21.8628 64.1286)') -- Ice-land );

- SELECT ST_Distance(

ST_GeometryFromText('Point(-118.4079 33.9434)'), -- LAX ST_GeometryFromText('Point(139.733 35.567)')) -- NRT (Tokyo/Narita) AS geometry_distance,

ST_Distance(

ST_GeographyFromText('Point(-118.4079 33.9434)'), -- LAX ST_GeographyFromText('Point(139.733 35.567)')) -- NRT (Tokyo/Narita) AS geography_distance;

Page 37: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

III-3. Geograpy

Gemotry & Geograpy

32

② Geograpy 테이블 생성-CREATE TABLE airports (

code VARCHAR(3),

geog GEOGRAPHY(Point)

);

INSERT INTO airports VALUES ('LAX', 'POINT(-118.4079 33.9434)');

INSERT INTO airports VALUES ('CDG', 'POINT(2.5559 49.0083)'); INSERT INTO airports VALUES ('REK', 'POINT(-21.8628 64.1286)');

- SELECT * FROM geography_columns;

③ Geometry 변환- SELECT code, ST_X(geog::geometry) AS longitude FROM airports;

Page 38: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

III-4. Geometry Constructing Functions

ST_Centroid / ST_PointOnSurface

33

ST_Buffer

CREATE TABLE liberty_island_zone AS SELECT ST_Buffer(geom,500)::geometry(Polygon,26918) AS geom FROM nyc_census_blocks WHERE blkid = '360610001001001';

Page 39: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

III-4. Geometry Constructing Functions

ST_Intersection

34

SELECT ST_AsText(ST_Intersection(

ST_Buffer('POINT(0 0)', 2),

ST_Buffer('POINT(3 0)', 2) )

);

SELECT ST_AsText(ST_Union(

ST_Buffer('POINT(0 0)', 2),

ST_Buffer('POINT(3 0)', 2) )

);

CREATE TABLE nyc_census_counties AS SELECT ST_Union(geom)::Geometry(MultiPolygon,26918) AS geom, SubStr(blkid,1,5) AS countyid FROM nyc_census_blocks GROUP BY countyid;

SELECT SubStr(blkid,1,5) AS countyid, Sum(ST_Area(geom)) AS area FROM nyc_census_blocks GROUP BY countyid;

SELECT countyid, ST_Area(geom) AS area FROM nyc_census_counties;

SELECT countyid, ST_AsText(geom) FROM nyc_census_counties;

ST_Union

Page 40: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

III-5. More Spatial Joins

Census Tracts Table 생성

35

① pgAdim 실행 – Query Tool 실행 ② C:\OpenGISEdu\postgis\data\nyc 폴더 nyc_census_sociodata.sql 파일 열기 ③ [F5] 실행 Census tracts 테이블 생성 ④ Refresh 선택 , 테이블 추가 확인 ⑤ ST_Union 을 이용한 새로운 테이블 생성 - CREATE TABLE nyc_census_tract_geoms AS

SELECT ST_Union(geom) AS geom, SubStr(blkid,1,11) AS tractid FROM nyc_census_blocks

GROUP BY tractid; -- Index the tractid

CREATE INDEX nyc_census_tract_geoms_tractid_idx ON nyc_census_tract_geoms (tractid);

⑥ Join 을 통한 속성정보 추가 테이블 생성 - CREATE TABLE nyc_census_tracts AS

SELECT g.geom, a.*

FROM nyc_census_tract_geoms g

JOIN nyc_census_sociodata a

ON g.tractid = a.tractid; -- Index the geometries

CREATE INDEX nyc_census_tract_gidx ON nyc_census_tracts USING GIST (geom);

뉴욕 지역의 graduate degrees 사람 비율이 높은 10 개 지역은 ?

SELECT Round(100.0 * Sum(t.edu_graduate_dipl) / Sum(t.edu_total), 1) AS graduate_pct, n.name, n.boron-ame FROM nyc_neighborhoods n JOIN nyc_census_tracts t ON ST_Intersects(n.geom, t.geom) WHERE t.edu_total > 0 GROUP BY n.name, n.boroname ORDER BY graduate_pct DESC LIMIT 10;

문제

Page 41: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

III-5. More Spatial Joins

Polygon/Polygon Joins

36

SELECT

Round(100.0 * Sum(t.edu_graduate_dipl) / Sum(t.edu_total), 1) AS graduate_pct, n.name, n.boron-ame

FROM nyc_neighborhoods n

JOIN nyc_census_tracts t

ON ST_Contains(n.geom, ST_Centroid(t.geom))

WHERE t.edu_total > 0

GROUP BY n.name, n.boroname

ORDER BY graduate_pct DESC LIMIT 10;

① SELECT Sum(popn_total) FROM nyc_census_blocks;

② SELECT Sum(popn_total)

FROM nyc_census_blocks census

JOIN nyc_subway_stations subway

ON ST_DWithin(census.geom, subway.geom, 500);

③ WITH distinct_blocks AS (

SELECT DISTINCT ON (blkid) popn_total

FROM nyc_census_blocks census

JOIN nyc_subway_stations subway

ON ST_DWithin(census.geom, subway.geom, 500) )

SELECT Sum(popn_total) FROM distinct_blocks;

큰 반경 거리 Join

Page 42: 공간정보거점대학 PostGIS 고급과정

IV. 어플리케이션을 이용한 PostGIS 사용하기

- 일러두기 -

• 본 자료는 모두 Creative Commons License CC-BY-NC 을 따릅니다 .

• 본 교재에서는 교육의 편의상 Windows 32 비트 기반의 프로그램들을 위주로 설명합니다 .

• 본 교재에서 사용하는 샘플 데이터 셋은 실제 정보와 다르므로 교육용 이외에는 사용할 수 없습니다 .

Page 43: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

IV-1. 프로그램 설치하기

프로그램 설치하기

37

① QGIS 2.0 설치 하기 - 설치프로그램 폴더 : QGIS-OSGeo4W-2.0.1-3-Setup-x86 설치 - 설치화면 기본 순서대로 설치② uDig 1.4 설치 하기 - 설치프로그램 폴더 : udig-1.4.0.win32.win32.x86

- 설치화면 기본 순서대로 설치③ OpenJUMP 1.6 설치하기 - 설치프로그램 폴더 : OpenJUMP-Installer-1.6.3-r3576-CORE

- 설치화면 기본 순서대로 설치④ JDK 설치하기 - 설치프로그램 폴더 : JDK 설치 및 환경설정 .txt 참조⑤ visual studio 평가판 설치하기 - 설치프로그램 폴더 : vcs_web.exe 설치하기 - 설치화면 기본 순서대로 설치

Page 44: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

IV-2. QGIS 이용한 PostGIS 이용하기

QGIS 에서 레이어 추가하기

38

① QGIS 2.0 실행② [ 플러그인 ] – [ 플러그인관리및설치 ] SPIT 설치 확인③ [ 데이터베이스 ] – [Spit(s)] –[ 쉐입 파일을 PostGIS에 가져오기④ [ 새로만들기 ] 선택 , 정보 입력 후 [ 확인 ] 선택⑤ [ 연결 ] 선택⑥ [ 추가 ] 선택 후 , Shape 파일 선택 추가⑦ 기본 지오매트리 컬럼 이름 사용 체크 해제 후 ‘ geom’ 변경⑧ 기본 SRID 사용 체크 해제 후 ‘ 5174’ 변경⑨ [ 확인 ] 선택⑩ pgAdmin 실행 후 korea 데이터베이스에 입력한 shape 파일 테이블 확인

Page 45: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

IV-2. QGIS 이용한 PostGIS 이용하기

QGIS 에서 PostGIS 레이어 불러와 사용하기

39

① QGIS 2.0 실행② [ 레이어 ] – [PostGIS 레이어 추가하기 ] 선택③ [ 새로만들기 ] 선택 , 정보 입력 후 [ 확인 ] 선택 – nyc 사용④ [ 연결 ] 선택⑤ public 선택 원하는 Shape 선택 후 [ 추가 ] 선택⑥ 선택된 레이어 변경하기

Page 46: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

IV-3. OpenJUMP 이용한 PostGIS 이용하기

OpenJUMP 에서 PostGIS 레이어 불러와 사용하기

40

① OpenJUMP 1.6 실행② Working, System 오른 쪽 마우스 선택 후 [Add Datas-tore Layer] 선택③ Coonection[ ] 아이콘 선택④ [Add] 선택⑤ Connection Manager 화면에서 [ok] 선택⑥ Add Datastore Layer 에서 Dataset( 레이어선택 ) 후 [ok] 선택⑦ 여러레이어를 올려 레이어 변경하기

Page 47: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

IV-4. uDig 이용한 PostGIS 이용하기

uDig 에서 PostGIS 레이어 불러와 이용하기

41

① uDig 1.46 실행② [ 파일 ] – [ 새로운 지도작업 ] – [ 지도 ] 선택③ [ 레이어 ] – [ 추가 ] 선택④ [PostGIS] 선택 , [ 다음 ] 선택⑤ [Add] 선택⑥ Host, User Name, Password 입력⑦ Database 콤보박스 [korea] 선택 후 [List] 선택⑧ 여러 레이어 체크박스 선택 후 [ 완료 ]

Page 48: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

IV-5. JDBC Driver 이용한 PostGIS 이용하기

JDBC Driver 이용한 PostGIS 이용하기

42

① 최신 PostgreSQL JDBC Driver 다운로드 http://jdbc.postgresql.org/download.html

② jar 파일 CLASSPATH 등록③ JDBC Driver 설치 방법 - 직접 다운로드 사이트 접속 다운 후 등록 - Application Stack Builder 통한 설치

Page 49: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

IV-5. .NET Driver 이용한 PostGIS 이용하기

.NET Driver 이용한 PostGIS 이용하기

43

① 최신 npgsql .NET PostgreSQL driver 다운로드 http://npgsql.projects.postgresql.org/

② Web.config 설정-- web.config connection string section -- <connec-tionStrings> <add name="DSN" connection-String="server=localhost;database=mydb;Port=5432;User Id=myuser;password=mypwd"/> </con-nectionStrings>

③ .NET Driver 설치 방법 - 직접 다운로드 사이트 접속 다운 후 등록 - Application Stack Builder 통한 설치

// Code for TestRaster.ashx <%@ WebHandler Language="C#" Class="TestRaster" %> using System; using System.Data; using System.Web; using Npgsql;

public class TestRaster : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "image/png"; context.Response.BinaryWrite(GetResults(context)); } public bool IsReusable { get { return false; } } public byte[] GetResults(HttpContext context) { byte[] result = null; NpgsqlCommand command; string sql = null; int input_srid = 26986; try { using (NpgsqlConnection conn = new NpgsqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DSN"].ConnectionString)) { conn.Open(); if (context.Request["srid"] != null) { input_srid = Convert.ToInt32(context.Request["srid"]); } sql = @"SELECT ST_AsPNG( ST_Transform( ST_AddBand( ST_Union(rast,1), ARRAY[ST_Union(rast,2),ST_Union(rast,3)]) ,:input_srid) ) As new_rast FROM aerials.boston WHERE ST_Intersects(rast, ST_Transform(ST_MakeEnvelope(-71.1217, 42.227, -71.1210, 42.218,4326),26986) )"; command = new NpgsqlCommand(sql, conn); command.Parameters.Add(new NpgsqlParameter("input_srid", input_srid)); re-sult = (byte[]) command.ExecuteScalar(); conn.Close(); } } catch (Exception ex) { result = null; context.Response.Write(ex.Message.Trim()); } return result; } }

Page 50: 공간정보거점대학 PostGIS 고급과정

V. PostGIS 그밖의 기능

- 일러두기 -

• 본 자료는 모두 Creative Commons License CC-BY-NC 을 따릅니다 .

• 본 교재에서는 교육의 편의상 Windows 32 비트 기반의 프로그램들을 위주로 설명합니다 .

• 본 교재에서 사용하는 샘플 데이터 셋은 실제 정보와 다르므로 교육용 이외에는 사용할 수 없습니다 .

Page 51: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

V-1. Tuning PostgreSQL for Spatial

Backend Configuration Editer

44

① pgAdmin 실행② [File] – [Open postgresql.conf] – postgresql.conf 파일 선택

Shared_buffer

Default Value : 32MB Recommended Value : 500MB (75%)

Page 52: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

V-1. Tuning PostgreSQL for Spatial

Work_mem

45

Default Value : 1MB Recommended value : 16MB

Maintenance_work_mem

Default Value : 16MB Recommended Value : 16MB(ex.128MB)

Page 53: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

V-1. Tuning PostgreSQL for Spatial

Wal_buffers

46

Default Value : 1MB Recommended value : 16MB

Checkpoint_segments

Default Value : 3MB Recommended Value : 6MB

Page 54: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

V-1. Tuning PostgreSQL for Spatial

Ramdom_page_cost

47

Default Value : 4.0 Recommended value : 2.0

Seq_page_cost

Default Value : 1.0 Recommended Value : 1.0

Page 55: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

V-1. Tuning PostgreSQL for Spatial

Reload configuration

48

① pgAdmin 접속 종료 ( 종료 )

② OpenSeo Suit Dashboard Shutdown, Start

③ pgAdim 접속 ( 재시작 )

④ 설정 정보가 반영된다 .

Page 56: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

V-2. Query Plans

Query Plans

49

① pgAdmin 실행 ② Query Tool 실행③ [Query] – [Query Analyze] 선택④ Query 실행 – nyc db 사용SELECT

Sum(popn_total)

FROM nyc_neighborhoods neighborhoods

JOIN nyc_census_blocks blocks

ON ST_Intersects(neighborhoods.geom, blocks.-geom)

WHERE neighborhoods.name = 'West Village';

⑤ [Output pane] – [Explain] 선택⑥ Sequence Scan : 테이블의모든 Row Scan

⑦ Index Scan : 제약조건 스캔⑧ Nested Loop

⑨ Hash Aggregate

Page 57: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

V-3. 백업 & 복원

백업

50

Page 58: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

V-3. 백업 & 복원

백업

51

Page 59: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

V-3. 백업 & 복원

복원

52

절차– 템플릿 데이터베이스 생성–Restore( 복원 )

Page 60: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

V-3. 백업 & 복원

복원

53

Page 61: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

V-3. 백업 & 복원

주의사항

54

① 상위버전과 하위버전 호환안됨② 하위버전 백업 상위버전 Restore 가능③ 상위버전 백업 하위버전 Restore 오류

버전충돌시 테이블 / 레이어 분리백업 / 복원

Page 62: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

V-4. pgRouting

pgRouting

55

pgRouting  은 PostGIS/PostgreSQL 에 라우팅 기능을 추한 PostGIS 의 ExtensionCamptocamp SA  에 의해 시작된 pgDijkstra 의 확장판이며 Orkney  에 의해 확장현재 Georepublic  에 의해 개발 및 유지 관리되고 있음pgRouting 는 GPLv2 라이선스 하에 사용 가능하며 개인 , 기업 및 조직의 커뮤니티에 의해 지원

데이터베이스 기반 라우팅 접근 방법의 장점– 데이터와 속성은 Quantum GIS, uDig 그리고 JDBC, ODBC 또는 Pl/pgSQL 등 다양한

클라이언트에 의해 직접 갱신 가능하며 , 클라이언트는 PC 나 모바일 기기가 될 수 있음– 데이터 변경 내용은 라우팅 엔진을 통해 즉시 반영되며 , 재계산이 필요 없음– “cost” 파라미터는 SQL 을 통해 동적으로 계산되고 그 값은 다중 필드 및 테이블의 다양한 값을

사용할 수 있음

Page 63: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

V-4. pgRouting

지원 알고리즘

56

Shortest Path Dijkstra– 휴리스틱 기법 (heuristic method) 을 사용하지 않는 최단거리 알고리즘 , 알고리즘을 개발한 Dr. Edsger

Wybe Dijkstra 교수의 이름을 사용 .

Shortest Path A-Star(A*)– 휴리스틱 기법을 사용하며 대용량 데이터셋에 적합한 최단거리 알고리즘

Shortest Path Shooting-Star(Shooting*)– 휴리스틱 기법을 사용하며 turn restrictions(U-turn, P-turn, left-turn 등 ), 신호등 , 편도차선 등의 시제

도로 네트워크를 위한 최단거리 알고리즘

Traveling Salesperson Problem (TSP)– 최대 40 개의 포인트를 지원하는 Traveling Salesman Problem(TSP, 외판원 문제 ) 알고리즘

Driving Distance calculation (Isolines)– 도로네트워크에 기반을 둔 특정지점에서 특정 시간내에 도달 할 수 있는 영역 . Service area

Page 64: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

V-4. pgRouting

Network 데이터셋

57

도로 네트워크 데이터셋은 최소한 다음의 정보를 포함

– Road link ID (gid)– Road class (class_id): primary roads, secondary roads, and local roads 등 Hierarchies– Road link length (length): Cost - Length, Travel Time 등– Road name (name)– Road geometry (the_geom)– Road restrictions & rule (optional): Lanes, Speed Limit, traffic light, one-way streets 등

Page 65: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

V-4. pgRouting

공공기관 생산 도로 네트워크

58

공공기관에서 생산하는 도로네트워크로 활용 가능한 데이터는 다음의 4 가지가 가능– 1. ITS 전국표준노드링크 : http://nodelink.its.go.kr/– 2. UTIS 통합노드링크 : http://www.utis.go.kr/– 3. 국가교통 DB센터 노드링크 : http://www.ktdb.go.kr/– 4. 새주소 도로구간

1. 2. 3. 데이터는 1:5000 축척을 기반으로 제작되었으며 주요 도로 ( 고속국도 / 일반국도 / 지방도 수준 ) 중심으로 상세한 지역에서의 활용은 어려움

4. 새주소 도로구간은 도로중심선으로 구축되어 있으나 네트워크 분석자료로 활용하기 위해서는 위상구조 편집이 필요하며 도로에 대한 상세정보 (Restrictions & rules) 는 없음

Page 66: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

V-4. pgRouting

공공기관 생산 도로 네트워크 ( 사례지역 : 제주도 , 배경은 주거지 ( 건물 ) 밀집도 )

59

새주소 도로중심선

Page 67: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

V-4. pgRouting

Installing pgRouting

60

웹사이트에 http://pgrouting.org/download.html PostGIS 2.1.1 bundle 설치시 기본적으로 pgrout-

ing 2.0 설치됨 [pgAdmin] 실행 [New database] 생성 CREATE EXTENSION postgis;

CREATE EXTENSION pgrouting;

Page 68: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

V-4. pgRouting

pgRouting reference

61

pgRouting Demo– http://websi.openvrp.com– http://map.veloland.ch– http://www.ridethecity.com– http://www.pgrouting.org/gallery.html

Reference– http://www.pgrouting.org/– http://workshop.pgrouting.org/– http://underdark.wordpress.com/2011/02/07/a-beginners-guide-to-pgrouting/– https://github.com/pgRouting/pgrouting/– http://2011.foss4g.org/sites/2011.foss4g.org/files/slides/FOSS4G2011_pgrouting2.pdf– http://2010.foss4g.org/presentations/3284.pdf

Page 69: 공간정보거점대학 PostGIS 고급과정

국가공간정보 거점대학 오픈 소스 GIS 심화 과정 윤정환 ([email protected])

V-5. Reference

reference

62

PostGIS - http://postgis.org/– Docs - http://postgis.org/docs/

PostgreSQL - http://www.postgresl.org/– Downloads - http://www.postgresql.org/download/– Docs - http://www.postgresql.org/docs/– JDBC Driver - http://jdbc.postgresql.org/– .Net Driver - http://npgsql.projects.postgresql.org/– Python Driver - http://www.pygresql.org/– C/C++ Driver - http://www.postgresql.org/docs/8.4/static/libpq.html

PgAdmin III - http://www.pgadmin.org/Open Source Desktop Clients

– uDig - http://udig.refractions.net/– QGIS - http://qgis.org/– OpenJUMP - http://openjump.org/

Page 70: 공간정보거점대학 PostGIS 고급과정

감사합니다 .

Q&A

한국어 지부 함께 성장하는 새로운 방법 , 오픈 소스 소프트웨어 !!