PostGIS 3.7.0beta1 사용자 지침서

PostGIS 개발 그룹

초록

PostGIS는 객체 관계형 데이터베이스 시스템인 PostgreSQL 의 확장 프로그램으로, 데이터베이스에 GIS(지리정보 시스템) 객체를 저장할 수 있게 해줍니다. PostGIS는 GiST 기반 R-Tree 공간 인덱스를 지원하며, GIS 객체의 분석 및 공간 처리를 위한 기능을 포함하고 있습니다.

이 문서는 3.7.0beta1 버전의 사용자 지침서입니다.

이 저작물은 크리에이티브 커먼즈 저작자표시-동일조건변경허락 3.0 라이선스를 따릅니다. 사용자가 원하는 대로 이 문서를 사용할 수 있지만, 우리는 사용자가 PostGIS 프로젝트의 저작권을 명시하고 가능한 위치에 https://postgis.net으로 연결되는 링크를 삽입하도록 요구합니다.


차례

1장. 소개

1.1. What Is PostGIS?

PostGIS extends PostgreSQL so that geospatial data can be stored, indexed, queried, and processed in the database. It keeps location data beside ordinary relational data, so a spatial query can use the same SQL, transactions, constraints, access controls, backup tools, and application connections as the rest of a PostgreSQL database.

The main postgis extension adds:

  • geometry for planar coordinate systems and geography for geodetic coordinates on the earth.

  • Spatial indexes that let the PostgreSQL planner avoid scanning every row when objects can be filtered by location.

  • Functions for measurement, relationships, overlays, geometry construction and editing, coordinate transformation, clustering, and spatial data exchange.

  • Support for common geospatial encodings and formats, including WKT, WKB, GeoJSON, GML, KML, FlatGeobuf, Geobuf, and Mapbox Vector Tiles.

This makes PostgreSQL a spatial database: applications can ask both ordinary questions and location-aware questions without moving data to a separate GIS processing system. Desktop GIS, map servers, ETL tools, and application frameworks can connect through normal PostgreSQL interfaces.

1.2. What Is in the PostGIS Distribution?

This manual documents the main PostGIS source distribution. Depending on how PostGIS was built and packaged, it can provide several PostgreSQL extensions and command-line tools:

postgis

The core geometry and geography types, spatial indexes, and most spatial functions.

postgis_raster

Raster storage, analysis, loading, and export. Raster support uses GDAL and can be omitted from a build.

postgis_topology

SQL/MM topology types and functions for models based on shared nodes, edges, and faces.

postgis_sfcgal

Additional 2D and 3D processing functions backed by the optional SFCGAL library.

Loaders and utilities

shp2pgsql, pgsql2shp, and raster2pgsql move data between common file formats and PostGIS. Other utilities support upgrades, profiling, and development.

The source tree also contains internal libraries such as liblwgeom and libpgcommon. They are implementation layers shared by PostGIS components, not separately released PostgreSQL extensions. Most users start by enabling the core extension with CREATE EXTENSION postgis; see 2장. PostGIS 설치 for available components and build options.

1.3. The PostGIS Project Family

This manual covers the main postgis/postgis distribution. The official PostGIS source organization also hosts or mirrors complementary projects. These projects have their own release cycles, installation instructions, and documentation; installing the core extension does not install them.

  • Address Standardizer parses and normalizes postal addresses. It moved from the main PostGIS source tree to a separate repository for the PostGIS 3.7 development cycle.

  • PostGIS TIGER Geocoder provides United States address geocoding and reverse geocoding using Census TIGER data. It is also maintained separately from the main distribution.

  • H3-pg provides PostgreSQL bindings for the H3 hierarchical hexagonal indexing system and interoperates with PostGIS.

  • PostGIS Java provides Java bindings for PostGIS types.

  • Introduction to PostGIS is the hands-on workshop maintained by the PostGIS project.

Other PostgreSQL spatial extensions can complement PostGIS while remaining independent projects. For example, pgRouting adds routing and graph analysis. Use each project's own manual for its functions and support policy.

1.4. How to Use This Manual

The manual is both a guide to the PostGIS data model and the complete reference for the SQL interface. Choose a starting point based on what you are trying to do:

If you are new to spatial SQL

Start with the Introduction to PostGIS workshop for a tutorial, then use 4장. Data Management to understand spatial types, coordinate systems, validity, loading, and indexes.

If you are installing or upgrading PostGIS

Read 2장. PostGIS 설치 and 3장. PostGIS Administration. Package-specific instructions and supported release information are maintained on the PostGIS website.

If you are writing spatial queries

Read 5장. Spatial Queries for spatial relationships and index-aware query patterns, and 6장. 성능 향상 비법 for common performance problems.

If you need a particular function

Use 7장. PostGIS Reference or 13장. PostGIS Special Functions Index. Function pages state accepted types, dimensional support, standards conformance, dependency requirements, and version availability.

If you use an optional component

See 9장. 지형(topology), 10장. 래스터 데이터의 관리, 쿼리 및 응용, 11장. 래스트 참조문서, or 8장. SFCGAL Functions Reference.

If something goes wrong

Collect the versions reported by PostGIS_Full_Version and follow 14장. Reporting Problems. Check 부록 A. Release Notes when behavior differs between release lines.

1.5. Standards Support

This manual marks individual functions as compliant with spatial standards so users can tell which behavior is portable and which behavior is a PostGIS extension. PostGIS implements the OGC Simple Features for SQL model, including the geometry type, Well-Known Text (WKT), Well-Known Binary (WKB), and the common spatial accessors, constructors, predicates, and processing functions. PostGIS also implements many SQL/MM Spatial types and functions.

PostGIS supports geometry families defined by later standards, including SQL/MM curved geometry and OGC Simple Features Access 1.2 PolyhedralSurface, Triangle, and TIN. Support for these geometry families is function-specific, and each function page documents the supported input types and conformance level.

PostGIS also includes widely used extensions and integrations. Examples of PostGIS extensions include Extended WKT (EWKT), Extended WKB (EWKB), SRID metadata in those extended formats, geography, and raster. PostGIS also supports input and output exchange formats defined by other standards, such as GeoJSON, GML, and KML. These features are documented individually and should not be read as OGC Simple Features or SQL/MM requirements unless the specific function or format says so.

When the implementation intentionally differs from a standard, or when a standard leaves behavior ambiguous, the relevant function page describes the PostGIS behavior. 13장. PostGIS Special Functions Index summarizes SQL/MM compliance and geometry-type support across functions.

1.6. Project and Community

PostGIS began in 2001 as a spatial database research project at Refractions Research. It is now an OSGeo project developed by contributors and organizations around the world. The Project Steering Committee coordinates releases, project policy, and the general direction of development. The complete contributor and sponsor record is in 15장. Credits and Acknowledgments at the end of this manual.

The manual is the authoritative reference for the released SQL interface. The project website and source tree provide the surrounding material:

  • Documentation routes readers to getting-started instructions, versioned manuals, tips, training material, and the FAQ.

  • Community lists mailing lists, chat, events, videos, and other support channels.

  • Developer documentation covers development environments, testing, coding style, internals, maintenance, governance, releases, and website work.

2장. PostGIS 설치

이 장에서는 PostGIS 설치에 요구되는 모든 과정을 설명합니다.

2.1. 짧은 설명

사용자의 검색 경로에 모든 의존성이 설정되어 있을 때 컴파일하려면:

Code
tar -xvzf postgis-3.7.0beta1.tar.gz
cd postgis-3.7.0beta1
./configure
make
make install

PostGIS가 설치되면, PostGIS를 사용하고자 하는 모든 데이터베이스 각각에서 활성화하거나 (3.3절. “공간 데이터베이스 생성”)업그레이드(3.4절. “Upgrading spatial databases”)해야 합니다.

2.2. 소스를 컴파일하고 설치하기

[참고]

현재 많은 OS 시스템들이 PostgreSQL/PostGIS용 사전 구축된 패키지를 포함하고 있습니다. 많은 경우, 최신 버전이 필요하거나 패키지 관리자인 경우가 아니라면 컴파일할 필요가 없습니다.

This section includes general compilation instructions, if you are compiling for Windows etc or another OS, you may find additional more detailed help at PostGIS User contributed compile guides and PostGIS Dev Wiki.

Pre-Built Packages for various OS are listed in PostGIS Pre-built Packages

만약 윈도우 사용자라면 Stackbuilder 또는 PostGIS Windows download site 를 통해 안정적인 버전을 받을 수 있습니다. 또 1~2주에 한 번 혹은 뭔가 특이한 일이 일어날 경우 빌드를 하는 very bleeding-edge windows experimental builds 가 있습니다. 사용자는 이를 통해 진행중인 PostGIS 배포본을 실행해볼 수 있습니다.

The PostGIS module is an extension to the PostgreSQL backend server. As such, PostGIS 3.7.0beta1 requires full PostgreSQL server headers access in order to compile. It can be built against PostgreSQL versions 14 - 18. Earlier versions of PostgreSQL are not supported.

Refer to the PostgreSQL installation guides if you haven't already installed PostgreSQL. https://www.postgresql.org .

[참고]

GEOS 기능성을 위해 PostgreSQL설치 시 표준 C++ 라이브러리를 명확하게 링크해야 할 수도 있습니다.

Code
LDFLAGS=-lstdc++ ./configure [YOUR OPTIONS HERE]

이것은 구 버전 개발 도구 이용시 거짓 C++ 예외 상호작용을 피하기 위한 방법입니다. 만약 사용자가 이상한 문제(백엔드가 갑자기 끊어진다거나 또는 비슷한 증상)를 겪는다면 PostgreSQL을 다시 컴파일해야 할 수도 있습니다.

다음은 PostGIS 소스를 설정하고 취합하는 단계를 설명합니다. 리눅스 사용자를 위한 설명이므로 윈도우 또는 맥 사용자에겐 해당되지 않습니다.

2.2.1. 소스 획득

PostGIS 소스 압축파일을 다운로드 웹사이트 https://download.osgeo.org/postgis/source/postgis-3.7.0beta1.tar.gz 에서 다운로드하십시오.

Code
wget https://download.osgeo.org/postgis/source/postgis-3.7.0beta1.tar.gz
tar -xvzf postgis-3.7.0beta1.tar.gz
cd postgis-3.7.0beta1

이 명령어를 실행하면 현재 작업 디렉토리에 postgis-3.7.0beta1 (이)라는 명칭의 디렉터리가 생길 것입니다.

다른 방법으로는, svn 저장소 http://svn.osgeo.org/postgis/trunk/ 에서 소스를 체크아웃(checkout)할 수 있습니다.

Code
git clone https://git.osgeo.org/gitea/postgis/postgis.git postgis
cd postgis
sh autogen.sh
    

설치를 계속하려면 새로 만든 postgis-3.7.0beta1 디렉터리로 이동합니다.

Code
./configure

2.2.2. 설치 요구사항

PostGIS를 빌드하고 사용하기 위해서는 다음과 같은 요구사항들을 만족해야 합니다.

필수 사항

  • PostgreSQL 14 - 18. A complete installation of PostgreSQL (including server headers) is required. PostgreSQL is available from https://www.postgresql.org 18 .

    For current release-line support and end-of-life policy, see https://postgis.net/development/versions_eol/

  • GNU C 컴파일러(gcc). PostGIS를 컴파일하기 위해 그 밖에 다른 ANSI C 컴파일러들을 사용할 수 있으나 gcc 로 컴파일했을 경우 오류가 훨씬 적게 발생합니다.

  • GNU Make(gmake 또는 make). 많은 시스템들에서 GNU make 는 make의 기본 버전입니다. make -v를 통해 버전을 확인하십시오. 다른 버전의 make는 PostGIS Makefile을 제대로 처리하지 못 할 수도 있습니다.

  • Proj reprojection library. Proj 6.1 or above is required. The Proj library is used to provide coordinate reprojection support within PostGIS. Proj is available for download from https://proj.org/ .

  • GEOS geometry library, version 3.8.0 or greater, but GEOS 3.14+ is required to take full advantage of all the new functions and features. GEOS is available for download from https://libgeos.org .

  • LibXML2, version 2.5.x or higher. LibXML2 is currently used in some imports functions (ST_GeomFromGML and ST_GeomFromKML). LibXML2 is available for download from https://gitlab.gnome.org/GNOME/libxml2/-/releases.

  • JSON-C 0.9 또는 이후 버전. JSON-C는 현재 ST_GeomFromGeoJson 함수를 통해 GeoJSON을 임포트하는 데 사용되고 있습니다. JSON-C는 https://github.com/json-c/json-c/releases/ 에서 다운로드할 수 있습니다.

  • The GNU Multiple Precision Arithmetic Library (libgmp). Used to control precision of math operations in PostGIS Topology. GMP is available for download from https://gmplib.org/.

  • GDAL, version 3+ is preferred. This is required for raster support. https://gdal.org/download.html.

  • 이 파라미터는 현재 작동되지 않습니다. 패키지가 PostgreSQL 설치 경로에만 설치될 것이기 때문입니다. 해당 버그를 추적하려면 http://trac.osgeo.org/postgis/ticket/635 를 참조하십시오.

선택 사항

  • 2.1절. “짧은 설명” 에 설명된 대로 사용자가 사용하길 원하는 드라이버를 활성화하는 작업도 잊지 마십시오.

  • shapefile 로더 shp2pgsql-gui 를 컴파일하기 위한 GTK(GTK+2.0, 2.8+ 필요). http://www.gtk.org/.

  • SFCGAL, 1.4.1 or higher is required, 2.3+ is needed to be able to use all functionality. SFCGAL can be used to provide additional 2D and 3D advanced analysis functions to PostGIS cf 8장. SFCGAL Functions Reference. https://sfcgal.gitlab.io/sfcgal/.

  • To enable ST_AsMVT protobuf-c library 1.1.0 or higher (for usage) and the protoc-c compiler (for building) are required. Also, pkg-config is required to verify the correct minimum version of protobuf-c. See protobuf-c. By default, Postgis will use Wagyu to validate MVT polygons faster which requires a c++11 compiler. It will use CXXFLAGS and the same compiler as the PostgreSQL installation. To disable this and use GEOS instead use the --without-wagyu during the configure step.

  • CUnit(CUnit). 회기 검증을 하는 데 필요합니다. http://cunit.sourceforge.net/

  • DocBook(xsltproc)은 문서를 발행할 때 필요합니다. DocBook은 http://www.docbook.org/ 에서 다운로드할 수 있습니다.

  • DBLatex(dblatex)는 PDF 형식의 문서를 발행할 때 필요합니다. DBLatex는 http://dblatex.sourceforge.net/ 에서 다운로드할 수 있습니다.

  • PDF documentation needs an SVG rasterizer for its high-resolution figure fallbacks. The build prefers rsvg-convert, and can also use GraphicsMagick (gm convert) or ImageMagick (magick or convert).

2.2.3. 설정

대부분의 리눅스 설치에서 첫 번째 단계는 소스 코드를 빌드하는 데 사용할 Makefile을 생성하는 것입니다. 셸 스크립트를 실행해서 Makefile을 작성합니다.

Code
./configure

추가 파라미터 없이 사용하면, 이 명령은 자동적으로 PostGIS 소스코드를 사용자 시스템에 빌드하는 데 필요한 필수 구성 요소들과 라이브러리의 위치를 확인하려 합니다. ./configure 명령어의 가장 흔한 사용법이긴 하지만, 이 스크립트는 비표준적인 위치에 있는 필수 라이브러리와 프로그램들에 대한 몇몇 파라미터를 받습니다.

다음은 가장 많이 사용되는 파라미터들만 나열한 목록입니다. 전체 목록은 --help 또는 --help=short 파라미터를 사용하십시오.

--with-library-minor-version

Starting with PostGIS 3.0, the library files generated by default will no longer have the minor version as part of the file name. This means all PostGIS 3 libs will end in postgis-3. This was done to make pg_upgrade easier, with downside that you can only install one version PostGIS 3 series in your server. To get the old behavior of file including the minor version: e.g. postgis-3.0 add this switch to your configure statement.

--prefix=PREFIX

This is the installation prefix for PostGIS command-line utilities. By default, utilities are installed in the executable directory reported by the detected PostgreSQL installation.

[경고]

PostgreSQL extension files are installed in the directories reported by pg_config, so the server can load them. This includes the PostGIS shared library and SQL extension files. Use --with-pgconfig=FILE to choose the PostgreSQL installation that PostGIS builds and installs against.

--with-pgconfig=FILE

PostgreSQL은 PostGIS 같은 확장 프로그램이 PostgreSQL 설치 디렉토리의 위치를 확인하게 해주는 pg_config 라는 유틸리티를 제공합니다. PostGIS 빌드 시 대상이 될 특정 PostgreSQL 설치 디렉터리를 사용자가 직접 설정하려면 이 파라미터(--with-pgconfig=/path/to/pg_config)를 사용하십시오.

--with-gdalconfig=FILE

GDAL은 래스터 지원을 위한 기능을 제공하는 필수 라이브러리로, GDAL 설치 디렉터리의 위치를 확인하는 소프트웨어 설치를 활성화하기 위한 gdal-config를 지원합니다. PostGIS 빌드 시 대상이 될 특정 GDAL 설치 디렉터리를 사용자가 직접 설정하려면 이 파라미터(--with-gdalconfig=/path/to/gdal-config)를 사용하십시오.

--with-geosconfig=FILE

GEOS는 필수 도형 라이브러리로, GEOS 설치 디렉터리의 위치를 확인하는 소프트웨어 설치를 활성화하기 위한 geos-config라는 유틸리티를 제공합니다. PostGIS 빌드 시 대상이 될 특정 GEOS 설치 디렉터리를 사용자가 직접 설정하려면 이 파라미터(--with-geosconfig=/path/to/geos-config)를 사용하십시오.

--with-xml2config=FILE

LibXML is the library required for doing GeomFromKML/GML processes. It normally is found if you have libxml installed, but if not or you want a specific version used, you'll need to point PostGIS at a specific xml2-config confi file to enable software installations to locate the LibXML installation directory. Use this parameter (>--with-xml2config=/path/to/xml2-config) to manually specify a particular LibXML installation that PostGIS will build against.

--with-projdir=DIR

Proj4는 PostGIS 필수 재투영 라이브러리입니다. PostGIS 빌드 시 대상이 될 특정 Proj4 설치 디렉터리를 사용자가 직접 설정하려면 이 파라미터(--with-projdir=/path/to/projdir)를 사용하십시오.

--with-libiconv=DIR

iconv 설치 경로

--with-jsondir=DIR

JSON-C 는 MIT-라이선스의 JSON 라이브러리로, PostGIS의 ST_GeomFromJSON 지원에 필요합니다. PostGIS 빌드 시 대상이 될 특정 JSON-C 설치 디렉터리를 사용자가 직접 설정하려면 이 파라미터(--with-jsondir=/path/to/jsondir)를 사용하십시오.

--with-gui

데이터 임포트 GUI 컴파일(GTK+2.0 필요). shp2pgsql-gui의 shp2pgsql에 대한 그래픽 인테페이스를 생성합니다.

--without-raster

래스터 지원 설치

--without-topology

Compile without topology support.

--with-gettext=no

기본적으로 PostGIS는 gettext 지원을 감지해서 함께 컴파일하지만, 로더의 파손을 야기하는 비호환성 문제가 발생할 경우 이 명령어로 gettext 지원을 완전히 비활성화시킬 수 있습니다. 이런 방법으로 설정을 변경해서 문제를 해결하는 예는 버그 티켓 http://trac.osgeo.org/postgis/ticket/748 을 참조하십시오. 주의: gettext 지원을 끈다고 해서 별다른 문제는 없습니다. gettext 지원은 아직 문서화되지도 않았고 검증중에 있는 GUI 로더 용 국제 도움말/라벨 지원에 사용됩니다.

--with-sfcgal=PATH

기본적으로 PostGIS는 이 스위치 없이는 sfcgal 지원과 함께 설치되지 않습니다. PATH 는 sfcgal-config를 가리키는 대체 경로를 지정하도록 해주는 선택적인 인자입니다.

--without-phony-revision

Disable updating postgis_revision.h to match current HEAD of the git repository.

[참고]

PostGIS를 SVN 저장소 에서 얻었다면, 먼저 다음 스크립트를 실행하십시오.

Code
./autogen.sh

이 스크립트는 configure 스크립트를 생성하는데, 이 스크립트는 PostGIS의 사용자 지정 설치를 위해 이용됩니다.

만약 tar 파일 형태로 PostGIS를 얻었다면 이미 configure 가 생성되었기 때문에 ./autogen.sh 를 실행할 필요는 없습니다.

2.2.4. 빌드

일단 Makefile이 생성되면 PostGIS 빌드 작업은 실행만큼이나 쉽습니다.

Code
make
래스터 출력
[last line of output]
PostGIS was built successfully. Ready to install.

All the functions have comments generated from the documentation. If you wish to install these comments into your spatial databases later, run the command which requires docbook. The postgis_comments.sql and other package comment files are also packaged in the tar.gz distribution in the doc folder so no need to make comments if installing from the tar ball. Comments are also included as part of the CREATE EXTENSION install.

Code
make comments

The make cheatsheets target generates html cheat sheets suitable for quick reference or for student handouts. This requires xsltproc to build and will generate 4 files in doc folder topology_cheatsheet.html, raster_cheatsheet.html, postgis_cheatsheet.html

html 및 pdf 형식으로 미리 만들어진 파일들을 PostGIS / PostgreSQL Study Guides 에서 다운로드받을 수 있습니다.

Code
make cheatsheets

2.2.5. PostGIS Extensions 빌드 및 배포

The PostGIS extensions are built and installed automatically when PostgreSQL extension support is available.

소스 저장소로부터 생성할 경우에는, 먼저 function descriptions 부터 빌드해야 합니다. docbook을 설치하셨다면 빌드할 수 있고, 다음 명령을 통해 수동으로 생성할 수도 있습니다:

Code
make comments

만약 사용자가 tar 파일 배포본을 이용해 빌드한다면 미리 빌드된 것이 tar 파일과 함께 배포됨으로 comments를 따로 빌드할 필요가 없습니다.

만약 PostgreSQL 9.1을 기반으로 빌드 중이라면 extensions은 설치 과정의 일환으로 자동 빌드될 것입니다. 만약 필요하다면 extensions 폴더로부터의 빌드하거나 또는 다른 서버에서 필요한 파일을 복사할 수 있습니다.

Set PGUSER if you need to override the psql connection user, then test before installing. After installation, run the extension regression tests.

Code
cd extensions
cd postgis
make clean
make
export PGUSER=postgres
make check
make install
make check RUNTESTFLAGS=--extension
[참고]

make check uses psql to run tests and as such can use psql environment variables. Common ones useful to override are PGUSER,PGPORT, and PGHOST. Refer to psql environment variables

extension 파일은 OS에 상관없이 PostGIS버전만 같으면 적용에 문제가 없습니다. 그러므로 PostGIS binaries가 설치된 서버에 확장 파일만 복사해도 문제가 없습니다.

만약 extension을 수동으로 또는 다른 서버에 설치하고 싶으면 다음 파일들을 사용자의 PostgreSQL 설치경로의 PostgreSQL / share / extension 폴더에 있는 extensions 폴더에서 복사하여 PostGIS가 설치되지 않은 서버에 필요한 바이너리 파일들을 넣어 주십시오.

  • 이것들이 지정되지 않은 경우 설치할 수 있는 extension 의 버전 등의 정보를 나타내는 제어 파일입니다. postgis.control, postgis_topology.control.

  • 각 extension의 /sql 폴더에 모든 파일들이 있습니다. 다음 파일들은 postgreSQL의 share/extension 폴더의 루트에 복사 되어야 함에 주의하십시오. extensions/postgis/sql/*.sql, extensions/postgis_topology/sql/*.sql

Once you do that, you should see postgis, postgis_topology as available extensions in PgAdmin -> extensions.

만약 psql을 이용 중이라면 다음의 쿼리를 실행함으로써 확인할 수 있습니다.

Code
SELECT name, default_version, installed_version
FROM pg_available_extensions
WHERE name LIKE 'postgis%'
ORDER BY name;
래스터 출력
┌──────────────────┬─────────────────┬───────────────────┐
│ name             │ default_version │ installed_version │
├──────────────────┼─────────────────┼───────────────────┤
│ postgis          │ 3.7.0beta1        │ 3.7.0beta1        │
│ postgis_raster   │ 3.7.0beta1        │ 3.7.0beta1        │
│ postgis_sfcgal   │ 3.7.0beta1        │                   │
│ postgis_topology │ 3.7.0beta1        │                   │
└──────────────────┴─────────────────┴───────────────────┘

만약 사용자가 쿼리하는 데이터베이스에 extension이 설치되어 있다면, 사용자는 installed_version 컬럼에서 이름을 볼 수 있습니다. 만약 아무 레코드도 없다면 서버에 postgis extension이 전혀 설치되어 있지 않음을 뜻합니다. PgAdmin III 1.14이상 버전에서는 데이터베이스 탐색 트리의 extensions에서 마우스 오른쪽 버튼 클릭을 통해 업그레이드 또는 삭제를 허용합니다.

extension이 이용 가능한 상태라면 pgAdmin extension 인터페이스 또는 다음의 sql 명령을 실행함으로써 선택한 데이터베이스 안에 postgis extension을 설치할 수 있습니다:

Code
CREATE EXTENSION postgis;
CREATE EXTENSION postgis_raster;
CREATE EXTENSION postgis_sfcgal;
CREATE EXTENSION postgis_topology;

PSQL에서 다음 명령어를 사용하면 어떤 버전을 설치했는지, 어떤 스키마로 설치했는지 알 수 있습니다.

Code
\connect mygisdb
\x
\dx postgis*
래스터 출력
List of installed extensions
┌─[ RECORD 1 ]────────────────────────────────────────────────┐
│ Name        │ postgis                                       │
│ Version     │ 3.7.0beta1                                        │
│ Schema      │ public                                        │
│ Description │ PostGIS geometry, geography, and raster…      │
├─[ RECORD 2 ]────────────────────────────────────────────────┤
│ Name        │ postgis_raster                                │
│ Version     │ 3.7.0beta1                                        │
│ Schema      │ public                                        │
│ Description │ PostGIS raster types and functions            │
├─[ RECORD 3 ]────────────────────────────────────────────────┤
│ Name        │ postgis_topology                              │
│ Version     │ 3.7.0beta1                                        │
│ Schema      │ topology                                      │
│ Description │ PostGIS topology spatial types and functions  │
└─────────────────────────────────────────────────────────────┘
[주의]

Extension tables spatial_ref_sys, layer, topology can not be explicitly backed up. They can only be backed up when the respective postgis or postgis_topology extension is backed up, which only happens when you back up the whole database. Only srid records not packaged with PostGIS are captured in backups, so don't change the entries we ship and expect the modifications to persist. Put in a ticket if you find an issue. The structures of extension tables are never backed up since they are created with CREATE EXTENSION and assumed to be the same for a given version of an extension. These behaviors are built into the current PostgreSQL extension model.

우리의 멋진 확장 프로그램 시스템 없이 3.7.0beta1 을 설치했다면, 먼저 다음 업그레이드 스크립트를 실행해서 확장 프로그램 기반 최신 버전으로 변경할 수 있습니다: postgis_upgrade_22_minor.sql,raster_upgrade_22_minor.sql,topology_upgrade_22_minor.sql.

Code
CREATE EXTENSION postgis FROM unpackaged;
CREATE EXTENSION postgis_raster FROM unpackaged;
CREATE EXTENSION postgis_topology FROM unpackaged;

2.2.6. 테스트

만약 PostGIS 빌드를 테스트하고 싶다면, 실행하십시오.

Code
make check

위 명령어는 활성 PostgreSQL 데이터베이스 바탕으로 생성된 라이브러리를 이용하여 다양한 확인과 회귀 테스트를 실행할 것입니다.

[참고]

PostgreSQL, GEOS, 또는 Proj4를 표준이 아닌 경로에 설치한 경우, LD_LIBRARY_PATH 환경 변수에 해당 라이브러리 경로를 설정해주어야 합니다.

[경고]

현재, make check 검사들을 실시할 때에는 PATHPGPORT 환경 변수를 따릅니다. PostgreSQL의 설정 매개변수인 --with-pgconfig에 명시되어 있어도 이것을 적용하지 않습니다. 따라서, PostgreSQL 설치시의 환경설정과 일치하도록 PATH를 수정해주십시오.

[참고]

Sandboxed build accounts that are not PostgreSQL superusers can delegate database ownership during the regression cycle by exporting POSTGIS_REGRESS_DB_OWNER. The harness will create the temporary regression database owned by the nominated role while continuing to connect using the less privileged account. Combine this with POSTGIS_REGRESS_ROLE_EXT_CREATOR when the extension creation role must differ from the database owner.

These variables allow automated environments to exercise the full upgrade and extension install paths without promoting the calling account to superuser, provided the target PostgreSQL instance permits extension installation by those delegate roles.

If successful, make check will produce the output of almost 500 tests. The results will look similar to the following (numerous lines omitted below):

Code
CUnit - A unit testing framework for C - Version 2.1-3
     http://cunit.sourceforge.net/

  .
  .
  .

Run Summary:    Type  Total    Ran Passed Failed Inactive
              suites     44     44    n/a      0        0
               tests    300    300    300      0        0
             asserts   4215   4215   4215      0      n/a
Elapsed time =    0.229 seconds

  .
  .
  .

Running tests

  .
  .
  .

Run tests: 134
Failed: 0


-- if you build with SFCGAL

  .
  .
  .

Running tests

  .
  .
  .

Run tests: 13
Failed: 0

-- if you built with raster support

  .
  .
  .

Run Summary:    Type  Total    Ran Passed Failed Inactive
              suites     12     12    n/a      0        0
               tests     65     65     65      0        0
             asserts  45896  45896  45896      0      n/a


  .
  .
  .

Running tests

  .
  .
  .

Run tests: 101
Failed: 0

-- topology regress

.
.
.

Running tests

  .
  .
  .

Run tests: 51
Failed: 0

-- if you built --with-gui, you should see this too

     CUnit - A unit testing framework for C - Version 2.1-2
     http://cunit.sourceforge.net/

  .
  .
  .

Run Summary:    Type  Total    Ran Passed Failed Inactive
              suites      2      2    n/a      0        0
               tests      4      4      4      0        0
             asserts      4      4      4      0      n/a

다음과 같은 결과가 나와야 합니다:

래스터 출력
============== dropping database "contrib_regression" ==============
DROP DATABASE
============== creating database "contrib_regression" ==============
CREATE DATABASE
ALTER DATABASE
============== installing fuzzystrmatch               ==============
CREATE EXTENSION
============== installing postgis                     ==============
CREATE EXTENSION
============== running regression test queries        ==============
test test-normalize_address   ... ok

=====================
All 2 tests passed.
=====================

2.2.7. 설치

PostGIS 설치를 위해서 다음을 입력하십시오.

Code
make install

이것은 --prefix 설정 파라미터에 정의된 하위 경로에 PostGIS 설치 파일을 복사할 것입니다.

  • 로더(loader)와 덤퍼 바이너리 들은 [prefix]/bin에 설치됩니다.

  • postgis.sql와 같은 SQL 파일들은 [prefix]/share/contrib에 설치됩니다.

  • PostGIS 라이브러리들은 [prefix]/lib에 설치됩니다.

만약 기존에 postgis_comments.sql, raster_comments.sql 파일을 생성하기 위해 make comments 명령어를 실행한 적이 있으시다면, 다음을 실행해 sql 파일을 설치하십시오.

Code
make comments-install
[참고]

xsltproc의 적용 이후 일반적인 설치로부터 postgis_comments.sql, raster_comments.sql, topology_comments.sql는 분리되었습니다.

2.3. 설치 과정에서 흔히 발생하는 문제들

인스톨이나 업그레이드 시 잘 되지 않을 경우 확인해야 할 몇 가지 사항은 아래와 같습니다.

PostgreSQL version mismatch.

PostgreSQL 14 또는 그 보다 최신 버전을 설치하셨는지 체크하십시오. 현재 작동하고 계시는 PostgreSQL의 버전과 동일한 PostgreSQL 소스 버전을 바탕으로 컴파일하였는지 확인해주십시오. (Linux) 배포본이 이미 PostgreSQL이 설치된 경우 중복 설치가 될 수 있고, 또는 이전에 설치한 사실을 잊어버렸을 수도 있습니다. PostGIS는 PostgreSQL 14 또는 그 이상 버전에서 작동되므로 구 버전을 이용 시 예상하지 못한 에러들이 발생할 수 있습니다. 어떤 PostgreSQL 버전이 작동하고 있는지 확인하기 위해서는 psql을 통하여 데이터베이스에 접속해 다음의 쿼리를 실행하십시오:

Code
SELECT version();

If you are running an RPM based distribution, you can check for the existence of pre-installed packages using the rpm command as follows:

Code
rpm -qa | grep postgresql

Restoring an upgrade into a database without PostGIS.

만약 업그레이드가 실패하면 기존 PostGIS설치 버전으로 복원하셔야 합니다.

Code
SELECT PostGIS_Full_Version();

또한 PostreSQL, Proj4 라이브러리 및 GEOS 라이브러리에 대한 버전과 경로에 대한 설정이 올바른지 확인하십시오.

설정은 postgis_config.hh 파일을 생성하기 위해 사용됩니다. POSTGIS_PGSQL_VERSION, POSTGIS_PROJ_VERSION and POSTGIS_GEOS_VERSION 변수가 정확한지 확인하십시오.

3장. PostGIS Administration

3.1. Performance Tuning

Tuning for PostGIS performance is much like tuning for any PostgreSQL workload. The only additional consideration is that geometries and rasters are usually large, so memory-related optimizations generally have more of an impact on PostGIS than other types of PostgreSQL queries.

For general details about optimizing PostgreSQL, refer to Tuning your PostgreSQL Server.

PostgreSQL configuration can be set at the server level without touching postgresql.conf or postgresql.auto.conf by using the ALTER SYSTEM command.

Set work_mem, reload the configuration so new connections use the change, and display the current value. Use SHOW ALL to list all settings.

Code
ALTER SYSTEM SET work_mem = '256MB';
SELECT pg_reload_conf();
SHOW work_mem;

In addition to the Postgres settings, PostGIS has some custom settings which are listed in 7.22절. “PostGIS GUC(Grand Unified Custom Variable)”.

3.1.1. Startup

These settings are configured in postgresql.conf:

constraint_exclusion

  • Default: partition

  • This is generally used for table partitioning. The default of "partition" forces the planner to only analyze tables for constraint consideration if they are in an inherited hierarchy and avoids paying the planner penalty otherwise.

shared_buffers

  • Default: ~128MB

  • Set to about 25% to 40% of available RAM. On windows you may not be able to set as high.

max_worker_processes controls the maximum number of background processes available to the server and therefore also bounds how many workers can participate in parallel queries.

  • Default: 8

  • Sets the maximum number of background processes that the system can support. This parameter can only be set at server start.

3.1.2. Runtime

work_mem - sets the size of memory used for sort operations and complex queries

  • Default: 1-4MB

  • Adjust up for large dbs, complex queries, lots of RAM

  • Adjust down for many concurrent users or low RAM.

  • If you have lots of RAM and few developers:

    Code
    SET work_mem TO '256MB';

maintenance_work_mem - the memory size used for VACUUM, CREATE INDEX, etc.

  • Default: 16-64MB

  • Generally too low - ties up I/O, locks objects while swapping memory

  • Recommend 32MB to 1GB on production servers w/lots of RAM, but depends on the # of concurrent users. If you have lots of RAM and few developers:

    Code
    SET maintenance_work_mem TO '1GB';

max_parallel_workers_per_gather

Parallel query support in modern PostgreSQL and PostGIS uses this setting to decide how many workers a plan may request. If set to higher than 0, then some queries such as those involving relation functions like ST_Intersects can use multiple processes and can run more than twice as fast when doing so. If you have a lot of processors to spare, you should change the value of this to as many processors as you have. Also make sure to bump up max_worker_processes to at least as high as this number.

  • Default: 0

  • Sets the maximum number of workers that can be started by a single Gather node. Parallel workers are taken from the pool of processes established by max_worker_processes. Note that the requested number of workers may not actually be available at run time. If this occurs, the plan will run with fewer workers than expected, which may be inefficient. Setting this value to 0, which is the default, disables parallel query execution.

3.2. Configuring raster support

If you enabled raster support you may want to read below how to properly configure it.

Out-of-db rasters and all raster drivers are disabled by default. In order to re-enable these, you need to set the following environment variables POSTGIS_GDAL_ENABLED_DRIVERS and POSTGIS_ENABLE_OUTDB_RASTERS in the server environment. You can also use the more cross-platform approach of setting the corresponding 7.22절. “PostGIS GUC(Grand Unified Custom Variable)”.

If you want to enable offline raster:

Code
POSTGIS_ENABLE_OUTDB_RASTERS=1

Any other setting or no setting at all will disable out of db rasters.

In order to enable all GDAL drivers available in your GDAL install, set this environment variable as follows

Code
POSTGIS_GDAL_ENABLED_DRIVERS=ENABLE_ALL

If you want to only enable specific drivers, set your environment variable as follows:

Code
POSTGIS_GDAL_ENABLED_DRIVERS="GTiff PNG JPEG GIF XYZ"
[참고]

If you are on windows, do not quote the driver list

Setting environment variables varies depending on OS. For PostgreSQL installed on Ubuntu or Debian via apt-postgresql, the preferred way is to edit /etc/postgresql/MAJOR/CLUSTER/environment where the placeholders refer to the PostgreSQL major version and cluster name.

On windows, if you are running as a service, you can set via System variables which for Windows 7 you can get to by right-clicking on Computer->Properties Advanced System Settings or in explorer navigating to Control Panel\All Control Panel Items\System. Then clicking Advanced System Settings ->Advanced->Environment Variables and adding new system variables.

After you set the environment variables, you'll need to restart your PostgreSQL service for the changes to take effect.

3.3. 공간 데이터베이스 생성

3.3.1. Spatially enable database using EXTENSION

If you have compiled and installed the extensions/postgis modules, you can turn a database into a spatial one using the EXTENSION mechanism.

Core postgis extension includes geometry, geography, spatial_ref_sys and all the functions and comments. Raster and topology are packaged as a separate extension.

Run the following SQL snippet in the database you want to enable spatially:

Code
CREATE EXTENSION IF NOT EXISTS plpgsql;
CREATE EXTENSION postgis;
CREATE EXTENSION postgis_raster; -- OPTIONAL
CREATE EXTENSION postgis_topology; -- OPTIONAL

3.3.2. Spatially enable database without using EXTENSION (discouraged)

[참고]

This is generally only needed if you cannot or don't want to get PostGIS installed in the PostgreSQL extension directory (for example during testing, development or in a restricted environment).

Adding PostGIS objects and function definitions into your database is done by loading the various sql files located in [prefix]/share/contrib as specified during the build phase.

The core PostGIS objects (geometry and geography types, and their support functions) are in the postgis.sql script. Raster objects are in the rtpostgis.sql script. Topology objects are in the topology.sql script.

For a complete set of EPSG coordinate system definition identifiers, you can also load the spatial_ref_sys.sql definitions file and populate the spatial_ref_sys table. This will permit you to perform ST_Transform() operations on geometries.

If you wish to add comments to the PostGIS functions, you can find them in the postgis_comments.sql script. Comments can be viewed by simply typing \dd [function_name] from a psql terminal window.

Run the following Shell commands in your terminal:

Code
DB=[yourdatabase]
SCRIPTSDIR=`pg_config --sharedir`/contrib/postgis-3.6/

# Core objects
psql -d ${DB} -f ${SCRIPTSDIR}/postgis.sql
psql -d ${DB} -f ${SCRIPTSDIR}/spatial_ref_sys.sql
psql -d ${DB} -f ${SCRIPTSDIR}/postgis_comments.sql # OPTIONAL

# Raster support (OPTIONAL)
psql -d ${DB} -f ${SCRIPTSDIR}/rtpostgis.sql
psql -d ${DB} -f ${SCRIPTSDIR}/raster_comments.sql # OPTIONAL

# Topology support (OPTIONAL)
psql -d ${DB} -f ${SCRIPTSDIR}/topology.sql
psql -d ${DB} -f ${SCRIPTSDIR}/topology_comments.sql # OPTIONAL

3.4. Upgrading spatial databases

Upgrading existing spatial databases can be tricky as it requires replacement or introduction of new PostGIS object definitions.

Unfortunately not all definitions can be easily replaced in a live database, so sometimes your best bet is a dump/reload process.

PostGIS provides a SOFT UPGRADE procedure for minor or bugfix releases, and a HARD UPGRADE procedure for major releases.

Before attempting to upgrade PostGIS, it is always worth to backup your data. If you use the -Fc flag to pg_dump you will always be able to restore the dump with a HARD UPGRADE.

3.4.1. Soft upgrade

If you installed your database using extensions, you'll need to upgrade using the extension model as well. If you installed using the old sql script way, you are advised to switch your install to extensions because the script way is no longer supported.

3.4.1.1. Soft upgrade using extensions

If you originally installed PostGIS with extensions, then you need to upgrade using extensions as well. Doing a minor upgrade with extensions is fairly painless.

Use the PostGIS_Extensions_Upgrade function to upgrade to the latest version you have installed.

Code
SELECT postgis_extensions_upgrade();

If you are upgrading a database that still runs PostGIS 2.5, issue an ALTER EXTENSION followed by postgis_extensions_upgrade() to make sure the legacy postgis_raster objects are folded back into the main extension.

Code
ALTER EXTENSION postgis UPDATE;
SELECT postgis_extensions_upgrade();

This second call is needed to rebundle the postgis_raster extension.

Code
SELECT postgis_extensions_upgrade();

If you have multiple versions of PostGIS installed, and you don't want to upgrade to the latest, you can explicitly specify the version as follows:

Code
ALTER EXTENSION postgis UPDATE TO "3.7.0beta1";
ALTER EXTENSION postgis_topology UPDATE TO "3.7.0beta1";

If you get an error notice something like:

래스터 출력
No migration path defined for … to 3.7.0beta1

Then you'll need to backup your database, create a fresh one as described in 3.3.1절. “Spatially enable database using EXTENSION” and then restore your backup on top of this new database.

If you get a notice message like:

래스터 출력
Version "3.7.0beta1" of extension "postgis" is already installed

Then everything is already up to date and you can safely ignore it. UNLESS you're attempting to upgrade from an development version to the next (which doesn't get a new version number); in that case you can append "next" to the version string, and next time you'll need to drop the "next" suffix again:

Code
ALTER EXTENSION postgis UPDATE TO "3.7.0beta1next";
        ALTER EXTENSION postgis_topology UPDATE TO "3.7.0beta1next";
[참고]

If you installed PostGIS originally without a version specified, you can often skip the reinstallation of postgis extension before restoring since the backup just has CREATE EXTENSION postgis and thus picks up the newest latest version during restore.

[참고]

If you are upgrading PostGIS extension from a version prior to 3.0.0, you will have a new extension postgis_raster which you can safely drop, if you don't need raster support.

Code
DROP EXTENSION postgis_raster;

3.4.1.2. Soft upgrade without extensions

Extensions have been the supported installation method for many releases. If you still rely on an unpackaged installation, perform a HARD UPGRADE into a database created with extensions and migrate your data there.

3.4.1.3. Hard upgrade

By HARD UPGRADE we mean full dump/reload of postgis-enabled databases. You need a HARD UPGRADE when PostGIS objects' internal storage changes or when SOFT UPGRADE is not possible. The Release Notes appendix reports for each version whether you need a dump/reload (HARD UPGRADE) to upgrade.

The dump/reload process is assisted by the postgis_restore script which takes care of skipping from the dump all definitions which belong to PostGIS (including old ones), allowing you to restore your schemas and data into a database with PostGIS installed without getting duplicate symbol errors or bringing forward deprecated objects.

Supplementary instructions for windows users are available at Windows Hard upgrade.

The Procedure is as follows:

  1. Create a "custom-format" dump of the database you want to upgrade (let's call it olddb) include binary blobs (-b) and verbose (-v) output. The user can be the owner of the db, need not be postgres super account.

    Code
    pg_dump -h localhost -p 5432 -U postgres -Fc -b -v -f "/somepath/olddb.backup" olddb
  2. Do a fresh install of PostGIS in a new database -- we'll refer to this database as newdb. Please refer to 3.3.2절. “Spatially enable database without using EXTENSION (discouraged)” and 3.3.1절. “Spatially enable database using EXTENSION” for instructions on how to do this.

    The spatial_ref_sys entries found in your dump will be restored, but they will not override existing ones in spatial_ref_sys. This is to ensure that fixes in the official set will be properly propagated to restored databases. If for any reason you really want your own overrides of standard entries just don't load the spatial_ref_sys.sql file when creating the new db.

    If your database is really old or you know you've been using long deprecated functions in your views and functions, you might need to load legacy.sql for all your functions and views etc. to properly come back. Only do this if _really_ needed. Consider upgrading your views and functions before dumping instead, if possible. The deprecated functions can be later removed by loading uninstall_legacy.sql.

  3. Restore your backup into your fresh newdb database using postgis_restore. Unexpected errors, if any, will be printed to the standard error stream by psql. Keep a log of those.

    Code
    postgis_restore "/somepath/olddb.backup" | psql -h localhost -p 5432 -U postgres newdb 2> errors.txt

Errors may arise in the following cases:

  1. Some of your views or functions make use of deprecated PostGIS objects. In order to fix this you may try loading legacy.sql script prior to restore or you'll have to restore to a version of PostGIS which still contains those objects and try a migration again after porting your code. If the legacy.sql way works for you, don't forget to fix your code to stop using deprecated functions and drop them loading uninstall_legacy.sql.

  2. Some custom records of spatial_ref_sys in dump file have an invalid SRID value. Valid SRID values are bigger than 0 and smaller than 999000. Values in the 999000.999999 range are reserved for internal use while values > 999999 can't be used at all. All your custom records with invalid SRIDs will be retained, with those > 999999 moved into the reserved range, but the spatial_ref_sys table would lose a check constraint guarding for that invariant to hold and possibly also its primary key ( when multiple invalid SRIDS get converted to the same reserved SRID value ).

    In order to fix this you should copy your custom SRS to a SRID with a valid value (maybe in the 910000..910999 range), convert all your tables to the new srid (see UpdateGeometrySRID), delete the invalid entry from spatial_ref_sys and re-construct the check(s) with:

    Code
    ALTER TABLE spatial_ref_sys ADD CONSTRAINT spatial_ref_sys_srid_check check (srid 
    > 0 AND srid < 999000 );
    
    Code
    ALTER TABLE spatial_ref_sys ADD PRIMARY KEY(srid));
        

    If you are upgrading an old database containing french IGN cartography, you will have probably SRIDs out of range and you will see, when importing your database, issues like this :

    Code
    WARNING: SRID 310642222 converted to 999175 (in reserved zone)

    In this case, you can try following steps : first throw out completely the IGN from the sql which is resulting from postgis_restore. So, after having run :

    Code
    postgis_restore "/somepath/olddb.backup" > olddb.sql

    run this command :

    Code
    grep -v IGNF olddb.sql > olddb-without-IGN.sql

    Create your newdb, activate the required PostGIS extensions, and insert the French IGN spatial reference definitions using this script. After these operations, import your data:

    Code
    psql -h localhost -p 5432 -U postgres -d newdb -f olddb-without-IGN.sql  2> errors.txt

4장. Data Management

4.1. GIS (벡터) 데이터 로드

4.1.1. OGC Geometry

The Open Geospatial Consortium (OGC) developed the Simple Features Access standard (SFA) to provide a model for geospatial data. It defines the fundamental spatial type of Geometry, along with operations which manipulate and transform geometry values to perform spatial analysis tasks. PostGIS implements the OGC Geometry model as the PostgreSQL data types geometry and geography.

Geometry is an abstract type. Geometry values belong to one of its concrete subtypes which represent various kinds and dimensions of geometric shapes. These include the atomic types Point, LineString, LinearRing and Polygon, and the collection types MultiPoint, MultiLineString, MultiPolygon and GeometryCollection. The Simple Features Access - Part 1: Common architecture v1.2.1 adds subtypes for the structures PolyhedralSurface, Triangle and TIN.

Geometry models shapes in the 2-dimensional Cartesian plane. The PolyhedralSurface, Triangle, and TIN types can also represent shapes in 3-dimensional space. The size and location of shapes are specified by their coordinates. Each coordinate has a X and Y ordinate value determining its location in the plane. Shapes are constructed from points or line segments, with points specified by a single coordinate, and line segments by two coordinates.

Coordinates may contain optional Z and M ordinate values. The Z ordinate is often used to represent elevation. The M ordinate contains a measure value, which may represent time or distance. If Z or M values are present in a geometry value, they must be defined for each point in the geometry. If a geometry has Z or M ordinates the coordinate dimension is 3D; if it has both Z and M the coordinate dimension is 4D. The coordinate dimension is at least 2, because every geometry has at least X and Y coordinates.

Geometry values are associated with a spatial reference system indicating the coordinate system in which it is embedded. The spatial reference system is identified by the geometry SRID number. The units of the X and Y axes are determined by the spatial reference system. In planar reference systems the X and Y coordinates typically represent easting and northing, while in geodetic systems they represent longitude and latitude. SRID 0 represents an infinite Cartesian plane with no units assigned to its axes. See 4.5절. “SPATIAL_REF_SYS 테이블과 공간 참조 시스템”.

The geometry dimension is a property of geometry types. Point types have dimension 0, linear types have dimension 1, polygonal types have dimension 2, and solid types have dimension 3. Collections have the dimension of the maximum element dimension.

A geometry value may be empty. Empty values contain no vertices (for atomic geometry types) or no elements (for collections).

An important property of geometry values is their spatial extent or bounding box, which the OGC model calls envelope. This is the 2 or 3-dimensional box which encloses the coordinates of a geometry. It is an efficient way to represent a geometry's extent in coordinate space and to check whether two geometries interact.

The geometry model allows evaluating topological spatial relationships as described in 5.1.1절. “Dimensionally Extended 9-Intersection Model”. To support this the concepts of interior, boundary and exterior are defined for each geometry type. Geometries are topologically closed, so they always contain their boundary. The boundary is a geometry of dimension one less than that of the geometry itself. For example, the boundary of a Polygon is its rings (LineStrings), the boundary of a LineString is its endpoints (Points), and the boundary of a Point is empty.

The OGC geometry model defines validity rules for each geometry type. These rules ensure that geometry values represents realistic situations (e.g. it is possible to specify a polygon with a hole lying outside its shell, but this makes no sense geometrically and is thus invalid). PostGIS also allows storing and manipulating invalid geometry values. This allows detecting and fixing them if needed. See 4.4절. “Geometry Validation”

4.1.1.1. Point

A Point is a 0-dimensional geometry that represents a single location in coordinate space.

Code
POINT (1 2)
POINT Z (1 2 3)
POINT ZM (1 2 3 4)

4.1.1.2. LineString

A LineString is a 1-dimensional line formed by a contiguous sequence of line segments. Each line segment is defined by two points, with the end point of one segment forming the start point of the next segment. An OGC-valid LineString has either zero or two or more points, but PostGIS also allows single-point LineStrings. LineStrings may cross themselves (self-intersect). A LineString is closed if the start and end points are the same. A LineString is simple if it does not self-intersect.

Code
LINESTRING (1 2, 3 4, 5 6)

4.1.1.3. LinearRing

A LinearRing is a LineString which is both closed and simple. The first and last points must be equal, and the line must not self-intersect.

Code
LINEARRING (0 0 0, 4 0 0, 4 4 0, 0 4 0, 0 0 0)

4.1.1.4. Polygon

A Polygon is a 2-dimensional planar region, delimited by an exterior boundary (the shell) and zero or more interior boundaries (holes). Each boundary is a LinearRing.

Code
POLYGON ((0 0 0, 4 0 0, 4 4 0, 0 4 0, 0 0 0), (1 1 0, 2 1 0, 2 2 0, 1 2 0, 1 1 0))

4.1.1.5. MultiPoint

A MultiPoint is a collection of Points.

Code
MULTIPOINT ( (0 0), (1 2) )

4.1.1.6. MultiLineString

A MultiLineString is a collection of LineStrings. A MultiLineString is closed if each of its elements is closed.

Code
MULTILINESTRING ( (0 0, 1 1, 1 2), (2 3, 3 2, 5 4) )

4.1.1.7. MultiPolygon

A MultiPolygon is a collection of non-overlapping, non-adjacent Polygons. Polygons in the collection may touch only at a finite number of points. (Two polygons are adjacent if they share an edge. They touch if they share only points or edges on their boundaries). For more details on MultiPolygon validity, see 4.4절. “Geometry Validation”.

Code
MULTIPOLYGON (((1 5, 5 5, 5 1, 1 1, 1 5)), ((6 5, 9 1, 6 1, 6 5)))

4.1.1.8. GeometryCollection

A GeometryCollection is a heterogeneous (mixed) collection of geometries.

Code
GEOMETRYCOLLECTION ( POINT(2 3), LINESTRING(2 3, 3 4))

4.1.1.9. PolyhedralSurface

A PolyhedralSurface is a contiguous collection of patches or facets which share some edges. Each patch is a planar Polygon. If the Polygon coordinates have Z ordinates then the surface is 3-dimensional.

Code
POLYHEDRALSURFACE Z (
((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)),
((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)),
((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)),
((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)),
((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)),
((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )

4.1.1.10. Triangle

A Triangle is a polygon defined by three distinct non-collinear vertices. Because a Triangle is a polygon it is specified by four coordinates, with the first and fourth being equal.

Code
TRIANGLE ((0 0, 0 9, 9 0, 0 0))

4.1.1.11. TIN

A TIN is a collection of non-overlapping Triangles representing a Triangulated Irregular Network.

Code
TIN Z ( ((0 0 0, 0 0 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 0 0 0)) )

4.1.2. SQL-MM Part 3

The ISO/IEC 13249-3 SQL Multimedia - Spatial standard (SQL/MM) extends the OGC SFA to define Geometry subtypes containing curves with circular arcs. The SQL/MM types support 3DM, 3DZ and 4D coordinates.

[참고]

SQL-MM 실행 과정에서 지정된 허용 오차를 기준으로 부동소수점을 비교합니다. 현재 허용 오차는 1E-8입니다.

4.1.2.1. CircularString

CIRCULARSTRING은 기본 곡선 유형으로, 선형계의 LINESTRING과 비슷합니다. 단일 분절에는 시작점과 종단점(첫 번째 및 세 번째) 그리고 곡선 위의 다른 한 점 이렇게 포인트 세 개가 필요합니다. 예외는 닫힌 원으로, 이 경우 시작점과 종단점이 동일합니다. 이 경우 두 번째 포인트는 원호의 중심, 즉 원의 반대편이 되어야만 합니다. 원호를 함께 묶으려면, LINESTRING과 마찬가지로 한 원호의 마지막 포인트가 다음 원호의 첫 번째 포인트가 되어야 합니다. 즉 유효한 원형 스트링은 1을 초과하는 홀수 개수의 포인트들을 가져야만 한다는 뜻입니다.

Code
CIRCULARSTRING(0 0, 1 1, 1 0)

CIRCULARSTRING(0 0, 4 0, 4 4, 0 4, 0 0)

4.1.2.2. CompoundCurve

복심곡선(compound curve)이란 곡선(원호) 분절과 선형 분절이 함께 있는 연속적인 단일 곡선을 말합니다. 즉 구성 요소들이 잘 형성되어야 함은 물론, (마지막을 제외한) 모든 구성 요소의 종단점이 다음 구성 요소의 시작점과 일치해야한 한다는 뜻입니다.

Code
COMPOUNDCURVE( CIRCULARSTRING(0 0, 1 1, 1 0), (1 0, 0 1))

4.1.2.3. CurvePolygon

CURVEPOLYGON은 일반 폴리곤입니다. 외곽선과 함께 0개 이상의 내곽선을 가지고 있을 뿐입니다. 차이라면 내외곽선이 원형 스트링, 선형 스트링, 또는 복합 스트링 형태를 할 수 있다는 점입니다.

PostGIS는 1.4버전부터 만곡 폴리곤에 대해 복심곡선을 지원합니다.

Code
CURVEPOLYGON(
CIRCULARSTRING(0 0, 4 0, 4 4, 0 4, 0 0),
(1 1, 3 3, 3 1, 1 1) )

Example: A CurvePolygon with the shell defined by a CompoundCurve containing a CircularString and a LineString, and a hole defined by a CircularString

Code
CURVEPOLYGON(
COMPOUNDCURVE( CIRCULARSTRING(0 0, 2 0, 2 1, 2 3, 4 3),
               (4 3, 4 5, 1 4, 0 0)),
CIRCULARSTRING(1.7 1, 1.4 0.4, 1.6 0.4, 1.6 0.5, 1.7 1) )

4.1.2.4. MultiCurve

MULTICURVE는 원형 스트링, 선형 스트링, 복합 스트링을 포함할 수 있는 곡선 집합입니다.

Code
MULTICURVE( (0 0, 5 5), CIRCULARSTRING(4 0, 4 4, 8 4))

4.1.2.5. MultiSurface

MULTISURFACE는 면 집합으로, (선형) 폴리곤일 수도 만곡 폴리곤일 수도 있습니다.

Code
MULTISURFACE(
CURVEPOLYGON(
  CIRCULARSTRING( 0 0, 4 0, 4 4, 0 4, 0 0),
  (1 1, 3 3, 3 1, 1 1)),
((10 10, 14 12, 11 10, 10 10), (11 11, 11.5 11, 11 11.5, 11 11)))

4.1.3. OpenGIS WKB 및 WKT

OpenGIS사양서에는 공간 오브젝트들을 나타내는 두 가지 표준 방법이 정의되어 있습니다: Well-Known Text (WKT) 형태와 Well-Known Binary (WKB) 형태. WKT와 WKB 모두 오브젝트 타입과 오브젝트를 구성하는 좌표들에 대한 정보를 포함하고 있습니다.

공간 참조 시스템의 WKT(Well-Known Text) 표현식입니다. 다음은 WKT SRS 표현식의 예입니다:

  • POINT(0 0)

  • POINT(0 0)

  • POINT(0 0)

  • POINT EMPTY

  • LINESTRING(0 0,1 1,1 2)

  • LINESTRING

  • POLYGON((0 0,4 0,4 4,0 4,0 0),(1 1, 2 1, 2 2, 1 2,1 1))

  • MULTIPOINT((0 0),(1 2))

  • MULTIPOINT((0 0),(1 2))

  • MULTIPOINT

  • MULTILINESTRING((0 0,1 1,1 2),(2 3,3 2,5 4))

  • MULTIPOLYGON(((0 0,4 0,4 4,0 4,0 0),(1 1,2 1,2 2,1 2,1 1)), ((-1 -1,-1 -2,-2 -2,-2 -1,-1 -1)))

  • GEOMETRYCOLLECTION(POINT(2 3), LINESTRING(2 3,3 4))

  • GEOMETRYCOLLECTION

Input and output of WKT is provided by the functions ST_AsText and ST_GeomFromText:

Code
text WKT = geometry;
geometry = ST_GeomFromText(text WKT, SRID);

For example, a statement to create and insert a spatial object from WKT with SRID 312 is:

Code
INSERT INTO geotable ( geom, name )
VALUES ( ST_GeomFromText('POINT(-126.4 45.32)', 312), 'A Place');

Well-Known Binary (WKB) provides a portable, full-precision representation of spatial data as binary data (arrays of bytes). Examples of the WKB representations of spatial objects are:

  • POINT(0 0)

    WKB: 0101000000000000000000F03F000000000000F03

  • LINESTRING(0 0,1 1,1 2)

    WKB: 0102000000020000000000000000000040000000000000004000000000000022400000000000002240

Input and output of WKB is provided by the functions ST_AsBinary and ST_GeomFromWKB:

Code
bytea WKB = ST_AsBinary(geometry);
geometry = ST_GeomFromWKB(bytea WKB, SRID);

예를 들어 OGC 공간 객체를 생성하고 삽입하기 위한 유효한 삽입 구문은 다음과 같을 것입니다:

Code
INSERT INTO geotable ( geom, name )
VALUES ( ST_GeomFromWKB('\x0101000000000000000000f03f000000000000f03f', 312), 'A Place');

4.2. Geometry Data Type

PostGIS implements the OGC Simple Features model by defining a PostgreSQL data type called geometry. It represents all of the geometry subtypes by using an internal type code (see GeometryType and ST_GeometryType). This allows modelling spatial features as rows of tables defined with a column of type geometry.

The geometry data type is opaque, which means that all access is done via invoking functions on geometry values. Functions allow creating geometry objects, accessing or updating all internal fields, and computing new geometry values. PostGIS supports all the functions specified in the OGC Simple feature access - Part 2: SQL option (SFS) specification, as well many others. See 7장. PostGIS Reference for the full list of functions.

[참고]

PostGIS follows the SFA standard by prefixing spatial functions with "ST_". This was intended to stand for "Spatial and Temporal", but the temporal part of the standard was never developed. Instead it can be interpreted as "Spatial Type".

OpenGIS 사양서는 공간 객체의 내부 저장 형식이 공간 참조 시스템 식별자(SRID)를 포함하도록 요구합니다. 데이터베이스에 삽입될 공간 객체 생성시 SRID가 필요합니다.

To make querying geometry efficient PostGIS defines various kinds of spatial indexes, and spatial operators to use them. See 4.9절. “인덱스 빌드 작업” and 5.2절. “Using Spatial Indexes” for details.

4.2.1. OpenGIS WKB 및 WKT

OGC SFA specifications initially supported only 2D geometries, and the geometry SRID is not included in the input/output representations. The OGC SFA specification 1.2.1 (which aligns with the ISO 19125 standard) adds support for 3D (ZYZ) and measured (XYM and XYZM) coordinates, but still does not include the SRID value.

Because of these limitations PostGIS defined extended EWKB and EWKT formats. They provide 3D (XYZ and XYM) and 4D (XYZM) coordinate support and include SRID information. Including all geometry information allows PostGIS to use EWKB as the format of record (e.g. in DUMP files).

EWKB and EWKT are used for the "canonical forms" of PostGIS data objects. For input, the canonical form for binary data is EWKB, and for text data either EWKB or EWKT is accepted. This allows geometry values to be created by casting a text value in either HEXEWKB or EWKT to a geometry value using ::geometry. For output, the canonical form for binary is EWKB, and for text it is HEXEWKB (hex-encoded EWKB).

For example this statement creates a geometry by casting from an EWKT text value, and outputs it using the canonical form of HEXEWKB:

Code
SELECT 'SRID=4;POINT(0 0)'::geometry;
래스터 출력
geometry
----------------------------------------------------
01010000200400000000000000000000000000000000000000

PostGIS EWKT output has a few differences to OGC WKT:

  • For 3DZ geometries the Z qualifier is omitted:

    POINT(0 0)

    POINT(0 0)

  • For 3DM geometries the M qualifier is included:

    POINT(0 0)

    POINT(0 0)

  • For 4D geometries the ZM qualifier is omitted:

    POINT(0 0)

    POINT(0 0)

EWKT avoids over-specifying dimensionality and the inconsistencies that can occur with the OGC/ISO format, such as:

  • POINT(0 0)

  • POINT(0 0)

  • POINT(0 0)

[경고]

PostGIS는 현재 OGC 형식의 상위 집합인 형식을 확장합니다(유효한 모든 WKB/WKT는 유효한 EWKB/EWKT가 됩니다). 하지만 향후 달라질 수도 있습니다. 특히 OGC가 PostGIS 확장 프로그램과 상충하는 새 형식을 들고 나온다면 말입니다. 그러므로 이 피처에 의존해서는 안 됩니다!

피쳐들의 공간 오브젝트들의 텍스트 문자열표현들(WKT) 의 예들로는 다음과 같은 것들이 있습니다:

  • POINT(0 0 0) -- XYZ

  • SRID=32632;POINT(0 0) -- SRID 추가 XY

  • POINTM(0 0 0) -- XYM

  • POINT(0 0 0 0) -- XYZM

  • SRID=4326;MULTIPOINTM(0 0 0,1 2 1) -- SRID 추가 XYM

  • MULTILINESTRING((0 0 0,1 1 0,1 2 1),(2 3 1,3 2 1,5 4 1))

  • POLYGON((0 0 0,4 0 0,4 4 0,0 4 0,0 0 0),(1 1 0,2 1 0,2 2 0,1 2 0,1 1 0))

  • MULTIPOLYGON(((0 0 0,4 0 0,4 4 0,0 4 0,0 0 0),(1 1 0,2 1 0,2 2 0,1 2 0,1 1 0)),((-1 -1 0,-1 -2 0,-2 -2 0,-2 -1 0,-1 -1 0)))

  • GEOMETRYCOLLECTIONM( POINTM(2 3 9), LINESTRINGM(2 3 4, 3 4 5) )

  • MULTICURVE( (0 0, 5 5), CIRCULARSTRING(4 0, 4 4, 8 4) )

  • POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )

  • TRIANGLE ((0 0, 0 9, 9 0, 0 0))

  • TIN( ((0 0 0, 0 0 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 0 0 0)) )

다음과 같은 인터페이스를 이용해서 이 형식을 입력/출력할 수 있습니다.

Code
bytea EWKB = ST_AsEWKB(geometry);
text EWKT = geometry;
geometry = ST_GeomFromEWKB(bytea EWKB);
geometry = ST_GeomFromEWKT(text EWKT);

예를 들어 PostGIS 공간 객체를 생성하고 삽입하기 위한 유효한 삽입 구문은 다음과 같을 것입니다:

Code
INSERT INTO geotable ( geom, name )
VALUES ( ST_GeomFromEWKT('SRID=312;POINTM(-126.4 45.32 15)'), 'A Place' )

4.3. PostGIS 지리형 유형

지리형 유형은 (종종 "측지" 좌표, 또는 "위도/경도"나 "경도/위도"라고 불리는) "지리" 좌표로 표현되는 공간 피처를 자체적으로 지원합니다. 지리 좌표는 각도 단위(도)를 사용하는 구면(球面) 좌표입니다.

PostGIS 도형 유형은 평면을 기반으로 합니다. 평면상에서 두 포인트 사이의 가장 짧은 경로는 직선입니다. 즉 데카르트 수학과 직선 벡터를 이용해서 도형에 대해 계산(면적, 거리, 길이, 교차점 등)한다는 뜻입니다.

PostGIS 지리형 유형은 구면을 기반으로 합니다. 구면상에서 두 포인트 사이의 가장 짧은 경로는 대권(大圈; great circle arc)입니다. 즉 지리형에 대한 계산(면적, 거리, 길이, 교차점 등)은 더 복잡한 수학을 이용해서 구면상에서 이루어져야 한다는 뜻입니다. 더 정확하게 측정하려면 지구의 실제 회전타원체(spheroidal shape)를 고려해서 계산해야 하는데, 수학이 아주 복잡해질 수밖에 없습니다.

기저 수학이 훨씬 더 복잡하기 때문에, 지리형 유형을 위해 정의된 함수는 도형 유형의 함수보다 더 적습니다. 시간이 지날수록 새 알고리즘이 추가되어 지리형 유형의 역량은 확장될 것입니다.

Like the geometry data type, geography data is associated with a spatial reference system via a spatial reference system identifier (SRID). Any geodetic (long/lat based) spatial reference system defined in the spatial_ref_sys table can be used. You can add your own custom geodetic spatial reference system as described in 4.5.2절. “SPATIAL_REF_SYS 테이블과 공간 참조 시스템”.

For all spatial reference systems the units returned by measurement functions (e.g. ST_Distance, ST_Length, ST_Perimeter, ST_Area) and for the distance argument of ST_DWithin are in meters.

4.3.1. 공간 테이블 생성

You can create a table to store geography data using the CREATE TABLE SQL statement with a column of type geography. The following example creates a table with a geography column storing 2D LineStrings in the WGS84 geodetic coordinate system (SRID 4326):

Code
CREATE TABLE global_points (
  id SERIAL PRIMARY KEY,
  name VARCHAR(64),
  location geography(POINT, 4326)
);

The geography type supports two optional type modifiers:

  • 유형 변경자가 허용하는 값은 다음과 같습니다. POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING, MULTIPOLYGON. 또 이 변경자는 Z, M 및 ZM이라는 접미사를 통해 차원수 제약도 지원합니다. 따라서, 예를 들자면 'LINESTRINGM'의 변경자는 3차원 이하의 라인 스트링만을 허용할 것이며, 세 번째 차원을 기준으로 취급할 것입니다. 마찬가지로 'POINTZM'은 네 가지 차원의 데이터를 입력해야 할 것입니다.

  • the SRID modifier restricts the spatial reference system SRID to a particular number. If omitted, the SRID defaults to 4326 (WGS84 geodetic), and all calculations are performed using WGS84.

Examples of creating tables with geography columns:

POINT: 2D 포인트 도형을 담은 테이블 생성:

Code
CREATE TABLE ptgeogwgs(gid serial PRIMARY KEY, geog geography(POINT));

POINT: 2D 포인트 도형을 담은 테이블 생성:

Code
CREATE TABLE ptgeognad83(gid serial PRIMARY KEY, geog geography(POINT, 4269));

Create a table with 3D (XYZ) POINTs and an explicit SRID of 4326:

Code
CREATE TABLE ptzgeogwgs84(gid serial PRIMARY KEY, geog geography(POINTZ, 4326));

Create a table with 2D LINESTRING geography with the default SRID 4326:

Code
CREATE TABLE lgeog(gid serial PRIMARY KEY, geog geography(LINESTRING));

POINT: 2D 포인트 도형을 담은 테이블 생성:

Code
CREATE TABLE lgeognad27(gid serial PRIMARY KEY, geog geography(POLYGON, 4267));

Geography fields are registered in the geography_columns system view. You can query the geography_columns view and see that the table is listed:

Code
SELECT * FROM geography_columns;

도형과 동일한 방법으로 인덱스를 생성합니다. PostGIS가 열 유형이 지리형인 것을 감지하고 일반적인 도형 용 평면 인덱스 대신 적절한 구면 기반 인덱스를 생성할 것입니다.

Code
CREATE INDEX global_points_gix ON global_points USING GIST ( location );

4.3.2. PostGIS 지리형 유형

You can insert data into geography tables in the same way as geometry. Geometry data will autocast to the geography type if it has SRID 4326. The EWKT and EWKB formats can also be used to specify geography values.

Code
INSERT INTO global_points (name, location) VALUES ('Town', 'SRID=4326;POINT(-110 30)');
INSERT INTO global_points (name, location) VALUES ('Forest', 'SRID=4326;POINT(-109 29)');
INSERT INTO global_points (name, location) VALUES ('London', 'SRID=4326;POINT(0 49)');

Any geodetic (long/lat) spatial reference system listed in spatial_ref_sys table may be specified as a geography SRID. Non-geodetic coordinate systems raise an error if used.

A NAD83 longitude/latitude geography value:

Code
SELECT 'SRID=4269;POINT(-123 34)'::geography;
래스터 출력
geography
----------------------------------------------------
 0101000020AD1000000000000000C05EC00000000000004140

A NAD27 longitude/latitude geography value:

Code
SELECT 'SRID=4267;POINT(-123 34)'::geography;
래스터 출력
geography
----------------------------------------------------
 0101000020AB1000000000000000C05EC00000000000004140

NAD83 UTM zone meters fails because it is a meter-based planar projection.

Code
SELECT 'SRID=26910;POINT(-123 34)'::geography;
래스터 출력
ERROR:  Only lon/lat coordinate systems are supported in geography.

쿼리 및 측정 함수는 미터 단위를 사용합니다. 따라서 거리 파라미터는 미터로 표현되어야 하고, 반환값도 미터(또는 면적의 경우 평방미터) 단위가 될 것입니다.

This query finds rows within a 1000 km tolerance:

Code
SELECT name FROM global_points WHERE ST_DWithin(location, 'SRID=4326;POINT(-110 29)'::geography, 1000000);

시애틀에서 런던으로 가는 비행기가(LINESTRING(-122.33 47.606, 0.0 51.5)) 레이캬비크에(POINT(-21.96 64.15)) 얼마나 접근하는지 계산해보면, 실제 계산시 지리형이 얼마나 강력한지 알 수 있습니다.

지리형 유형이 시애틀과 런던을 잇는 대권항로와 레이캬비크 사이의 구면 상 가장 짧은 거리를 실제로 계산할 수 있습니다.

Code
SELECT ST_Distance('LINESTRING(-122.33 47.606,0.0 51.5)'::geography, 'POINT(-21.96 64.15)'::geography);
래스터 출력
st_distance
-----------------
 122235.23815667

대권 매퍼(Great Circle mapper) 도형 유형은 평면 세계지도 상에서 시애틀과 런던을 직선으로 잇는 경로와 레이캬비크 사이의 아무 의미도 없는 데카르트 거리를 계산합니다. 결과값의 명목상 단위를 "도(degree)"라고 할 수도 있겠지만, 결과값은 세 포인트 사이의 어떤 실제 각도 차이도 반영하지 않기 때문에 "도"라고 하는 것조차 부정확한 일이 됩니다.

Code
SELECT ST_Distance('LINESTRING(-122.33 47.606,0.0 51.5)'::geometry, 'POINT(-21.96 64.15)'::geometry);
래스터 출력
st_distance
--------------------
 13.342271221453624
Figure
Geometry figure for visual-manual-12

4.3.3. 도형 데이터 유형과 지리형 데이터 유형을 중첩해서 이용하는 경우

새로운 지리형 유형은 데이터를 경도/위도 좌표로 저장할 수 있도록 해주지만, 단점도 있습니다. 도형을 대상으로 정의된 함수보다 지리형 대상 함수가 더 적고, 그 정의된 함수도 실행하는 데 CPU 시간을 더 많이 잡아먹습니다.

사용자가 선택한 유형은 사용자가 빌드하는 응용 프로그램 영역에서 기대한대로 동작하도록 적합한 조건을 갖춰야 합니다. 사용자 데이터가 전세계 또는 광대한 대륙 지역을 포괄할 예정입니까 아니면 시, 도, 군 또는 그 이하의 지자체에 국한될 예정입니까?

  • 사용자 데이터가 좁은 지역에 국한된다면, 사용 가능한 실행성 및 기능성 관점에서, 적합한 투영을 선택하고 도형을 이용하는 것이 최선의 해결책이 될 수도 있습니다.

  • 사용자 데이터가 전세계 또는 대륙에 걸쳐 있을 경우, 지리형을 이용하면 일일이 어떤 투영법을 이용할지 고민하지 않고 시스템을 빌드할 수도 있습니다. 사용자 데이터를 경도/위도로 저장하고, 지리형을 대상으로 정의된 함수를 이용하십시오.

  • 투영에 대한 이해가 부족하고, 따로 공부하고 싶지도 않으며, 지리형 사용시 기능성이 제한된다는 사실을 받아들일 준비가 되어 있다면, 도형보다 지리형을 사용하는 편이 더 쉬울 수 있습니다. 그냥 사용자 데이터를 경도/위도로 로드한 다음 작업을 시작하십시오.

지리형과 도형을 각각 지원하는 함수를 비교해보려면 13.11절. “PostGIS Function Support Matrix” 를 참조하십시오. 지리형 함수의 목록 및 설명을 간단하게 살펴보려면 13.4절. “PostGIS Geography Support Functions” 를 참조하십시오.

4.3.4. 지리형 고급 FAQ

4.3.4.1.

계산 작업시 구체 상에서 계산하게 됩니까 회전타원체 상에서 하게 됩니까?

By default, all distance and area calculations are done on the spheroid. You should find that the results of calculations in local areas match up well with local planar results in good local projections. Over larger areas, the spheroidal calculations will be more accurate than any calculation done on a projected plane. The difference is that the spheroid takes into account the curvature and non-spherical shape of the Earth, whereas planar calculations assume a flat surface.

최종 불 파라미터 'FALSE'를 설정하면 모든 지리형 함수가 구체 상 계산을 할 수 있습니다. 이렇게 하면 계산 속도가 조금 빨라질 것입니다. 특히 도형들이 매우 단순한 경우에 말입니다.

4.3.4.2.

날짜변경선과 남극/북극은 어떻습니까?

모든 계산은 날짜변경선이나 양극을 고려하지 않고 이루어집니다. 좌표가 회전타원체(경도/위도)이기 때문에 날짜변경선을 지나는 형상이라도, 계산이라는 관점에서 보면, 다른 어떤 형상과도 다를 바가 없습니다.

4.3.4.3.

공간 처리할 수 있는 가장 긴 원호가 무엇인가요?

두 포인트 사이의 "보간 라인"으로 대권호(great circle arc)를 이용합니다. 즉 대권을 따라 어느 방향으로 이동하느냐에 따라 두 포인트가 실제로는 두 가지 방식으로 만난다는 뜻입니다. 모든 코드는 포인트들이 대권을 따라 가는 두 경로 가운데 '짧은' 경로로 만난다고 가정합니다. 결과적으로, 180도 이상의 원호를 가진다면 정확히 모델링된 형상이 아니게 됩니다.

4.3.4.4.

유럽이나 러시아의 면적을 계산하거나 또는 광대한 지역을 삽입하는 작업이 이렇게 느린 이유가 뭐지요?

폴리곤이 너무나 크기 때문이지요! 광대한 지역은 두 가지 이유로 좋지 않습니다. 먼저 경계가 워낙 길기 때문에 어떤 쿼리를 실행하든 인덱스가 피처 전체를 읽어오는 경향이 있습니다. 그리고 꼭짓점 개수도 너무 많아서 거리, 밀폐 여부 등의 테스트를 할 때 적어도 한 번, 때로는 n번 이상(이때 n은 다른 후보 피처의 꼭짓점 개수) 꼭짓점 목록 전체를 훑어야 하기 때문입니다.

도형의 경우, 대용량 폴리곤을 대상으로 좁은 지역에 대한 쿼리를 할 때 사용자 도형 데이터를 더 작은 덩어리들로 "비정규화"해서 인덱스가 효율적으로 객체의 일부분을 하위 쿼리(subquery)할 수 있도록 만들어 쿼리 시 매번 전체 객체를 읽어올 필요가 없도록 하는 편이 좋습니다. 유럽 전체를 폴리곤 한 개로 저장할 수 있다고 해서 꼭 그렇게 해야 한다는 뜻은 아닙니다.

4.4. Geometry Validation

PostGIS is compliant with the Open Geospatial Consortium’s (OGC) Simple Features specification. That standard defines the concepts of geometry being simple and valid. These definitions allow the Simple Features geometry model to represent spatial objects in a consistent and unambiguous way that supports efficient computation. (Note: the OGC SF and SQL/MM have the same definitions for simple and valid.)

4.4.1. Simple Geometry

A simple geometry is one that has no anomalous geometric points, such as self intersection or self tangency.

POINT 란 0차원 도형 객체로서 상속적으로 단순형 입니다.

MULTIPOINT 는 어떤 두 좌표(POINT)도 동일하지 않은 (동일한 좌표를 공유하지 않는) 단순형 입니다.

A LINESTRING is simple if it does not pass through the same point twice, except for the endpoints. If the endpoints of a simple LineString are identical it is called closed and referred to as a Linear Ring.

Use ST_IsSimple to classify linear geometries. Each labeled result below is returned only when the function agrees with the stated classification; example (c) also verifies that the simple LineString is closed.

Code
WITH cases(label, geom) AS (VALUES
  ('a', 'LINESTRING (10 190, 140 130, 70 80, 190 10)'::geometry),
  ('b', 'LINESTRING (10 190, 130 40, 170 160, 10 10)'::geometry),
  ('c', 'LINESTRING (90 190, 120 190, 130 140, 190 50, 70 10, 10 70, 10 150, 90 190)'::geometry),
  ('d', 'LINESTRING (90 190, 120 190, 50 60, 130 10, 190 50, 160 90, 10 150, 90 190)'::geometry)
)
SELECT
  (SELECT geom FROM cases WHERE label = 'a' AND ST_IsSimple(geom))
    AS "input_(a) simple",
  (SELECT geom FROM cases WHERE label = 'b' AND NOT ST_IsSimple(geom))
    AS "input_(b) not simple",
  (SELECT geom FROM cases
             WHERE label = 'c' AND ST_IsSimple(geom) AND ST_IsClosed(geom))
    AS "input_(c) simple, closed",
  (SELECT geom FROM cases WHERE label = 'd' AND NOT ST_IsSimple(geom))
    AS "input_(d) not simple";
래스터 출력
-[ RECORD 1 ]----------
input_(a) simple         | LINESTRING(10 190,140 130,70 80,190 10)
input_(b) not simple     | LINESTRING(10 190,130 40,170 160,10 10)
input_(c) simple, closed | LINESTRING(90 190,120 190,130 140,190 50,70 10,10 70,10 150,90 190)
input_(d) not simple     | LINESTRING(90 190,120 190,50 60,130 10,190 50,160 90,10 150,90 190)
Figure
Geometry figure for visual-simple-linestrings

A MULTILINESTRING is simple only if all of its elements are simple and the only intersection between any two elements occurs at points that are on the boundaries of both elements.

The next example applies the same classification to the three MultiLineStrings. In (f) the component lines meet only at a shared endpoint, while in (g) they cross in their interiors.

Code
WITH cases(label, geom) AS (VALUES
  ('e', 'MULTILINESTRING ((30 190, 60 60, 170 10), (100 190, 180 150, 160 70))'::geometry),
  ('f', 'MULTILINESTRING ((30 190, 60 60, 170 10), (30 190, 180 150, 160 70))'::geometry),
  ('g', 'MULTILINESTRING ((30 190, 60 60, 170 10), (100 190, 180 150, 80 10))'::geometry)
)
SELECT
  (SELECT geom FROM cases WHERE label = 'e' AND ST_IsSimple(geom))
    AS "input_(e) simple",
  (SELECT geom FROM cases WHERE label = 'f' AND ST_IsSimple(geom))
    AS "input_(f) simple",
  (SELECT geom FROM cases WHERE label = 'g' AND NOT ST_IsSimple(geom))
    AS "input_(g) not simple";
래스터 출력
-[ RECORD 1 ]----------
input_(e) simple     | MULTILINESTRING((30 190,60 60,170 10),(100 190,180 150,160 70))
input_(f) simple     | MULTILINESTRING((30 190,60 60,170 10),(30 190,180 150,160 70))
input_(g) not simple | MULTILINESTRING((30 190,60 60,170 10),(100 190,180 150,80 10))
Figure
Geometry figure for visual-simple-multilinestrings

POLYGONs are formed from linear rings, so valid polygonal geometry is always simple.

Generally, PostGIS functions do not require geometric arguments to be simple. Simplicity is primarily used as a basis for defining geometric validity. It is also a requirement for some kinds of spatial data models (for example, linear networks often disallow lines that cross). Multipoint and linear geometry can be made simple using ST_UnaryUnion.

4.4.2. Valid Geometry

Geometry validity primarily applies to 2-dimensional geometries (POLYGONs and MULTIPOLYGONs) . Validity is defined by rules that allow polygonal geometry to model planar areas unambiguously.

A POLYGON is valid if:

  1. the polygon boundary rings (the exterior shell ring and interior hole rings) are simple (do not cross or self-touch). Because of this a polygon cannot have cut lines, spikes or loops. This implies that polygon holes must be represented as interior rings, rather than by the exterior ring self-touching (a so-called "inverted hole").

  2. boundary rings do not cross

  3. boundary rings may touch at points but only as a tangent (i.e. not in a line)

  4. interior rings are contained in the exterior ring

  5. the polygon interior is simply connected (i.e. the rings must not touch in a way that splits the polygon into more than one part)

Consecutive repeated points in a polygon boundary ring do not make the ring non-simple. Under the SFS curve model, a curve is interpreted by a continuous parameterization; consecutive equal coordinates are topologically indistinguishable from a single vertex. PostGIS therefore treats them as redundant vertices, so they do not make an otherwise valid polygon invalid.

The following examples use ST_IsValid to check the validity rules. Each labeled geometry is returned only if its computed validity agrees with the label.

Code
WITH cases(label, geom) AS (VALUES
  ('h', 'POLYGON ((10 140, 90 190, 130 170, 190 60, 160 10, 50 20, 10 140),
                 (50 100, 70 80, 110 100, 110 140, 50 100))'::geometry),
  ('i', 'POLYGON ((10 140, 90 190, 130 170, 190 60, 160 10, 50 20, 10 140),
                 (190 60, 140 40, 110 60, 120 90, 190 60))'::geometry)
)
SELECT
  (SELECT geom FROM cases WHERE label = 'h' AND ST_IsValid(geom))
    AS "input_(h) valid",
  (SELECT geom FROM cases WHERE label = 'i' AND ST_IsValid(geom))
    AS "input_(i) valid, tangent hole";
래스터 출력
-[ RECORD 1 ]----------
input_(h) valid               | POLYGON((10 140,90 190,130 170,190 60,160 10,50 20,10 140),(50 100,70 80,110 100,110 140,50 100))
input_(i) valid, tangent hole | POLYGON((10 140,90 190,130 170,190 60,160 10,50 20,10 140),(190 60,140 40,110 60,120 90,190 60))
Figure
Geometry figure for visual-valid-polygons

Examples (j-m) are invalid. They show, respectively, a disconnected interior, crossing rings, a cut line, and a hole outside the shell. The invalidity reason is checked with ST_IsValidReason. The disconnected interior in (j) can instead be represented as a valid MULTIPOLYGON.

Code
WITH cases(label, geom, reason_pattern) AS (VALUES
  ('(j) disconnected interior',
   'POLYGON ((10 140, 90 190, 130 170, 190 60, 160 10, 50 20, 10 140),
             (130 170, 10 140, 50 120, 110 110, 130 170))'::geometry,
   'Interior is disconnected%'),
  ('(k) crossing rings',
   'POLYGON ((10 140, 90 190, 130 170, 190 60, 160 10, 50 20, 10 140),
             (90 189, 10 139, 80 110, 110 130, 90 189))'::geometry,
   'Self-intersection%'),
  ('(l) cut line',
   'POLYGON ((10 100, 60 140, 60 190, 60 140, 130 170,
              190 60, 160 10, 50 20, 10 100))'::geometry,
   'Ring Self-intersection%'),
  ('(m) hole outside shell',
   'POLYGON ((10 40, 10 100, 130 130, 190 80, 140 20, 50 10, 10 40),
             (81 143, 103 143, 112 162, 107 175, 89 183, 71 169, 81 143))'::geometry,
   'Hole lies outside shell%')
)
SELECT label, geom
FROM cases
WHERE NOT ST_IsValid(geom)
  AND ST_IsValidReason(geom) LIKE reason_pattern
ORDER BY label;
래스터 출력
label          | geom
-------------------------+----------------------------------------------------------------------------------------------------------------------------------------
 (j) disconnected interior | POLYGON((10 140,90 190,130 170,190 60,160 10,50 20,10 140),(130 170,10 140,50 120,110 110,130 170))
 (k) crossing rings       | POLYGON((10 140,90 190,130 170,190 60,160 10,50 20,10 140),(90 189,10 139,80 110,110 130,90 189))
 (l) cut line             | POLYGON((10 100,60 140,60 190,60 140,130 170,190 60,160 10,50 20,10 100))
 (m) hole outside shell   | POLYGON((10 40,10 100,130 130,190 80,140 20,50 10,10 40),(81 143,103 143,112 162,107 175,89 183,71 169,81 143))
Figure
Geometry figure for visual-invalid-polygons

A MULTIPOLYGON is valid if:

  1. its element POLYGONs are valid

  2. elements do not overlap (i.e. their interiors must not intersect)

  3. elements touch only at points (i.e. not along a line)

The next example checks the MultiPolygon rules. In (n) the polygons touch at only one point. In (o) they share an edge, and in (p) their interiors overlap.

Code
WITH cases(label, geom, valid, reason_pattern) AS (VALUES
  ('(n) point touch',
   'MULTIPOLYGON (((10 40, 29 118, 100 75, 180 88, 140 30, 70 10, 10 40)),
                  ((50 170, 100 190, 160 180, 180 140, 180 90, 120 120,
                    30 120, 50 170)))'::geometry,
   true, NULL),
  ('(o) shared edge',
   'MULTIPOLYGON (((10 40, 30 120, 120 120, 180 88, 140 30, 70 10, 10 40)),
                  ((50 170, 100 190, 160 180, 180 140, 180 90, 120 120,
                    30 120, 50 170)))'::geometry,
   false, 'Self-intersection%'),
  ('(p) overlap',
   'MULTIPOLYGON (((10 40, 42 93, 130 150, 180 86, 140 30, 70 10, 10 40)),
                  ((50 170, 100 190, 138 182, 149 156, 146 137, 100 100,
                    58 140, 50 170)))'::geometry,
   false, 'Self-intersection%')
)
SELECT label, geom
FROM cases
WHERE ST_IsValid(geom) = valid
  AND (valid OR ST_IsValidReason(geom) LIKE reason_pattern)
ORDER BY label;
래스터 출력
label       | geom
------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------
 (n) point touch  | MULTIPOLYGON(((10 40,29 118,100 75,180 88,140 30,70 10,10 40)),((50 170,100 190,160 180,180 140,180 90,120 120,30 120,50 170)))
 (o) shared edge  | MULTIPOLYGON(((10 40,30 120,120 120,180 88,140 30,70 10,10 40)),((50 170,100 190,160 180,180 140,180 90,120 120,30 120,50 170)))
 (p) overlap      | MULTIPOLYGON(((10 40,42 93,130 150,180 86,140 30,70 10,10 40)),((50 170,100 190,138 182,149 156,146 137,100 100,58 140,50 170)))
Figure
Geometry figure for visual-validity-multipolygons

These rules mean that valid polygonal geometry is also simple.

For linear geometry the only validity rule is that LINESTRINGs must have at least two points and have non-zero length (or equivalently, have at least two distinct points.) Note that non-simple (self-intersecting) lines are valid.

Code
SELECT
ST_IsValid('LINESTRING(0 0,1 1)') AS len_nonzero,
ST_IsValid('LINESTRING(0 0,0 0,0 0)') AS len_zero,
ST_IsValid('LINESTRING(10 10,150 150,180 50,20 130)') AS self_int;
래스터 출력
len_nonzero | len_zero | self_int
-------------+----------+----------
 t           | f        | t
Figure
Geometry figure for visual-manual-18

POINT and MULTIPOINT geometries have no validity rules.

4.4.3. Managing Validity

PostGIS allows creating and storing both valid and invalid Geometry. This allows invalid geometry to be detected and flagged or fixed. There are also situations where the OGC validity rules are stricter than desired (examples of this are zero-length linestrings and polygons with inverted holes.)

Many of the functions provided by PostGIS rely on the assumption that geometry arguments are valid. For example, it does not make sense to calculate the area of a polygon that has a hole defined outside of the polygon, or to construct a polygon from a non-simple boundary line. Assuming valid geometric inputs allows functions to operate more efficiently, since they do not need to check for topological correctness. (Notable exceptions are that zero-length lines and polygons with inversions are generally handled correctly.) Also, most PostGIS functions produce valid geometry output if the inputs are valid. This allows PostGIS functions to be chained together safely.

If you encounter unexpected error messages when calling PostGIS functions (such as "GEOS Intersection() threw an error!"), you should first confirm that the function arguments are valid. If they are not, then consider using one of the techniques below to ensure the data you are processing is valid.

[참고]

If a function reports an error with valid inputs, then you may have found an error in either PostGIS or one of the libraries it uses, and you should report this to the PostGIS project. The same is true if a PostGIS function returns an invalid geometry for valid input.

To test if a geometry is valid use the ST_IsValid function:

Code
SELECT ST_IsValid('POLYGON ((20 180,180 180,180 20,20 20,20 180))');
래스터 출력
t
Figure
Geometry figure for visual-manual-19

Information about the nature and location of an geometry invalidity are provided by the ST_IsValidDetail function:

Code
SELECT valid, reason,location AS location
        FROM ST_IsValidDetail('POLYGON ((20 20,120 190,50 190,170 50,20 20))') AS t;
래스터 출력
valid |      reason       |                  location
-------+-------------------+---------------------------------------------
 f     | Self-intersection | POINT(91.51162790697674 141.56976744186048)
Figure
Geometry figure for visual-manual-20

In some situations it is desirable to correct invalid geometry automatically. Use the ST_MakeValid function to do this. (ST_MakeValid is a case of a spatial function that does allow invalid input!)

By default, PostGIS does not check for validity when loading geometry, because validity testing can take a lot of CPU time for complex geometries. If you do not trust your data sources, you can enforce a validity check on your tables by adding a check constraint:

Code
ALTER TABLE mytable
ADD CONSTRAINT geometry_valid_check
  CHECK (ST_IsValid(geom));

4.5. SPATIAL_REF_SYS 테이블과 공간 참조 시스템

A Spatial Reference System (SRS) (also called a Coordinate Reference System (CRS)) defines how geometry is referenced to locations on the Earth's surface. There are three types of SRS:

  • A geodetic SRS uses angular coordinates (longitude and latitude) which map directly to the surface of the earth.

  • A projected SRS uses a mathematical projection transformation to "flatten" the surface of the spheroidal earth onto a plane. It assigns location coordinates in a way that allows direct measurement of quantities such as distance, area, and angle. The coordinate system is Cartesian, which means it has a defined origin point and two perpendicular axes (usually oriented North and East). Each projected SRS uses a stated length unit (usually metres or feet). A projected SRS may be limited in its area of applicability to avoid distortion and fit within the defined coordinate bounds.

  • A local SRS is a Cartesian coordinate system which is not referenced to the earth's surface. In PostGIS this is specified by a SRID value of 0.

There are many different spatial reference systems in use. Common SRSes are standardized in the European Petroleum Survey Group EPSG database. For convenience PostGIS (and many other spatial systems) refers to SRS definitions using an integer identifier called a SRID.

A geometry is associated with a Spatial Reference System by its SRID value, which is accessed by ST_SRID. The SRID for a geometry can be assigned using ST_SetSRID. Some geometry constructor functions allow supplying a SRID (such as ST_Point and ST_MakeEnvelope). The EWKT format supports SRIDs with the SRID=n; prefix.

Spatial functions processing pairs of geometries (such as overlay and relationship functions) require that the input geometries are in the same spatial reference system (have the same SRID). Geometry data can be transformed into a different spatial reference system using ST_Transform and ST_TransformPipeline. Geometry returned from functions has the same SRS as the input geometries.

4.5.1. SPATIAL_REF_SYS Table

The SPATIAL_REF_SYS table used by PostGIS is an OGC-compliant database table that defines the available spatial reference systems. It holds the numeric SRIDs and textual descriptions of the coordinate systems.

SPATIAL_REF_SYS 테이블 정의는 다음과 같습니다:

Code
CREATE TABLE spatial_ref_sys (
  srid       INTEGER NOT NULL PRIMARY KEY,
  auth_name  VARCHAR(256),
  auth_srid  INTEGER,
  srtext     VARCHAR(2048),
  proj4text  VARCHAR(2048)
)

다음과 같은 명령행 옵션이 있습니다:

srid

데이터베이스 내부에서 공간 참조 시스템(SRS)을 고유하게 식별하는 정수값입니다.

auth_name

해당 참조 시스템을 위해 인용되는 표준 또는 표준들 본체의 명칭입니다. 예를 들어 "EPSG"는 유효한 AUTH_NAME 이라고 할 수 있습니다.

auth_srid

The ID of the Spatial Reference System as defined by the Authority cited in the auth_name. In the case of EPSG, this is the EPSG code.

srtext

공간 참조 시스템의 WKT(Well-Known Text) 표현식입니다. 다음은 WKT SRS 표현식의 예입니다:

Code
PROJCS["NAD83 / UTM Zone 10N",
  GEOGCS["NAD83",
    DATUM["North_American_Datum_1983",
      SPHEROID["GRS 1980", 6378137, 298.257222101]
    ],
    PRIMEM["Greenwich", 0],
    UNIT["degree", 0.0174532925199433]
  ],
  PROJECTION["Transverse_Mercator"],
  PARAMETER["latitude_of_origin", 0],
  PARAMETER["central_meridian", -123],
  PARAMETER["scale_factor", 0.9996],
  PARAMETER["false_easting", 500000],
  PARAMETER["false_northing", 0],
  UNIT["metre", 1]
]

For a discussion of SRS WKT, see the OGC standard Well-known text representation of coordinate reference systems.

proj4text

PostGIS는 좌표 변환 기능을 제공하기 위해 proj4 라이브러리를 이용합니다. PROJ4TEXT 열이 특정 SRID에 대응하는 proj4 좌펴 정의 스트링을 담고 있습니다. 다음은 그 예입니다:

Code
+proj=utm +zone=10 +ellps=clrk66 +datum=NAD27 +units=m

이에 대한 자세한 정보는 http://trac.osgeo.org/proj/ 주소의 proj4 웹사이트를 참조하십시오. spatial_ref_sys.sql 파일이 모든 EPSG 투영에 대한 SRTEXTPROJ4TEXT 정의를 담고 있습니다.

When retrieving spatial reference system definitions for use in transformations, PostGIS uses fhe following strategy:

  • If auth_name and auth_srid are present (non-NULL) use the PROJ SRS based on those entries (if one exists).

  • If srtext is present create a SRS using it, if possible.

  • If proj4text is present create a SRS using it, if possible.

4.5.2. SPATIAL_REF_SYS 테이블과 공간 참조 시스템

PostGIS의 SPATIAL_REF_SYS 테이블이 proj 라이브러리가 처리할 수 있는, 좀 더 널리 사용되는 공간 참조 시스템 3000여 개를 담고 있긴 하지만 현재까지 알려진 모든 공간 참조 시스템을 다 담고 있지는 않으며, 사용자가 proj4의 구조를 잘 알고 있다면 자기만의 사용자 지정 투영을 정의할 수도 있습니다. 공간 참조 시스템 대부분은 특정 지역에 특화되어 있으며, 특화된 지역 범위 바깥에서 사용할 경우 어떤 의미도 없다는 점을 명심하십시오.

핵심 SPATIAL_REF_SYS 테이블에 정의되지 않은 공간 참조 시스템은 http://spatialreference.org/ 에 훌륭하게 정리되어 있습니다.

Some commonly used spatial reference systems are: 4326 - WGS 84 Long Lat, 4269 - NAD 83 Long Lat, 3395 - WGS 84 World Mercator, 2163 - US National Atlas Equal Area, and the 60 WGS84 UTM zones. UTM zones are one of the most ideal for measurement, but only cover 6-degree regions. For WGS84 longitude/latitude data, the UTM zone is least(floor((longitude + 180) / 6) + 1, 60); the EPSG code is 32600 + zone in the northern hemisphere or 32700 + zone in the southern hemisphere.

미국 여러 주의 평면 공간 참조 시스템(미터 또는 피트 기반)은 각 주마다 보통 한 개 또는 두 개가 존재합니다. 미터 기반 공간 참조 시스템 대부분은 SPATIAL_REF_SYS 테이블에 들어 있지만, 피트 기반 또는 ESRI가 생성한 공간 참조 시스템 중 상당수는 사용자가 spatialreference.org 에서 찾아와야 합니다.

You can even define non-Earth-based coordinate systems, such as Mars 2000 This Mars coordinate system is non-planar (it's in degrees spheroidal), but you can use it with the geography type to obtain length and proximity measurements in meters instead of degrees.

Here is an example of loading a custom coordinate system using an unassigned SRID and the PROJ definition for a US-centric Lambert Conformal projection:

Code
INSERT INTO spatial_ref_sys (srid, proj4text)
VALUES ( 990000,
  '+proj=lcc  +lon_0=-95 +lat_0=25 +lat_1=25 +lat_2=25 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs'
);

4.6. 공간 테이블 생성

4.6.1. 공간 테이블 생성

You can create a table to store geometry data using the CREATE TABLE SQL statement with a column of type geometry. The following example creates a table with a geometry column storing 2D (XY) LineStrings in the BC-Albers coordinate system (SRID 3005):

Code
CREATE TABLE roads (
  id SERIAL PRIMARY KEY,
  name VARCHAR(64),
  geom geometry(LINESTRING, 3005)
);

The geometry type supports two optional type modifiers:

  • 유형 변경자가 허용하는 값은 다음과 같습니다. POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING, MULTIPOLYGON. 또 이 변경자는 Z, M 및 ZM이라는 접미사를 통해 차원수 제약도 지원합니다. 따라서, 예를 들자면 'LINESTRINGM'의 변경자는 3차원 이하의 라인 스트링만을 허용할 것이며, 세 번째 차원을 기준으로 취급할 것입니다. 마찬가지로 'POINTZM'은 네 가지 차원의 데이터를 입력해야 할 것입니다.

  • the SRID modifier restricts the spatial reference system SRID to a particular number. If omitted, the SRID defaults to 0.

Examples of creating tables with geometry columns:

Create a table holding any kind of geometry with the default SRID:

Code
CREATE TABLE geoms(gid serial PRIMARY KEY, geom geometry);

Create a table with 2D POINT geometry with the default SRID:

Code
CREATE TABLE pts(gid serial PRIMARY KEY, geom geometry(POINT));

Create a table with 3D (XYZ) POINTs and an explicit SRID of 3005:

Code
CREATE TABLE pts(gid serial PRIMARY KEY, geom geometry(POINTZ, 3005));

Create a table with 4D (XYZM) LINESTRING geometry with the default SRID:

Code
CREATE TABLE lines(gid serial PRIMARY KEY, geom geometry(LINESTRINGZM));

Create a table with 2D POLYGON geometry with the SRID 4267 (NAD 1927 long lat):

Code
CREATE TABLE polys(gid serial PRIMARY KEY, geom geometry(POLYGON, 4267));

It is possible to have more than one geometry column in a table. This can be specified when the table is created, or a column can be added using the ALTER TABLE SQL statement. This example adds a column that can hold 3D LineStrings:

Code
ALTER TABLE roads ADD COLUMN geom2 geometry(LINESTRINGZ, 4326);

4.6.2. The GEOMETRY_COLUMNS VIEW

OpenGIS의 "SQL 용 단순 피처 사양서(Simple Features Specification for SQL)"는 표준 GIS 객체 유형, 그 유형들을 다루기 위해 필요한 함수, 그리고 메타데이터 테이블의 집합을 정의합니다. 메타데이터의 일관성을 유지하기 위해 공간 열 생성 및 삭제와 같은 작업은 OpenGIS가 정의한 특별한 과정을 거쳐 이루어집니다.

Code
\d geometry_columns
래스터 출력
View "public.geometry_columns"
      Column       |          Type          | Modifiers
-------------------+------------------------+-----------
 f_table_catalog   | character varying(256) |
 f_table_schema    | character varying(256) |
 f_table_name      | character varying(256) |
 f_geometry_column | character varying(256) |
 coord_dimension   | integer                |
 srid              | integer                |
 type              | character varying(30)  |

다음과 같은 명령행 옵션이 있습니다:

f_table_catalog, f_table_schema, f_table_name

도형 열을 담고 있는 피처 테이블의 조건을 완전히 만족하는 명칭입니다. "카탈로그"와 "스키마"가 오라클 용어라는 점을 주목하십시오. "카탈로그"를 대체하는 PostgreSQL 용어가 없기 때문에 해당 열은 공백으로 남게 됩니다. "스키마"의 경우 PostgreSQL 스키마 명칭이 사용됩니다(기본값은 public 입니다).

f_geometry_column

피처 테이블이 담고 있는 도형 열의 명칭입니다.

coord_dimension

The coordinate dimension (2, 3 or 4) of the column. The coordinate dimension is at least 2, representing X and Y coordinates.

srid

해당 테이블이 담고 있는 도형의 좌표가 사용하는 공간 좌표 시스템의 ID로, SPATIAL_REF_SYS 를 참조하는 외래 키(foreign key)입니다.

type

공간 객체의 유형입니다. 공간 열을 단일 유형으로 제약하려면 다음 유형 가운데 하나를 이용하십시오. POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING, MULTIPOLYGON, GEOMETRYCOLLECTION 또는 이에 상응하는 XYM 버전의 POINTM, LINESTRINGM, POLYGONM, MULTIPOINTM, MULTILINESTRINGM, MULTIPOLYGONM, GEOMETRYCOLLECTIONM. 혼합 유형 집합을 이용하려면 유형으로 "GEOMETRY"를 이용할 수 있습니다.

4.6.3. geometry_columns에 도형 열을 직접 등록하기

AddGeometryColumn() 함수를 쓸 수 없을 때 이런 일이 발생할 수 있는 두 가지 경우가 있는데, SQL 뷰 그리고 대규모 삽입(bulk insert)의 경우입니다. 이런 경우, 해당 열에 제약 조건을 걸어서 geometry_columns 테이블 등록을 바로잡을 수 있습니다. PostGIS 2.0 이상 버전에서는, 사용자 열이 typmod 기반이라면 생성 과정 중에 정확하게 등록할 것이기 때문에 아무것도 할 필요가 없다는 점을 기억하십시오.

For example, suppose you have a view created like this.

Code
CREATE VIEW public.vwmytablemercator AS
SELECT gid, ST_Transform(geom, 3395) As geom, f_name
FROM public.mytable;

To register the geometry column correctly, cast the transformed geometry.

Code
DROP VIEW public.vwmytablemercator;
CREATE VIEW  public.vwmytablemercator AS
    SELECT gid, ST_Transform(geom, 3395)::geometry(Geometry, 3395) As geom, f_name
    FROM public.mytable;

If the geometry type is known to be a 2D Polygon, specify it in the cast.

Code
DROP VIEW public.vwmytablemercator;
CREATE VIEW  public.vwmytablemercator AS
    SELECT gid, ST_Transform(geom, 3395)::geometry(Polygon, 3395) As geom, f_name
    FROM public.mytable;

For a derivative table created by a bulk insert, create the table first.

Code
SELECT poi.gid, poi.geom, citybounds.city_name
INTO myschema.my_special_pois
FROM poi INNER JOIN citybounds ON ST_Intersects(citybounds.geom, poi.geom);

Create a 2D spatial index on the new table.

Code
CREATE INDEX idx_myschema_myspecialpois_geom_gist
ON myschema.my_special_pois USING gist(geom);

If the points are 3D or measured, an n-D index may be more appropriate.

Code
CREATE INDEX my_special_pois_geom_gist_nd
ON my_special_pois USING gist(geom gist_geometry_ops_nd);

Manually register the new table's geometry column in geometry_columns. This also changes the underlying table structure to make the column typmod-based.

Code
SELECT Populate_Geometry_Columns('myschema.my_special_pois'::regclass);

To retain constraint-based definition behavior, such as for inherited tables where all children do not have the same type and SRID, set the optional use_typmod argument to false.

Code
SELECT Populate_Geometry_Columns('myschema.my_special_pois'::regclass, false);

Although the old constraint-based method is still supported, direct pass-through view columns register correctly in geometry_columns for both typmod-based and constraint-based source columns. In this example we define a column using typmod and another using constraints.

Code
CREATE TABLE pois_ny(gid SERIAL PRIMARY KEY, poi_name text, cat text, geom geometry(POINT, 4326));
SELECT AddGeometryColumn('pois_ny', 'geom_2160', 2160, 'POINT', 2, false);

If we run \d pois_ny in psql, we observe they are defined differently -- one is typmod, one is constraint.

Code
\d pois_ny
래스터 출력
Table "public.pois_ny"
  Column   |         Type          |                       Modifiers

-----------+-----------------------+------------------------------------------------------
 gid       | integer               | not null default nextval('pois_ny_gid_seq'::regclass)
 poi_name  | text                  |
 cat       | character varying(20) |
 geom      | geometry(Point,4326)  |
 geom_2160 | geometry              |
Indexes:
    "pois_ny_pkey" PRIMARY KEY, btree (gid)
Check constraints:
    "enforce_dims_geom_2160" CHECK (st_ndims(geom_2160) = 2)
    "enforce_geotype_geom_2160" CHECK (geometrytype(geom_2160) = 'POINT'::text
        OR geom_2160 IS NULL)
    "enforce_srid_geom_2160" CHECK (st_srid(geom_2160) = 2160)

둘 다 geometry_columns 테이블에 정확하게 등록됩니다.

Code
SELECT f_table_name, f_geometry_column, srid, type
FROM geometry_columns
WHERE f_table_name = 'pois_ny';
래스터 출력
f_table_name | f_geometry_column | srid | type
-------------+-------------------+------+-------
pois_ny      | geom              | 4326 | POINT
pois_ny      | geom_2160         | 2160 | POINT

하지만 -- 다음과 같은 뷰를 생성하려 한다면

Code
CREATE VIEW vw_pois_ny_parks AS
SELECT *
  FROM pois_ny
  WHERE cat='park';

SELECT f_table_name, f_geometry_column, srid, type
    FROM geometry_columns
    WHERE f_table_name = 'vw_pois_ny_parks';

Both the typmod based geom view column and the direct constraint based view column register correctly.

래스터 출력
f_table_name   | f_geometry_column | srid |   type
------------------+-------------------+------+----------
 vw_pois_ny_parks | geom              | 4326 | POINT
 vw_pois_ny_parks | geom_2160         | 2160 | POINT

If the view applies a spatial function to the geometry, such as ST_Transform, you still need to cast the transformed column explicitly so the view can expose the correct type and SRID:

Code
DROP VIEW vw_pois_ny_parks;
CREATE VIEW vw_pois_ny_parks AS
SELECT gid, poi_name, cat,
  geom,
  ST_Transform(geom, 2160)::geometry(POINT, 2160) As geom_2160
  FROM pois_ny
  WHERE cat = 'park';
SELECT f_table_name, f_geometry_column, srid, type
    FROM geometry_columns
    WHERE f_table_name = 'vw_pois_ny_parks';
래스터 출력
f_table_name   | f_geometry_column | srid | type
------------------+-------------------+------+-------
 vw_pois_ny_parks | geom              | 4326 | POINT
 vw_pois_ny_parks | geom_2160         | 2160 | POINT

4.7. GIS (벡터) 데이터 로드

공간 테이블 생성을 끝냈다면, 사용자가 데이터베이스에 GIS 데이터를 업로드할 준비가 된 것입니다. 현재, 형식화된 SQL 구문을 사용하거나 shapefile 로더/덤퍼를 사용하는 두 가지 방법으로 PostGIS/PostgreSQL 데이터베이스에 데이터를 입력할 수 있습니다.

4.7.1. SQL을 이용해 데이터 가져오기

사용자 데이터를 텍스트 표현식으로 변환할 수 있다면, PostGIS에 사용자 데이터를 입력하는 가장 쉬운 방법은 형식화된(formatted) SQL을 이용하는 것입니다. Oracle이나 다른 SQL 데이터베이스와 마찬가지로, SQL 터미널 모니터에 SQL "INSERT" 선언문으로 가득 찬 대용량 텍스트 파일을 송신하는(piping) 방법으로 데이터를 일괄 로드시킬 수 있습니다.

데이터 업로드 파일(예를 들어 roads.sql)은 다음처럼 보일 것입니다:

Code
BEGIN;
INSERT INTO roads (road_id, roads_geom, road_name)
  VALUES (1, 'LINESTRING(191232 243118,191108 243242)', 'Jeff Rd');
INSERT INTO roads (road_id, roads_geom, road_name)
  VALUES (2, 'LINESTRING(189141 244158,189265 244817)', 'Geordie Rd');
INSERT INTO roads (road_id, roads_geom, road_name)
  VALUES (3, 'LINESTRING(192783 228138,192612 229814)', 'Paul St');
INSERT INTO roads (road_id, roads_geom, road_name)
  VALUES (4, 'LINESTRING(189412 252431,189631 259122)', 'Graeme Ave');
INSERT INTO roads (road_id, roads_geom, road_name)
  VALUES (5, 'LINESTRING(190131 224148,190871 228134)', 'Phil Tce');
INSERT INTO roads (road_id, roads_geom, road_name)
  VALUES (6, 'LINESTRING(198231 263418,198213 268322)', 'Dave Cres');
COMMIT;

"psql" SQL 터미널 모니터를 이용해서 PostgreSQL로 데이터 파일을 매우 쉽게 송신할 수 있습니다.

Code
psql -d [database] -f roads.sql

4.7.2. shp2pgsql: ESRI shapefile 로더 이용하기

shp2pgsql 데이터 로더는 ESRI shapefile을, 도형 형식이든 지리형 형식이든, PostGIS/PostgreSQL 데이터베이스로 삽입하기에 적합한 SQL로 변환합니다. 이 로더에는 명령행(command line) 플래그로 구별되는 몇 가지 실행 모드가 존재합니다.

The input must be an unpacked shapefile path. The loader does not read .zip archives directly; unpack the .shp, .shx, and .dbf files before loading.

shp2pgsql 명령행 로더 외에, 사용자가 PostGIS를 처음 접하는 경우 스크립트를 사용하지 않고 단 한 번 로드하는 데 더 쉽게 사용할 수 있을 뿐만 아니라 명령행 로더가 가진 대부분의 옵션도 가지고 있는 shp2pgsql-gui 그래픽 인터페이스도 있습니다. shp2pgsql-gui를 pgAdmin III의 플러그인으로 설정할 수도 있습니다.

c|a|d|p -- 이들은 상호배타적인 옵션들입니다:

-c

새 테이블을 생성한 다음 shapefile의 데이터로 해당 테이블을 채웁니다. 이것이 기본 모드입니다.

-a

기존 데이터베이스 테이블에 shapefile의 데이터를 추가합니다. 이 옵션을 이용해서 복수의 파일을 로드하려면, 파일들이 동일한 속성 및 동일한 데이터 유형을 담고 있어야 한다는 점을 주의하십시오.

-d

기존 데이터베이스 테이블을 삭제(drop)한 다음 shapefile의 데이터를 가진 새 테이블을 생성합니다.

-p

테이블을 생성하는 SQL 코드만 생성하고, 어떤 실제 데이터도 추가하지 않습니다. 테이블 생성과 데이터 로드 단계를 완전히 분리해야 할 경우 사용할 수 있습니다.

-?

도움말 화면을 표출합니다.

-D

산출물 데이터의 형식으로 PostgreSQL "덤프(dump)" 형식을 사용합니다. 이 옵션은 -a, -c 및 -d와 함께 사용할 수 있습니다. 이 덤프 형식은 기본 "삽입" SQL 형식보다 훨씬 빨리 로드할 수 있습니다. 대용량 데이터셋의 경우 이 옵션을 사용하십시오.

-f <fid_column>, --feature-id-column <fid_column>

Specify the name of the feature id column. The default is gid. The value must be a simple PostgreSQL identifier and cannot use a PostgreSQL system column name.

-s [<FROM_SRID>:]<SRID>

도형 테이블을 생성하고 지정된 SRID로 채웁니다. 입력 shapefile이 주어진 FROM_SRID를 쓰도록 설정하는 옵션도 있습니다. 이런 경우 도형이 목표 SRID로 재투영될 것입니다. FROM_SRID는 -D 옵션과 함께 사용될 수 없습니다.

-k

식별자의 대소문자(열, 스키마 및 속성)를 유지합니다. shapefile 안의 속성은 모두 대문자라는 점을 주의하십시오.

-i

DBF 헤더 서명이 64비트 bigint 형식을 보장하더라도, 모든 정수를 표준 32비트 정수로 강제 변환하고 64비트 bigint 형식을 생성하지 않습니다.

-I

도형 열에 GiST 인덱스를 생성합니다.

-u

Create the target table as UNLOGGED. This can speed up loading transient staging data, but PostgreSQL does not preserve unlogged table contents after a crash or unclean shutdown.

-m

Specify a file containing a set of mappings of (long) column names to 10 character DBF column names. The content of the file is one or more lines of two names separated by white space and no trailing or leading space. For example:

COLUMNNAME DBFFIELD1
AVERYLONGCOLUMNNAME DBFFIELD2

-S

다중(multi) 도형 대신 단순 도형을 생성합니다. 이 옵션은 모든 도형이 실제로 단일형(예: 단일 외곽선을 가진 다중 폴리곤 또는 단일 꼭짓점을 가진 다중 포인트)일 경우에만 작동합니다.

-t <dimensionality>

산출 도형이 지정된 차원수를 가지도록 강제합니다. 차원수를 지시하는 데 다음 스트링을 사용하십시오: 2D, 3DZ, 3DM, 4D

입력물이 지정된 차원수보다 낮은 차원일 경우, 출력물의 해당 차원은 0으로 채워질 것입니다. 입력물이 지정된 차원수보다 높은 차원일 경우, 필요 없는 차원은 제거될 것입니다.

-w

WKB 대신 WKT 형식으로 출력합니다. 정확도가 부족하기 때문에 좌표가 이동될 가능성이 있다는 점을 주의하십시오.

-e

각 선언문을 상호처리를 이용하지 않고 자체적으로 실행합니다. 오류를 생성하는 몇몇 망가진 도형이 있을 경우 이 옵션을 사용하면 괜찮은 데이터 대다수를 로드할 수 있습니다. "덤프" 형식은 항상 상호처리를 이용하기 때문에 -D 플래그와 함께 사용할 수 없다는 점을 주의하십시오.

-W <encoding>

입력 데이터(DBF 파일)의 인코딩을 지정합니다. 이 옵션을 사용하면, DBF의 모든 속성을 지정된 인코딩에서 UTF8로 변환합니다. 그 결과로 생성되는 SQL 출력물은 SET CLIENT_ENCODING to UTF8 명령어를 담게 되어, 백엔드에서 UTF8을 데이터베이스 내부에서 이용하도록 설정된 어떤 인코딩으로든 재변환할 수 있습니다.

-N <policy>

NULL 도형 처리 방침 -- insert*(상관없이 삽입), skip(건너뛰기), abort(중단)

-n

DBF 파일만 임포트합니다. 사용자 데이터에 대응하는 shapefile이 없다면, 자동적으로 이 모드로 전환하여 DBF만 로드할 것입니다. 따라서 전체 shapefile 집합을 가지고 있지만 도형을 빼고 속성 데이터만 필요한 경우에만 이 플래그를 설정해야 합니다.

-G

(경도/위도가 필요한) 도형 대신 WGS84 경위도(SRID=4326)를 쓰는 지리형을 이용합니다.

-T <tablespace>

새 테이블을 위한 테이블스페이스를 지정합니다. -X 파라미터가 함께 쓰인 경우가 아니라면 여전히 인덱스가 기본 테이블스페이스를 이용할 것입니다. PostgreSQL 문서는 사용자 지정 테이블스페이스가 필요한 경우를 잘 설명하고 있습니다.

-X <tablespace>

새 테이블의 인덱스를 위한 테이블스페이스를 지정합니다. 이 옵션은 기본 키(primary key) 인덱스에 적용되며, -I 플래그를 함께 사용하는 경우 GiST 공간 인덱스에도 적용됩니다.

-Z

When used, this flag will prevent the generation of ANALYZE statements. Without the -Z flag (default behavior), the ANALYZE statements will be generated.

다음은 로더를 이용해서 입력 파일을 생성하고 업로드하는 세션의 예시입니다:

Code
shp2pgsql -c -D -s 4269 -i -I shaperoads.shp myschema.roadstable > roads.sql
psql -d roadsdb -f roads.sql

UNIX 파이프(pipe)를 이용하면 모든 변환 및 업로드 작업을 한 번에 끝낼 수 있습니다:

Code
shp2pgsql shaperoads.shp myschema.roadstable | psql -d roadsdb

To load a directory of Shapefiles, run the loader once per file and derive the table name from the file name. On Windows cmd.exe, use a single percent sign interactively and double percent signs in a batch file:

Code
REM In a .bat file, use %%F. At an interactive cmd.exe prompt, use %F.
for %%F in ("C:\data\shapefiles\*.shp") do (
  shp2pgsql -d -D -s 4269 -I -W UTF-8 "%%~fF" "myschema.%%~nF" | psql -d roadsdb
)

If every Shapefile has the same attributes and data types and should be appended into one table, create the table from the first file and use -a for the remaining files.

4.8. 공간 테이블 생성

SQL이나 shapefile 로더/덤퍼를 이용해서 데이터베이스로부터 데이터를 추출할 수 있습니다. SQL 단원에서 공간 테이블에 대한 비교 및 쿼리를 할 수 있는 몇몇 연산자에 대해 논의할 것입니다.

4.8.1. SQL을 이용해 데이터 가져오기

데이터베이스로부터 데이터를 추출하는 가장 간단한 방법은 SQL 선별(select) 쿼리로 반환될 레코드 및 열의 개수를 줄인 다음 해당 결과 열을 파싱 가능한 텍스트 파일로 덤프받는 것입니다:

Code
SELECT road_id,road_geom AS geom, road_name FROM roads;
래스터 출력
road_id | geom                                    | road_name
--------+-----------------------------------------+-----------
      1 | LINESTRING(191232 243118,191108 243242) | Jeff Rd
      2 | LINESTRING(189141 244158,189265 244817) | Geordie Rd
      3 | LINESTRING(192783 228138,192612 229814) | Paul St
      4 | LINESTRING(189412 252431,189631 259122) | Graeme Ave
      5 | LINESTRING(190131 224148,190871 228134) | Phil Tce
      6 | LINESTRING(198231 263418,198213 268322) | Dave Cres
      7 | LINESTRING(218421 284121,224123 241231) | Chris Way
(6 rows)

하지만, 반환되는 필드의 개수를 줄이기 위해 어떤 종류의 제약이 필요할 때가 있을 것입니다. 속성 기반 제약의 경우, 일반적인 비공간 테이블의 경우와 동일한 SQL 문법을 쓰면 됩니다. 공간 제약의 경우, 다음 유용한 연산자들을 쓸 수 있습니다.

ST_Intersects

This function tells whether two geometries share any space.

=

이 연산자는 두 도형이 기하학적으로 동일한지를 테스트합니다.예를 들어, 'POLYGON((0 0,1 1,1 0,0 0))'과 'POLYGON((0 0,1 1,1 0,0 0))'이 동일한지를 말입니다(동일합니다).

다음으로, 이 연산자들을 쿼리에 쓸 수 있습니다. SQL 명령행에 도형과 경계 상자를 지정할 때, "ST_GeomFromText()" 함수를 이용해서 스트링 표현식을 도형으로 정확하게 변환시켜야 합니다. 해당 데이터와 일치하는 가공의 공간 참조 시스템은 312입니다. 다음은 그 예시입니다:

Code
SELECT road_id, road_name
FROM roads
WHERE roads_geom='SRID=312;LINESTRING(191232 243118,191108 243242)'::geometry;

이 쿼리는 해당 값과 동일한 도형을 담고 있는 "ROADS_GEOM" 테이블로부터 단일 레코드를 반환할 것입니다.

To check whether some of the roads passes in the area defined by a polygon:

Code
SELECT road_id, road_name
FROM roads
WHERE ST_Intersects(roads_geom, 'SRID=312;POLYGON((...))');

가장 흔한 공간 쿼리는 아마도 데이터 브라우저 또는 웹 매퍼 같은 클라이언트 소프트웨어가 화면 표출을 위해 "맵 프레임(map frame)" 용량에 해당하는 데이터를 가져오기 위해 사용하는 "프레임 기반(frame-based)" 쿼리일 것입니다.

"&&" 연산자 사용시, 비교 피처로 BOX3D 또는 도형을 지정할 수 있습니다. 하지만 도형을 지정했을 경우, 비교 작업에 해당 경계 상자가 사용될 것입니다.

Using a "BOX3D" object for the frame, such a query looks like this:

Code
SELECT roads_geom AS geom
FROM roads
WHERE
  roads_geom && ST_MakeEnvelope(191232, 243117,191232, 243119,312);

화면에 해당하는 데이터의 투영체를 지정하는 데 SRID 312를 썼다는 사실에 주의하십시오.

4.8.2. 덤퍼 이용하기

pgsql2shp 테이블 덤퍼는 데이터베이스에 직접 연결되어 (아마도 쿼리가 정의했을) 테이블을 shapefile로 변환합니다. 기본 문법은 다음과 같습니다:

Code
pgsql2shp [<options
>] <database
> [<schema
>.]<table>
Code
pgsql2shp [<options
>] <database
> <query>

다음과 같은 명령행 옵션이 있습니다:

-f <filename>

특정 파일명으로 출력물을 작성합니다.

-h <host>

연결할 데이터베이스 호스트를 설정합니다.

-p <port>

데이터베이스 호스트 연결시 사용할 포트를 설정합니다.

-P <password>

데이터베이스 연결에 사용할 비밀번호를 설정합니다.

-u <user>

데이터베이스 연결에 사용할 사용자명을 설정합니다.

-g <geometry column>

복수의 도형 열을 가진 테이블일 경우, shapefile 작성에 이용될 도형 열을 설정합니다.

-b

바이너리 커서를 사용하도록 설정합니다. 이 옵션을 쓰면 실행 속도가 빨라지지만, 테이블 안에 있는 비(非) 도형 속성 가운데 하나라도 텍스트로 작성할 캐스트(cast)가 부족할 경우 실행되지 않을 것입니다.

-r

로(raw) 모드입니다. gid 필드를 삭제하거나, 열 명칭을 제외하지 않습니다.

-m filename

식별자를 10문자 명칭으로 다시 매핑(remap)합니다. 해당 파일의 내용은 공백으로 구분된 두 심볼로 이루어진 복수의 행으로, 행 맨 앞과 맨 뒤에는 공백이 없어야 합니다. VERYLONGSYMBOL SHORTONE ANOTHERVERYLONGSYMBOL SHORTER 등과 같은 예가 있습니다.

4.9. 인덱스 빌드 작업

인덱스 덕분에 공간 데이터베이스가 대용량 데이터셋을 사용할 수 있습니다. 인덱스 작업을 하지 않으면, 어떤 피처를 검색하든 데이터베이스 안의 모든 레코드를 "순차 스캔"해야 할 것입니다. 인덱스 작업은 데이터를 특정 레코드를 찾기 위해 빠르게 훑어갈 수 있는 검색 트리로 조직해서 검색 속도를 향상시킵니다. PostgreSQL는 기본적으로 B-Tree, R-Tree, GiST 세 종류의 인덱스를 지원합니다.

The B-tree index method commonly used for attribute data is not very useful for spatial data, since it only supports storing and querying data in a single dimension. Data such as geometry (which has 2 or more dimensions) requires an index method that supports range query across all the data dimensions. One of the key advantages of PostgreSQL for spatial data handling is that it offers several kinds of index methods which work well for multi-dimensional data: GiST, BRIN and SP-GiST indexes.

  • GiST(Generalized Search Tree) 인덱스는 데이터를 "한 쪽에 있는 것", "겹치는 것", "내부에 있는 것"으로 분해하며 GIS 데이터를 포함한 광범위한 데이터 유형에 쓰일 수 있습니다. PostGIS는 GiST를 써서 GIS 데이터에 인덱스 작업을 한 다음, 해당 데이터에 다시 작업된 R-Tree 인덱스를 이용합니다.

  • BRIN (Block Range Index) indexes operate by summarizing the spatial extent of ranges of table records. Search is done via a scan of the ranges. BRIN is only appropriate for use for some kinds of data (spatially sorted, with infrequent or no update). But it provides much faster index create time, and much smaller index size.

  • SP-GiST (Space-Partitioned Generalized Search Tree) is a generic index method that supports partitioned search trees such as quad-trees, k-d trees, and radix trees (tries).

Spatial indexes store only the bounding box of geometries. Spatial queries use the index as a primary filter to quickly determine a set of geometries potentially matching the query condition. Most spatial queries require a secondary filter that uses a spatial predicate function to test a more specific spatial condition. For more information on queying with spatial predicates see 5.2절. “Using Spatial Indexes”.

See also the PostGIS Workshop section on spatial indexes, and the PostgreSQL manual.

4.9.1. GiST 인덱스

GiST는 "일반화된 검색 트리"의 줄임말로, 인덱스 작업의 포괄적인 형태입니다. GIS 인덱스 작업 외에도, 일반 B-Tree 인덱스 작업으로는 쓸 수 없는 온갖 종류의 비정규 데이터 구조(정수 배열, 분광 데이터 등등)에 대한 검색 속도를 향상시키는 데 GiST를 이용합니다.

GIS 데이터 테이블이 수천 행을 넘게 되면, 데이터 공간 검색의 속도를 향상시키기 위해 인덱스를 빌드하고 싶게 될 것입니다(사용자의 모든 검색이 속성에 기반하는 경우가 아니라면 말입니다. 그런 경우, 속성 필드에 대해 일반 인덱스를 빌드하면 됩니다).

"도형" 열에 대해 GiST 인덱스를 빌드하는 데 필요한 문법은 다음과 같습니다:

Code
CREATE INDEX [indexname] ON [tablename] USING GIST ( [geometryfield]);

이 문법은 항상 2D 인덱스를 빌드할 것입니다. 해당 도형 유형에 PostGIS 2.0 이상 버전이 지원하는 n차원 인덱스를 얻으려면, 다음 문법으로 생성할 수 있습니다:

Code
CREATE INDEX [indexname] ON [tablename] USING GIST ([geometryfield] gist_geometry_ops_nd);

Building a spatial index is a computationally intensive exercise. It also blocks write access to your table for the time it creates, so on a production system you may want to do in in a slower CONCURRENTLY-aware way:

Code
CREATE INDEX CONCURRENTLY [indexname] ON [tablename] USING GIST ( [geometryfield]);

After building an index, it is sometimes helpful to force PostgreSQL to collect table statistics, which are used to optimize query plans:

Code
VACUUM ANALYZE [table_name] [(column_name)];

4.9.2. GiST 인덱스

BRIN stands for "Block Range Index". It is a general-purpose index method provided by PostgreSQL. BRIN is a lossy index method, meaning that a secondary check is required to confirm that a record matches a given search condition (which is the case for all provided spatial indexes). It provides much faster index creation and much smaller index size, with reasonable read performance. Its primary purpose is to support indexing very large tables on columns which have a correlation with their physical location within the table. In addition to spatial indexing, BRIN can speed up searches on various kinds of attribute data structures (integer, arrays etc). For more information see the PostgreSQL manual.

GIS 데이터 테이블이 수천 행을 넘게 되면, 데이터 공간 검색의 속도를 향상시키기 위해 인덱스를 빌드하고 싶게 될 것입니다(사용자의 모든 검색이 속성에 기반하는 경우가 아니라면 말입니다. 그런 경우, 속성 필드에 대해 일반 인덱스를 빌드하면 됩니다).

A BRIN index stores the bounding box enclosing all the geometries contained in the rows in a contiguous set of table blocks, called a block range. When executing a query using the index the block ranges are scanned to find the ones that intersect the query extent. This is efficient only if the data is physically ordered so that the bounding boxes for block ranges have minimal overlap (and ideally are mutually exclusive). The resulting index is very small in size, but is typically less performant for read than a GiST index over the same data.

Building a BRIN index is much less CPU-intensive than building a GiST index. It's common to find that a BRIN index is ten times faster to build than a GiST index over the same data. And because a BRIN index stores only one bounding box for each range of table blocks, it's common to use up to a thousand times less disk space than a GiST index.

You can choose the number of blocks to summarize in a range. If you decrease this number, the index will be bigger but will probably provide better performance.

For BRIN to be effective, the table data should be stored in a physical order which minimizes the amount of block extent overlap. It may be that the data is already sorted appropriately (for instance, if it is loaded from another dataset that is already sorted in spatial order). Otherwise, this can be accomplished by sorting the data by a one-dimensional spatial key. One way to do this is to create a new table sorted by the geometry values (which in recent PostGIS versions uses an efficient Hilbert curve ordering):

Code
CREATE TABLE table_sorted AS
SELECT * FROM table  ORDER BY geom;

Alternatively, data can be sorted in-place by using a GeoHash as a (temporary) index, and clustering on that index:

Code
CREATE INDEX idx_temp_geohash ON table
    USING btree (ST_GeoHash(ST_Transform(geom, 4326 ), 20));
CLUSTER table USING idx_temp_geohash;

"도형" 열에 대해 GiST 인덱스를 빌드하는 데 필요한 문법은 다음과 같습니다:

Code
CREATE INDEX [indexname] ON [tablename] USING BRIN ( [geome_col]);

이 문법은 항상 2D 인덱스를 빌드할 것입니다. 해당 도형 유형에 PostGIS 2.0 이상 버전이 지원하는 n차원 인덱스를 얻으려면, 다음 문법으로 생성할 수 있습니다:

Code
CREATE INDEX [indexname] ON [tablename]
USING BRIN ([geome_col] brin_geometry_inclusion_ops_3d);

You can also get a 4D-dimensional index using the 4D operator class:

Code
CREATE INDEX [indexname] ON [tablename]
USING BRIN ([geome_col] brin_geometry_inclusion_ops_4d);

The above commands use the default number of blocks in a range, which is 128. To specify the number of blocks to summarise in a range, use this syntax

Code
CREATE INDEX [indexname] ON [tablename]
USING BRIN ( [geome_col] ) WITH (pages_per_range = [number]); 

Keep in mind that a BRIN index only stores one index entry for a large number of rows. If your table stores geometries with a mixed number of dimensions, it's likely that the resulting index will have poor performance. You can avoid this performance penalty by choosing the operator class with the least number of dimensions of the stored geometries

"도형" 열에 대해 GiST 인덱스를 빌드하는 데 필요한 문법은 다음과 같습니다:

Code
CREATE INDEX [indexname] ON [tablename] USING BRIN ( [geog_col]);

이 문법은 항상 2D 인덱스를 빌드할 것입니다. 해당 도형 유형에 PostGIS 2.0 이상 버전이 지원하는 n차원 인덱스를 얻으려면, 다음 문법으로 생성할 수 있습니다:

Currently, only "inclusion support" is provided, meaning that just the &&, ~ and @ operators can be used for the 2D cases (for both geometry and geography), and just the &&& operator for 3D geometries. There is currently no support for kNN searches.

An important difference between BRIN and other index types is that the database does not maintain the index dynamically. Changes to spatial data in the table are simply appended to the end of the index. This will cause index search performance to degrade over time. The index can be updated by performing a VACUUM, or by using a special function brin_summarize_new_values(regclass). For this reason BRIN may be most appropriate for use with data that is read-only, or only rarely changing. For more information refer to the manual.

To summarize using BRIN for spatial data:

  • Index build time is very fast, and index size is very small.

  • Index query time is slower than GiST, but can still be very acceptable.

  • Requires table data to be sorted in a spatial ordering.

  • Requires manual index maintenance.

  • Most appropriate for very large tables, with low or no overlap (e.g. points), which are static or change infrequently.

  • More effective for queries which return relatively large numbers of data records.

4.9.3. GiST 인덱스

SP-GiST stands for "Space-Partitioned Generalized Search Tree" and is a generic form of indexing for multi-dimensional data types that supports partitioned search trees, such as quad-trees, k-d trees, and radix trees (tries). The common feature of these data structures is that they repeatedly divide the search space into partitions that need not be of equal size. In addition to spatial indexing, SP-GiST is used to speed up searches on many kinds of data, such as phone routing, ip routing, substring search, etc. For more information see the PostgreSQL manual.

As it is the case for GiST indexes, SP-GiST indexes are lossy, in the sense that they store the bounding box enclosing spatial objects. SP-GiST indexes can be considered as an alternative to GiST indexes.

GIS 데이터 테이블이 수천 행을 넘게 되면, 데이터 공간 검색의 속도를 향상시키기 위해 인덱스를 빌드하고 싶게 될 것입니다(사용자의 모든 검색이 속성에 기반하는 경우가 아니라면 말입니다. 그런 경우, 속성 필드에 대해 일반 인덱스를 빌드하면 됩니다).

Code
CREATE INDEX [indexname] ON [tablename] USING SPGIST ( [geometryfield]);

이 문법은 항상 2D 인덱스를 빌드할 것입니다. 해당 도형 유형에 PostGIS 2.0 이상 버전이 지원하는 n차원 인덱스를 얻으려면, 다음 문법으로 생성할 수 있습니다:

Code
CREATE INDEX [indexname] ON [tablename] USING SPGIST ([geometryfield] spgist_geometry_ops_3d);

Building a spatial index is a computationally intensive operation. It also blocks write access to your table for the time it creates, so on a production system you may want to do in in a slower CONCURRENTLY-aware way:

Code
CREATE INDEX CONCURRENTLY [indexname] ON [tablename] USING SPGIST ( [geometryfield]);

After building an index, it is sometimes helpful to force PostgreSQL to collect table statistics, which are used to optimize query plans:

Code
VACUUM ANALYZE [table_name] [(column_name)];

An SP-GiST index can accelerate queries involving the following operators:

  • <<, &<, &>, >>, <<|, &<|, |&>, |>>, &&, @>, <@, and ~=, for 2-dimensional indexes,

  • &/&, ~==, @>>, and <<@, for 3-dimensional indexes.

There is no support for kNN searches at the moment.

4.9.4. 인덱스 빌드 작업

일반적인 경우라면 인덱스는 눈에 보이지 않게 데이터 접속 속도를 향상시킵니다. 인덱스가 빌드된 후, 쿼리 설계자는 쿼리 설계의 속도를 향상기키는 데 언제 인덱스 정보를 사용할 것인지 투명하게 결정합니다. 안타깝게도 PostgreSQL 쿼리 설계자가 GiST 인덱스의 사용을 제대로 최적화시키지 못 하기 때문에, 종종 공간 인덱스를 활용해야 할 검색이 대신 기본값인 전체 데이터의 순차 스캔을 이용할 때가 있습니다.

사용자의 공간 인덱스가 (또는 사용자의 속성 인덱스가) 활용되지 않고 있다는 사실을 알게 되었다면, 몇 가지 해결 방법이 있습니다:

  • Examine the query plan and check your query actually computes the thing you need. An erroneous JOIN, either forgotten or to the wrong table, can unexpectedly retrieve table records multiple times. To get the query plan, execute with EXPLAIN in front of the query.

  • Make sure statistics are gathered about the number and distributions of values in a table, to provide the query planner with better information to make decisions around index usage. VACUUM ANALYZE will compute both.

    You should regularly vacuum your databases anyways. Many PostgreSQL DBAs run VACUUM as an off-peak cron job on a regular basis.

  • 두 번째, 빈공간 분석으로 해결이 안 될 경우 SET ENABLE_SEQSCAN=OFF 명령어를 통해 강제로 쿼리 설계자가 인덱스 정보를 이용하도록 할 수 있습니다. 이 명령어는 공간 인덱스 쿼리일 경우에 한해 드물게 이용해야 합니다. 일반적으로, 쿼리 설계자는 언제 일반 B-Tree 인덱스를 활용해야 하는지 사용자보다 더 잘 알고 있습니다. 사용자 쿼리 실행 후, 다른 쿼리가 평소처럼 쿼리 설계자를 활용하도록 ENABLE_SEQSCAN 을 다시 켤지 고려해봐야 합니다.

  • 쿼리 설계자가 순차 및 인덱스 스캔의 경중(cost)을 잘못 판단하고 있다면, postgresql.conf 파일의 random_page_cost의 값을 줄여보거나 "SET random_page_cost=#"로 써보십시오. 해당 파라미터의 기본값은 4이지만, 1또는 2로 설정해보십시오. 값을 감소시킬수록 점점 더 쿼리 설계자가 인덱스 스캔을 활용하게 될 것입니다.

  • If SET ENABLE_SEQSCAN TO OFF; does not help your query, the query may be using a SQL construct that the Postgres planner is not yet able to optimize. It may be possible to rewrite the query in a way that the planner is able to handle. For example, a subquery with an inline SELECT may not produce an efficient plan, but could possibly be rewritten using a LATERAL JOIN.

For more information see the Postgres manual section on Query Planning.

5장. Spatial Queries

The raison d'etre of spatial databases is to perform queries inside the database which would ordinarily require desktop GIS functionality. Using PostGIS effectively requires knowing what spatial functions are available, how to use them in queries, and ensuring that appropriate indexes are in place to provide good performance.

5.1. Determining Spatial Relationships

Spatial relationships indicate how two geometries interact with one another. They are a fundamental capability for querying geometry.

5.1.1. Dimensionally Extended 9-Intersection Model

According to the OpenGIS Simple Features Implementation Specification for SQL, "the basic approach to comparing two geometries is to make pair-wise tests of the intersections between the Interiors, Boundaries and Exteriors of the two geometries and to classify the relationship between the two geometries based on the entries in the resulting 'intersection' matrix."

In the theory of point-set topology, the points in a geometry embedded in 2-dimensional space are categorized into three sets:

Boundary

The boundary of a geometry is the set of geometries of the next lower dimension. For POINTs, which have a dimension of 0, the boundary is the empty set. The boundary of a LINESTRING is the two endpoints. For POLYGONs, the boundary is the linework of the exterior and interior rings.

Interior

The interior of a geometry are those points of a geometry that are not in the boundary. For POINTs, the interior is the point itself. The interior of a LINESTRING is the set of points between the endpoints. For POLYGONs, the interior is the areal surface inside the polygon.

Exterior

The exterior of a geometry is the rest of the space in which the geometry is embedded; in other words, all points not in the interior or on the boundary of the geometry. It is a 2-dimensional non-closed surface.

The Dimensionally Extended 9-Intersection Model (DE-9IM) describes the spatial relationship between two geometries by specifying the dimensions of the 9 intersections between the above sets for each geometry. The intersection dimensions can be formally represented in a 3x3 intersection matrix.

For a geometry g the Interior, Boundary, and Exterior are denoted using the notation I(g), B(g), and E(g). Also, dim(s) denotes the dimension of a set s with the domain of {0,1,2,F}:

  • 0 => point

  • 1 => line

  • 2 => area

  • F => empty set

Using this notation, the intersection matrix for two geometries a and b is:

 InteriorBoundaryExterior
Interiordim( I(a) ∩ I(b) )dim( I(a) ∩ B(b) )dim( I(a) ∩ E(b) )
Boundarydim( B(a) ∩ I(b) )dim( B(a) ∩ B(b) )dim( B(a) ∩ E(b) )
Exteriordim( E(a) ∩ I(b) )dim( E(a) ∩ B(b) )dim( E(a) ∩ E(b) )

The following overlapping polygons provide a concrete example. ST_Relate computes the matrix 212101212; it matches the overlap pattern T*T***T** used by ST_Overlaps.

Code
WITH example AS (
  SELECT
    'POLYGON ((140 140,140 122,135 105,126 100,118 99,110 94,100 86,97 73,102 59,98 49,87 38,70 30,55 29,40 30,28 38,20 50,14 66,10 84,6 100,4 119,4 143,6 166,10 180,18 191,28 195,40 190,55 189,67 186,86 179,112 165,124 158,133 148,140 140),(48 177,40 177,30 174,24 166,22 159,25 155,30 153,40 154,45 157,52 162,53 169,51 174,48 177))'::geometry AS a,
    'POLYGON ((75 63,79 50,87 38,95 31,108 25,124 22,140 18,154 11,166 6,176 10,184 21,188 35,190 58,190 82,193 104,190 121,185 139,178 154,166 163,154 171,139 172,124 171,112 165,96 152,92 142,92 126,86 116,79 110,75 104,72 94,73 86,75 76,75 63))'::geometry AS b
), relation AS (
  SELECT a, b, ST_Relate(a, b) AS matrix
  FROM example
)
SELECT matrix,
       ST_RelateMatch(matrix, 'T*T***T**') AS matches_overlap_pattern,
       ST_Overlaps(a, b) AS overlaps
FROM relation;
래스터 출력
matrix   | matches_overlap_pattern | overlaps
-----------+-------------------------+----------
 212101212 | t                       | t
(1 row)
Figure
Geometry figure for visual-de9im-overlapping-polygons

The executable query and generated overlay above are the visual source for the relation. The query below renders the nine cells of the same kind of matrix as a 3-by-3 set of examples. The final exterior/exterior cell is clipped to a finite viewport, since the true exterior/exterior intersection is unbounded.

Code
WITH example AS (
  SELECT
    ST_MakeEnvelope(0, 0, 6, 4) AS a,
    ST_MakeEnvelope(3, -1, 8, 3) AS b,
    ST_MakeEnvelope(-1, -2, 9, 5) AS viewport
), parts AS (
  SELECT
    a,
    b,
    ST_Boundary(a) AS ba,
    ST_Boundary(b) AS bb,
    viewport
  FROM example
)
SELECT
  ST_Relate(a, b) AS matrix,
  ST_AsText(ST_Normalize(a)) AS input_a,
  ST_AsText(ST_Normalize(b)) AS input_b,
  ST_AsText(ST_Normalize(ST_Intersection(a, b))) AS "2 I(a) ∩ I(b)",
  ST_AsText(ST_Normalize(ST_Intersection(a, bb))) AS "1 I(a) ∩ B(b)",
  ST_AsText(ST_Normalize(ST_Difference(a, b))) AS "2 I(a) ∩ E(b)",
  ST_AsText(ST_Normalize(ST_Intersection(ba, b))) AS "1 B(a) ∩ I(b)",
  ST_AsText(ST_Normalize(ST_Intersection(ba, bb))) AS "0 B(a) ∩ B(b)",
  ST_AsText(ST_Normalize(ST_Collect(
      'LINESTRING(0 0,0 4,6 4,6 3)'::geometry,
      'LINESTRING(0 0,3 0)'::geometry
  ))) AS "1 B(a) ∩ E(b)",
  ST_AsText(ST_Normalize(ST_Difference(b, a))) AS "2 E(a) ∩ I(b)",
  ST_AsText(ST_Normalize(ST_Collect(
      'LINESTRING(3 -1,8 -1,8 3,6 3)'::geometry,
      'LINESTRING(3 -1,3 0)'::geometry
  ))) AS "1 E(a) ∩ B(b)",
  ST_AsText(ST_Normalize(ST_Difference(viewport, ST_Union(a, b))))
    AS "2 E(a) ∩ E(b) clipped"
FROM parts;
래스터 출력
-[ RECORD 1 ]----------+-----------------------------------------------------------------------------
matrix                 | 212101212
input_a                | POLYGON((0 0,0 4,6 4,6 0,0 0))
input_b                | POLYGON((3 -1,3 3,8 3,8 -1,3 -1))
2 I(a) ∩ I(b)          | POLYGON((3 0,3 3,6 3,6 0,3 0))
1 I(a) ∩ B(b)          | LINESTRING(3 0,3 3,6 3)
2 I(a) ∩ E(b)          | POLYGON((0 0,0 4,6 4,6 3,3 3,3 0,0 0))
1 B(a) ∩ I(b)          | LINESTRING(3 0,6 0,6 3)
0 B(a) ∩ B(b)          | MULTIPOINT((6 3),(3 0))
1 B(a) ∩ E(b)          | MULTILINESTRING((0 0,0 4,6 4,6 3),(0 0,3 0))
2 E(a) ∩ I(b)          | POLYGON((3 -1,3 0,6 0,6 3,8 3,8 -1,3 -1))
1 E(a) ∩ B(b)          | MULTILINESTRING((3 -1,8 -1,8 3,6 3),(3 -1,3 0))
2 E(a) ∩ E(b) clipped  | POLYGON((-1 -2,-1 5,9 5,9 -2,-1 -2),(0 0,3 0,3 -1,8 -1,8 3,6 3,6 4,0 4,0 0))
Figure
Geometry figure for visual-de9im-matrix-cells

Reading from left to right and top to bottom, the intersection matrix is represented as the text string '212101212'.

For more information, refer to:

5.1.2. Named Spatial Relationships

To make it easy to determine common spatial relationships, the OGC SFS defines a set of named spatial relationship predicates. PostGIS provides these as the functions ST_Contains, ST_Crosses, ST_Disjoint, ST_Equals, ST_Intersects, ST_Overlaps, ST_Touches, ST_Within. It also defines the non-standard relationship predicates ST_Covers, ST_CoveredBy, and ST_ContainsProperly.

Spatial predicates are usually used as conditions in SQL WHERE or JOIN clauses. The named spatial predicates automatically use a spatial index if one is available, so there is no need to use the bounding box operator && as well. For example:

Code
SELECT city.name, state.name, city.geom
FROM city JOIN state ON ST_Intersects(city.geom, state.geom);

For more details and illustrations, see the PostGIS Workshop.

5.1.3. General Spatial Relationships

In some cases the named spatial relationships are insufficient to provide a desired spatial filter condition. These requirements can be expressed by computing the full DE-9IM intersection matrix with ST_Relate.

To test a particular spatial relationship, an intersection matrix pattern is used. This is the matrix representation augmented with the additional symbols {T,*}:

  • T => intersection dimension is non-empty; i.e. is in {0,1,2}

  • * => don't care

Using intersection matrix patterns, specific spatial relationships can be evaluated succinctly. The ST_Relate and ST_RelateMatch functions can both test these patterns.

These road segments share a line segment. ST_Crosses does not find this relationship for linear features, because it only returns true when their interiors intersect at a point. The pattern 1*1***1** tests for a one-dimensional intersection instead.

Code
WITH roads AS (
  SELECT
    'LINESTRING(10 10,40 90,70 110,140 110,170 130,190 190)'::geometry AS "road A",
    'LINESTRING(10 190,50 130,90 110,130 110,160 70,180 10)'::geometry AS "road B"
), relation AS (
  SELECT "road A", "road B", ST_Relate("road A", "road B") AS matrix
  FROM roads
)
SELECT
  ST_Intersection("road A", "road B") AS overlap,
  matrix,
  ST_Crosses("road A", "road B") AS "ST_Crosses",
  ST_RelateMatch(matrix, '1*1***1**') AS "matches 1*1***1**"
FROM relation;
래스터 출력
overlap           |  matrix   | ST_Crosses | matches 1*1***1**
----------------------------+-----------+------------+-------------------
 LINESTRING(90 110,130 110) | 1F1FF0102 | f          | t
(1 row)
Figure
Geometry figure for visual-relate-overlapping-roads

The next example finds a wharf which runs from the lake interior onto its shoreline, with one endpoint on the shoreline. The other wharves provide nearby counterexamples in the figure. The pattern 102101FF2 expresses the complete required relationship in one test.

Code
WITH data AS (
  SELECT
    'POLYGON((-20 10,30 30,80 70,110 80,145 85,190 110,300 220,230 220,-20 220,-20 10))'::geometry AS lake,
    'MULTILINESTRING((120 180,145 85,110 80),(10 130,30 70),(90 140,110 80,94.81118881118876 75.83496503496498),(150 160,180 80))'::geometry AS wharves
), wharf AS (
  SELECT lake, (item).path[1] AS id, (item).geom
  FROM data CROSS JOIN LATERAL ST_Dump(wharves) AS item
), relation AS (
  SELECT id, geom, ST_Relate(lake, geom) AS matrix
  FROM wharf
)
SELECT
  id AS wharf,
  geom AS "matching wharf",
  matrix
FROM relation
WHERE ST_RelateMatch(matrix, '102101FF2')
ORDER BY id;
래스터 출력
wharf |           matching wharf           |  matrix
-------+-----------------------------------+-----------
     1 | LINESTRING(120 180,145 85,110 80) | 102101FF2
(1 row)
Figure
Geometry figure for visual-relate-lake-wharves

5.2. Using Spatial Indexes

When constructing queries using spatial conditions, for best performance it is important to ensure that a spatial index is used, if one exists (see 4.9절. “인덱스 빌드 작업”). To do this, a spatial operator or index-aware function must be used in a WHERE or ON clause of the query.

Spatial operators include the bounding box operators (of which the most commonly used is &&; see 7.10.1절. “Bounding Box Operators” for the full list) and the distance operators used in nearest-neighbor queries (the most common being <->; see 7.10.2절. “연산자(operator)” for the full list.)

Index-aware functions automatically add a bounding box operator to the spatial condition. Index-aware functions include the named spatial relationship predicates ST_Contains, ST_ContainsProperly, ST_CoveredBy, ST_Covers, ST_Crosses, ST_Intersects, ST_Overlaps, ST_Touches, ST_Within, ST_Within, and ST_3DIntersects, and the distance predicates ST_DWithin, ST_DFullyWithin, ST_3DDFullyWithin, and ST_3DDWithin .)

Functions such as ST_Distance do not use indexes to optimize their operation. For example, the following query would be quite slow on a large table:

Code
SELECT geom
FROM geom_table
WHERE ST_Distance(geom, 'SRID=312;POINT(100000 200000)') < 100

This query selects all the geometries in geom_table which are within 100 units of the point (100000, 200000). It will be slow because it is calculating the distance between each point in the table and the specified point, ie. one ST_Distance() calculation is computed for every row in the table.

The number of rows processed can be reduced substantially by using the index-aware function ST_DWithin:

Code
SELECT geom
FROM geom_table
WHERE ST_DWithin(geom, 'SRID=312;POINT(100000 200000)', 100)

This query selects the same geometries, but it does it in a more efficient way. This is enabled by ST_DWithin() using the && operator internally on an expanded bounding box of the query geometry. If there is a spatial index on geom, the query planner will recognize that it can use the index to reduce the number of rows scanned before calculating the distance. The spatial index allows retrieving only records with geometries whose bounding boxes overlap the expanded extent and hence which might be within the required distance. The actual distance is then computed to confirm whether to include the record in the result set.

For more information and examples see the PostGIS Workshop.

5.3. Examples of Spatial SQL

The examples in this section make use of a table of linear roads, and a table of polygonal municipality boundaries. The definition of the bc_roads table is:

래스터 출력
Column    | Type              | Description
----------+-------------------+-------------------
gid       | integer           | Unique ID
name      | character varying | Road Name
geom      | geometry          | Location Geometry (Linestring)

The definition of the bc_municipality table is:

래스터 출력
Column   | Type              | Description
---------+-------------------+-------------------
gid      | integer           | Unique ID
code     | integer           | Unique ID
name     | character varying | City / Town Name
geom     | geometry          | Location Geometry (Polygon)

5.3.1.

What is the total length of all roads, expressed in kilometers?

You can answer this question with a very simple piece of SQL:

Code
SELECT sum(ST_Length(geom))/1000 AS km_roads FROM bc_roads;
래스터 출력
km_roads
------------------
70842.1243039643

5.3.2.

How large is the city of Prince George, in hectares?

This query combines an attribute condition (on the municipality name) with a spatial calculation (of the polygon area):

Code
SELECT
  ST_Area(geom)/10000 AS hectares
FROM bc_municipality
WHERE name = 'PRINCE GEORGE';
래스터 출력
hectares
------------------
32657.9103824927

5.3.3.

What is the largest municipality in the province, by area?

This query uses a spatial measurement as an ordering value. There are several ways of approaching this problem, but the most efficient is below:

Code
SELECT
  name,
  ST_Area(geom)/10000 AS hectares
FROM bc_municipality
ORDER BY hectares DESC
LIMIT 1;
래스터 출력
name           | hectares
---------------+-----------------
TUMBLER RIDGE  | 155020.02556131

Note that in order to answer this query we have to calculate the area of every polygon. If we were doing this a lot it would make sense to add an area column to the table that could be indexed for performance. By ordering the results in a descending direction, and them using the PostgreSQL "LIMIT" command we can easily select just the largest value without using an aggregate function like MAX().

5.3.4.

What is the length of roads fully contained within each municipality?

This is an example of a "spatial join", which brings together data from two tables (with a join) using a spatial interaction ("contained") as the join condition (rather than the usual relational approach of joining on a common key):

Code
SELECT
  m.name,
  sum(ST_Length(r.geom))/1000 as roads_km
FROM bc_roads AS r
JOIN bc_municipality AS m
  ON ST_Contains(m.geom, r.geom)
GROUP BY m.name
ORDER BY roads_km;
래스터 출력
name                        | roads_km
----------------------------+----------
SURREY                      | 1539.476
VANCOUVER                   | 1450.331
LANGLEY DISTRICT            |  833.793
BURNABY                     |  773.769
PRINCE GEORGE               |  694.376
...

This query takes a while, because every road in the table is summarized into the final result (about 250K roads for the example table). For smaller datasets (several thousand records on several hundred) the response can be very fast.

5.3.5.

Create a new table with all the roads within the city of Prince George.

This is an example of an "overlay", which takes in two tables and outputs a new table that consists of spatially clipped or cut resultants. Unlike the "spatial join" demonstrated above, this query creates new geometries. An overlay is like a turbo-charged spatial join, and is useful for more exact analysis work:

Code
CREATE TABLE pg_roads as
SELECT
  ST_Intersection(r.geom, m.geom) AS intersection_geom,
  ST_Length(r.geom) AS rd_orig_length,
  r.*
FROM bc_roads AS r
JOIN bc_municipality AS m
  ON ST_Intersects(r.geom, m.geom)
WHERE
  m.name = 'PRINCE GEORGE';

5.3.6.

What is the length in kilometers of "Douglas St" in Victoria?

Code
SELECT
  sum(ST_Length(r.geom))/1000 AS kilometers
FROM bc_roads r
JOIN bc_municipality m
  ON ST_Intersects(m.geom, r.geom
WHERE
  r.name = 'Douglas St'
  AND m.name = 'VICTORIA';
래스터 출력
kilometers
------------------
4.89151904172838

5.3.7.

What is the largest municipality polygon that has a hole?

Code
SELECT gid, name, ST_Area(geom) AS area
FROM bc_municipality
WHERE ST_NRings(geom) 
> 1
ORDER BY area DESC LIMIT 1;
래스터 출력
gid  | name         | area
-----+--------------+------------------
12   | SPALLUMCHEEN | 257374619.430216

6장. 성능 향상 비법

6.1. 대용량 도형을 담은 저용량 테이블

6.1.1. 문제점 설명

Current PostgreSQL versions suffer from a query optimizer weakness regarding TOAST tables. TOAST tables are a kind of "extension room" used to store large (in the sense of data size) values that do not fit into normal data pages (like long texts, images or complex geometries with lots of vertices), see the PostgreSQL Documentation for TOAST for more information).

상당히 대용량의 도형을 가진 테이블이지만, (전체 유럽 국가들의 고해상도 국경을 담고 있는 테이블처럼) 도형 행이 그렇게 많지 않을 경우 문제가 드러납니다. 이때 테이블 자체는 저용량이지만, 많은 TOAST 공간을 차지합니다. 이번 예제의 경우, 테이블 자체는 약 80행을 담고 있고 데이터 페이지 3장만 사용하지만, TOAST 테이블은 8,225페이지를 차지합니다.

이 테이블의 행 가운데 몇 행과만 일치하는 경계 상자를 검색하기 위한 도형 연산자 &&를 이용하는 쿼리를 전송해봅시다. 이때 쿼리 최적화기는 해당 테이블이 데이터 페이지 3장과 80행만 가지고 있다고 판단합니다. 이런 저용량 테이블에는 인덱스보다 순차 스캔이 훨씬 빠를 거라고 추정할 것입니다. 따라서 GiST 인덱스를 무시하기로 합니다. 일반적인 경우라면 이 추정이 맞습니다. 그러나 이번 예제의 경우, && 연산자가 경계 상자를 비교하기 위해 디스크에서 모든 도형을 불러와야 하기 때문에, 결국 모든 TOAST 페이지도 읽어야 합니다.

사용자 시스템에 이 버그가 있는지 확인하려면, "EXPLAIN ANALYZE" PostgreSQL 명령어를 실행하십시오. 자세한 정보 및 기술적인 세부 사항을 알고 싶다면, PostgreSQL 성능 메일링 리스트에 있는 다음 스레드를 읽어볼 수 있습니다: http://archives.postgresql.org/pgsql-performance/2005-02/msg00030.php

and newer thread on PostGIS https://lists.osgeo.org/pipermail/postgis-devel/2017-June/026209.html

6.1.2. 해결 방법

PostgreSQL 개발자들은 쿼리 추정이 TOAST를 인식하도록 만들어 이 문제를 해결하려 하고 있습니다. 현 시점에서는, 다음 두 가지 해결 방법이 있습니다:

첫 번째 해결책은 쿼리 설계자가 인덱스를 사용하도록 강제하는 방법입니다. 쿼리를 전송하기 전에 서버로 "SET enable_seqscan TO off;"를 전송하십시오. 이렇게 하면 기본적으로 쿼리 설계자가 순차 스캔을 사용할 수 있는 경우에도 사용하지 않도록 강제합니다. 따라서 평상시처럼 GiST 인덱스를 이용할 것입니다. 그러나 이 플래그를 매번 연결할 때마다 설정해야 하고 다른 상황에서 쿼리 설계자가 잘못 추정하도록 하기 때문에, 쿼리가 끝난 후에 "SET enable_seqscan TO on;"을 전송해야 합니다.

두 번째 해결책은 쿼리 설계자가 추정하는 만큼 순차 스캔 속도를 높이는 방법입니다. 경계 상자를 "캐시"하는 추가 열을 생성한 다음, 이 추가 열을 대상으로 일치 여부를 쿼리하면 됩니다. 이번 예제의 경우, 해당 명령어는 다음과 같습니다:

Code
SELECT AddGeometryColumn('myschema', 'mytable', 'bbox', '4326', 'GEOMETRY', '2');
UPDATE mytable SET bbox = ST_Envelope(ST_Force2D(geom));

이제 geom_column 대신 bbox 에 대해 && 연산자를 이용하도록 다음과 같이 사용자 쿼리를 변경하십시오:

Code
SELECT geom_column
FROM mytable
WHERE bbox && ST_SetSRID('BOX3D(0 0,1 1)'::box3d,4326);

물론, mytable의 열을 변경하거나 추가할 경우, bbox의 "일관성"을 유지해야 합니다. 일관성을 유지시키는 가장 명료한 방법은 트리거(trigger)일 것입니다. 물론 사용자 응용 프로그램을 수정해서 bbox 열의 정보를 항상 최신 상태로 유지하도록 하거나, 모든 수정 작업 후 매번 앞에서 나온 UPDATE 쿼리를 실행할 수도 있습니다.

6.2. 도형 인덱스에 대한 클러스터 작업

The PostgreSQL CLUSTER command physically reorders table rows according to an index. For a mostly read-only table whose queries frequently use the same spatial index, this can reduce I/O and improve cache locality.

PostgreSQL supports clustering on GiST indices, including indices on nullable geometry columns. To cluster a table using a geometry index:

Code
CLUSTER my_table USING my_geom_index;
래스터 출력
CLUSTER

6.3. 차원 변환 피하기

때때로 사용자 테이블에 3D 또는 4D 데이터가 있지만, 항상 2D 도형만을 출력하는 OpenGIS 준수 ST_AsText() 또는 ST_AsBinary() 함수를 통해서만 접근하는 경우가 있을 수 있습니다. 이런 경우 내부적으로 ST_Force2D() 함수를 호출하는데, 대용량 도형의 경우 이 함수는 시스템의 자원을 상당히 잡아먹습니다. 이런 자원 낭비를 피하려면, 미리 그 추가적인 차원을 완전히 삭제하는 편이 효율적일 수 있습니다.

Code
UPDATE mytable SET geom = ST_Force2D(geom);
VACUUM FULL ANALYZE mytable;

AddGeometryColumn() 함수를 통해 사용자 도형 열을 추가했을 경우 도형 차원에 제약조건이 걸려 있다는 사실을 주의하십시오. 이를 우회하려면 제약조건을 삭제해야 합니다. geometry_columns 테이블 내부 항목을 업데이트한 다음 제약조건을 다시 생성하는 걸 잊지 마십시오.

대용량 테이블의 경우, 사용자의 기본 키 또는 또다른 사용 가능한 기준과 함께 WHERE 절을 이용해서 테이블의 일부분만 업데이트하도록 제한한 다음 업데이트마다 간단히 "VACUUM;"을 실행하는 방식으로 이 업데이트를 작은 부분으로 나누는 편이 좋을 수 있습니다. 이렇게 하면 필요한 임시 디스크 공간이 급격히 줄어듭니다. 또한 몇 종류의 차원이 섞인 도형들을 가지고 있을 경우, "WHERE dimension(the_geom)>2"로 업데이트를 제한하면 이미 2D인 도형을 다시 작성하는 일을 건너뛸 수 있습니다.

7장. PostGIS Reference

아래의 함수들은 PostGIS 사용자가 필요로 하는 함수들이며, 일반 사용자가 쓰지 않는 PostGIS 객체에 필요한 다른 지원 함수들도 있습니다.

[참고]

PostGIS는 기존 명명 규칙에서 SQL-MM-중심 명명 규칙으로 전환하기 시작했습니다. 그 결과로, 여러분이 알고 있고 좋아하는 대부분의 함수 이름이 표준 Spatial Type (ST) 접두어를 사용한 이름으로 변경되었습니다. 갱신된 함수들이 이전 함수들과 같은 기능을 제공하며, 비록 이 문서에는 나열되어 있지는 않지만 이전 함수도 사용할 수 있습니다. 다음 버전 출시에는 이 문서에 없는 비 ST_ 함수들이 더 이상 사용되지 않을 것이며 제외될 예정이므로 이들 함수의 사용을 중단해 주십시오.

7.1. PostgreSQL PostGIS Geometry/Geography/Box 유형

초록

이 섹션에서는 PostGIS에 의해 설치된 PostgreSQL의 데이터 유형을 나열합니다. 다음은 우리가 자신의 함수를 설계할 때 특히 중요한 이들의 캐스팅 동작을 설명합니다.

Each data type describes its type casting behavior. A type cast converts values of one data type into another type. PostgreSQL allows defining casting behavior for custom types, along with the functions used to convert type values. Casts can have automatic behavior, which allows automatic conversion of a function argument to a type supported by the function.

Some casts have explicit behavior, which means the cast must be specified using the syntax CAST(myval As sometype) or myval::sometype. Explicit casting avoids the issue of ambiguous casts, which can occur when using an overloaded function which does not support a given type. For example, a function may accept a box2d or a box3d, but not a geometry. Since geometry has an automatic cast to both box types, this produces an "ambiguous function" error. To prevent the error use an explicit cast to the desired box type.

All data types can be cast to text, so this does not need to be specified explicitly.

  • box2d — The type representing a 2-dimensional bounding box.
  • box3d — The type representing a 3-dimensional bounding box.
  • geometry — geography는 지구곡면 좌표계에서 피처를 표현하는데 사용되는 공간 데이터 타입입니다.
  • geometry_dump — A composite type used to describe the parts of complex geometry.
  • geography — The type representing spatial features with geodetic (ellipsoidal) coordinate systems.

제목

box2d — The type representing a 2-dimensional bounding box.

설명

box3d 지오메트리 또는 지오메트리 셋의 범위를 표현하는데 사용되는 postgis 공간 데이터 타입입니다. ST_3DExtent는 box3d 객체를 반환합니다.

The representation contains the values xmin, ymin, xmax, ymax. These are the minimum and maximum values of the X and Y extents.

box2d objects have a text representation which looks like BOX(1 2,5 6).

형변환 습성

이 섹션에는 자동 형변환 뿐만 아니라 이 데이터 유형에 허용되는 명시적 캐스팅이 나열됩니다.

형변환 결과습성
box3d자동적
geometry자동적

제목

box3d — The type representing a 3-dimensional bounding box.

설명

box3d 지오메트리 또는 지오메트리 셋의 범위를 표현하는데 사용되는 postgis 공간 데이터 타입입니다. ST_3DExtent는 box3d 객체를 반환합니다.

The representation contains the values xmin, ymin, zmin, xmax, ymax, zmax. These are the minimum and maximum values of the X, Y and Z extents.

box3d objects have a text representation which looks like BOX3D(1 2 3,5 6 5).

형변환 습성

이 섹션에는 자동 형변환 뿐만 아니라 이 데이터 유형에 허용되는 명시적 캐스팅이 나열됩니다.

형변환 결과습성
box자동적
box2d자동적
geometry자동적

제목

geometry — geography는 지구곡면 좌표계에서 피처를 표현하는데 사용되는 공간 데이터 타입입니다.

설명

geography는 지구곡면 좌표계에서 피처를 표현하는데 사용되는 공간 데이터 타입입니다.

All spatial operations on geometry use the units of the Spatial Reference System the geometry is in.

형변환 습성

이 섹션에는 자동 형변환 뿐만 아니라 이 데이터 유형에 허용되는 명시적 캐스팅이 나열됩니다.

형변환 결과습성
box자동적
box2d자동적
box3d자동적
bytea자동적
geography자동적
text자동적

제목

geometry_dump — A composite type used to describe the parts of complex geometry.

설명

geometry_dump is a composite data type containing the fields:

  • geom - a geometry representing a component of the dumped geometry. The geometry type depends on the originating function.

  • path[] - an integer array that defines the navigation path within the dumped geometry to the geom component. The path array is 1-based (i.e. path[1] is the first element.)

It is used by the ST_Dump* family of functions as an output type to explode a complex geometry into its constituent parts.


제목

geography — The type representing spatial features with geodetic (ellipsoidal) coordinate systems.

설명

geography는 지구곡면 좌표계에서 피처를 표현하는데 사용되는 공간 데이터 타입입니다.

Spatial operations on the geography type provide more accurate results by taking the ellipsoidal model into account.

형변환 습성

이 섹션에는 자동 형변환 뿐만 아니라 이 데이터 유형에 허용되는 명시적 캐스팅이 나열됩니다.

형변환 결과습성
geometry명시적

7.2. 관리 함수

초록

These functions assist in defining tables containing geometry columns.

  • AddGeometryColumn — 공간 테이블에서 지오메트리 컬럼을 제거합니다.
  • DropGeometryColumn — 공간 테이블에서 지오메트리 컬럼을 제거합니다.
  • DropGeometryTable — 테이블 및 geometry_columns의 모든 참조를 삭제합니다.
  • Find_SRID — Returns the SRID defined for a geometry column.
  • Populate_Geometry_Columns — Ensures geometry columns are defined with type modifiers or have appropriate spatial constraints.
  • UpdateGeometrySRID — Updates the SRID of all features in a geometry column, and the table metadata.

제목

AddGeometryColumn — 공간 테이블에서 지오메트리 컬럼을 제거합니다.

요약

text AddGeometryColumn(varchar table_name, varchar column_name, integer srid, varchar type, integer dimension, boolean use_typmod=true);

text AddGeometryColumn(varchar schema_name, varchar table_name, varchar column_name, integer srid, varchar type, integer dimension, boolean use_typmod=true);

text AddGeometryColumn(varchar catalog_name, varchar schema_name, varchar table_name, varchar column_name, integer srid, varchar type, integer dimension, boolean use_typmod=true);

설명

기존 테이블의 속성으로 지오메트리 컬럼을 추가합니다. schema_name은 테이블 스키마의 이름입니다. srid은 정수값 이어야 하며 SPATIAL_REF_SYS 테이블의 요소를 참조합니다. type은 지오메트리 타입과 일티하는 문자열, 예를 들어 'POLYGON' 이나 'MULTILINESTRING' 이어야 합니다. 스키마 이름이 없거나 (혹은 현재 search_path에 안버이거나) 지정된 SRID, 지오메트리 타입, 차원 등이 잘못된 경우 오류가 발생됩니다.

변경사항: 2.0.0 이 함수는 geometry_columns이 시스템 카테고리에서 읽히는 뷰인 동안 더 이상 geometry_columns을 업데이트 하지 않습니다. 이것은 기본적으로 컨스트레인트를 만들지 않지만, 대신에 PostgreSQL의 내장된 타입 변경 동작이 대신합니다. 그래서 예를 들어 WGS84 POINT 컬럼을 이 함수로 만든다면 이 함수는 다음과 동등합니다: ALTER TABLE some_table ADD COLUMN geom geometry(Point,4326);

변경 사항: 2.0.0 버전. 제약조건의 구식 습성이 필요할 경우, 기본값인 use_typmod 를 이용하되, 거짓으로 설정하십시오.

변경 사항: 2.0.0 버전. 더 이상 뷰를 직접 geometry_columns에 등록시킬 수는 없지만, 도형 typmod 테이블 도형을 기반으로 빌드된 , 그리고 래퍼 함수 없이 사용되는 뷰는 자신의 페어런트 테이블 열의 typmod 습성을 상속하기 때문에 스스로를 정확히 등록시킵니다. 이런 뷰 도형 열을 geometry_columns에 정확히 등록시키려면, 다른 도형을 출력하는 도형 함수를 이용하는 뷰를 typmod 도형으로 형변환시켜야 할 것입니다. 4.6.3절. “geometry_columns에 도형 열을 직접 등록하기” 을 참조하십시오.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

개선 사항: 2.0.0 버전. use_typmod 인자가 추가됐습니다. 제약조건 기반 도형 열 대신 기본적으로 typmod 도형 열을 생성합니다.

예시

This example creates a schema to hold data.

Code
CREATE SCHEMA my_schema;

Create a simple PostgreSQL table in the schema.

Code
CREATE TABLE my_schema.my_spatial_table (id serial);

Describing the table shows a single id column.

Code
\d my_schema.my_spatial_table
래스터 출력
Table "my_schema.my_spatial_table"
 Column |  Type   |                                Modifiers
--------+---------+-------------------------------------------------------------------------
 id     | integer | not null default nextval('my_schema.my_spatial_table_id_seq'::regclass)

Add a spatial column to the table.

Code
SELECT AddGeometryColumn('my_schema', 'my_spatial_table', 'geom', 4326, 'POINT', 2);

Add a point column using the old constraint-based behavior.

Code
SELECT AddGeometryColumn('my_schema', 'my_spatial_table', 'geom_c', 4326, 'POINT', 2, false);

Add a CurvePolygon column using the old constraint-based behavior.

Code
SELECT AddGeometryColumn('my_schema', 'my_spatial_table', 'geomcp_c', 4326, 'CURVEPOLYGON', 2, false);
래스터 출력
my_schema.my_spatial_table.geomcp_c SRID:4326 TYPE:CURVEPOLYGON DIMS:2

Describe the table again to see the new geometry columns.

Code
\d my_schema.my_spatial_table
래스터 출력
Table "my_schema.my_spatial_table"

Columns:
  id       integer               not null default nextval('my_schema.my_spatial_table_id_seq'::regclass)
  geom     geometry(Point,4326)
  geom_c   geometry
  geomcp_c geometry

Check constraints:
    "enforce_dims_geom_c" CHECK (st_ndims(geom_c) = 2)
    "enforce_dims_geomcp_c" CHECK (st_ndims(geomcp_c) = 2)
    "enforce_geotype_geom_c" CHECK (geometrytype(geom_c) = 'POINT'::text OR geom_c IS NULL)
    "enforce_geotype_geomcp_c" CHECK (geometrytype(geomcp_c) = 'CURVEPOLYGON'::text OR geomcp_c IS NULL)
    "enforce_srid_geom_c" CHECK (st_srid(geom_c) = 4326)
    "enforce_srid_geomcp_c" CHECK (st_srid(geomcp_c) = 4326)

The geometry_columns view also registers the new columns.

Code
SELECT f_geometry_column As col_name, type, srid, coord_dimension As ndims
FROM geometry_columns
WHERE f_table_name = 'my_spatial_table' AND f_table_schema = 'my_schema';
래스터 출력
col_name |     type     | srid | ndims
----------+--------------+------+-------
 geom     | Point        | 4326 |     2
 geom_c   | Point        | 4326 |     2
 geomcp_c | CurvePolygon | 4326 |     2

제목

DropGeometryColumn — 공간 테이블에서 지오메트리 컬럼을 제거합니다.

요약

text DropGeometryColumn(varchar table_name, varchar column_name);

text DropGeometryColumn(varchar schema_name, varchar table_name, varchar column_name);

text DropGeometryColumn(varchar catalog_name, varchar schema_name, varchar table_name, varchar column_name);

설명

공간 테이블에서 도형 열을 제거합니다. schema_name이 geometry_columns 테이블에 있는 테이블 행의 f_table_schema 항목과 일치해야 한다는 점에 주의하십시오.

[주의]

DropGeometryColumn is retained for backward compatibility and is not recommended for new applications. Use the standard ALTER TABLE ... DROP COLUMN command instead. The geometry_columns view updates automatically from the system catalogs.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

Changed: 2.0.0. Retained for backward compatibility after geometry_columns became a view of the system catalogs.

예시

Use standard SQL to drop the geometry column. The geometry_columns view updates automatically.

Code
ALTER TABLE my_schema.my_spatial_table DROP COLUMN geom;

The legacy compatibility function performs the equivalent operation.

Code
SELECT DropGeometryColumn ('my_schema', 'my_spatial_table', 'geom');
래스터 출력
my_schema.my_spatial_table.geom effectively removed.

제목

DropGeometryTable — 테이블 및 geometry_columns의 모든 참조를 삭제합니다.

요약

boolean DropGeometryTable(varchar table_name);

boolean DropGeometryTable(varchar schema_name, varchar table_name);

boolean DropGeometryTable(varchar catalog_name, varchar schema_name, varchar table_name);

설명

테이블 및 geometry_columns에 있는 테이블의 모든 참조를 삭제합니다. 주의: 스키마를 제공하지 않는다면 스키마를 인식하는(schema-aware) pgSQL 설치 상에서 current_schema()를 사용해보십시오.

[주의]

DropGeometryTable is retained for backward compatibility and is not recommended for new applications. Use the standard DROP TABLE command instead. The geometry_columns view updates automatically from the system catalogs.

Changed: 2.0.0. Retained for backward compatibility after geometry_columns became a view of the system catalogs.

예시

Use standard SQL to drop a table containing geometry columns. The geometry_columns view updates automatically.

Code
DROP TABLE my_schema.my_spatial_table;

The legacy compatibility function performs the equivalent operation.

Code
SELECT DropGeometryTable ('my_schema', 'my_spatial_table');
래스터 출력
my_schema.my_spatial_table dropped.

제목

Find_SRID — Returns the SRID defined for a geometry column.

요약

integer Find_SRID(varchar a_schema_name, varchar a_table_name, varchar a_geomfield_name);

설명

Returns the integer SRID of the specified geometry column by searching through the GEOMETRY_COLUMNS table. If the geometry column has not been properly added (e.g. with the AddGeometryColumn function), this function will not work.

예시

Code
SELECT Find_SRID('public', 'tiger_us_state_2007', 'geom_4269');
래스터 출력
4269

참고

ST_SRID


제목

Populate_Geometry_Columns — Ensures geometry columns are defined with type modifiers or have appropriate spatial constraints.

요약

text Populate_Geometry_Columns(boolean use_typmod=true);

int Populate_Geometry_Columns(oid relation_oid, boolean use_typmod=true);

설명

지오메트리 컬럼이 타입 변경자로 정의되거나 적절한 공간 제약을 가지고 있는지 확인합니다. 이 함수는 공간 관련 테이블들이 geometry_columns 뷰에 올바르게 등록되도록 합니다. 기본적으로 유형 변경자를 가지지 않는 모든 지오메트리 컬럼들을 유형 변경자를 가진 지오메트리 컬럼들로 변환시킵니다. 엣날식 동작을 원하면 use_typmod=false으로 설정

하위 호환성 및 각 차일드 테이블이 서로 다른 도형 유형을 가질 수도 있는 테이블 상속 같은 공간 필요성을 위해, 구 버전 확인 제약조건 습성을 계속 지원합니다. 구 버전 습성이 필요하다면, use_typmod=false 처럼 새 선택적 인자를 거짓으로 패스해야 합니다. 이렇게 하면 유형 변경자는 없지만 제약조건 3개가 정의된 도형 열을 생성할 것입니다. 다시 말해, 모든 도형 열이 적어도 3개의 제약조건을 가진 테이블에 종속된다는 뜻입니다:

  • enforce_dims_the_geom - ensures every geometry has the same dimension (see ST_NDims)

  • enforce_geotype_the_geom - ensures every geometry is of the same type (see GeometryType)

  • enforce_srid_the_geom - ensures every geometry is in the same projection (see ST_SRID)

oid 테이블이 제공될 경우, 이 함수는 테이블에 있는 모든 도형 열의 SRID, 차원, 그리고 도형 유형을 결정하려 하며, 필요한 경우 제약조건을 추가하기도 합니다. 함수가 제대로 작동했다면, 올바른 행이 geometry_columns 테이블에 삽입됩니다. 아닐 경우, 예외가 잡혀 문제점을 설명하는 오류 메시지가 뜹니다.

oid 테이블과 함께 oid 뷰가 제공될 경우, 이 함수는 geometry_columns 테이블에 올바른 항목을 삽입하며 뷰에 있는 모든 도형의 SRID, 차원, 유형을 결정하려 하지만, 제약조건을 강제하지는 않습니다.

이 함수의 파라미터가 없는 변종은, 공간 제약조건을 테이블의 적절한 곳에 추가하며 먼저 데이터베이스 내부의 모든 공간 테이블 및 뷰에 대해 geometry_columns 테이블의 용량을 줄이고(truncate) 다시 채우는 파라미터가 있는 변종을 위한 단순 래퍼입니다. 파라미터가 없는 변종은 데이터베이스 내부에서 감지된 도형 열의 개수 및 geometry_columns 테이블로 삽입된 개수를 요약해서 반환합니다. 파라미터가 있는 버전은 단순히 geometry_columns 테이블로 삽입된 행의 개수를 반환합니다.

1.4.0 버전부터 사용할 수 있습니다.

변경 사항: 2.0.0 버전. 이제 도형 유형을 제한하기 위해 확인 제약조건 대신 유형 변경자를 이용합니다. 새 use_typmod 를 거짓으로 설정하면, 확인 제약조건 습성을 계속 쓸 수 있습니다.

개선 사항: 2.0.0 버전. 열 생성시 유형 변경자와 함께, 또는 확인 제약조건과 함께 생성할지 통제할 수 있는 use_typmod 의 선택적 인자가 추가됐습니다.

예시

This example populates geometry column metadata using typmod behavior. For this to work, there must be existing data.

Code
CREATE TABLE public.myspatial_table(gid serial, geom geometry);
INSERT INTO myspatial_table(geom) VALUES(ST_GeomFromText('LINESTRING(1 2,3 4)', 4326) );
SELECT Populate_Geometry_Columns('public.myspatial_table'::regclass);
래스터 출력
1

Describe the table to see the typmod-based geometry column.

Code
\d myspatial_table
래스터 출력
Table "public.myspatial_table"

Columns:
  gid  integer                    not null default nextval('myspatial_table_gid_seq'::regclass)
  geom geometry(LineString,4326)

This example changes the geometry columns to use constraints if they are not typmod or already constrained. For this to work, there must be existing data.

Code
CREATE TABLE public.myspatial_table_cs(gid serial, geom geometry);
INSERT INTO myspatial_table_cs(geom) VALUES(ST_GeomFromText('LINESTRING(1 2,3 4)', 4326) );
SELECT Populate_Geometry_Columns('public.myspatial_table_cs'::regclass, false);
래스터 출력
1

Describe the table to see the constraint-based geometry column.

Code
\d myspatial_table_cs
래스터 출력
Table "public.myspatial_table_cs"
 Column |   Type   |                            Modifiers
--------+----------+------------------------------------------------------------------
 gid    | integer  | not null default nextval('myspatial_table_cs_gid_seq'::regclass)
 geom   | geometry |
Check constraints:
    "enforce_dims_geom" CHECK (st_ndims(geom) = 2)
    "enforce_geotype_geom" CHECK (geometrytype(geom) = 'LINESTRING'::text OR geom IS NULL)
    "enforce_srid_geom" CHECK (st_srid(geom) = 4326)

제목

UpdateGeometrySRID — Updates the SRID of all features in a geometry column, and the table metadata.

요약

text UpdateGeometrySRID(varchar table_name, varchar column_name, integer srid);

text UpdateGeometrySRID(varchar schema_name, varchar table_name, varchar column_name, integer srid);

text UpdateGeometrySRID(varchar catalog_name, varchar schema_name, varchar table_name, varchar column_name, integer srid);

설명

지오메트리 컬럼, geometry_columns 메타데이터 및 srid를 대상으로 모든 피처들의 SRID를 갱신합니다. 주의: 만약 스키마가 지원되지 않으면 schema-aware pgsql installations 설치본에서 current_schema() 사용

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

예시

Insert geometries into roads table with a SRID set already using EWKT format:

Code
COPY roads (geom) FROM STDIN;
SRID=4326;LINESTRING(0 0, 10 10)
SRID=4326;LINESTRING(10 10, 15 0)
\.
        

다음은 도로 테이블의 이전 SRID와 상관없이 SRID를 4326으로 변경할 것입니다:

Code
SELECT UpdateGeometrySRID('roads', 'geom', 4326);

앞의 예시는 다음 DDL 선언문과 동일합니다:

Code
ALTER TABLE roads
ALTER COLUMN geom TYPE geometry(MULTILINESTRING, 4326)
  USING ST_SetSRID(geom, 4326);

로드 작업 중 투영체를 잘못 (또는 'unknown'으로) 적용했는데 모든 데이터를 한번에 웹 메르카토르로 변환하고 싶다면, DDL을 통해 가능합니다. 하지만 PostGIS 관리 함수 가운데 한번에 이런 작업을 할 수 있는 동일한 함수는 없습니다.

Code
ALTER TABLE roads
ALTER COLUMN geom TYPE geometry(MULTILINESTRING, 3857) USING ST_Transform(ST_SetSRID(geom, 4326), 3857) ;

7.3. 도형 작성자(constructor)

초록

These functions instantiate new geometry or geography values. They assemble primitives, coordinate sequences, or existing geometries into well-formed spatial objects that can participate in subsequent analysis.

  • ST_Collect — Creates a GeometryCollection or Multi* geometry from a set of geometries.
  • ST_LineFromMultiPoint — 멀티포인트 도형으로부터 라인스트링을 생성합니다.
  • ST_MakeEnvelope — 주어진 최소값과 최대값으로 형성된 직사각형 폴리곤을 생성합니다. 입력값이 SRID로 지정된 SRS를 가지고 있어야 합니다.
  • ST_MakeLine — 포인트, 멀티포인트 또는 라인 도형으로부터 라인스트링을 생성합니다.
  • ST_MakePoint — Creates a 2D, 3DZ or 4D Point.
  • ST_MakePointM — x, y 좌표 및 단위를 가진 포인트를 생성합니다.
  • ST_MakePolygon — Creates a Polygon or CurvePolygon from a shell and optional list of holes.
  • ST_Point — Creates a Point with X, Y and SRID values.
  • ST_PointZ — Creates a Point with X, Y, Z and SRID values.
  • ST_PointM — Creates a Point with X, Y, M and SRID values.
  • ST_PointZM — Creates a Point with X, Y, Z, M and SRID values.
  • ST_Polygon — Creates a Polygon from a LineString with a specified SRID.
  • ST_TileEnvelope — Creates a rectangular Polygon in Web Mercator (SRID:3857) using the XYZ tile system.
  • ST_HexagonGrid — Returns a set of hexagons and cell indices that completely cover the bounds of the geometry argument.
  • ST_Hexagon — Returns a single hexagon, using the provided edge size and cell coordinate within the hexagon grid space.
  • ST_SquareGrid — Returns a set of grid squares and cell indices that completely cover the bounds of the geometry argument.
  • ST_Square — Returns a single square, using the provided edge size and cell coordinate within the square grid space.
  • ST_Letters — Returns the input letters rendered as geometry with a default start position at the origin and default text height of 100.
  • ST_MakeNurbsCurve — Creates a NURBS (Non-Uniform Rational B-Spline) curve from control points, optional weights, and optional knot vector.

제목

ST_Collect — Creates a GeometryCollection or Multi* geometry from a set of geometries.

요약

geometry ST_Collect(geometry g1, geometry g2);

geometry ST_Collect(geometry[] g1_array);

geometry ST_Collect(geometry set g1field);

설명

Collects geometries into a geometry collection. The result is either a Multi* or a GeometryCollection, depending on whether the input geometries have the same or different types (homogeneous or heterogeneous). The input geometries are left unchanged within the collection.

Variant 1: accepts two input geometries

Variant 2: accepts an array of geometries

Variant 3: aggregate function accepting a rowset of geometries.

[주의]

ST_Collect does not dissolve boundaries or resolve overlaps. Collecting overlapping polygons can produce an invalid MultiPolygon. If the result must be a valid polygonal geometry with overlaps merged, use ST_Union instead. ST_Union also splits linestrings at intersections and may return a single geometry after dissolving boundaries.

If any input geometry is a collection (Multi* or GeometryCollection), ST_Collect returns a GeometryCollection, since that is the only type which can contain nested collections. To prevent this, use ST_Dump in a subquery to expand input collections to their atomic elements (see example below).

1.4.0 버전부터 사용할 수 있습니다. 이 버전부터 ST_MakeLine가 도형 배열을 입력받을 수 있습니다. 더 많은 포인트를 더 빨리 처리하기 위해 ST_MakeLine 합산 함수를 개선했습니다.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

예시

Two-input variant.

Collect 2D points.

Code
SELECT ST_Collect(
    'POINT(1 2)',
    'POINT(-2 3)' );
래스터 출력
MULTIPOINT((1 2),(-2 3))
Figure
Geometry figure for visual-st-collect-01

Collect 3D points.

Code
SELECT ST_Collect(
        'POINT(1 2 3)',
        'POINT(1 2 4)' );
래스터 출력
MULTIPOINT(1 2 3,1 2 4)
Figure
Geometry figure for visual-st-collect-02

Collect curves.

Code
SELECT ST_Collect(
        'CIRCULARSTRING(220268 150415,220227 150505,220227 150406)',
        'CIRCULARSTRING(220227 150406,2220227 150407,220227 150406)');
래스터 출력
MULTICURVE(CIRCULARSTRING(220268 150415,220227 150505,220227 150406),
CIRCULARSTRING(220227 150406,2220227 150407,220227 150406))
Figure
Geometry figure for visual-st-collect-03

Array variant.

Using an array constructor for a subquery.

Code
SELECT ST_Collect(ARRAY(SELECT geom FROM sometable));

Using an array constructor for values.

Code
SELECT ST_Collect(
        ARRAY[ 'LINESTRING(1 2,3 4)'::geometry,
            'LINESTRING(3 4,4 5)'::geometry ] ) As wktcollect;
래스터 출력
MULTILINESTRING((1 2,3 4),(3 4,4 5))
Figure
Geometry figure for visual-st-collect-04

Aggregate variant.

Creating multiple collections by grouping geometries in a table.

Code
SELECT stusps, ST_Collect(geom) AS geom
FROM (
  SELECT stusps, (ST_Dump(geom)).geom AS geom
  FROM somestatetable
) AS f
GROUP BY stusps;

제목

ST_LineFromMultiPoint — 멀티포인트 도형으로부터 라인스트링을 생성합니다.

요약

geometry ST_LineFromMultiPoint(geometry aMultiPoint);

설명

멀티포인트 도형으로부터 라인스트링을 생성합니다.

Use ST_MakeLine to create lines from Point or LineString inputs.

This function supports 3d and will not drop the z-index.

예시

멀티포인트 도형으로부터 라인스트링을 생성합니다.

Code
SELECT ST_LineFromMultiPoint('MULTIPOINT(1 2 3,4 5 6,7 8 9)');
래스터 출력
LINESTRING(1 2 3,4 5 6,7 8 9)
Figure
Geometry figure for visual-st-linefrommultipoint-01

제목

ST_MakeEnvelope — 주어진 최소값과 최대값으로 형성된 직사각형 폴리곤을 생성합니다. 입력값이 SRID로 지정된 SRS를 가지고 있어야 합니다.

요약

geometry ST_MakeEnvelope(float xmin, float ymin, float xmax, float ymax, integer srid=unknown);

설명

최소값과 최대값으로 형성된 직사각형 폴리곤을 생성합니다. 입력값이 SRID로 지정된 SRS를 가지고 있어야 합니다. 지정된 SRID가 없을 경우 알려지지 않은 공간 참조 시스템을 쓴다고 가정합니다.

1.5 버전부터 사용할 수 있습니다.

개선 사항: 2.0 버전부터 SRID를 지정하지 않고도 직사각형(envelope)을 설정할 수 있는 기능이 추가됐습니다.

예시

Building a bounding box polygon.

Code
SELECT ST_MakeEnvelope(10, 10, 11, 11, 4326);
래스터 출력
POLYGON((10 10, 10 11, 11 11, 11 10, 10 10))
Figure
Geometry figure for visual-st-makeenvelope-01

제목

ST_MakeLine — 포인트, 멀티포인트 또는 라인 도형으로부터 라인스트링을 생성합니다.

요약

geometry ST_MakeLine(geometry geom1, geometry geom2);

geometry ST_MakeLine(geometry[] geoms_array);

geometry ST_MakeLine(geometry set geoms);

설명

Creates a LineString containing the points of Point, MultiPoint, or LineString geometries. Other geometry types cause an error.

Variant 1: accepts two input geometries

Variant 2: accepts an array of geometries

Variant 3: aggregate function accepting a rowset of geometries. To ensure the order of the input geometries use ORDER BY in the function call, or a subquery with an ORDER BY clause.

Repeated nodes at the beginning of input LineStrings are collapsed to a single point. Repeated points in Point and MultiPoint inputs are not collapsed. Components of MultiLineString are handled in the order they appear in the collection. ST_RemoveRepeatedPoints can be used to collapse repeated points from the output LineString.

This function supports 3d and will not drop the z-index.

Availability: 3.7.0 - Support for MultiLineString input elements was introduced

2.0.0 버전부터 라인스트링 구성 요소 입력을 지원하기 시작했습니다.

2.0.0 버전부터 라인스트링 구성 요소 입력을 지원하기 시작했습니다.

1.4.0 버전부터 사용할 수 있습니다. 이 버전부터 ST_MakeLine가 도형 배열을 입력받을 수 있습니다. 더 많은 포인트를 더 빨리 처리하기 위해 ST_MakeLine 합산 함수를 개선했습니다.

예시

Two-input variant.

Create a line composed of two points.

Code
SELECT ST_MakeLine(ST_Point(1, 2), ST_Point(3, 4));
래스터 출력
LINESTRING(1 2,3 4)
Figure
Geometry figure for visual-st-makeline-01

주어진 3D 포인트 도형 2개로 정의되는 BOX3D를 생성합니다.

Code
SELECT ST_MakeLine(ST_MakePoint(1, 2, 3), ST_MakePoint(3, 4, 5));
래스터 출력
LINESTRING(1 2 3,3 4 5)
Figure
Geometry figure for visual-st-makeline-02

포인트, 멀티포인트 또는 라인 도형으로부터 라인스트링을 생성합니다.

Code
SELECT ST_MakeLine('LINESTRING(0 0,1 1)', 'LINESTRING(2 2,3 3)');
래스터 출력
LINESTRING(0 0,1 1,2 2,3 3)
Figure
Geometry figure for visual-st-makeline-03

Array variant.

Create a line from an array formed by a subquery with ordering.

Code
SELECT ST_MakeLine(ARRAY(SELECT ST_Centroid(geom) FROM visit_locations ORDER BY visit_time));

Create a 3D line from an array of 3D points

Code
SELECT ST_MakeLine(ARRAY[ST_MakePoint(1, 2, 3), ST_MakePoint(3, 4, 5), ST_MakePoint(6, 6, 6)]);
래스터 출력
LINESTRING(1 2 3,3 4 5,6 6 6)
Figure
Geometry figure for visual-st-makeline-04

Aggregate variant.

이 예시는 GPS 포인트 배열을 입력받아, 도형 항목이 이동 순서대로의 GPS 포인트들로 이루어진 라인스트링인 GPS 이동 하나당 한 개의 레코드를 생성합니다.

Using aggregate ORDER BY provides a correctly-ordered LineString.

Code
SELECT gps.track_id, ST_MakeLine(gps.geom ORDER BY gps_time) AS geom
FROM gps_points AS gps
GROUP BY gps.track_id;

When ordering within the aggregate is not possible, ordering in a subquery can be used. However, sometimes the query plan may not respect the order of the subquery.

Code
SELECT gps.track_id, ST_MakeLine(gps.geom) AS geom
FROM (
  SELECT track_id, gps_time, geom
  FROM gps_points
  ORDER BY track_id, gps_time
) AS gps
GROUP BY gps.track_id;

제목

ST_MakePoint — Creates a 2D, 3DZ or 4D Point.

요약

geometry ST_MakePoint(float x, float y);

geometry ST_MakePoint(float x, float y, float z);

geometry ST_MakePoint(float x, float y, float z, float m);

설명

Creates a 2D XY, 3D XYZ or 4D XYZM Point geometry. Use ST_MakePointM to make points with XYM coordinates.

Use ST_SetSRID to specify a SRID for the created point.

While not OGC-compliant, ST_MakePoint is faster than ST_GeomFromText and ST_PointFromText. It is also easier to use for numeric coordinate values.

[참고]

For geodetic coordinates, X is longitude and Y is latitude

[참고]

The functions ST_Point, ST_PointZ, ST_PointM, and ST_PointZM can be used to create points with a given SRID.

This function supports 3d and will not drop the z-index.

예시

This example creates a point with an unknown SRID.

Code
SELECT ST_MakePoint(-71.1043443253471, 42.3150676015829);

This example creates a point in the WGS 84 geodetic CRS.

Code
SELECT ST_SetSRID(ST_MakePoint(-71.1043443253471, 42.3150676015829), 4326);

This example creates a 3D point with altitude.

Code
SELECT ST_MakePoint(1, 2, 1.5);

This example returns the Z coordinate of a point.

Code
SELECT ST_Z(ST_MakePoint(1, 2, 1.5));
래스터 출력
1.5

제목

ST_MakePointM — x, y 좌표 및 단위를 가진 포인트를 생성합니다.

요약

geometry ST_MakePointM(float x, float y, float m);

설명

Creates a point with X, Y and M (measure) ordinates. Use ST_MakePoint to make points with XY, XYZ, or XYZM coordinates.

Use ST_SetSRID to specify a SRID for the created point.

[참고]

For geodetic coordinates, X is longitude and Y is latitude

[참고]

The functions ST_PointM, and ST_PointZM can be used to create points with an M value and a given SRID.

예시

[참고]

ST_AsEWKT is used for text output because ST_AsText does not support M values.

Create point with unknown SRID.

Code
SELECT ST_MakePointM(-71.1043443253471, 42.3150676015829, 10);
래스터 출력
POINTM(-71.1043443253471 42.3150676015829 10)
Figure
Geometry figure for visual-st-makepointm-01

x, y 좌표 및 단위를 가진 포인트를 생성합니다.

Code
SELECT ST_SetSRID(ST_MakePointM(-71.104, 42.315, 10), 4326);
래스터 출력
SRID=4326;POINTM(-71.104 42.315 10)
Figure
Geometry figure for visual-st-makepointm-02

Get measure of created point.

Code
SELECT ST_M(ST_MakePointM(-71.104, 42.315, 10));
래스터 출력
10

제목

ST_MakePolygon — Creates a Polygon or CurvePolygon from a shell and optional list of holes.

요약

geometry ST_MakePolygon(geometry linestring);

geometry ST_MakePolygon(geometry outerlinestring, geometry[] interiorlinestrings);

설명

Creates a Polygon or CurvePolygon formed by the given shell and optional array of holes. Input geometries must be closed LineStrings, CircularStrings, CompoundCurves, or NURBSCurves (rings). If any input ring is curved, the result is a CurvePolygon.

Variant 1: Accepts one shell ring.

Variant 2: Accepts a shell ring and an array of inner (hole) rings. A geometry array can be constructed using the PostgreSQL array_agg(), ARRAY[] or ARRAY() constructs.

[참고]

이 함수에 멀티라인스트링을 입력할 수는 없습니다. 라인스트링을 생성하려면 ST_LineMerge 또는 ST_Dump 를 이용하십시오.

This function supports 3d and will not drop the z-index.

Enhanced: 3.7.0 - Support for curved input rings was introduced.

예시

Single input variant.

인코딩된 폴리라인 스트링으로부터 라인스트링을 생성합니다.

Code
SELECT ST_MakePolygon('LINESTRING(75 29,77 29,77 29,75 29)');

Create a Polygon from an open LineString, using ST_StartPoint and ST_AddPoint to close it.

Code
SELECT ST_MakePolygon(ST_AddPoint(foo.open_line, ST_StartPoint(foo.open_line)) )
FROM (
  SELECT 'LINESTRING(75 29,77 29,77 29,75 29)'::geometry As open_line) As foo;

인코딩된 폴리라인 스트링으로부터 라인스트링을 생성합니다.

Code
SELECT ST_MakePolygon('LINESTRING(75.15 29.53 1,77 29 1,77.6 29.5 1,75.15 29.53 1)');
래스터 출력
POLYGON((75.15 29.53 1,77 29 1,77.6 29.5 1,75.15 29.53 1))
Figure
Geometry figure for visual-st-makepolygon-01

Create a Polygon from a LineString with measures

Code
SELECT ST_MakePolygon('LINESTRINGM(75.15 29.53 1,77 29 1,77.6 29.5 2, 75.15 29.53 2)');
래스터 출력
POLYGONM((75.15 29.53 1,77 29 1,77.6 29.5 2,75.15 29.53 2))
Figure
Geometry figure for visual-st-makepolygon-02

Create a CurvePolygon from a CircularString shell.

Code
SELECT ST_MakePolygon('CIRCULARSTRING(0 0,1 1,2 0,1 -1,0 0)');
래스터 출력
CURVEPOLYGON(CIRCULARSTRING(0 0,1 1,2 0,1 -1,0 0))
Figure
Geometry figure for visual-st-makepolygon-03

Outer shell with inner holes variant.

개미 구멍을 가진 도넛을 빌드해봅시다.

Code
SELECT ST_MakePolygon(
    ST_ExteriorRing(ST_Buffer(ring.line, 10)),
    ARRAY[  ST_Translate(ring.line, 1, 1),
        ST_ExteriorRing(ST_Buffer(ST_Point(20, 20), 1)) ]
    )
FROM (SELECT ST_ExteriorRing(ST_Buffer(ST_Point(10, 10), 10, 10)) AS line ) AS ring;

Create a set of province boundaries with holes representing lakes. The input is a table of province Polygons/MultiPolygons and a table of water linestrings. Lines forming lakes are determined by using ST_IsClosed. The province linework is extracted by using ST_Boundary. As required by ST_MakePolygon, the boundary is forced to be a single LineString by using ST_LineMerge. (However, note that if a province has more than one region or has islands this will produce an invalid polygon.) Using a LEFT JOIN ensures all provinces are included even if they have no lakes.

[참고]

NULL 배열을 ST_MakePolygon에 입력하면 NULL을 반환하기 때문에 CASE 구조를 활용합니다.

Code
SELECT p.gid, p.province_name,
  CASE
    WHEN array_agg(w.geom) IS NULL THEN p.geom
    ELSE ST_MakePolygon(
      ST_LineMerge(ST_Boundary(p.geom)),
      array_agg(w.geom)
    )
  END AS geom
FROM provinces p
LEFT JOIN waterlines w
  ON ST_Within(w.geom, p.geom)
  AND ST_IsClosed(w.geom)
GROUP BY p.gid, p.province_name, p.geom;

Another technique is to utilize a correlated subquery and the ARRAY() constructor that converts a row set to an array.

Code
SELECT p.gid, p.province_name,
  CASE
    WHEN EXISTS (
      SELECT w.geom
      FROM waterlines w
      WHERE ST_Within(w.geom, p.geom)
      AND ST_IsClosed(w.geom)
    )
    THEN ST_MakePolygon(
      ST_LineMerge(ST_Boundary(p.geom)),
      ARRAY(
        SELECT w.geom
        FROM waterlines w
        WHERE ST_Within(w.geom, p.geom)
        AND ST_IsClosed(w.geom)
      )
    )
    ELSE p.geom
  END AS geom
FROM provinces p;

제목

ST_Point — Creates a Point with X, Y and SRID values.

요약

geometry ST_Point(float x, float y);

geometry ST_Point(float x, float y, integer srid=unknown);

설명

Returns a Point with the given X and Y coordinate values. This is the SQL-MM equivalent for ST_MakePoint that takes just X and Y.

[참고]

For geodetic coordinates, X is longitude and Y is latitude

Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID to mark the srid on the geometry.

This method implements the SQL/MM specification. SQL-MM 3: 6.1.2

예시

Geometry.

Code
SELECT ST_Point(-71.104, 42.315);

Creating a point with SRID specified:

Code
SELECT ST_Point(-71.104, 42.315, 4326);

Alternative way of specifying SRID:

Code
SELECT ST_SetSRID(ST_Point(-71.104, 42.315), 4326);

Create geography points using the :: cast syntax:

Code
SELECT ST_Point(-71.104, 42.315, 4326)::geography;

Pre-PostGIS 3.2 code, using CAST:

Code
SELECT CAST(ST_SetSRID(ST_Point(-71.104, 42.315), 4326) AS geography);

If the point coordinates are not in a geodetic coordinate system (such as WGS84), then they must be reprojected before casting to a geography. In this example a point in Pennsylvania State Plane feet (SRID 2273) is projected to WGS84 (SRID 4326).

Code
SELECT ST_Transform(ST_Point(3637510, 3014852, 2273), 4326)::geography;

제목

ST_PointZ — Creates a Point with X, Y, Z and SRID values.

요약

geometry ST_PointZ(float x, float y, float z, integer srid=unknown);

설명

주어진 좌표값을 가진 ST_Point를 반환합니다. ST_MakePoint와 동일한 OGC 함수입니다.

Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID to mark the srid on the geometry.

예시

Code
SELECT ST_PointZ(-71.104, 42.315, 3.4, 4326)
Code
SELECT ST_PointZ(-71.104, 42.315, 3.4, srid => 4326)
Code
SELECT ST_PointZ(-71.104, 42.315, 3.4)

제목

ST_PointM — Creates a Point with X, Y, M and SRID values.

요약

geometry ST_PointM(float x, float y, float m, integer srid=unknown);

설명

주어진 좌표값을 가진 ST_Point를 반환합니다. ST_MakePoint와 동일한 OGC 함수입니다.

Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID to mark the srid on the geometry.

예시

Code
SELECT ST_PointM(-71.104, 42.315, 3.4, 4326)
Code
SELECT ST_PointM(-71.104, 42.315, 3.4, srid => 4326)
Code
SELECT ST_PointM(-71.104, 42.315, 3.4)

제목

ST_PointZM — Creates a Point with X, Y, Z, M and SRID values.

요약

geometry ST_PointZM(float x, float y, float z, float m, integer srid=unknown);

설명

주어진 좌표값을 가진 ST_Point를 반환합니다. ST_MakePoint와 동일한 OGC 함수입니다.

Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID to mark the srid on the geometry.

예시

Code
SELECT ST_PointZM(-71.104, 42.315, 3.4, 4.5, 4326)
Code
SELECT ST_PointZM(-71.104, 42.315, 3.4, 4.5, srid => 4326)
Code
SELECT ST_PointZM(-71.104, 42.315, 3.4, 4.5)

제목

ST_Polygon — Creates a Polygon from a LineString with a specified SRID.

요약

geometry ST_Polygon(geometry lineString, integer srid);

설명

Returns a polygon built from the given LineString and sets the spatial reference system from the srid.

ST_Polygon is similar to ST_MakePolygon Variant 1 with the addition of setting the SRID.

, ST_MakePoint, ST_SetSRID

[참고]

이 함수에 멀티라인스트링을 입력할 수는 없습니다. 라인스트링을 생성하려면 ST_LineMerge 또는 ST_Dump 를 이용하십시오.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1.

This method implements the SQL/MM specification. SQL-MM 3: 8.3.2

This function supports 3d and will not drop the z-index.

예시

Create a 2D polygon.

Code
SELECT ST_Polygon('LINESTRING(75 29,77 29,77 31,75 31,75 29)'::geometry, 4326);
래스터 출력
POLYGON((75 29,77 29,77 31,75 31,75 29))
Figure
Geometry figure for visual-st-polygon-01

Create a 3D polygon.

Code
SELECT ST_Polygon('LINESTRING(75 29 1,77 29 2,77 31 2,75 31 1,75 29 1)'::geometry, 4326);
래스터 출력
SRID=4326;POLYGON((75 29 1,77 29 2,77 31 2,75 31 1,75 29 1))
Figure
Geometry figure for visual-st-polygon-02

제목

ST_TileEnvelope — Creates a rectangular Polygon in Web Mercator (SRID:3857) using the XYZ tile system.

요약

geometry ST_TileEnvelope(integer tileZoom, integer tileX, integer tileY, geometry bounds=SRID=3857;LINESTRING(-20037508.342789 -20037508.342789,20037508.342789 20037508.342789), float margin=0.0);

설명

Creates a rectangular Polygon giving the extent of a tile in the XYZ tile system. The tile is specified by the zoom level Z and the XY index of the tile in the grid at that level. Can be used to define the tile bounds required by ST_AsMVTGeom to convert geometry into the MVT tile coordinate space.

By default, the tile envelope is in the Web Mercator coordinate system (SRID:3857) using the standard range of the Web Mercator system (-20037508.342789, 20037508.342789). This is the most common coordinate system used for MVT tiles. The optional bounds parameter can be used to generate tiles in any coordinate system. It is a geometry that has the SRID and extent of the "Zoom Level zero" square within which the XYZ tile system is inscribed.

The optional margin parameter can be used to expand a tile by the given percentage. E.g. margin=0.125 expands the tile by 12.5%, which is equivalent to buffer=512 when the tile extent size is 4096, as used in ST_AsMVTGeom. This is useful to create a tile buffer to include data lying outside of the tile's visible area, but whose existence affects the tile rendering. For example, a city name (a point) could be near an edge of a tile, so its label should be rendered on two tiles, even though the point is located in the visible area of just one tile. Using expanded tiles in a query will include the city point in both tiles. Use a negative value to shrink the tile instead. Values less than -0.5 are prohibited because that would eliminate the tile completely. Do not specify a margin when using with ST_AsMVTGeom. See the example for ST_AsMVT.

개선 사항: 2.0.0 버전에서 선택적인 기본 SRID 파라미터가 추가됐습니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

Show tile (2, 1, 1) within the root tile (0, 0, 0).

Code
SELECT ST_TileEnvelope(0, 0, 0) AS input_z0_x0_y0, ST_TileEnvelope(2, 1, 1) AS z2_x1_y1;
래스터 출력
input_z0_x0_y0 | z2_x1_y1
----------------+-----------
POLYGON((-20037508.342789244 -20037508.342789244,-20037508.342789244 20037508.342789244,20037508.342789244 20037508.342789244,20037508.342789244 -20037508.342789244,-20037508.342789244 -20037508.342789244)) | POLYGON((-10018754.171394622 0,-10018754.171394622 10018754.171394622,0 10018754.171394622,0 0,-10018754.171394622 0))
Figure
Geometry figure for visual-st-tileenvelope-01
Code
SELECT ST_TileEnvelope(3, 1, 1, ST_MakeEnvelope(-180, -90, 180, 90, 4326));
래스터 출력
POLYGON((-135 45,-135 67.5,-90 67.5,-90 45,-135 45))
Figure
Geometry figure for visual-st-tileenvelope-02

제목

ST_HexagonGrid — Returns a set of hexagons and cell indices that completely cover the bounds of the geometry argument.

요약

setof record ST_HexagonGrid(float8 size, geometry bounds);

설명

Starts with the concept of a hexagon tiling of the plane. (Not a hexagon tiling of the globe; for H3 use the h3-pg extension.) For a given planar SRS, and a given edge size, starting at the origin of the SRS, there is one unique hexagonal tiling of the plane, Tiling(SRS, Size). This function answers the question: what hexagons in a given Tiling(SRS, Size) overlap with a given bounds.

The SRS for the output hexagons is the SRS provided by the bounds geometry.

Doubling or tripling the edge size of the hexagon generates a new parent tiling that fits with the origin tiling. Unfortunately, it is not possible to generate parent hexagon tilings that the child tiles perfectly fit inside.

2.1.0 버전부터 사용할 수 있습니다.

예시

Unit hexagons covering rectangular bounds.

Code
WITH bounds AS (
    SELECT ST_MakeEnvelope(2, 1, 4, 3, 3857) AS geom
), grid AS (
    SELECT hex.*
    FROM bounds
    CROSS JOIN LATERAL ST_HexagonGrid(1, geom) AS hex
)
SELECT (SELECT geom FROM bounds) AS input_bounds,
    ST_Collect(geom ORDER BY i, j) AS grid
FROM grid;
래스터 출력
POLYGON((2 1,2 3,4 3,4 1,2 1)) | MULTIPOLYGON(((0.5 0.866,1 0,2 0,2.5 0.866,2 1.732,1 1.732,0.5 0.866)),((0.5 2.598,1 1.732,2 1.732,2.5 2.598,2 3.464,1 3.464,0.5 2.598)),((2 1.732,2.5 0.866,3.5 0.866,4 1.732,3.5 2.598,2.5 2.598,2 1.732)),((2 3.464,2.5 2.598,3.5 2.598,4 3.464,3.5 4.33,2.5 4.33,2 3.464)),((3.5 0.866,4 0,5 0,5.5 0.866,5 1.732,4 1.732,3.5 0.866)),((3.5 2.598,4 1.732,5 1.732,5.5 2.598,5 3.464,4 3.464,3.5 2.598)))
Figure
Geometry figure for visual-st-hexagongrid-01

Child tiles that intersect a doubled-size parent hexagon share the tiling origin, but do not nest perfectly inside the parent.

Code
WITH parent AS (
    SELECT ST_Hexagon(2, 0, 0) AS geom
), children AS (
    SELECT child.*
    FROM parent
    CROSS JOIN LATERAL ST_HexagonGrid(1, geom) AS child
    WHERE ST_Area(ST_Intersection(child.geom, parent.geom)) > 0
)
SELECT ST_Collect(geom ORDER BY i, j) AS children,
    (SELECT geom FROM parent) AS parent
FROM children;
래스터 출력
MULTIPOLYGON(((-2.5 -0.866,-2 -1.732,-1 -1.732,-0.5 -0.866,-1 0,-2 0,-2.5 -0.866)),((-2.5 0.866,-2 0,-1 0,-0.5 0.866,-1 1.732,-2 1.732,-2.5 0.866)),((-1 -1.732,-0.5 -2.598,0.5 -2.598,1 -1.732,0.5 -0.866,-0.5 -0.866,-1 -1.732)),((-1 0,-0.5 -0.866,0.5 -0.866,1 0,0.5 0.866,-0.5 0.866,-1 0)),((-1 1.732,-0.5 0.866,0.5 0.866,1 1.732,0.5 2.598,-0.5 2.598,-1 1.732)),((0.5 -0.866,1 -1.732,2 -1.732,2.5 -0.866,2 0,1 0,0.5 -0.866)),((0.5 0.866,1 0,2 0,2.5 0.866,2 1.732,1 1.732,0.5 0.866))) | POLYGON((-2 0,-1 -1.732,1 -1.732,2 0,1 1.732,-1 1.732,-2 0))
Figure
Geometry figure for visual-st-hexagongrid-02

Counting points in hexagons.

To do a point summary against a hexagonal tiling, generate a hexagon grid using the extent of the points as the bounds, then spatially join to that grid.

Code
SELECT COUNT(*), hexes.geom
FROM ST_HexagonGrid(
  10000,
  ST_SetSRID(ST_EstimatedExtent('pointtable', 'geom'), 3857)
) AS hexes
INNER JOIN pointtable AS pts
  ON ST_Intersects(pts.geom, hexes.geom)
GROUP BY hexes.geom;

Generating hex coverage of polygons.

If a grid is generated for each polygon boundary and filtered to intersecting cells, adjacent regions receive overlapping hexagons along their shared border. The build-time figure below uses two simple regions in place of an external administrative-boundary table, so the example is self-contained.

Code
WITH admin1(gid, geom) AS (
    VALUES
        (1, ST_MakeEnvelope(0, 0, 3, 3, 3857)),
        (2, ST_MakeEnvelope(3, 0, 6, 3, 3857))
), coverage AS (
    SELECT hex.i, hex.j, hex.geom
    FROM admin1
    CROSS JOIN LATERAL ST_HexagonGrid(1.5, admin1.geom) AS hex
    WHERE ST_Intersects(admin1.geom, hex.geom)
    GROUP BY hex.i, hex.j, hex.geom
), layers AS (
    SELECT 'region' AS kind, gid AS position, geom
    FROM admin1
    UNION ALL
    SELECT
        'hexagon',
        1000 + row_number() OVER (ORDER BY i, j),
        geom
    FROM coverage
)
SELECT
    CASE kind WHEN 'region' THEN geom END AS input_region,
    CASE kind WHEN 'hexagon' THEN geom END AS hexagon
FROM layers
ORDER BY position;
래스터 출력
POLYGON((0 0,0 3,3 3,3 0,0 0)) | null
POLYGON((3 0,3 3,6 3,6 0,3 0)) | null
null | POLYGON((-1.5 0,-0.75 -1.3,0.75 -1.3,1.5 0,0.75 1.3,-0.75 1.3,-1.5 0))
null | POLYGON((-1.5 2.6,-0.75 1.3,0.75 1.3,1.5 2.6,0.75 3.9,-0.75 3.9,-1.5 2.6))
null | POLYGON((0.75 1.3,1.5 0,3 0,3.75 1.3,3 2.6,1.5 2.6,0.75 1.3))
null | POLYGON((0.75 3.9,1.5 2.6,3 2.6,3.75 3.9,3 5.2,1.5 5.2,0.75 3.9))
null | POLYGON((3 0,3.75 -1.3,5.25 -1.3,6 0,5.25 1.3,3.75 1.3,3 0))
null | POLYGON((3 2.6,3.75 1.3,5.25 1.3,6 2.6,5.25 3.9,3.75 3.9,3 2.6))
null | POLYGON((5.25 1.3,6 0,7.5 0,8.25 1.3,7.5 2.6,6 2.6,5.25 1.3))
null | POLYGON((5.25 3.9,6 2.6,7.5 2.6,8.25 3.9,7.5 5.2,6 5.2,5.25 3.9))
Figure
Geometry figure for visual-st-hexagongrid-03

The same pattern applies to a real administrative-boundary table:

[참고]

The LATERAL keyword is implied for set-returning functions when referring to a prior table in the FROM list. So CROSS JOIN LATERAL, CROSS JOIN, or just plain , are equivalent constructs for this example.

Code
SELECT admin1.gid, hex.geom
FROM
    admin1
    CROSS JOIN
    ST_HexagonGrid(100000, admin1.geom) AS hex
WHERE
    adm0_a3 = 'USA'
    AND
    ST_Intersects(admin1.geom, hex.geom)

제목

ST_Hexagon — Returns a single hexagon, using the provided edge size and cell coordinate within the hexagon grid space.

요약

geometry ST_Hexagon(float8 size, integer cell_i, integer cell_j, geometry origin);

설명

Uses the same hexagon tiling concept as ST_HexagonGrid, but generates just one hexagon at the desired cell coordinate. Optionally, can adjust origin coordinate of the tiling, the default origin is at 0,0.

Hexagons are generated with no SRID set, so use ST_SetSRID to set the SRID to the one you expect.

2.1.0 버전부터 사용할 수 있습니다.

예시

Creating a hexagon at the origin.

Code
SELECT ST_SetSRID(ST_Hexagon(1.0, 0, 0), 3857);
래스터 출력
POLYGON((-1 0,-0.5 -0.8660254037844387,0.5 -0.8660254037844387,1 0,0.5 0.8660254037844387,-0.5 0.8660254037844387,-1 0))
Figure
Geometry figure for visual-st-hexagon-01

제목

ST_SquareGrid — Returns a set of grid squares and cell indices that completely cover the bounds of the geometry argument.

요약

setof record ST_SquareGrid(float8 size, geometry bounds);

설명

Starts with the concept of a square tiling of the plane. For a given planar SRS, and a given edge size, starting at the origin of the SRS, there is one unique square tiling of the plane, Tiling(SRS, Size). This function answers the question: what grids in a given Tiling(SRS, Size) overlap with a given bounds.

The SRS for the output squares is the SRS provided by the bounds geometry.

Doubling or edge size of the square generates a new parent tiling that perfectly fits with the original tiling. Standard web map tilings in mercator are just powers-of-two square grids in the mercator plane.

2.1.0 버전부터 사용할 수 있습니다.

예시

Generating a 1 degree grid for a country.

The grid will fill the whole bounds of the country, so if you want just squares that touch the country you will have to filter afterwards with ST_Intersects.

Code
WITH grid AS (
SELECT (ST_SquareGrid(1, ST_Transform(geom, 4326))).*
FROM admin0 WHERE name = 'Canada'
)
  SELEcT geom
  FROM grid

Counting points in squares (using single chopped grid).

To do a point summary against a square tiling, generate a square grid using the extent of the points as the bounds, then spatially join to that grid. Note the estimated extent might be off from actual extent, so be cautious and at very least make sure you've analyzed your table.

Code
SELECT COUNT(*), squares.geom
FROM pointtable AS pts
INNER JOIN ST_SquareGrid(
  1000,
  ST_SetSRID(ST_EstimatedExtent('pointtable', 'geom'), 3857)
) AS squares
  ON ST_Intersects(pts.geom, squares.geom)
GROUP BY squares.geom;

Counting points in squares using set of grid per point.

This yields the same result as the first example but will be slower for a large number of points

Code
SELECT COUNT(*), squares.geom
FROM pointtable AS pts
INNER JOIN ST_SquareGrid(
  1000,
  pts.geom
) AS squares
  ON ST_Intersects(pts.geom, squares.geom)
GROUP BY squares.geom;

제목

ST_Square — Returns a single square, using the provided edge size and cell coordinate within the square grid space.

요약

geometry ST_Square(float8 size, integer cell_i, integer cell_j, geometry origin='POINT(0 0)');

설명

Uses the same square tiling concept as ST_SquareGrid, but generates just one square at the desired cell coordinate. Optionally, can adjust origin coordinate of the tiling, the default origin is at 0,0.

Squares are generated with the SRID of the given origin. Use ST_SetSRID to set the SRID if the given origin has an unknown SRID (as is the case by default).

2.1.0 버전부터 사용할 수 있습니다.

예시

Creating a square at the origin.

Code
SELECT ST_SetSRID(ST_Square(1.0, 0, 0), 3857);
래스터 출력
st_astext
-------------------------------------
 POLYGON((0 0,0 1,1 1,1 0,0 0))
(1 row)
Figure
Geometry figure for visual-st-square-01

제목

ST_Letters — Returns the input letters rendered as geometry with a default start position at the origin and default text height of 100.

요약

geometry ST_Letters(text letters, json font);

설명

Uses a built-in font to render out a string as a multipolygon geometry. The default text height is 100.0, the distance from the bottom of a descender to the top of a capital. The default start position places the start of the baseline at the origin. Over-riding the font involves passing in a json map, with a character as the key, and base64 encoded TWKB for the font shape, with the fonts having a height of 1000 units from the bottom of the descenders to the tops of the capitals.

The text is generated at the origin by default, so to reposition and resize the text, first apply the ST_Scale function and then apply the ST_Translate function.

Availability: 3.3.0

예시

Generating the word 'Yo'.

Code
SELECT ST_Letters('Yo');
래스터 출력
MULTIPOLYGON(((34.5 73.8,54 73.8,53.1 72.9,35.1 28.7,35.1 0.9,36 0,18 0,19 0.9,19 28.7,0.9 72.9,0 73.8,19.5 73.8,18.6 72.9,23 61.6,27 47.4,31.1 61.9,35.4 72.9,34.5 73.8)),((68.87 58,69.97 58,71.07 57.9,72.17 57.8,73.17 57.7,74.27 57.5,75.27 57.3,76.17 57.1,77.17 56.8,78.07 56.5,78.97 56.1,79.87 55.7,80.67 55.3,81.47 54.8,82.27 54.3,82.97 53.7,83.67 53.1,84.37 52.5,84.97 51.8,85.57 51.1,86.07 50.3,86.57 49.5,87.07 48.7,87.57 47.9,87.97 47,88.37 46.1,88.67 45.1,88.97 44.1,89.17 43.1,89.37 42.1,89.47 41,89.57 39.9,89.57 38.7,89.57 18.9,89.57 17.7,89.47 16.6,89.37 15.5,89.17 14.5,88.97 13.5,88.77 12.5,88.47 11.5,88.07 10.6,87.67 9.7,87.27 8.9,86.77 8.1,86.27 7.3,85.67 6.6,85.07 5.9,84.47 5.2,83.77 4.6,83.07 4,82.27 3.5,81.57 2.9,80.77 2.5,79.87 2,79.07 1.6,78.17 1.2,77.27 0.8,76.37 0.5,75.37 0.2,74.37 0,73.37 -0.2,72.27 -0.4,71.17 -0.5,70.07 -0.5,68.97 -0.5,67.87 -0.5,66.77 -0.4,65.67 -0.3,64.57 -0.2,63.57 0,62.57 0.2,61.57 0.5,60.57 0.8,59.67 1.1,58.77 1.5,57.87 1.9,57.07 2.4,56.27 2.9,55.47 3.4,54.77 3.9,54.07 4.5,53.37 5.1,52.77 5.8,52.17 6.5,51.67 7.2,51.17 8,50.67 8.8,50.17 9.7,49.77 10.6,49.37 11.5,49.07 12.5,48.77 13.5,48.57 14.5,48.37 15.6,48.27 16.7,48.17 17.8,48.17 18.9,48.17 38.7,48.17 39.9,48.27 41,48.37 42.1,48.57 43.1,48.77 44.1,48.97 45.1,49.27 46.1,49.67 47,50.07 47.9,50.47 48.7,50.97 49.5,51.47 50.3,52.07 51,52.67 51.7,53.27 52.4,53.97 53,54.67 53.6,55.47 54.1,56.17 54.6,57.07 55.1,57.87 55.6,58.77 56,59.67 56.4,60.57 56.7,61.57 57,62.47 57.3,63.47 57.5,64.57 57.7,65.57 57.8,66.67 57.9,67.77 58,68.87 58),(73.77 38.9,72.27 41.6,68.97 42.6,65.57 41.7,64.07 38.9,64.07 18.9,65.47 16.2,68.77 15.2,72.07 16.1,73.77 18.9,73.77 38.9)))
Figure
Geometry figure for visual-st-letters-01

Generating the word 'PostGIS'.

Code
SELECT ST_Letters('PostGIS') AS letters;
래스터 출력
MULTIPOLYGON(((43 39,43 38,42 37,42 36,42 35,42 34,42 33,42 32,41 31,41 30,40 29,40 28,39 28,39 27,38 26,38 26,37 25,36 24,36 24,35 24,34 23,33 23,33 22,32 22,31 22,30 21,29 21,28 21,27 21,26 20,25 20,24 20,23 20,17 20,17 1,18 0,0 0,1 1,1 73,0 74,23 74,24 74,25 74,26 74,27 74,28 73,29 73,30 73,31 73,32 72,33 72,33 72,34 72,35 71,36 70,36 70,37 69,38 69,38 68,39 67,39 67,40 66,40 65,41 64,41 64,42 63,42 62,42 61,42 60,42 58,42 57,43 56,43 55,43 39),(26 56,26 58,23 59,17 59,17 35,23 35,26 36,26 38,26 56)),((69 58,70 58,71 58,72 58,73 58,74 58,75 57,76 57,77 57,78 56,79 56,80 56,81 55,82 55,82 54,83 54,84 53,85 52,85 52,86 51,86 50,87 50,87 49,88 48,88 47,89 46,89 45,89 44,89 43,90 42,90 41,90 40,90 39,90 19,90 18,90 17,90 16,89 14,89 14,89 12,89 12,88 11,88 10,87 9,87 8,86 7,86 7,85 6,85 5,84 5,83 4,82 4,82 3,81 2,80 2,79 2,78 1,77 1,77 0,76 0,75 0,74 0,72 0,71 0,70 0,69 0,68 0,67 0,66 0,65 0,64 0,63 0,62 0,61 1,60 1,59 2,58 2,57 2,56 3,56 3,55 4,54 4,54 5,53 6,52 6,52 7,51 8,51 9,50 10,50 11,50 12,49 12,49 14,49 14,49 16,48 17,48 18,48 19,48 39,48 40,48 41,49 42,49 43,49 44,49 45,49 46,50 47,50 48,51 49,51 50,52 50,52 51,53 52,53 52,54 53,55 54,56 54,56 55,57 55,58 56,59 56,60 56,61 57,62 57,63 57,64 58,65 58,66 58,67 58,68 58,69 58),(74 39,72 42,69 43,66 42,64 39,64 19,66 16,69 15,72 16,74 19,74 39)),((111 38,112 37,112 37,113 37,113 37,114 36,115 36,116 36,116 36,117 35,118 35,119 34,120 34,121 33,121 33,122 32,123 32,124 31,125 30,126 30,126 29,127 28,128 27,128 27,129 26,129 25,130 24,130 23,131 22,131 21,131 20,131 18,131 17,131 16,131 15,131 14,130 12,130 11,130 10,129 9,129 8,128 8,128 7,127 6,127 5,126 5,126 4,125 3,124 3,124 2,123 2,122 1,121 1,120 1,120 0,119 0,118 0,117 0,116 0,115 0,114 0,113 0,112 0,111 0,110 0,110 0,109 0,108 0,107 0,106 0,105 0,104 0,103 0,102 1,101 1,100 1,99 2,97 2,96 3,95 3,94 4,99 19,99 19,100 18,100 18,100 18,101 18,101 18,102 18,102 18,103 17,103 17,104 17,104 17,105 17,105 17,106 16,106 16,107 16,107 16,108 16,108 16,109 16,110 16,110 16,111 16,111 16,112 15,112 15,113 15,113 15,113 15,114 15,114 15,115 16,115 16,115 17,115 17,115 18,115 18,115 19,115 19,115 20,114 20,114 20,113 20,113 20,113 20,112 20,112 21,111 21,111 21,110 21,109 22,109 22,108 22,108 22,107 23,107 23,106 24,106 24,105 24,104 24,104 25,103 25,103 26,102 26,102 26,101 27,101 28,100 28,100 28,99 29,99 30,98 30,98 31,98 31,97 32,97 33,97 33,96 34,96 35,96 35,96 36,96 37,96 38,96 38,95 39,95 40,95 41,96 42,96 43,96 43,96 44,96 45,96 45,96 46,97 47,97 47,97 48,97 48,97 49,98 49,98 50,98 50,99 51,99 51,99 52,100 52,100 52,100 53,101 53,101 53,101 54,101 54,102 54,102 54,102 55,103 55,103 55,103 55,104 56,105 56,106 56,106 57,107 57,108 57,109 58,110 58,111 58,112 58,113 58,114 58,115 58,116 58,117 58,118 58,118 58,119 58,120 58,121 57,122 57,123 57,123 57,124 56,125 56,126 56,126 56,127 56,127 55,128 55,128 55,129 55,129 55,123 40,123 40,122 40,122 40,122 40,122 40,121 40,121 40,121 41,120 41,120 41,119 41,119 41,119 41,118 41,118 41,118 41,117 41,117 41,117 42,116 42,116 42,115 42,115 42,115 42,114 42,114 42,114 42,113 42,113 42,113 42,112 42,112 42,112 42,112 42,112 42,112 42,112 42,112 42,112 42,111 42,111 42,111 41,111 41,111 41,111 41,111 41,111 40,111 40,111 40,111 40,111 40,111 40,111 39,111 39,111 39,111 39,111 39,111 38,111 38,111 38,111 38,111 38,111 38,111 38)),((161 15,166 15,167 16,167 -1,166 0,160 0,160 0,159 0,158 0,157 0,157 0,156 0,155 0,155 0,154 0,153 0,153 1,152 1,151 1,151 1,150 2,149 2,149 2,148 3,147 3,147 4,146 4,146 5,145 5,145 6,144 6,144 7,143 8,143 9,142 10,142 10,141 11,141 12,141 43,136 43,135 42,135 59,136 58,141 58,141 74,140 75,158 75,157 74,157 58,165 58,166 59,166 42,165 43,157 43,157 18,157 17,157 17,157 17,158 17,158 16,158 16,158 16,159 16,159 16,159 16,160 16,160 15,160 15,161 15,161 15,161 15)),((214 13,214 12,213 12,213 11,213 10,212 10,212 9,212 8,211 8,211 7,210 6,210 6,209 5,209 5,208 4,208 4,207 3,206 3,206 2,205 2,204 2,203 1,203 1,202 0,201 0,200 0,199 0,199 0,198 0,197 0,196 -1,195 -1,194 -1,193 -1,192 -1,190 0,189 0,188 0,187 0,186 0,185 1,184 1,183 1,182 2,182 2,181 3,180 3,179 4,178 4,178 5,177 6,176 6,176 7,175 8,175 9,175 10,174 10,174 11,174 12,173 13,173 14,173 15,173 16,173 18,173 19,173 54,173 56,173 56,173 57,173 58,173 59,173 60,173 61,174 62,174 63,174 64,174 64,175 65,175 66,176 67,176 68,177 68,177 69,178 70,179 70,179 71,180 71,181 72,182 72,183 72,184 73,185 73,186 73,187 74,188 74,189 74,190 74,192 74,210 74,210 58,192 58,191 58,191 58,191 58,190 58,190 58,190 58,190 57,189 57,189 57,189 56,189 56,189 56,189 56,189 55,189 55,189 54,189 19,189 19,189 18,189 18,189 18,189 17,189 17,189 17,190 17,190 16,190 16,191 16,191 16,191 16,192 15,192 15,193 15,193 15,193 15,194 15,194 15,195 15,195 15,196 15,196 15,196 15,197 15,197 15,198 16,198 16,198 16,199 16,199 16,199 32,193 32,193 46,214 46,214 13)),((236 73,236 1,237 0,219 0,220 1,220 73,219 74,237 74,236 73)),((264 45,265 45,266 44,266 44,267 44,268 43,269 43,270 42,271 42,272 42,273 41,274 40,274 40,275 39,276 39,277 38,277 38,278 37,279 36,279 35,280 35,280 34,281 33,281 32,282 31,282 30,283 29,283 28,283 27,283 26,284 25,284 24,284 22,283 21,283 20,283 20,283 19,283 18,283 17,283 16,283 15,282 15,282 14,282 13,282 13,281 12,281 11,281 11,280 10,280 10,280 9,279 9,279 8,279 8,278 7,278 7,278 6,277 6,277 6,276 5,276 5,276 5,275 4,275 4,275 4,274 3,273 3,272 2,271 2,270 1,269 1,268 1,267 0,266 0,264 0,263 0,262 0,261 0,260 0,259 0,258 0,257 0,256 0,255 0,253 0,252 0,251 1,250 1,249 2,248 2,247 2,246 3,245 3,244 4,243 4,242 4,242 5,246 21,247 20,248 20,248 20,249 20,250 19,251 19,251 19,252 18,253 18,254 18,255 18,255 17,256 17,257 17,258 17,259 17,259 16,260 16,261 16,262 16,262 17,263 17,264 17,264 17,265 17,265 18,266 18,266 19,267 19,267 20,267 21,267 22,267 22,267 23,267 23,267 24,267 24,267 24,267 25,266 25,266 26,265 26,265 26,264 27,264 27,263 28,262 28,261 28,261 29,260 29,259 30,258 30,258 30,257 31,256 31,255 32,254 32,253 33,253 33,252 34,251 34,250 35,249 36,248 36,248 37,247 38,246 39,246 39,245 40,244 41,244 42,244 43,243 44,243 45,243 46,242 47,242 49,242 50,242 51,242 53,242 55,242 56,242 58,243 60,243 61,244 62,245 64,246 65,247 66,248 67,249 68,250 69,251 70,252 71,253 72,255 72,256 73,258 73,259 74,261 74,262 74,264 74,265 74,267 74,269 74,270 74,272 73,274 73,275 73,277 72,279 72,280 71,275 56,275 57,274 57,274 57,273 57,273 57,272 57,271 58,271 58,270 58,269 58,269 58,268 58,267 58,267 58,266 58,265 58,265 58,264 58,263 58,263 58,262 58,262 58,261 57,260 57,260 56,260 56,259 56,259 55,258 54,258 54,258 53,258 52,258 52,258 51,258 51,258 50,258 50,259 49,259 48,259 48,260 48,260 47,261 47,262 46,262 46,263 46,263 45,264 45)))
Figure
Geometry figure for visual-st-letters-02

Scaling and moving words.

Code
WITH letters AS (
    SELECT ST_Letters('Yo') AS geom
)
SELECT geom AS input_letters,
       ST_Translate(ST_Scale(geom, 2, 2), 120, 0)
           AS scaled_letters
FROM letters;
래스터 출력
MULTIPOLYGON(((34 74,54 74,53 73,35 29,35 1,36 0,18 0,19 1,19 29,1 73,0 74,20 74,19 73,23 62,27 47,31 62,35 73,34 74)),((69 58,70 58,71 58,72 58,73 58,74 58,75 57,76 57,77 57,78 56,79 56,80 56,81 55,81 55,82 54,83 54,84 53,84 52,85 52,86 51,86 50,87 50,87 49,88 48,88 47,88 46,89 45,89 44,89 43,89 42,89 41,90 40,90 39,90 19,90 18,89 17,89 16,89 14,89 14,89 12,88 12,88 11,88 10,87 9,87 8,86 7,86 7,85 6,84 5,84 5,83 4,82 4,82 3,81 2,80 2,79 2,78 1,77 1,76 0,75 0,74 0,73 0,72 0,71 0,70 0,69 0,68 0,67 0,66 0,65 0,64 0,63 0,62 0,61 1,60 1,59 2,58 2,57 2,56 3,55 3,55 4,54 4,53 5,53 6,52 6,52 7,51 8,51 9,50 10,50 11,49 12,49 12,49 14,49 14,48 16,48 17,48 18,48 19,48 39,48 40,48 41,48 42,49 43,49 44,49 45,49 46,50 47,50 48,50 49,51 50,51 50,52 51,53 52,53 52,54 53,55 54,55 54,56 55,57 55,58 56,59 56,60 56,61 57,62 57,62 57,63 58,65 58,66 58,67 58,68 58,69 58),(74 39,72 42,69 43,66 42,64 39,64 19,65 16,69 15,72 16,74 19,74 39))) | MULTIPOLYGON(((189 148,228 148,226 146,190 57,190 2,192 0,156 0,158 2,158 57,122 146,120 148,159 148,157 146,166 123,174 95,182 124,191 146,189 148)),((258 116,260 116,262 116,264 116,266 115,269 115,271 115,272 114,274 114,276 113,278 112,280 111,281 111,283 110,285 109,286 107,287 106,289 105,290 104,291 102,292 101,293 99,294 97,295 96,296 94,297 92,297 90,298 88,298 86,299 84,299 82,299 80,299 77,299 38,299 35,299 33,299 31,298 29,298 27,298 25,297 23,296 21,295 19,295 18,294 16,293 15,291 13,290 12,289 10,288 9,286 8,285 7,283 6,282 5,280 4,278 3,276 2,275 2,273 1,271 0,269 0,267 0,265 -1,262 -1,260 -1,258 -1,256 -1,254 -1,251 -1,249 0,247 0,245 0,243 1,241 2,239 2,238 3,236 4,234 5,233 6,231 7,230 8,228 9,227 10,226 12,224 13,223 14,222 16,221 18,220 19,220 21,219 23,218 25,218 27,217 29,217 31,217 33,216 36,216 38,216 77,216 80,217 82,217 84,217 86,218 88,218 90,219 92,219 94,220 96,221 97,222 99,223 101,224 102,225 103,227 105,228 106,229 107,231 108,232 109,234 110,236 111,238 112,239 113,241 113,243 114,245 115,247 115,249 115,251 116,253 116,256 116,258 116),(268 78,265 83,258 85,251 83,248 78,248 38,251 32,258 30,264 32,268 38,268 78)))
Figure
Geometry figure for visual-st-letters-03

제목

ST_MakeNurbsCurve — Creates a NURBS (Non-Uniform Rational B-Spline) curve from control points, optional weights, and optional knot vector.

요약

geometry ST_MakeNurbsCurve(integer degree, geometry control_points, float8[] weights, float8[] knots);

설명

Creates a NURBS (Non-Uniform Rational B-Spline) curve geometry from the specified parameters. NURBS curves are smooth parametric curves that provide precise control over curve shape through control points, weights, and knot values.

The degree parameter specifies the polynomial degree of the curve (must be between 1 and 10). Higher degrees produce smoother curves.

The control_points must be a LINESTRING geometry defining the control polygon. The number of control points must be at least degree + 1.

The optional weights array assigns a weight to each control point. All weights must be positive. If NULL or omitted, uniform weights (1.0) are used, resulting in a non-rational B-spline.

The optional knots array defines the parameter space. If NULL or omitted, a uniform clamped knot vector is automatically generated. If provided, the knot vector must have exactly (npoints + degree + 1) elements and must be non-decreasing.

Availability: 3.7.0

예시

This example creates a degree-2 NURBS curve with uniform weights.

Code
SELECT ST_MakeNurbsCurve(
    2,
    'LINESTRING(0 0,5 10,10 0)'::geometry
);
래스터 출력
NURBSCURVE(DEGREE 2, CONTROLPOINTS(NURBSPOINT(WEIGHTEDPOINT(0 0),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT(5 10),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT(10 0),WEIGHT 1)),KNOTS (KNOT(0,3), KNOT(1,3)))
Figure
Geometry figure for visual-st-makenurbscurve-01

This example creates a rational NURBS curve with custom weights.

Code
SELECT ST_MakeNurbsCurve(
    2,
    'LINESTRING(0 0,5 10,10 0)'::geometry,
    ARRAY[1.0, 2.0, 1.0]
);
래스터 출력
NURBSCURVE(DEGREE 2, CONTROLPOINTS(NURBSPOINT(WEIGHTEDPOINT(0 0),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT(5 10),WEIGHT 2), NURBSPOINT(WEIGHTEDPOINT(10 0),WEIGHT 1)),KNOTS (KNOT(0,3), KNOT(1,3)))
Figure
Geometry figure for visual-st-makenurbscurve-02

This example creates a NURBS curve with a non-uniform knot vector.

Code
SELECT ST_MakeNurbsCurve(
    2,
    'LINESTRING(0 0,3 10,7 10,10 0)'::geometry,
    ARRAY[1.0, 1.0, 1.0, 1.0],
    ARRAY[0.0, 0.0, 0.0, 0.3, 1.0, 1.0, 1.0]
);
래스터 출력
NURBSCURVE(DEGREE 2, CONTROLPOINTS(NURBSPOINT(WEIGHTEDPOINT(0 0),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT(3 10),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT(7 10),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT(10 0),WEIGHT 1)),KNOTS (KNOT(0,3), KNOT(0.3,1), KNOT(1,3)))
Figure
Geometry figure for visual-st-makenurbscurve-03

7.4. 도형 접근자(accessor)

초록

These functions expose structural information about an existing geometry without changing it. They provide access to metadata such as geometry type, dimensionality, or coordinate components so that spatial expressions can interrogate complex objects in a controlled way.

  • GeometryType — ST_Geometry 값의 도형 유형을 반환합니다.
  • ST_Boundary — 해당 도형의 결합된 범위의 닫힘 여부를 반환합니다.
  • ST_BoundingDiagonal — 주어진 도형의 경계 상자의 대각선을 반환합니다.
  • ST_CoordDim — ST_Geometry 값의 좌표 차원을 반환합니다.
  • ST_Dimension — ST_Geometry 값의 좌표 차원을 반환합니다.
  • ST_Dump — Returns a set of geometry_dump rows for the components of a geometry.
  • ST_DumpPoints — 도형의 내용을 요약한 텍스트를 반환합니다.
  • ST_DumpSegments — 도형의 내용을 요약한 텍스트를 반환합니다.
  • ST_DumpRings — Returns a set of geometry_dump rows for the exterior and interior rings of a Polygon.
  • ST_EndPoint — Returns the last point of a LineString, CircularLineString, or NURBSCurve.
  • ST_Envelope — 주어진 도형의 이중 정밀도(double precision; float8) 경계 상자를 표현하는 도형을 반환합니다.
  • ST_ExteriorRing — 폴리곤 도형의 내곽 고리의 개수를 반환합니다.
  • ST_GeometryN — ST_Geometry 값의 도형 유형을 반환합니다.
  • ST_GeometryType — ST_Geometry 값의 도형 유형을 반환합니다.
  • ST_HasArc — Tests if a geometry contains a circular arc
  • ST_InteriorRingN — 폴리곤 도형의 내곽 고리의 개수를 반환합니다.
  • ST_NumCurves — Return the number of component curves in a CompoundCurve.
  • ST_CurveN — Returns the Nth component curve geometry of a CompoundCurve.
  • ST_IsClosedLINESTRING 의 시작점과 종단점이 일치하는 경우 TRUE 를 반환합니다. 다면체 표면이 닫혀 (부피를 가지고) 있는 경우 TRUE 를 반환합니다.
  • ST_IsCollection — 해당 도형이 텅 빈 도형 집합, 폴리곤, 포인트 등인 경우 TRUE 를 반환합니다.
  • ST_IsEmpty — Tests if a geometry is empty.
  • ST_IsPolygonCCW — Tests if Polygons have exterior rings oriented counter-clockwise and interior rings oriented clockwise.
  • ST_IsPolygonCW — Tests if Polygons have exterior rings oriented clockwise and interior rings oriented counter-clockwise.
  • ST_IsRing — Tests if a LineString is closed and simple.
  • ST_IsSimple — 해당 도형이 자체 교차하거나 자체 접촉하는 이례적인 도형 포인트를 가지고 있지 않을 경우 TRUE 를 반환합니다.
  • ST_M — Returns the M coordinate of a Point.
  • ST_MemSize — ST_Geometry 값의 도형 유형을 반환합니다.
  • ST_NDims — ST_Geometry 값의 좌표 차원을 반환합니다.
  • ST_NPoints — 도형이 가지고 있는 포인트(꼭짓점)의 개수를 반환합니다.
  • ST_NRings — 폴리곤 도형의 내곽 고리의 개수를 반환합니다.
  • ST_NumGeometries — 도형이 가지고 있는 포인트의 개수를 반환합니다. 모든 도형을 입력받을 수 있습니다.
  • ST_NumInteriorRings — 폴리곤 도형의 내곽 고리의 개수를 반환합니다.
  • ST_NumInteriorRing — Returns the number of interior rings (holes) of a Polygon. Alias for ST_NumInteriorRings.
  • ST_NumPatches — Returns the number of faces in a PolyhedralSurface or TIN.
  • ST_NumPoints — ST_LineString 또는 ST_CircularString 값에 있는 포인트의 개수를 반환합니다.
  • ST_PatchN — Returns the Nth face of a PolyhedralSurface or TIN.
  • ST_PointN — ST_LineString 또는 ST_CircularString 값에 있는 포인트의 개수를 반환합니다.
  • ST_Points — 도형의 모든 좌표들을 담고 있는 멀티포인트를 반환합니다.
  • ST_StartPoint — Returns the first point of a LineString, CircularLineString, or NURBSCurve.
  • ST_StartM — Returns the M coordinate of the first point of a LineString, CircularLineString, or NURBSCurve.
  • ST_EndM — Returns the M coordinate of the last point of a LineString, CircularLineString, or NURBSCurve.
  • ST_SetStartM — Sets the M coordinate of the first point of a LineString, CircularLineString, or NURBSCurve.
  • ST_SetEndM — Sets the M coordinate of the last point of a LineString, CircularLineString, or NURBSCurve.
  • ST_Summary — 도형의 내용을 요약한 텍스트를 반환합니다.
  • ST_X — Returns the X coordinate of a Point.
  • ST_Y — Returns the Y coordinate of a Point.
  • ST_Z — Returns the Z coordinate of a Point.
  • ST_ZMFlag — ST_Geometry 값의 좌표 차원을 반환합니다.
  • ST_HasZ — Checks if a geometry has a Z dimension.
  • ST_HasM — Checks if a geometry has an M (measure) dimension.
  • ST_ControlPoints — Returns the control points of a NURBS curve as a MULTIPOINT geometry.
  • ST_Degree — Returns the polynomial degree of a NURBS curve.
  • ST_Weights — Returns the weight array of a rational NURBS curve.
  • ST_Knots — Returns the knot vector of a NURBS curve.
  • ST_NumControlPoints — Returns the number of control points in a NURBS curve.
  • ST_NurbsCurveIsRational — Checks if a NURBS curve is rational (has weights).
  • ST_IsNurbsCurve — Checks if a geometry is a NURBS curve.
  • ST_Evaluate — Evaluates a NURBS curve at a specific parameter value and returns the resulting point.
  • ST_NurbsToLineString — Converts a NURBS curve to a LINESTRING by uniform sampling.

제목

GeometryType — ST_Geometry 값의 도형 유형을 반환합니다.

요약

text GeometryType(geometry geomA);

설명

도형의 유형을 스트링으로 반환합니다. 예: 'LINESTRING', 'POLYGON', 'MULTIPOINT' 등등.

OGC 사양 s2.1.1.1 - 해당 도형 인스턴스가 속해 있는, 인스턴스화할 수 있는 도형 하위 유형의 명칭을 스트링으로 반환합니다.

[참고]

이 함수는 'POINTM' 형식의 스트링을 반환해서 도형에 단위가 적용되었는지 여부도 보여줍니다.

개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1.

This method supports Circular Strings and Curves.

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

Code
SELECT GeometryType('LINESTRING(77.29 29.07,77.42 29.26,77.27 29.31,77.29 29.07)'::geometry);
래스터 출력
LINESTRING
Figure
Geometry figure for visual-geometrytype-01
Code
SELECT ST_GeometryType('POLYHEDRALSURFACE( ((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)),
((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)),((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)),
((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)),
((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)),((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1)) )');
    POLYHEDRALSURFACE
            
Code
SELECT GeometryType(geom) as result
FROM
  (SELECT
     'TIN (((
              0 0 0,
              0 0 1,
              0 1 0,
              0 0 0
          )),((
              0 0 0,
              0 1 0,
              1 1 0,
              0 0 0
          ))
          )'::geometry  AS geom
  ) AS g;
래스터 출력
TIN
Figure
Geometry figure for visual-geometrytype-02

제목

ST_Boundary — 해당 도형의 결합된 범위의 닫힘 여부를 반환합니다.

요약

geometry ST_Boundary(geometry geomA);

설명

해당 도형의 결합된 범위의 닫힘(closure) 여부를 반환합니다. 결합 범위(combinatorial boundary)는 OGC 사양서의 3.12.3.2 단원이 설명하는대로 정의됩니다. 이 함수의 결과가 닫힘이기 때문에, 즉 위상적(位相的)으로 폐쇄됐기 때문에, OGC 사양서 3.12.2 단원에서 설명한대로 표현적인 도형 원형(primitive)을 이용해서 결과 범위를 표현할 수 있습니다.

GEOS 모듈로 실행

[참고]

2.0.0 미만 버전에서 이 함수를 GEOMETRYCOLLECTION과 함께 사용하면 예외가 발생했습니다. 2.0.0 이후 버전은 대신 (입력을 지원하지 않는다는 의미의) NULL을 반환합니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. OGC SPEC s2.1.1.1

This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 5.1.17

This function supports 3d and will not drop the z-index.

개선 사항: 2.1.0 버전부터 삼각형을 지원하기 시작했습니다.

Changed: 3.2.0 support for TIN, does not use geos, does not linearize curves

예시

LineString with boundary points overlaid.

Code
SELECT ST_Boundary(geom)
FROM (SELECT 'LINESTRING(100 150,50 60,70 80,160 170)'::geometry As geom) As f;
                
래스터 출력
MULTIPOINT((100 150),(160 170))
Figure
Geometry figure for visual-st-boundary-01

Polygon holes with the boundary MultiLineString overlaid.

Code
SELECT ST_Boundary(geom)
FROM (SELECT
'POLYGON (( 10 130,50 190,110 190,140 150,150 80,100 10,20 40,10 130 ),
    ( 70 40,100 50,120 80,80 110,50 90,70 40 ))'::geometry As geom) As f;
                
래스터 출력
MULTILINESTRING((10 130,50 190,110 190,140 150,150 80,100 10,20 40,10 130),
        (70 40,100 50,120 80,80 110,50 90,70 40))
Figure
Geometry figure for visual-st-boundary-02
Code
SELECT ST_Boundary('LINESTRING(1 1,0 0,-1 1)');
래스터 출력
MULTIPOINT((1 1),(-1 1))
Figure
Geometry figure for visual-st-boundary-03
Code
SELECT ST_Boundary('POLYGON((1 1,0 0,-1 1,1 1))');
래스터 출력
LINESTRING(1 1,0 0,-1 1,1 1)
Figure
Geometry figure for visual-st-boundary-04

This example uses a 3D polygon.

Code
SELECT ST_Boundary('POLYGON((1 1 1,0 0 1,-1 1 1,1 1 1))');
래스터 출력
LINESTRING(1 1 1,0 0 1,-1 1 1,1 1 1)
Figure
Geometry figure for visual-st-boundary-05

This example uses a 3D MultiLineString.

Code
SELECT ST_Boundary('MULTILINESTRING((1 1 1,0 0 0.5,-1 1 1),(1 1 0.5,0 0 0.5,-1 1 0.5,1 1 0.5) )');
래스터 출력
MULTIPOINT(1 1 1,-1 1 1)
Figure
Geometry figure for visual-st-boundary-06

제목

ST_BoundingDiagonal — 주어진 도형의 경계 상자의 대각선을 반환합니다.

요약

geometry ST_BoundingDiagonal(geometry geom, boolean fits=false);

설명

주어진 도형의 경계 상자의 대각선을 라인스트링으로 반환합니다. 빈 도형을 입력받은 경우 빈 대각선을 반환하게 됩니다. 빈 도형이 아니라면 포인트 2개 중 시작점이 각 차원의 최소값들을, 종단점이 각 차원의 최대값들을 가진 라인스트링을 반환합니다.

fits 파라미터는 딱 맞는(best fit) 경계 상자가 필요한지 여부를 설정합니다. 거짓으로 설정한다면 조금 넉넉한 경계 상자도 용납할 수 있습니다(수많은 꼭짓점을 가진 도형의 경우 더 빨리 처리할 수 있습니다). 어떤 경우든 반환된 대각선의 경계 상자는 항상 입력 도형을 둘러쌉니다.

반환된 라인스트링 도형은 언제나 입력 도형의 SRID 및 차원수를 유지합니다.

[참고]

차원이 낮은 (입력 도형이 단일 꼭짓점) 경우 반환되는 라인스트링이 위상적으로 유효하지 않을 (내부가 없을) 것입니다. 그렇다고 해서 반환된 도형이 의미론적으로 유효하지 않다는 뜻은 아닙니다.

2.2.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

This function supports M coordinates.

예시

This example shows a polygon together with the diagonal of its bounding box.

Code
WITH input AS (
  SELECT 'POLYGON((10 20,30 60,70 40,90 10,50 -10,10 20))'::geometry AS geom
)
SELECT geom AS input_polygon,
       ST_BoundingDiagonal(geom) AS diagonal
FROM input;
래스터 출력
POLYGON((10 20,30 60,70 40,90 10,50 -10,10 20)) | LINESTRING(10 -10,90 60)
Figure
Geometry figure for visual-st-boundingdiagonal-01

This example returns the minimum X coordinate of a buffer around a point.

Code
SELECT ST_X(ST_StartPoint(ST_BoundingDiagonal(
  ST_Buffer(ST_Point(0, 0), 10)
)));
래스터 출력
-10

제목

ST_CoordDim — ST_Geometry 값의 좌표 차원을 반환합니다.

요약

integer ST_CoordDim(geometry geomA);

설명

ST_Geometry 값의 좌표 차원을 반환합니다.

이 함수는 MM을 준수하는, ST_NDims 와 동일한 함수합니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1.

This method implements the SQL/MM specification. SQL-MM 3: 5.1.3

This method supports Circular Strings and Curves.

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

Code
SELECT ST_CoordDim('CIRCULARSTRING(1 2 3,1 3 4,5 6 7,8 9 10,11 12 13)');
래스터 출력
3
Code
SELECT ST_CoordDim(ST_Point(1, 2));
래스터 출력
2

참고

ST_NDims


제목

ST_Dimension — ST_Geometry 값의 좌표 차원을 반환합니다.

요약

integer ST_Dimension(geometry g);

설명

좌표 차원과 동등하거나 낮아야 하는, 해당 도형 객체의 내재된 차원을 반환합니다. OGC 사양서 s2.1.1.1 단원을 보면 POINT 는 0, LINESTRING 은 1, POLYGON 은 2, 그리고 GEOMETRYCOLLECTION 의 경우 구성 요소 가운데 가장 높은 차원입니다. 알려지지 않은 (텅 빈) 도형인 경우 null을 반환합니다.

This method implements the SQL/MM specification. SQL-MM 3: 5.1.2

[참고]

A TIN, including a closed TIN surface, is a surface geometry and has dimension 2. Use CG_MakeSolid to make the solid representation explicit; the resulting 3D solid has dimension 3. Solid geometry semantics, such as volume, are handled separately by the SQL/MM 3D solid functions (SQL-MM IEC 13249-3: 9.1).

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface) 및 TIN을 지원합니다. 빈 도형이 주어져도 더 이상 예외가 발생하지 않습니다.

[참고]

2.0.0 미만 버전에서는 빈 도형에 대해 예외를 발생시켰습니다.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

Code
SELECT ST_Dimension('GEOMETRYCOLLECTION(LINESTRING(1 1,0 0), POINT(0 0))');
래스터 출력
1
Figure
Geometry figure for visual-st-dimension-01
Code
SELECT ST_Dimension('TIN Z (((0 0 0,0 0 1,0 1 0,0 0 0)),((0 0 0,0 1 0,1 0 0,0 0 0)),((0 0 0,1 0 0,0 0 1,0 0 0)),((1 0 0,0 1 0,0 0 1,1 0 0)))');
래스터 출력
2
Figure
Geometry figure for visual-st-dimension-02

제목

ST_Dump — Returns a set of geometry_dump rows for the components of a geometry.

요약

geometry_dump[] ST_Dump(geometry g1);

설명

A set-returning function (SRF) that extracts the components of a geometry. It returns a set of geometry_dump rows, each containing a geometry (geom field) and an array of integers (path field).

For an atomic geometry type (POINT,LINESTRING,POLYGON) a single record is returned with an empty path array and the input geometry as geom. For a collection or multi-geometry a record is returned for each of the collection components, and the path denotes the position of the component inside the collection.

ST_Dump is useful for expanding geometries. It is the inverse of a ST_Collect / GROUP BY, in that it creates new rows. For example it can be use to expand MULTIPOLYGONS into POLYGONS.

개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다.

Availability: PostGIS 1.0.0RC1. Requires PostgreSQL 7.3 or higher.

[참고]

1.3.4 미만 버전에서 이 함수에 만곡 도형(curve)을 담고 있는 도형을 입력하면 충돌이 일어났습니다. 1.3.4 버전부터 이 버그가 해결됐습니다.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

This function supports 3d and will not drop the z-index.

예시

Dump the components of geometries stored in a table.

Code
SELECT sometable.field1,
       (ST_Dump(sometable.geom)).geom AS geom
FROM sometable;

Break a CompoundCurve into its constituent LineStrings and CircularStrings.

Code
SELECT a.geom, ST_HasArc(a.geom)
  FROM ( SELECT (ST_Dump(p_geom)).geom AS geom
         FROM (SELECT 'COMPOUNDCURVE(CIRCULARSTRING(0 0,1 1,1 0),(1 0,0 1))'::geometry AS p_geom) AS b
        ) AS a;
래스터 출력
st_asewkt          | st_hasarc
-----------------------------+----------
 CIRCULARSTRING(0 0,1 1,1 0) | t
 LINESTRING(1 0,0 1)         | f
(2 rows)
Figure
Geometry figure for visual-st-dump-01

This example breaks a PolyhedralSurface into its faces.

Code
SELECT (a.p_geom).path[1] As path,(a.p_geom).geom As geom_ewkt
  FROM (SELECT ST_Dump('POLYHEDRALSURFACE(
((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)),
((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)),((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)),((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)),
((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)),((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1))
)' ) AS p_geom )  AS a;
래스터 출력
path |                geom_ewkt
------+------------------------------------------
    1 | POLYGON((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0))
    2 | POLYGON((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0))
    3 | POLYGON((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0))
    4 | POLYGON((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0))
    5 | POLYGON((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0))
    6 | POLYGON((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1))
Figure
Geometry figure for visual-st-dump-02

This example uses a TIN geometry.

Code
SELECT (g.gdump).path,(g.gdump).geom as wkt
  FROM
    (SELECT
       ST_Dump('TIN (((
                0 0 0,
                0 0 1,
                0 1 0,
                0 0 0
            )),((
                0 0 0,
                0 1 0,
                1 1 0,
                0 0 0
            ))
            )' ) AS gdump
    ) AS g;
래스터 출력
path |                 wkt
------+-------------------------------------
 {1}  | TRIANGLE((0 0 0,0 0 1,0 1 0,0 0 0))
 {2}  | TRIANGLE((0 0 0,0 1 0,1 1 0,0 0 0))
Figure
Geometry figure for visual-st-dump-03

제목

ST_DumpPoints — 도형의 내용을 요약한 텍스트를 반환합니다.

요약

geometry_dump[] ST_DumpPoints(geometry geom);

설명

A set-returning function (SRF) that extracts the coordinates (vertices) of a geometry. It returns a set of geometry_dump rows, each containing a geometry (geom field) and an array of integers (path field).

  • the geom field POINTs represent the coordinates of the supplied geometry.

  • the path field (an integer[]) is an index enumerating the coordinate positions in the elements of the supplied geometry. The indices are 1-based. For example, for a LINESTRING the paths are {i} where i is the nth coordinate in the LINESTRING. For a POLYGON the paths are {i,j} where i is the ring number (1 is outer; inner rings follow) and j is the coordinate position in the ring.

To obtain a single geometry containing the coordinates use ST_Points.

Enhanced: 2.1.0 Faster speed. Reimplemented as native-C.

개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다.

1.5.0 버전부터 사용할 수 있습니다.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

This function supports 3d and will not drop the z-index.

예시

Explode a table of LineStrings into their vertices.

Code
SELECT edge_id, (dp).path[1] As index,(dp).geom As wktnode
FROM (SELECT 1 As edge_id,
    ST_DumpPoints(ST_GeomFromText('LINESTRING(1 2,3 4,10 10)')) AS dp
     UNION ALL
     SELECT 2 As edge_id,
    ST_DumpPoints(ST_GeomFromText('LINESTRING(3 5,5 6,9 10)')) AS dp
   ) As foo;
래스터 출력
edge_id | index |    wktnode
---------+-------+--------------
       1 |     1 | POINT(1 2)
       1 |     2 | POINT(3 4)
       1 |     3 | POINT(10 10)
       2 |     1 | POINT(3 5)
       2 |     2 | POINT(5 6)
       2 |     3 | POINT(9 10)
Figure
Geometry figure for visual-st-dumppoints-01

Dump every vertex from a mixed GeometryCollection.

Code
SELECT path,geom
FROM (
  SELECT (ST_DumpPoints(g.geom)).*
  FROM
    (SELECT
       'GEOMETRYCOLLECTION(
          POINT ( 0 1 ),
          LINESTRING ( 0 3,3 4 ),
          POLYGON (( 2 0,2 3,0 2,2 0 )),
          POLYGON (( 3 0,3 3,6 3,6 0,3 0 ),
                   ( 5 1,4 2,5 2,5 1 )),
          MULTIPOLYGON (
                  (( 0 5,0 8,4 8,4 5,0 5 ),
                   ( 1 6,3 6,2 7,1 6 )),
                  (( 5 4,5 8,6 7,5 4 ))
          )
        )'::geometry AS geom
    ) AS g
  ) j;
래스터 출력
path    | st_astext
-----------+------------
 {1,1}     | POINT(0 1)
 {2,1}     | POINT(0 3)
 {2,2}     | POINT(3 4)
 {3,1,1}   | POINT(2 0)
 {3,1,2}   | POINT(2 3)
 {3,1,3}   | POINT(0 2)
 {3,1,4}   | POINT(2 0)
 {4,1,1}   | POINT(3 0)
 {4,1,2}   | POINT(3 3)
 {4,1,3}   | POINT(6 3)
 {4,1,4}   | POINT(6 0)
 {4,1,5}   | POINT(3 0)
 {4,2,1}   | POINT(5 1)
 {4,2,2}   | POINT(4 2)
 {4,2,3}   | POINT(5 2)
 {4,2,4}   | POINT(5 1)
 {5,1,1,1} | POINT(0 5)
 {5,1,1,2} | POINT(0 8)
 {5,1,1,3} | POINT(4 8)
 {5,1,1,4} | POINT(4 5)
 {5,1,1,5} | POINT(0 5)
 {5,1,2,1} | POINT(1 6)
 {5,1,2,2} | POINT(3 6)
 {5,1,2,3} | POINT(2 7)
 {5,1,2,4} | POINT(1 6)
 {5,2,1,1} | POINT(5 4)
 {5,2,1,2} | POINT(5 8)
 {5,2,1,3} | POINT(6 7)
 {5,2,1,4} | POINT(5 4)
(29 rows)

Collect the dumped vertices to visualize them over the source geometry.

Code
WITH source(geom) AS (VALUES (
  'GEOMETRYCOLLECTION(
     POINT (0 1),
     LINESTRING (0 3,3 4),
     POLYGON ((2 0,2 3,0 2,2 0)),
     POLYGON ((3 0,3 3,6 3,6 0,3 0),(5 1,4 2,5 2,5 1)),
     MULTIPOLYGON (((0 5,0 8,4 8,4 5,0 5),(1 6,3 6,2 7,1 6)),
                   ((5 4,5 8,6 7,5 4))))'::geometry
))
SELECT ST_Collect((dp).geom ORDER BY (dp).path) AS vertices
FROM source
CROSS JOIN LATERAL ST_DumpPoints(source.geom) AS dp;
래스터 출력
MULTIPOINT((0 1),(0 3),(3 4),(2 0),(2 3),(0 2),(2 0),(3 0),(3 3),(6 3),(6 0),(3 0),(5 1),(4 2),(5 2),(5 1),(0 5),(0 8),(4 8),(4 5),(0 5),(1 6),(3 6),(2 7),(1 6),(5 4),(5 8),(6 7),(5 4))
Figure
Geometry figure for visual-st-dumppoints-03

This example uses a cube represented as a PolyhedralSurface.

Code
SELECT (g.gdump).path,(g.gdump).geom as wkt
  FROM
    (SELECT
       ST_DumpPoints('POLYHEDRALSURFACE( ((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)),
((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)),((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)),
((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)),
((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)),((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1)) )' ) AS gdump
    ) AS g;
래스터 출력
path   |     wkt
---------+--------------
 {1,1,1} | POINT(0 0 0)
 {1,1,2} | POINT(0 0 1)
 {1,1,3} | POINT(0 1 1)
 {1,1,4} | POINT(0 1 0)
 {1,1,5} | POINT(0 0 0)
 {2,1,1} | POINT(0 0 0)
 {2,1,2} | POINT(0 1 0)
 {2,1,3} | POINT(1 1 0)
 {2,1,4} | POINT(1 0 0)
 {2,1,5} | POINT(0 0 0)
 {3,1,1} | POINT(0 0 0)
 {3,1,2} | POINT(1 0 0)
 {3,1,3} | POINT(1 0 1)
 {3,1,4} | POINT(0 0 1)
 {3,1,5} | POINT(0 0 0)
 {4,1,1} | POINT(1 1 0)
 {4,1,2} | POINT(1 1 1)
 {4,1,3} | POINT(1 0 1)
 {4,1,4} | POINT(1 0 0)
 {4,1,5} | POINT(1 1 0)
 {5,1,1} | POINT(0 1 0)
 {5,1,2} | POINT(0 1 1)
 {5,1,3} | POINT(1 1 1)
 {5,1,4} | POINT(1 1 0)
 {5,1,5} | POINT(0 1 0)
 {6,1,1} | POINT(0 0 1)
 {6,1,2} | POINT(1 0 1)
 {6,1,3} | POINT(1 1 1)
 {6,1,4} | POINT(0 1 1)
 {6,1,5} | POINT(0 0 1)
(30 rows)

This example uses a Triangle geometry.

Code
SELECT (g.gdump).path,(g.gdump).geom as wkt
  FROM
    (SELECT
       ST_DumpPoints('TRIANGLE ((
                0 0,
                0 9,
                9 0,
                0 0
            ))' ) AS gdump
    ) AS g;
래스터 출력
path |    wkt
------+------------
 {1,1} | POINT(0 0)
 {1,2} | POINT(0 9)
 {1,3} | POINT(9 0)
 {1,4} | POINT(0 0)
Figure
Geometry figure for visual-st-dumppoints-05

This example uses a TIN geometry.

Code
SELECT (g.gdump).path,(g.gdump).geom as wkt
  FROM
    (SELECT
       ST_DumpPoints('TIN (((
                0 0 0,
                0 0 1,
                0 1 0,
                0 0 0
            )),((
                0 0 0,
                0 1 0,
                1 1 0,
                0 0 0
            ))
            )' ) AS gdump
    ) AS g;
래스터 출력
path   |     wkt
---------+--------------
 {1,1,1} | POINT(0 0 0)
 {1,1,2} | POINT(0 0 1)
 {1,1,3} | POINT(0 1 0)
 {1,1,4} | POINT(0 0 0)
 {2,1,1} | POINT(0 0 0)
 {2,1,2} | POINT(0 1 0)
 {2,1,3} | POINT(1 1 0)
 {2,1,4} | POINT(0 0 0)
(8 rows)
Figure
Geometry figure for visual-st-dumppoints-06

제목

ST_DumpSegments — 도형의 내용을 요약한 텍스트를 반환합니다.

요약

geometry_dump[] ST_DumpSegments(geometry geom);

설명

A set-returning function (SRF) that extracts the segments of a geometry. It returns a set of geometry_dump rows, each containing a geometry (geom field) and an array of integers (path field).

  • the geom field LINESTRINGs represent the linear segments of the supplied geometry, while the CIRCULARSTRINGs represent the arc segments.

  • the path field (an integer[]) is an index enumerating the segment start point positions in the elements of the supplied geometry. The indices are 1-based. For example, for a LINESTRING the paths are {i} where i is the nth segment start point in the LINESTRING. For a POLYGON the paths are {i,j} where i is the ring number (1 is outer; inner rings follow) and j is the segment start point position in the ring.

Availability: 3.2.0

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

This function supports 3d and will not drop the z-index.

표준 예시

Code
SELECT path,geom
FROM (
    SELECT (ST_DumpSegments(g.geom)).*
    FROM (SELECT 'GEOMETRYCOLLECTION(
    LINESTRING(1 1,3 3,4 4),
    POLYGON((5 5,6 6,7 7,5 5))
)'::geometry AS geom
        ) AS g
) j;
래스터 출력
path   │      st_astext
---------------------------------
 {1,1}   │ LINESTRING(1 1,3 3)
 {1,2}   │ LINESTRING(3 3,4 4)
 {2,1,1} │ LINESTRING(5 5,6 6)
 {2,1,2} │ LINESTRING(6 6,7 7)
 {2,1,3} │ LINESTRING(7 7,5 5)
(5 rows)
Figure
Geometry figure for visual-st-dumpsegments-01

다면체 표면, TIN 및 삼각형 예시

This example uses a Triangle geometry.

Code
SELECT path,geom
FROM (
    SELECT (ST_DumpSegments(g.geom)).*
    FROM (SELECT 'TRIANGLE((
        0 0,
        0 9,
        9 0,
        0 0
    ))'::geometry AS geom
        ) AS g
) j;
래스터 출력
path  │      st_astext
 ---------------------------------
 {1,1} │ LINESTRING(0 0,0 9)
 {1,2} │ LINESTRING(0 9,9 0)
 {1,3} │ LINESTRING(9 0,0 0)
(3 rows)
Figure
Geometry figure for visual-st-dumpsegments-02

This example uses a TIN geometry.

Code
SELECT path,geom
FROM (
    SELECT (ST_DumpSegments(g.geom)).*
    FROM (SELECT 'TIN(((
        0 0 0,
        0 0 1,
        0 1 0,
        0 0 0
    )),((
        0 0 0,
        0 1 0,
        1 1 0,
        0 0 0
    ))
    )'::geometry AS geom
        ) AS g
) j;
래스터 출력
path   │        st_asewkt
  ---------------------------------
 {1,1,1} │ LINESTRING(0 0 0,0 0 1)
 {1,1,2} │ LINESTRING(0 0 1,0 1 0)
 {1,1,3} │ LINESTRING(0 1 0,0 0 0)
 {2,1,1} │ LINESTRING(0 0 0,0 1 0)
 {2,1,2} │ LINESTRING(0 1 0,1 1 0)
 {2,1,3} │ LINESTRING(1 1 0,0 0 0)
(6 rows)
Figure
Geometry figure for visual-st-dumpsegments-03

제목

ST_DumpRings — Returns a set of geometry_dump rows for the exterior and interior rings of a Polygon.

요약

geometry_dump[] ST_DumpRings(geometry a_polygon);

설명

A set-returning function (SRF) that extracts the rings of a polygon. It returns a set of geometry_dump rows, each containing a geometry (geom field) and an array of integers (path field).

The geom field contains each ring as a POLYGON. The path field is an integer array of length 1 containing the polygon ring index. The exterior ring (shell) has index 0. The interior rings (holes) have indices of 1 and higher.

[참고]

This only works for POLYGON geometries, not MULTIPOLYGONs. Use ST_Dump to extract polygon elements from polygonal geometries: ST_DumpRings((ST_Dump(geom)).geom )

Availability: PostGIS 1.1.3. Requires PostgreSQL 7.3 or higher.

This function supports 3d and will not drop the z-index.

예시

Extracting all rings as polygons.

Code
SELECT polyTable.field1, polyTable.field1,
      (ST_DumpRings(polyTable.geom)).geom As geom
FROM polyTable

Extracting shell and holes from a polygon.

Code
SELECT path,geom As geom
FROM ST_DumpRings('POLYGON ((1 9,9 9,9 1,1 1,1 9),(2 2,2 3,3 3,3 2,2 2),(4 2,4 4,6 4,6 2,4 2))');
래스터 출력
path |              geom
------+--------------------------------
 {0}  | POLYGON((1 9,9 9,9 1,1 1,1 9))
 {1}  | POLYGON((2 2,2 3,3 3,3 2,2 2))
 {2}  | POLYGON((4 2,4 4,6 4,6 2,4 2))
Figure
Geometry figure for visual-st-dumprings-01

Finding interior rings which lie close to the exterior ring.

Code
WITH poly AS (
  SELECT 'POLYGON ((
      0 0, 10 0, 10 10, 0 10, 0 0
    ), (
      1 1, 1 2, 2 2, 2 1, 1 1
    ), (
      8.5 1, 8.5 2, 9.5 2, 9.5 1, 8.5 1
    ))'::geometry AS geom
),
rings AS (
  SELECT d.path[1] AS ring_no,
         ST_Boundary(d.geom) AS ring_geom
  FROM poly
  CROSS JOIN LATERAL ST_DumpRings(poly.geom) AS d
),
shell AS (
  SELECT ring_geom
  FROM rings
  WHERE ring_no = 0
),
holes AS (
  SELECT ring_no, ring_geom
  FROM rings
  WHERE ring_no > 0
)
SELECT h.ring_no,
       ST_Normalize(ST_Multi(ST_LineMerge(
         ST_Intersection(ST_Buffer(s.ring_geom, 1.0), h.ring_geom)
       ))) AS close_part
FROM shell AS s
JOIN holes AS h
  ON ST_DWithin(s.ring_geom, h.ring_geom, 1.0);
래스터 출력
ring_no |                   close_part
---------+-------------------------------------------------
       1 | MULTILINESTRING((1 2,1 1,2 1))
       2 | MULTILINESTRING((8.5 1,9 1,9.5 1,9.5 2,9 2))
Figure
Geometry figure for visual-st-dumprings-02

제목

ST_EndPoint — Returns the last point of a LineString, CircularLineString, or NURBSCurve.

요약

geometry ST_EndPoint(geometry g);

설명

Returns the last point of a LINESTRING, CIRCULARLINESTRING, or NURBSCURVE geometry as a POINT. Returns NULL if the input is not a LINESTRING, CIRCULARLINESTRING, or NURBSCURVE.

This method implements the SQL/MM specification. SQL-MM 3: 7.1.4

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

변경 사항: 2.0.0 버전부터 단일 도형 멀티라인스트링을 지원하지 않습니다. PostGIS 예전 버전이라면 단일 라인 멀티라인스트링을 입력받는 경우 시작점을 반환했을 겁니다. 2.0.0 버전은 다른 모든 멀티라인스트링처럼 NULL을 반환할 뿐입니다. 구식 습성은 문서화되지 않은 기능이지만, 사용자 데이터를 라인스트링으로 저장했다고 가정한 사용자의 경우 현재 2.0 버전에서 NULL이 반환될 수도 있습니다.

예시

End point of a LineString

Code
SELECT ST_EndPoint('LINESTRING(1 1,2 2,3 3)'::geometry);
래스터 출력
POINT(3 3)
Figure
Geometry figure for visual-st-endpoint-01

End point of a non-LineString is NULL

Code
SELECT ST_EndPoint('POINT(1 1)'::geometry) IS NULL AS is_null;
래스터 출력
t

End point of a 3D LineString

3D endpoint.

Code
SELECT ST_EndPoint('LINESTRING(1 1 2,1 2 3,0 0 5)');
래스터 출력
POINT(0 0 5)
Figure
Geometry figure for visual-st-endpoint-03

ST_LineString 또는 ST_CircularString 값에 있는 포인트의 개수를 반환합니다.

Code
SELECT ST_EndPoint('CIRCULARSTRING(5 2,-3 2,-2 1,-4 2,6 3)'::geometry);
래스터 출력
POINT(6 3)
Figure
Geometry figure for visual-st-endpoint-04

End point of a NURBSCurve

Code
SELECT ST_EndPoint('NURBSCURVE(2, (0 0, 1 1, 2 0))'::geometry);
래스터 출력
POINT(2 0)
Figure
Geometry figure for visual-st-endpoint-05

제목

ST_Envelope — 주어진 도형의 이중 정밀도(double precision; float8) 경계 상자를 표현하는 도형을 반환합니다.

요약

geometry ST_Envelope(geometry g1);

설명

주어진 도형에 대해 float8 형 최소치 경계 상자를 도형으로 반환합니다. 해당 폴리곤은 경계 상자의 꼭짓점 포인트들로 정의됩니다((MINX, MINY), (MINX, MAXY), (MAXX, MAXY), (MAXX, MINY), (MINX, MINY)). (PostGIS는 ZMIN/ZMAX 좌표도 추가할 것입니다.)

차원이 낮은 (수직 라인, 포인트) 경우 POLYGON 보다 낮은 차원의, 예를 들어 POINT 또는 LINESTRING 도형을 반환할 것입니다.

1.5.0 버전부터 사용할 수 있으며, float4 형 대신 이중 정밀도 형으로 출력하도록 변경되었습니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.1

This method implements the SQL/MM specification. SQL-MM 3: 5.1.19

예시

Code
SELECT ST_Envelope('POINT(1 3)'::geometry);
래스터 출력
POINT(1 3)
Figure
Geometry figure for visual-st-envelope-01
Code
SELECT ST_Envelope('LINESTRING(0 0,1 3)'::geometry);
래스터 출력
POLYGON((0 0,0 3,1 3,1 0,0 0))
Figure
Geometry figure for visual-st-envelope-02
Code
SELECT ST_Envelope('POLYGON((0 0,0 1,1.0000001 1,1.0000001 0,0 0))'::geometry);
래스터 출력
POLYGON((0 0,0 1,1.0000001 1,1.0000001 0,0 0))
Figure
Geometry figure for visual-st-envelope-03
Code
SELECT ST_Envelope('POLYGON((0 0,0 1,1.0000000001 1,1.0000000001 0,0 0))'::geometry);
래스터 출력
POLYGON((0 0,0 1,1.0000000001 1,1.0000000001 0,0 0))
Figure
Geometry figure for visual-st-envelope-04
Code
SELECT Box3D(geom), Box2D(geom), ST_Envelope(geom) As envelopewkt
    FROM (SELECT 'POLYGON((0 0,0 1000012333334.34545678,1.0000001 1,1.0000001 0,0 0))'::geometry As geom) As foo;

Envelope of a point and LineString.

Code
SELECT ST_Envelope(ST_Collect(
            'LINESTRING(55 75,125 150)',
            ST_Point(20, 80)
            )) As wktenv;
래스터 출력
POLYGON((20 75,20 150,125 150,125 75,20 75))
Figure
Geometry figure for visual-st-envelope-05

제목

ST_ExteriorRing — 폴리곤 도형의 내곽 고리의 개수를 반환합니다.

요약

geometry ST_ExteriorRing(geometry a_polygon);

설명

POLYGON 도형의 외곽 고리(exterior ring)를 표현하는 라인스트링을 반환합니다. 도형이 폴리곤이 아닌 경우 NULL을 반환합니다.

[참고]

이 함수는 멀티폴리곤을 입력받지 못 합니다. 멀티폴리곤의 경우 ST_Dump 함수와 결합해서 이용하십시오.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. 2.1.5.1

This method implements the SQL/MM specification. SQL-MM 3: 8.2.3, 8.3.3

This function supports 3d and will not drop the z-index.

예시

Extract the exterior ring from a Polygon with a hole.

Code
WITH input(geom) AS (VALUES (
  'POLYGON((0 0,2 9,9 11,14 6,12 0,0 0),(4 3,9 3,10 7,5 8,4 3))'::geometry
))
SELECT geom AS input_polygon,
       ST_ExteriorRing(geom) AS exterior_ring
FROM input;
래스터 출력
POLYGON((0 0,2 9,9 11,14 6,12 0,0 0),(4 3,9 3,10 7,5 8,4 3)) | LINESTRING(0 0,2 9,9 11,14 6,12 0,0 0)
Figure
Geometry figure for visual-st-exteriorring-01

For a MultiPolygon, dump the component Polygons before extracting their exterior rings. Both component Polygons in this example have holes.

Code
WITH input(geom) AS (VALUES (
  'MULTIPOLYGON(
    ((0 0,2 9,9 11,14 6,12 0,0 0),(4 3,9 3,10 7,5 8,4 3)),
    ((18 1,18 10,29 10,31 4,25 0,18 1),(21 3,25 2,28 5,25 8,21 7,21 3))
  )'::geometry
))
SELECT part.geom AS input_polygon,
       ST_ExteriorRing(part.geom) AS exterior_ring
FROM input
CROSS JOIN LATERAL ST_Dump(geom) AS part
ORDER BY part.path;
래스터 출력
POLYGON((0 0,2 9,9 11,14 6,12 0,0 0),(4 3,9 3,10 7,5 8,4 3)) | LINESTRING(0 0,2 9,9 11,14 6,12 0,0 0)
POLYGON((18 1,18 10,29 10,31 4,25 0,18 1),(21 3,25 2,28 5,25 8,21 7,21 3)) | LINESTRING(18 1,18 10,29 10,31 4,25 0,18 1)
Figure
Geometry figure for visual-st-exteriorring-02

Extract exterior rings from a table of Polygons.

Code
SELECT gid, ST_ExteriorRing(geom) AS ering
FROM sometable;

For a table of MultiPolygons, dump the component Polygons and collect their exterior rings into a MultiLineString.

Code
SELECT gid, ST_Collect(ST_ExteriorRing(geom)) AS erings
FROM (
  SELECT gid, (ST_Dump(geom)).geom AS geom
  FROM sometable
) AS foo
GROUP BY gid;

This example returns the 3D exterior ring of a Polygon.

Code
SELECT ST_ExteriorRing(
    'POLYGON Z ((0 0 5,4 0 5,4 3 5,0 3 5,0 0 5))'
    );
래스터 출력
LINESTRING(0 0 5,4 0 5,4 3 5,0 3 5,0 0 5)
Figure
Geometry figure for visual-st-exteriorring-03

제목

ST_GeometryN — ST_Geometry 값의 도형 유형을 반환합니다.

요약

geometry ST_GeometryN(geometry geomA, integer n);

설명

Returns the 1-based Nth element of a GEOMETRYCOLLECTION, MULTIPOINT, MULTILINESTRING, MULTICURVE, or MULTIPOLYGON. For a unitary geometry, including a TIN or PolyhedralSurface, an index of 1 returns the input geometry and any other index returns NULL. Use ST_PatchN and ST_NumPatches to access and count the faces of a TIN or PolyhedralSurface.

[참고]

0.8.0 버전부터 인덱스는 OGC 사양을 따라 1-기반입니다. 예전 버전은 대신 0-기반 인덱스를 시행했습니다.

[참고]

모든 도형들을 추출하고자 한다면 ST_Dump 함수가 더 효율적이며, 단일 도형에 대해서도 작동할 것입니다.

개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다.

변경 사항: 2.0.0 미만 버전은 단일 도형에 대해 NULL을 반환했을 겁니다. 2.0.0 버전부터 ST_GeometryN(..,1) 경우에 대한 도형을 반환하도록 변경됐습니다.

Changed: 3.6.0 TIN and PolyhedralSurface are treated as unitary geometries and are not decomposed into patches; use ST_PatchN to access faces.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1.

This method implements the SQL/MM specification. SQL-MM 3: 9.1.5

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

표준 예시

Extracting a subset of points from a 3D multipoint.

Code
SELECT n, ST_GeometryN(geom, n) As geomewkt
FROM (
VALUES
    (1, 'MULTIPOINT((1 2 7), (3 4 7), (5 6 7), (8 9 10))'::geometry ),
    (2, 'MULTICURVE(CIRCULARSTRING(2.5 2.5,4.5 2.5, 3.5 3.5), (10 11, 12 11))'::geometry )
    ) As foo(id, geom)
    CROSS JOIN generate_series(1,100) n
WHERE n <= ST_NumGeometries(geom)
ORDER BY id, n;
래스터 출력
 n |               geomewkt
---+-----------------------------------------
 1 | POINT(1 2 7)
 2 | POINT(3 4 7)
 3 | POINT(5 6 7)
 4 | POINT(8 9 10)
 1 | CIRCULARSTRING(2.5 2.5,4.5 2.5,3.5 3.5)
 2 | LINESTRING(10 11,12 11)
Figure
Geometry figure for visual-st-geometryn-01

Extracting all geometries (useful when you want to assign an id).

Code
SELECT gid, n, ST_GeometryN(geom, n)
FROM sometable CROSS JOIN generate_series(1,100) n
WHERE n <= ST_NumGeometries(geom);

다면체 표면, TIN 및 삼각형 예시

A PolyhedralSurface or TIN is treated as a single geometry, not as a collection of faces. ST_GeometryN does not decompose the surface into patches, so an index greater than 1 returns NULL. Use ST_PatchN and ST_NumPatches to access individual faces.

This example requests the third element of a PolyhedralSurface.

Code
SELECT ST_GeometryN(p_geom, 3) As geom_ewkt
  FROM (SELECT 'POLYHEDRALSURFACE(
((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)),
((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)),
((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)),
((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)),
((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)),
((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1))
)'::geometry  AS p_geom )  AS a;
래스터 출력
NULL
Figure
Geometry figure for visual-st-geometryn-02

This example requests the second element of a TIN.

Code
SELECT ST_GeometryN(geom, 2) as wkt
  FROM
    (SELECT
       'TIN (((
                0 0 0,
                0 0 1,
                0 1 0,
                0 0 0
            )),((
                0 0 0,
                0 1 0,
                1 1 0,
                0 0 0
            ))
            )'::geometry  AS geom
    ) AS g;
래스터 출력
NULL
Figure
Geometry figure for visual-st-geometryn-03

제목

ST_GeometryType — ST_Geometry 값의 도형 유형을 반환합니다.

요약

text ST_GeometryType(geometry g1);

설명

도형의 유형을 'ST_LineString', 'ST_Polygon', 'ST_MultiPolygon' 등과 같은 스트링으로 반환합니다. 이 함수는 도형의 단위가 설정돼 있는지 알려주지 않는 것은 물론, 반환된 결과물이 스트링이며 접두사 ST가 달린다는 점에서도 GeometryType(geometry) 함수와는 다릅니다.

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다.

This method implements the SQL/MM specification. SQL-MM 3: 5.1.4

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

예시

Code
SELECT ST_GeometryType('LINESTRING(77.29 29.07,77.42 29.26,77.27 29.31,77.29 29.07)'::geometry);
래스터 출력
ST_LineString
Code
SELECT ST_GeometryType('POLYHEDRALSURFACE( ((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)),
((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)),((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)),
((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)),
((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)),((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1)) )'::geometry);
래스터 출력
ST_PolyhedralSurface
Code
SELECT ST_GeometryType(geom) AS result
FROM
  (SELECT
     'TIN (((
              0 0 0,
              0 0 1,
              0 1 0,
              0 0 0
          )),((
              0 0 0,
              0 1 0,
              1 1 0,
              0 0 0
          ))
          )'::geometry AS geom
  ) AS g;
래스터 출력
ST_Tin

제목

ST_HasArc — Tests if a geometry contains a circular arc

요약

boolean ST_HasArc(geometry geomA);

설명

해당 도형이 텅 빈 도형 집합, 폴리곤, 포인트 등인 경우 TRUE 를 반환합니다.

1.2.2 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

예시

Code
SELECT ST_HasArc(ST_Collect('LINESTRING(1 2,3 4,5 6)', 'CIRCULARSTRING(1 1,2 3,4 5,6 7,5 6)'));
래스터 출력
t
Figure
Geometry figure for visual-st-hasarc-01

제목

ST_InteriorRingN — 폴리곤 도형의 내곽 고리의 개수를 반환합니다.

요약

geometry ST_InteriorRingN(geometry a_polygon, integer n);

설명

폴리곤 도형의 N번째 내곽 라인스트링 고리를 반환합니다. 도형이 폴리곤이 아니거나 주어진 N이 범위(range)를 벗어난 경우 NULL을 반환합니다.

[참고]

이 함수는 멀티폴리곤을 입력받지 못 합니다. 멀티폴리곤의 경우 ST_Dump 함수와 결합해서 이용하십시오.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1.

This method implements the SQL/MM specification. SQL-MM 3: 8.2.6, 8.3.5

This function supports 3d and will not drop the z-index.

예시

Code
WITH data AS (
  SELECT ST_BuildArea(ST_Collect(
    ST_Buffer(ST_Point(1, 2), 20, 3),
    ST_Buffer(ST_Point(1, 2), 10, 3)
  )) AS geom
)
SELECT geom AS input_polygon,
       ST_InteriorRingN(geom, 1) AS ring
FROM data;
래스터 출력
POLYGON((21 2,18.320508075688775 -7.999999999999998,11.000000000000002 -15.320508075688771,1 -18,-8.999999999999996 -15.320508075688775,-16.32050807568877 -8.000000000000007,-19 2,-16.320508075688778 11.999999999999995,-9.000000000000009 19.320508075688767,1 22,10.999999999999986 19.32050807568878,18.320508075688767 12.000000000000009,21 2),(11 2,9.660254037844384 7.000000000000004,5.999999999999993 10.66025403784439,1 12,-4.000000000000004 10.660254037844384,-7.660254037844389 6.999999999999997,-9 2,-7.660254037844386 -3.000000000000004,-3.999999999999998 -6.660254037844387,1 -8,6.000000000000001 -6.660254037844386,9.660254037844387 -2.999999999999999,11 2)) | LINESTRING(11 2,9.660254037844384 7.000000000000004,5.999999999999993 10.66025403784439,1 12,-4.000000000000004 10.660254037844384,-7.660254037844389 6.999999999999997,-9 2,-7.660254037844386 -3.000000000000004,-3.999999999999998 -6.660254037844387,1 -8,6.000000000000001 -6.660254037844386,9.660254037844387 -2.999999999999999,11 2)
Figure
Geometry figure for visual-st-interiorringn-01

제목

ST_NumCurves — Return the number of component curves in a CompoundCurve.

요약

integer ST_NumCurves(geometry a_compoundcurve);

설명

Return the number of component curves in a CompoundCurve, zero for an empty CompoundCurve, or NULL for a non-CompoundCurve input.

This method implements the SQL/MM specification. SQL-MM 3: 8.2.6, 8.3.5

This function supports 3d and will not drop the z-index.

예시

This CompoundCurve contains three component curves.

Code
SELECT ST_NumCurves('COMPOUNDCURVE(
    (2 2,2.5 2.5),
    CIRCULARSTRING(2.5 2.5,4.5 2.5,3.5 3.5),
    (3.5 3.5,2.5 4.5,3 5,2 2)
  )');
래스터 출력
3
Figure
Geometry figure for visual-st-numcurves-01

An empty CompoundCurve has no component curves.

Code
SELECT ST_NumCurves('COMPOUNDCURVE EMPTY');
래스터 출력
0

제목

ST_CurveN — Returns the Nth component curve geometry of a CompoundCurve.

요약

geometry ST_CurveN(geometry a_compoundcurve, integer index);

설명

Returns the Nth component curve geometry of a CompoundCurve. The index starts at 1. Returns NULL if the geometry is not a CompoundCurve or the index is out of range.

This method implements the SQL/MM specification. SQL-MM 3: 8.2.6, 8.3.5

This function supports 3d and will not drop the z-index.

예시

This example extracts the second component curve, a CircularString, from a CompoundCurve.

Code
SELECT ST_CurveN(
  'COMPOUNDCURVE(
    (0 0,2 0),
    CIRCULARSTRING(2 0,3 1,4 0),
    (4 0,6 1)
  )',
  2) AS curve;
래스터 출력
CIRCULARSTRING(2 0,3 1,4 0)
Figure
Geometry figure for visual-st-curven-01

제목

ST_IsClosed — LINESTRING 의 시작점과 종단점이 일치하는 경우 TRUE 를 반환합니다. 다면체 표면이 닫혀 (부피를 가지고) 있는 경우 TRUE 를 반환합니다.

요약

boolean ST_IsClosed(geometry g);

설명

LINESTRING 의 시작점과 종단점이 일치하는 경우 TRUE 를 반환합니다. 다면체 표면의 경우, 다면체 표면이 면적(열림)을 가지고 있는지 부피(닫힘)를 가지고 있는지 알려줍니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1.

This method implements the SQL/MM specification. SQL-MM 3: 7.1.5, 9.3.3

[참고]

SQL-MM defines the result of ST_IsClosed(NULL) to be 0, while PostGIS returns NULL.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다.

This function supports Polyhedral surfaces.

라인스트링 및 포인트 예시

Code
SELECT ST_IsClosed('LINESTRING(0 0,1 1)'::geometry);
래스터 출력
f
Figure
Geometry figure for visual-st-isclosed-01
Code
SELECT ST_IsClosed('LINESTRING(0 0,0 1,1 1,0 0)'::geometry);
래스터 출력
t
Figure
Geometry figure for visual-st-isclosed-02
Code
SELECT ST_IsClosed('MULTILINESTRING((0 0,0 1,1 1,0 0),(0 0,1 1))'::geometry);
래스터 출력
f
Figure
Geometry figure for visual-st-isclosed-03
Code
SELECT ST_IsClosed('POINT(0 0)'::geometry);
래스터 출력
t
Code
SELECT ST_IsClosed('MULTIPOINT((0 0),(1 1))'::geometry);
래스터 출력
t

다면체 표면 예시

This example uses a cube.

Code
SELECT ST_IsClosed('POLYHEDRALSURFACE( ((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)),
((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)),((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)),
((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)),
((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)),((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1)) )');
래스터 출력
t
Figure
Geometry figure for visual-st-isclosed-06

This example uses the same cube with one side missing.

Code
SELECT ST_IsClosed('POLYHEDRALSURFACE( ((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)),
       ((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)),((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)),
       ((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)),
       ((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)) )');
래스터 출력
f
Figure
Geometry figure for visual-st-isclosed-07

참고

ST_IsRing


제목

ST_IsCollection — 해당 도형이 텅 빈 도형 집합, 폴리곤, 포인트 등인 경우 TRUE 를 반환합니다.

요약

boolean ST_IsCollection(geometry g);

설명

인수의 도형 유형이 다음 가운데 하나일 경우 TRUE 를 반환합니다:

  • GEOMETRYCOLLECTION

  • MULTI{POINT,POLYGON,LINESTRING,CURVE,SURFACE}

  • COMPOUNDCURVE

[참고]

이 함수는 도형의 유형을 분석합니다. 즉 비어 있거나 단일 요소를 담고 있는 집합일 경우에도 TRUE 를 반환할 것이라는 뜻입니다.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

예시

Code
SELECT ST_IsCollection('LINESTRING(0 0,1 1)'::geometry);
래스터 출력
f
Figure
Geometry figure for visual-st-iscollection-01
Code
SELECT ST_IsCollection('MULTIPOINT EMPTY'::geometry);
래스터 출력
t
Code
SELECT ST_IsCollection('MULTIPOINT((0 0))'::geometry);
래스터 출력
t
Code
SELECT ST_IsCollection('MULTIPOINT((0 0),(42 42))'::geometry);
래스터 출력
t
Code
SELECT ST_IsCollection('GEOMETRYCOLLECTION(POINT(0 0))'::geometry);
래스터 출력
t

제목

ST_IsEmpty — Tests if a geometry is empty.

요약

boolean ST_IsEmpty(geometry geomA);

설명

해당 도형이 텅 빈 도형인 경우 TRUE 를 반환합니다. TRUE 인 경우, 해당 도형이 텅 빈 도형 집합, 폴리곤, 포인트 등을 표현한다는 뜻입니다.

[참고]

SQL-MM은 ST_IsEmpty(NULL) 의 결과를 0으로 정의하지만, PostGIS는 NULL 을 반환합니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.1

This method implements the SQL/MM specification. SQL-MM 3: 5.1.7

This method supports Circular Strings and Curves.

변경 사항: PostGIS 2.0.0 미만 버전에서는 ST_GeomFromText('GEOMETRYCOLLECTION(EMPTY)') 를 사용할 수 있었습니다. PostGIS 2.0.0 버전부터, SQL/MM 표준을 더 잘 준수하기 위해 이런 사용법은 금지됐습니다.

예시

Code
SELECT ST_IsEmpty('GEOMETRYCOLLECTION EMPTY'::geometry);
래스터 출력
t
Code
SELECT ST_IsEmpty('POLYGON EMPTY'::geometry);
래스터 출력
t
Code
SELECT ST_IsEmpty('POLYGON((1 2,3 4,5 6,1 2))'::geometry);
래스터 출력
f
Figure
Geometry figure for visual-st-isempty-03
Code
SELECT ST_IsEmpty('POLYGON((1 2,3 4,5 6,1 2))'::geometry) = false;
래스터 출력
t
(1 row)
Figure
Geometry figure for visual-st-isempty-04
Code
SELECT ST_IsEmpty('CIRCULARSTRING EMPTY'::geometry);
래스터 출력
t

제목

ST_IsPolygonCCW — Tests if Polygons have exterior rings oriented counter-clockwise and interior rings oriented clockwise.

요약

boolean ST_IsPolygonCCW(geometry geom);

설명

Returns true if all polygonal components of the input geometry use a counter-clockwise orientation for their exterior ring, and a clockwise direction for all interior rings.

Returns true if the geometry has no polygonal components.

[참고]

Closed linestrings are not considered polygonal components, so you would still get a true return by passing a single closed linestring no matter its orientation.

[참고]

If a polygonal geometry does not use reversed orientation for interior rings (i.e., if one or more interior rings are oriented in the same direction as an exterior ring) then both ST_IsPolygonCW and ST_IsPolygonCCW will return false.

2.2.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

This function supports M coordinates.


제목

ST_IsPolygonCW — Tests if Polygons have exterior rings oriented clockwise and interior rings oriented counter-clockwise.

요약

boolean ST_IsPolygonCW(geometry geom);

설명

Returns true if all polygonal components of the input geometry use a clockwise orientation for their exterior ring, and a counter-clockwise direction for all interior rings.

Returns true if the geometry has no polygonal components.

[참고]

Closed linestrings are not considered polygonal components, so you would still get a true return by passing a single closed linestring no matter its orientation.

[참고]

If a polygonal geometry does not use reversed orientation for interior rings (i.e., if one or more interior rings are oriented in the same direction as an exterior ring) then both ST_IsPolygonCW and ST_IsPolygonCCW will return false.

2.2.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

This function supports M coordinates.


제목

ST_IsRing — Tests if a LineString is closed and simple.

요약

boolean ST_IsRing(geometry g);

설명

Returns TRUE if this LINESTRING is both ST_IsClosed (ST_StartPoint(g) ~= ST_EndPoint(g)) and ST_IsSimple (does not self intersect).

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. 2.1.5.1

This method implements the SQL/MM specification. SQL-MM 3: 7.1.6

[참고]

SQL-MM defines the result of ST_IsRing(NULL) to be 0, while PostGIS returns NULL.

예시

Code
SELECT ST_IsRing(geom), ST_IsClosed(geom), ST_IsSimple(geom)
FROM (SELECT 'LINESTRING(0 0,0 1,1 1,1 0,0 0)'::geometry AS geom) AS foo;
래스터 출력
st_isring | st_isclosed | st_issimple
-----------+-------------+-------------
 t         | t           | t
(1 row)
Figure
Geometry figure for visual-st-isring-01
Code
SELECT ST_IsRing(geom), ST_IsClosed(geom), ST_IsSimple(geom)
FROM (SELECT 'LINESTRING(0 0,0 1,1 0,1 1,0 0)'::geometry AS geom) AS foo;
래스터 출력
st_isring | st_isclosed | st_issimple
-----------+-------------+-------------
 f         | t           | f
(1 row)
Figure
Geometry figure for visual-st-isring-02

제목

ST_IsSimple — 해당 도형이 자체 교차하거나 자체 접촉하는 이례적인 도형 포인트를 가지고 있지 않을 경우 TRUE 를 반환합니다.

요약

boolean ST_IsSimple(geometry geomA);

설명

해당 도형이 자체 교차하거나 자체 접촉하는 이례적인 도형 포인트를 가지고 있지 않을 경우 TRUE 를 반환합니다. 도형 단순성 및 유효성에 대한 OGC의 정의를 더 자세히 알고 싶다면, "OpenGIS의 도형 준수성 확인(Ensuring OpenGIS compliance of geometries)" 을 참조하십시오.

[참고]

SQL-MM은 ST_IsSimple(NULL) 의 결과를 0으로 정의하지만, PostGIS는 NULL 을 반환합니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.1

This method implements the SQL/MM specification. SQL-MM 3: 5.1.8

This function supports 3d and will not drop the z-index.

예시

Code
SELECT ST_IsSimple('POLYGON((1 2,3 4,5 6,1 2))');
래스터 출력
f
Figure
Geometry figure for visual-st-issimple-01
Code
SELECT ST_IsSimple('LINESTRING(1 1,2 2,2 3.5,1 3,1 2,2 1)');
래스터 출력
f
Figure
Geometry figure for visual-st-issimple-02

제목

ST_M — Returns the M coordinate of a Point.

요약

float ST_M(geometry a_point);

설명

포인트의 M 좌표를 반환합니다. M 좌표가 없는 경우 NULL을 반환합니다. 포인트만 입력받을 수 있습니다.

[참고]

이 함수는 (아직) OGC 사양에 들어가지 않지만, 포인트 좌표 추출자(extractor) 함수 목록을 완성하기 위해 이 문서에 작성됐습니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1.

This method implements the SQL/MM specification.

This function supports 3d and will not drop the z-index.

예시

Code
SELECT ST_M('POINT(1 2 3 4)');
래스터 출력
4

제목

ST_MemSize — ST_Geometry 값의 도형 유형을 반환합니다.

요약

integer ST_MemSize(geometry geomA);

설명

ST_Geometry 값의 도형 유형을 반환합니다.

This complements the PostgreSQL built-in database object functions pg_column_size, pg_size_pretty, pg_relation_size, pg_total_relation_size.

[참고]

pg_relation_size which gives the byte size of a table may return byte size lower than ST_MemSize. This is because pg_relation_size does not add toasted table contribution and large geometries are stored in TOAST tables.

pg_total_relation_size 함수는 테이블, TOAST가 적용된 테이블 및 인덱스를 포함합니다.

pg_column_size returns how much space a geometry would take in a column considering compression, so may be lower than ST_MemSize

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

Changed: 2.2.0 name changed to ST_MemSize to follow naming convention.

예시

Compare the memory used by all geometries in a Massachusetts town dataset with the subset for Boston.

Code
SELECT pg_size_pretty(sum(ST_MemSize(geom))) AS totgeomsum,
       pg_size_pretty(sum(CASE WHEN town = 'BOSTON' THEN ST_MemSize(geom) ELSE 0 END)) AS bossum,
       cast(
           sum(CASE WHEN town = 'BOSTON' THEN ST_MemSize(geom) ELSE 0 END) * 100.0
           / sum(ST_MemSize(geom)) AS numeric(10, 2)
       ) AS perbos
FROM towns;
래스터 출력
totgeomsum | bossum | perbos
------------+--------+--------
 1522 kB    | 30 kB  |   1.99
(1 row)

Return the memory size of a CircularString in bytes.

Code
SELECT ST_MemSize('CIRCULARSTRING(220268 150415,220227 150505,220227 150406)'::geometry);
래스터 출력
st_memsize
------------
         80
(1 row)

Calculate the percentage of a table's total size used by geometry data.

Code
SELECT pg_total_relation_size('public.neighborhoods') AS fulltable_size,
       sum(ST_MemSize(geom)) AS geomsize,
       sum(ST_MemSize(geom)) * 100.0
           / pg_total_relation_size('public.neighborhoods') AS pergeom
FROM neighborhoods;
래스터 출력
fulltable_size | geomsize |         pergeom
----------------+----------+--------------------------
         262144 |    96238 | 36.71188354492187500000
(1 row)

제목

ST_NDims — ST_Geometry 값의 좌표 차원을 반환합니다.

요약

integer ST_NDims(geometry g1);

설명

도형의 좌표 차원을 반환합니다. PostGIS는 2 - 2차원 (x,y), 3 - 3차원 (x,y,z), 3 - 단위를 가진 2차원 (x,y,m), 그리고 4 - 단위를 가진 3차원 공간 (x,y,z,m)을 지원합니다.

This function supports 3d and will not drop the z-index.

예시

Code
SELECT ST_NDims('POINT(1 1)') As d2point,
ST_NDims('POINT(1 1 2)') As d3point,
ST_NDims('POINTM(1 1 0.5)') As d2pointm;
래스터 출력
d2point | d3point | d2pointm
---------+---------+----------
       2 |       3 |        3

제목

ST_NPoints — 도형이 가지고 있는 포인트(꼭짓점)의 개수를 반환합니다.

요약

integer ST_NPoints(geometry g1);

설명

도형이 가지고 있는 포인트의 개수를 반환합니다. 모든 도형을 입력받을 수 있습니다.

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다.

[참고]

1.3.4 미만 버전에서 이 함수에 만곡 도형(curve)을 담고 있는 도형을 입력하면 충돌이 일어났습니다. 1.3.4 버전부터 이 버그가 해결됐습니다.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

예시

Count the points in a 2D LineString.

Code
SELECT ST_NPoints('LINESTRING(77.29 29.07,77.42 29.26,77.27 29.31,77.29 29.07)');
래스터 출력
st_npoints
------------
          4
(1 row)

Count the points in a 3D LineString.

Code
SELECT ST_NPoints('LINESTRING(77.29 29.07 1,77.42 29.26 0,77.27 29.31 -1,77.29 29.07 3)');
래스터 출력
st_npoints
------------
          4
(1 row)

제목

ST_NRings — 폴리곤 도형의 내곽 고리의 개수를 반환합니다.

요약

integer ST_NRings(geometry geomA);

설명

도형이 폴리곤 또는 멀티폴리곤인 경우 고리의 개수를 반환합니다. NumInteriorRings 함수와는 달리, 외곽 고리도 개수에 포함시킵니다.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

예시

Code
SELECT ST_NRings(geom) As Nrings, ST_NumInteriorRings(geom) As ninterrings
FROM (SELECT 'POLYGON((1 2,3 4,5 6,1 2))'::geometry As geom) As foo;
래스터 출력
nrings | ninterrings
--------+-------------
      1 |           0
(1 row)
Figure
Geometry figure for visual-st-nrings-01

제목

ST_NumGeometries — 도형이 가지고 있는 포인트의 개수를 반환합니다. 모든 도형을 입력받을 수 있습니다.

요약

integer ST_NumGeometries(geometry geom);

설명

Returns the number of elements in a geometry collection (GEOMETRYCOLLECTION or MULTI*). For non-empty atomic geometries returns 1. For empty geometries returns 0.

개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다.

변경 사항: 2.0.0 미만 버전에서 도형이 집합이나 멀티 유형이 아닐 경우 NULL을 반환했습니다. 2.0.0 버전부터 폴리곤, 라인스트링, 포인트 같은 단일 도형에 대해 1을 반환합니다.

Changed: 3.6.0 TIN and PolyhedralSurface are treated as unitary geometries and return 1; use ST_NumPatches to count faces.

This method implements the SQL/MM specification. SQL-MM 3: 9.1.4

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

This example returns 1; prior versions would have returned NULL.

Code
SELECT ST_NumGeometries('LINESTRING(77.29 29.07,77.42 29.26,77.27 29.31,77.29 29.07)');
래스터 출력
st_numgeometries
------------------
                1
(1 row)

A MultiPoint counts as one geometry within a GeometryCollection.

Code
SELECT ST_NumGeometries('GEOMETRYCOLLECTION(MULTIPOINT((-2 3),(-2 2)),
LINESTRING(5 5,10 10),
POLYGON((-7 4.2,-7.1 5,-7.1 4.3,-7 4.2)))');
래스터 출력
st_numgeometries
------------------
                3
(1 row)

제목

ST_NumInteriorRings — 폴리곤 도형의 내곽 고리의 개수를 반환합니다.

요약

integer ST_NumInteriorRings(geometry a_polygon);

설명

폴리곤 도형의 내곽 고리의 개수를 반환합니다. 도형이 폴리곤이 아닐 경우 NULL을 반환합니다.

This method implements the SQL/MM specification. SQL-MM 3: 8.2.5

변경 사항: 2.0.0 미만 버전에서는 멀티폴리곤을 입력하면 첫 번째 폴리곤의 내곽 고리의 개수를 반환받을 수 있었습니다.

예시

Count the interior rings of a Polygon.

Code
SELECT gid, field1, field2, ST_NumInteriorRings(geom) AS numholes
FROM sometable;

For a MultiPolygon, dump its component Polygons and sum their interior ring counts.

Code
SELECT gid, field1, field2, SUM(ST_NumInteriorRings(geom)) AS numholes
FROM (
    SELECT gid, field1, field2, (ST_Dump(geom)).geom AS geom
    FROM sometable
) AS foo
GROUP BY gid, field1, field2;
            

제목

ST_NumInteriorRing — Returns the number of interior rings (holes) of a Polygon. Alias for ST_NumInteriorRings.

요약

integer ST_NumInteriorRing(geometry a_polygon);

설명

This function is an alias for ST_NumInteriorRings.

1.2.2 버전부터 사용할 수 있습니다.


제목

ST_NumPatches — Returns the number of faces in a PolyhedralSurface or TIN.

요약

integer ST_NumPatches(geometry g1);

설명

Returns the number of faces in a PolyhedralSurface or TIN. Returns NULL for other geometries. Unlike ST_NumGeometries, this function counts individual faces.

2.0.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1.

This method implements the SQL/MM specification. SQL-MM ISO/IEC 13249-3: 8.5

This function supports Polyhedral surfaces.

예시

Code
SELECT ST_NumPatches('POLYHEDRALSURFACE( ((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)),
((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)),((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)),
((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)),
((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)),((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1)) )');
래스터 출력
st_numpatches
---------------
             6
(1 row)

제목

ST_NumPoints — ST_LineString 또는 ST_CircularString 값에 있는 포인트의 개수를 반환합니다.

요약

integer ST_NumPoints(geometry g1);

설명

ST_LineString 또는 ST_CircularString 값에 있는 포인트의 개수를 반환합니다. 1.4 미만 버전에서는 사양서대로 라인스트링만 입력받았습니다. 1.4 버전부터 이 함수는 단순히 라인스트링만이 아닌, 도형의 꼭짓점의 개수를 반환하는 ST_NPoints 함수와 비슷해졌습니다. 쿼리 목적이 다양하고 많은 도형 유형을 사용할 수 있는 ST_NPoints 함수를 대신 사용하는 편이 좋습니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1.

This method implements the SQL/MM specification. SQL-MM 3: 7.2.4

예시

Code
SELECT ST_NumPoints('LINESTRING(77.29 29.07,77.42 29.26,77.27 29.31,77.29 29.07)');
래스터 출력
st_numpoints
--------------
            4
(1 row)

제목

ST_PatchN — Returns the Nth face of a PolyhedralSurface or TIN.

요약

geometry ST_PatchN(geometry geomA, integer n);

설명

Returns the 1-based Nth face of a PolyhedralSurface or TIN. Returns NULL for other geometries or an out-of-range index. Use this function to access faces, because ST_GeometryN treats PolyhedralSurface and TIN as unitary geometries.

[참고]

인덱스는 1-기반입니다.

[참고]

모든 도형들을 추출하고자 한다면 ST_Dump 함수가 더 효율적입니다.

2.0.0 버전부터 사용할 수 있습니다.

This method implements the SQL/MM specification. SQL-MM ISO/IEC 13249-3: 8.5

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

Extract the 2nd face of the polyhedral surface.

Code
SELECT ST_PatchN(geom, 2) As geomewkt
FROM (
VALUES ('POLYHEDRALSURFACE( ((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)),
    ((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)),((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)),
    ((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)),
    ((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)),((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1)) )'::geometry) ) As foo(geom);
래스터 출력
POLYGON((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0))
Figure
Geometry figure for visual-st-patchn-01

제목

ST_PointN — ST_LineString 또는 ST_CircularString 값에 있는 포인트의 개수를 반환합니다.

요약

geometry ST_PointN(geometry a_linestring, integer n);

설명

도형 안에 있는 단일 라인스트링 또는 원형 라인스트링의 N번째 포인트를 반환합니다. 음수 값은 라인스트링의 종단점으로부터 반대로 집계되므로, -1이 마지막 포인트입니다. 도형 안에 라인스트링이 없는 경우 NULL을 반환합니다.

[참고]

Index is 1-based as for OGC specs since version 0.8.0. Backward indexing (negative index) is not in OGC. Previous versions implemented this as 0-based instead.

[참고]

멀티라인스트링 안에 있는 각 라인스트링의 N번째 포인트를 얻고자 할 경우, 이 함수를 ST_Dump 함수와 연결해서 이용하십시오.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1.

This method implements the SQL/MM specification. SQL-MM 3: 7.2.5, 7.3.5

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

변경 사항: 2.0.0 버전부터 단일 도형 멀티라인스트링을 지원하지 않습니다. PostGIS 예전 버전이라면 단일 라인 멀티라인스트링을 입력받는 경우 시작점을 반환했을 겁니다. 2.0.0 버전은 다른 모든 멀티라인스트링처럼 NULL을 반환할 뿐입니다.

변경 사항: 2.3.0 버전부터 음수 인덱스(-1이 마지막 포인트)를 이용할 수 있습니다.

예시

This example extracts all POINT geometries from a LineString.

Code
SELECT ST_PointN(
      column1,
      generate_series(1, ST_NPoints(column1))
   )
FROM ( VALUES ('LINESTRING(0 0,1 1,2 2)'::geometry) ) AS foo;
래스터 출력
POINT(0 0)
 POINT(1 1)
 POINT(2 2)
(3 rows)
Figure
Geometry figure for visual-st-pointn-01

This example uses a CircularString.

Code
SELECT ST_PointN('CIRCULARSTRING(1 2,3 2,1 2)', 2);
래스터 출력
POINT(3 2)
Figure
Geometry figure for visual-st-pointn-02

The index is 1-based. A negative index counts backward from the end of the LineString.

Code
SELECT f
FROM ST_GeomFromText('LINESTRING(0 0 0,1 1 1,2 2 2)') AS g
  CROSS JOIN ST_PointN(g, -2) AS f;
래스터 출력
POINT Z (1 1 1)
Figure
Geometry figure for visual-st-pointn-03

제목

ST_Points — 도형의 모든 좌표들을 담고 있는 멀티포인트를 반환합니다.

요약

geometry ST_Points( geometry geom );

설명

Returns a MultiPoint containing all the coordinates of a geometry. Duplicate points are preserved, including the start and end points of ring geometries. (If desired, duplicate points can be removed by calling ST_RemoveRepeatedPoints on the result).

To obtain information about the position of each coordinate in the parent geometry use ST_DumpPoints.

M and Z coordinates are preserved if present.

This method supports Circular Strings and Curves.

This function supports 3d and will not drop the z-index.

2.3.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT ST_Points('POLYGON Z ((30 10 4,10 30 5,40 40 6,30 10 4))');
래스터 출력
MULTIPOINT Z ((30 10 4),(10 30 5),(40 40 6),(30 10 4))
Figure
Geometry figure for visual-st-points-01

제목

ST_StartPoint — Returns the first point of a LineString, CircularLineString, or NURBSCurve.

요약

geometry ST_StartPoint(geometry geomA);

설명

Returns the first point of a LINESTRING, CIRCULARLINESTRING, or NURBSCURVE geometry as a POINT. For other geometries, returns the first point in coordinate order.

This method implements the SQL/MM specification. SQL-MM 3: 7.1.3

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

Enhanced: 3.2.0 returns a point for all geometries. Prior behavior returns NULLs if input was not a LineString.

변경 사항: 2.0.0 버전부터 단일 도형 멀티라인스트링을 지원하지 않습니다. PostGIS 예전 버전이라면 단일 라인 멀티라인스트링을 입력받는 경우 시작점을 반환했을 겁니다. 2.0.0 버전은 다른 모든 멀티라인스트링처럼 NULL을 반환할 뿐입니다. 구식 습성은 문서화되지 않은 기능이지만, 사용자 데이터를 라인스트링으로 저장했다고 가정한 사용자의 경우 현재 2.0 버전에서 NULL이 반환될 수도 있습니다.

예시

Start point of a LineString

Code
SELECT ST_StartPoint('LINESTRING(0 1,0 2)'::geometry);
래스터 출력
POINT(0 1)
Figure
Geometry figure for visual-st-startpoint-01

Start point of a Point is the Point itself

Code
SELECT ST_StartPoint('POINT(0 1)'::geometry);
래스터 출력
POINT(0 1)
Figure
Geometry figure for visual-st-startpoint-02

Start point of a 3D LineString

Code
SELECT ST_StartPoint('LINESTRING(0 1 1,0 2 2)'::geometry);
래스터 출력
POINT(0 1 1)
Figure
Geometry figure for visual-st-startpoint-03

ST_LineString 또는 ST_CircularString 값에 있는 포인트의 개수를 반환합니다.

Code
SELECT ST_StartPoint('CIRCULARSTRING(5 2,-3 2,-2 1,-4 2,6 3)'::geometry);
래스터 출력
POINT(5 2)
Figure
Geometry figure for visual-st-startpoint-04

Start point of a NURBSCurve

Code
SELECT ST_StartPoint('NURBSCURVE(2, (0 0, 1 1, 2 0))'::geometry);
래스터 출력
POINT(0 0)
Figure
Geometry figure for visual-st-startpoint-05

Build edge node references from the start and end points of a LineString table. The example uses exact endpoint equality, so linework with nearly coincident endpoints should be snapped or otherwise cleaned first.

Code
WITH roads(road_id, geom) AS (
  VALUES
    (1, 'LINESTRING(0 0, 1 0)'::geometry),
    (2, 'LINESTRING(1 0, 1 1)'::geometry),
    (3, 'LINESTRING(1 0, 2 0)'::geometry)
),
endpoints AS (
  SELECT road_id, 'from' AS end_name, ST_StartPoint(geom) AS geom,
         ST_AsEWKB(ST_StartPoint(geom)) AS endpoint_key
  FROM roads
  UNION ALL
  SELECT road_id, 'to' AS end_name, ST_EndPoint(geom) AS geom,
         ST_AsEWKB(ST_EndPoint(geom)) AS endpoint_key
  FROM roads
),
nodes AS (
  SELECT dense_rank() OVER (ORDER BY ST_X(geom), ST_Y(geom), endpoint_key) AS node_id,
         endpoint_key
  FROM (
    SELECT DISTINCT ON (endpoint_key) endpoint_key, geom
    FROM endpoints
    ORDER BY endpoint_key
  ) AS distinct_endpoints
)
SELECT e.road_id,
       max(n.node_id) FILTER (WHERE e.end_name = 'from') AS from_node,
       max(n.node_id) FILTER (WHERE e.end_name = 'to') AS to_node
FROM endpoints AS e
JOIN nodes AS n USING (endpoint_key)
GROUP BY e.road_id
ORDER BY e.road_id;
래스터 출력
road_id | from_node | to_node
---------+-----------+---------
     1 |         1 |       2
     2 |         2 |       3
     3 |         2 |       4
Figure
Geometry figure for visual-st-startpoint-06

제목

ST_StartM — Returns the M coordinate of the first point of a LineString, CircularLineString, or NURBSCurve.

요약

float8 ST_StartM(geometry geom);

설명

Returns the M coordinate of the first point of a LINESTRING, CIRCULARLINESTRING, or NURBSCURVE geometry. Returns NULL if the input geometry does not have an M dimension or is not a LINESTRING, CIRCULARLINESTRING, or NURBSCURVE.

This method supports Circular Strings and Curves.

예시

Start M value of a LineString

Code
SELECT ST_StartM('LINESTRING M(0 0 10,1 1 20,2 0 30)'::geometry);
래스터 출력
10
Figure
Geometry figure for visual-st-startm-01

Start M value of a CircularString

Code
SELECT ST_StartM('CIRCULARSTRING M(0 0 5,1 1 10,2 0 15)'::geometry);
래스터 출력
5
Figure
Geometry figure for visual-st-startm-02

Start M value of a NURBSCurve

Code
SELECT ST_StartM('NURBSCURVE M(2, (0 0 100, 1 1 200, 2 0 300))'::geometry);
래스터 출력
100
Figure
Geometry figure for visual-st-startm-03

Geometry without M dimension returns NULL

Code
SELECT ST_StartM('LINESTRING(0 0,1 1)'::geometry) IS NULL AS is_null;
래스터 출력
t
Figure
Geometry figure for visual-st-startm-04

제목

ST_EndM — Returns the M coordinate of the last point of a LineString, CircularLineString, or NURBSCurve.

요약

float8 ST_EndM(geometry geom);

설명

Returns the M coordinate of the last point of a LINESTRING, CIRCULARLINESTRING, or NURBSCURVE geometry. Returns NULL if the input geometry does not have an M dimension or is not a LINESTRING, CIRCULARLINESTRING, or NURBSCURVE.

This method supports Circular Strings and Curves.

예시

End M value of a LineString

Code
SELECT ST_EndM('LINESTRING M(0 0 10,1 1 20,2 0 30)'::geometry);
래스터 출력
30
Figure
Geometry figure for visual-st-endm-01

End M value of a CircularString

Code
SELECT ST_EndM('CIRCULARSTRING M(0 0 5,1 1 10,2 0 15)'::geometry);
래스터 출력
15
Figure
Geometry figure for visual-st-endm-02

End M value of a NURBSCurve

Code
SELECT ST_EndM('NURBSCURVE M(2, (0 0 100, 1 1 200, 2 0 300))'::geometry);
래스터 출력
300
Figure
Geometry figure for visual-st-endm-03

Geometry without M dimension returns NULL

Code
SELECT ST_EndM('LINESTRING(0 0,1 1)'::geometry) IS NULL AS is_null;
래스터 출력
t
Figure
Geometry figure for visual-st-endm-04

제목

ST_SetStartM — Sets the M coordinate of the first point of a LineString, CircularLineString, or NURBSCurve.

요약

geometry ST_SetStartM(geometry geom, float8 m);

설명

Returns a copy of the input LINESTRING, CIRCULARLINESTRING, or NURBSCURVE geometry with the M coordinate of the first point set to the specified value. If the input geometry does not have an M dimension, it will be added. Returns NULL if the input is not a LINESTRING, CIRCULARLINESTRING, or NURBSCURVE.

This method supports Circular Strings and Curves.

예시

Set start M value of a LineString

Code
SELECT ST_SetStartM('LINESTRING M(0 0 10,1 1 20,2 0 30)'::geometry, 100);
래스터 출력
LINESTRING M (0 0 100,1 1 20,2 0 30)
Figure
Geometry figure for visual-st-setstartm-01

Add M dimension and set start M value

Code
SELECT ST_SetStartM('LINESTRING(0 0,1 1,2 0)'::geometry, 50);
래스터 출력
LINESTRING M (0 0 50,1 1 0,2 0 0)
Figure
Geometry figure for visual-st-setstartm-02

Set start M value of a CircularString

Code
SELECT ST_SetStartM('CIRCULARSTRING M(0 0 5,1 1 10,2 0 15)'::geometry, 99);
래스터 출력
CIRCULARSTRING M (0 0 99,1 1 10,2 0 15)
Figure
Geometry figure for visual-st-setstartm-03

Set start M value of a NURBSCurve

Code
SELECT ST_SetStartM('NURBSCURVE M(2, (0 0 100, 1 1 200, 2 0 300))'::geometry, 500);
래스터 출력
NURBSCURVE M (DEGREE 2,CONTROLPOINTS M (NURBSPOINT(WEIGHTEDPOINT M (0 0 500),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT M (1 1 200),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT M (2 0 300),WEIGHT 1)),KNOTS (KNOT(0,3), KNOT(1,3)))
Figure
Geometry figure for visual-st-setstartm-04

제목

ST_SetEndM — Sets the M coordinate of the last point of a LineString, CircularLineString, or NURBSCurve.

요약

geometry ST_SetEndM(geometry geom, float8 m);

설명

Returns a copy of the input LINESTRING, CIRCULARLINESTRING, or NURBSCURVE geometry with the M coordinate of the last point set to the specified value. If the input geometry does not have an M dimension, it will be added. Returns NULL if the input is not a LINESTRING, CIRCULARLINESTRING, or NURBSCURVE.

This method supports Circular Strings and Curves.

예시

Set end M value of a LineString

Code
SELECT ST_SetEndM('LINESTRING M(0 0 10,1 1 20,2 0 30)'::geometry, 999);
래스터 출력
LINESTRING M (0 0 10,1 1 20,2 0 999)
Figure
Geometry figure for visual-st-setendm-01

Add M dimension and set end M value

Code
SELECT ST_SetEndM('LINESTRING(0 0,1 1,2 0)'::geometry, 75);
래스터 출력
LINESTRING M (0 0 0,1 1 0,2 0 75)
Figure
Geometry figure for visual-st-setendm-02

Set end M value of a CircularString

Code
SELECT ST_SetEndM('CIRCULARSTRING M(0 0 5,1 1 10,2 0 15)'::geometry, 88);
래스터 출력
CIRCULARSTRING M (0 0 5,1 1 10,2 0 88)
Figure
Geometry figure for visual-st-setendm-03

Set end M value of a NURBSCurve

Code
SELECT ST_SetEndM('NURBSCURVE M(2, (0 0 100, 1 1 200, 2 0 300))'::geometry, 999);
래스터 출력
NURBSCURVE M (DEGREE 2,CONTROLPOINTS M (NURBSPOINT(WEIGHTEDPOINT M (0 0 100),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT M (1 1 200),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT M (2 0 999),WEIGHT 1)),KNOTS (KNOT(0,3), KNOT(1,3)))
Figure
Geometry figure for visual-st-setendm-04

제목

ST_Summary — 도형의 내용을 요약한 텍스트를 반환합니다.

요약

text ST_Summary(geometry g);

text ST_Summary(geography g);

설명

도형의 내용을 요약한 텍스트를 반환합니다.

도형 유형 뒤에 대괄호로 표기된 플래그는 다음과 같은 뜻입니다:

  • M: M 좌표가 존재합니다.

  • Z: Z 좌표가 존재합니다.

  • B: 캐쉬된 경계 상자를 가지고 있습니다.

  • G: 측지형(지리형)입니다.

  • S: 공간 참조 시스템을 가지고 있습니다.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

1.2.2 버전부터 사용할 수 있습니다.

개선 사항: 2.0.0 버전부터 지리형을 지원하기 시작했습니다.

개선 사항: 2.1.0 버전. 알려진 공간 참조 시스템을 가진 경우를 나타내는 S 플래그가 추가됐습니다.

개선 사항: 2.2.0 버전부터 TIN 및 만곡 도형(curve)을 지원하기 시작했습니다.

예시

Code
SELECT ST_Summary('LINESTRING(0 0,1 1)'::geometry) as geom,
ST_Summary('POLYGON((0 0,1 1,1 2,1 1,0 0))'::geography) geog;
래스터 출력
geom             |          geog
-----------------------------+--------------------------
 LineString[B] with 2 points | Polygon[BGS] with 1 rings
                             | ring 0 has 5 points
                             :
(1 row)
Code
SELECT ST_Summary('LINESTRING(0 0 1,1 1 1)'::geography) As geog_line,
ST_Summary('SRID=4326;POLYGON((0 0 1,1 1 2,1 2 3,1 1 1,0 0 1))'::geometry) As geom_poly;
래스터 출력
geog_line             |        geom_poly
-------------------------------- +--------------------------
 LineString[ZBGS] with 2 points | Polygon[ZBS] with 1 rings
                                :    ring 0 has 5 points
                                :
(1 row)

제목

ST_X — Returns the X coordinate of a Point.

요약

float ST_X(geometry a_point);

설명

포인트의 X 좌표를 반환합니다. X 좌표가 없는 경우 NULL을 반환합니다. 포인트만 입력받을 수 있습니다.

[참고]

To get the minimum and maximum X value of geometry coordinates use the functions ST_XMin and ST_XMax.

This method implements the SQL/MM specification. SQL-MM 3: 6.1.3

This function supports 3d and will not drop the z-index.

예시

Code
SELECT ST_X('POINT(1 2 3 4)');
래스터 출력
1
Code
SELECT ST_Y(ST_Centroid('LINESTRING(1 2 3 4,1 1 1 1)'::geometry));
래스터 출력
1.5

제목

ST_Y — Returns the Y coordinate of a Point.

요약

float ST_Y(geometry a_point);

설명

포인트의 Y 좌표를 반환합니다. Y 좌표가 없는 경우 NULL을 반환합니다. 포인트만 입력받을 수 있습니다.

[참고]

To get the minimum and maximum Y value of geometry coordinates use the functions ST_YMin and ST_YMax.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1.

This method implements the SQL/MM specification. SQL-MM 3: 6.1.4

This function supports 3d and will not drop the z-index.

예시

Code
SELECT ST_Y('POINT(1 2 3 4)');
래스터 출력
2
Code
SELECT ST_Y(ST_Centroid('LINESTRING(1 2 3 4,1 1 1 1)'::geometry));
래스터 출력
1.5

제목

ST_Z — Returns the Z coordinate of a Point.

요약

float ST_Z(geometry a_point);

설명

포인트의 Z 좌표를 반환합니다. Z 좌표가 없는 경우 NULL을 반환합니다. 포인트만 입력받을 수 있습니다.

[참고]

To get the minimum and maximum Z value of geometry coordinates use the functions ST_ZMin and ST_ZMax.

This method implements the SQL/MM specification.

This function supports 3d and will not drop the z-index.

예시

Code
SELECT ST_Z('POINT(1 2 3 4)');
래스터 출력
3

제목

ST_ZMFlag — ST_Geometry 값의 좌표 차원을 반환합니다.

요약

smallint ST_ZMFlag(geometry geomA);

설명

ST_Geometry 값의 좌표 차원을 반환합니다.

Values are: 0 = 2D, 1 = 3D-M, 2 = 3D-Z, 3 = 4D.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

예시

Code
SELECT ST_ZMFlag('LINESTRING(1 2,3 4)');
래스터 출력
0
Code
SELECT ST_ZMFlag('LINESTRINGM(1 2 3, 3 4 3)');
래스터 출력
1
Code
SELECT ST_ZMFlag('CIRCULARSTRING(1 2 3,3 4 3,5 6 3)');
래스터 출력
2
Code
SELECT ST_ZMFlag('POINT(1 2 3 4)');
래스터 출력
3

제목

ST_HasZ — Checks if a geometry has a Z dimension.

요약

boolean ST_HasZ(geometry geom);

설명

Checks if the input geometry has a Z dimension and returns a boolean value. If the geometry has a Z dimension, it returns true; otherwise, it returns false.

Geometry objects with a Z dimension typically represent three-dimensional (3D) geometries, while those without it are two-dimensional (2D) geometries.

This function is useful for determining if a geometry has elevation or height information.

Availability: 3.5.0

This function supports 3d and will not drop the z-index.

This function supports M coordinates.

예시

Code
SELECT ST_HasZ('POINT(1 2 3)');
래스터 출력
t
Code
SELECT ST_HasZ('LINESTRING(0 0,1 1)');
래스터 출력
f
Figure
Geometry figure for visual-st-hasz-02

제목

ST_HasM — Checks if a geometry has an M (measure) dimension.

요약

boolean ST_HasM(geometry geom);

설명

Checks if the input geometry has an M (measure) dimension and returns a boolean value. If the geometry has an M dimension, it returns true; otherwise, it returns false.

Geometry objects with an M dimension typically represent measurements or additional data associated with spatial features.

This function is useful for determining if a geometry includes measure information.

Availability: 3.5.0

This function supports 3d and will not drop the z-index.

This function supports M coordinates.

예시

Code
SELECT ST_HasM('POINTM(1 2 3)');
래스터 출력
t
Code
SELECT ST_HasM('LINESTRING(0 0,1 1)');
래스터 출력
f
Figure
Geometry figure for visual-st-hasm-02

제목

ST_ControlPoints — Returns the control points of a NURBS curve as a MULTIPOINT geometry.

요약

geometry ST_ControlPoints(geometry nurbscurve);

설명

Extracts the control points from a NURBS curve and returns them as a MULTIPOINT geometry. Control points define the control polygon that influences the shape of the NURBS curve.

The function raises an error if the input is not a NURBS curve. Returns NULL if the input is NULL.

Availability: 3.7.0

예시

This example extracts control points from a NURBS curve.

Code
SELECT ST_ControlPoints('NURBSCURVE(2, (0 0, 5 10, 10 0))'::geometry);
래스터 출력
MULTIPOINT((0 0),(5 10),(10 0))
Figure
Geometry figure for visual-st-controlpoints-01

This example counts the control points.

Code
SELECT ST_NPoints(ST_ControlPoints('NURBSCURVE(2, (0 0, 5 10, 10 0))'::geometry));
래스터 출력
3

제목

ST_Degree — Returns the polynomial degree of a NURBS curve.

요약

integer ST_Degree(geometry nurbscurve);

설명

Returns the polynomial degree of a NURBS curve as an integer. The degree determines the curve's smoothness and flexibility. Higher degrees produce smoother curves but require more control points.

The function raises an error if the input is not a NURBS curve. Returns NULL if the input is NULL.

Availability: 3.7.0

예시

This example returns the degree of a NURBS curve.

Code
SELECT ST_Degree('NURBSCURVE(2, (0 0, 5 10, 10 0))'::geometry);
래스터 출력
2
Figure
Geometry figure for visual-st-degree-01

This example checks whether a NURBS curve is cubic.

Code
SELECT ST_Degree('NURBSCURVE(3, (0 0, 2 5, 5 8, 10 0))'::geometry) = 3;
래스터 출력
t
Figure
Geometry figure for visual-st-degree-02

제목

ST_Weights — Returns the weight array of a rational NURBS curve.

요약

float8[] ST_Weights(geometry nurbscurve);

설명

Returns the weight values of a rational NURBS curve as an array of double precision values. Weights control the influence of each control point on the curve shape. Higher weights pull the curve closer to the corresponding control point.

Returns NULL if the curve has no weights (non-rational B-spline) or if the input is NULL. Raises an error if the input is not a NURBS curve.

Availability: 3.7.0

예시

This example returns weights from a rational NURBS curve.

Code
SELECT ST_Weights(ST_MakeNurbsCurve(2, 'LINESTRING(0 0,5 10,10 0)'::geometry, ARRAY[1.0, 2.0, 1.0]));
래스터 출력
{1,2,1}
Figure
Geometry figure for visual-st-weights-01

This example checks the weights of a non-rational curve.

Code
SELECT ST_Weights('NURBSCURVE(2, (0 0, 5 10, 10 0))'::geometry);
래스터 출력
null
Figure
Geometry figure for visual-st-weights-02

제목

ST_Knots — Returns the knot vector of a NURBS curve.

요약

float8[] ST_Knots(geometry nurbscurve);

설명

Returns the knot vector of a NURBS curve as an array of double precision values. The knot vector defines the parameter space and controls where and how the control points affect the curve. It must be a non-decreasing sequence with length equal to (number of control points + degree + 1).

Returns NULL if the curve uses the default uniform clamped knot vector or if the input is NULL. Raises an error if the input is not a NURBS curve.

Availability: 3.7.0

예시

This example returns knots from a NURBS curve with a custom knot vector.

Code
SELECT ST_Knots(ST_MakeNurbsCurve(
        2,
        'LINESTRING(0 0,5 10,10 0)'::geometry,
        ARRAY[1.0, 2.0, 1.0],
        ARRAY[0, 0, 0, 1, 1, 1]));
래스터 출력
{0,0,0,1,1,1}
Figure
Geometry figure for visual-st-knots-01

This example checks the knots of a curve using the default knot vector.

Code
SELECT ST_Knots('NURBSCURVE(2, (0 0, 5 10, 10 0))'::geometry);
래스터 출력
null
Figure
Geometry figure for visual-st-knots-02

제목

ST_NumControlPoints — Returns the number of control points in a NURBS curve.

요약

integer ST_NumControlPoints(geometry nurbscurve);

설명

Returns the number of control points in a NURBS curve. The number of control points must be at least (degree + 1) for a valid NURBS curve.

Raises an error if the input is not a NURBS curve. Returns NULL if the input is NULL.

Availability: 3.7.0

예시

This example returns the number of control points.

Code
SELECT ST_NumControlPoints('NURBSCURVE(2, (0 0, 5 10, 10 0))'::geometry);
래스터 출력
3
Figure
Geometry figure for visual-st-numcontrolpoints-01

This example verifies that a curve has enough control points for its degree.

Code
SELECT ST_NumControlPoints(curve) 
>= ST_Degree(curve) + 1 AS valid
FROM (SELECT 'NURBSCURVE(2, (0 0, 5 10, 10 0))'::geometry AS curve) AS t;
래스터 출력
t
Figure
Geometry figure for visual-st-numcontrolpoints-02

제목

ST_NurbsCurveIsRational — Checks if a NURBS curve is rational (has weights).

요약

boolean ST_NurbsCurveIsRational(geometry nurbscurve);

설명

Returns TRUE if the NURBS curve has weights assigned to its control points (rational NURBS), FALSE if it uses uniform weights (non-rational B-spline).

Rational NURBS curves provide more flexibility in curve shape control through variable weights. Non-rational B-splines use uniform weights and are a special case of NURBS curves.

Raises an error if the input is not a NURBS curve. Returns NULL if the input is NULL.

Availability: 3.7.0

예시

This example checks whether a curve is rational.

Code
SELECT ST_NurbsCurveIsRational(ST_MakeNurbsCurve(
        2,
        'LINESTRING(0 0,5 10,10 0)'::geometry,
        ARRAY[1.0, 2.0, 1.0]));
래스터 출력
t
Figure
Geometry figure for visual-st-nurbscurveisrational-01

This example checks a non-rational curve.

Code
SELECT ST_NurbsCurveIsRational('NURBSCURVE(2, (0 0, 5 10, 10 0))'::geometry);
래스터 출력
f
Figure
Geometry figure for visual-st-nurbscurveisrational-02

제목

ST_IsNurbsCurve — Checks if a geometry is a NURBS curve.

요약

boolean ST_IsNurbsCurve(geometry geom);

설명

Returns TRUE if the geometry is a NURBS curve, FALSE otherwise. This function can be used to test geometry types before applying NURBS-specific functions.

Returns NULL if the input is NULL.

Availability: 3.7.0

예시

This example checks whether a geometry is a NURBS curve.

Code
SELECT ST_IsNurbsCurve('NURBSCURVE(2, (0 0, 5 10, 10 0))'::geometry);
래스터 출력
t
Figure
Geometry figure for visual-st-isnurbscurve-01

This example tests a regular LineString.

Code
SELECT ST_IsNurbsCurve('LINESTRING(0 0,10 10)'::geometry);
래스터 출력
f
Figure
Geometry figure for visual-st-isnurbscurve-02

제목

ST_Evaluate — Evaluates a NURBS curve at a specific parameter value and returns the resulting point.

요약

geometry ST_Evaluate(geometry nurbscurve, float8 parameter);

설명

Evaluates a NURBS curve at the specified parameter value and returns a POINT geometry representing the position on the curve. The parameter typically ranges from 0.0 (start of curve) to 1.0 (end of curve), though the actual range depends on the knot vector.

Raises an error if the input is not a NURBS curve or if evaluation fails. Returns NULL if either input is NULL.

Availability: 3.7.0

예시

This example returns the midpoint of a NURBS curve.

Code
SELECT ST_Evaluate('NURBSCURVE(2, (0 0, 5 10, 10 0))'::geometry, 0.5);

This example samples multiple points along a curve.

Code
SELECT t, ST_Evaluate(curve, t) AS point
FROM (SELECT 'NURBSCURVE(2, (0 0, 5 10, 10 0))'::geometry AS curve) AS c,
         generate_series(0, 1, 0.25) AS t;

제목

ST_NurbsToLineString — Converts a NURBS curve to a LINESTRING by uniform sampling.

요약

geometry ST_NurbsToLineString(geometry nurbscurve, integer num_segments=32);

설명

Converts a NURBS curve to a LINESTRING geometry by creating a piecewise linear approximation. The curve is sampled at uniformly distributed parameter values and the resulting points are connected with straight line segments.

The optional num_segments parameter specifies the number of line segments in the output (default: 32, range: 2-10000). Higher values produce smoother approximations but increase geometry complexity.

Raises an error if the input is not a NURBS curve. Returns NULL if the input is NULL.

Availability: 3.7.0

예시

This example converts a NURBS curve to a LineString using the default quality.

Code
SELECT ST_NurbsToLineString('NURBSCURVE(2, (0 0, 5 10, 10 0))'::geometry);
래스터 출력
LINESTRING(0 0,0.3125 0.60546875,0.625 1.171875,0.9375 1.69921875,1.25 2.1875,1.5625 2.63671875,1.875 3.046875,2.1875 3.41796875,2.5 3.75,2.8125 4.04296875,3.125 4.296875,3.4375 4.51171875,3.75 4.6875,4.0625 4.82421875,4.375 4.921875,4.6875 4.98046875,5 5,5.3125 4.98046875,5.625 4.921875,5.9375 4.82421875,6.25 4.6875,6.5625 4.51171875,6.875 4.296875,7.1875 4.04296875,7.5 3.75,7.8125 3.41796875,8.125 3.046875,8.4375 2.63671875,8.75 2.1875,9.0625 1.69921875,9.375 1.171875,9.6875 0.60546875,10 0)
Figure
Geometry figure for visual-st-nurbstolinestring-01

This example creates a high-quality approximation with 64 segments.

Code
SELECT ST_NurbsToLineString('NURBSCURVE(2, (0 0, 5 10, 10 0))'::geometry, 64);
래스터 출력
LINESTRING(0 0,0.15625 0.3076171875,0.3125 0.60546875,0.46875 0.8935546875,0.625 1.171875,0.78125 1.4404296875,0.9375 1.69921875,1.09375 1.9482421875,1.25 2.1875,1.40625 2.4169921875,1.5625 2.63671875,1.71875 2.8466796875,1.875 3.046875,2.03125 3.2373046875,2.1875 3.41796875,2.34375 3.5888671875,2.5 3.75,2.65625 3.9013671875,2.8125 4.04296875,2.96875 4.1748046875,3.125 4.296875,3.28125 4.4091796875,3.4375 4.51171875,3.59375 4.6044921875,3.75 4.6875,3.90625 4.7607421875,4.0625 4.82421875,4.21875 4.8779296875,4.375 4.921875,4.53125 4.9560546875,4.6875 4.98046875,4.84375 4.9951171875,5 5,5.15625 4.9951171875,5.3125 4.98046875,5.46875 4.9560546875,5.625 4.921875,5.78125 4.8779296875,5.9375 4.82421875,6.09375 4.7607421875,6.25 4.6875,6.40625 4.6044921875,6.5625 4.51171875,6.71875 4.4091796875,6.875 4.296875,7.03125 4.1748046875,7.1875 4.04296875,7.34375 3.9013671875,7.5 3.75,7.65625 3.5888671875,7.8125 3.41796875,7.96875 3.2373046875,8.125 3.046875,8.28125 2.8466796875,8.4375 2.63671875,8.59375 2.4169921875,8.75 2.1875,8.90625 1.9482421875,9.0625 1.69921875,9.21875 1.4404296875,9.375 1.171875,9.53125 0.8935546875,9.6875 0.60546875,9.84375 0.3076171875,10 0)
Figure
Geometry figure for visual-st-nurbstolinestring-02

This example creates a lower-quality, faster approximation with 16 segments.

Code
SELECT ST_NurbsToLineString('NURBSCURVE(2, (0 0, 5 10, 10 0))'::geometry, 16);
래스터 출력
LINESTRING(0 0,0.625 1.171875,1.25 2.1875,1.875 3.046875,2.5 3.75,3.125 4.296875,3.75 4.6875,4.375 4.921875,5 5,5.625 4.921875,6.25 4.6875,6.875 4.296875,7.5 3.75,8.125 3.046875,8.75 2.1875,9.375 1.171875,10 0)
Figure
Geometry figure for visual-st-nurbstolinestring-03

7.5. 도형 편집자(editor)

초록

These functions create modified geometries by changing type, structure or vertices.

  • ST_AddPoint — 라인스트링에 포인트를 추가합니다.
  • ST_CollectionExtract — Given a geometry collection, returns a multi-geometry containing only elements of a specified type.
  • ST_CollectionHomogenize — Returns the simplest representation of a geometry collection.
  • ST_CurveToLine — Converts a geometry containing curves to a linear geometry.
  • ST_Scroll — Change start point of a closed LineString.
  • ST_FlipCoordinates — Returns a version of a geometry with X and Y axis flipped.
  • ST_Force2D — 도형을 "2차원 모드"로 강제합니다.
  • ST_Force3D — 도형을 XYZ 모드로 강제합니다. ST_Force3DZ라고도 합니다.
  • ST_Force3DZ — 도형을 XYZ 모드로 강제합니다.
  • ST_Force3DM — 도형을 XYM 모드로 강제합니다.
  • ST_Force4D — 도형을 XYZM 모드로 강제합니다.
  • ST_ForceCollection — 도형을 도형 집합으로 변환합니다.
  • ST_ForceCurve — 적용이 가능한 경우, 도형을 해당 도형의 만곡 유형으로 상위 형변환(upcast)합니다.
  • ST_ForcePolygonCCW — Orients all exterior rings counter-clockwise and all interior rings clockwise.
  • ST_ForcePolygonCW — Orients all exterior rings clockwise and all interior rings counter-clockwise.
  • ST_ForceSFS — Force geometries to use SFS 1.1 or 1.2 geometry types.
  • ST_ForceRHR — 폴리곤 안에 있는 꼭짓점들의 방향(orientation)이 오른손 법칙(Right-Hand Rule)을 따르도록 강제합니다.
  • ST_LineExtend — Returns a line extended forwards and backwards by specified distances.
  • ST_LineToCurve — Converts a linear geometry to a curved geometry.
  • ST_Multi — 도형을 멀티 유형 도형으로 반환합니다.
  • ST_Normalize — 도형을 해당 도형의 기본형으로 반환합니다.
  • ST_Project — Returns a point projected from a start point by a distance and bearing (azimuth).
  • ST_QuantizeCoordinates — Sets least significant bits of coordinates to zero
  • ST_RemovePoint — Remove a point from a linestring.
  • ST_RemoveRepeatedPoints — Returns a version of a geometry with duplicate points removed.
  • ST_RemoveIrrelevantPointsForView — Removes points that are irrelevant for rendering a specific rectangular view of a geometry.
  • ST_RemoveSmallParts — Removes small parts (polygon rings or linestrings) of a geometry.
  • ST_Reverse — 꼭짓점들의 순서가 반대인 도형을 반환합니다.
  • ST_Segmentize — Returns a modified geometry/geography having no segment longer than a given distance.
  • ST_SetPoint — 라인스트링의 포인트를 주어진 포인트로 대체합니다.
  • ST_ShiftLongitude — Shifts the longitude coordinates of a geometry between -180..180 and 0..360.
  • ST_WrapX — X값 근처에서 도형을 래핑합니다.
  • ST_SnapToGrid — 입력 도형의 모든 포인트를 정규 그리드로 스냅(snap)시킵니다.
  • ST_Snap — 입력 도형의 분절 구간과 꼭짓점을 참조 도형의 꼭짓점으로 스냅시킵니다.
  • ST_SwapOrdinates — 입력 도형을 좌표값을 뒤바꾼 상태로 반환합니다.

제목

ST_AddPoint — 라인스트링에 포인트를 추가합니다.

요약

geometry ST_AddPoint(geometry linestring, geometry point);

geometry ST_AddPoint(geometry linestring, geometry point, integer position = -1);

설명

Adds a point to a LineString before the index position (using a 0-based index). If the position parameter is omitted or is -1 the point is appended to the end of the LineString.

1.1.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

예시

Add a point to the end of a 3D line

Code
SELECT ST_AddPoint('LINESTRING(0 0 1,1 1 1)', ST_MakePoint(1, 2, 3));
래스터 출력
LINESTRING(0 0 1,1 1 1,1 2 3)
Figure
Geometry figure for visual-st-addpoint-01

Guarantee all lines in a table are closed by adding the start point of each line to the end of the line only for those that are not closed.

Code
UPDATE sometable
SET geom = ST_AddPoint(geom, ST_StartPoint(geom))
FROM sometable
WHERE ST_IsClosed(geom) = false;

제목

ST_CollectionExtract — Given a geometry collection, returns a multi-geometry containing only elements of a specified type.

요약

geometry ST_CollectionExtract(geometry collection);

geometry ST_CollectionExtract(geometry collection, integer type);

설명

Given a geometry collection, returns a homogeneous multi-geometry.

If the type is not specified, returns a multi-geometry containing only geometries of the highest dimension. So polygons are preferred over lines, which are preferred over points.

If the type is specified, returns a multi-geometry containing only that type. If there are no sub-geometries of the right type, an EMPTY geometry is returned. Only points, lines and polygons are supported. The type numbers are:

  • 1 == POINT

  • 2 == LINESTRING

  • 3 == POLYGON

For atomic geometry inputs, the geometry is returned unchanged if the input type matches the requested type. Otherwise, the result is an EMPTY geometry of the specified type. If required, these can be converted to multi-geometries using ST_Multi.

[주의]

MultiPolygon results are not checked for validity. If the polygon components are adjacent or overlapping the result will be invalid. (For example, this can occur when applying this function to an ST_Split result.) This situation can be checked with ST_IsValid and repaired with ST_MakeValid.

1.5.0 버전부터 사용할 수 있습니다.

[참고]

Prior to 1.5.3 this function returned atomic inputs unchanged, no matter type. In 1.5.3 non-matching single geometries returned a NULL result. In 2.0.0 non-matching single geometries return an EMPTY result of the requested type.

예시

Extract highest-dimension type:

Code
SELECT ST_CollectionExtract('GEOMETRYCOLLECTION( POINT(0 0), LINESTRING(1 1,2 2) )');
래스터 출력
MULTILINESTRING((1 1, 2 2))
Figure
Geometry figure for visual-st-collectionextract-01

Extract points (type 1 == POINT):

Code
SELECT ST_CollectionExtract('GEOMETRYCOLLECTION(GEOMETRYCOLLECTION(POINT(0 0)))',
        1);
래스터 출력
MULTIPOINT((0 0))
Figure
Geometry figure for visual-st-collectionextract-02

Extract lines (type 2 == LINESTRING):

Code
SELECT ST_CollectionExtract('GEOMETRYCOLLECTION(GEOMETRYCOLLECTION(LINESTRING(0 0,1 1)), LINESTRING(2 2,3 3))',
        2);
래스터 출력
MULTILINESTRING((0 0, 1 1), (2 2, 3 3))
Figure
Geometry figure for visual-st-collectionextract-03

제목

ST_CollectionHomogenize — Returns the simplest representation of a geometry collection.

요약

geometry ST_CollectionHomogenize(geometry collection);

설명

도형 집합을 입력받아 해당 내용의 "가장 단순한" 표현식을 반환합니다.

  • Homogeneous (uniform) collections are returned as the appropriate multi-geometry.

  • Heterogeneous (mixed) collections are flattened into a single GeometryCollection.

  • Collections containing a single atomic element are returned as that element.

  • Atomic geometries are returned unchanged. If required, these can be converted to a multi-geometry using ST_Multi.

[주의]

This function does not ensure that the result is valid. In particular, a collection containing adjacent or overlapping Polygons will create an invalid MultiPolygon. This situation can be checked with ST_IsValid and repaired with ST_MakeValid.

2.0.0 버전부터 사용할 수 있습니다.

예시

Single-element collection converted to an atomic geometry

Code
SELECT ST_CollectionHomogenize('GEOMETRYCOLLECTION(POINT(0 0))');
래스터 출력
POINT(0 0)
Figure
Geometry figure for visual-st-collectionhomogenize-01

Nested single-element collection converted to an atomic geometry:

Code
SELECT ST_CollectionHomogenize('GEOMETRYCOLLECTION(MULTIPOINT((0 0)))');
래스터 출력
POINT(0 0)
Figure
Geometry figure for visual-st-collectionhomogenize-02

Collection converted to a multi-geometry:

Code
SELECT ST_CollectionHomogenize('GEOMETRYCOLLECTION(POINT(0 0), POINT(1 1))');
래스터 출력
MULTIPOINT((0 0),(1 1))
Figure
Geometry figure for visual-st-collectionhomogenize-03

Nested heterogeneous collection flattened to a GeometryCollection:

Code
SELECT ST_CollectionHomogenize('GEOMETRYCOLLECTION(POINT(0 0), GEOMETRYCOLLECTION( LINESTRING(1 1,2 2)))');
래스터 출력
GEOMETRYCOLLECTION(POINT(0 0), LINESTRING(1 1,2 2))
Figure
Geometry figure for visual-st-collectionhomogenize-04

Collection of Polygons converted to an (invalid) MultiPolygon:

Code
SELECT ST_CollectionHomogenize('GEOMETRYCOLLECTION (POLYGON ((10 50,50 50,50 10,10 10,10 50)),POLYGON ((90 50,90 10,50 10,50 50,90 50)))');
래스터 출력
MULTIPOLYGON(((10 50,50 50,50 10,10 10,10 50)),((90 50,90 10,50 10,50 50,90 50)))
Figure
Geometry figure for visual-st-collectionhomogenize-05

제목

ST_CurveToLine — Converts a geometry containing curves to a linear geometry.

요약

geometry ST_CurveToLine(geometry curveGeom, float tolerance, integer tolerance_type, integer flags);

설명

Converts a CIRCULAR STRING to regular LINESTRING or CURVEPOLYGON to POLYGON or MULTISURFACE to MULTIPOLYGON. Useful for outputting to devices that can't support CIRCULARSTRING geometry types

Converts a given geometry to a linear geometry. Each curved geometry or segment is converted into a linear approximation using the given `tolerance` and options (32 segments per quadrant and no options by default).

The 'tolerance_type' argument determines interpretation of the `tolerance` argument. It can take the following values:

  • 0 (default): Tolerance is max segments per quadrant.

  • 1: Tolerance is max-deviation of line from curve, in source units.

  • 2: Tolerance is max-angle, in radians, between generating radii.

The 'flags' argument is a bitfield. 0 by default. Supported bits are:

  • 1: Symmetric (orientation independent) output.

  • 2: Retain angle, avoids reducing angles (segment lengths) when producing symmetric output. Has no effect when Symmetric flag is off.

Availability: 1.3.0

Enhanced: 2.4.0 added support for max-deviation and max-angle tolerance, and for symmetric output.

Enhanced: 3.0.0 implemented a minimum number of segments per linearized arc to prevent topological collapse.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1.

This method implements the SQL/MM specification. SQL-MM 3: 7.1.7

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

예시

Code
SELECT ST_CurveToLine('CIRCULARSTRING(220268 150415,220227 150505,220227 150406)');
래스터 출력
LINESTRING(220268 150415,220269.95064912 150416.539364228,220271.823415575 150418.17258804,220273.613787707 150419.895736857,
220275.317452352 150421.704659462,220276.930305234 150423.594998003,220278.448460847 150425.562198489,
220279.868261823 150427.60152176,220281.186287736 150429.708054909,220282.399363347 150431.876723113,
220283.50456625 150434.10230186,220284.499233914 150436.379429536,220285.380970099 150438.702620341,220286.147650624 150441.066277505,
220286.797428488 150443.464706771,220287.328738321 150445.892130112,220287.740300149 150448.342699654,
220288.031122486 150450.810511759,220288.200504713 150453.289621251,220288.248038775 150455.77405574,
220288.173610157 150458.257830005,220287.977398166 150460.734960415,220287.659875492 150463.199479347,
220287.221807076 150465.64544956,220286.664248262 150468.066978495,220285.988542259 150470.458232479,220285.196316903 150472.81345077,
220284.289480732 150475.126959442,220283.270218395 150477.39318505,220282.140985384 150479.606668057,
220280.90450212 150481.762075989,220279.5637474 150483.85421628,220278.12195122 150485.87804878,
220276.582586992 150487.828697901,220274.949363179 150489.701464356,220273.226214362 150491.491836488,
220271.417291757 150493.195501133,220269.526953216 150494.808354014,220267.559752731 150496.326509628,
220265.520429459 150497.746310603,220263.41389631 150499.064336517,220261.245228106 150500.277412127,
220259.019649359 150501.38261503,220256.742521683 150502.377282695,220254.419330878 150503.259018879,
220252.055673714 150504.025699404,220249.657244448 150504.675477269,220247.229821107 150505.206787101,
220244.779251566 150505.61834893,220242.311439461 150505.909171266,220239.832329968 150506.078553494,
220237.347895479 150506.126087555,220234.864121215 150506.051658938,220232.386990804 150505.855446946,
220229.922471872 150505.537924272,220227.47650166 150505.099855856,220225.054972724 150504.542297043,
220222.663718741 150503.86659104,220220.308500449 150503.074365683,
220217.994991777 150502.167529512,220215.72876617 150501.148267175,
220213.515283163 150500.019034164,220211.35987523 150498.7825509,
220209.267734939 150497.441796181,220207.243902439 150496,
220205.293253319 150494.460635772,220203.420486864 150492.82741196,220201.630114732 150491.104263143,
220199.926450087 150489.295340538,220198.313597205 150487.405001997,220196.795441592 150485.437801511,
220195.375640616 150483.39847824,220194.057614703 150481.291945091,220192.844539092 150479.123276887,220191.739336189 150476.89769814,
220190.744668525 150474.620570464,220189.86293234 150472.297379659,220189.096251815 150469.933722495,
220188.446473951 150467.535293229,220187.915164118 150465.107869888,220187.50360229 150462.657300346,
220187.212779953 150460.189488241,220187.043397726 150457.710378749,220186.995863664 150455.22594426,
220187.070292282 150452.742169995,220187.266504273 150450.265039585,220187.584026947 150447.800520653,
220188.022095363 150445.35455044,220188.579654177 150442.933021505,220189.25536018 150440.541767521,
220190.047585536 150438.18654923,220190.954421707 150435.873040558,220191.973684044 150433.60681495,
220193.102917055 150431.393331943,220194.339400319 150429.237924011,220195.680155039 150427.14578372,220197.12195122 150425.12195122,
220198.661315447 150423.171302099,220200.29453926 150421.298535644,220202.017688077 150419.508163512,220203.826610682 150417.804498867,
220205.716949223 150416.191645986,220207.684149708 150414.673490372,220209.72347298 150413.253689397,220211.830006129 150411.935663483,
220213.998674333 150410.722587873,220216.22425308 150409.61738497,220218.501380756 150408.622717305,220220.824571561 150407.740981121,
220223.188228725 150406.974300596,220225.586657991 150406.324522731,220227 150406)
Figure
Geometry figure for visual-st-curvetoline-01

This example uses 3D input.

Code
SELECT ST_CurveToLine('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)');
래스터 출력
LINESTRING(220268 150415 1,220269.95064912 150416.539364228 1.0181172856673,
220271.823415575 150418.17258804 1.03623457133459,220273.613787707 150419.895736857 1.05435185700189,....AD INFINITUM ....
   220225.586657991 150406.324522731 1.32611114201132,220227 150406 3)

Use only 2 segments to approximate quarter circle.

Code
SELECT ST_CurveToLine('CIRCULARSTRING(220268 150415,220227 150505,220227 150406)', 2);
래스터 출력
LINESTRING(220268 150415,220287.740300149 150448.342699654,220278.12195122 150485.87804878,
220244.779251566 150505.61834893,220207.243902439 150496,220187.50360229 150462.657300346,
220197.12195122 150425.12195122,220227 150406)
Figure
Geometry figure for visual-st-curvetoline-03

Ensure the approximated line is no more than 20 units away from the original curve, and make the result direction-neutral.

Code
SELECT ST_CurveToLine(
    'CIRCULARSTRING(0 0,100 -100,200 0)'::geometry,
    20,
    1,
    1
  );
래스터 출력
LINESTRING(0 0,49.99999999999996 -86.60254037844383,149.99999999999994 -86.6025403784439,200 0)
Figure
Geometry figure for visual-st-curvetoline-04

제목

ST_Scroll — Change start point of a closed LineString.

요약

geometry ST_Scroll(geometry linestring, geometry point);

설명

Changes the start/end point of a closed LineString to the given vertex point.

Availability: 3.2.0

This function supports 3d and will not drop the z-index.

This function supports M coordinates.

예시

Make a closed line start at its 3rd vertex.

Code
SELECT ST_Scroll('SRID=4326;LINESTRING(0 0 0 1,10 0 2 0,5 5 4 2,0 0 0 1)', 'POINT(5 5 4 2)');
래스터 출력
SRID=4326;LINESTRING(5 5 4 2,0 0 0 1,10 0 2 0,5 5 4 2)
Figure
Geometry figure for visual-st-scroll-01

제목

ST_FlipCoordinates — Returns a version of a geometry with X and Y axis flipped.

요약

geometry ST_FlipCoordinates(geometry geom);

설명

Returns a version of the given geometry with X and Y axis flipped. Useful for fixing geometries which contain coordinates expressed as latitude/longitude (Y,X).

2.0.0 버전부터 사용할 수 있습니다.

This method supports Circular Strings and Curves.

This function supports 3d and will not drop the z-index.

This function supports M coordinates.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

Code
SELECT ST_FlipCoordinates(GeomFromEWKT('POINT(1 2)'));
래스터 출력
POINT(2 1)
Figure
Geometry figure for visual-st-flipcoordinates-01

제목

ST_Force2D — 도형을 "2차원 모드"로 강제합니다.

요약

geometry ST_Force2D(geometry geomA);

설명

도형을 "2차원 모드"로 강제해서 출력 표현식이 X 및 Y 좌표만을 가지도록 합니다. 이 함수는 (OGC가 사양에 2차원 도형만 있기 때문에) OGC 준수 출력물을 강제하는 데 유용합니다.

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다.

변경 사항: 2.1.0 미만 버전, 즉 2.0.x 버전까지 이 함수의 명칭은 ST_Force_2D였습니다.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

This function supports 3d and will not drop the z-index.

예시

Code
SELECT ST_Force2D('CIRCULARSTRING(1 1 2,2 3 2,4 5 2,6 7 2,5 6 2)');
래스터 출력
CIRCULARSTRING(1 1,2 3,4 5,6 7,5 6)
Figure
Geometry figure for visual-st-force2d-01
Code
SELECT ST_Force2D('POLYGON((0 0 2,0 5 2,5 0 2,0 0 2),(1 1 2,3 1 2,1 3 2,1 1 2))');
래스터 출력
POLYGON((0 0,0 5,5 0,0 0),(1 1,3 1,1 3,1 1))
Figure
Geometry figure for visual-st-force2d-02

제목

ST_Force3D — 도형을 XYZ 모드로 강제합니다. ST_Force3DZ라고도 합니다.

요약

geometry ST_Force3D(geometry geomA, float Zvalue = 0.0);

설명

Forces the geometries into XYZ mode. This is an alias for ST_Force3DZ. If a geometry has no Z component, then a Zvalue Z coordinate is tacked on.

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다.

변경 사항: 2.1.0 미만 버전, 즉 2.0.x 버전까지 이 함수의 명칭은 ST_Force_3D였습니다.

Changed: 3.1.0. Added support for supplying a non-zero Z value.

This function supports Polyhedral surfaces.

This method supports Circular Strings and Curves.

This function supports 3d and will not drop the z-index.

예시

Nothing happens to an already 3D geometry.

Code
SELECT ST_Force3D('CIRCULARSTRING(1 1 2,2 3 2,4 5 2,6 7 2,5 6 2)');
래스터 출력
CIRCULARSTRING(1 1 2,2 3 2,4 5 2,6 7 2,5 6 2)
Figure
Geometry figure for visual-st-force-3d-01
Code
SELECT ST_Force3D('POLYGON((0 0,0 5,5 0,0 0),(1 1,3 1,1 3,1 1))');
래스터 출력
POLYGON((0 0 0,0 5 0,5 0 0,0 0 0),(1 1 0,3 1 0,1 3 0,1 1 0))
Figure
Geometry figure for visual-st-force-3d-02

제목

ST_Force3DZ — 도형을 XYZ 모드로 강제합니다.

요약

geometry ST_Force3DZ(geometry geomA, float Zvalue = 0.0);

설명

Forces the geometries into XYZ mode. If a geometry has no Z component, then a Zvalue Z coordinate is tacked on.

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다.

변경 사항: 2.1.0 미만 버전, 즉 2.0.x 버전까지 이 함수의 명칭은 ST_Force_3DZ였습니다.

Changed: 3.1.0. Added support for supplying a non-zero Z value.

This function supports Polyhedral surfaces.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

예시

Nothing happens to an already 3D geometry.

Code
SELECT ST_Force3DZ('CIRCULARSTRING(1 1 2,2 3 2,4 5 2,6 7 2,5 6 2)');
래스터 출력
CIRCULARSTRING(1 1 2,2 3 2,4 5 2,6 7 2,5 6 2)
Figure
Geometry figure for visual-st-force-3dz-01
Code
SELECT ST_Force3DZ('POLYGON((0 0,0 5,5 0,0 0),(1 1,3 1,1 3,1 1))');
래스터 출력
POLYGON((0 0 0,0 5 0,5 0 0,0 0 0),(1 1 0,3 1 0,1 3 0,1 1 0))
Figure
Geometry figure for visual-st-force-3dz-02

제목

ST_Force3DM — 도형을 XYM 모드로 강제합니다.

요약

geometry ST_Force3DM(geometry geomA, float Mvalue = 0.0);

설명

Forces the geometries into XYM mode. If a geometry has no M component, then a Mvalue M coordinate is tacked on. If it has a Z component, then Z is removed

변경 사항: 2.1.0 미만 버전, 즉 2.0.x 버전까지 이 함수의 명칭은 ST_Force_3DM이었습니다.

Changed: 3.1.0. Added support for supplying a non-zero M value.

This method supports Circular Strings and Curves.

예시

Nothing happens to an already 3D geometry.

Code
SELECT ST_Force3DM('CIRCULARSTRING(1 1 2,2 3 2,4 5 2,6 7 2,5 6 2)');
래스터 출력
CIRCULARSTRINGM(1 1 0,2 3 0,4 5 0,6 7 0,5 6 0)
Figure
Geometry figure for visual-st-force-3dm-01
Code
SELECT ST_Force3DM('POLYGON((0 0 1,0 5 1,5 0 1,0 0 1),(1 1 1,3 1 1,1 3 1,1 1 1))');
래스터 출력
POLYGONM((0 0 0,0 5 0,5 0 0,0 0 0),(1 1 0,3 1 0,1 3 0,1 1 0))
Figure
Geometry figure for visual-st-force-3dm-02

제목

ST_Force4D — 도형을 XYZM 모드로 강제합니다.

요약

geometry ST_Force4D(geometry geomA, float Zvalue = 0.0, float Mvalue = 0.0);

설명

Forces the geometries into XYZM mode. Zvalue and Mvalue is tacked on for missing Z and M dimensions, respectively.

변경 사항: 2.1.0 미만 버전, 즉 2.0.x 버전까지 이 함수의 명칭은 ST_Force_4D였습니다.

Changed: 3.1.0. Added support for supplying non-zero Z and M values.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

예시

Nothing happens to an already 3D geometry.

Code
SELECT ST_Force4D('CIRCULARSTRING(1 1 2,2 3 2,4 5 2,6 7 2,5 6 2)');
래스터 출력
CIRCULARSTRING(1 1 2 0,2 3 2 0,4 5 2 0,6 7 2 0,5 6 2 0)
Figure
Geometry figure for visual-st-force-4d-01
Code
SELECT ST_Force4D('MULTILINESTRINGM((0 0 1,0 5 2,5 0 3,0 0 4),(1 1 1,3 1 1,1 3 1,1 1 1))');
래스터 출력
MULTILINESTRING((0 0 0 1,0 5 0 2,5 0 0 3,0 0 0 4),(1 1 0 1,3 1 0 1,1 3 0 1,1 1 0 1))
Figure
Geometry figure for visual-st-force-4d-02

제목

ST_ForceCollection — 도형을 도형 집합으로 변환합니다.

요약

geometry ST_ForceCollection(geometry geomA);

설명

도형을 도형 집합으로 변환합니다. 이 함수는 WKB 표현식을 단순화하는 데 유용합니다.

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다.

1.2.2 버전부터 사용할 수 있습니다. 1.3.4 미만 버전에서 이 함수에 만곡 도형(curve)을 담고 있는 도형을 입력하면 충돌이 일어났습니다. 1.3.4 버전부터 이 버그가 해결됐습니다.

변경 사항: 2.1.0 미만 버전, 즉 2.0.x 버전까지 이 함수의 명칭은 ST_Force_Collection이었습니다.

This function supports Polyhedral surfaces.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

예시

Code
SELECT ST_ForceCollection('POLYGON((0 0 1,0 5 1,5 0 1,0 0 1),(1 1 1,3 1 1,1 3 1,1 1 1))');
래스터 출력
GEOMETRYCOLLECTION(POLYGON((0 0 1,0 5 1,5 0 1,0 0 1),(1 1 1,3 1 1,1 3 1,1 1 1)))
Figure
Geometry figure for visual-st-force-collection-01
Code
SELECT ST_ForceCollection('CIRCULARSTRING(220227 150406,2220227 150407,220227 150406)');
래스터 출력
GEOMETRYCOLLECTION(CIRCULARSTRING(220227 150406,2220227 150407,220227 150406))
Figure
Geometry figure for visual-st-force-collection-02

This example uses a PolyhedralSurface.

Code
SELECT ST_ForceCollection('POLYHEDRALSURFACE(((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)),
 ((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)),
 ((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)),
 ((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)),
 ((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)),
 ((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1)))');
래스터 출력
GEOMETRYCOLLECTION(
  POLYGON((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)),
  POLYGON((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)),
  POLYGON((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)),
  POLYGON((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)),
  POLYGON((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)),
  POLYGON((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1))
)
                
Figure
Geometry figure for visual-st-force-collection-03

제목

ST_ForceCurve — 적용이 가능한 경우, 도형을 해당 도형의 만곡 유형으로 상위 형변환(upcast)합니다.

요약

geometry ST_ForceCurve(geometry g);

설명

적용이 가능한 경우, 도형을 해당 도형의 만곡 표현식으로 바꿉니다. 라인을 복합 곡선(compoundcurve)으로, 멀티라인을 멀티커브로, 폴리곤을 커브폴리곤으로, 멀티폴리곤을 멀티서페이스(multisurface)로 변환합니다. 입력 폴리곤이 이미 만곡된 표현식인 경우 입력 표현식을 그대로 반환합니다.

2.2.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

예시

Code
SELECT ST_ForceCurve('POLYGON((0 0 2,5 0 2,0 5 2,0 0 2),(1 1 2,1 3 2,3 1 2,1 1 2))'::geometry
  );
래스터 출력
CURVEPOLYGON Z ((0 0 2,5 0 2,0 5 2,0 0 2),(1 1 2,1 3 2,3 1 2,1 1 2))
Figure
Geometry figure for visual-st-forcecurve-01

제목

ST_ForcePolygonCCW — Orients all exterior rings counter-clockwise and all interior rings clockwise.

요약

geometry ST_ForcePolygonCCW(geometry geom);

설명

Forces (Multi)Polygons to use a counter-clockwise orientation for their exterior ring, and a clockwise orientation for their interior rings. Non-polygonal geometries are returned unchanged.

2.2.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

This function supports M coordinates.

예시

Force a polygon and its hole to use counter-clockwise exterior rings and clockwise interior rings.

Code
WITH data AS (
  SELECT 'POLYGON((0 0,0 4,4 4,4 0,0 0),
                  (1 1,3 1,3 3,1 3,1 1))'::geometry AS geom
)
SELECT geom AS input_polygon,
       ST_ForcePolygonCCW(geom) AS ccw_polygon
FROM data;
래스터 출력
POLYGON((0 0,0 4,4 4,4 0,0 0),(1 1,3 1,3 3,1 3,1 1)) | POLYGON((0 0,4 0,4 4,0 4,0 0),(1 1,1 3,3 3,3 1,1 1))
Figure
Geometry figure for visual-st-forcepolygonccw-01

제목

ST_ForcePolygonCW — Orients all exterior rings clockwise and all interior rings counter-clockwise.

요약

geometry ST_ForcePolygonCW(geometry geom);

설명

Forces (Multi)Polygons to use a clockwise orientation for their exterior ring, and a counter-clockwise orientation for their interior rings. Non-polygonal geometries are returned unchanged.

2.2.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

This function supports M coordinates.

예시

Force a polygon and its hole to use clockwise exterior rings and counter-clockwise interior rings.

Code
WITH data AS (
  SELECT 'POLYGON((0 0,4 0,4 4,0 4,0 0),
                  (1 1,1 3,3 3,3 1,1 1))'::geometry AS geom
)
SELECT geom AS input_polygon,
       ST_ForcePolygonCW(geom) AS cw_polygon
FROM data;
래스터 출력
POLYGON((0 0,4 0,4 4,0 4,0 0),(1 1,1 3,3 3,3 1,1 1)) | POLYGON((0 0,0 4,4 4,4 0,0 0),(1 1,3 1,3 3,1 3,1 1))
Figure
Geometry figure for visual-st-forcepolygoncw-01

제목

ST_ForceSFS — Force geometries to use SFS 1.1 or 1.2 geometry types.

요약

geometry ST_ForceSFS(geometry geomA);

geometry ST_ForceSFS(geometry geomA, text version);

설명

Forces a geometry to use the geometry types defined by the requested version of the OGC Simple Features Specification. The default is SFS 1.1. Curved geometries are converted to linear representations, TRIANGLE is converted to POLYGON, and TIN and POLYHEDRALSURFACE are converted to GEOMETRYCOLLECTION values containing POLYGON elements.

If version begins with 1.2, curved geometries are still converted to linear representations, but TRIANGLE, TIN, and POLYHEDRALSURFACE are preserved. Other version values use the default SFS 1.1 behavior. Geometry collections are processed recursively, and the SRID and Z/M coordinates are preserved.

2.1.0 버전부터 사용할 수 있습니다.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

This method supports Circular Strings and Curves.

This function supports 3d and will not drop the z-index.

예시

Compare the geometry types produced for SFS 1.1 (the default) and SFS 1.2. Read each row from the input type in the direction of the result columns.

Code
WITH inputs(geom) AS (VALUES
    ('CIRCULARSTRING(0 0, 1 1, 2 0)'::geometry),
    ('TRIANGLE((0 0, 0 2, 2 0, 0 0))'::geometry),
    ('TIN(((0 0, 0 2, 2 0, 0 0)))'::geometry),
    ('POLYHEDRALSURFACE(((0 0, 0 2, 2 0, 0 0)))'::geometry)
)
SELECT ST_GeometryType(geom) || ' →' AS input,
       ST_GeometryType(ST_ForceSFS(geom)) AS "SFS 1.1 (default)",
       ST_GeometryType(ST_ForceSFS(geom, '1.2')) AS "SFS 1.2"
FROM inputs;
래스터 출력
input          |   SFS 1.1 (default)   |       SFS 1.2
------------------------+-----------------------+----------------------
 ST_CircularString →    | ST_LineString         | ST_LineString
 ST_Triangle →          | ST_Polygon            | ST_Triangle
 ST_Tin →               | ST_GeometryCollection | ST_Tin
 ST_PolyhedralSurface → | ST_GeometryCollection | ST_PolyhedralSurface
(4 rows)

제목

ST_ForceRHR — 폴리곤 안에 있는 꼭짓점들의 방향(orientation)이 오른손 법칙(Right-Hand Rule)을 따르도록 강제합니다.

요약

geometry ST_ForceRHR(geometry g);

설명

Forces the orientation of the vertices in a polygon to follow a Right-Hand-Rule, in which the area that is bounded by the polygon is to the right of the boundary. In particular, the exterior ring is orientated in a clockwise direction and the interior rings in a counter-clockwise direction. This function is a synonym for ST_ForcePolygonCW

[참고]

The above definition of the Right-Hand-Rule conflicts with definitions used in other contexts. To avoid confusion, it is recommended to use ST_ForcePolygonCW.

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다.

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

예시

Code
SELECT ST_ForceRHR('POLYGON((0 0 2,5 0 2,0 5 2,0 0 2),(1 1 2,1 3 2,3 1 2,1 1 2))'
  );
래스터 출력
POLYGON((0 0 2,0 5 2,5 0 2,0 0 2),(1 1 2,3 1 2,1 3 2,1 1 2))
Figure
Geometry figure for visual-st-forcerhr-01

제목

ST_LineExtend — Returns a line extended forwards and backwards by specified distances.

요약

geometry ST_LineExtend(geometry line, float distance_forward, float distance_backward=0.0);

설명

Returns a line extended forwards and backwards by adding new start (and end) points at the given distance(s). A distance of zero does not add a point. Only non-negative distances are allowed. The direction(s) of the added point(s) is determined by the first (and last) two distinct points of the line. Duplicate points are ignored.

Availability: 3.4.0

Example: Extends a line 5 units forward and 6 units backward

Code
SELECT ST_LineExtend('LINESTRING(0 0,0 10)'::geometry, 5, 6);
래스터 출력
LINESTRING(0 -6,0 0,0 10,0 15)
Figure
Geometry figure for visual-st-lineextend-01

제목

ST_LineToCurve — Converts a linear geometry to a curved geometry.

요약

geometry ST_LineToCurve(geometry geomANoncircular);

설명

Converts plain LINESTRING/POLYGON to CIRCULAR STRINGs and Curved Polygons. Note much fewer points are needed to describe the curved equivalent.

[참고]

If the input LINESTRING/POLYGON is not curved enough to clearly represent a curve, the function will return the same input geometry.

Availability: 1.3.0

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

예시

This example converts a linear Polygon approximating a circle to a CurvePolygon.

Code
WITH data AS (
    SELECT ST_Buffer('POINT(1 3)'::geometry, 3) AS geom
)
SELECT geom AS "input_Linear polygon",
       ST_LineToCurve(geom) AS "Curved polygon"
FROM data;
래스터 출력
-[ RECORD 1 ]----------
input_Linear polygon | POLYGON((4 3,3.942 2.415,3.772 1.852,3.494 1.333,3.121 0.879,2.667 0.506,2.148 0.228,1.585 0.058,1 0,0.415 0.058,-0.148 0.228,-0.667 0.506,-1.121 0.879,-1.494 1.333,-1.772 1.852,-1.942 2.415,-2 3,-1.942 3.585,-1.772 4.148,-1.494 4.667,-1.121 5.121,-0.667 5.494,-0.148 5.772,0.415 5.942,1 6,1.585 5.942,2.148 5.772,2.667 5.494,3.121 5.121,3.494 4.667,3.772 4.148,3.942 3.585,4 3))
Curved polygon       | CURVEPOLYGON(CIRCULARSTRING(4 3,-2 3,4 3))
Figure
Geometry figure for visual-st-linetocurve-01

This example converts a 3D linear ring to a CircularString while preserving Z.

Code
WITH data AS (
    SELECT ST_Translate(
        ST_Force3D(ST_Boundary(ST_Buffer(ST_Point(1, 3), 2, 2))),
        0, 0, 3
    ) AS geom
)
SELECT geom AS "input_Linear ring at Z=3",
       ST_LineToCurve(geom) AS "Circular string at Z=3"
FROM data;
래스터 출력
-[ RECORD 1 ]----------
input_Linear ring at Z=3 | LINESTRING Z (3 3 3,2.414 1.586 3,1 1 3,-0.414 1.586 3,-1 3 3,-0.414 4.414 3,1 5 3,2.414 4.414 3,3 3 3)
Circular string at Z=3   | CIRCULARSTRING Z (3 3 3,-1 3 3,3 3 3)
Figure
Geometry figure for visual-st-linetocurve-02

제목

ST_Multi — 도형을 멀티 유형 도형으로 반환합니다.

요약

geometry ST_Multi(geometry geom);

설명

Returns the geometry as a MULTI* geometry collection. If the geometry is already a collection, it is returned unchanged.

예시

A Polygon is converted to a single-element MultiPolygon. The coordinates are unchanged.

Code
SELECT ST_Multi('POLYGON ((10 30,30 30,30 10,10 10,10 30))');
래스터 출력
MULTIPOLYGON(((10 30,30 30,30 10,10 10,10 30)))
Figure
Geometry figure for visual-st-multi-01

참고

ST_AsText


제목

ST_Normalize — 도형을 해당 도형의 기본형으로 반환합니다.

요약

geometry ST_Normalize(geometry geom);

설명

도형을 해당 도형의 정규화된/기본 형태로 반환합니다. 폴리곤 고리, 폴리곤 내부 고리에 있는 꼭짓점, 멀티 유형 도형 집합체의 요소를 재정렬할 수도 있습니다.

대부분의 경우, 테스트 작업 목적으로만 쓸모가 있습니다(기대한 결과물과 반환된 결과물의 비교 등).

2.3.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT ST_Normalize('GEOMETRYCOLLECTION(
    POINT(2 3),
    MULTILINESTRING((0 0,1 1),(2 2,3 3)),
    POLYGON(
      (0 10,0 0,10 0,10 10,0 10),
      (4 2,2 2,2 4,4 4,4 2),
      (6 8,8 8,8 6,6 6,6 8)
    )
  )');
래스터 출력
GEOMETRYCOLLECTION(POLYGON((0 0,0 10,10 10,10 0,0 0),(6 6,8 6,8 8,6 8,6 6),(2 2,4 2,4 4,2 4,2 2)), MULTILINESTRING((2 2,3 3),(0 0,1 1)), POINT(2 3))
Figure
Geometry figure for visual-st-normalize-01

참고

ST_Equals,


제목

ST_Project — Returns a point projected from a start point by a distance and bearing (azimuth).

요약

geometry ST_Project(geometry g1, float distance, float azimuth);

geometry ST_Project(geometry g1, geometry g2, float distance);

geography ST_Project(geography g1, float distance, float azimuth);

geography ST_Project(geography g1, geography g2, float distance);

설명

Returns a point projected from a point along a geodesic using a given distance and azimuth (bearing). This is known as the direct geodesic problem.

The two-point version uses the path from the first to the second point to implicitly define the azimuth and uses the distance as before.

The distance is given in meters. Negative values are supported.

The azimuth (also known as heading or bearing) is given in radians. It is measured clockwise from true north.

  • North is azimuth zero (0 degrees)

  • East is azimuth π/2 (90 degrees)

  • South is azimuth π (180 degrees)

  • West is azimuth 3π/2 (270 degrees)

Negative azimuth values and values greater than 2π (360 degrees) are supported.

2.0.0 버전부터 사용할 수 있습니다.

Enhanced: 2.4.0 Allow negative distance and non-normalized azimuth.

Enhanced: 3.4.0 Allow geometry arguments and two-point form omitting azimuth.

Example: Projected point at 100,000 meters and bearing 45 degrees

Code
SELECT ST_Project('POINT(0 0)'::geography, 100000, radians(45.0));
래스터 출력
POINT(0.635231029125537 0.639472334729198)
Figure
Geometry figure for visual-st-project-01

제목

ST_QuantizeCoordinates — Sets least significant bits of coordinates to zero

요약

geometry ST_QuantizeCoordinates(geometry g, int prec_x, int prec_y = NULL, int prec_z = NULL, int prec_m = NULL);

설명

ST_QuantizeCoordinates determines the number of bits (N) required to represent a coordinate value with a specified number of digits after the decimal point, and then sets all but the N most significant bits to zero. The resulting coordinate value will still round to the original value, but will have improved compressiblity. This can result in a significant disk usage reduction provided that the geometry column is using a compressible storage type. The function allows specification of a different number of digits after the decimal point in each dimension; unspecified dimensions are assumed to have the precision of the x dimension. Negative digits are interpreted to refer digits to the left of the decimal point, (i.e., prec_x=-2 will preserve coordinate values to the nearest 100.

The coordinates produced by ST_QuantizeCoordinates are independent of the geometry that contains those coordinates and the relative position of those coordinates within the geometry. As a result, existing topological relationships between geometries are unaffected by use of this function. The function may produce invalid geometry when it is called with a number of digits lower than the intrinsic precision of the geometry.

Availability: 2.5.0

Technical Background

PostGIS stores all coordinate values as double-precision floating point integers, which can reliably represent 15 significant digits. However, PostGIS may be used to manage data that intrinsically has fewer than 15 significant digits. An example is TIGER data, which is provided as geographic coordinates with six digits of precision after the decimal point (thus requiring only nine significant digits of longitude and eight significant digits of latitude.)

When 15 significant digits are available, there are many possible representations of a number with 9 significant digits. A double precision floating point number uses 52 explicit bits to represent the significand (mantissa) of the coordinate. Only 30 bits are needed to represent a mantissa with 9 significant digits, leaving 22 insignificant bits; we can set their value to anything we like and still end up with a number that rounds to our input value. For example, the value 100.123456 can be represented by the floating point numbers closest to 100.123456000000, 100.123456000001, and 100.123456432199. All are equally valid, in that ST_AsText(geom, 6) will return the same result with any of these inputs. As we can set these bits to any value, ST_QuantizeCoordinates sets the 22 insignificant bits to zero. For a long coordinate sequence this creates a pattern of blocks of consecutive zeros that is compressed by PostgreSQL more efficiently.

[참고]

Only the on-disk size of the geometry is potentially affected by ST_QuantizeCoordinates. ST_MemSize, which reports the in-memory usage of the geometry, will return the the same value regardless of the disk space used by a geometry.

예시

Code
SELECT ST_QuantizeCoordinates('POINT (100.123456 0)'::geometry, 4);
래스터 출력
POINT(100.12344360351562 0)
Figure
Geometry figure for visual-st-quantizecoordinates-01
Code
WITH test AS (SELECT 'POINT (123.456789123456 123.456789123456)'::geometry AS geom)
SELECT
  digits,
  encode(ST_QuantizeCoordinates(geom, digits), 'hex'),
  ST_QuantizeCoordinates(geom, digits)
FROM test, generate_series(15, -15, -1) AS digits;
래스터 출력
digits |                   encode                   |                  st_astext
--------+--------------------------------------------+----------------------------------------------
     15 | 01010000005f9a72083cdd5e405f9a72083cdd5e40 | POINT(123.456789123456 123.456789123456)
     14 | 01010000005f9a72083cdd5e405f9a72083cdd5e40 | POINT(123.456789123456 123.456789123456)
     13 | 01010000005e9a72083cdd5e405e9a72083cdd5e40 | POINT(123.45678912345599 123.45678912345599)
     12 | 0101000000409a72083cdd5e40409a72083cdd5e40 | POINT(123.45678912345556 123.45678912345556)
     11 | 0101000000009a72083cdd5e40009a72083cdd5e40 | POINT(123.45678912345466 123.45678912345466)
     10 | 0101000000009872083cdd5e40009872083cdd5e40 | POINT(123.45678912344738 123.45678912344738)
      9 | 0101000000008072083cdd5e40008072083cdd5e40 | POINT(123.45678912336007 123.45678912336007)
      8 | 0101000000000070083cdd5e40000070083cdd5e40 | POINT(123.45678912103176 123.45678912103176)
      7 | 0101000000000060083cdd5e40000060083cdd5e40 | POINT(123.4567891061306 123.4567891061306)
      6 | 0101000000000000083cdd5e40000000083cdd5e40 | POINT(123.45678901672363 123.45678901672363)
      5 | 0101000000000000003cdd5e40000000003cdd5e40 | POINT(123.456787109375 123.456787109375)
      4 | 0101000000000000003cdd5e40000000003cdd5e40 | POINT(123.456787109375 123.456787109375)
      3 | 01010000000000000038dd5e400000000038dd5e40 | POINT(123.45654296875 123.45654296875)
      2 | 01010000000000000000dd5e400000000000dd5e40 | POINT(123.453125 123.453125)
      1 | 01010000000000000000dc5e400000000000dc5e40 | POINT(123.4375 123.4375)
      0 | 01010000000000000000c05e400000000000c05e40 | POINT(123 123)
     -1 | 01010000000000000000005e400000000000005e40 | POINT(120 120)
     -2 | 010100000000000000000058400000000000005840 | POINT(96 96)
     -3 | 010100000000000000000058400000000000005840 | POINT(96 96)
     -4 | 010100000000000000000058400000000000005840 | POINT(96 96)
     -5 | 010100000000000000000058400000000000005840 | POINT(96 96)
     -6 | 010100000000000000000058400000000000005840 | POINT(96 96)
     -7 | 010100000000000000000058400000000000005840 | POINT(96 96)
     -8 | 010100000000000000000058400000000000005840 | POINT(96 96)
     -9 | 010100000000000000000058400000000000005840 | POINT(96 96)
    -10 | 010100000000000000000058400000000000005840 | POINT(96 96)
    -11 | 010100000000000000000058400000000000005840 | POINT(96 96)
    -12 | 010100000000000000000058400000000000005840 | POINT(96 96)
    -13 | 010100000000000000000058400000000000005840 | POINT(96 96)
    -14 | 010100000000000000000058400000000000005840 | POINT(96 96)
    -15 | 010100000000000000000058400000000000005840 | POINT(96 96)
(31 rows)

제목

ST_RemovePoint — Remove a point from a linestring.

요약

geometry ST_RemovePoint(geometry linestring, integer offset);

설명

Removes a point from a LineString, given its index (0-based). Useful for turning a closed line (ring) into an open linestring.

Enhanced: 3.2.0

1.1.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

예시

Guarantees no lines are closed by removing the end point of closed lines (rings). Assumes geom is of type LINESTRING

Code
UPDATE sometable
    SET geom = ST_RemovePoint(geom, ST_NPoints(geom) - 1)
    FROM sometable
    WHERE ST_IsClosed(geom);

제목

ST_RemoveRepeatedPoints — Returns a version of a geometry with duplicate points removed.

요약

geometry ST_RemoveRepeatedPoints(geometry geom, float8 tolerance = 0.0);

설명

Returns a version of the given geometry with duplicate consecutive points removed. The function processes only (Multi)LineStrings, (Multi)Polygons and MultiPoints but it can be called with any kind of geometry. Elements of GeometryCollections are processed individually. The endpoints of LineStrings are preserved.

If a non-zero tolerance parameter is provided, vertices within the tolerance distance of one another are considered to be duplicates. The distance is computed in 2D (XY plane).

Enhanced: 3.2.0

2.2.0 버전부터 사용할 수 있습니다.

This function supports Polyhedral surfaces.

This function supports 3d and will not drop the z-index.

예시

Code
SELECT ST_RemoveRepeatedPoints('MULTIPOINT ((1 1),(2 2),(3 3),(2 2))');
래스터 출력
MULTIPOINT((1 1),(2 2),(3 3))
Figure
Geometry figure for visual-st-removerepeatedpoints-01
Code
SELECT ST_RemoveRepeatedPoints('LINESTRING (0 0,0 0,1 1,0 0,1 1,2 2)');
래스터 출력
LINESTRING(0 0,1 1,0 0,1 1,2 2)
Figure
Geometry figure for visual-st-removerepeatedpoints-02

Example: Collection elements are processed individually.

Code
SELECT ST_RemoveRepeatedPoints('GEOMETRYCOLLECTION (LINESTRING (1 1,2 2,2 2,3 3),POINT (4 4),POINT (4 4),POINT (5 5))');
래스터 출력
GEOMETRYCOLLECTION(LINESTRING(1 1,2 2,3 3), POINT(4 4), POINT(4 4), POINT(5 5))
Figure
Geometry figure for visual-st-removerepeatedpoints-03

Example: Repeated point removal with a distance tolerance.

Code
SELECT ST_RemoveRepeatedPoints('LINESTRING (0 0,0 0,1 1,5 5,1 1,2 2)', 2);
래스터 출력
LINESTRING(0 0,5 5,2 2)
Figure
Geometry figure for visual-st-removerepeatedpoints-04

제목

ST_RemoveIrrelevantPointsForView — Removes points that are irrelevant for rendering a specific rectangular view of a geometry.

요약

geometry ST_RemoveIrrelevantPointsForView(geometry geom, box2d bounds, boolean cartesian_hint = false);

설명

Returns a geometry without points being irrelevant for rendering the geometry within a given rectangular view.

This function can be used to quickly preprocess geometries that should be rendered only within certain bounds.

Only geometries of type (MULTI)POLYGON and (MULTI)LINESTRING are evaluated. Other geometries keep unchanged.

In contrast to ST_ClipByBox2D() this function

  • sorts out points without computing new intersection points which avoids rounding errors and usually increases performance,

  • returns a geometry with equal or similar point number,

  • leads to the same rendering result within the specified view, and

  • may introduce self-intersections which would make the resulting geometry invalid (see example below).

If cartesian_hint is set to true, the algorithm applies additional optimizations involving cartesian math to further reduce the resulting point number. Please note that using this option might introduce rendering artifacts if the resulting coordinates are projected into another (non-cartesian) coordinate system before rendering.

[주의]

For polygons, this function does currently not ensure that the result is valid. This situation can be checked with ST_IsValid and repaired with ST_MakeValid.

Availability: 3.5.0

예시

The input polygon has 55 points. The result retains 15 points, while rendering the same shape inside the view envelope.

Code
WITH data(geom, view) AS (VALUES (
  'POLYGON((3.2 14.2,6.8 14.2,7.6 11.9,7.2 9.8,7.8 7.2,10.3 7.2,11.5 7.5,13.8 7.2,14.6 5.9,14.2 4.8,14.8 3.2,14.6 0.9,13.2 -1.2,12.8 -3.8,12 -4.1,11 -4,9.8 -4.2,8.8 -4.8,8.3 -2.5,6.5 0.2,5.8 2.2,5.3 0.2,3.5 -1.5,2.8 -3.8,1.6 -4.5,-0.3 -5.2,-2.2 -5.8,-0.9 -4.8,-1.5 -4.4,-1.8 -2.8,-1.2 -1.8,0.5 -1.8,1.8 -1.8,2.3 -0.1,1.5 1.8,1.8 3.2,0 3.5,-3.2 4.2,-5.2 4.2,-4.4 4.9,-4.9 5.5,-4.3 5.9,-3.8 6.4,-3 6.9,-3.2 7.8,-2.2 8.2,-1.7 8.9,-2.7 9.4,-2.2 9.9,-1.4 10.9,-1.8 11.8,-1.2 12.2,-2.3 12.8,-2.9 13.2,0.6 13.5,3.2 14.2))'::geometry,
  ST_MakeEnvelope(0.1, 0, 10, 10)
))
SELECT geom AS input_geom,
       view AS input_view,
       ST_RemoveIrrelevantPointsForView(geom, view, true) AS result,
       view AS view
FROM data;
래스터 출력
-[ RECORD 1 ]----------
input_geom | POLYGON((3.2 14.2,6.8 14.2,7.6 11.9,7.2 9.8,7.8 7.2,10.3 7.2,11.5 7.5,13.8 7.2,14.6 5.9,14.2 4.8,14.8 3.2,14.6 0.9,13.2 -1.2,12.8 -3.8,12 -4.1,11 -4,9.8 -4.2,8.8 -4.8,8.3 -2.5,6.5 0.2,5.8 2.2,5.3 0.2,3.5 -1.5,2.8 -3.8,1.6 -4.5,-0.3 -5.2,-2.2 -5.8,-0.9 -4.8,-1.5 -4.4,-1.8 -2.8,-1.2 -1.8,0.5 -1.8,1.8 -1.8,2.3 -0.1,1.5 1.8,1.8 3.2,0 3.5,-3.2 4.2,-5.2 4.2,-4.4 4.9,-4.9 5.5,-4.3 5.9,-3.8 6.4,-3 6.9,-3.2 7.8,-2.2 8.2,-1.7 8.9,-2.7 9.4,-2.2 9.9,-1.4 10.9,-1.8 11.8,-1.2 12.2,-2.3 12.8,-2.9 13.2,0.6 13.5,3.2 14.2))
input_view | POLYGON((0.1 0,0.1 10,10 10,10 0,0.1 0))
result     | POLYGON((7.6 11.9,7.2 9.8,7.8 7.2,10.3 7.2,11 -4,8.3 -2.5,6.5 0.2,5.8 2.2,5.3 0.2,3.5 -1.5,2.3 -0.1,1.5 1.8,1.8 3.2,0 3.5,-2.9 13.2,7.6 11.9))
view       | POLYGON((0.1 0,0.1 10,10 10,10 0,0.1 0))
Figure
Geometry figure for visual-st-removeirrelevantpointsforview-01

Only linework affecting the view is retained; existing vertices are reused.

Code
WITH data(geom, view) AS (VALUES (
  'MULTILINESTRING((0 0,10 0,20 0,30 0),(0 15,5 15,10 15,15 15,20 15,25 15,30 15,40 15),(13 13,15 15,17 17))'::geometry,
  ST_MakeEnvelope(12, 12, 18, 18)
))
SELECT geom AS input_geom,
       view AS input_view,
       ST_RemoveIrrelevantPointsForView(geom, view, true) AS result,
       view AS view
FROM data;
래스터 출력
-[ RECORD 1 ]----------
input_geom | MULTILINESTRING((0 0,10 0,20 0,30 0),(0 15,5 15,10 15,15 15,20 15,25 15,30 15,40 15),(13 13,15 15,17 17))
input_view | POLYGON((12 12,12 18,18 18,18 12,12 12))
result     | MULTILINESTRING((10 15,15 15,20 15),(13 13,15 15,17 17))
view       | POLYGON((12 12,12 18,18 18,18 12,12 12))
Figure
Geometry figure for visual-st-removeirrelevantpointsforview-02

A line with no segment relevant to the view becomes empty.

Code
SELECT ST_RemoveIrrelevantPointsForView('LINESTRING(0 0,10 0,20 0,30 0)',
ST_MakeEnvelope(12, 12, 18, 18), true);
래스터 출력
LINESTRING

Removing vertices without computing intersections can introduce self-intersections in the result.

Code
WITH data(geom, view) AS (VALUES (
  'POLYGON((0 10,0 0,10 -10,30 0,25 20,10 -5,0 10))'::geometry,
  ST_MakeEnvelope(-5, 1, 20, 12)
))
SELECT geom AS input_geom,
       view AS input_view,
       ST_RemoveIrrelevantPointsForView(geom, view, true) AS result,
       view AS view
FROM data;
래스터 출력
-[ RECORD 1 ]----------
input_geom | POLYGON((0 10,0 0,10 -10,30 0,25 20,10 -5,0 10))
input_view | POLYGON((-5 1,-5 12,20 12,20 1,-5 1))
result     | POLYGON((0 10,0 0,30 0,25 20,10 -5,0 10))
view       | POLYGON((-5 1,-5 12,20 12,20 1,-5 1))
Figure
Geometry figure for visual-st-removeirrelevantpointsforview-04

With the default cartesian_hint, the function removes only points known to be irrelevant to the view.

Code
WITH data(geom, view) AS (VALUES (
  'POLYGON((0 30,15 30,30 30,30 0,0 0,0 30))'::geometry,
  ST_MakeEnvelope(12, 12, 18, 18)
))
SELECT geom AS input_geom,
       view AS input_view,
       ST_RemoveIrrelevantPointsForView(geom, view) AS result,
       view AS view
FROM data;
래스터 출력
-[ RECORD 1 ]----------
input_geom | POLYGON((0 30,15 30,30 30,30 0,0 0,0 30))
input_view | POLYGON((12 12,12 18,18 18,18 12,12 12))
result     | POLYGON((0 30,30 30,30 0,0 0,0 30))
view       | POLYGON((12 12,12 18,18 18,18 12,12 12))
Figure
Geometry figure for visual-st-removeirrelevantpointsforview-05

제목

ST_RemoveSmallParts — Removes small parts (polygon rings or linestrings) of a geometry.

요약

geometry ST_RemoveSmallParts(geometry geom, double precision minSizeX, double precision minSizeY);

설명

Returns a geometry without small parts (exterior or interior polygon rings, or linestrings).

This function can be used as preprocessing step for creating simplified maps, e. g. to remove small islands or holes.

It evaluates only geometries of type (MULTI)POLYGON and (MULTI)LINESTRING. Other geometries remain unchanged.

If minSizeX is greater than 0, parts are sorted out if their width is smaller than minSizeX.

If minSizeY is greater than 0, parts are sorted out if their height is smaller than minSizeY.

Both minSizeX and minSizeY are measured in coordinate system units of the geometry.

For polygon types, evaluation is done separately for each ring which can lead to one of the following results:

  • the original geometry,

  • a POLYGON with all rings with less vertices,

  • a POLYGON with a reduced number of interior rings (having possibly less vertices),

  • a POLYGON EMPTY, or

  • a MULTIPOLYGON with a reduced number of polygons (having possibly less interior rings or vertices), or

  • a MULTIPOLYGON EMPTY.

For linestring types, evaluation is done for each linestring which can lead to one of the following results:

  • the original geometry,

  • a LINESTRING with a reduced number of vertices,

  • a LINESTRING EMPTY,

  • a MULTILINESTRING with a reduced number of linestrings (having possibly less vertices), or

  • a MULTILINESTRING EMPTY.

Availability: 3.5.0

예시

Code
SELECT ST_RemoveSmallParts('MULTIPOLYGON(
    ((60 160,120 160,120 220,60 220,60 160),(70 170,70 210,110 210,110 170,70 170)),
    ((85 75,155 75,155 145,85 145,85 75)),
    ((50 110,70 110,70 130,50 130,50 110)))',
    50, 50);
래스터 출력
MULTIPOLYGON(((60 160,120 160,120 220,60 220,60 160)),((85 75,155 75,155 145,85 145,85 75)))
Figure
Geometry figure for visual-st-removesmallparts-01
Code
SELECT ST_RemoveSmallParts('LINESTRING(10 10,20 20)',
    50, 50);
래스터 출력
LINESTRING

제목

ST_Reverse — 꼭짓점들의 순서가 반대인 도형을 반환합니다.

요약

geometry ST_Reverse(geometry g1);

설명

어떤 도형도 입력받을 수 있으며, 꼭짓점들의 순서를 반전시킵니다.

Enhanced: 2.4.0 support for curves was introduced.

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

예시

Code
WITH data(geom) AS (VALUES (
  ST_MakeLine(ST_Point(1, 2), ST_Point(1, 10))
))
SELECT geom AS input_line,
       ST_Reverse(geom) AS reversed_line
FROM data;
래스터 출력
input_line      |    reversed_line
----------------------+----------------------
 LINESTRING(1 2,1 10) | LINESTRING(1 10,1 2)
(1 row)
Figure
Geometry figure for visual-st-reverse-01

제목

ST_Segmentize — Returns a modified geometry/geography having no segment longer than a given distance.

요약

geometry ST_Segmentize(geometry geom, float max_segment_length);

geography ST_Segmentize(geography geog, float max_segment_length);

설명

Returns a modified geometry/geography having no segment longer than max_segment_length. Length is computed in 2D. Segments are always split into equal-length subsegments.

  • For geometry, the maximum length is in the units of the spatial reference system.

  • For geography, the maximum length is in meters. Distances are computed on the sphere. Added vertices are created along the spherical great-circle arcs defined by segment endpoints.

[참고]

This only shortens long segments. It does not lengthen segments shorter than the maximum length.

[주의]

For inputs containing long segments, specifying a relatively short max_segment_length can cause a very large number of vertices to be added. This can happen unintentionally if the argument is specified accidentally as a number of segments, rather than a maximum length.

1.2.2 버전부터 사용할 수 있습니다.

Enhanced: 3.0.0 Segmentize geometry now produces equal-length subsegments

Enhanced: 2.3.0 Segmentize geography now produces equal-length subsegments

개선 사항: 2.1.0 버전부터 지리형을 지원하기 시작했습니다.

Changed: 2.1.0 As a result of the introduction of geography support, the usage ST_Segmentize('LINESTRING(1 2, 3 4)', 0.5) causes an ambiguous function error. The input needs to be properly typed as a geometry or geography. Use ST_GeomFromText, ST_GeogFromText or a cast to the required type (e.g. ST_Segmentize('LINESTRING(1 2, 3 4)'::geometry, 0.5) )

예시

Segmentizing a line. Long segments are split evenly, and short segments are not split.

Code
SELECT ST_Segmentize('MULTILINESTRING((0 0,0 1,0 9),(1 10,1 18))'::geometry,
5);
래스터 출력
MULTILINESTRING((0 0,0 1,0 5,0 9),(1 10,1 14,1 18))
Figure
Geometry figure for visual-st-segmentize-01

Segmentizing a polygon:

Code
SELECT ST_Segmentize('POLYGON((0 0,0 8,30 0,0 0))'::geometry,
        10);
래스터 출력
POLYGON((0 0,0 8,7.5 6,15 4,22.5 2,30 0,20 0,10 0,0 0))
Figure
Geometry figure for visual-st-segmentize-02

Segmentizing a geographic line, using a maximum segment length of 2000 kilometers. Vertices are added along the great-circle arc connecting the endpoints.

Code
SELECT ST_Segmentize(('LINESTRING (0 0,60 60)'::geography), 2000000);
래스터 출력
LINESTRING(0 0,4.252632294621186 8.43596525986862,8.69579947419404 16.824093489701564,13.550465473227048 25.107950473646188,19.1066053508691 33.21091076089908,25.779290201459894 41.01711439406505,34.188839517966954 48.337222885886,45.238153936612264 54.84733442373889,60 60)
Figure
Geometry figure for visual-st-segmentize-03

제목

ST_SetPoint — 라인스트링의 포인트를 주어진 포인트로 대체합니다.

요약

geometry ST_SetPoint(geometry linestring, integer zerobasedposition, geometry point);

설명

라인스트링의 N번째 포인트를 주어진 포인트로 대체합니다. 인덱스는 0-기반입니다. 음수 인덱스는 반대로 세기 때문에, -1이 마지막 포인트가 됩니다. 꼭짓점 하나가 움직였을 때 연결 관계를 유지하려는 경우 이 함수가 트리거 역할로 특히 유용합니다.

1.1.0 버전부터 사용할 수 있습니다.

업데이트 사항: 2.3.0 버전에서 음수 인덱스를 지원하기 시작했습니다.

This function supports 3d and will not drop the z-index.

예시

Change first point in line string from -1 3 to -1 1.

Code
SELECT ST_SetPoint('LINESTRING(-1 2,-1 3)', 0, 'POINT(-1 1)');
래스터 출력
LINESTRING(-1 1,-1 3)
Figure
Geometry figure for visual-st-setpoint-01

Change last point in a line string (let's play with 3D linestring this time)

Code
SELECT ST_SetPoint(foo.geom, ST_NumPoints(foo.geom) - 1, 'POINT(-1 1 3)')
FROM (SELECT 'LINESTRING(-1 2 3,-1 3 4,5 6 7)'::geometry As geom) As foo;
래스터 출력
LINESTRING(-1 2 3,-1 3 4,-1 1 3)
Figure
Geometry figure for visual-st-setpoint-02
Code
SELECT ST_SetPoint(g, -3, p)
FROM ST_GeomFromText('LINESTRING(0 0,1 1,2 2,3 3,4 4)') AS g
    CROSS JOIN ST_PointN(g, 1) as p;
래스터 출력
LINESTRING(0 0,1 1,0 0,3 3,4 4)
Figure
Geometry figure for visual-st-setpoint-03

제목

ST_ShiftLongitude — Shifts the longitude coordinates of a geometry between -180..180 and 0..360.

요약

geometry ST_ShiftLongitude(geometry geom);

설명

Reads every point/vertex in a geometry, and shifts its longitude coordinate from -180..0 to 180..360 and vice versa if between these ranges. This function is symmetrical so the result is a 0..360 representation of a -180..180 data and a -180..180 representation of a 0..360 data.

[참고]

This is only useful for data with coordinates in longitude/latitude; e.g. SRID 4326 (WGS 84 geographic)

[주의]

1.3.4 미만 버전에서는 버그 때문에 멀티포인트를 입력받지 못 했습니다. 1.3.4 버전부터 멀티포인트도 입력할 수 있습니다.

This function supports 3d and will not drop the z-index.

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface) 및 TIN을 지원합니다.

주의: 2.2.0 미만 버전에서, 이 함수의 명칭은 "ST_Shift_Longitude"였습니다.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

This example performs a forward longitude shift on a single point.

Code
SELECT ST_ShiftLongitude('SRID=4326;POINT(270 0)'::geometry)
래스터 출력
POINT(-90 0)
Figure
Geometry figure for visual-st-shiftlongitude-01

This example performs a reverse longitude shift on a single point.

Code
SELECT ST_ShiftLongitude('SRID=4326;POINT(-90 0)'::geometry)
래스터 출력
POINT(270 0)
Figure
Geometry figure for visual-st-shiftlongitude-02

This example shows that LineStrings are shifted only where coordinates require it.

Code
SELECT ST_ShiftLongitude('SRID=4326;LINESTRING(174 12,182 13)'::geometry)
래스터 출력
LINESTRING(174 12,-178 13)
Figure
Geometry figure for visual-st-shiftlongitude-03

참고

ST_WrapX


제목

ST_WrapX — X값 근처에서 도형을 래핑합니다.

요약

geometry ST_WrapX(geometry geom, float8 wrap, float8 move);

설명

This function splits the input geometries and then moves every resulting component falling on the right (for negative 'move') or on the left (for positive 'move') of given 'wrap' line in the direction specified by the 'move' parameter, finally re-unioning the pieces together.

[참고]

이 함수는 경위도 입력물이 한 편에서 다른 편으로 걸쳐 있지 않은 관심 피처를 갖도록 하는 데 유용합니다.

Availability: 2.3.0 requires GEOS

This function supports 3d and will not drop the z-index.

예시

Move all components whose bounding boxes fall completely to the left of x = 0 by +360.

Code
SELECT ST_WrapX(geom, 0, 360);

Move all components whose bounding boxes fall completely to the left of x = -30 by +360.

Code
SELECT ST_WrapX(geom, -30, 360);

제목

ST_SnapToGrid — 입력 도형의 모든 포인트를 정규 그리드로 스냅(snap)시킵니다.

요약

geometry ST_SnapToGrid(geometry geomA, float originX, float originY, float sizeX, float sizeY);

geometry ST_SnapToGrid(geometry geomA, float sizeX, float sizeY);

geometry ST_SnapToGrid(geometry geomA, float size);

geometry ST_SnapToGrid(geometry geomA, geometry pointOrigin, float sizeX, float sizeY, float sizeZ, float sizeM);

설명

변종 1, 2, 3: 입력 도형의 모든 포인트를 원점과 셀(cell) 크기로 정의된 그리드로 스냅(snap)시킵니다. 동일한 셀에 떨어지는 연속된 포인트들을 제거하며, 출력 포인트들이 주어진 유형의 도형을 정의하기에 부족할 경우 결국 NULL을 반환합니다. 도형 집합 안에서 이렇게 붕괴된 도형은 집합에서 제외됩니다. 정확도를 낮추는 데 유용합니다.

변종 4: 1.1.0 버전에서 추가되었습니다. 입력 도형의 모든 포인트를 원점(두 번째 인수, 포인트여야 합니다) 및 셀 크기로 정의된 그리드로 스냅시킵니다. 사용자가 그리드로 스냅시키고 싶지 않은 차원의 경우, 셀 크기를 0으로 설정하십시오.

[참고]

반환되는 도형이 단순성을 잃을 수도 있습니다(ST_IsSimple 참조).

[참고]

1.1.0 버전 배포 전에는 이 함수가 항상 2차원 도형을 반환했습니다. 1.1.0 버전부터 반환되는 도형이, 더 높은 차원값은 건드리지 않은 채, 입력 도형과 동일한 차원수를 가지게 됐습니다. 모든 그리드 차원을 정의하려면 두 번째 도형 인자를 입력받는 버전을 이용하십시오.

1.0.0RC1 버전부터 사용할 수 있습니다.

1.1.0 버전부터 Z 및 M을 지원합니다.

This function supports 3d and will not drop the z-index.

예시

Snap a geometry column to a precision grid of 10^-3.

Code
UPDATE mytable
   SET geom = ST_SnapToGrid(geom, 0.001);

Display how the same grid size rounds a LineString.

Code
SELECT ST_SnapToGrid('LINESTRING(1.1115678 2.123,4.111111 3.2374897,4.11112 3.23748667)'::geometry,
        0.001);
래스터 출력
LINESTRING(1.112 2.123,4.111 3.237)
Figure
Geometry figure for visual-st-snaptogrid-01

This example snaps a 4D geometry.

Code
SELECT ST_SnapToGrid('LINESTRING(-1.1115678 2.123 2.3456 1.11111,
        4.111111 3.2374897 3.1234 1.1111,-1.11111112 2.123 2.3456 1.1111112)'::geometry,
        'POINT(1.12 2.22 3.2 4.4444)',
        0.1, 0.1, 0.1, 0.01);
래스터 출력
LINESTRING(-1.08 2.12 2.3 1.1144,4.12 3.22 3.1 1.1144,-1.08 2.12 2.3 1.1144)
Figure
Geometry figure for visual-st-snaptogrid-02

With a 4D geometry - the ST_SnapToGrid(geom,size) only touches x and y coords but keeps m and z the same.

Code
SELECT ST_SnapToGrid('LINESTRING(-1.1115678 2.123 3 2.3456,
        4.111111 3.2374897 3.1234 1.1111)'::geometry,
       0.01);
래스터 출력
LINESTRING(-1.11 2.12 3 2.3456,4.11 3.24 3.1234 1.1111)
Figure
Geometry figure for visual-st-snaptogrid-03

제목

ST_Snap — 입력 도형의 분절 구간과 꼭짓점을 참조 도형의 꼭짓점으로 스냅시킵니다.

요약

geometry ST_Snap(geometry input, geometry reference, float tolerance);

설명

Snaps the vertices and segments of a geometry to another Geometry's vertices. A snap distance tolerance is used to control where snapping is performed. The result geometry is the input geometry with the vertices snapped. If no snapping occurs then the input geometry is returned unchanged.

한 도형을 또다른 도형으로 스냅시키면, (노드 및 교차점 계산 과정에서 문제를 일으킬 수 있는) 거의 일치하는 경계선을 제거함으로써 오버레이 연산을 강력하게 향상시킬 수 있습니다.

스냅을 너무 많이 하면 유효하지 않은 지형을 생성하는 결과를 가져올 수 있기 때문에, 경험식(heuristics)을 통해 어떤 경우 안전하게 스냅시킬 수 있는지 알아내서 스냅시킬 꼭짓점의 개수 및 위치를 결정합니다. 하지만 이런 방식은 몇몇 가능할 수도 있는 스냅 작업을 제외하게 될 수도 있습니다.

[참고]

반환되는 도형이 단순성(ST_IsSimple 참조) 및 유효성(ST_IsValid 참조)을 잃을 수도 있습니다.

GEOS 모듈로 실행

2.0.0 버전부터 사용할 수 있습니다.

예시

A MultiPolygon snapped to a LineString at 1.01 times their distance.

Code
SELECT ST_Snap(poly, line, ST_Distance(poly, line)*1.01) AS polysnapped
FROM (SELECT
   ST_GeomFromText('MULTIPOLYGON(
     ((26 125,26 200,126 200,126 125,26 125 ),
      ( 51 150,101 150,76 175,51 150 )),
      (( 151 100,151 200,176 175,151 100 )))') As poly,
       ST_GeomFromText('LINESTRING (5 107,54 84,101 100)') As line
    ) As foo;
래스터 출력
MULTIPOLYGON(((26 125,26 200,126 200,126 125,101 100,26 125),
(51 150,101 150,76 175,51 150)),((151 100,151 200,176 175,151 100)))
Figure
Geometry figure for visual-st-snap-01

A MultiPolygon snapped to a LineString at 1.25 times their distance.

Code
SELECT ST_Snap(poly, line, ST_Distance(poly, line)*1.25) AS polysnapped
FROM (SELECT
  ST_GeomFromText('MULTIPOLYGON(
    (( 26 125,26 200,126 200,126 125,26 125 ),
      ( 51 150,101 150,76 175,51 150 )),
      (( 151 100,151 200,176 175,151 100 )))') As poly,
       ST_GeomFromText('LINESTRING (5 107,54 84,101 100)') As line
    ) As foo;
래스터 출력
MULTIPOLYGON(((5 107,26 200,126 200,126 125,101 100,54 84,5 107),
(51 150,101 150,76 175,51 150)),((151 100,151 200,176 175,151 100)))
Figure
Geometry figure for visual-st-snap-02

The LineString snapped to the original MultiPolygon at 1.01 times their distance.

Code
SELECT ST_Snap(line, poly, ST_Distance(poly, line)*1.01) AS linesnapped
FROM (SELECT
  ST_GeomFromText('MULTIPOLYGON(
     ((26 125,26 200,126 200,126 125,26 125),
      (51 150,101 150,76 175,51 150 )),
      ((151 100,151 200,176 175,151 100)))') As poly,
       ST_GeomFromText('LINESTRING (5 107,54 84,101 100)') As line
    ) As foo;
래스터 출력
LINESTRING(5 107,26 125,54 84,101 100)
Figure
Geometry figure for visual-st-snap-03

The LineString snapped to the original MultiPolygon at 1.25 times their distance.

Code
SELECT ST_Snap(line, poly, ST_Distance(poly, line)*1.25) AS linesnapped
FROM (SELECT
  ST_GeomFromText('MULTIPOLYGON(
     (( 26 125,26 200,126 200,126 125,26 125 ),
      (51 150,101 150,76 175,51 150 )),
      ((151 100,151 200,176 175,151 100 )))') As poly,
       ST_GeomFromText('LINESTRING (5 107,54 84,101 100)') As line
    ) As foo;
래스터 출력
LINESTRING(26 125,54 84,101 100)
Figure
Geometry figure for visual-st-snap-04

제목

ST_SwapOrdinates — 입력 도형을 좌표값을 뒤바꾼 상태로 반환합니다.

요약

geometry ST_SwapOrdinates(geometry geom, cstring ords);

설명

입력 도형을 좌표값을 뒤바꾼 상태로 반환합니다.

ords 파라미터는 뒤바꿀 좌표를 명명하는 문자 2개 길이의 스트링입니다. 유효한 명칭은 x, y, z, 그리고 m입니다.

2.2.0 버전부터 사용할 수 있습니다.

This method supports Circular Strings and Curves.

This function supports 3d and will not drop the z-index.

This function supports M coordinates.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

This example scales the M value by 2.

Code
SELECT ST_SwapOrdinates(ST_Scale(ST_SwapOrdinates(g, 'xm'),
      2, 1
    ),
  'xm') FROM ( SELECT 'POINT ZM (0 0 0 2)'::geometry g ) foo;
래스터 출력
POINT ZM (0 0 0 4)
Figure
Geometry figure for visual-st-swapordinates-01

7.6. Geometry Validation

초록

These functions test whether geometries are valid according to the OGC SFS standard. They also provide information about the nature and location of invalidity. There is also a function to create a valid geometry out of an invalid one.

  • ST_IsValid — Tests if a geometry is well-formed in 2D.
  • ST_IsValidDetail — Returns a valid_detail row stating if a geometry is valid or if not a reason and a location.
  • ST_IsValidReason — Returns text stating if a geometry is valid, or a reason for invalidity.
  • ST_MakeValid — Attempts to make an invalid geometry valid without losing vertices.

제목

ST_IsValid — Tests if a geometry is well-formed in 2D.

요약

boolean ST_IsValid(geometry g);

boolean ST_IsValid(geometry g, integer flags);

설명

Tests if an ST_Geometry value is well-formed and valid in 2D according to the OGC rules. For geometries with 3 and 4 dimensions, the validity is still only tested in 2 dimensions. For geometries that are invalid, a PostgreSQL NOTICE is emitted providing details of why it is not valid.

For the version with the flags parameter, supported values are documented in ST_IsValidDetail This version does not print a NOTICE explaining invalidity.

For more information on the definition of geometry validity, refer to 4.4절. “Geometry Validation”

[참고]

SQL-MM defines the result of ST_IsValid(NULL) to be 0, while PostGIS returns NULL.

GEOS 모듈로 실행

The version accepting flags is available starting with 2.0.0.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1.

This method implements the SQL/MM specification. SQL-MM 3: 5.1.9

[참고]

Neither OGC-SFS nor SQL-MM specifications include a flag argument for ST_IsValid. The flag is a PostGIS extension.

예시

Code
SELECT ST_IsValid('LINESTRING(0 0,1 1)') As good_line,
ST_IsValid('POLYGON((0 0,1 1,1 2,1 1,0 0))') As bad_poly;
래스터 출력
NOTICE:  Self-intersection at or near point 0 0
 good_line | bad_poly
-----------+----------
 t         | f
Figure
Geometry figure for visual-st-isvalid-01

Find tables with invalid geometries in registered geometry columns.

Code
CREATE TEMP TABLE invalid_geometry_columns (
    table_name text,
    column_name text,
    invalid_count bigint
);

DO $$
DECLARE
    rec record;
    invalid_count bigint;
BEGIN
    FOR rec IN
        SELECT f_table_schema, f_table_name, f_geometry_column
        FROM geometry_columns
        ORDER BY f_table_schema, f_table_name, f_geometry_column
    LOOP
        EXECUTE format(
            'SELECT count(*) FROM %I.%I WHERE NOT ST_IsValid(%I, 0)',
            rec.f_table_schema,
            rec.f_table_name,
            rec.f_geometry_column
        ) INTO invalid_count;

        IF invalid_count 
> 0 THEN
            INSERT INTO invalid_geometry_columns
            VALUES (
                format('%I.%I', rec.f_table_schema, rec.f_table_name),
                rec.f_geometry_column,
                invalid_count
            );
        END IF;
    END LOOP;
END;
$$;

SELECT * FROM invalid_geometry_columns;

제목

ST_IsValidDetail — Returns a valid_detail row stating if a geometry is valid or if not a reason and a location.

요약

valid_detail ST_IsValidDetail(geometry geom, integer flags);

설명

Returns a valid_detail row, containing a boolean (valid) stating if a geometry is valid, a varchar (reason) stating a reason why it is invalid and a geometry (location) pointing out where it is invalid.

Useful to improve on the combination of ST_IsValid and ST_IsValidReason to generate a detailed report of invalid geometries.

The optional flags parameter is a bitfield. It can have the following values:

  • 0: Use usual OGC SFS validity semantics.

  • 1: Consider certain kinds of self-touching rings (inverted shells and exverted holes) as valid. This is also known as "the ESRI flag", since this is the validity model used by those tools. Note that this is invalid under the OGC model.

GEOS 모듈로 실행

2.0.0 버전부터 사용할 수 있습니다.

예시

This example returns the first three rejects from a successful quintuplet experiment.

Code
SELECT gid, reason(ST_IsValidDetail(geom)), location(ST_IsValidDetail(geom)) as location
FROM
(SELECT ST_MakePolygon(ST_ExteriorRing(e.buff), array_agg(f.line)) As geom, gid
FROM (SELECT ST_Buffer(ST_Point(x1*10,y1), z1) As buff, x1*10 + y1*100 + z1*1000 As gid
    FROM generate_series(-4,6) x1
    CROSS JOIN generate_series(2,5) y1
    CROSS JOIN generate_series(1,8) z1
    WHERE x1 
> y1*0.5 AND z1 < x1*y1) As e
    INNER JOIN (SELECT ST_Translate(ST_ExteriorRing(ST_Buffer(ST_Point(x1*10,y1), z1)),y1*1, z1*2) As line
    FROM generate_series(-3,6) x1
    CROSS JOIN generate_series(2,5) y1
    CROSS JOIN generate_series(1,10) z1
    WHERE x1 
> y1*0.75 AND z1 < x1*y1) As f
ON (ST_Area(e.buff) 
> 78 AND ST_Contains(e.buff, f.line))
GROUP BY gid, e.buff) As quintuplet_experiment
WHERE ST_IsValid(geom) = false
ORDER BY gid
LIMIT 3;
래스터 출력
 gid  |      reason       |  location
------+-------------------+-------------
 5330 | Self-intersection | POINT(32 5)
 5340 | Self-intersection | POINT(42 5)
 5350 | Self-intersection | POINT(52 5)

This example reports a valid LineString.

Code
SELECT * FROM ST_IsValidDetail('LINESTRING(220227 150406,2220227 150407,222020 150410)');
래스터 출력
 valid | reason | location
-------+--------+----------
 t     |        |
Figure
Geometry figure for visual-st-isvaliddetail-02

제목

ST_IsValidReason — Returns text stating if a geometry is valid, or a reason for invalidity.

요약

text ST_IsValidReason(geometry geomA);

text ST_IsValidReason(geometry geomA, integer flags);

설명

Returns text stating if a geometry is valid, or if invalid a reason why.

Useful in combination with ST_IsValid to generate a detailed report of invalid geometries and reasons.

Allowed flags are documented in ST_IsValidDetail.

GEOS 모듈로 실행

Availability: 1.4

Availability: 2.0 version taking flags.

예시

This example uses an invalid bow-tie polygon.

Code
SELECT ST_IsValidReason(
    'POLYGON ((100 200,100 100,200 200,
     200 100,100 200))'::geometry) as validity_info;
래스터 출력
Self-intersection[150 150]
Figure
Geometry figure for visual-st-isvalidreason-01

This example returns the first three rejects from a successful quintuplet experiment.

Code
SELECT gid, ST_IsValidReason(geom) as validity_info
FROM
(SELECT ST_MakePolygon(ST_ExteriorRing(e.buff), array_agg(f.line)) As geom, gid
FROM (SELECT ST_Buffer(ST_Point(x1*10,y1), z1) As buff, x1*10 + y1*100 + z1*1000 As gid
    FROM generate_series(-4,6) x1
    CROSS JOIN generate_series(2,5) y1
    CROSS JOIN generate_series(1,8) z1
    WHERE x1 
> y1*0.5 AND z1 < x1*y1) As e
    INNER JOIN (SELECT ST_Translate(ST_ExteriorRing(ST_Buffer(ST_Point(x1*10,y1), z1)),y1*1, z1*2) As line
    FROM generate_series(-3,6) x1
    CROSS JOIN generate_series(2,5) y1
    CROSS JOIN generate_series(1,10) z1
    WHERE x1 
> y1*0.75 AND z1 < x1*y1) As f
ON (ST_Area(e.buff) 
> 78 AND ST_Contains(e.buff, f.line))
GROUP BY gid, e.buff) As quintuplet_experiment
WHERE ST_IsValid(geom) = false
ORDER BY gid
LIMIT 3;
래스터 출력
 gid  |      validity_info
------+--------------------------
 5330 | Self-intersection [32 5]
 5340 | Self-intersection [42 5]
 5350 | Self-intersection [52 5]

Simple example.

Code
SELECT ST_IsValidReason('LINESTRING(220227 150406,2220227 150407,222020 150410)');
래스터 출력
 st_isvalidreason
------------------
 Valid Geometry
Figure
Geometry figure for visual-st-isvalidreason-03

제목

ST_MakeValid — Attempts to make an invalid geometry valid without losing vertices.

요약

geometry ST_MakeValid(geometry input);

geometry ST_MakeValid(geometry input, text params);

설명

The function attempts to create a valid representation of a given invalid geometry without losing any of the input vertices. Valid geometries are returned unchanged.

Supported inputs are: POINTS, MULTIPOINTS, LINESTRINGS, MULTILINESTRINGS, POLYGONS, MULTIPOLYGONS and GEOMETRYCOLLECTIONS containing any mix of them.

In case of full or partial dimensional collapses, the output geometry may be a collection of lower-to-equal dimension geometries, or a geometry of lower dimension.

Single polygons may become multi-geometries in case of self-intersections.

The params argument can be used to supply an options string to select the method to use for building valid geometry. The options string is in the format "method=linework|structure keepcollapsed=true|false". If no "params" argument is provided, the "linework" algorithm will be used as the default.

The "method" key has two values.

  • "linework" is the default algorithm, and builds valid geometries by first extracting all lines, noding that linework together, then building a value output from the linework. The requirement that no vertices are lost can generate complex collections as outputs.

  • "structure" is an algorithm that distinguishes between interior and exterior rings, building new geometry by unioning exterior rings, and then differencing all interior rings. The results tend to be more intuitive, where collapsed lines are discarded in the output.

The "keepcollapsed" key is only valid for the "structure" algorithm, and takes a value of "true" or "false".

  • Keep collapsed of "false" is the default, and means that geometry components that collapse to a lower dimensionality, for example a one-point linestring will be dropped.

  • Keep collapsed of "true" means geometry components that collapse to a lower dimensionality will be retained.

GEOS 모듈로 실행

2.0.0 버전부터 사용할 수 있습니다.

Enhanced: 2.0.1, speed improvements

Enhanced: 2.1.0, added support for GEOMETRYCOLLECTION and MULTIPOINT.

Enhanced: 3.1.0, added removal of Coordinates with NaN values.

Enhanced: 3.2.0, added algorithm options, 'linework' and 'structure' which requires GEOS >= 3.10.0.

This function supports 3d and will not drop the z-index.

예시

Make valid a MultiPolygon of two overlapping polygons using the linework and structure methods.

Code
SELECT ST_MakeValid(before_geom) AS linework,
  ST_MakeValid(before_geom, 'method=structure') AS structure
FROM (SELECT 'MULTIPOLYGON(((186 194,187 194,188 195,189 195,190 195,
191 195,192 195,193 194,194 194,194 193,195 192,195 191,
195 190,195 189,195 188,194 187,194 186,14 6,13 6,12 5,11 5,
10 5,9 5,8 5,7 6,6 6,6 7,5 8,5 9,5 10,5 11,5 12,6 13,6 14,186 194)),
((150 90,149 80,146 71,142 62,135 55,128 48,119 44,110 41,100 40,
90 41,81 44,72 48,65 55,58 62,54 71,51 80,50 90,51 100,
54 109,58 118,65 125,72 132,81 136,90 139,100 140,110 139,
119 136,128 132,135 125,142 118,146 109,149 100,150 90)))'::geometry AS before_geom) AS f;
래스터 출력
MULTIPOLYGON(((11 5,10 5,9 5,8 5,7 6,6 6,6 7,5 8,5 9,5 10,5 11,5 12,6 13,6 14,56.769 64.769,58 62,64 56,14 6,13 6,12 5,11 5)),((54 71,51 80,50 90,51 100,54 109,58 118,65 125,72 132,81 136,90 139,100 140,110 139,119 136,125.231 133.231,56.769 64.769,54 71)),((186 194,187 194,188 195,189 195,190 195,191 195,192 195,193 194,194 194,194 193,195 192,195 191,195 190,195 189,195 188,194 187,194 186,134 126,128 132,125.231 133.231,186 194)),((135 125,142 118,146 109,149 100,150 90,149 80,146 71,142 62,135 55,128 48,119 44,110 41,100 40,90 41,81 44,72 48,65 55,64 56,134 126,135 125))) | MULTIPOLYGON(((149 80,146 71,142 62,135 55,128 48,119 44,110 41,100 40,90 41,81 44,72 48,65 55,64 56,14 6,13 6,12 5,11 5,10 5,9 5,8 5,7 6,6 6,6 7,5 8,5 9,5 10,5 11,5 12,6 13,6 14,56.769 64.769,54 71,51 80,50 90,51 100,54 109,58 118,65 125,72 132,81 136,90 139,100 140,110 139,119 136,125.231 133.231,186 194,187 194,188 195,189 195,190 195,191 195,192 195,193 194,194 194,194 193,195 192,195 191,195 190,195 189,195 188,194 187,194 186,134 126,135 125,142 118,146 109,149 100,150 90,149 80)))
Figure
Geometry figure for visual-st-makevalid-01

Make valid a MultiPolygon of six overlapping polygons using the linework and structure methods.

Code
SELECT ST_MakeValid(before_geom) AS linework,
  ST_MakeValid(before_geom, 'method=structure') AS structure
FROM (SELECT 'MULTIPOLYGON(((91 50,79 22,51 10,23 22,11 50,23 78,51 90,79 78,91 50)),
      ((91 100,79 72,51 60,23 72,11 100,23 128,51 140,79 128,91 100)),
      ((91 150,79 122,51 110,23 122,11 150,23 178,51 190,79 178,91 150)),
      ((141 50,129 22,101 10,73 22,61 50,73 78,101 90,129 78,141 50)),
      ((141 100,129 72,101 60,73 72,61 100,73 128,101 140,129 128,141 100)),
      ((141 150,129 122,101 110,73 122,61 150,73 178,101 190,129 178,141 150)))'::geometry AS before_geom) AS c;
래스터 출력
MULTIPOLYGON(((51 110,68.5 117.5,61 100,68.5 82.5,51 90,23 78,21.714 75,11 100,21.714 125,23 122,51 110)),((51 190,76 179.286,73 178,61 150,68.5 132.5,51 140,23 128,21.714 125,11 150,23 178,51 190)),((141 150,130.286 125,129 128,101 140,83.5 132.5,91 150,79 178,76 179.286,101 190,129 178,141 150)),((129 78,101 90,83.5 82.5,91 100,83.5 117.5,101 110,129 122,130.286 125,141 100,130.286 75,129 78)),((101 10,76 20.714,79 22,91 50,83.5 67.5,101 60,129 72,130.286 75,141 50,129 22,101 10)),((11 50,21.714 75,23 72,51 60,68.5 67.5,61 50,73 22,76 20.714,51 10,23 22,11 50)),((83.5 82.5,80.286 75,79 78,76 79.286,83.5 82.5)),((83.5 67.5,76 70.714,79 72,80.286 75,83.5 67.5)),((68.5 67.5,71.714 75,73 72,76 70.714,68.5 67.5)),((68.5 82.5,76 79.286,73 78,71.714 75,68.5 82.5)),((83.5 132.5,80.286 125,79 128,76 129.286,83.5 132.5)),((83.5 117.5,76 120.714,79 122,80.286 125,83.5 117.5)),((68.5 117.5,71.714 125,73 122,76 120.714,68.5 117.5)),((68.5 132.5,76 129.286,73 128,71.714 125,68.5 132.5))) | MULTIPOLYGON(((23 22,11 50,21.714 75,11 100,21.714 125,11 150,23 178,51 190,76 179.286,101 190,129 178,141 150,130.286 125,141 100,130.286 75,141 50,129 22,101 10,76 20.714,51 10,23 22)))
Figure
Geometry figure for visual-st-makevalid-02

Collapsed Geometry Examples

Code
SELECT ST_MakeValid(
'LINESTRING(0 0,0 0)',
'method=structure keepcollapsed=true'
);
래스터 출력
POINT(0 0)
Figure
Geometry figure for visual-st-makevalid-03
Code
SELECT ST_MakeValid(
'LINESTRING(0 0,0 0)',
'method=structure keepcollapsed=false'
);
래스터 출력
LINESTRING

7.7. Spatial Reference System Functions

초록

These functions work with the Spatial Reference System of geometries as defined in the spatial_ref_sys table.

  • ST_InverseTransformPipeline — Return a new geometry with coordinates transformed to a different spatial reference system using the inverse of a defined coordinate transformation pipeline.
  • ST_SetSRID — Set the SRID on a geometry.
  • ST_SRID — Returns the spatial reference identifier for a geometry.
  • ST_Transform — Return a new geometry with coordinates transformed to a different spatial reference system.
  • ST_TransformPipeline — Return a new geometry with coordinates transformed to a different spatial reference system using a defined coordinate transformation pipeline.
  • postgis_srs_codes — Return the list of SRS codes associated with the given authority.
  • postgis_srs — Return a metadata record for the requested authority and srid.
  • postgis_srs_all — Return metadata records for every spatial reference system in the underlying Proj database.
  • postgis_srs_search — Return metadata records for projected coordinate systems that have areas of usage that fully contain the bounds parameter.

제목

ST_InverseTransformPipeline — Return a new geometry with coordinates transformed to a different spatial reference system using the inverse of a defined coordinate transformation pipeline.

요약

geometry ST_InverseTransformPipeline(geometry geom, text pipeline, integer to_srid);

설명

Return a new geometry with coordinates transformed to a different spatial reference system using a defined coordinate transformation pipeline to go in the inverse direction.

Refer to ST_TransformPipeline for details on writing a transformation pipeline.

Availability: 3.4.0

The SRID of the input geometry is ignored, and the SRID of the output geometry will be set to zero unless a value is provided via the optional to_srid parameter. When using ST_TransformPipeline the pipeline is executed in a forward direction. Using `ST_InverseTransformPipeline()` the pipeline is executed in the inverse direction.

Transforms using pipelines are a specialised version of ST_Transform. In most cases `ST_Transform` will choose the correct operations to convert between coordinate systems, and should be preferred.

예시

Change WGS 84 long lat to UTM 31N using the EPSG:16031 conversion

This example transforms in the inverse direction.

Code
SELECT ST_InverseTransformPipeline(
        'POINT(426857.9877165967 5427937.523342293)'::geometry,
        'urn:ogc:def:coordinateOperation:EPSG::16031'
    ) AS wgs_geom;
래스터 출력
POINT(2 48.99999999999999)
Figure
Geometry figure for visual-st-inversetransformpipeline-01

GDA2020 example.

This example uses ST_Transform with automatic selection of a conversion pipeline.

Code
SELECT ST_Transform('SRID=4939;POINT(143.0 -37.0)'::geometry, 7844) AS gda2020_auto;
래스터 출력
POINT(143.00000635638918 -36.999986706128176)
Figure
Geometry figure for visual-st-inversetransformpipeline-02

제목

ST_SetSRID — Set the SRID on a geometry.

요약

geometry ST_SetSRID(geometry geom, integer srid);

설명

Sets the SRID on a geometry to a particular integer value. Useful in constructing bounding boxes for queries.

[참고]

This function does not transform the geometry coordinates in any way - it simply sets the meta data defining the spatial reference system the geometry is assumed to be in. Use ST_Transform if you want to transform the geometry into a new projection.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1.

This method supports Circular Strings and Curves.

예시

Mark a point as WGS 84 longitude/latitude.

Code
SELECT ST_SetSRID(ST_Point(-123.365556, 48.428611), 4326) AS wgs84long_lat;
래스터 출력
SRID=4326;POINT(-123.365556 48.428611)
Figure
Geometry figure for visual-st-setsrid-01

Mark a point as WGS 84 longitude/latitude and then transform it to Web Mercator.

Code
SELECT ST_Transform(ST_SetSRID(ST_Point(-123.365556, 48.428611), 4326), 3785) AS sphere_merc;
래스터 출력
SRID=3785;POINT(-13732990.8753491 6178458.96425423)
Figure
Geometry figure for visual-st-setsrid-02

제목

ST_SRID — Returns the spatial reference identifier for a geometry.

요약

integer ST_SRID(geometry g1);

설명

Returns the spatial reference identifier for the ST_Geometry as defined in spatial_ref_sys table. 4.5절. “SPATIAL_REF_SYS 테이블과 공간 참조 시스템”

[참고]

spatial_ref_sys table is a table that catalogs all spatial reference systems known to PostGIS and is used for transformations from one spatial reference system to another. So verifying you have the right spatial reference system identifier is important if you plan to ever transform your geometries.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.1

This method implements the SQL/MM specification. SQL-MM 3: 5.1.5

This method supports Circular Strings and Curves.

예시

Code
SELECT ST_SRID(ST_GeomFromText('POINT(-71.1043 42.315)', 4326));
래스터 출력
st_srid
---------
    4326
(1 row)

제목

ST_Transform — Return a new geometry with coordinates transformed to a different spatial reference system.

요약

geometry ST_Transform(geometry g1, integer srid);

geometry ST_Transform(geometry geom, text to_proj);

geometry ST_Transform(geometry geom, text from_proj, text to_proj);

geometry ST_Transform(geometry geom, text from_proj, integer to_srid);

설명

Returns a new geometry with its coordinates transformed to a different spatial reference system. The destination spatial reference to_srid may be identified by a valid SRID integer parameter (i.e. it must exist in the spatial_ref_sys table). Alternatively, a spatial reference defined as a PROJ.4 string can be used for to_proj and/or from_proj, however these methods are not optimized. If the destination spatial reference system is expressed with a PROJ.4 string instead of an SRID, the SRID of the output geometry will be set to zero. With the exception of functions with from_proj, input geometries must have a defined SRID.

ST_Transform is often confused with ST_SetSRID. ST_Transform actually changes the coordinates of a geometry from one spatial reference system to another, while ST_SetSRID() simply changes the SRID identifier of the geometry.

ST_Transform automatically selects a suitable conversion pipeline given the source and target spatial reference systems. To use a specific conversion method, use ST_TransformPipeline.

[참고]

Requires PostGIS be compiled with PROJ support. Use PostGIS_Full_Version to confirm you have PROJ support compiled in.

[참고]

If using more than one transformation, it is useful to have a functional index on the commonly used transformations to take advantage of index usage.

[참고]

1.3.4 미만 버전에서 이 함수에 만곡 도형(curve)을 담고 있는 도형을 입력하면 충돌이 일어났습니다. 1.3.4 버전부터 이 버그가 해결됐습니다.

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다.

Enhanced: 2.3.0 support for direct PROJ.4 text was introduced.

This method implements the SQL/MM specification. SQL-MM 3: 5.1.6

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

예시

Change Massachusetts state plane US feet geometry to WGS 84 long lat

Code
SELECT ST_Transform(
  'SRID=2249;POLYGON((743238 2967416,743238 2967450,
    743265 2967450,743265.625 2967416,743238 2967416))'::geometry,
  4326) AS wgs_geom;
래스터 출력
SRID=4326;POLYGON((-71.1776848522251 42.3902896512903,-71.17768437663261 42.390382947801015,-71.17758443054647 42.390382667791854,-71.17758259272304 42.390289364798825,-71.1776848522251 42.3902896512903))
Figure
Geometry figure for visual-st-transform-01

3D Circular String example.

Code
SELECT ST_Transform('SRID=2249;CIRCULARSTRING(743238 2967416 1,743238 2967450 2,743265 2967450 3,743265.625 2967416 3,743238 2967416 4)'::geometry,
    4326);
래스터 출력
SRID=4326;CIRCULARSTRING(-71.1776848522251 42.3902896512903 1,-71.17768437663261 42.390382947801015 2,
-71.17758443054647 42.390382667791854 3,
-71.17758259272304 42.390289364798825 3,-71.1776848522251 42.3902896512903 4)

    
Figure
Geometry figure for visual-st-transform-02

Example of creating a partial functional index. For tables where you are not sure all the geometries will be filled in, its best to use a partial index that leaves out null geometries which will both conserve space and make your index smaller and more efficient.

Code
CREATE INDEX idx_geom_26986_parcels
  ON parcels
  USING gist
  (ST_Transform(geom, 26986))
  WHERE geom IS NOT NULL;
    

Examples of using PROJ.4 text to transform with custom spatial references.

Find intersection of two polygons near the North pole, using a custom Gnomic projection. See http://boundlessgeo.com/2012/02/flattening-the-peel/.

Code
WITH data AS (
  SELECT
    ST_GeomFromText('POLYGON((170 50,170 72,-130 72,-130 50,170 50))', 4326) AS p1,
    ST_GeomFromText('POLYGON((-170 68,-170 90,-141 90,-141 68,-170 68))', 4326) AS p2,
    '+proj=gnom +ellps=WGS84 +lat_0=70 +lon_0=-160 +no_defs'::text AS gnom
)
SELECT ST_Transform(ST_Intersection(ST_Transform(p1, gnom), ST_Transform(p2, gnom)),
  gnom, 4326)
FROM data;
래스터 출력
POLYGON((-140.9999840290591 73.42768865981984,-141 68,-170 68,-170.0000026915361 74.05492179637055,-140.9999840290591 73.42768865981984))
Figure
Geometry figure for visual-st-transform-03

Configuring transformation behavior

Sometimes coordinate transformation involving a grid-shift can fail, for example if PROJ.4 has not been built with grid-shift files or the coordinate does not lie within the range for which the grid shift is defined. By default, PostGIS will throw an error if a grid shift file is not present, but this behavior can be configured on a per-SRID basis either by testing different to_proj values of PROJ.4 text, or altering the proj4text value within the spatial_ref_sys table.

For example, the proj4text parameter +datum=NAD87 is a shorthand form for the following +nadgrids parameter:

Code
+nadgrids=@conus, @alaska, @ntv2_0.gsb, @ntv1_can.dat

The @ prefix means no error is reported if the files are not present, but if the end of the list is reached with no file having been appropriate (ie. found and overlapping) then an error is issued.

If, conversely, you wanted to ensure that at least the standard files were present, but that if all files were scanned without a hit a null transformation is applied you could use:

Code
+nadgrids=@conus, @alaska, @ntv2_0.gsb, @ntv1_can.dat, null

The null grid shift file is a valid grid shift file covering the whole world and applying no shift. So for a complete example, if you wanted to alter PostGIS so that transformations to SRID 4267 that didn't lie within the correct range did not throw an ERROR, you would use the following:

Code
UPDATE spatial_ref_sys SET proj4text = '+proj=longlat +ellps=clrk66 +nadgrids=@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat,null +no_defs' WHERE srid = 4267;

제목

ST_TransformPipeline — Return a new geometry with coordinates transformed to a different spatial reference system using a defined coordinate transformation pipeline.

요약

geometry ST_TransformPipeline(geometry g1, text pipeline, integer to_srid);

설명

Return a new geometry with coordinates transformed to a different spatial reference system using a defined coordinate transformation pipeline.

Transformation pipelines are defined using any of the following string formats:

  • urn:ogc:def:coordinateOperation:AUTHORITY::CODE. Note that a simple EPSG:CODE string does not uniquely identify a coordinate operation: the same EPSG code can be used for a CRS definition.

  • A PROJ pipeline string of the form: +proj=pipeline .... Automatic axis normalisation will not be applied, and if necessary the caller will need to add an additional pipeline step, or remove axisswap steps.

  • Concatenated operations of the form: urn:ogc:def:coordinateOperation,coordinateOperation:EPSG::3895,coordinateOperation:EPSG::1618.

Availability: 3.4.0

The SRID of the input geometry is ignored, and the SRID of the output geometry will be set to zero unless a value is provided via the optional to_srid parameter. When using `ST_TransformPipeline()` the pipeline is executed in a forward direction. Using ST_InverseTransformPipeline the pipeline is executed in the inverse direction.

Transforms using pipelines are a specialised version of ST_Transform. In most cases `ST_Transform` will choose the correct operations to convert between coordinate systems, and should be preferred.

예시

Change WGS 84 long lat to UTM 31N using the EPSG:16031 conversion

This example transforms in the forward direction.

Code
SELECT
    ST_SetSRID(ST_TransformPipeline(
        'SRID=4326;POINT(2 49)'::geometry,
        'urn:ogc:def:coordinateOperation:EPSG::16031'
    ), 32631) AS utm_geom;
래스터 출력
SRID=32631;POINT(426857.9877165967 5427937.523342293)
Figure
Geometry figure for visual-st-transformpipeline-01

This example transforms in the inverse direction.

Code
SELECT
    ST_SetSRID(ST_InverseTransformPipeline(
        'SRID=32631;POINT(426857.9877165967 5427937.523342293)'::geometry,
        'urn:ogc:def:coordinateOperation:EPSG::16031'
    ), 4326) AS wgs_geom;
래스터 출력
SRID=4326;POINT(2 48.99999999999999)
Figure
Geometry figure for visual-st-transformpipeline-02

GDA2020 example.

This example uses ST_Transform with automatic selection of a conversion pipeline.

Code
SELECT ST_Transform('SRID=4939;POINT(143.0 -37.0)'::geometry, 7844) AS gda2020_auto;
래스터 출력
POINT(143.00000635638918 -36.999986706128176)
Figure
Geometry figure for visual-st-transformpipeline-03

Using a defined conversion (EPSG:8447)

Code
SELECT
    ST_TransformPipeline(
        'SRID=4939;POINT(143.0 -37.0)'::geometry,
        'urn:ogc:def:coordinateOperation:EPSG::8447'
    ) AS gda2020_code;
래스터 출력
POINT(143.0000063280214 -36.999986718287545)

This example uses a PROJ pipeline definition matching EPSG:8447, as returned from projinfo. Any axisswap steps must be removed.

Code
SELECT
    ST_TransformPipeline(
        'SRID=4939;POINT(143.0 -37.0)'::geometry,
        '+proj=pipeline
   +step +proj=unitconvert +xy_in=deg +xy_out=rad
   +step +proj=hgridshift +grids=au_icsm_GDA94_GDA2020_conformal_and_distortion.tif
   +step +proj=unitconvert +xy_in=rad +xy_out=deg'
    ) AS gda2020_pipeline;
래스터 출력
POINT(143.0000063280214 -36.999986718287545)

제목

postgis_srs_codes — Return the list of SRS codes associated with the given authority.

요약

setof text postgis_srs_codes(text auth_name);

설명

Returns a set of all auth_srid for the given auth_name.

Availability: 3.4.0

Proj version 6+

예시

List the first ten codes associated with the EPSG authority.

Code
SELECT * FROM postgis_srs_codes('EPSG') ORDER BY 1 LIMIT 10;
래스터 출력
10156
10157
10158
10160
10162
10163
10164
10165
10166
10167

제목

postgis_srs — Return a metadata record for the requested authority and srid.

요약

setof record postgis_srs(text auth_name, text auth_srid);

설명

Returns a metadata record for the requested auth_srid for the given auth_name. The record will have the auth_name, auth_srid, srname, srtext, proj4text, and the corners of the area of usage, point_sw and point_ne.

Availability: 3.4.0

Proj version 6+

예시

Get the metadata for EPSG:3005.

Code
SELECT auth_name, auth_srid, srname,point_sw AS point_sw,point_ne AS point_ne
FROM postgis_srs('EPSG', '3005');
래스터 출력
-[ RECORD 1 ]-------------------
auth_name | EPSG
auth_srid | 3005
srname    | NAD83 / BC Albers
point_sw  | POINT(-139.04 48.25)
point_ne  | POINT(-114.08 60.01)

제목

postgis_srs_all — Return metadata records for every spatial reference system in the underlying Proj database.

요약

setof record postgis_srs_all(void);

설명

Returns a set of all metadata records in the underlying Proj database. The records will have the auth_name, auth_srid, srname, srtext, proj4text, and the corners of the area of usage, point_sw and point_ne.

Availability: 3.4.0

Proj version 6+

예시

Get the first 10 metadata records from the Proj database.

Code
SELECT auth_name, auth_srid, srname FROM postgis_srs_all() ORDER BY auth_name, auth_srid LIMIT 10;
래스터 출력
auth_name | auth_srid |                                srname
-----------+-----------+----------------------------------------------------------------------
 EPSG      | 10156     | ETRS89 + MSL UK & Ireland VORF08 depth
 EPSG      | 10157     | ETRS89 + CD UK & Ireland VORF08 depth
 EPSG      | 10158     | S34J-IRF
 EPSG      | 10160     | S34J reconstruction east-orientated
 EPSG      | 10162     | JGD2011 / Japan Plane Rectangular CS I + JGD2011 (vertical) height
 EPSG      | 10163     | JGD2011 / Japan Plane Rectangular CS II + JGD2011 (vertical) height
 EPSG      | 10164     | JGD2011 / Japan Plane Rectangular CS III + JGD2011 (vertical) height
 EPSG      | 10165     | JGD2011 / Japan Plane Rectangular CS IV + JGD2011 (vertical) height
 EPSG      | 10166     | JGD2011 / Japan Plane Rectangular CS V + JGD2011 (vertical) height
 EPSG      | 10167     | JGD2011 / Japan Plane Rectangular CS VI + JGD2011 (vertical) height    

7.8. Geometry Input

초록

These functions create geometry objects from various textual or binary formats.

7.8.1. Well-Known Text (WKT)

  • ST_BdPolyFromText — 멀티라인스트링 WKT 텍스트 표현식으로 주어진 임의의 폐쇄형 라인스트링 집합으로 폴리곤을 작성합니다.
  • ST_BdMPolyFromText — 멀티라인스트링 WKT 텍스트 표현식으로 주어진 임의의 폐쇄형 라인스트링 집합으로 멀티폴리곤을 작성합니다.
  • ST_GeogFromText — WKT (확장) 표현식으로부터 지정된 지리형 값을 반환합니다.
  • ST_GeographyFromText — WKT (확장) 표현식으로부터 지정된 지리형 값을 반환합니다.
  • ST_GeomCollFromText — Makes a collection Geometry from collection WKT with the given SRID. If SRID is not given, it defaults to 0.
  • ST_GeomFromEWKT — EWKT(Extended Well-Known Text)로부터 지정된 ST_Geometry 값을 반환합니다.
  • ST_GeomFromMARC21 — Takes MARC21/XML geographic data as input and returns a PostGIS geometry object.
  • ST_GeometryFromText — Returns a geometry from Well-Known Text (WKT). Alias for ST_GeomFromText.
  • ST_GeomFromText — WKT 표현식으로부터 지정된 ST_Geometry 값을 반환합니다.
  • ST_LineFromText — 주어진 SRID와 함께 WKT 표현식으로부터 도형을 만듭니다. SRID가 주어지지 않은 경우, 기본값인 0을 씁니다.
  • ST_MLineFromText — WKT 표현식으로부터 지정된 ST_MultiLineString 값을 반환합니다.
  • ST_MPointFromText — Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.
  • ST_MPolyFromText — Makes a MultiPolygon Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.
  • ST_PointFromText — 주어진 SRID와 함께 WKT 표현식으로부터 포인트 도형을 만듭니다. SRID가 주어지지 않은 경우, 기본값인 0을 씁니다.
  • ST_PolygonFromText — Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.
  • ST_WKTToSQL — Returns a geometry from Well-Known Text (WKT). SQL/MM alias for ST_GeomFromText.

제목

ST_BdPolyFromText — 멀티라인스트링 WKT 텍스트 표현식으로 주어진 임의의 폐쇄형 라인스트링 집합으로 폴리곤을 작성합니다.

요약

geometry ST_BdPolyFromText(text WKT, integer srid);

설명

멀티라인스트링 WKT 텍스트 표현식으로 주어진 임의의 폐쇄형 라인스트링 집합으로 폴리곤을 작성합니다.

[참고]

WKT가 멀티라인스트링이 아닐 경우 오류가 발생합니다. 출력물이 멀티폴리곤일 경우 오류가 발생하는데 이런 경우 ST_BdMPolyFromText를 사용하거나, 또는 PostGIS 특화 접근법을 사용하려면 ST_BuildArea()를 참조하십시오.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2

GEOS 모듈로 실행

1.1.0 버전부터 사용할 수 있습니다.


제목

ST_BdMPolyFromText — 멀티라인스트링 WKT 텍스트 표현식으로 주어진 임의의 폐쇄형 라인스트링 집합으로 멀티폴리곤을 작성합니다.

요약

geometry ST_BdMPolyFromText(text WKT, integer srid);

설명

멀티라인스트링 WKT 텍스트 표현식으로 주어진 임의의 폐쇄형 라인스트링 집합으로 멀티폴리곤을 작성합니다.

[참고]

WKT가 멀티라인스트링이 아닐 경우 오류가 발생합니다. 출력물이 단일 폴리곤으로 이루어졌을 경우에도 멀티폴리곤으로 강제합니다. 해당 연산시 단일 폴리곤을 출력할 것이라고 확신한다면 ST_BdPolyFromText 를 사용하거나, 또는 PostGIS 특화 접근법을 사용하려 할 경우 ST_BuildArea() 를 참조하십시오.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2

GEOS 모듈로 실행

1.1.0 버전부터 사용할 수 있습니다.


제목

ST_GeogFromText — WKT (확장) 표현식으로부터 지정된 지리형 값을 반환합니다.

요약

geography ST_GeogFromText(text EWKT);

설명

WKT 표현식 또는 확장 WKT 표현식으로부터 지리형 객체를 반환합니다. 투영체를 따로 설정하지 않은 경우 SRID 4326으로 가정합니다. 이 함수는 ST_GeographyFromText와 동일합니다. 포인트는 항상 경위도 형식으로 표현됩니다.

예시

Add a WGS 84 geography point column to a table.

Code
ALTER TABLE sometable ADD COLUMN geog geography(POINT, 4326);

Populate the geography column from longitude and latitude columns.

Code
UPDATE sometable
SET geog = ST_GeogFromText('SRID=4326;POINT(' || lon || ' ' || lat || ')');

Specify a geography point using EPSG:4267, NAD27.

Code
SELECT ST_GeogFromText('SRID=4267;POINT(-77.0092 38.889588)');
래스터 출력
SRID=4267;POINT(-77.0092 38.889588)
Figure
Geometry figure for visual-st-geogfromtext-01

제목

ST_GeographyFromText — WKT (확장) 표현식으로부터 지정된 지리형 값을 반환합니다.

요약

geography ST_GeographyFromText(text EWKT);

설명

WKT 표현식으로부터 지리형 객체를 반환합니다. 투영체를 따로 설정하지 않은 경우 SRID 4326으로 가정합니다.


제목

ST_GeomCollFromText — Makes a collection Geometry from collection WKT with the given SRID. If SRID is not given, it defaults to 0.

요약

geometry ST_GeomCollFromText(text WKT, integer srid);

geometry ST_GeomCollFromText(text WKT);

설명

Makes a collection Geometry from the Well-Known-Text (WKT) representation with the given SRID. If SRID is not given, it defaults to 0.

OGC 사양 3.2.6.2 - 선택적인 SRID를 적합성 스위트(conformance suite)로부터 가져오십시오.

WKT가 도형 집합(GEOMETRYCOLLECTION)이 아닌 경우 null을 반환합니다.

[참고]

사용자 WKT 도형이 모두 집합이라고 확신한다면, 이 함수를 사용하지 마십시오. 이 함수는 추가적인 유효성 검사 단계를 거치므로 ST_GeomFromText보다 느립니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2

This method implements the SQL/MM specification.

예시

Code
SELECT ST_GeomCollFromText('GEOMETRYCOLLECTION(POINT(1 2), LINESTRING(1 2,3 4))');

제목

ST_GeomFromEWKT — EWKT(Extended Well-Known Text)로부터 지정된 ST_Geometry 값을 반환합니다.

요약

geometry ST_GeomFromEWKT(text EWKT);

설명

OGC EWKT(Extended Well-Known Text) 표현식으로부터 PostGIS ST_Geometry 객체를 작성합니다.

[참고]

EWKT 형식이 OGC 표준은 아니지만, SRID(공간 참조 시스템 식별자)를 포함하는 PostGIS 특화 형식입니다.

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface) 및 TIN을 지원합니다.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

Create a LineString with SRID 4269.

Code
SELECT ST_GeometryType(geom) AS geometry_type, ST_SRID(geom) AS srid
FROM ST_GeomFromEWKT('SRID=4269;LINESTRING(-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932)') AS geom;
래스터 출력
geometry_type | srid
---------------+------
 ST_LineString | 4269
(1 row)

Create a MultiLineString with SRID 4269.

Code
SELECT ST_GeometryType(geom) AS geometry_type, ST_SRID(geom) AS srid
FROM ST_GeomFromEWKT('SRID=4269;MULTILINESTRING((-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932))') AS geom;
래스터 출력
geometry_type    | srid
---------------------+------
 ST_MultiLineString  | 4269
(1 row)

Create a Point with SRID 4269.

Code
SELECT ST_GeometryType(geom) AS geometry_type, ST_SRID(geom) AS srid
FROM ST_GeomFromEWKT('SRID=4269;POINT(-71.064544 42.28787)') AS geom;
래스터 출력
geometry_type | srid
---------------+------
 ST_Point      | 4269
(1 row)

Create a Polygon with SRID 4269.

Code
SELECT ST_GeometryType(geom) AS geometry_type, ST_SRID(geom) AS srid
FROM ST_GeomFromEWKT('SRID=4269;POLYGON((-71.1776585052917 42.3902909739571,-71.1776820268866 42.3903701743239,
-71.1776063012595 42.3903825660754,-71.1775826583081 42.3903033653531,-71.1776585052917 42.3902909739571))') AS geom;
래스터 출력
geometry_type | srid
---------------+------
 ST_Polygon    | 4269
(1 row)

Create a MultiPolygon with SRID 4269.

Code
SELECT ST_GeometryType(geom) AS geometry_type, ST_SRID(geom) AS srid
FROM ST_GeomFromEWKT('SRID=4269;MULTIPOLYGON(((-71.1031880899493 42.3152774590236,
-71.1031627617667 42.3152960829043,-71.102923838298 42.3149156848307,
-71.1023097974109 42.3151969047397,-71.1019285062273 42.3147384934248,
-71.102505233663 42.3144722937587,-71.10277487471 42.3141658254797,
-71.103113945163 42.3142739188902,-71.10324876416 42.31402489987,
-71.1033002961013 42.3140393340215,-71.1033488797549 42.3139495090772,
-71.103396240451 42.3138632439557,-71.1041521907712 42.3141153348029,
-71.1041411411543 42.3141545014533,-71.1041287795912 42.3142114839058,
-71.1041188134329 42.3142693656241,-71.1041112482575 42.3143272556118,
-71.1041072845732 42.3143851580048,-71.1041057218871 42.3144430686681,
-71.1041065602059 42.3145009876017,-71.1041097995362 42.3145589148055,
-71.1041166403905 42.3146168544148,-71.1041258822717 42.3146748022936,
-71.1041375307579 42.3147318674446,-71.1041492906949 42.3147711126569,
-71.1041598612795 42.314808571739,-71.1042515013869 42.3151287620809,
-71.1041173835118 42.3150739481917,-71.1040809891419 42.3151344119048,
-71.1040438678912 42.3151191367447,-71.1040194562988 42.3151832057859,
-71.1038734225584 42.3151140942995,-71.1038446938243 42.3151006300338,
-71.1038315271889 42.315094347535,-71.1037393329282 42.315054824985,
-71.1035447555574 42.3152608696313,-71.1033436658644 42.3151648370544,
-71.1032580383161 42.3152269126061,-71.103223066939 42.3152517403219,
-71.1031880899493 42.3152774590236)),
((-71.1043632495873 42.315113108546,-71.1043583974082 42.3151211109857,
-71.1043443253471 42.3150676015829,-71.1043850704575 42.3150793250568,-71.1043632495873 42.315113108546)))') AS geom;
래스터 출력
geometry_type   | srid
-------------------+------
 ST_MultiPolygon   | 4269
(1 row)

Create a 3D CircularString without an SRID.

Code
SELECT ST_GeometryType(geom) AS geometry_type, ST_SRID(geom) AS srid
FROM ST_GeomFromEWKT('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)') AS geom;
래스터 출력
geometry_type    | srid
--------------------+------
 ST_CircularString  | 0
(1 row)

Create a PolyhedralSurface without an SRID.

Code
SELECT ST_GeometryType(geom) AS geometry_type, ST_SRID(geom) AS srid
FROM ST_GeomFromEWKT('POLYHEDRALSURFACE(
    ((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)),
    ((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)),
    ((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)),
    ((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)),
    ((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)),
    ((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1))
)') AS geom;
래스터 출력
geometry_type       | srid
--------------------------+------
 ST_PolyhedralSurface     | 0
(1 row)

제목

ST_GeomFromMARC21 — Takes MARC21/XML geographic data as input and returns a PostGIS geometry object.

요약

geometry ST_GeomFromMARC21 ( text marcxml );

설명

This function creates a PostGIS geometry from a MARC21/XML record, which can contain a POINT or a POLYGON. In case of multiple geographic data entries in the same MARC21/XML record, a MULTIPOINT or MULTIPOLYGON will be returned. If the record contains mixed geometry types, a GEOMETRYCOLLECTION will be returned. It returns NULL if the MARC21/XML record does not contain any geographic data (datafield:034).

LOC MARC21/XML versions supported:

Availability: 3.3.0, requires libxml2 2.6+

[참고]

The MARC21/XML Coded Cartographic Mathematical Data currently does not provide any means to describe the Spatial Reference System of the encoded coordinates, so this function will always return a geometry with SRID 0.

[참고]

Returned POLYGON geometries will always be clockwise oriented.

예시

Converting MARC21/XML geographic data containing a single POINT encoded as hddd.dddddd

Code
SELECT ST_GeomFromMARC21(
'<record xmlns="http://www.loc.gov/MARC21/slim">
    <leader
>00000nz a2200000nc 4500</leader>
    <controlfield tag="001"
>040277569</controlfield>
    <datafield tag="034" ind1=" " ind2=" ">
        <subfield code="d"
>W004.500000</subfield>
        <subfield code="e"
>W004.500000</subfield>
        <subfield code="f"
>N054.250000</subfield>
        <subfield code="g"
>N054.250000</subfield>
    </datafield>
</record
>'
);
래스터 출력
POINT(-4.5 54.25)
Figure
Geometry figure for visual-st-geomfrommarc21-01

Converting MARC21/XML geographic data containing a single POLYGON encoded as hdddmmss

Code
SELECT ST_GeomFromMARC21(
'<record xmlns="http://www.loc.gov/MARC21/slim">
    <leader
>01062cem a2200241 a 4500</leader>
    <controlfield tag="001"
>   84696781 </controlfield>
    <datafield tag="034" ind1="1" ind2=" ">
        <subfield code="a"
>a</subfield>
        <subfield code="b"
>50000</subfield>
        <subfield code="d"
>E0130600</subfield>
        <subfield code="e"
>E0133100</subfield>
        <subfield code="f"
>N0523900</subfield>
        <subfield code="g"
>N0522300</subfield>
    </datafield>
</record
>'
);
래스터 출력
POLYGON((13.1 52.65,13.516666666666667 52.65,13.516666666666667 52.38333333333333,13.1 52.38333333333333,13.1 52.65))
Figure
Geometry figure for visual-st-geomfrommarc21-02

Converting MARC21/XML geographic data containing a POLYGON and a POINT:

Code
SELECT ST_GeomFromMARC21(
'<record xmlns="http://www.loc.gov/MARC21/slim">
    <datafield tag="034" ind1="1" ind2=" ">
        <subfield code="a"
>a</subfield>
        <subfield code="b"
>50000</subfield>
        <subfield code="d"
>E0130600</subfield>
        <subfield code="e"
>E0133100</subfield>
        <subfield code="f"
>N0523900</subfield>
        <subfield code="g"
>N0522300</subfield>
    </datafield>
    <datafield tag="034" ind1=" " ind2=" ">
        <subfield code="d"
>W004.500000</subfield>
        <subfield code="e"
>W004.500000</subfield>
        <subfield code="f"
>N054.250000</subfield>
        <subfield code="g"
>N054.250000</subfield>
    </datafield>
</record
>'
);
래스터 출력
GEOMETRYCOLLECTION(POLYGON((13.1 52.65,13.516666666666667 52.65,13.516666666666667 52.38333333333333,13.1 52.38333333333333,13.1 52.65)), POINT(-4.5 54.25))
Figure
Geometry figure for visual-st-geomfrommarc21-03

참고

ST_AsMARC21


제목

ST_GeometryFromText — Returns a geometry from Well-Known Text (WKT). Alias for ST_GeomFromText.

요약

geometry ST_GeometryFromText(text WKT);

geometry ST_GeometryFromText(text WKT, integer srid);

설명

This function is an alias for ST_GeomFromText and provides the same signatures.

1.2.2 버전부터 사용할 수 있습니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1.

This method implements the SQL/MM specification. SQL-MM 3: 5.1.40


제목

ST_GeomFromText — WKT 표현식으로부터 지정된 ST_Geometry 값을 반환합니다.

요약

geometry ST_GeomFromText(text WKT);

geometry ST_GeomFromText(text WKT, integer srid);

설명

OGC WKT(Well-Known Text) 표현식으로부터 PostGIS ST_Geometry 객체를 작성합니다.

[참고]

ST_GeomFromText 함수의 변종이 2개 있는데, 첫 번째는 SRID를 입력받지 않고 공간 참조 시스템이 정의되지 않은(SRID=0) 도형을 반환합니다. 두 번째는 SRID를 두 번째 인수로 입력받아 해당 SRID를 자체 메타데이터의 일부로 포함하는 도형을 반환합니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. 사양 3.2.6.2 - 선택적인 SRID를 적합성 스위트(conformance suite)로부터 가져오십시오.

This method implements the SQL/MM specification. SQL-MM 3: 5.1.40

This method supports Circular Strings and Curves.

[참고]

While not OGC-compliant, ST_MakePoint is faster than ST_GeomFromText and ST_PointFromText. It is also easier to use for numeric coordinate values. ST_Point is another option similar in speed to ST_MakePoint and is OGC-compliant, but doesn't support anything but 2D points.

변경 사항: PostGIS 2.0.0 미만 버전에서는 ST_GeomFromText('GEOMETRYCOLLECTION(EMPTY)') 를 사용할 수 있었습니다. PostGIS 2.0.0 버전부터, SQL/MM 표준을 더 잘 준수하기 위해 이런 사용법은 금지됐습니다. 이제는 ST_GeomFromText('GEOMETRYCOLLECTION EMPTY') 라고 작성해야 합니다.

예시

Create a LineString with SRID 0.

Code
SELECT ST_SRID(ST_GeomFromText('LINESTRING(-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932)'));
래스터 출력
0
Figure
Geometry figure for st-geomfromtext-linestring-srid0

Create the same LineString with SRID 4269.

Code
SELECT ST_SRID(ST_GeomFromText('LINESTRING(-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932)', 4269));
래스터 출력
4269
Figure
Geometry figure for st-geomfromtext-linestring-srid4269

Create a MultiLineString.

Code
SELECT ST_GeometryType(ST_GeomFromText('MULTILINESTRING((-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932))'));
래스터 출력
ST_MultiLineString
Figure
Geometry figure for st-geomfromtext-multilinestring

Create a Point.

Code
SELECT ST_GeometryType(ST_GeomFromText('POINT(-71.064544 42.28787)'));
래스터 출력
ST_Point

Create a Polygon.

Code
SELECT ST_GeometryType(ST_GeomFromText('POLYGON((-71.1776585052917 42.3902909739571,-71.1776820268866 42.3903701743239,
-71.1776063012595 42.3903825660754,-71.1775826583081 42.3903033653531,-71.1776585052917 42.3902909739571))'));
래스터 출력
ST_Polygon
Figure
Geometry figure for st-geomfromtext-polygon

Create a MultiPolygon with SRID 4326.

Code
SELECT ST_GeometryType(ST_GeomFromText('MULTIPOLYGON(((-71.1031880899493 42.3152774590236,
-71.1031627617667 42.3152960829043,-71.102923838298 42.3149156848307,
-71.1023097974109 42.3151969047397,-71.1019285062273 42.3147384934248,
-71.102505233663 42.3144722937587,-71.10277487471 42.3141658254797,
-71.103113945163 42.3142739188902,-71.10324876416 42.31402489987,
-71.1033002961013 42.3140393340215,-71.1033488797549 42.3139495090772,
-71.103396240451 42.3138632439557,-71.1041521907712 42.3141153348029,
-71.1041411411543 42.3141545014533,-71.1041287795912 42.3142114839058,
-71.1041188134329 42.3142693656241,-71.1041112482575 42.3143272556118,
-71.1041072845732 42.3143851580048,-71.1041057218871 42.3144430686681,
-71.1041065602059 42.3145009876017,-71.1041097995362 42.3145589148055,
-71.1041166403905 42.3146168544148,-71.1041258822717 42.3146748022936,
-71.1041375307579 42.3147318674446,-71.1041492906949 42.3147711126569,
-71.1041598612795 42.314808571739,-71.1042515013869 42.3151287620809,
-71.1041173835118 42.3150739481917,-71.1040809891419 42.3151344119048,
-71.1040438678912 42.3151191367447,-71.1040194562988 42.3151832057859,
-71.1038734225584 42.3151140942995,-71.1038446938243 42.3151006300338,
-71.1038315271889 42.315094347535,-71.1037393329282 42.315054824985,
-71.1035447555574 42.3152608696313,-71.1033436658644 42.3151648370544,
-71.1032580383161 42.3152269126061,-71.103223066939 42.3152517403219,
-71.1031880899493 42.3152774590236)),
((-71.1043632495873 42.315113108546,-71.1043583974082 42.3151211109857,
-71.1043443253471 42.3150676015829,-71.1043850704575 42.3150793250568,-71.1043632495873 42.315113108546)))', 4326));
래스터 출력
ST_MultiPolygon
Figure
Geometry figure for st-geomfromtext-multipolygon

Create a CircularString.

Code
SELECT ST_GeometryType(ST_GeomFromText('CIRCULARSTRING(220268 150415,220227 150505,220227 150406)'));
래스터 출력
ST_CircularString
Figure
Geometry figure for st-geomfromtext-circularstring

제목

ST_LineFromText — 주어진 SRID와 함께 WKT 표현식으로부터 도형을 만듭니다. SRID가 주어지지 않은 경우, 기본값인 0을 씁니다.

요약

geometry ST_LineFromText(text WKT);

geometry ST_LineFromText(text WKT, integer srid);

설명

Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0. If WKT passed in is not a LINESTRING, then null is returned.

[참고]

OGC 사양 3.2.6.2 - 선택적인 SRID를 적합성 스위트(conformance suite)로부터 가져오십시오.

[참고]

사용자 도형이 모두 라인스트링이란 걸 알고 있다면, 그냥 ST_GeomFromText 함수를 쓰는 편이 더 효율적입니다. 이 함수는 ST_GeomFromText만 호출하고, 라인스트링을 반환한다는 유효성 검사를 추가합니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2

This method implements the SQL/MM specification. SQL-MM 3: 7.2.8

예시

Code
SELECT ST_LineFromText('LINESTRING(1 2,3 4)') AS aline,
ST_LineFromText('POINT(1 2)') IS NULL AS null_return;
래스터 출력
aline                 | null_return
------------------------------------
LINESTRING(1 2,3 4)  | t
                
Figure
Geometry figure for visual-st-linefromtext-01

제목

ST_MLineFromText — WKT 표현식으로부터 지정된 ST_MultiLineString 값을 반환합니다.

요약

geometry ST_MLineFromText(text WKT, integer srid);

geometry ST_MLineFromText(text WKT);

설명

Makes a Geometry from Well-Known-Text (WKT) with the given SRID. If SRID is not given, it defaults to 0.

OGC 사양 3.2.6.2 - 선택적인 SRID를 적합성 스위트(conformance suite)로부터 가져오십시오.

WKT가 멀티라인스트링이 아닌 경우 null을 반환합니다.

[참고]

사용자 WKT 도형이 모두 포인트라고 확신한다면, 이 함수를 사용하지 마십시오. 이 함수는 추가적인 유효성 검사 단계를 거치므로 ST_GeomFromText보다 느립니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2

This method implements the SQL/MM specification. SQL-MM 3: 9.4.4

예시

Code
SELECT ST_MLineFromText('MULTILINESTRING((1 2,3 4),(4 5,6 7))');

제목

ST_MPointFromText — Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.

요약

geometry ST_MPointFromText(text WKT, integer srid);

geometry ST_MPointFromText(text WKT);

설명

Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.

OGC 사양 3.2.6.2 - 선택적인 SRID를 적합성 스위트(conformance suite)로부터 가져오십시오.

WKT가 멀티포인트가 아닌 경우 null을 반환합니다.

[참고]

사용자 WKT 도형이 모두 포인트라고 확신한다면, 이 함수를 사용하지 마십시오. 이 함수는 추가적인 유효성 검사 단계를 거치므로 ST_GeomFromText보다 느립니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. 3.2.6.2

This method implements the SQL/MM specification. SQL-MM 3: 9.2.4

예시

Code
SELECT ST_MPointFromText('MULTIPOINT((1 2),(3 4))');
SELECT ST_MPointFromText('MULTIPOINT((-70.9590 42.1180),(-70.9611 42.1223))', 4326);

제목

ST_MPolyFromText — Makes a MultiPolygon Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.

요약

geometry ST_MPolyFromText(text WKT, integer srid);

geometry ST_MPolyFromText(text WKT);

설명

Makes a MultiPolygon from WKT with the given SRID. If SRID is not given, it defaults to 0.

OGC 사양 3.2.6.2 - 선택적인 SRID를 적합성 스위트(conformance suite)로부터 가져오십시오.

WKT가 멀티폴리곤이 아닌 경우 오류가 발생합니다.

[참고]

사용자 WKT 도형이 모두 멀티폴리곤이라고 확신한다면, 이 함수를 사용하지 마십시오. 이 함수는 추가적인 유효성 검사 단계를 거치므로 ST_GeomFromText보다 느립니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2

This method implements the SQL/MM specification. SQL-MM 3: 9.6.4

예시

Create a 3D MultiPolygon with an interior ring and SRID 0.

Code
SELECT ST_MPolyFromText(
    'MULTIPOLYGON(((0 0 1,20 0 1,20 20 1,0 20 1,0 0 1),
                   (5 5 3,5 7 3,7 7 3,7 5 3,5 5 3)))'
);
래스터 출력
MULTIPOLYGON(((0 0 1,20 0 1,20 20 1,0 20 1,0 0 1),(5 5 3,5 7 3,7 7 3,7 5 3,5 5 3)))
Figure
Geometry figure for visual-st-mpolyfromtext-01

Create a MultiPolygon with SRID 4326.

Code
SELECT ST_MPolyFromText(
    'MULTIPOLYGON(((-70.916 42.1002,-70.9468 42.0946,-70.9765 42.0872,
      -70.9754 42.0875,-70.9749 42.0879,-70.9752 42.0881,-70.9754 42.0891,
      -70.9758 42.0894,-70.9759 42.0897,-70.9759 42.0899,-70.9754 42.0902,
      -70.9756 42.0906,-70.9753 42.0907,-70.9753 42.0917,-70.9757 42.0924,
      -70.9755 42.0928,-70.9755 42.0942,-70.9751 42.0948,-70.9755 42.0953,
      -70.9751 42.0958,-70.9751 42.0962,-70.9759 42.0983,-70.9767 42.0987,
      -70.9768 42.0991,-70.9771 42.0997,-70.9771 42.1003,-70.9768 42.1005,
      -70.977 42.1011,-70.9766 42.1019,-70.9768 42.1026,-70.9769 42.1033,
      -70.9775 42.1042,-70.9773 42.1043,-70.9776 42.1043,-70.9778 42.1048,
      -70.9773 42.1058,-70.9774 42.1061,-70.9779 42.1065,-70.9782 42.1078,
      -70.9788 42.1085,-70.9798 42.1087,-70.9806 42.109,-70.9807 42.1093,
      -70.9806 42.1099,-70.9809 42.1109,-70.9808 42.1112,-70.9798 42.1116,
      -70.9792 42.1127,-70.979 42.1129,-70.9787 42.1134,-70.979 42.1139,
      -70.9791 42.1141,-70.9987 42.1116,-71.0022 42.1273,-70.9408 42.1513,
      -70.9315 42.1165,-70.916 42.1002)))',
    4326
);
래스터 출력
SRID=4326;MULTIPOLYGON(((-70.916 42.1002,-70.9468 42.0946,-70.9765 42.0872,-70.9754 42.0875,-70.9749 42.0879,-70.9752 42.0881,-70.9754 42.0891,-70.9758 42.0894,-70.9759 42.0897,-70.9759 42.0899,-70.9754 42.0902,-70.9756 42.0906,-70.9753 42.0907,-70.9753 42.0917,-70.9757 42.0924,-70.9755 42.0928,-70.9755 42.0942,-70.9751 42.0948,-70.9755 42.0953,-70.9751 42.0958,-70.9751 42.0962,-70.9759 42.0983,-70.9767 42.0987,-70.9768 42.0991,-70.9771 42.0997,-70.9771 42.1003,-70.9768 42.1005,-70.977 42.1011,-70.9766 42.1019,-70.9768 42.1026,-70.9769 42.1033,-70.9775 42.1042,-70.9773 42.1043,-70.9776 42.1043,-70.9778 42.1048,-70.9773 42.1058,-70.9774 42.1061,-70.9779 42.1065,-70.9782 42.1078,-70.9788 42.1085,-70.9798 42.1087,-70.9806 42.109,-70.9807 42.1093,-70.9806 42.1099,-70.9809 42.1109,-70.9808 42.1112,-70.9798 42.1116,-70.9792 42.1127,-70.979 42.1129,-70.9787 42.1134,-70.979 42.1139,-70.9791 42.1141,-70.9987 42.1116,-71.0022 42.1273,-70.9408 42.1513,-70.9315 42.1165,-70.916 42.1002)))
Figure
Geometry figure for visual-st-mpolyfromtext-02

제목

ST_PointFromText — 주어진 SRID와 함께 WKT 표현식으로부터 포인트 도형을 만듭니다. SRID가 주어지지 않은 경우, 기본값인 0을 씁니다.

요약

geometry ST_PointFromText(text WKT);

geometry ST_PointFromText(text WKT, integer srid);

설명

Constructs a PostGIS ST_Geometry point object from the OGC Well-Known text representation. If SRID is not given, it defaults to unknown (currently 0). If geometry is not a WKT point representation, returns null. If completely invalid WKT, then throws an error.

[참고]

ST_PointFromText 함수의 변종이 2개 있는데, 첫 번째는 SRID를 입력받지 않고 공간 참조 시스템이 정의되지 않은 도형을 반환합니다. 두 번째는 SRID를 두 번째 인수로 입력받아 자체 메타데이터의 일부로 해당 SRID를 포함하는 ST_Geometry를 반환합니다. spatial_ref_sys 테이블에 정의되어 있는 SRID여야 합니다.

[참고]

사용자 WKT 도형이 모두 포인트라고 확신한다면, 이 함수를 사용하지 마십시오. 이 함수는 추가적인 유효성 검사 단계를 거치므로 ST_GeomFromText보다 느립니다. 사용자가 경위도 좌표로부터 포인트를 빌드하고 OGC 준수 여부보다 성능 및 정확도에 더 관심이 있다면, ST_MakePoint 또는 OGC를 준수하는 동일한 ST_Point 함수를 이용하십시오.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. 사양 3.2.6.2 - 선택적인 SRID를 적합성 스위트(conformance suite)로부터 가져오십시오.

This method implements the SQL/MM specification. SQL-MM 3: 6.1.8

예시

Create a point with the default SRID 0.

Code
SELECT ST_PointFromText('POINT(-71.064544 42.28787)');
래스터 출력
POINT(-71.064544 42.28787)
Figure
Geometry figure for visual-st-pointfromtext-01

Create a point with SRID 4326.

Code
SELECT ST_PointFromText('POINT(-71.064544 42.28787)', 4326);
래스터 출력
SRID=4326;POINT(-71.064544 42.28787)
Figure
Geometry figure for visual-st-pointfromtext-02

제목

ST_PolygonFromText — Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.

요약

geometry ST_PolygonFromText(text WKT);

geometry ST_PolygonFromText(text WKT, integer srid);

설명

Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0. Returns null if WKT is not a polygon.

OGC 사양 3.2.6.2 - 선택적인 SRID를 적합성 스위트(conformance suite)로부터 가져오십시오.

[참고]

사용자 WKT 도형이 모두 폴리곤이라고 확신한다면, 이 함수를 사용하지 마십시오. 이 함수는 추가적인 유효성 검사 단계를 거치므로 ST_GeomFromText보다 느립니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2

This method implements the SQL/MM specification. SQL-MM 3: 8.3.6

예시

The result is returned as a native geometry. The documentation test runner compares that value directly with the readable EWKT shown below and uses the same geometry for the generated figure.

Code
SELECT ST_PolygonFromText('POLYGON((-71.1776585052917 42.3902909739571,-71.1776820268866 42.3903701743239,
-71.1776063012595 42.3903825660754,-71.1775826583081 42.3903033653531,-71.1776585052917 42.3902909739571))');
래스터 출력
POLYGON((-71.1776585052917 42.3902909739571,-71.1776820268866 42.3903701743239,-71.1776063012595 42.3903825660754,-71.1775826583081 42.3903033653531,-71.1776585052917 42.3902909739571))
Figure
Geometry figure for visual-st-polygonfromtext-01
Code
SELECT ST_PolygonFromText('POINT(1 2)') IS NULL AS point_is_notpoly;
래스터 출력
t

제목

ST_WKTToSQL — Returns a geometry from Well-Known Text (WKT). SQL/MM alias for ST_GeomFromText.

요약

geometry ST_WKTToSQL(text WKT);

설명

This function is the SQL/MM alias for ST_GeomFromText with no SRID argument.

This method implements the SQL/MM specification. SQL-MM 3: 5.1.34

7.8.2. Well-Known Binary (WKB)

  • ST_GeogFromWKB — WKB 도형 표현식 또는 EWKB(확장 WKB)로부터 지리형 인스턴스를 생성합니다.
  • ST_GeomFromEWKB — EWKB(Extended Well-Known Binary)로부터 지정된 ST_Geometry 값을 반환합니다.
  • ST_GeomFromWKB — WKB(Well-Known Binary) 도형 표현식과 선택적인 SRID로부터 도형 인스턴스를 생성합니다.
  • ST_LineFromWKB — Creates a LINESTRING from a WKB representation, optionally using a given SRID.
  • ST_LinestringFromWKB — Creates a LINESTRING from a WKB representation, optionally using a given SRID.
  • ST_PointFromWKB — 주어진 SRID와 함께 WKB로부터 도형을 만듭니다.
  • ST_WKBToSQL — Returns a geometry from Well-Known Binary (WKB). SQL/MM alias for ST_GeomFromWKB without an SRID argument.

제목

ST_GeogFromWKB — WKB 도형 표현식 또는 EWKB(확장 WKB)로부터 지리형 인스턴스를 생성합니다.

요약

geography ST_GeogFromWKB(bytea wkb);

설명

ST_GeogFromWKB 함수는 도형의 WKB 표현식 또는 PostGIS 확장 WKB를 받아 적절한 지리형 유형의 인스턴스를 생성합니다. 이 함수는 SQL에서 도형 공장(Geometry Factory) 역할을 합니다.

SRID를 설정하지 않은 경우, 기본값으로 4326(WGS84 경위도)을 씁니다.

This method supports Circular Strings and Curves.

예시

Although bytea rep contains single \, these need to be escaped when inserting into a table.

Code
SELECT ST_GeogFromWKB(E'\\001\\002\\000\\000\\000\\002\\000\\000\\000\\037\\205\\353Q\\270~\\\\\\300\\323Mb\\020X\\231C@\\020X9\\264\\310~\\\\\\300)\\\\\\217\\302\\365\\230C@');
래스터 출력
LINESTRING(-113.98 39.198,-113.981 39.195)
Figure
Geometry figure for visual-st-geogfromwkb-01

제목

ST_GeomFromEWKB — EWKB(Extended Well-Known Binary)로부터 지정된 ST_Geometry 값을 반환합니다.

요약

geometry ST_GeomFromEWKB(bytea EWKB);

설명

Constructs a PostGIS geometry from an Extended Well-Known Binary (EWKB) representation.

[참고]

EWKB 형식이 OGC 표준은 아니지만, SRID(공간 참조 시스템 식별자)를 포함하는 PostGIS 특화 형식입니다.

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface) 및 TIN을 지원합니다.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

This example constructs LINESTRING(-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932) in NAD83 longitude/latitude (SRID 4269) from its EWKB representation.

PostgreSQL escape string syntax (E'...') always interprets backslash escapes. Each backslash therefore has to be doubled so that the bytea input parser receives the octal escapes.

Code
SELECT ST_GeomFromEWKB((
    E'\\001\\002\\000\\000\\040\\255\\020\\000\\000\\003\\000\\000\\000\\344\\112\\075' ||
    E'\\013\\102\\312\\121\\300\\156\\303\\050\\010\\036\\041\\105\\100\\047\\277\\105' ||
    E'\\047\\113\\312\\121\\300\\366\\173\\142\\235\\052\\041\\105\\100\\225\\174\\354' ||
    E'\\056\\120\\312\\121\\300\\160\\231\\323\\145\\061\\041\\105\\100'
)::bytea);
래스터 출력
0102000020AD10000003000000E44A3D0B42CA51C06EC328081E21454027BF45274BCA51C0F67B629D2A214540957CEC2E50CA51C07099D36531214540
Figure
Geometry figure for visual-st-geomfromewkb-01

With standard_conforming_strings enabled (the default), ordinary string literals preserve backslashes. The same EWKB can therefore be written with a single backslash before each octal byte value.

Code
SELECT ST_GeomFromEWKB((
    '\001\002\000\000\040\255\020\000\000\003\000\000\000\344\112\075' ||
    '\013\102\312\121\300\156\303\050\010\036\041\105\100\047\277\105' ||
    '\047\113\312\121\300\366\173\142\235\052\041\105\100\225\174\354' ||
    '\056\120\312\121\300\160\231\323\145\061\041\105\100'
)::bytea);
래스터 출력
0102000020AD10000003000000E44A3D0B42CA51C06EC328081E21454027BF45274BCA51C0F67B629D2A214540957CEC2E50CA51C07099D36531214540

제목

ST_GeomFromWKB — WKB(Well-Known Binary) 도형 표현식과 선택적인 SRID로부터 도형 인스턴스를 생성합니다.

요약

geometry ST_GeomFromWKB(bytea geom);

geometry ST_GeomFromWKB(bytea geom, integer srid);

설명

ST_GeogFromWKB 함수는 도형의 WKB 표현식과 SRID(공간 참조 시스템 ID)를 받아 적절한 도형 유형의 인스턴스를 생성합니다. 이 함수는 SQL에서 도형 공장(Geometry Factory) 역할을 합니다. 이 함수는 ST_WKBToSQL 함수를 대체할 수 있습니다.

SRID를 설정하지 않은 경우, 기본값으로 0(unkown)을 씁니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.7.2 - 선택적인 SRID를 적합성 스위트(conformance suite)로부터 가져오십시오.

This method implements the SQL/MM specification. SQL-MM 3: 5.1.41

This method supports Circular Strings and Curves.

예시

Although bytea rep contains single \, these need to be escaped when inserting into a table. Unless standard_conforming_strings is set to on.

Code
SELECT ST_GeomFromWKB(E'\\001\\002\\000\\000\\000\\002\\000\\000\\000\\037\\205\\353Q\\270~\\\\\\300\\323Mb\\020X\\231C@\\020X9\\264\\310~\\\\\\300)\\\\\\217\\302\\365\\230C@', 4326);
래스터 출력
SRID=4326;LINESTRING(-113.98 39.198,-113.981 39.195)
Figure
Geometry figure for visual-st-geomfromwkb-01
Code
SELECT ST_GeomFromWKB(ST_AsEWKB('POINT(2 5)'::geometry)
  );
래스터 출력
POINT(2 5)
Figure
Geometry figure for visual-st-geomfromwkb-02

제목

ST_LineFromWKB — Creates a LINESTRING from a WKB representation, optionally using a given SRID.

요약

geometry ST_LineFromWKB(bytea WKB);

geometry ST_LineFromWKB(bytea WKB, integer srid);

설명

The ST_LineFromWKB function takes a Well-Known Binary (WKB) representation of a geometry and an optional Spatial Reference System ID (SRID), and creates a LINESTRING geometry. It is a type-specific geometry factory in SQL.

If an SRID is not specified, it defaults to 0. NULL is returned if the input bytea does not represent a LINESTRING geometry.

[참고]

OGC 사양 3.2.6.2 - 선택적인 SRID를 적합성 스위트(conformance suite)로부터 가져오십시오.

[참고]

If you know all your geometries are LINESTRINGs, it is more efficient to use ST_GeomFromWKB directly. This function calls ST_GeomFromWKB and adds validation that the result is a LINESTRING.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2

This method implements the SQL/MM specification. SQL-MM 3: 7.2.9

예시

Code
SELECT ST_LineFromWKB(
    ST_AsBinary(ST_GeomFromText('LINESTRING(1 2,3 4)'))
) AS aline,
ST_LineFromWKB(
    ST_AsBinary(ST_GeomFromText('POINT(1 2)'))
) IS NULL AS null_return;
래스터 출력
aline                 | null_return
------------------------------------
LINESTRING(1 2,3 4)  | t
                
Figure
Geometry figure for visual-st-linefromwkb-01

제목

ST_LinestringFromWKB — Creates a LINESTRING from a WKB representation, optionally using a given SRID.

요약

geometry ST_LinestringFromWKB(bytea WKB);

geometry ST_LinestringFromWKB(bytea WKB, integer srid);

설명

The ST_LinestringFromWKB function takes a Well-Known Binary (WKB) representation of a geometry and an optional Spatial Reference System ID (SRID), and creates a LINESTRING geometry. It is an alias for ST_LineFromWKB.

If an SRID is not specified, it defaults to 0. NULL is returned if the input bytea does not represent a LINESTRING geometry.

[참고]

OGC 사양 3.2.6.2 - 선택적인 SRID를 적합성 스위트(conformance suite)로부터 가져오십시오.

[참고]

If you know all your geometries are LINESTRINGs, it is more efficient to use ST_GeomFromWKB directly. This function calls ST_GeomFromWKB and adds validation that the result is a LINESTRING.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2

This method implements the SQL/MM specification. SQL-MM 3: 7.2.9

예시

Code
SELECT ST_LinestringFromWKB(
    ST_AsBinary(ST_GeomFromText('LINESTRING(1 2,3 4)'))
) AS aline,
ST_LinestringFromWKB(
    ST_AsBinary(ST_GeomFromText('POINT(1 2)'))
) IS NULL AS null_return;
래스터 출력
aline                 | null_return
------------------------------------
LINESTRING(1 2,3 4)  | t
Figure
Geometry figure for visual-st-linestringfromwkb-01

제목

ST_PointFromWKB — 주어진 SRID와 함께 WKB로부터 도형을 만듭니다.

요약

geometry ST_GeomFromWKB(bytea geom);

geometry ST_GeomFromWKB(bytea geom, integer srid);

설명

ST_PointFromWKB 함수는 도형의 WKB 표현식과 SRID(공간 참조 시스템 ID)를 받아 적절한 도형 유형의 인스턴스 - 이 경우, POINT 도형 - 를 생성합니다. 이 함수는 SQL에서 도형 공장(Geometry Factory) 역할을 합니다.

SRID를 설정하지 않은 경우, 기본값인 0을 씁니다. 입력된 bytea가 포인트가 아닌 경우, NULL을 반환합니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.7.2

This method implements the SQL/MM specification. SQL-MM 3: 6.1.9

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

예시

Code
SELECT ST_PointFromWKB(ST_AsEWKB('POINT(2 5)'::geometry));
래스터 출력
POINT(2 5)
Figure
Geometry figure for visual-st-pointfromwkb-01
Code
SELECT ST_PointFromWKB(ST_AsEWKB('LINESTRING(2 5,2 6)'::geometry));
래스터 출력
null

제목

ST_WKBToSQL — Returns a geometry from Well-Known Binary (WKB). SQL/MM alias for ST_GeomFromWKB without an SRID argument.

요약

geometry ST_WKBToSQL(bytea WKB);

설명

This function is the SQL/MM alias for ST_GeomFromWKB with no SRID argument.

This method implements the SQL/MM specification. SQL-MM 3: 5.1.36

7.8.3. Other Formats

제목

ST_Box2dFromGeoHash — GeoHash 스트링으로부터 BOX2D를 반환합니다.

요약

box2d ST_Box2dFromGeoHash(text geohash, integer precision=full_precision_of_geohash);

설명

GeoHash 스트링으로부터 BOX2D를 반환합니다.

If no precision is specified ST_Box2dFromGeoHash returns a BOX2D based on full precision of the input GeoHash string.

precision 을 설정한 경우, ST_Box2dFromGeoHash가 GeoHash에서 나온 그만큼의 문자를 이용해서 BOX2D를 생성합니다. 정확도 값이 낮을수록 BOX2D의 용량이 커지고 값이 높을수록 정확도가 올라갑니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT ST_Box2dFromGeoHash('9qqj7nmxncgyy4d0dbxqz0');
래스터 출력
BOX(-115.172816 36.114646,-115.172816 36.114646)
Code
SELECT ST_Box2dFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 0);
래스터 출력
BOX(-180 -90,180 90)
Code
SELECT ST_Box2dFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 10);
래스터 출력
BOX(-115.17282128334 36.1146408319473,-115.172810554504 36.1146461963654)

제목

ST_GeomFromGeoHash — GeoHash 스트링으로부터 도형을 반환합니다.

요약

geometry ST_GeomFromGeoHash(text geohash, integer precision=full_precision_of_geohash);

설명

GeoHash 스트링으로부터 도형을 반환합니다. 해당 도형은 GeoHash 범위를 표현하는 폴리곤이 될 것입니다.

precision 을 설정하지 않은 경우, ST_GeomFromGeoHash가 입력 GeoHash 스트링의 전체 정확도를 기반으로 폴리곤을 반환합니다.

precision 을 설정한 경우, ST_GeomFromGeoHash가 GeoHash에서 나온 그만큼의 문자를 이용해서 폴리곤을 생성합니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

The cells are returned together so their relative sizes remain visible in a shared coordinate frame.

Code
SELECT ST_GeomFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 4) AS "precision 4", ST_GeomFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 5) AS "precision 5", ST_GeomFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 6) AS "precision 6";
래스터 출력
-[ RECORD 1 ]----------
precision 4 | POLYGON((-115.3125 36.03515625,-115.3125 36.2109375,-114.9609375 36.2109375,-114.9609375 36.03515625,-115.3125 36.03515625))
precision 5 | POLYGON((-115.1806640625 36.0791015625,-115.1806640625 36.123046875,-115.13671875 36.123046875,-115.13671875 36.0791015625,-115.1806640625 36.0791015625))
precision 6 | POLYGON((-115.1806640625 36.112060546875,-115.1806640625 36.1175537109375,-115.169677734375 36.1175537109375,-115.169677734375 36.112060546875,-115.1806640625 36.112060546875))
Figure
Geometry figure for visual-st-geomfromgeohash-01

제목

ST_GeomFromGML — 도형의 GML 표현식을 입력받아 PostGIS 도형 객체를 출력합니다.

요약

geometry ST_GeomFromGML(text geomgml);

geometry ST_GeomFromGML(text geomgml, integer srid);

설명

OGC GML 표현식으로부터 PostGIS ST_Geometry 객체를 작성합니다.

ST_GeomFromGML은 GML 도형 조각(geometry fragment)에 대해서만 작동합니다. 완전한 GML 문서를 사용하려 할 경우 오류가 발생합니다.

지원하는 OGC GML 버전은 다음과 같습니다:

  • GML 3.2.1 네임스페이스

  • GML 3.1.1 단순 피처 프로파일 SF-2 (GML 3.1.0 및 3.0.0 하위 호환)

  • GML 2.1.2

OGC GML 표준: http://www.opengeospatial.org/standards/gml

1.5 버전부터 사용할 수 있습니다. LibXML2 1.6 이상 버전이 필요합니다.

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface) 및 TIN을 지원합니다.

개선 사항: 2.0.0 버전에서 선택적인 기본 SRID 파라미터가 추가됐습니다.

Enhanced: 3.7.0 support for GML ArcString, curved Ring, and CurvePolygon geometries was introduced.

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

GML은 혼합 차원을 (예를 들어 동일한 멀티 도형(MultiGeometry) 안에서 2D와 3D를 함께) 쓸 수 있습니다. PostGIS 도형은 그렇지 않기 때문에, 사라진 Z 차원을 찾은 경우 ST_GeomFromGML이 전체 도형을 2D로 변환합니다.

GML은 동일한 멀티 도형 안에서 혼합 SRS를 지원합니다. PostGIS 도형은 그렇지 않기 때문에, 이 경우 ST_GeomFromGML이 모든 하위 도형들을 SRS 루트 노드로 재투영합니다. GML 루트 노드로 쓸 수 있는 srsName 속성이 없을 경우, 오류가 발생합니다.

ST_GeomFromGML은 분명한 GML 네임스페이스를 꼼꼼히 따지지 않습니다. 일반적인 사용시에는 네임스페이스를 명시적으로 언급하지 않아도 됩니다. 하지만 GML 내부에 XLink 피처를 사용하고 싶다면 그래야 합니다.

예시

A single geometry with srsName.

Code
        SELECT ST_AsEWKT(ST_GeomFromGML($$
            <gml:LineString xmlns:gml="http://www.opengis.net/gml"
                    srsName="EPSG:4269">
                <gml:coordinates>
            -71.16028,42.258729 -71.160837,42.259112 -71.161143,42.25932
                </gml:coordinates>
            </gml:LineString>
        $$));

                
래스터 출력
SRID=4269;LINESTRING(-71.16028 42.258729,-71.160837 42.259112,-71.161143 42.25932)
Figure
Geometry figure for visual-st-geomfromgml-01

XLink usage.

Code
        SELECT ST_AsEWKT(ST_GeomFromGML($$
            <gml:LineString xmlns:gml="http://www.opengis.net/gml"
                    xmlns:xlink="http://www.w3.org/1999/xlink"
                    srsName="EPSG:4269">
        <gml:pointProperty>
            <gml:Point gml:id="p1"
><gml:pos
>-71.16028 42.258729</gml:pos
></gml:Point>
        </gml:pointProperty>
        <gml:pos
>-71.160837 42.259112</gml:pos>
        <gml:pos
>-71.161143 42.258729</gml:pos>
                <gml:pointProperty>
                    <gml:Point xlink:type="simple" xlink:href="#p1"/>
                </gml:pointProperty>
            </gml:LineString>
        $$));

                
래스터 출력
SRID=4269;LINESTRING(-71.16028 42.258729,-71.160837 42.259112,-71.161143 42.258729,-71.16028 42.258729)
Figure
Geometry figure for visual-st-geomfromgml-02

Polyhedral Surface.

Code
SELECT ST_AsEWKT(ST_GeomFromGML('
<gml:PolyhedralSurface xmlns:gml="http://www.opengis.net/gml">
<gml:polygonPatches>
  <gml:PolygonPatch>
    <gml:exterior>
      <gml:LinearRing
><gml:posList srsDimension="3"
>0 0 0 0 0 1 0 1 1 0 1 0 0 0 0</gml:posList
></gml:LinearRing>
    </gml:exterior>
  </gml:PolygonPatch>
  <gml:PolygonPatch>
    <gml:exterior>
    <gml:LinearRing
><gml:posList srsDimension="3"
>0 0 0 0 1 0 1 1 0 1 0 0 0 0 0</gml:posList
></gml:LinearRing>
    </gml:exterior>
  </gml:PolygonPatch>
  <gml:PolygonPatch>
    <gml:exterior>
    <gml:LinearRing
><gml:posList srsDimension="3"
>0 0 0 1 0 0 1 0 1 0 0 1 0 0 0</gml:posList
></gml:LinearRing>
    </gml:exterior>
  </gml:PolygonPatch>
  <gml:PolygonPatch>
    <gml:exterior>
    <gml:LinearRing
><gml:posList srsDimension="3"
>1 1 0 1 1 1 1 0 1 1 0 0 1 1 0</gml:posList
></gml:LinearRing>
    </gml:exterior>
  </gml:PolygonPatch>
  <gml:PolygonPatch>
    <gml:exterior>
    <gml:LinearRing
><gml:posList srsDimension="3"
>0 1 0 0 1 1 1 1 1 1 1 0 0 1 0</gml:posList
></gml:LinearRing>
    </gml:exterior>
  </gml:PolygonPatch>
  <gml:PolygonPatch>
    <gml:exterior>
    <gml:LinearRing
><gml:posList srsDimension="3"
>0 0 1 1 0 1 1 1 1 0 1 1 0 0 1</gml:posList
></gml:LinearRing>
    </gml:exterior>
  </gml:PolygonPatch>
</gml:polygonPatches>
</gml:PolyhedralSurface
>'));
래스터 출력
POLYHEDRALSURFACE(((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)),
((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)),
((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)),
((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)),
((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)),
((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1)))
Figure
Geometry figure for visual-st-geomfromgml-03

제목

ST_GeomFromGeoJSON — GeoJSON 표현식을 입력받아 PostGIS 도형 객체를 출력합니다.

요약

geometry ST_GeomFromGeoJSON(text geomjson);

geometry ST_GeomFromGeoJSON(json geomjson);

geometry ST_GeomFromGeoJSON(jsonb geomjson);

설명

GeoJSON 표현식으로부터 PostGIS 도형 객체를 작성합니다.

ST_GeomFromGML은 JSON 도형 조각(geometry fragment)에 대해서만 작동합니다. 완전한 JSON 문서를 사용하려 할 경우 오류가 발생합니다.

Enhanced: 3.0.0 parsed geometry defaults to SRID=4326 if not specified otherwise.

Enhanced: 2.5.0 can now accept json and jsonb as inputs.

2.0.0 버전부터 사용할 수 있습니다. JSON-C 0.9 이상 버전이 필요합니다.

[참고]

JSON-C 지원을 활성화시키지 않았다면, 출력물 대신 오류 메시지를 보게 될 것입니다. JSON-C를 활성화하려면, "--with-jsondir=/path/to/json-c" 인자와 함께 설정하십시오. 자세한 내용은 2.2.3절. “설정” 을 참조하십시오.

This function supports 3d and will not drop the z-index.

예시

Code
SELECT ST_GeomFromGeoJSON('{"type":"Point","coordinates":[-48.23456,20.12345]}') AS wkt;
래스터 출력
POINT(-48.23456 20.12345)
Figure
Geometry figure for visual-st-geomfromgeojson-01

This example creates a 3D LineString.

Code
SELECT ST_GeomFromGeoJSON('{"type":"LineString","coordinates":[[1,2,3],[4,5,6],[7,8,9]]}') AS wkt;
래스터 출력
LINESTRING Z (1 2 3,4 5 6,7 8 9)
Figure
Geometry figure for visual-st-geomfromgeojson-02

제목

ST_GeomFromKML — 도형의 KML 표현식을 입력받아 PostGIS 도형 객체를 출력합니다.

요약

geometry ST_GeomFromKML(text geomkml);

설명

Constructs a PostGIS geometry from an OGC KML representation.

ST_GeomFromKML은 KML 도형 조각(geometry fragment)에 대해서만 작동합니다. 완전한 KML 문서를 사용하려 할 경우 오류가 발생합니다.

지원하는 OGC KML 버전은 다음과 같습니다:

  • KML 2.2.0 네임스페이스

OGC KML 표준: http://www.opengeospatial.org/standards/kml

Availability: 1.5, requires libxml2 2.6+

This function supports 3d and will not drop the z-index.

[참고]

ST_GeomFromKML does not support SQL/MM curve geometries.

예시

A single LineString geometry.

Code
        SELECT ST_AsEWKT(ST_GeomFromKML($$
            <LineString>
                <coordinates
>-71.1663, 42.2614
                    -71.1667, 42.2616</coordinates>
            </LineString>
        $$));

                
래스터 출력
SRID=4326;LINESTRING(-71.1663 42.2614,-71.1667 42.2616)
Figure
Geometry figure for visual-st-geomfromkml-01

제목

ST_GeomFromTWKB — TWKB("Tiny Well-Known Binary") 도형 표현식으로부터 도형 인스턴스를 생성합니다.

요약

geometry ST_GeomFromTWKB(bytea twkb);

설명

ST_GeomFromTWKB 함수는 TWKB("Tiny Well-Known Binary") 도형 표현식(WKB)을 받아 적절한 도형 유형의 인스턴스를 생성합니다.

예시

Code
SELECT ST_GeomFromTWKB(ST_AsTWKB('LINESTRING(126 34,127 35)'::geometry));
래스터 출력
LINESTRING(126 34, 127 35)
Figure
Geometry figure for visual-st-geomfromtwkb-01
Code
SELECT ST_GeomFromTWKB(E'\\x620002f7f40dbce4040105');
래스터 출력
LINESTRING(-113.98 39.198,-113.981 39.195)
Figure
Geometry figure for visual-st-geomfromtwkb-02

참고

ST_AsTWKB


제목

ST_GMLToSQL — Returns a geometry from GML. Alias for ST_GeomFromGML.

요약

geometry ST_GMLToSQL(text geomgml);

geometry ST_GMLToSQL(text geomgml, integer srid);

설명

This function is an alias for ST_GeomFromGML and provides the same signatures.

This method implements the SQL/MM specification. SQL-MM 3: 5.1.50.

1.5 버전부터 사용할 수 있습니다. LibXML2 1.6 이상 버전이 필요합니다.

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface) 및 TIN을 지원합니다.

개선 사항: 2.0.0 버전에서 선택적인 기본 SRID 파라미터가 추가됐습니다.

Enhanced: 3.7.0 support for GML ArcString, curved Ring, and CurvePolygon geometries was introduced.


제목

ST_LineFromEncodedPolyline — 인코딩된 폴리라인(polyline)으로부터 라인스트링을 생성합니다.

요약

geometry ST_LineFromEncodedPolyline(text polyline, integer precision=5);

설명

인코딩된 폴리라인 스트링으로부터 라인스트링을 생성합니다.

Optional precision specifies how many decimal places will be preserved in Encoded Polyline. Value should be the same on encoding and decoding, or coordinates will be incorrect.

참조: http://developers.google.com/maps/documentation/utilities/polylinealgorithm

2.2.0 버전부터 사용할 수 있습니다.

예시

This example creates a LineString from a polyline.

Code
SELECT ST_LineFromEncodedPolyline('_p~iF~ps|U_ulLnnqC_mqNvxq`@');
래스터 출력
SRID=4326;LINESTRING(-120.2 38.5,-120.95 40.7,-126.453 43.252)
Figure
Geometry figure for visual-st-linefromencodedpolyline-01

This example selects a different precision than the one used for polyline encoding.

Code
SELECT ST_LineFromEncodedPolyline('_p~iF~ps|U_ulLnnqC_mqNvxq`@', 6);
래스터 출력
SRID=4326;LINESTRING(-12.02 3.85,-12.095 4.07,-12.6453 4.3252)

    
Figure
Geometry figure for visual-st-linefromencodedpolyline-02

제목

ST_PointFromGeoHash — GeoHash 스트링으로부터 포인트를 반환합니다.

요약

point ST_PointFromGeoHash(text geohash, integer precision=full_precision_of_geohash);

설명

GeoHash 스트링으로부터 포인트를 반환합니다. 해당 포인트는 GeoHash의 중심점입니다.

precision 을 설정하지 않은 경우, ST_PointFromGeoHash가 입력 GeoHash 스트링의 전체 정확도를 기반으로 포인트를 반환합니다.

precision 을 설정한 경우, ST_PointFromGeoHash가 GeoHash에서 나온 그만큼의 문자를 이용해서 포인트를 생성합니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT ST_PointFromGeoHash('9qqj7nmxncgyy4d0dbxqz0');
래스터 출력
POINT(-115.172816 36.114646)
Figure
Geometry figure for visual-st-pointfromgeohash-01
Code
SELECT ST_PointFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 4);
래스터 출력
POINT(-115.13671875 36.123046875)
Figure
Geometry figure for visual-st-pointfromgeohash-02
Code
SELECT ST_PointFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 10);
래스터 출력
POINT(-115.172815918922 36.1146435141563)
Figure
Geometry figure for visual-st-pointfromgeohash-03

제목

ST_FromFlatGeobufToTable — Creates a table based on the structure of FlatGeobuf data.

요약

void ST_FromFlatGeobufToTable(text schemaname, text tablename, bytea FlatGeobuf input data);

설명

Creates a table based on the structure of FlatGeobuf data. (http://flatgeobuf.org).

schema Schema name.

table Table name.

data Input FlatGeobuf data.

Availability: 3.2.0


제목

ST_FromFlatGeobuf — Reads FlatGeobuf data.

요약

setof anyelement ST_FromFlatGeobuf(anyelement Table reference, bytea FlatGeobuf input data);

설명

Reads FlatGeobuf data (http://flatgeobuf.org). NOTE: PostgreSQL bytea cannot exceed 1GB.

tabletype reference to a table type.

data input FlatGeobuf data.

Availability: 3.2.0

7.9. Geometry Output

초록

These functions convert geometry objects into various textual or binary formats.

7.9.1. Well-Known Text (WKT)

  • ST_AsEWKT — 도형의 WKT(Well-Known Text) 표현식을 SRID 메타데이터와 함께 반환합니다.
  • ST_AsText — 도형/지리형의 WKT(Well-Known Text) 표현식을 SRID 메타데이터 없이 반환합니다.

제목

ST_AsEWKT — 도형의 WKT(Well-Known Text) 표현식을 SRID 메타데이터와 함께 반환합니다.

요약

text ST_AsEWKT(geometry g1);

text ST_AsEWKT(geometry g1, integer maxdecimaldigits=15);

text ST_AsEWKT(geography g1);

text ST_AsEWKT(geography g1, integer maxdecimaldigits=15);

설명

Returns the Well-Known Text representation of the geometry prefixed with the SRID. The optional maxdecimaldigits argument may be used to reduce the maximum number of decimal digits after floating point used in output (defaults to 15).

To perform the inverse conversion of EWKT representation to PostGIS geometry use ST_GeomFromEWKT.

[주의]

Using the maxdecimaldigits parameter can cause output geometry to become invalid. To avoid this use ST_ReducePrecision with a suitable gridsize first.

[참고]

The WKT spec does not include the SRID. To get the OGC WKT format use ST_AsText.

[주의]

WKT format does not maintain precision so to prevent floating truncation, use ST_AsBinary or ST_AsEWKB format for transport.

Enhanced: 3.1.0 support for optional precision parameter.

개선 사항: 2.0.0 버전부터 지리형, 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

Code
SELECT ST_AsEWKT('0103000020e61000000100000005000000000000000000000000000000000000000000000000000000000000000000f03f000000000000f03f000000000000f03f000000000000f03f000000000000000000000000000000000000000000000000'::geometry);
래스터 출력
SRID=4326;POLYGON((0 0,0 1,1 1,1 0,0 0))
Figure
Geometry figure for visual-st-asewkt-01
Code
SELECT ST_AsEWKT('0108000080030000000000000060E30A4100000000785C0241000000000000F03F0000000018E20A4100000000485F024100000000000000400000000018E20A4100000000305C02410000000000000840');
래스터 출력
CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)
Figure
Geometry figure for visual-st-asewkt-02

제목

ST_AsText — 도형/지리형의 WKT(Well-Known Text) 표현식을 SRID 메타데이터 없이 반환합니다.

요약

text ST_AsText(geometry g1);

text ST_AsText(geometry g1, integer maxdecimaldigits = 15);

text ST_AsText(geography g1);

text ST_AsText(geography g1, integer maxdecimaldigits = 15);

설명

Returns the OGC Well-Known Text (WKT) representation of the geometry/geography. The optional maxdecimaldigits argument may be used to limit the number of digits after the decimal point in output ordinates (defaults to 15).

To perform the inverse conversion of WKT representation to PostGIS geometry use ST_GeomFromText.

[참고]

The standard OGC WKT representation does not include the SRID. To include the SRID as part of the output representation, use the non-standard PostGIS function ST_AsEWKT

[주의]

The textual representation of numbers in WKT may not maintain full floating-point precision. To ensure full accuracy for data storage or transport it is best to use Well-Known Binary (WKB) format (see ST_AsBinary and maxdecimaldigits).

[주의]

Using the maxdecimaldigits parameter can cause output geometry to become invalid. To avoid this use ST_ReducePrecision with a suitable gridsize first.

1.5.0 버전부터 지리형을 지원합니다.

Enhanced: 2.5 - optional parameter precision introduced.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.1

This method implements the SQL/MM specification. SQL-MM 3: 5.1.25

This method supports Circular Strings and Curves.

예시

Code
SELECT ST_AsText('01030000000100000005000000000000000000000000000000000000000000000000000000000000000000f03f000000000000f03f000000000000f03f000000000000f03f000000000000000000000000000000000000000000000000');
래스터 출력
POLYGON((0 0,0 1,1 1,1 0,0 0))
Figure
Geometry figure for visual-st-astext-01

Full precision output is the default.

Code
SELECT ST_AsText('POINT(111.1111111 1.1111111)'::geometry);
래스터 출력
POINT(111.1111111 1.1111111)

The maxdecimaldigits argument can be used to limit output precision.

Code
SELECT ST_AsText('POINT(111.1111111 1.1111111)'::geometry, 2);
래스터 출력
POINT(111.11 1.11)

7.9.2. Well-Known Binary (WKB)

  • ST_AsBinary — Return the OGC/ISO Well-Known Binary (WKB) representation of the geometry/geography without SRID meta data.
  • ST_AsEWKB — Return the Extended Well-Known Binary (EWKB) representation of the geometry with SRID meta data.
  • ST_AsHEXEWKB — 도형을 소 엔디안(NDR) 또는 대 엔디안(XDR) 인코딩을 통해 HEXEWKB (텍스트) 형식으로 반환합니다.

제목

ST_AsBinary — Return the OGC/ISO Well-Known Binary (WKB) representation of the geometry/geography without SRID meta data.

요약

bytea ST_AsBinary(geometry g1);

bytea ST_AsBinary(geometry g1, text NDR_or_XDR);

bytea ST_AsBinary(geography g1);

bytea ST_AsBinary(geography g1, text NDR_or_XDR);

설명

Returns the OGC/ISO Well-Known Binary (WKB) representation of the geometry. The first function variant defaults to encoding using server machine endian. The second function variant takes a text argument specifying the endian encoding: either 'NDR' for little-endian; or 'XDR' for big-endian. Supplying unknown arguments will result in little-endian output.

WKB format is useful to read geometry data from the database and maintaining full numeric precision. This avoids the precision rounding that can happen with text formats such as WKT.

To perform the inverse conversion of WKB to PostGIS geometry use ST_GeomFromWKB.

[참고]

The OGC/ISO WKB format does not include the SRID. To get the EWKB format which does include the SRID use ST_AsEWKB

[참고]

PostgreSQL outputs bytea values in hex encoding by default. If your GUI tools require the old behavior, then SET bytea_output='escape' in your database.

개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다.

개선 사항: 2.0.0 버전부터 더 높은 좌표 차원을 지원합니다.

개선 사항: 2.0.0 버전부터 지리형과 함께 엔디안을 설정하는 방식을 지원합니다.

1.5.0 버전부터 지리형을 지원합니다.

Changed: 2.0.0 Inputs to this function can not be unknown -- must be geometry. Constructs such as ST_AsBinary('POINT(1 2)') are no longer valid and you will get an n ST_AsBinary(unknown) is not unique error. Code like that needs to be changed to ST_AsBinary('POINT(1 2)'::geometry);. If that is not possible, then install legacy.sql.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.1

This method implements the SQL/MM specification. SQL-MM 3: 5.1.37

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

This function supports 3d and will not drop the z-index.

예시

Code
SELECT ST_AsBinary(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))', 4326));
래스터 출력
\x01030000000100000005000000000000000000000000000000000000000000000000000000000000
000000f03f000000000000f03f000000000000f03f000000000000f03f0000000000000000000000
00000000000000000000000000
Code
SELECT ST_AsBinary(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))', 4326), 'XDR');
래스터 출력
\x000000000300000001000000050000000000000000000000000000000000000000000000003ff000
00000000003ff00000000000003ff00000000000003ff00000000000000000000000000000000000
00000000000000000000000000

제목

ST_AsEWKB — Return the Extended Well-Known Binary (EWKB) representation of the geometry with SRID meta data.

요약

bytea ST_AsEWKB(geometry g1);

bytea ST_AsEWKB(geometry g1, text NDR_or_XDR);

설명

Returns the Extended Well-Known Binary (EWKB) representation of the geometry with SRID metadata. The first function variant defaults to encoding using server machine endian. The second function variant takes a text argument specifying the endian encoding: either 'NDR' for little-endian; or 'XDR' for big-endian. Supplying unknown arguments will result in little-endian output.

WKB format is useful to read geometry data from the database and maintaining full numeric precision. This avoids the precision rounding that can happen with text formats such as WKT.

To perform the inverse conversion of EWKB to PostGIS geometry use ST_GeomFromEWKB.

[참고]

To get the OGC/ISO WKB format use ST_AsBinary. Note that OGC/ISO WKB format does not include the SRID.

개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

Code
SELECT ST_AsEWKB(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))', 4326));
래스터 출력
\x0103000020e610000001000000050000000000000000000000000000000000000000000000000000
00000000000000f03f000000000000f03f000000000000f03f000000000000f03f00000000000000
0000000000000000000000000000000000
Code
SELECT ST_AsEWKB(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))', 4326), 'XDR');
래스터 출력
\x0020000003000010e600000001000000050000000000000000000000000000000000000000000000
003ff00000000000003ff00000000000003ff00000000000003ff000000000000000000000000000
0000000000000000000000000000000000

제목

ST_AsHEXEWKB — 도형을 소 엔디안(NDR) 또는 대 엔디안(XDR) 인코딩을 통해 HEXEWKB (텍스트) 형식으로 반환합니다.

요약

text ST_AsHEXEWKB(geometry g1, text NDRorXDR);

text ST_AsHEXEWKB(geometry g1);

설명

도형을 소 엔디안(NDR) 또는 대 엔디안(XDR) 인코딩을 통해 HEXEWKB (텍스트) 형식으로 반환합니다. 인코딩을 설정하지 않으면 NDR을 씁니다.

1.2.2 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

예시

Code
SELECT ST_AsHEXEWKB(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))', 4326));
래스터 출력
0103000020E6100000010000000500
00000000000000000000000000000000
00000000000000000000000000000000F03F
000000000000F03F000000000000F03F000000000000F03
F000000000000000000000000000000000000000000000000

Which gives the same answer as:

Code
SELECT ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))', 4326)::text;

7.9.3. Other Formats

  • ST_AsEncodedPolyline — 라인스트링 도형으로부터 인코딩된 폴리라인을 반환합니다.
  • ST_AsFlatGeobuf — Return a FlatGeobuf representation of a set of rows.
  • ST_AsGeobuf — Return a Geobuf representation of a set of rows.
  • ST_AsGeoJSON — Return a geometry or feature in GeoJSON format.
  • ST_AsGML — 도형을 GML 2 또는 GML 3 버전 요소로 반환합니다.
  • ST_AsKML — 도형을 GML 2 또는 GML 3 버전 요소로 반환합니다.
  • ST_AsLatLonText — 주어진 포인트의 도, 분, 초 표현식을 반환합니다.
  • ST_AsMARC21 — Returns geometry as a MARC21/XML record with a geographic datafield (034).
  • ST_AsMVTGeom — Transforms a geometry into the coordinate space of a MVT tile.
  • ST_AsMVT — Aggregate function returning a MVT representation of a set of rows.
  • ST_AsSVG — Returns SVG path data for a geometry.
  • ST_AsTWKB — 도형을 TWKB(Tiny Well-Known Binary)로 반환합니다.
  • ST_AsX3D — 도형을 X3D XML 노드 요소 형식: ISO-IEC-19776-1.2-X3DEncodings-XML로 반환합니다.
  • ST_GeoHash — 도형의 GeoHash 표현식을 반환합니다.

제목

ST_AsEncodedPolyline — 라인스트링 도형으로부터 인코딩된 폴리라인을 반환합니다.

요약

text ST_AsEncodedPolyline(geometry geom, integer precision=5);

설명

Returns the geometry in the Encoded Polyline Algorithm Format. The format stores latitude and longitude deltas as integers after multiplying coordinates by 10 raised to the requested precision.

The informal names polyline5 and polyline6 refer to the same encoding with precision 5 and 6. The precision must match when encoding and decoding; otherwise the coordinates are scaled incorrectly.

The input geometry must use SRID 4326, with longitude as X and latitude as Y. Use ST_Transform to transform geometries in other coordinate systems before encoding.

The OSRM API returns precision 5 for geometries=polyline and precision 6 for geometries=polyline6. Decode the resulting route.geometry with ST_LineFromEncodedPolyline using the matching precision.

2.2.0 버전부터 사용할 수 있습니다.

예시

Encode the same WGS 84 LineString using precision 5 and 6.

Code
WITH route AS (
  SELECT ST_GeomFromEWKT(
    'SRID=4326;LINESTRING(-120.2 38.5,-120.95 40.7,-126.453 43.252)'
  ) AS geom
)
SELECT ST_AsEncodedPolyline(geom, 5) AS polyline5,
       ST_AsEncodedPolyline(geom, 6) AS polyline6
FROM route;
래스터 출력
polyline5          |            polyline6
-----------------------------+----------------------------------
 _p~iF~ps|U_ulLnnqC_mqNvxq`@ | _izlhA~rlgdF_{geC~ywl@_kwzCn`{nI

Decode an OSRM route.geometry returned with geometries=polyline6.

Code
SELECT ST_AsEWKT(ST_LineFromEncodedPolyline(
  '_izlhA~rlgdF_{geC~ywl@_kwzCn`{nI',
  6
)) AS route;
래스터 출력
SRID=4326;LINESTRING(-120.2 38.5,-120.95 40.7,-126.453 43.252)
Figure
Geometry figure for visual-st-asencodedpolyline-02

The Google Maps JavaScript Geometry library decodes precision-5 strings. This browser example assumes that map is an initialized Google map.

Code
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry"
></script>
<script>
  const encodedPath = "_p~iF~ps|U_ulLnnqC_mqNvxq`@";
  const flightPath = new google.maps.Polyline({
    path: google.maps.geometry.encoding.decodePath(encodedPath),
    map: map,
    strokeColor: "#0000CC",
    strokeOpacity: 1.0,
    strokeWeight: 4
  });
</script>

제목

ST_AsFlatGeobuf — Return a FlatGeobuf representation of a set of rows.

요약

bytea ST_AsFlatGeobuf(anyelement set row);

bytea ST_AsFlatGeobuf(anyelement row, bool index);

bytea ST_AsFlatGeobuf(anyelement row, bool index, text geom_name);

설명

Return a FlatGeobuf representation (http://flatgeobuf.org) of a set of rows corresponding to a FeatureCollection. NOTE: PostgreSQL bytea cannot exceed 1GB.

row row data with at least a geometry column.

index toggle spatial index creation. Default is false.

geom_name is the name of the geometry column in the row data. If NULL it will default to the first found geometry column.

Availability: 3.2.0


제목

ST_AsGeobuf — Return a Geobuf representation of a set of rows.

요약

bytea ST_AsGeobuf(anyelement set row);

bytea ST_AsGeobuf(anyelement row, text geom_name);

설명

Return a Geobuf representation (https://github.com/mapbox/geobuf) of a set of rows corresponding to a FeatureCollection. Every input geometry is analyzed to determine maximum precision for optimal storage. Note that Geobuf in its current form cannot be streamed so the full output will be assembled in memory.

row row data with at least a geometry column.

geom_name is the name of the geometry column in the row data. If NULL it will default to the first found geometry column.

2.2.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT encode(ST_AsGeobuf(q, 'geom'), 'base64')
FROM (SELECT 'POLYGON((0 0,0 1,1 1,1 0,0 0))'::geometry AS geom) AS q;
래스터 출력
GAAiEAoOCgwIBBoIAAAAAgIAAAE=

제목

ST_AsGeoJSON — Return a geometry or feature in GeoJSON format.

요약

text ST_AsGeoJSON(record feature, text geom_column="", integer maxdecimaldigits=9, boolean pretty_bool=false, text id_column='');

text ST_AsGeoJSON(geometry geom, integer maxdecimaldigits=9, integer options=8);

text ST_AsGeoJSON(geography geog, integer maxdecimaldigits=9, integer options=0);

설명

Returns a geometry as a GeoJSON "geometry" object, or a row as a GeoJSON "feature" object.

The resulting GeoJSON geometry and feature representations conform with the GeoJSON specifications RFC 7946, except when the parsed geometries are referenced with a CRS other than WGS84 longitude and latitude (EPSG:4326, urn:ogc:def:crs:OGC::CRS84); the GeoJSON geometry object will then have a short CRS SRID identifier attached by default. 2D and 3D Geometries are both supported. GeoJSON only supports SFS 1.1 geometry types (no curve support for example).

The geom_column parameter is used to distinguish between multiple geometry columns. If omitted, the first geometry column in the record will be determined. Conversely, passing the parameter will save column type lookups.

The maxdecimaldigits argument may be used to reduce the maximum number of decimal places used in output (defaults to 9). If you are using EPSG:4326 and are outputting the geometry only for display, maxdecimaldigits=6 can be a good choice for many maps.

[주의]

Using the maxdecimaldigits parameter can cause output geometry to become invalid. To avoid this use ST_ReducePrecision with a suitable gridsize first.

The options argument can be used to add BBOX or CRS in GeoJSON output:

  • 0: means no option

  • 1: GeoJSON BBOX

  • 2: GeoJSON Short CRS (예: EPSG:4326)

  • 4: GeoJSON Long CRS (예: urn:ogc:def:crs:EPSG::4326)

  • 8: GeoJSON Short CRS if not EPSG:4326 (default)

The id_column parameter is used to set the "id" member of the returned GeoJSON features. As per GeoJSON RFC, this SHOULD be used whenever a feature has a commonly used identifier, such as a primary key. When not specified, the produced features will not get an "id" member and any columns other than the geometry, including any potential keys, will just end up inside the feature’s "properties" member.

When the input record includes duplicate column names, the resulting "properties" object will contain repeated keys. ST_AsGeoJSON raises a warning in that case because PostgreSQL jsonb keeps only the last value for duplicate keys.

The GeoJSON specification states that polygons are oriented using the Right-Hand Rule, and some clients require this orientation. This can be ensured by using ST_ForcePolygonCCW. The specification also requires that geometry be in the WGS84 coordinate system (SRID = 4326). If necessary geometry can be projected into WGS84 using ST_Transform: ST_Transform(geom, 4326 ).

GeoJSON can be tested and viewed online at geojson.io and geojsonlint.com. It is widely supported by web mapping frameworks:

1.3.4 버전부터 사용할 수 있습니다.

1.5.0 버전부터 지리형을 지원합니다.

변경 사항: 2.0.0 버전부터 기본 독립 변수(default arg) 및 명명된 독립 변수(named arg)를 지원합니다.

Changed: 3.0.0 support records as input

Changed: 3.0.0 output SRID if not EPSG:4326.

Changed: 3.5.0 allow specifying the column containing the feature id

Changed: 3.7.0 added warning about duplicate keys

This function supports 3d and will not drop the z-index.

예시

Generate a FeatureCollection:

Code
SELECT json_build_object(
    'type', 'FeatureCollection',
    'features', json_agg(ST_AsGeoJSON(t.*, id_column =
> 'id')::json)
    )
FROM ( VALUES (1, 'one', 'POINT(1 1)'::geometry),
              (2, 'two', 'POINT(2 2)'),
              (3, 'three', 'POINT(3 3)')
     ) as t(id, name, geom);
래스터 출력
{"type" : "FeatureCollection", "features" : [{"type": "Feature", "geometry": {"type":"Point","coordinates":[1,1]}, "id": 1, "properties": {"name": "one"}}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[2,2]}, "id": 2, "properties": {"name": "two"}}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[3,3]}, "id": 3, "properties": {"name": "three"}}]}

Generate a Feature:

Code
SELECT ST_AsGeoJSON(t.*, id_column =
> 'id')
FROM (VALUES (1, 'one', 'POINT(1 1)'::geometry)) AS t(id, name, geom);
래스터 출력
{"type": "Feature", "geometry": {"type":"Point","coordinates":[1,1]}, "id": 1, "properties": {"name": "one"}}

Don't forget to transform your data to WGS84 longitude, latitude to conform with the GeoJSON specification:

Code
SELECT ST_AsGeoJSON(ST_Transform(geom, 4326)) FROM fe_edges LIMIT 1;
래스터 출력
{"type":"MultiLineString","coordinates":[[[-89.734634999999997,31.492072000000000],
[-89.734955999999997,31.492237999999997]]]}

3D geometries are supported:

Code
SELECT ST_AsGeoJSON('LINESTRING(1 2 3,4 5 6)');
래스터 출력
{"type":"LineString","coordinates":[[1,2,3],[4,5,6]]}

Options argument can be used to add BBOX and CRS in GeoJSON output:

Code
SELECT ST_AsGeoJSON(ST_SetSRID('POINT(1 1)'::geometry, 4326), 9, 4|1);
래스터 출력
{"type":"Point","crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:EPSG::4326"}},"bbox":[1.000000000,1.000000000,1.000000000,1.000000000],"coordinates":[1,1]}

제목

ST_AsGML — 도형을 GML 2 또는 GML 3 버전 요소로 반환합니다.

요약

text ST_AsGML(geometry geom, integer maxdecimaldigits=15, integer options=0);

text ST_AsGML(geography geog, integer maxdecimaldigits=15, integer options=0, text nprefix=null, text id=null);

text ST_AsGML(integer version, geometry geom, integer maxdecimaldigits=15, integer options=0, text nprefix=null, text id=null);

text ST_AsGML(integer version, geography geog, integer maxdecimaldigits=15, integer options=0, text nprefix=null, text id=null);

설명

Return the geometry as a Geography Markup Language (GML) element. The version parameter, if specified, may be either 2 or 3. If no version parameter is specified then the default is assumed to be 2. The maxdecimaldigits argument may be used to reduce the maximum number of decimal places used in output (defaults to 15).

[주의]

Using the maxdecimaldigits parameter can cause output geometry to become invalid. To avoid this use ST_ReducePrecision with a suitable gridsize first.

GML 2는 2.1.2 버전을, GML 3은 3.1.1 버전을 가리킵니다.

'옵션' 인수는 비트필드(bitfield) 구조체입니다. CRS 출력 유형을 GML 출력으로 정의하고, 데이터를 위도/경도로 선언하는 데 쓸 수 있습니다.

  • 0: GML Short CRS (예: EPSG:4326), 기본값

  • 1: GML Long CRS (예: urn:ogc:def:crs:EPSG::4326)

  • 2: GML 3에 한해, 출력물에서 srsDimension 속성을 제거합니다.

  • 4: GML 3에 한해, 라인을 위해 <Curve> 보다 <LineString> 태그를 사용합니다.

  • 16: 데이터가 위도/경도(예: srid=4326)라고 선언합니다. 기본적으로는 데이터가 평면 좌표라고 가정합니다. 이 옵션은 축의 순서(axis order)와 관련돼 있어, GML 3.1.1 출력물에 대해서만 쓸모가 있습니다. 따라서 이 옵션을 설정하면, 데이터베이스의 경도 위도 대신 위도 경도로 좌표의 순서를 바꿀 것입니다.

  • 32: 도형을 둘러싼 상자(envelope)를 출력합니다.

사용자 지정 네임스페이스 접두사를 설정하거나 접두사를 사용하지 않도록 설정(비어 있는 경우)하는 데 '네임스페이스 접두사' 인수를 사용할 수도 있습니다. 이 인수가 NULL이거나 생략된 경우 'gml' 접두사를 씁니다.

1.3.2 버전부터 사용할 수 있습니다.

1.5.0 버전부터 지리형을 지원합니다.

개선 사항: 2.0.0 버전부터 접두사를 지원합니다. 라인에 대해 커브 대신 라인스트링 태그를 이용할 수 있도록 GML 3용 옵션 '4'가 등장했습니다. GML 3가 다면체 표면 및 TIN을 지원하기 시작했습니다. 상자를 출력하는 옵션 '32'도 새롭게 등장했습니다.

변경 사항: 2.0.0 버전부터 명명된 독립변수(named arg)를 기본값으로 씁니다.

개선 사항: 2.1.0 버전부터 GML 3를 위해 ID를 지원하기 시작했습니다.

[참고]

ST_AsGML 함수의 3 이상 버전만이 다면체 표면 및 TIN을 지원합니다.

This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 17.2

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

Version 2.

Code
SELECT ST_AsGML(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))', 4326));
래스터 출력
<gml:Polygon srsName="EPSG:4326"
><gml:outerBoundaryIs
><gml:LinearRing
><gml:coordinates
>0,0 0,1 1,1 1,0 0,0</gml:coordinates
></gml:LinearRing
></gml:outerBoundaryIs
></gml:Polygon
>

Version 3.

Flip coordinates and output extended EPSG (16 | 1)

Code
SELECT ST_AsGML(3, ST_GeomFromText('POINT(5.234234233242 6.34534534534)', 4326), 5, 17);
래스터 출력
<gml:Point srsName="urn:ogc:def:crs:EPSG::4326"
><gml:pos srsDimension="2"
>6.34535 5.23423</gml:pos
></gml:Point
>

Output the envelope (32).

Code
SELECT ST_AsGML(3, ST_GeomFromText('LINESTRING(1 2, 3 4, 10 20)',4326), 5, 32);
래스터 출력
<gml:Envelope srsName="EPSG:4326" srsDimension="2"
><gml:lowerCorner
>1 2</gml:lowerCorner
><gml:upperCorner
>10 20</gml:upperCorner
></gml:Envelope
>

Output the envelope (32), reverse (lat lon instead of lon lat) (16), long srs (1) = 32 | 16 | 1 = 49.

Code
SELECT ST_AsGML(3, ST_GeomFromText('LINESTRING(1 2, 3 4, 10 20)',4326), 5, 49);
래스터 출력
<gml:Envelope srsName="urn:ogc:def:crs:EPSG::4326" srsDimension="2"
><gml:lowerCorner
>2 1</gml:lowerCorner
><gml:upperCorner
>20 10</gml:upperCorner
></gml:Envelope
>

This example uses a PolyhedralSurface.

Code
SELECT ST_AsGML(
3,
'POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)),
((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)),
((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)),
((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )'::geometry);
래스터 출력
 <gml:PolyhedralSurface>
<gml:polygonPatches>
   <gml:PolygonPatch>
    <gml:exterior>
        <gml:LinearRing>
           <gml:posList srsDimension="3"
>0 0 0 0 0 1 0 1 1 0 1 0 0 0 0</gml:posList>
        </gml:LinearRing>
    </gml:exterior>
   </gml:PolygonPatch>
   <gml:PolygonPatch>
    <gml:exterior>
        <gml:LinearRing>
           <gml:posList srsDimension="3"
>0 0 0 0 1 0 1 1 0 1 0 0 0 0 0</gml:posList>
        </gml:LinearRing>
    </gml:exterior>
   </gml:PolygonPatch>
   <gml:PolygonPatch>
    <gml:exterior>
        <gml:LinearRing>
           <gml:posList srsDimension="3"
>0 0 0 1 0 0 1 0 1 0 0 1 0 0 0</gml:posList>
        </gml:LinearRing>
    </gml:exterior>
   </gml:PolygonPatch>
   <gml:PolygonPatch>
    <gml:exterior>
        <gml:LinearRing>
           <gml:posList srsDimension="3"
>1 1 0 1 1 1 1 0 1 1 0 0 1 1 0</gml:posList>
        </gml:LinearRing>
    </gml:exterior>
   </gml:PolygonPatch>
   <gml:PolygonPatch>
    <gml:exterior>
        <gml:LinearRing>
           <gml:posList srsDimension="3"
>0 1 0 0 1 1 1 1 1 1 1 0 0 1 0</gml:posList>
        </gml:LinearRing>
    </gml:exterior>
   </gml:PolygonPatch>
   <gml:PolygonPatch>
    <gml:exterior>
        <gml:LinearRing>
           <gml:posList srsDimension="3"
>0 0 1 1 0 1 1 1 1 0 1 1 0 0 1</gml:posList>
        </gml:LinearRing>
    </gml:exterior>
   </gml:PolygonPatch>
</gml:polygonPatches>
</gml:PolyhedralSurface
>

제목

ST_AsKML — 도형을 GML 2 또는 GML 3 버전 요소로 반환합니다.

요약

text ST_AsKML(geometry geom, integer maxdecimaldigits=15, text nprefix=NULL);

text ST_AsKML(geography geog, integer maxdecimaldigits=15, text nprefix=NULL);

설명

도형을 KML(Keyhole Markup Language) 요소로 반환합니다. 이 함수에는 몇 가지 변종이 있습니다. 출력물에 쓰이는 소수점 이하 자릿수의 최대값(기본값은 15), 버전의 기본값은 2이며 기본 네임스페이스는 접두사를 쓰지 않습니다.

[주의]

Using the maxdecimaldigits parameter can cause output geometry to become invalid. To avoid this use ST_ReducePrecision with a suitable gridsize first.

1.2.2 버전부터 사용할 수 있습니다. 버전 파라미터를 포함하는 최신 변종은 1.3.2 버전부터 등장했습니다.

개선 사항: 2.0.0 버전부터 네임스페이스에 접두사를 추가할 수 있습니다. 기본값은 접두사를 쓰지 않는 것입니다.

Changed: 3.0.0 - Removed the "versioned" variant signature

[참고]

PostGIS를 Proj 지원과 함께 컴파일해야 합니다. Proj 지원과 함께 컴파일됐는지 여부를 확인하려면 PostGIS_Full_Version 을 이용하십시오.

[참고]

ST_AsKML 출력물은 SRID가 없는 도형과는 동작하지 않을 것입니다.

This function supports 3d and will not drop the z-index.

예시

Code
SELECT ST_AsKML(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))', 4326));
래스터 출력
<Polygon
><outerBoundaryIs
><LinearRing
><coordinates
>0,0 0,1 1,1 1,0 0,0</coordinates
></LinearRing
></outerBoundaryIs
></Polygon
>

This example outputs a 3D LineString.

Code
SELECT ST_AsKML('SRID=4326;LINESTRING(1 2 3,4 5 6)');
래스터 출력
<LineString
><coordinates
>1,2,3 4,5,6</coordinates
></LineString
>

제목

ST_AsLatLonText — 주어진 포인트의 도, 분, 초 표현식을 반환합니다.

요약

text ST_AsLatLonText(geometry pt, text format='');

설명

포인트의 도, 분, 초 표현식을 반환합니다.

[참고]

이 함수는 포인트가 위도/경도 투영체 안에 있다고 가정합니다. 출력물에서 X(경도) 및 Y(위도) 좌표는 "정규" 범위(경도는 -180도에서 180도, 위도는 -90도에서 90도)로 정규화됩니다.

텍스트 파라미터는 결과물의 텍스트를 위한 형식을 담고 있는 형식 스트링으로, 날짜 형식 스트링과 비슷합니다. 유효한 토큰은 도를 나타내는 "D", 분을 나타내는 "M", 초를 나타내는 "S", 그리고 기본방향(북남동서, cardinal direction)을 나타내는 "C"입니다. D, M, S 토큰들은 원하는 폭 및 정밀도를 표시하기 위해 반복될 수도 있습니다("SSS.SSSS"는 "1.0023"처럼 표기하라는 뜻입니다).

M, S, C는 선택적입니다. "C"가 생략된 경우, 도는 남쪽 또는 서쪽일 경우 "-" 부호와 함께 표시됩니다. "S"가 생략된 경우, 사용자가 설정한 대로의 소수점 이하 자릿수 정밀도로 분이 표시될 것입니다. "M"도 생략된 경우, 사용자가 설정한 대로의 소수점 이하 자릿수 정밀도로 도가 표시될 것입니다.

형식 스트링이 빠진 (또는 길이가 0인) 경우 기본 형식을 쓸 것입니다.

2.0 버전부터 사용할 수 있습니다.

예시

기본 형식

Code
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)'));
래스터 출력
2°19'29.928"S 3°14'3.243"W

(기본값과 동일한) 형식을 제공합니다.

Code
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)', 'D°M''S.SSS"C'));
래스터 출력
2°19'29.928"S 3°14'3.243"W

D, M, S, C 및 .이 아닌 다른 문자들은 그냥 무시됩니다.

Code
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)', 'D degrees, M minutes, S seconds to the C'));
래스터 출력
2 degrees, 19 minutes, 30 seconds to the S 3 degrees, 14 minutes, 3 seconds to the W

기본방향 대신 부호가 붙은 도를 사용합니다.

Code
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)', 'D°M''S.SSS"'));
래스터 출력
-2°19'29.928" -3°14'3.243"

소수점이 붙은 도를 사용합니다.

Code
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)', 'D.DDDD degrees C'));
래스터 출력
2.3250 degrees S 3.2342 degrees W

지나치게 큰 값은 정규화됩니다.

Code
SELECT (ST_AsLatLonText('POINT (-302.2342342 -792.32498)'));
래스터 출력
72°19'29.928"S 57°45'56.757"E

제목

ST_AsMARC21 — Returns geometry as a MARC21/XML record with a geographic datafield (034).

요약

text ST_AsMARC21 ( geometry geom , text format='hdddmmss' );

설명

This function returns a MARC21/XML record with Coded Cartographic Mathematical Data representing the bounding box of a given geometry. The format parameter allows to encode the coordinates in subfields $d,$e,$f and $g in all formats supported by the MARC21/XML standard. Valid formats are:

  • cardinal direction, degrees, minutes and seconds (default): hdddmmss

  • decimal degrees with cardinal direction: hddd.dddddd

  • decimal degrees without cardinal direction: ddd.dddddd

  • decimal minutes with cardinal direction: hdddmm.mmmm

  • decimal minutes without cardinal direction: dddmm.mmmm

  • decimal seconds with cardinal direction: hdddmmss.sss

The decimal sign may be also a comma, e.g. hdddmm,mmmm.

The precision of decimal formats can be limited by the number of characters after the decimal sign, e.g. hdddmm.mm for decimal minutes with a precision of two decimals.

This function ignores the Z and M dimensions.

LOC MARC21/XML versions supported:

Availability: 3.3.0

[참고]

This function does not support non lon/lat geometries, as they are not supported by the MARC21/XML standard (Coded Cartographic Mathematical Data).

[참고]

The MARC21/XML Standard does not provide any means to annotate the spatial reference system for Coded Cartographic Mathematical Data, which means that this information will be lost after conversion to MARC21/XML.

예시

Converting a POINT to MARC21/XML formatted as hdddmmss (default)

Code
SELECT ST_AsMARC21('SRID=4326;POINT(-4.504289 54.253312)'::geometry);
래스터 출력
                                st_asmarc21
-------------------------------------------------
<record xmlns="http://www.loc.gov/MARC21/slim">
    <datafield tag="034" ind1="1" ind2=" ">
        <subfield code="a"
>a</subfield>
        <subfield code="d"
>W0043015</subfield>
        <subfield code="e"
>W0043015</subfield>
        <subfield code="f"
>N0541512</subfield>
        <subfield code="g"
>N0541512</subfield>
    </datafield>
</record>

Converting a POLYGON to MARC21/XML formatted in decimal degrees

Code
SELECT ST_AsMARC21('SRID=4326;POLYGON((-4.5792388916015625 54.18172660239091,-4.56756591796875 54.196993557130355,-4.546623229980469 54.18313300502024,-4.5792388916015625 54.18172660239091))'::geometry,'hddd.dddd');

<record xmlns="http://www.loc.gov/MARC21/slim">
    <datafield tag="034" ind1="1" ind2=" ">
        <subfield code="a"
>a</subfield>
        <subfield code="d"
>W004.5792</subfield>
        <subfield code="e"
>W004.5466</subfield>
        <subfield code="f"
>N054.1970</subfield>
        <subfield code="g"
>N054.1817</subfield>
    </datafield>
</record>



Converting a GEOMETRYCOLLECTION to MARC21/XML formatted in decimal minutes. The geometries order in the MARC21/XML output correspond to their order in the collection.

Code
SELECT ST_AsMARC21('SRID=4326;GEOMETRYCOLLECTION(POLYGON((13.1 52.65,13.516666666666667 52.65,13.516666666666667 52.38333333333333,13.1 52.38333333333333,13.1 52.65)),POINT(-4.5 54.25))'::geometry,'hdddmm.mmmm');
래스터 출력
                                st_asmarc21
-------------------------------------------------
<record xmlns="http://www.loc.gov/MARC21/slim">
    <datafield tag="034" ind1="1" ind2=" ">
        <subfield code="a"
>a</subfield>
        <subfield code="d"
>E01307.0000</subfield>
        <subfield code="e"
>E01331.0000</subfield>
        <subfield code="f"
>N05240.0000</subfield>
        <subfield code="g"
>N05224.0000</subfield>
    </datafield>
    <datafield tag="034" ind1="1" ind2=" ">
        <subfield code="a"
>a</subfield>
        <subfield code="d"
>W00430.0000</subfield>
        <subfield code="e"
>W00430.0000</subfield>
        <subfield code="f"
>N05415.0000</subfield>
        <subfield code="g"
>N05415.0000</subfield>
    </datafield>
</record>

제목

ST_AsMVTGeom — Transforms a geometry into the coordinate space of a MVT tile.

요약

geometry ST_AsMVTGeom(geometry geom, box2d bounds, integer extent=4096, integer buffer=256, boolean clip_geom=true);

설명

Transforms a geometry into the coordinate space of a MVT (Mapbox Vector Tile) tile, clipping it to the tile bounds if required. The geometry must be in the coordinate system of the target map (using ST_Transform if needed). Commonly this is Web Mercator (SRID:3857).

The function attempts to preserve geometry validity, and corrects it if needed. This may cause the result geometry to collapse to a lower dimension.

The function performs geometry simplification appropriate to the integer tile coordinate space. After transforming to tile coordinates it snaps coordinates to the integer grid, removes repeated points, and removes points that lie on straight lines. It does not perform general-purpose, scale-dependent simplification such as ST_Simplify. To reduce detail before tile conversion, simplify the geometry in map coordinates before calling ST_AsMVTGeom.

The rectangular bounds of the tile in the target map coordinate space must be provided, so the geometry can be transformed, and clipped if required. The bounds can be generated using ST_TileEnvelope.

This function is used to convert geometry into the tile coordinate space required by ST_AsMVT.

geom is the geometry to transform, in the coordinate system of the target map.

bounds is the rectangular bounds of the tile in map coordinate space, with no buffer.

extent is the tile extent size in tile coordinate space as defined by the MVT specification. Defaults to 4096.

buffer is the buffer size in tile coordinate space for geometry clippig. Defaults to 256.

clip_geom is a boolean to control if geometries are clipped or encoded as-is. Defaults to true.

2.2.0 버전부터 사용할 수 있습니다.

[참고]

From 3.0, Wagyu can be chosen at configure time to clip and validate MVT polygons. This library is faster and produces more correct results than the GEOS default, but it might drop small polygons.

예시

Code
SELECT ST_AsMVTGeom('POLYGON ((0 0,10 0,10 5,0 -5,0 0))',
    ST_MakeBox2D(ST_Point(0, 0), ST_Point(4096, 4096)),
    4096, 0, false);
래스터 출력
MULTIPOLYGON(((5 4096,10 4091,10 4096,5 4096)),((5 4096,0 4101,0 4096,5 4096)))
Figure
Geometry figure for visual-st-asmvtgeom-01

Canonical example for a Web Mercator tile using a computed tile bounds to query and clip geometry. This assumes the data.geom column has srid of 4326.

Code
SELECT ST_AsMVTGeom(ST_Transform(geom, 3857 ),
            ST_TileEnvelope(12, 513, 412),
            extent =
> 4096,
            buffer =
> 64) AS geom
  FROM data
  WHERE geom && ST_Transform(ST_TileEnvelope(12, 513, 412, margin =
> (64.0 / 4096)), 4326)



제목

ST_AsMVT — Aggregate function returning a MVT representation of a set of rows.

요약

bytea ST_AsMVT(anyelement set row);

bytea ST_AsMVT(anyelement row, text name);

bytea ST_AsMVT(anyelement row, text name, integer extent);

bytea ST_AsMVT(anyelement row, text name, integer extent, text geom_name);

bytea ST_AsMVT(anyelement row, text name, integer extent, text geom_name, text feature_id_name);

설명

An aggregate function which returns a binary Mapbox Vector Tile representation of a set of rows corresponding to a tile layer. The rows must contain a geometry column which will be encoded as a feature geometry. The geometry must be in tile coordinate space and valid as per the MVT specification. ST_AsMVTGeom can be used to transform geometry into tile coordinate space. Other row columns are encoded as feature attributes.

The Mapbox Vector Tile format can store features with varying sets of attributes. To use this capability supply a JSONB column in the row data containing Json objects one level deep. The keys and values in the JSONB values will be encoded as feature attributes.

Tiles with multiple layers can be created by concatenating multiple calls to this function using || or STRING_AGG.

[중요]

Do not call with a GEOMETRYCOLLECTION as an element in the row. However you can use ST_AsMVTGeom to prepare a geometry collection for inclusion.

row row data with at least a geometry column.

name is the name of the layer. Default is the string "default".

extent is the tile extent in screen space as defined by the specification. Default is 4096.

geom_name is the name of the geometry column in the row data. Default is the first geometry column. Note that PostgreSQL by default automatically folds unquoted identifiers to lower case, which means that unless the geometry column is quoted, e.g. "MyMVTGeom", this parameter must be provided as lowercase.

feature_id_name is the name of the Feature ID column in the row data. If NULL or negative the Feature ID is not set. The first column matching name and valid type (smallint, integer, bigint) will be used as Feature ID, and any subsequent column will be added as a property. JSON properties are not supported.

Enhanced: 3.0 - added support for Feature ID.

Enhanced: 2.5.0 - added support parallel query.

2.2.0 버전부터 사용할 수 있습니다.

예시

Code
WITH mvtgeom AS
(
  SELECT ST_AsMVTGeom(geom, ST_TileEnvelope(12, 513, 412), extent =
> 4096, buffer =
> 64) AS geom, name, description
  FROM points_of_interest
  WHERE geom && ST_TileEnvelope(12, 513, 412, margin =
> (64.0 / 4096))
)
SELECT ST_AsMVT(mvtgeom.*)
FROM mvtgeom;


        

제목

ST_AsSVG — Returns SVG path data for a geometry.

요약

text ST_AsSVG(geometry geom, integer rel=0, integer maxdecimaldigits=15);

text ST_AsSVG(geography geog, integer rel=0, integer maxdecimaldigits=15);

설명

도형을 SVG(Scalar Vector Graphics) 경로 데이터로 반환합니다. 상대 이동(relative move) 관점에서 구현된 경로 데이터를 얻으려면 두 번째 인수로 1을 사용하고, 절대 이동(absolute move) 관점에서 구현된 경로 데이터를 얻으려면 기본값 0을 사용하십시오. 출력물에 쓰인 소수점 이하 자릿수의 최대값(기본값은 15)을 줄이는 데 세 번째 인수를 쓸 수도 있습니다. 'rel' 독립 변수가 0일 때 포인트 도형을 cx/cy로 렌더링하고, 'rel' 독립 변수가 1일 때 x/y로 렌더링합니다. 멀티포인트 도형들은 쉼표(",")로 구분하고, 도형 집합의 도형들은 쌍반점(";")으로 구분합니다.

For working with PostGIS SVG graphics, checkout pg_svg library which provides plpgsql functions for working with outputs from ST_AsSVG.

Enhanced: 3.4.0 to support all curve types

변경 사항: 2.0.0 버전부터 기본 독립 변수(default arg)를 사용하고 명명된 독립 변수(named arg)를 지원합니다.

1.2.2 버전부터 사용할 수 있습니다. 1.4.0버전에서 http://www.w3.org/TR/SVG/paths.html#PathDataBNF 를 준수하기 위해 절대 경로에 L 명령어를 포함시켰습니다.

This method supports Circular Strings and Curves.

예시

Code
SELECT ST_AsSVG('POLYGON((0 0,0 1,1 1,1 0,0 0))'::geometry);
래스터 출력
M 0 0 L 0 -1 1 -1 1 0 Z
Figure
Geometry figure for visual-st-assvg-01

Circular string

Code
SELECT ST_AsSVG('CIRCULARSTRING(-2 0,0 2,2 0,0 2,2 4)'::geometry);
래스터 출력
M -2 0 A 2 2 0 0 1 2 0 A 2 2 0 0 1 2 -4
Figure
Geometry figure for visual-st-assvg-02

Multi-curve

Code
SELECT ST_AsSVG('MULTICURVE((5 5,3 5,3 3,0 3),
CIRCULARSTRING(0 0,2 1,2 2))'::geometry, 0, 0);
래스터 출력
M 5 -5 L 3 -5 3 -3 0 -3 M 0 0 A 2 2 0 0 0 2 -2
Figure
Geometry figure for visual-st-assvg-03

Multi-surface

Code
SELECT ST_AsSVG('MULTISURFACE(
CURVEPOLYGON(CIRCULARSTRING(-2 0,-1 -1,0 0,1 -1,2 0,0 2,-2 0),
    (-1 0,0 0.5,1 0,0 1,-1 0)),
((7 8,10 10,6 14,4 11,7 8)))'::geometry, 0, 2);
래스터 출력
M -2 0 A 1 1 0 0 0 0 0 A 1 1 0 0 0 2 0 A 2 2 0 0 0 -2 0 Z
M -1 0 L 0 -0.5 1 0 0 -1 -1 0 Z
M 7 -8 L 10 -10 6 -14 4 -11 Z
Figure
Geometry figure for visual-st-assvg-04

제목

ST_AsTWKB — 도형을 TWKB(Tiny Well-Known Binary)로 반환합니다.

요약

bytea ST_AsTWKB(geometry geom, integer prec=0, integer prec_z=0, integer prec_m=0, boolean with_sizes=false, boolean with_boxes=false);

bytea ST_AsTWKB(geometry[] geom, bigint[] ids, integer prec=0, integer prec_z=0, integer prec_m=0, boolean with_sizes=false, boolean with_boxes=false);

설명

도형을 TWKB(Tiny Well-Known Binary) 형식으로 반환합니다. TWKB는 출력물의 용량을 최소화하는 데 집중한 압축 바이너리 형식 입니다.

소수점 이하 자릿수 파라미터가 출력물에 어느 정도의 정밀도를 저장할지 결정합니다. 기본적으로, 모든 값은 인코딩하기 전에 가장 가까운 단위로 반올림됩니다. 더 높은 정밀도를 복사하고 싶다면, 자릿수를 올리십시오. 예를 들어, 값이 1이라면 소수점 오른쪽의 첫 번째 숫자까지 보전될 것입니다.

크기 및 경계 상자 파라미터는 객체의 인코딩된 길이 및 경계에 대한 선택적인 정보를 출력물에 포함시킬지 말지를 결정합니다. 기본적으로는 포함되지 않습니다. 사용자의 클라이언트 소프트웨어가 필요로하지 않는다면 활성화시키지 마십시오. 디스크 공간을 소비할 뿐입니다(디스크 공간을 절약하는 것이 TWKB의 목적입니다).

이 함수의 배열 입력 형식은 도형 집합 및 유일 식별자를 식별자를 보전하는 TWKB 집합으로 변환하는 데 쓰입니다. 집합의 압축을 풀어 그 안에 있는 객체들에 대한 상세 정보에 접근하는 기능을 가진 클라이언트에 유용합니다. array_agg 함수를 이용해서 배열을 생성할 수 있습니다. 다른 파라미터들은 이 함수의 단순 형태의 경우와 동일하게 실행됩니다.

[참고]

https://github.com/TWKB/Specification 에서 형식 사양서를 찾아볼 수 있으며, https://github.com/TWKB/twkb.js 에서 자바스크립트 클라이언트를 빌드하기 위한 코드를 찾을 수 있습니다.

Enhanced: 2.4.0 memory and speed improvements.

2.2.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT ST_AsTWKB('LINESTRING(1 1,5 5)'::geometry);
래스터 출력
\x02000202020808

식별자를 포함하는 종합 TWKB 객체를 생성하려면, 먼저 "array_agg()"를 통해 원하는 도형과 객체를 합친 다음 적절한 TWKB 함수를 호출하십시오.

Code
SELECT ST_AsTWKB(array_agg(geom), array_agg(gid)) FROM mytable;
래스터 출력
\x040402020400000202

제목

ST_AsX3D — 도형을 X3D XML 노드 요소 형식: ISO-IEC-19776-1.2-X3DEncodings-XML로 반환합니다.

요약

text ST_AsX3D(geometry g1, integer maxdecimaldigits=15, integer options=0);

설명

도형을 http://www.web3d.org/standards/number/19776-1 에서 정의하는 X3D XML 형식화 노드 요소로 반환합니다. maxdecimaldigits (정밀도)를 설정하지 않을 경우 기본값인 15를 씁니다.

[참고]

X3D 도형 유형이 PostGIS 도형 유형을 직접 매핑하지 않기 때문에 PostGIS 도형을 X3D 도형으로 번역하는 다양한 방법이 있습니다. 또 현재 렌더링 도구 대부분이 새로운 X3D 유형을 지원하지 않기 때문에, 더 잘 매핑돼 있는 몇몇 X3D 유형을 다루지 않습니다. 이 단원에서 다루는 것이 우리가 결정한 매핑입니다. 사용자가 선호하는 매핑을 표시할 수 있게 해주는 아이디어나 방법이 떠올랐다면 부디 버그 티켓(bug ticket)을 포스팅해주십시오.

다음은 현재 PostGIS 2D/3D 유형을 X3D 유형으로 매핑하는 방법입니다.

The 'options' argument is a bitfield that denotes whether to represent coordinates with the X3D GeoCoordinates geospatial node and whether to flip the x/y axis. By default, ST_AsX3D outputs in database form (long,lat or X,Y), but the X3D default of lat/lon, y/x may be preferred.

  • 0: 데이터베이스 순서로 정렬된 X/Y(예를 들어 경도/위도 = X,Y가 표준 데이터베이스 순서입니다), 데이터 값, 비(非) 공간 좌표(구식 정규 좌표 태그).

  • 1: X 및 Y를 뒤집습니다. 지리좌표(GeoCoordinate) 옵션 스위치와 연결해서 사용할 경우, 출력물이 기본값인 "latitude_first"(위도 먼저)가 될 것이고 좌표도 마찬가지로 뒤집힐 것입니다.

  • 2: 좌표를 지리공간 지리좌표로 출력합니다. 도형이 WGS84 경위도(SRID 4326)가 아닐 경우, 이 옵션은 오류를 발생시킬 것입니다. 현재 이 지리좌표 유형만 지원합니다. 공간 참조 시스템을 정의하는 X3D 사양 을 참조하십시오. 출력물은 기본적으로 GeoCoordinate geoSystem='"GD" "WE" "longitude_first"' 가 됩니다. X3D 기본값인 GeoCoordinate geoSystem='"GD" "WE" "latitude_first"' 를 선호한다면, (2 + 1) = 3 을 쓰십시오.

PostGIS 유형2D X3D 유형3D X3D 유형
LINESTRING아직 구현되지 않았습니다. 구현시 PolyLine2D가 될 것입니다.LineSet
MULTILINESTRING아직 구현되지 않았습니다. 구현시 PolyLine2D가 될 것입니다.IndexedLineSet
MULTIPOINTPolypoint2DPointSet
POINT공백으로 구분된 좌표를 출력합니다.공백으로 구분된 좌표를 출력합니다.
(MULTI) POLYGON, POLYHEDRALSURFACE유효하지 않은 X3D 마크업(markup)입니다.IndexedFaceSet (현재 내곽 고리를 또다른 면 집합(faceset)으로 출력합니다.)
TINTriangleSet2D (아직 구현되지 않았습니다.)IndexedTriangleSet
[참고]

2차원 도형 지원이 아직 완성되지 않았습니다. 현재 내곽 고리를 그저 개별적인 폴리곤으로 그립니다. 이 부분은 현재 작업중입니다.

Lots of advancements happening in 3D space particularly with X3D Integration with HTML5

또 렌더링된 도형을 보는 데 이용할 수 있는 멋진 오픈소스 X3D 뷰어가 있습니다. 맥, 리눅스, 윈도우 용 Free Wrl 바이너리를 http://freewrl.sourceforge.net/ 에서 다운로드할 수 있습니다. 도형을 보기 위해 패키징된 FreeWRL_Launcher를 이용하십시오.

Also check out PostGIS minimalist X3D viewer that utilizes this function and x3dDom html/js open source toolkit.

2.0.0 버전부터 ISO-IEC-19776-1.2-X3DEncodings-XML을 이용할 수 있습니다.

개선 사항: 2.2.0 버전부터 지리좌표 및 축(x/y, 경도/위도) 뒤집기를 지원합니다. 자세한 내용은 옵션을 살펴보십시오.

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

Create a complete X3D document containing a cube that is viewable in FreeWRL and other X3D viewers.

Code
SELECT '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE X3D PUBLIC "ISO//Web3D//DTD X3D 3.0//EN" "http://www.web3d.org/specifications/x3d-3.0.dtd">
<X3D>
  <Scene>
    <Transform>
      <Shape>
       <Appearance>
            <Material emissiveColor=''0 0 1''/>
       </Appearance
> ' ||
       ST_AsX3D(ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)),
((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)),
((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)),
((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )')) ||
      '</Shape>
    </Transform>
  </Scene>
</X3D
>' As x3ddoc;
래스터 출력
    x3ddoc
    --------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE X3D PUBLIC "ISO//Web3D//DTD X3D 3.0//EN" "http://www.web3d.org/specifications/x3d-3.0.dtd">
<X3D>
  <Scene>
    <Transform>
      <Shape>
       <Appearance>
            <Material emissiveColor='0 0 1'/>
       </Appearance>
       <IndexedFaceSet  coordIndex='0 1 2 3 -1 4 5 6 7 -1 8 9 10 11 -1 12 13 14 15 -1 16 17 18 19 -1 20 21 22 23'>
            <Coordinate point='0 0 0 0 0 1 0 1 1 0 1 0 0 0 0 0 1 0 1 1 0 1 0 0 0 0 0 1 0 0 1 0 1 0 0 1 1 1 0 1 1 1 1 0 1 1 0 0 0 1 0 0 1 1 1 1 1 1 1 0 0 0 1 1 0 1 1 1 1 0 1 1' />
      </IndexedFaceSet>
      </Shape>
    </Transform>
  </Scene>
</X3D>

PostGIS buildings.

Copy and paste the output of this query to x3d scene viewer and click Show

Code
SELECT string_agg('<Shape
>' || ST_AsX3D(CG_Extrude(geom, 0,0, i*0.5)) ||
    '<Appearance>
          <Material diffuseColor="' || (0.01*i)::text || ' 0.8 0.2" specularColor="' || (0.05*i)::text || ' 0 0.5"/>
        </Appearance>
    </Shape
>', '')
FROM ST_Subdivide(ST_Letters('PostGIS'),20) WITH ORDINALITY AS f(geom,i);

The following preview shows the extruded geometry generated from a simplified version of the same source lettering. It is a geometry preview, not X3D markup; use the preceding ST_AsX3D query output in an X3D viewer to inspect the native X3D scene.

Code
SELECT
    CG_Extrude(
        ST_SimplifyPreserveTopology(ST_Letters('PostGIS'), 2),
        0, 0, 10
    ) AS buildings;
래스터 출력
GEOMETRYCOLLECTION Z (POLYHEDRALSURFACE Z (((42.6 39.2 0,36.3 24.5 0,17 20.3 0,17.9 0 0,0 0 0,0 73.8 0,27.3 73.6 0,36.3 70 0,41.8 61.6 0,42.6 39.2 0),(26.5 55.7 0,17 58.8 0,17 35.3 0,25.6 36.2 0,26.5 55.7 0)),((42.6 39.2 10,41.8 61.6 10,36.3 70 10,27.3 73.6 10,0 73.8 10,0 0 10,17.9 0 10,17 20.3 10,36.3 24.5 10,42.6 39.2 10),(26.5 55.7 10,25.6 36.2 10,17 35.3 10,17 58.8 10,26.5 55.7 10)),((42.6 39.2 0,42.6 39.2 10,36.3 24.5 10,36.3 24.5 0,42.6 39.2 0)),((36.3 24.5 0,36.3 24.5 10,17 20.3 10,17 20.3 0,36.3 24.5 0)),((17 20.3 0,17 20.3 10,17.9 0 10,17.9 0 0,17 20.3 0)),((17.9 0 0,17.9 0 10,0 0 10,0 0 0,17.9 0 0)),((0 0 0,0 0 10,0 73.8 10,0 73.8 0,0 0 0)),((0 73.8 0,0 73.8 10,27.3 73.6 10,27.3 73.6 0,0 73.8 0)),((27.3 73.6 0,27.3 73.6 10,36.3 70 10,36.3 70 0,27.3 73.6 0)),((36.3 70 0,36.3 70 10,41.8 61.6 10,41.8 61.6 0,36.3 70 0)),((41.8 61.6 0,41.8 61.6 10,42.6 39.2 10,42.6 39.2 0,41.8 61.6 0)),((26.5 55.7 0,26.5 55.7 10,17 58.8 10,17 58.8 0,26.5 55.7 0)),((17 58.8 0,17 58.8 10,17 35.3 10,17 35.3 0,17 58.8 0)),((17 35.3 0,17 35.3 10,25.6 36.2 10,25.6 36.2 0,17 35.3 0)),((25.6 36.2 0,25.6 36.2 10,26.5 55.7 10,26.5 55.7 0,25.6 36.2 0))),POLYHEDRALSURFACE Z (((69.01 58 0,84.51 52.5 0,89.71 39.9 0,87.81 9.7 0,81.71 2.9 0,71.31 -0.5 0,54.91 3.9 0,48.31 17.8 0,50.61 48.7 0,58.01 55.6 0,69.01 58 0),(73.91 38.9 0,69.11 42.6 0,64.21 38.9 0,64.21 18.9 0,68.91 15.2 0,73.91 18.9 0,73.91 38.9 0)),((69.01 58 10,58.01 55.6 10,50.61 48.7 10,48.31 17.8 10,54.91 3.9 10,71.31 -0.5 10,81.71 2.9 10,87.81 9.7 10,89.71 39.9 10,84.51 52.5 10,69.01 58 10),(73.91 38.9 10,73.91 18.9 10,68.91 15.2 10,64.21 18.9 10,64.21 38.9 10,69.11 42.6 10,73.91 38.9 10)),((69.01 58 0,69.01 58 10,84.51 52.5 10,84.51 52.5 0,69.01 58 0)),((84.51 52.5 0,84.51 52.5 10,89.71 39.9 10,89.71 39.9 0,84.51 52.5 0)),((89.71 39.9 0,89.71 39.9 10,87.81 9.7 10,87.81 9.7 0,89.71 39.9 0)),((87.81 9.7 0,87.81 9.7 10,81.71 2.9 10,81.71 2.9 0,87.81 9.7 0)),((81.71 2.9 0,81.71 2.9 10,71.31 -0.5 10,71.31 -0.5 0,81.71 2.9 0)),((71.31 -0.5 0,71.31 -0.5 10,54.91 3.9 10,54.91 3.9 0,71.31 -0.5 0)),((54.91 3.9 0,54.91 3.9 10,48.31 17.8 10,48.31 17.8 0,54.91 3.9 0)),((48.31 17.8 0,48.31 17.8 10,50.61 48.7 10,50.61 48.7 0,48.31 17.8 0)),((50.61 48.7 0,50.61 48.7 10,58.01 55.6 10,58.01 55.6 0,50.61 48.7 0)),((58.01 55.6 0,58.01 55.6 10,69.01 58 10,69.01 58 0,58.01 55.6 0)),((73.91 38.9 0,73.91 38.9 10,69.11 42.6 10,69.11 42.6 0,73.91 38.9 0)),((69.11 42.6 0,69.11 42.6 10,64.21 38.9 10,64.21 38.9 0,69.11 42.6 0)),((64.21 38.9 0,64.21 38.9 10,64.21 18.9 10,64.21 18.9 0,64.21 38.9 0)),((64.21 18.9 0,64.21 18.9 10,68.91 15.2 10,68.91 15.2 0,64.21 18.9 0)),((68.91 15.2 0,68.91 15.2 10,73.91 18.9 10,73.91 18.9 0,68.91 15.2 0)),((73.91 18.9 0,73.91 18.9 10,73.91 38.9 10,73.91 38.9 0,73.91 18.9 0))),POLYHEDRALSURFACE Z (((111.02 37.6 0,123.92 31.1 0,130.72 20.8 0,126.82 5.3 0,116.02 -0.3 0,94.02 3.7 0,98.82 18.9 0,112.52 15.3 0,115.02 17.6 0,98.72 29.6 0,96.12 45.4 0,100.52 53 0,107.32 57.1 0,128.92 54.7 0,122.72 39.9 0,112.02 42.1 0,111.02 37.6 0)),((111.02 37.6 10,112.02 42.1 10,122.72 39.9 10,128.92 54.7 10,107.32 57.1 10,100.52 53 10,96.12 45.4 10,98.72 29.6 10,115.02 17.6 10,112.52 15.3 10,98.82 18.9 10,94.02 3.7 10,116.02 -0.3 10,126.82 5.3 10,130.72 20.8 10,123.92 31.1 10,111.02 37.6 10)),((111.02 37.6 0,111.02 37.6 10,123.92 31.1 10,123.92 31.1 0,111.02 37.6 0)),((123.92 31.1 0,123.92 31.1 10,130.72 20.8 10,130.72 20.8 0,123.92 31.1 0)),((130.72 20.8 0,130.72 20.8 10,126.82 5.3 10,126.82 5.3 0,130.72 20.8 0)),((126.82 5.3 0,126.82 5.3 10,116.02 -0.3 10,116.02 -0.3 0,126.82 5.3 0)),((116.02 -0.3 0,116.02 -0.3 10,94.02 3.7 10,94.02 3.7 0,116.02 -0.3 0)),((94.02 3.7 0,94.02 3.7 10,98.82 18.9 10,98.82 18.9 0,94.02 3.7 0)),((98.82 18.9 0,98.82 18.9 10,112.52 15.3 10,112.52 15.3 0,98.82 18.9 0)),((112.52 15.3 0,112.52 15.3 10,115.02 17.6 10,115.02 17.6 0,112.52 15.3 0)),((115.02 17.6 0,115.02 17.6 10,98.72 29.6 10,98.72 29.6 0,115.02 17.6 0)),((98.72 29.6 0,98.72 29.6 10,96.12 45.4 10,96.12 45.4 0,98.72 29.6 0)),((96.12 45.4 0,96.12 45.4 10,100.52 53 10,100.52 53 0,96.12 45.4 0)),((100.52 53 0,100.52 53 10,107.32 57.1 10,107.32 57.1 0,100.52 53 0)),((107.32 57.1 0,107.32 57.1 10,128.92 54.7 10,128.92 54.7 0,107.32 57.1 0)),((128.92 54.7 0,128.92 54.7 10,122.72 39.9 10,122.72 39.9 0,128.92 54.7 0)),((122.72 39.9 0,122.72 39.9 10,112.02 42.1 10,112.02 42.1 0,122.72 39.9 0)),((112.02 42.1 0,112.02 42.1 10,111.02 37.6 10,111.02 37.6 0,112.02 42.1 0))),POLYHEDRALSURFACE Z (((156.82 17.7 0,167.02 16 0,167.02 -0.9 0,149.22 2 0,141.42 11.3 0,141.12 42.7 0,134.62 41.8 0,134.62 58.9 0,141.12 57.9 0,140.02 75.4 0,157.92 75.4 0,156.82 57.9 0,166.02 58.9 0,166.02 41.8 0,156.82 42.7 0,156.82 17.7 0)),((156.82 17.7 10,156.82 42.7 10,166.02 41.8 10,166.02 58.9 10,156.82 57.9 10,157.92 75.4 10,140.02 75.4 10,141.12 57.9 10,134.62 58.9 10,134.62 41.8 10,141.12 42.7 10,141.42 11.3 10,149.22 2 10,167.02 -0.9 10,167.02 16 10,156.82 17.7 10)),((156.82 17.7 0,156.82 17.7 10,167.02 16 10,167.02 16 0,156.82 17.7 0)),((167.02 16 0,167.02 16 10,167.02 -0.9 10,167.02 -0.9 0,167.02 16 0)),((167.02 -0.9 0,167.02 -0.9 10,149.22 2 10,149.22 2 0,167.02 -0.9 0)),((149.22 2 0,149.22 2 10,141.42 11.3 10,141.42 11.3 0,149.22 2 0)),((141.42 11.3 0,141.42 11.3 10,141.12 42.7 10,141.12 42.7 0,141.42 11.3 0)),((141.12 42.7 0,141.12 42.7 10,134.62 41.8 10,134.62 41.8 0,141.12 42.7 0)),((134.62 41.8 0,134.62 41.8 10,134.62 58.9 10,134.62 58.9 0,134.62 41.8 0)),((134.62 58.9 0,134.62 58.9 10,141.12 57.9 10,141.12 57.9 0,134.62 58.9 0)),((141.12 57.9 0,141.12 57.9 10,140.02 75.4 10,140.02 75.4 0,141.12 57.9 0)),((140.02 75.4 0,140.02 75.4 10,157.92 75.4 10,157.92 75.4 0,140.02 75.4 0)),((157.92 75.4 0,157.92 75.4 10,156.82 57.9 10,156.82 57.9 0,157.92 75.4 0)),((156.82 57.9 0,156.82 57.9 10,166.02 58.9 10,166.02 58.9 0,156.82 57.9 0)),((166.02 58.9 0,166.02 58.9 10,166.02 41.8 10,166.02 41.8 0,166.02 58.9 0)),((166.02 41.8 0,166.02 41.8 10,156.82 42.7 10,156.82 42.7 0,166.02 41.8 0)),((156.82 42.7 0,156.82 42.7 10,156.82 17.7 10,156.82 17.7 0,156.82 42.7 0))),POLYHEDRALSURFACE Z (((213.81 13.2 0,208.11 4.2 0,198.51 -0.3 0,184.21 0.9 0,174.91 8.8 0,172.61 57.4 0,175.21 66.1 0,180.91 71.6 0,209.81 74 0,209.81 58.4 0,189.11 56.8 0,188.61 18.7 0,193.81 14.8 0,199.11 16.5 0,199.11 32.2 0,193.41 32.2 0,193.41 46.4 0,213.81 46.4 0,213.81 13.2 0)),((213.81 13.2 10,213.81 46.4 10,193.41 46.4 10,193.41 32.2 10,199.11 32.2 10,199.11 16.5 10,193.81 14.8 10,188.61 18.7 10,189.11 56.8 10,209.81 58.4 10,209.81 74 10,180.91 71.6 10,175.21 66.1 10,172.61 57.4 10,174.91 8.8 10,184.21 0.9 10,198.51 -0.3 10,208.11 4.2 10,213.81 13.2 10)),((213.81 13.2 0,213.81 13.2 10,208.11 4.2 10,208.11 4.2 0,213.81 13.2 0)),((208.11 4.2 0,208.11 4.2 10,198.51 -0.3 10,198.51 -0.3 0,208.11 4.2 0)),((198.51 -0.3 0,198.51 -0.3 10,184.21 0.9 10,184.21 0.9 0,198.51 -0.3 0)),((184.21 0.9 0,184.21 0.9 10,174.91 8.8 10,174.91 8.8 0,184.21 0.9 0)),((174.91 8.8 0,174.91 8.8 10,172.61 57.4 10,172.61 57.4 0,174.91 8.8 0)),((172.61 57.4 0,172.61 57.4 10,175.21 66.1 10,175.21 66.1 0,172.61 57.4 0)),((175.21 66.1 0,175.21 66.1 10,180.91 71.6 10,180.91 71.6 0,175.21 66.1 0)),((180.91 71.6 0,180.91 71.6 10,209.81 74 10,209.81 74 0,180.91 71.6 0)),((209.81 74 0,209.81 74 10,209.81 58.4 10,209.81 58.4 0,209.81 74 0)),((209.81 58.4 0,209.81 58.4 10,189.11 56.8 10,189.11 56.8 0,209.81 58.4 0)),((189.11 56.8 0,189.11 56.8 10,188.61 18.7 10,188.61 18.7 0,189.11 56.8 0)),((188.61 18.7 0,188.61 18.7 10,193.81 14.8 10,193.81 14.8 0,188.61 18.7 0)),((193.81 14.8 0,193.81 14.8 10,199.11 16.5 10,199.11 16.5 0,193.81 14.8 0)),((199.11 16.5 0,199.11 16.5 10,199.11 32.2 10,199.11 32.2 0,199.11 16.5 0)),((199.11 32.2 0,199.11 32.2 10,193.41 32.2 10,193.41 32.2 0,199.11 32.2 0)),((193.41 32.2 0,193.41 32.2 10,193.41 46.4 10,193.41 46.4 0,193.41 32.2 0)),((193.41 46.4 0,193.41 46.4 10,213.81 46.4 10,213.81 46.4 0,193.41 46.4 0)),((213.81 46.4 0,213.81 46.4 10,213.81 13.2 10,213.81 13.2 0,213.81 46.4 0))),POLYHEDRALSURFACE Z (((235.82 72.9 0,236.82 0 0,218.52 0 0,218.52 73.8 0,235.82 72.9 0)),((235.82 72.9 10,218.52 73.8 10,218.52 0 10,236.82 0 10,235.82 72.9 10)),((235.82 72.9 0,235.82 72.9 10,236.82 0 10,236.82 0 0,235.82 72.9 0)),((236.82 0 0,236.82 0 10,218.52 0 10,218.52 0 0,236.82 0 0)),((218.52 0 0,218.52 0 10,218.52 73.8 10,218.52 73.8 0,218.52 0 0)),((218.52 73.8 0,218.52 73.8 10,235.82 72.9 10,235.82 72.9 0,218.52 73.8 0))),POLYHEDRALSURFACE Z (((258.33 49.5 0,279.93 34.6 0,283.43 25.9 0,282.53 15.4 0,277.93 6.8 0,270.73 1.6 0,252.33 0.5 0,241.53 4.9 0,246.43 20.6 0,260.73 16.4 0,266.23 18.7 0,267.43 23.2 0,245.63 39.4 0,242.03 48.6 0,242.83 59.6 0,247.53 67.3 0,257.53 73.2 0,280.43 70.8 0,275.23 56.4 0,264.53 58.3 0,258.73 55.1 0,258.33 49.5 0)),((258.33 49.5 10,258.73 55.1 10,264.53 58.3 10,275.23 56.4 10,280.43 70.8 10,257.53 73.2 10,247.53 67.3 10,242.83 59.6 10,242.03 48.6 10,245.63 39.4 10,267.43 23.2 10,266.23 18.7 10,260.73 16.4 10,246.43 20.6 10,241.53 4.9 10,252.33 0.5 10,270.73 1.6 10,277.93 6.8 10,282.53 15.4 10,283.43 25.9 10,279.93 34.6 10,258.33 49.5 10)),((258.33 49.5 0,258.33 49.5 10,279.93 34.6 10,279.93 34.6 0,258.33 49.5 0)),((279.93 34.6 0,279.93 34.6 10,283.43 25.9 10,283.43 25.9 0,279.93 34.6 0)),((283.43 25.9 0,283.43 25.9 10,282.53 15.4 10,282.53 15.4 0,283.43 25.9 0)),((282.53 15.4 0,282.53 15.4 10,277.93 6.8 10,277.93 6.8 0,282.53 15.4 0)),((277.93 6.8 0,277.93 6.8 10,270.73 1.6 10,270.73 1.6 0,277.93 6.8 0)),((270.73 1.6 0,270.73 1.6 10,252.33 0.5 10,252.33 0.5 0,270.73 1.6 0)),((252.33 0.5 0,252.33 0.5 10,241.53 4.9 10,241.53 4.9 0,252.33 0.5 0)),((241.53 4.9 0,241.53 4.9 10,246.43 20.6 10,246.43 20.6 0,241.53 4.9 0)),((246.43 20.6 0,246.43 20.6 10,260.73 16.4 10,260.73 16.4 0,246.43 20.6 0)),((260.73 16.4 0,260.73 16.4 10,266.23 18.7 10,266.23 18.7 0,260.73 16.4 0)),((266.23 18.7 0,266.23 18.7 10,267.43 23.2 10,267.43 23.2 0,266.23 18.7 0)),((267.43 23.2 0,267.43 23.2 10,245.63 39.4 10,245.63 39.4 0,267.43 23.2 0)),((245.63 39.4 0,245.63 39.4 10,242.03 48.6 10,242.03 48.6 0,245.63 39.4 0)),((242.03 48.6 0,242.03 48.6 10,242.83 59.6 10,242.83 59.6 0,242.03 48.6 0)),((242.83 59.6 0,242.83 59.6 10,247.53 67.3 10,247.53 67.3 0,242.83 59.6 0)),((247.53 67.3 0,247.53 67.3 10,257.53 73.2 10,257.53 73.2 0,247.53 67.3 0)),((257.53 73.2 0,257.53 73.2 10,280.43 70.8 10,280.43 70.8 0,257.53 73.2 0)),((280.43 70.8 0,280.43 70.8 10,275.23 56.4 10,275.23 56.4 0,280.43 70.8 0)),((275.23 56.4 0,275.23 56.4 10,264.53 58.3 10,264.53 58.3 0,275.23 56.4 0)),((264.53 58.3 0,264.53 58.3 10,258.73 55.1 10,258.73 55.1 0,264.53 58.3 0)),((258.73 55.1 0,258.73 55.1 10,258.33 49.5 10,258.33 49.5 0,258.73 55.1 0))))
Figure
Geometry figure for visual-st-asx3d-02

An Octagon elevated 3 Units and decimal precision of 6.

Code
SELECT ST_AsX3D(ST_Translate(ST_Force3D(ST_Buffer(ST_Point(10,10),5, 'quad_segs=2')), 0,0,
    3),
  6) As x3dfrag;
래스터 출력
x3dfrag
--------
<IndexedFaceSet  convex='false' coordIndex='0 1 2 3 4 5 6 7'
><Coordinate point='15 10 3 13.535534 6.464466 3 10 5 3 6.464466 6.464466 3 5 10 3 6.464466 13.535534 3 10 15 3 13.535534 13.535534 3 ' /></IndexedFaceSet>

TIN.

Code
SELECT ST_AsX3D(ST_GeomFromEWKT('TIN (((
                0 0 0,
                0 0 1,
                0 1 0,
                0 0 0
            )), ((
                0 0 0,
                0 1 0,
                1 1 0,
                0 0 0
            ))
            )')) As x3dfrag;
래스터 출력
    x3dfrag
    --------
<IndexedTriangleSet  index='0 1 2 3 4 5'
><Coordinate point='0 0 0 0 0 1 0 1 0 0 0 0 0 1 0 1 1 0'/></IndexedTriangleSet>

Closed multilinestring (the boundary of a polygon with holes).

Code
SELECT ST_AsX3D(ST_GeomFromEWKT('MULTILINESTRING((20 0 10,16 -12 10,0 -16 10,-12 -12 10,-20 0 10,-12 16 10,0 24 10,16 16 10,20 0 10),
  (12 0 10,8 8 10,0 12 10,-8 8 10,-8 0 10,-8 -4 10,0 -8 10,8 -4 10,12 0 10))')
) As x3dfrag;
래스터 출력
    x3dfrag
    --------
<IndexedLineSet  coordIndex='0 1 2 3 4 5 6 7 0 -1 8 9 10 11 12 13 14 15 8'>
    <Coordinate point='20 0 10 16 -12 10 0 -16 10 -12 -12 10 -20 0 10 -12 16 10 0 24 10 16 16 10 12 0 10 8 8 10 0 12 10 -8 8 10 -8 0 10 -8 -4 10 0 -8 10 8 -4 10 ' />
 </IndexedLineSet>

제목

ST_GeoHash — 도형의 GeoHash 표현식을 반환합니다.

요약

text ST_GeoHash(geometry geom, integer maxchars=full_precision_of_point);

설명

Computes a GeoHash representation of a geometry. A GeoHash encodes a geographic Point into a text form that is sortable and searchable based on prefixing. A shorter GeoHash is a less precise representation of a point. It can be thought of as a box that contains the point.

Non-point geometry values with non-zero extent can also be mapped to GeoHash codes. The precision of the code depends on the geographic extent of the geometry.

If maxchars is not specified, the returned GeoHash code is for the smallest cell containing the input geometry. Points return a GeoHash with 20 characters of precision (about enough to hold the full double precision of the input). Other geometric types may return a GeoHash with less precision, depending on the extent of the geometry. Larger geometries are represented with less precision, smaller ones with more precision. The box determined by the GeoHash code always contains the input feature.

If maxchars is specified the returned GeoHash code has at most that many characters. It maps to a (possibly) lower precision representation of the input geometry. For non-points, the starting point of the calculation is the center of the bounding box of the geometry.

1.4.0 버전부터 사용할 수 있습니다.

[참고]

ST_GeoHash requires input geometry to be in geographic (lon/lat) coordinates.

This method supports Circular Strings and Curves.

예시

Code
SELECT ST_GeoHash(ST_Point(-126, 48));
래스터 출력
c0w3hf1s70w3hf1s70w3
Code
SELECT ST_GeoHash(ST_Point(-126, 48), 5);
래스터 출력
c0w3h

This example shows that the GeoHash for a line containing a point is a prefix of the point code.

Code
SELECT ST_GeoHash('LINESTRING(-126 48,-126.1 48.1)'::geometry);
래스터 출력
c0w3

7.10. 연산자(operator)

초록

These entries document the spatial operators defined by PostGIS. Operators complement the function catalogue by supplying concise symbolic predicates for bounding-box interactions and spatial relationships. Their semantics follow the same geometric rules as the corresponding functions but are optimised for use in SQL expressions and index-supported filtering.

7.10.1. Bounding Box Operators

  • && — A의 2D 경계 상자와 B의 2D 경계 상자가 교차하는 경우 TRUE 를 반환합니다.
  • &&(geometry,box2df) — Returns TRUE if a geometry's (cached) 2D bounding box intersects a 2D float precision bounding box (BOX2DF).
  • &&(box2df,geometry) — Returns TRUE if a 2D float precision bounding box (BOX2DF) intersects a geometry's (cached) 2D bounding box.
  • &&(box2df,box2df) — Returns TRUE if two 2D float precision bounding boxes (BOX2DF) intersect each other.
  • &&& — A의 n차원 경계 상자와 B의 n차원 경계 상자가 교차하는 경우 TRUE 를 반환합니다.
  • &&&(geometry,gidx) — Returns TRUE if a geometry's (cached) n-D bounding box intersects a n-D float precision bounding box (GIDX).
  • &&&(gidx,geometry) — Returns TRUE if a n-D float precision bounding box (GIDX) intersects a geometry's (cached) n-D bounding box.
  • &&&(gidx,gidx) — Returns TRUE if two n-D float precision bounding boxes (GIDX) intersect each other.
  • &< — A의 경계 상자가 B의 경계 상자와 겹치거나 그 왼쪽에 있을 경우 TRUE 를 반환합니다.
  • &<| — A의 경계 상자가 B의 경계 상자와 겹치거나 그 아래에 있을 경우 TRUE 를 반환합니다.
  • &> — A의 경계 상자가 B의 경계 상자와 겹치거나 그 오른쪽에 있을 경우 TRUE 를 반환합니다.
  • << — A의 경계 상자가 오로지 B의 경계 상자 왼쪽에 있을 경우에만 TRUE 를 반환합니다.
  • <<| — A의 경계 상자가 오로지 B의 경계 상자 아래에 있을 경우에만 TRUE 를 반환합니다.
  • = — Returns TRUE if the coordinates and coordinate order geometry/geography A are the same as the coordinates and coordinate order of geometry/geography B.
  • >> — A의 경계 상자가 오로지 B의 경계 상자 오른쪽에 있을 경우에만 TRUE 를 반환합니다.
  • @ — B의 경계 상자가 A의 경계 상자를 담고 있을 경우 TRUE 를 반환합니다.
  • @(geometry,box2df) — Returns TRUE if a geometry's 2D bounding box is contained into a 2D float precision bounding box (BOX2DF).
  • @(box2df,geometry) — Returns TRUE if a 2D float precision bounding box (BOX2DF) is contained into a geometry's 2D bounding box.
  • @(box2df,box2df) — Returns TRUE if a 2D float precision bounding box (BOX2DF) is contained into another 2D float precision bounding box.
  • |&> — A의 경계 상자가 B의 경계 상자와 겹치거나 그 위에 있을 경우 TRUE 를 반환합니다.
  • |>> — A의 경계 상자가 오로지 B의 경계 상자 위에 있을 경우에만 TRUE 를 반환합니다.
  • ~ — A의 경계 상자가 B의 경계 상자를 담고 있을 경우 TRUE 를 반환합니다.
  • ~(geometry,box2df) — Returns TRUE if a geometry's 2D bonding box contains a 2D float precision bounding box (GIDX).
  • ~(box2df,geometry) — Returns TRUE if a 2D float precision bounding box (BOX2DF) contains a geometry's 2D bonding box.
  • ~(box2df,box2df) — Returns TRUE if a 2D float precision bounding box (BOX2DF) contains another 2D float precision bounding box (BOX2DF).
  • ~= — A의 경계 상자와 B의 경계 상자가 동일할 경우 TRUE 를 반환합니다.

제목

&& — A의 2D 경계 상자와 B의 2D 경계 상자가 교차하는 경우 TRUE 를 반환합니다.

요약

boolean &&( geometry A , geometry B );

boolean &&( geography A , geography B );

설명

&& 연산자는 도형 A의 2D 경계 상자와 도형 B의 2D 경계 상자가 교차하는 경우 TRUE 를 반환합니다.

[참고]

이 피연산자(operand)는 도형에서 이용할 수도 있는 모든 인덱스를 활용할 것입니다.

개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다.

1.5.0 버전부터 지리형을 지원합니다.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

예시

Code
SELECT tbl1.column1, tbl2.column1, tbl1.column2 && tbl2.column2 AS overlaps
FROM ( VALUES
    (1, 'LINESTRING(0 0, 3 3)'::geometry),
    (2, 'LINESTRING(0 1, 0 5)'::geometry)) AS tbl1,
( VALUES
    (3, 'LINESTRING(1 2, 4 6)'::geometry)) AS tbl2;
래스터 출력
 column1 | column1 | overlaps
---------+---------+----------
       1 |       3 | t
       2 |       3 | f
(2 rows)
Figure
Geometry figure for visual-geometry-overlaps-01

제목

&&(geometry,box2df) — Returns TRUE if a geometry's (cached) 2D bounding box intersects a 2D float precision bounding box (BOX2DF).

요약

boolean &&( geometry A , box2df B );

설명

The && operator returns TRUE if the cached 2D bounding box of geometry A intersects the 2D bounding box B, using float precision. This means that if B is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)

[참고]

This operand is intended to be used internally by BRIN indexes, more than by users.

Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

예시

Code
SELECT ST_Point(1,1) && ST_MakeBox2D(ST_Point(0,0), ST_Point(2,2)) AS overlaps;
래스터 출력
 overlaps
----------
 t
(1 row)

제목

&&(box2df,geometry) — Returns TRUE if a 2D float precision bounding box (BOX2DF) intersects a geometry's (cached) 2D bounding box.

요약

boolean &&( box2df A , geometry B );

설명

The && operator returns TRUE if the 2D bounding box A intersects the cached 2D bounding box of geometry B, using float precision. This means that if A is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)

[참고]

This operand is intended to be used internally by BRIN indexes, more than by users.

Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

예시

Code
SELECT ST_MakeBox2D(ST_Point(0,0), ST_Point(2,2)) && ST_Point(1,1) AS overlaps;
래스터 출력
 overlaps
----------
 t
(1 row)

제목

&&(box2df,box2df) — Returns TRUE if two 2D float precision bounding boxes (BOX2DF) intersect each other.

요약

boolean &&( box2df A , box2df B );

설명

The && operator returns TRUE if two 2D bounding boxes A and B intersect each other, using float precision. This means that if A (or B) is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)

[참고]

This operator is intended to be used internally by BRIN indexes, more than by users.

Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

예시

Code
SELECT ST_MakeBox2D(ST_Point(0,0), ST_Point(2,2)) && ST_MakeBox2D(ST_Point(1,1), ST_Point(3,3)) AS overlaps;
래스터 출력
 overlaps
----------
 t
(1 row)

제목

&&& — A의 n차원 경계 상자와 B의 n차원 경계 상자가 교차하는 경우 TRUE 를 반환합니다.

요약

boolean &&&( geometry A , geometry B );

설명

&&& 연산자는 도형 A의 n차원 경계 상자와 도형 B의 n차원 경계 상자가 교차하는 경우 TRUE 를 반환합니다.

[참고]

이 피연산자(operand)는 도형에서 이용할 수도 있는 모든 인덱스를 활용할 것입니다.

2.0.0 버전부터 사용할 수 있습니다.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

This function supports 3d and will not drop the z-index.

예시

3D LineStrings.

Code
SELECT tbl1.column1, tbl2.column1, tbl1.column2 &&& tbl2.column2 AS overlaps_3d,
                        tbl1.column2 && tbl2.column2 AS overlaps_2d
FROM ( VALUES
    (1, 'LINESTRING Z(0 0 1, 3 3 2)'::geometry),
    (2, 'LINESTRING Z(1 2 0, 0 5 -1)'::geometry)) AS tbl1,
( VALUES
    (3, 'LINESTRING Z(1 2 1, 4 6 1)'::geometry)) AS tbl2;
래스터 출력
 column1 | column1 | overlaps_3d | overlaps_2d
---------+---------+-------------+-------------
       1 |       3 | t           | t
       2 |       3 | f           | t
Figure
Geometry figure for visual-geometry-overlaps-nd-01

3M LineStrings.

Code
SELECT tbl1.column1, tbl2.column1, tbl1.column2 &&& tbl2.column2 AS overlaps_3zm,
                        tbl1.column2 && tbl2.column2 AS overlaps_2d
FROM ( VALUES
    (1, 'LINESTRING M(0 0 1, 3 3 2)'::geometry),
    (2, 'LINESTRING M(1 2 0, 0 5 -1)'::geometry)) AS tbl1,
( VALUES
    (3, 'LINESTRING M(1 2 1, 4 6 1)'::geometry)) AS tbl2;
래스터 출력
 column1 | column1 | overlaps_3zm | overlaps_2d
---------+---------+-------------+-------------
       1 |       3 | t           | t
       2 |       3 | f           | t
Figure
Geometry figure for visual-geometry-overlaps-nd-02

참고

&&


제목

&&&(geometry,gidx) — Returns TRUE if a geometry's (cached) n-D bounding box intersects a n-D float precision bounding box (GIDX).

요약

boolean &&&( geometry A , gidx B );

설명

The &&& operator returns TRUE if the cached n-D bounding box of geometry A intersects the n-D bounding box B, using float precision. This means that if B is a (double precision) box3d, it will be internally converted to a float precision 3D bounding box (GIDX)

[참고]

This operator is intended to be used internally by BRIN indexes, more than by users.

Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

This function supports 3d and will not drop the z-index.

예시

Code
SELECT ST_MakePoint(1,1,1) &&& ST_3DMakeBox(ST_MakePoint(0,0,0), ST_MakePoint(2,2,2)) AS overlaps;
래스터 출력
 overlaps
----------
 t
(1 row)

제목

&&&(gidx,geometry) — Returns TRUE if a n-D float precision bounding box (GIDX) intersects a geometry's (cached) n-D bounding box.

요약

boolean &&&( gidx A , geometry B );

설명

The &&& operator returns TRUE if the n-D bounding box A intersects the cached n-D bounding box of geometry B, using float precision. This means that if A is a (double precision) box3d, it will be internally converted to a float precision 3D bounding box (GIDX)

[참고]

This operator is intended to be used internally by BRIN indexes, more than by users.

Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

This function supports 3d and will not drop the z-index.

예시

Code
SELECT ST_3DMakeBox(ST_MakePoint(0,0,0), ST_MakePoint(2,2,2)) &&& ST_MakePoint(1,1,1) AS overlaps;
래스터 출력
 overlaps
----------
 t
(1 row)

제목

&&&(gidx,gidx) — Returns TRUE if two n-D float precision bounding boxes (GIDX) intersect each other.

요약

boolean &&&( gidx A , gidx B );

설명

The &&& operator returns TRUE if two n-D bounding boxes A and B intersect each other, using float precision. This means that if A (or B) is a (double precision) box3d, it will be internally converted to a float precision 3D bounding box (GIDX)

[참고]

This operator is intended to be used internally by BRIN indexes, more than by users.

Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

This function supports 3d and will not drop the z-index.

예시

Code
SELECT ST_3DMakeBox(ST_MakePoint(0,0,0), ST_MakePoint(2,2,2)) &&& ST_3DMakeBox(ST_MakePoint(1,1,1), ST_MakePoint(3,3,3)) AS overlaps;
래스터 출력
 overlaps
----------
 t
(1 row)

제목

&< — A의 경계 상자가 B의 경계 상자와 겹치거나 그 왼쪽에 있을 경우 TRUE 를 반환합니다.

요약

boolean &<( geometry A , geometry B );

설명

&< 연산자는 도형 A의 경계 상자가 도형 B의 경계 상자와 겹치거나 그 왼쪽에 있을 경우, 또는 더 정확히 말하자면 도형 B의 경계 상자와 겹치거나 그 오른쪽에 있지 않을 경우, TRUE 를 반환합니다.

[참고]

이 피연산자(operand)는 도형에서 이용할 수도 있는 모든 인덱스를 활용할 것입니다.

예시

Code
SELECT tbl1.column1, tbl2.column1, tbl1.column2 &< tbl2.column2 AS overleft
FROM
  ( VALUES
    (1, 'LINESTRING(1 2, 4 6)'::geometry)) AS tbl1,
  ( VALUES
    (2, 'LINESTRING(0 0, 3 3)'::geometry),
    (3, 'LINESTRING(0 1, 0 5)'::geometry),
    (4, 'LINESTRING(6 0, 6 1)'::geometry)) AS tbl2;
래스터 출력
 column1 | column1 | overleft
---------+---------+----------
       1 |       2 | f
       1 |       3 | f
       1 |       4 | t
(3 rows)
Figure
Geometry figure for visual-st-geometry-overleft-01

참고

&&, |&>, &>, &<|


제목

&<| — A의 경계 상자가 B의 경계 상자와 겹치거나 그 아래에 있을 경우 TRUE 를 반환합니다.

요약

boolean &<|( geometry A , geometry B );

설명

&<| 연산자는 도형 A의 경계 상자가 도형 B의 경계 상자와 겹치거나 그 아래에 있을 경우, 또는 더 정확히 말하자면 도형 B의 경계 상자와 겹치거나 위에 있지 않을 경우, TRUE 를 반환합니다.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

[참고]

이 피연산자(operand)는 도형에서 이용할 수도 있는 모든 인덱스를 활용할 것입니다.

예시

Code
SELECT tbl1.column1, tbl2.column1, tbl1.column2 &<| tbl2.column2 AS overbelow
FROM
  ( VALUES
    (1, 'LINESTRING(6 0, 6 4)'::geometry)) AS tbl1,
  ( VALUES
    (2, 'LINESTRING(0 0, 3 3)'::geometry),
    (3, 'LINESTRING(0 1, 0 5)'::geometry),
    (4, 'LINESTRING(1 2, 4 6)'::geometry)) AS tbl2;
래스터 출력
 column1 | column1 | overbelow
---------+---------+-----------
       1 |       2 | f
       1 |       3 | t
       1 |       4 | t
(3 rows)
Figure
Geometry figure for visual-st-geometry-overbelow-01

참고

&&, |&>, &>, &<


제목

&> — A의 경계 상자가 B의 경계 상자와 겹치거나 그 오른쪽에 있을 경우 TRUE 를 반환합니다.

요약

boolean &>( geometry A , geometry B );

설명

&> 연산자는 도형 A의 경계 상자가 도형 B의 경계 상자와 겹치거나 그 오른쪽에 있을 경우, 또는 더 정확히 말하자면 도형 B의 경계 상자와 겹치거나 그 왼쪽에 있지 않을 경우, TRUE 를 반환합니다.

[참고]

이 피연산자(operand)는 도형에서 이용할 수도 있는 모든 인덱스를 활용할 것입니다.

예시

Code
SELECT tbl1.column1, tbl2.column1, tbl1.column2 &
> tbl2.column2 AS overright
FROM
  ( VALUES
    (1, 'LINESTRING(1 2,4 6)'::geometry)) AS tbl1,
  ( VALUES
    (2, 'LINESTRING(0 0,3 3)'::geometry),
    (3, 'LINESTRING(0 1,0 5)'::geometry),
    (4, 'LINESTRING(6 0,6 1)'::geometry)) AS tbl2;
래스터 출력
 column1 | column1 | overright
---------+---------+-----------
       1 |       2 | t
       1 |       3 | t
       1 |       4 | f
(3 rows)
Figure
Geometry figure for visual-st-geometry-overright-01

참고

&&, |&>, &<|, &<


제목

<< — A의 경계 상자가 오로지 B의 경계 상자 왼쪽에 있을 경우에만 TRUE 를 반환합니다.

요약

boolean <<( geometry A , geometry B );

설명

<< 연산자는 도형 A의 경계 상자가 오로지 도형 B의 경계 상자 왼쪽에 있을 경우에만 TRUE 를 반환합니다.

[참고]

이 피연산자(operand)는 도형에서 이용할 수도 있는 모든 인덱스를 활용할 것입니다.

예시

Code
SELECT tbl1.column1, tbl2.column1, tbl1.column2 << tbl2.column2 AS left
FROM
  ( VALUES
    (1, 'LINESTRING (1 2, 1 5)'::geometry)) AS tbl1,
  ( VALUES
    (2, 'LINESTRING (0 0, 4 3)'::geometry),
    (3, 'LINESTRING (6 0, 6 5)'::geometry),
    (4, 'LINESTRING (2 2, 5 6)'::geometry)) AS tbl2;
래스터 출력
 column1 | column1 | left
---------+---------+------
       1 |       2 | f
       1 |       3 | t
       1 |       4 | t
(3 rows)
Figure
Geometry figure for visual-st-geometry-left-01

참고

>>, |>>, <<|


제목

<<| — A의 경계 상자가 오로지 B의 경계 상자 아래에 있을 경우에만 TRUE 를 반환합니다.

요약

boolean <<|( geometry A , geometry B );

설명

<<| 연산자는 도형 A의 경계 상자가 오로지 도형 B의 경계 상자 아래에 있을 경우에만 TRUE 를 반환합니다.

[참고]

이 피연산자(operand)는 도형에서 이용할 수도 있는 모든 인덱스를 활용할 것입니다.

예시

Code
SELECT tbl1.column1, tbl2.column1, tbl1.column2 <<| tbl2.column2 AS below
FROM
  ( VALUES
    (1, 'LINESTRING (0 0, 4 3)'::geometry)) AS tbl1,
  ( VALUES
    (2, 'LINESTRING (1 4, 1 7)'::geometry),
    (3, 'LINESTRING (6 1, 6 5)'::geometry),
    (4, 'LINESTRING (2 3, 5 6)'::geometry)) AS tbl2;
래스터 출력
 column1 | column1 | below
---------+---------+-------
       1 |       2 | t
       1 |       3 | f
       1 |       4 | f
(3 rows)
Figure
Geometry figure for visual-st-geometry-below-01

참고

<<, >>, |>>


제목

= — Returns TRUE if the coordinates and coordinate order geometry/geography A are the same as the coordinates and coordinate order of geometry/geography B.

요약

boolean =( geometry A , geometry B );

boolean =( geography A , geography B );

설명

The = operator returns TRUE if the coordinates and coordinate order geometry/geography A are the same as the coordinates and coordinate order of geometry/geography B. PostgreSQL uses the =, <, and > operators defined for geometries to perform internal orderings and comparison of geometries (ie. in a GROUP BY or ORDER BY clause).

[참고]

Only geometry/geography that are exactly equal in all respects, with the same coordinates, in the same order, are considered equal by this operator. For "spatial equality", that ignores things like coordinate order, and can detect features that cover the same spatial area with different representations, use ST_OrderingEquals or ST_Equals

[경고]

This operand will NOT make use of any indexes that may be available on the geometries. For an index assisted exact equality test, combine = with &&.

Changed: 2.4.0, in prior versions this was bounding box equality not a geometric equality. If you need bounding box equality, use ~= instead.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

예시

Code
SELECT 'LINESTRING(0 0,0 1,1 0)'::geometry = 'LINESTRING(1 1,0 0)'::geometry;
래스터 출력
 ?column?
----------
 f
(1 row)
Figure
Geometry figure for visual-st-geometry-eq-01
Code
SELECT column1
FROM ( VALUES
    ('LINESTRING(0 0, 1 1)'::geometry),
    ('LINESTRING(1 1, 0 0)'::geometry)) AS foo;
래스터 출력
          st_astext
---------------------
 LINESTRING(0 0,1 1)
 LINESTRING(1 1,0 0)
(2 rows)
Figure
Geometry figure for visual-st-geometry-eq-02

Note: the GROUP BY uses the "=" to compare for geometry equivalency.

Code
SELECT column1
FROM ( VALUES
    ('LINESTRING(0 0, 1 1)'::geometry),
    ('LINESTRING(1 1, 0 0)'::geometry)) AS foo
GROUP BY column1;
래스터 출력
      st_astext
---------------------
 LINESTRING(0 0,1 1)
 LINESTRING(1 1,0 0)
(2 rows)
Figure
Geometry figure for visual-st-geometry-eq-03

In versions prior to 2.0, this used to return true.

Code
SELECT 'POINT(1707296.37 4820536.77)'::geometry =
   'POINT(1707296.27 4820536.87)'::geometry As pt_intersect;
래스터 출력
 pt_intersect
--------------
 f
(1 row)

제목

>> — A의 경계 상자가 오로지 B의 경계 상자 오른쪽에 있을 경우에만 TRUE 를 반환합니다.

요약

boolean >>( geometry A , geometry B );

설명

>> 연산자는 도형 A의 경계 상자가 오로지 도형 B의 경계 상자 오른쪽에 있을 경우에만 TRUE 를 반환합니다.

[참고]

이 피연산자(operand)는 도형에서 이용할 수도 있는 모든 인덱스를 활용할 것입니다.

예시

Code
SELECT tbl1.column1, tbl2.column1, tbl1.column2 
>
> tbl2.column2 AS right
FROM
  ( VALUES
    (1, 'LINESTRING (2 3,5 6)'::geometry)) AS tbl1,
  ( VALUES
    (2, 'LINESTRING (1 4,1 7)'::geometry),
    (3, 'LINESTRING (6 1,6 5)'::geometry),
    (4, 'LINESTRING (0 0,4 3)'::geometry)) AS tbl2;
래스터 출력
 column1 | column1 | right
---------+---------+-------
       1 |       2 | t
       1 |       3 | f
       1 |       4 | f
(3 rows)
Figure
Geometry figure for visual-st-geometry-right-01

참고

<<, |>>, <<|


제목

@ — B의 경계 상자가 A의 경계 상자를 담고 있을 경우 TRUE 를 반환합니다.

요약

boolean @( geometry A , geometry B );

설명

@ 연산자는 도형 B의 경계 상자가 도형 A의 경계 상자를 완전히 담고 있을 경우 TRUE 를 반환합니다.

[참고]

이 피연산자(operand)는 도형에서 이용할 수도 있는 모든 인덱스를 활용할 것입니다.

예시

Code
SELECT tbl1.column1, tbl2.column1, tbl1.column2 @ tbl2.column2 AS contained
FROM
  ( VALUES
    (1, 'LINESTRING (1 1, 3 3)'::geometry)) AS tbl1,
  ( VALUES
    (2, 'LINESTRING (0 0, 4 4)'::geometry),
    (3, 'LINESTRING (2 2, 4 4)'::geometry),
    (4, 'LINESTRING (1 1, 3 3)'::geometry)) AS tbl2;
래스터 출력
 column1 | column1 | contained
---------+---------+-----------
       1 |       2 | t
       1 |       3 | f
       1 |       4 | t
(3 rows)
Figure
Geometry figure for visual-st-geometry-contained-01

참고

~, &&


제목

@(geometry,box2df) — Returns TRUE if a geometry's 2D bounding box is contained into a 2D float precision bounding box (BOX2DF).

요약

boolean @( geometry A , box2df B );

설명

The @ operator returns TRUE if the A geometry's 2D bounding box is contained the 2D bounding box B, using float precision. This means that if B is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)

[참고]

This operand is intended to be used internally by BRIN indexes, more than by users.

Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

예시

Code
SELECT ST_Buffer('POINT(2 2)'::geometry, 1) @ ST_MakeBox2D(ST_Point(0, 0), ST_Point(5, 5)) AS is_contained;
래스터 출력
t

제목

@(box2df,geometry) — Returns TRUE if a 2D float precision bounding box (BOX2DF) is contained into a geometry's 2D bounding box.

요약

boolean @( box2df A , geometry B );

설명

The @ operator returns TRUE if the 2D bounding box A is contained into the B geometry's 2D bounding box, using float precision. This means that if B is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)

[참고]

This operand is intended to be used internally by BRIN indexes, more than by users.

Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

예시

Code
SELECT ST_MakeBox2D(ST_Point(2, 2), ST_Point(3, 3)) @ ST_Buffer('POINT(1 1)'::geometry, 10) AS is_contained;
래스터 출력
t

제목

@(box2df,box2df) — Returns TRUE if a 2D float precision bounding box (BOX2DF) is contained into another 2D float precision bounding box.

요약

boolean @( box2df A , box2df B );

설명

The @ operator returns TRUE if the 2D bounding box A is contained into the 2D bounding box B, using float precision. This means that if A (or B) is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)

[참고]

This operand is intended to be used internally by BRIN indexes, more than by users.

Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

예시

Code
SELECT ST_MakeBox2D(ST_Point(2, 2), ST_Point(3, 3)) @ ST_MakeBox2D(ST_Point(0, 0), ST_Point(5, 5)) AS is_contained;
래스터 출력
t

제목

|&> — A의 경계 상자가 B의 경계 상자와 겹치거나 그 위에 있을 경우 TRUE 를 반환합니다.

요약

boolean |&>( geometry A , geometry B );

설명

|&> 연산자는 도형 A의 경계 상자가 도형 B의 경계 상자와 겹치거나 그 위에 있을 경우, 또는 더 정확히 말하자면 도형 B의 경계 상자와 겹치거나 아래에 있지 않을 경우, TRUE 를 반환합니다.

[참고]

이 피연산자(operand)는 도형에서 이용할 수도 있는 모든 인덱스를 활용할 것입니다.

예시

Code
SELECT tbl1.column1, tbl2.column1, tbl1.column2 |&
> tbl2.column2 AS overabove
FROM
  ( VALUES
    (1, 'LINESTRING(6 0,6 4)'::geometry)) AS tbl1,
  ( VALUES
    (2, 'LINESTRING(0 0,3 3)'::geometry),
    (3, 'LINESTRING(0 1,0 5)'::geometry),
    (4, 'LINESTRING(1 2,4 6)'::geometry)) AS tbl2;
래스터 출력
 column1 | column1 | overabove
---------+---------+-----------
       1 |       2 | t
       1 |       3 | f
       1 |       4 | f
(3 rows)
Figure
Geometry figure for visual-st-geometry-overabove-01

참고

&&, &>, &<|, &<


제목

|>> — A의 경계 상자가 오로지 B의 경계 상자 위에 있을 경우에만 TRUE 를 반환합니다.

요약

boolean |>>( geometry A , geometry B );

설명

The |>> operator returns TRUE if the bounding box of geometry A is strictly above the bounding box of geometry B.

[참고]

이 피연산자(operand)는 도형에서 이용할 수도 있는 모든 인덱스를 활용할 것입니다.

예시

Code
SELECT tbl1.column1, tbl2.column1, tbl1.column2 |>> tbl2.column2 AS above
FROM
  ( VALUES
    (1, 'LINESTRING (1 4,1 7)'::geometry)) AS tbl1,
  ( VALUES
    (2, 'LINESTRING (0 0,4 2)'::geometry),
    (3, 'LINESTRING (6 1,6 5)'::geometry),
    (4, 'LINESTRING (2 3,5 6)'::geometry)) AS tbl2;
래스터 출력
column1 | column1 | above
---------+---------+-------
       1 |       2 | t
       1 |       3 | f
       1 |       4 | f
(3 rows)
Figure
Geometry figure for visual-st-geometry-above-01

참고

<<, >>, <<|


제목

~ — A의 경계 상자가 B의 경계 상자를 담고 있을 경우 TRUE 를 반환합니다.

요약

boolean ~( geometry A , geometry B );

설명

~ 연산자는 도형 A의 경계 상자가 도형 B의 경계 상자를 완전히 담고 있을 경우 TRUE 를 반환합니다.

[참고]

이 피연산자(operand)는 도형에서 이용할 수도 있는 모든 인덱스를 활용할 것입니다.

예시

Code
SELECT tbl1.column1, tbl2.column1, tbl1.column2 ~ tbl2.column2 AS contains
FROM
  ( VALUES
    (1, 'LINESTRING (0 0,3 3)'::geometry)) AS tbl1,
  ( VALUES
    (2, 'LINESTRING (0 0,4 4)'::geometry),
    (3, 'LINESTRING (1 1,2 2)'::geometry),
    (4, 'LINESTRING (0 0,3 3)'::geometry)) AS tbl2;
래스터 출력
column1 | column1 | contains
---------+---------+----------
       1 |       2 | f
       1 |       3 | t
       1 |       4 | t
(3 rows)
Figure
Geometry figure for visual-st-geometry-contain-01

참고

@, &&


제목

~(geometry,box2df) — Returns TRUE if a geometry's 2D bonding box contains a 2D float precision bounding box (GIDX).

요약

boolean ~( geometry A , box2df B );

설명

The ~ operator returns TRUE if the 2D bounding box of a geometry A contains the 2D bounding box B, using float precision. This means that if B is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)

[참고]

This operand is intended to be used internally by BRIN indexes, more than by users.

Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

예시

Code
SELECT ST_Buffer('POINT(1 1)'::geometry, 10) ~ ST_MakeBox2D(ST_Point(0, 0), ST_Point(2, 2)) AS contains;
래스터 출력
t

제목

~(box2df,geometry) — Returns TRUE if a 2D float precision bounding box (BOX2DF) contains a geometry's 2D bonding box.

요약

boolean ~( box2df A , geometry B );

설명

The ~ operator returns TRUE if the 2D bounding box A contains the B geometry's bounding box, using float precision. This means that if A is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)

[참고]

This operand is intended to be used internally by BRIN indexes, more than by users.

Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

예시

Code
SELECT ST_MakeBox2D(ST_Point(0, 0), ST_Point(5, 5)) ~ ST_Buffer('POINT(2 2)'::geometry, 1) AS contains;
래스터 출력
t

제목

~(box2df,box2df) — Returns TRUE if a 2D float precision bounding box (BOX2DF) contains another 2D float precision bounding box (BOX2DF).

요약

boolean ~( box2df A , box2df B );

설명

The ~ operator returns TRUE if the 2D bounding box A contains the 2D bounding box B, using float precision. This means that if A is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)

[참고]

This operand is intended to be used internally by BRIN indexes, more than by users.

Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

예시

Code
SELECT ST_MakeBox2D(ST_Point(0, 0), ST_Point(5, 5)) ~ ST_MakeBox2D(ST_Point(2, 2), ST_Point(3, 3)) AS contains;
래스터 출력
t

제목

~= — A의 경계 상자와 B의 경계 상자가 동일할 경우 TRUE 를 반환합니다.

요약

boolean ~=( geometry A , geometry B );

설명

~= 연산자는 도형/지리형 A의 경계 상자와 도형/지리형 B의 경계 상자가 동일할 경우 TRUE 를 반환합니다.

[참고]

이 피연산자(operand)는 도형에서 이용할 수도 있는 모든 인덱스를 활용할 것입니다.

1.5.0 버전에서 습성이 변경됐습니다.

This function supports Polyhedral surfaces.

[주의]

This operator has changed behavior in PostGIS 1.5 from testing for actual geometric equality to only checking for bounding box equality. To complicate things it also depends on if you have done a hard or soft upgrade which behavior your database has. To find out which behavior your database has you can run the query below. To check for true equality use ST_OrderingEquals or ST_Equals.

예시

Code
SELECT 'LINESTRING(0 0,1 1)'::geometry ~= 'LINESTRING(0 1,1 0)'::geometry AS equality;
래스터 출력
t
Figure
Geometry figure for visual-st-geometry-same-01

7.10.2. 연산자(operator)

  • <-> — A와 B 사이의 2차원 거리를 반환합니다.
  • |=| — A와 B 사이의 최근접점(closest point of approach)을 잇는 궤도(trajectory)의 거리를 반환합니다.
  • <#> — A와 B의 경계 상자 사이의 2차원 거리를 반환합니다.
  • <<->> — Returns the n-D distance between the A and B geometries or bounding boxes

제목

<-> — A와 B 사이의 2차원 거리를 반환합니다.

요약

double precision <->( geometry A , geometry B );

double precision <->( geography A , geography B );

설명

The <-> operator returns the 2D distance between two geometries. Used in the "ORDER BY" clause provides index-assisted nearest-neighbor result sets with true KNN distance search for geometries, and distance on the sphere for geographies.

[참고]

이 피연산자(operand)는 도형에 대해 이용할 수 있을지도 모르는 2차원 GiST 인덱스를 활용할 것입니다. 연산자가 ORDER BY 절 안에 있을 때만 공간 인덱스를 쓴다는 점에서 공간 인덱스를 이용하는 다른 연산자들과는 다릅니다.

[참고]

도형 가운데 하나가, 예를 들어 a.geom이 아니라 'SRID=3005;POINT(1011102 450541)'::geometry와 같이, (하위 쿼리/CTE(common table expression) 안에 있지 않은) 상수일 경우에만 인덱스의 효과가 나타납니다.

실제 사용례를 살펴보려면 OpenGeo workshop: Nearest-Neighbour Searching 을 참조하십시오.

Enhanced: 2.2.0 -- True KNN ("K nearest neighbor") behavior for geometry and geography. Note for geography KNN is based on sphere rather than spheroid.

Changed: 2.2.0 -- Old hybrid-syntax workarounds may be slower once true KNN is available. See examples below.

Availability: 2.0.0 -- Weak KNN provides nearest neighbors based on geometry centroid distances instead of true distances. Exact results for points, inexact for all other types.

예시

Code
SELECT ST_Distance(geom, 'SRID=3005;POINT(1011102 450541)'::geometry) as d, edabbr, vaabbr
FROM va2005
ORDER BY d limit 10;
래스터 출력
d         | edabbr | vaabbr
------------------+--------+--------
                0 | ALQ    | 128
 5541.57712511724 | ALQ    | 129A
 5579.67450712005 | ALQ    | 001
  6083.4207708641 | ALQ    | 131
  7691.2205404848 | ALQ    | 003
 7900.75451037313 | ALQ    | 122
 8694.20710669982 | ALQ    | 129B
 9564.24289057111 | ALQ    | 130
  12089.665931705 | ALQ    | 127
 18472.5531479404 | ALQ    | 002
(10 rows)

그리고 KNN의 가공되지 않은 답은:

Code
SELECT ST_Distance(geom, 'SRID=3005;POINT(1011102 450541)'::geometry) as d,edabbr, vaabbr
FROM va2005
ORDER BY geom <-> 'SRID=3005;POINT(1011102 450541)'::geometry limit 10;
래스터 출력
        d         | edabbr | vaabbr
------------------+--------+--------
                0 | ALQ    | 128
 5541.57712511724 | ALQ    | 129A
 5579.67450712005 | ALQ    | 001
  6083.4207708641 | ALQ    | 131
  7691.2205404848 | ALQ    | 003
 7900.75451037313 | ALQ    | 122
 8694.20710669982 | ALQ    | 129B
 9564.24289057111 | ALQ    | 130
  12089.665931705 | ALQ    | 127
 18472.5531479404 | ALQ    | 002
(10 rows)

사용자가 이 두 쿼리에 대해 "EXPLAIN ANALYZE"를 실행하면 두 번째 쿼리의 성능이 향상되는 것을 볼 수 있을 겁니다.

When a plan cannot produce exact distances directly, use a hybrid query to find the true nearest neighbors. First a CTE query using the index-assisted KNN, then an exact query to get correct ordering:

Code
WITH index_query AS (
  SELECT ST_Distance(geom, 'SRID=3005;POINT(1011102 450541)'::geometry) as d,edabbr, vaabbr
    FROM va2005
  ORDER BY geom <-> 'SRID=3005;POINT(1011102 450541)'::geometry LIMIT 100)
  SELECT *
    FROM index_query
  ORDER BY d limit 10;
래스터 출력
        d         | edabbr | vaabbr
------------------+--------+--------
                0 | ALQ    | 128
 5541.57712511724 | ALQ    | 129A
 5579.67450712005 | ALQ    | 001
  6083.4207708641 | ALQ    | 131
  7691.2205404848 | ALQ    | 003
 7900.75451037313 | ALQ    | 122
 8694.20710669982 | ALQ    | 129B
 9564.24289057111 | ALQ    | 130
  12089.665931705 | ALQ    | 127
 18472.5531479404 | ALQ    | 002
(10 rows)

제목

|=| — A와 B 사이의 최근접점(closest point of approach)을 잇는 궤도(trajectory)의 거리를 반환합니다.

요약

double precision |=|( geometry A , geometry B );

설명

The |=| operator returns the 3D distance between two trajectories (See ST_IsValidTrajectory). This is the same as ST_DistanceCPA but as an operator it can be used for doing nearest neighbor searches using an N-dimensional index.

[참고]

이 피연산자(operand)는 도형에 대해 이용할 수 있을지도 모르는 N차원 GiST 인덱스를 활용할 것입니다. 연산자가 ORDER BY 절 안에 있을 때만 공간 인덱스를 쓴다는 점에서 공간 인덱스를 이용하는 다른 연산자들과는 다릅니다.

[참고]

도형 가운데 하나가, 예를 들어 a.geom이 아니라 'SRID=3005;LINESTRINGM(0 0 0,0 0 1)'::geometry와 같이, (하위 쿼리/CTE(common table expression) 안에 있지 않은) 상수일 경우에만 인덱스의 효과가 나타납니다.

Availability: 2.2.0.

예시

This example orders stored trajectories by their distance from a literal query trajectory.

Code
\set qt 'ST_AddMeasure(ST_MakeLine(ST_MakePointM(-350, 300, 0), ST_MakePointM(-410, 490, 0)), 10, 20)'

SELECT track_id, dist FROM (
  SELECT track_id,
    ST_DistanceCPA(tr, :qt) dist
  FROM trajectories
  ORDER BY tr |=| :qt
  LIMIT 5
) foo;
래스터 출력
track_id        dist
----------+-------------------
      395 | 0.576496831518066
      380 |  5.06797130410151
      390 |  7.72262293958322
      385 |   9.8004461358071
      405 |  10.9534397988433
(5 rows)

제목

<#> — A와 B의 경계 상자 사이의 2차원 거리를 반환합니다.

요약

double precision <#>( geometry A , geometry B );

설명

The <#> operator returns distance between two floating point bounding boxes, possibly reading them from a spatial index. Useful for doing nearest neighbor approximate distance ordering.

[참고]

이 피연산자(operand)는 도형에 대해 이용할 수 있을지도 모르는 어떤 인덱스라도 활용할 것입니다. 연산자가 ORDER BY 절 안에 있을 때만 공간 인덱스를 쓴다는 점에서 공간 인덱스를 이용하는 다른 연산자들과는 다릅니다.

[참고]

도형 가운데 하나가, 예를 들어 g1.geom <#>가 아니라 ORDER BY (ST_GeomFromText('POINT(1 2)') <#> geom)과 같이, 상수일 경우에만 인덱스의 효과가 나타납니다.

Availability: 2.0.0.

예시

Code
SELECT *
FROM (
SELECT b.tlid, b.mtfcc,
    b.geom <#
> ST_GeomFromText('LINESTRING(746149 2948672,745954 2948576,
        745787 2948499,745740 2948468,745712 2948438,
        745690 2948384,745677 2948319)', 2249) As b_dist,
        ST_Distance(b.geom, ST_GeomFromText('LINESTRING(746149 2948672,745954 2948576,
        745787 2948499,745740 2948468,745712 2948438,
        745690 2948384,745677 2948319)', 2249)) As act_dist
    FROM bos_roads As b
    ORDER BY b_dist, b.tlid
    LIMIT 100) As foo
    ORDER BY act_dist, tlid LIMIT 10;
래스터 출력
   tlid    | mtfcc |      b_dist      |     act_dist
-----------+-------+------------------+------------------
  85732027 | S1400 |                0 |                0
  85732029 | S1400 |                0 |                0
  85732031 | S1400 |                0 |                0
  85734335 | S1400 |                0 |                0
  85736037 | S1400 |                0 |                0
 624683742 | S1400 |                0 | 128.528874268666
  85719343 | S1400 | 260.839270432962 | 260.839270432962
  85741826 | S1400 | 164.759294123275 | 260.839270432962
  85732032 | S1400 |           277.75 | 311.830282365264
  85735592 | S1400 |           222.25 | 311.830282365264
(10 rows)

제목

<<->> — Returns the n-D distance between the A and B geometries or bounding boxes

요약

double precision <<->>( geometry A , geometry B );

설명

<<->> 연산자는 두 도형의 경계 상자의 중심점 사이의 N차 (유클리드) 거리를 반환합니다. 최근접 근사치 거리의 순서를 정렬하는 데 유용합니다.

[참고]

이 피연산자(operand)는 도형에 대해 이용할 수 있을지도 모르는 N차원 GiST 인덱스를 활용할 것입니다. 연산자가 ORDER BY 절 안에 있을 때만 공간 인덱스를 쓴다는 점에서 공간 인덱스를 이용하는 다른 연산자들과는 다릅니다.

[참고]

도형 가운데 하나가, 예를 들어 a.geom이 아니라 'SRID=3005;POINT(1011102 450541)'::geometry와 같이, (하위 쿼리/CTE(common table expression) 안에 있지 않은) 상수일 경우에만 인덱스의 효과가 나타납니다.

Availability: 2.2.0.

참고

<->

7.11. Spatial Relationships

초록

These functions determine spatial relationships between geometries.

7.11.1. Topological Relationships

  • ST_3DIntersects — Tests if two geometries spatially intersect in 3D - only for points, linestrings, polygons, polyhedral surface (area)
  • ST_Contains — Tests if every point of B lies in A, and their interiors have a point in common
  • ST_ContainsProperly — Tests if every point of B lies in the interior of A
  • ST_CoveredBy — Tests if every point of A lies in B
  • ST_Covers — Tests if every point of B lies in A
  • ST_Crosses — Tests if two geometries have some, but not all, interior points in common
  • ST_Disjoint — Tests if two geometries have no points in common
  • ST_Equals — Tests if two geometries include the same set of points
  • ST_Intersects — Tests if two geometries intersect (they have at least one point in common)
  • ST_LineCrossingDirection — Returns a number indicating the crossing behavior of two LineStrings
  • ST_OrderingEquals — Tests if two geometries represent the same geometry and have points in the same directional order
  • ST_Overlaps — Tests if two geometries have the same dimension and intersect, but each has at least one point not in the other
  • ST_Relate — Tests if two geometries have a topological relationship matching an Intersection Matrix pattern, or computes their Intersection Matrix
  • ST_RelateMatch — Tests if a DE-9IM Intersection Matrix matches an Intersection Matrix pattern
  • ST_Touches — Tests if two geometries have at least one point in common, but their interiors do not intersect
  • ST_Within — Tests if every point of A lies in B, and their interiors have a point in common

제목

ST_3DIntersects — Tests if two geometries spatially intersect in 3D - only for points, linestrings, polygons, polyhedral surface (area)

요약

boolean ST_3DIntersects( geometry geomA , geometry geomB );

설명

Overlaps, Touches, Within all imply spatial intersection. If any of the aforementioned returns true, then the geometries also spatially intersect. Disjoint implies false for spatial intersection.

[참고]

This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available on the geometries.

[참고]

Because of floating robustness failures, geometries don't always intersect as you'd expect them to after geometric processing. For example the closest point on a linestring to a geometry may not lie on the linestring. For these kind of issues where a distance of a centimeter you want to just consider as intersecting, use ST_3DDWithin.

Changed: 3.0.0 SFCGAL backend removed, GEOS backend supports TINs.

2.0.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 5.1

도형 예시

Code
SELECT ST_3DIntersects(pt, line), ST_Intersects(pt, line)
FROM (SELECT 'POINT(0 0 2)'::geometry As pt, 'LINESTRING (0 0 1,0 2 3)'::geometry As line) As foo;
래스터 출력
st_3dintersects | st_intersects
-----------------+---------------
 f               | t
(1 row)
Figure
Geometry figure for visual-st-3dintersects-01

TIN Examples

Code
SELECT ST_3DIntersects('TIN(((0 0 0,1 0 0,0 1 0,0 0 0)))'::geometry, 'POINT(.1 .1 0)'::geometry);
래스터 출력
t
Figure
Geometry figure for visual-st-3dintersects-02

제목

ST_Contains — Tests if every point of B lies in A, and their interiors have a point in common

요약

boolean ST_Contains(geometry geomA, geometry geomB);

설명

Returns TRUE if geometry A contains geometry B. A contains B if and only if all points of B lie inside (i.e. in the interior or boundary of) A (or equivalently, no points of B lie in the exterior of A), and the interiors of A and B have at least one point in common.

In mathematical terms: ST_Contains(A, B) ⇔ (A ⋂ B = B) ∧ (Int(A) ⋂ Int(B) ≠ ∅)

The contains relationship is reflexive: every geometry contains itself. (In contrast, in the ST_ContainsProperly predicate a geometry does not properly contain itself.) The relationship is antisymmetric: if ST_Contains(A,B) = true and ST_Contains(B,A) = true, then the two geometries must be topologically equal (ST_Equals(A,B) = true).

ST_Contains is the converse of ST_Within. So, ST_Contains(A,B) = ST_Within(B,A).

[참고]

Because the interiors must have a common point, a subtlety of the definition is that polygons and lines do not contain lines and points lying fully in their boundary. For further details see Subtleties of OGC Covers, Contains, Within. The ST_Covers predicate provides a more inclusive relationship.

[참고]

This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available on the geometries. To avoid index use, use the function _ST_Contains.

GEOS 모듈로 실행

Enhanced: 2.3.0 Enhancement to PIP short-circuit extended to support MultiPoints with few points. Prior versions only supported point in polygon.

Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION

[중요]

Do not use this function with invalid geometries. You will get unexpected results.

NOTE: this is the "allowable" version that returns a boolean, not an integer.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.2 // s2.1.13.3 - same as within(geometry B, geometry A)

This method implements the SQL/MM specification. SQL-MM 3: 5.1.31

예시

ST_Contains returns TRUE in the following situations:

A LineString contains a MultiPoint whose points lie in its interior or boundary.

Code
SELECT ST_Contains(a, b)
FROM (SELECT
  'LINESTRING (10 190,60 80,130 120,190 10)'::geometry AS a,
  'MULTIPOINT (60 80,190 10)'::geometry AS b
) AS example;
래스터 출력
t
Figure
Geometry figure for visual-st-contains-01

A Polygon contains a Point in its interior.

Code
SELECT ST_Contains(a, b)
FROM (SELECT
  'POLYGON ((10 130,50 190,110 190,140 150,150 80,100 10,20 40,10 130))'::geometry AS a,
  'POINT (99 130)'::geometry AS b
) AS example;
래스터 출력
t
Figure
Geometry figure for visual-st-contains-02

A Polygon contains a LineString with interior points inside the Polygon.

Code
SELECT ST_Contains(a, b)
FROM (SELECT
  'POLYGON ((10 130,50 190,110 190,140 150,150 80,100 10,20 40,10 130))'::geometry AS a,
  'LINESTRING (50 190,110 190,99 130)'::geometry AS b
) AS example;
래스터 출력
t
Figure
Geometry figure for visual-st-contains-03

A Polygon contains another Polygon in its interior.

Code
SELECT ST_Contains(a, b)
FROM (SELECT
  'POLYGON ((10 130,50 190,110 190,140 150,150 80,100 10,20 40,10 130))'::geometry AS a,
  'POLYGON ((70 40,100 50,120 80,80 110,50 90,70 40))'::geometry AS b
) AS example;
래스터 출력
t
Figure
Geometry figure for visual-st-contains-04

ST_Contains returns FALSE in the following situations:

A Polygon does not contain a MultiPoint when one point lies in a hole.

Code
SELECT ST_Contains(a, b)
FROM (SELECT
  'POLYGON ((10 130,50 190,110 190,140 150,150 80,100 10,20 40,10 130),(70 40,100 50,120 80,80 110,50 90,70 40))'::geometry AS a,
  'MULTIPOINT (99 130,87 70)'::geometry AS b
) AS example;
래스터 출력
f
Figure
Geometry figure for visual-st-contains-05

A Polygon does not contain a LineString extending outside it.

Code
SELECT ST_Contains(a, b)
FROM (SELECT
  'POLYGON ((10 130,50 190,110 190,140 150,150 80,100 10,20 40,10 130))'::geometry AS a,
  'LINESTRING (99 130,170 131)'::geometry AS b
) AS example;
래스터 출력
f
Figure
Geometry figure for visual-st-contains-06

Due to the interior intersection condition ST_Contains returns FALSE in the following situations (whereas ST_Covers returns TRUE):

A LineString does not contain a Point lying only on its boundary.

Code
SELECT ST_Contains(a, b), ST_Covers(a, b)
FROM (SELECT
  'LINESTRING (10 190,60 80,130 120,190 10)'::geometry AS a,
  'POINT (190 10)'::geometry AS b
) AS example;
래스터 출력
f | t
Figure
Geometry figure for visual-st-contains-07

A Polygon does not contain a LineString lying entirely on its boundary.

Code
SELECT ST_Contains(a, b), ST_Covers(a, b)
FROM (SELECT
  'POLYGON ((10 130,50 190,110 190,140 150,150 80,100 10,20 40,10 130))'::geometry AS a,
  'LINESTRING (80 190,110 190,140 150,150 80)'::geometry AS b
) AS example;
래스터 출력
f | t
Figure
Geometry figure for visual-st-contains-08

This example tests a circle within another circle.

Code
WITH circles AS (
  SELECT ST_Buffer(center, 10) AS smallc,
         ST_Buffer(center, 20) AS bigc
  FROM (SELECT 'POINT(1 2)'::geometry AS center) AS p
)
SELECT
  ST_Contains(smallc, bigc) AS smallcontainsbig,
  ST_Contains(bigc, smallc) AS bigcontainssmall,
  ST_Contains(bigc, ST_Union(smallc, bigc)) AS bigcontainsunion,
  ST_Equals(bigc, ST_Union(smallc, bigc)) AS bigisunion,
  ST_Covers(bigc, ST_ExteriorRing(bigc)) AS bigcoversexterior,
  ST_Contains(bigc, ST_ExteriorRing(bigc)) AS bigcontainsexterior
FROM circles;
래스터 출력
-[ RECORD 1 ]-----
smallcontainsbig   | f
bigcontainssmall   | t
bigcontainsunion   | t
bigisunion         | t
bigcoversexterior  | t
bigcontainsexterior | f
Figure
Geometry figure for visual-st-contains-09

This example demonstrates the difference between contains and contains-properly predicates.

Code
SELECT
  ST_GeometryType(geom_a) AS geomtype,
  ST_Contains(geom_a, geom_a) AS acontainsa,
  ST_ContainsProperly(geom_a, geom_a) AS acontainspropa,
  ST_Contains(geom_a, ST_Boundary(geom_a)) AS acontainsba,
  ST_ContainsProperly(geom_a, ST_Boundary(geom_a)) AS acontainspropba
FROM (VALUES
    (ST_Buffer(ST_Point(1, 1), 5, 1)),
    (ST_MakeLine(ST_Point(1, 1), ST_Point(-1, -1))),
    (ST_Point(1, 1))
  ) AS foo(geom_a);
래스터 출력
geomtype    | acontainsa | acontainspropa | acontainsba | acontainspropba
--------------+------------+----------------+-------------+-----------------
ST_Polygon    | t          | f              | f           | f
ST_LineString | t          | f              | f           | f
ST_Point      | t          | t              | f           | f

 
Figure
Geometry figure for visual-st-contains-10

제목

ST_ContainsProperly — Tests if every point of B lies in the interior of A

요약

boolean ST_ContainsProperly(geometry geomA, geometry geomB);

설명

Returns true if every point of B lies in the interior of A (or equivalently, no point of B lies in the the boundary or exterior of A).

In mathematical terms: ST_ContainsProperly(A, B) ⇔ Int(A) ⋂ B = B

A contains B properly if the DE-9IM Intersection Matrix for the two geometries matches [T**FF*FF*]

A does not properly contain itself, but does contain itself.

A use for this predicate is computing the intersections of a set of geometries with a large polygonal geometry. Since intersection is a fairly slow operation, it can be more efficient to use containsProperly to filter out test geometries which lie fully inside the area. In these cases the intersection is known a priori to be exactly the original test geometry.

[참고]

This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available on the geometries. To avoid index use, use the function _ST_ContainsProperly.

[참고]

The advantage of this predicate over ST_Contains and ST_Intersects is that it can be computed more efficiently, with no need to compute topology at individual points.

GEOS 모듈로 실행

1.4.0 버전부터 사용할 수 있습니다.

Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION

[중요]

Do not use this function with invalid geometries. You will get unexpected results.

예시

This example tests a circle within another circle.

Code
WITH circles AS (
  SELECT ST_Buffer(center, 10) AS smallc,
         ST_Buffer(center, 20) AS bigc
  FROM (SELECT 'POINT(1 2)'::geometry AS center) AS p
)
SELECT
  ST_ContainsProperly(smallc, bigc) AS smallcontainspropbig,
  ST_ContainsProperly(bigc, smallc) AS bigcontainspropsmall,
  ST_ContainsProperly(bigc, ST_Union(smallc, bigc)) AS bigcontainspropunion,
  ST_Equals(bigc, ST_Union(smallc, bigc)) AS bigisunion,
  ST_Covers(bigc, ST_ExteriorRing(bigc)) AS bigcoversexterior,
  ST_ContainsProperly(bigc, ST_ExteriorRing(bigc)) AS bigcontainsexterior
FROM circles;
래스터 출력
-[ RECORD 1 ]-----
smallcontainspropbig   | f
bigcontainspropsmall   | t
bigcontainspropunion   | f
bigisunion             | t
bigcoversexterior      | t
bigcontainsexterior    | f
Figure
Geometry figure for visual-st-containsproperly-01

This example demonstrates the difference between contains and contains-properly predicates.

Code
WITH input(geom) AS (VALUES
  (ST_Buffer(ST_Point(1, 1), 5, 1)),
  (ST_MakeLine(ST_Point(1, 1), ST_Point(-1, -1))),
  (ST_Point(1, 1))
)
SELECT ST_GeometryType(geom) AS geomtype,
       ST_Contains(geom, geom) AS acontainsa,
       ST_ContainsProperly(geom, geom) AS acontainspropa,
       ST_Contains(geom, ST_Boundary(geom)) AS acontainsba,
       ST_ContainsProperly(geom, ST_Boundary(geom)) AS acontainspropba
FROM input;
래스터 출력
geomtype    | acontainsa | acontainspropa | acontainsba | acontainspropba
--------------+------------+----------------+-------------+-----------------
ST_Polygon    | t          | f              | f           | f
ST_LineString | t          | f              | f           | f
ST_Point      | t          | t              | f           | f
 
Figure
Geometry figure for visual-st-containsproperly-02

제목

ST_CoveredBy — Tests if every point of A lies in B

요약

boolean ST_CoveredBy(geometry geomA, geometry geomB);

boolean ST_CoveredBy(geography geogA, geography geogB);

설명

Returns true if every point in Geometry/Geography A lies inside (i.e. intersects the interior or boundary of) Geometry/Geography B. Equivalently, tests that no point of A lies outside (in the exterior of) B.

In mathematical terms: ST_CoveredBy(A, B) ⇔ A ⋂ B = A

ST_CoveredBy is the converse of ST_Covers. So, ST_CoveredBy(A,B) = ST_Covers(B,A).

Generally this function should be used instead of ST_Within, since it has a simpler definition which does not have the quirk that "boundaries are not within their geometry".

[참고]

This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available on the geometries. To avoid index use, use the function _ST_CoveredBy.

Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION

[중요]

Do not use this function with invalid geometries. You will get unexpected results.

GEOS 모듈로 실행

1.2.2 버전부터 사용할 수 있습니다.

NOTE: this is the "allowable" version that returns a boolean, not an integer.

Not an OGC standard, but Oracle has it too.

예시

This example tests a circle covered by another circle.

Code
WITH circles AS (
  SELECT ST_Buffer(center, 10) AS smallc,
         ST_Buffer(center, 20) AS bigc
  FROM (SELECT 'POINT(1 2)'::geometry AS center) AS p
)
SELECT
  ST_CoveredBy(smallc, smallc) AS smallinsmall,
  ST_CoveredBy(smallc, bigc) AS smallcoveredbybig,
  ST_CoveredBy(ST_ExteriorRing(bigc), bigc) AS exteriorcoveredbybig,
  ST_Within(ST_ExteriorRing(bigc), bigc) AS exteriorwithinbig
FROM circles;
래스터 출력
smallinsmall | smallcoveredbybig | exteriorcoveredbybig | exteriorwithinbig
--------------+-------------------+----------------------+------------------
 t            | t                 | t                    | f
(1 row) 
Figure
Geometry figure for visual-st-coveredby-01

제목

ST_Covers — Tests if every point of B lies in A

요약

boolean ST_Covers(geometry geomA, geometry geomB);

boolean ST_Covers(geography geogpolyA, geography geogpointB);

설명

Returns true if every point in Geometry/Geography B lies inside (i.e. intersects the interior or boundary of) Geometry/Geography A. Equivalently, tests that no point of B lies outside (in the exterior of) A.

In mathematical terms: ST_Covers(A, B) ⇔ A ⋂ B = B

ST_Covers is the converse of ST_CoveredBy. So, ST_Covers(A,B) = ST_CoveredBy(B,A).

Generally this function should be used instead of ST_Contains, since it has a simpler definition which does not have the quirk that "geometries do not contain their boundary".

[참고]

This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available on the geometries. To avoid index use, use the function _ST_Covers.

Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION

[중요]

Do not use this function with invalid geometries. You will get unexpected results.

GEOS 모듈로 실행

Enhanced: 2.4.0 Support for polygon in polygon and line in polygon added for geography type

Enhanced: 2.3.0 Enhancement to PIP short-circuit for geometry extended to support MultiPoints with few points. Prior versions only supported point in polygon.

1.5.0 버전부터 지리형을 지원합니다.

1.2.2 버전부터 사용할 수 있습니다.

NOTE: this is the "allowable" version that returns a boolean, not an integer.

Not an OGC standard, but Oracle has it too.

예시

Geometry example

This example tests a circle covering another circle.

Code
WITH circles AS (
  SELECT ST_Buffer(center, 10) AS smallc,
         ST_Buffer(center, 20) AS bigc
  FROM (SELECT 'POINT(1 2)'::geometry AS center) AS p
)
SELECT
  ST_Covers(smallc, smallc) AS smallinsmall,
  ST_Covers(smallc, bigc) AS smallcoversbig,
  ST_Covers(bigc, ST_ExteriorRing(bigc)) AS bigcoversexterior,
  ST_Contains(bigc, ST_ExteriorRing(bigc)) AS bigcontainsexterior
FROM circles;
래스터 출력
smallinsmall | smallcoversbig | bigcoversexterior | bigcontainsexterior
--------------+----------------+-------------------+---------------------
 t            | f              | t                 | f
(1 row) 
Figure
Geometry figure for visual-st-covers-01

Geography example

This example compares a point with a 300-meter buffer against a point and against a 10-meter buffer around that point.

Code
SELECT ST_Covers(geog_poly, geog_pt) As poly_covers_pt,
  ST_Covers(ST_Buffer(geog_pt, 10), geog_pt) As buff_10m_covers_cent
  FROM (SELECT ST_Buffer('SRID=4326;POINT(-99.327 31.4821)'::geography, 300) As geog_poly,
        'SRID=4326;POINT(-99.33 31.483)'::geography As geog_pt ) As foo;
래스터 출력
poly_covers_pt | buff_10m_covers_cent
----------------+------------------
 f              | t

제목

ST_Crosses — Tests if two geometries have some, but not all, interior points in common

요약

boolean ST_Crosses(geometry g1, geometry g2);

설명

Compares two geometry objects and returns true if their intersection "spatially crosses"; that is, the geometries have some, but not all interior points in common. The intersection of the interiors of the geometries must be non-empty and must have dimension less than the maximum dimension of the two input geometries, and the intersection of the two geometries must not equal either geometry. Otherwise, it returns false. The crosses relation is symmetric and irreflexive.

In mathematical terms: ST_Crosses(A, B) ⇔ (dim( Int(A) ⋂ Int(B) ) < max( dim( Int(A) ), dim( Int(B) ) )) ∧ (A ⋂ B ≠ A) ∧ (A ⋂ B ≠ B)

Geometries cross if their DE-9IM Intersection Matrix matches:

  • T*T****** for Point/Line, Point/Area, and Line/Area situations

  • T*****T** for Line/Point, Area/Point, and Area/Line situations

  • 0******** for Line/Line situations

  • the result is false for Point/Point and Area/Area situations

[참고]

The OpenGIS Simple Features Specification defines this predicate only for Point/Line, Point/Area, Line/Line, and Line/Area situations. JTS / GEOS extends the definition to apply to Line/Point, Area/Point and Area/Line situations as well. This makes the relation symmetric.

[참고]

This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available on the geometries.

Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.13.3

This method implements the SQL/MM specification. SQL-MM 3: 5.1.29

예시

The following situations all return true.

A LineString crosses a MultiPoint when some, but not all, points lie on the line.

Code
SELECT ST_Crosses(a, b)
FROM (SELECT
  'LINESTRING (10 190,60 80,130 120,190 10)'::geometry AS a,
  'MULTIPOINT (80 170,120 13,130 120,181 142)'::geometry AS b
) AS example;
래스터 출력
t
Figure
Geometry figure for visual-st-crosses-01

A Polygon crosses a MultiPoint when some, but not all, points lie in its interior.

Code
SELECT ST_Crosses(a, b)
FROM (SELECT
  'POLYGON ((30 190,10 100,10 10,90 20,110 70,80 130,30 190))'::geometry AS a,
  'MULTIPOINT (56 60,120 13,130 119,181 142)'::geometry AS b
) AS example;
래스터 출력
t
Figure
Geometry figure for visual-st-crosses-02

A LineString crosses a Polygon when part of the line lies inside and part outside.

Code
SELECT ST_Crosses(a, b)
FROM (SELECT
  'POLYGON ((30 190,10 100,10 10,90 20,110 70,80 130,30 190))'::geometry AS a,
  'LINESTRING (30 40,70 50,120 150,190 190)'::geometry AS b
) AS example;
래스터 출력
t
Figure
Geometry figure for visual-st-crosses-03

Two LineStrings cross when they share an interior point.

Code
SELECT ST_Crosses(a, b)
FROM (SELECT
  'LINESTRING (10 190,60 80,130 120,190 10)'::geometry AS a,
  'LINESTRING (10 10,70 30,110 120,190 190)'::geometry AS b
) AS example;
래스터 출력
t
Figure
Geometry figure for visual-st-crosses-04

Consider a situation where a user has two tables: a table of roads and a table of highways.

Code
CREATE TABLE roads (
  id serial NOT NULL,
  geom geometry,
  CONSTRAINT roads_pkey PRIMARY KEY (road_id)
);

Code
CREATE TABLE highways (
  id serial NOT NULL,
  the_gem geometry,
  CONSTRAINT roads_pkey PRIMARY KEY (road_id)
);

To determine a list of roads that cross a highway, use a query similar to:

Code
SELECT roads.id
FROM roads, highways
WHERE ST_Crosses(roads.geom, highways.geom);

제목

ST_Disjoint — Tests if two geometries have no points in common

요약

boolean ST_Disjoint( geometry A , geometry B );

설명

Returns true if two geometries are disjoint. Geometries are disjoint if they have no point in common.

If any other spatial relationship is true for a pair of geometries, they are not disjoint. Disjoint implies that ST_Intersects is false.

In mathematical terms: ST_Disjoint(A, B) ⇔ A ⋂ B = ∅

Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION

GEOS 모듈로 실행

[참고]

This function call does not use indexes. A negated ST_Intersects predicate can be used as a more performant alternative that uses indexes: ST_Disjoint(A,B) = NOT ST_Intersects(A,B)

[참고]

NOTE: this is the "allowable" version that returns a boolean, not an integer.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.2 //s2.1.13.3 - a.Relate(b, 'FF*FF****')

This method implements the SQL/MM specification. SQL-MM 3: 5.1.26

예시

Code
SELECT ST_Disjoint('POINT(0 0)'::geometry, 'LINESTRING ( 2 0,0 2 )'::geometry);
래스터 출력
t
Figure
Geometry figure for visual-st-disjoint-01
Code
SELECT ST_Disjoint('POINT(0 0)'::geometry, 'LINESTRING ( 0 0,0 2 )'::geometry);
래스터 출력
f
Figure
Geometry figure for visual-st-disjoint-02

제목

ST_Equals — Tests if two geometries include the same set of points

요약

boolean ST_Equals(geometry A, geometry B);

설명

Returns true if the given geometries are "topologically equal". Use this for a 'better' answer than '='. Topological equality means that the geometries have the same dimension, and their point-sets occupy the same space. This means that the order of vertices may be different in topologically equal geometries. To verify the order of points is consistent use ST_OrderingEquals (it must be noted ST_OrderingEquals is a little more stringent than simply verifying order of points are the same).

In mathematical terms: ST_Equals(A, B) ⇔ A = B

The following relation holds: ST_Equals(A, B) ⇔ ST_Within(A,B) ∧ ST_Within(B,A)

Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.2

This method implements the SQL/MM specification. SQL-MM 3: 5.1.24

Changed: 2.2.0 Returns true even for invalid geometries if they are binary equal

예시

Code
SELECT ST_Equals('LINESTRING(0 0,10 10)',
'LINESTRING(0 0,5 5,10 10)');
래스터 출력
t
Figure
Geometry figure for visual-st-equals-01
Code
SELECT ST_Equals(ST_Reverse('LINESTRING(0 0,10 10)'),
'LINESTRING(0 0,5 5,10 10)');
래스터 출력
t
Figure
Geometry figure for visual-st-equals-02

제목

ST_Intersects — Tests if two geometries intersect (they have at least one point in common)

요약

boolean ST_Intersects( geometry geomA , geometry geomB );

boolean ST_Intersects( geography geogA , geography geogB );

설명

Returns true if two geometries intersect. Geometries intersect if they have any point in common.

For geography, a distance tolerance of 0.00001 meters is used (so points that are very close are considered to intersect).

In mathematical terms: ST_Intersects(A, B) ⇔ A ⋂ B ≠ ∅

Geometries intersect if their DE-9IM Intersection Matrix matches one of:

  • T********

  • *T*******

  • ***T*****

  • ****T****

Spatial intersection is implied by all the other spatial relationship tests, except ST_Disjoint, which tests that geometries do NOT intersect.

[참고]

This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available on the geometries.

Changed: 3.0.0 SFCGAL version removed and native support for 2D TINS added.

Enhanced: 2.5.0 Supports GEOMETRYCOLLECTION.

Enhanced: 2.3.0 Enhancement to PIP short-circuit extended to support MultiPoints with few points. Prior versions only supported point in polygon.

Performed by the GEOS module (for geometry), geography is native

Availability: 1.5 support for geography was introduced.

[참고]

For geography, this function has a distance tolerance of about 0.00001 meters and uses the sphere rather than spheroid calculation.

[참고]

NOTE: this is the "allowable" version that returns a boolean, not an integer.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.2 //s2.1.13.3 - ST_Intersects(g1, g2 ) --> Not (ST_Disjoint(g1, g2 ))

This method implements the SQL/MM specification. SQL-MM 3: 5.1.27

This method supports Circular Strings and Curves.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

도형 예시

Code
SELECT ST_Intersects('POINT(0 0)'::geometry, 'LINESTRING ( 2 0,0 2 )'::geometry);
래스터 출력
f
Figure
Geometry figure for visual-st-intersects-01
Code
SELECT ST_Intersects('POINT(0 0)'::geometry, 'LINESTRING ( 0 0,0 2 )'::geometry);
래스터 출력
t
Figure
Geometry figure for visual-st-intersects-02

This example looks up rows in a table; for faster lookup, the geometry column should have a GiST index.

Code
SELECT id, name FROM cities WHERE ST_Intersects(geom, 'SRID=4326;POLYGON((28 53,27.707 52.293,27 52,26.293 52.293,26 53,26.293 53.707,27 54,27.707 53.707,28 53))');
래스터 출력
id | name
----+-------
  2 | Minsk
(1 row)

지리형 예시

Code
SELECT ST_Intersects('SRID=4326;LINESTRING(-43.23456 72.4567,-43.23456 72.4568)'::geography,
'SRID=4326;POINT(-43.23456 72.4567772)'::geography
);
래스터 출력
t

제목

ST_LineCrossingDirection — Returns a number indicating the crossing behavior of two LineStrings

요약

integer ST_LineCrossingDirection(geometry linestringA, geometry linestringB);

설명

Given two linestrings returns an integer between -3 and 3 indicating what kind of crossing behavior exists between them. 0 indicates no crossing. This is only supported for LINESTRINGs.

The crossing number has the following meaning:

  • 0: LINE NO CROSS

  • -1: LINE CROSS LEFT

  • 1: LINE CROSS RIGHT

  • -2: LINE MULTICROSS END LEFT

  • 2: LINE MULTICROSS END RIGHT

  • -3: LINE MULTICROSS END SAME FIRST LEFT

  • 3: LINE MULTICROSS END SAME FIRST RIGHT

Availability: 1.4

예시

Example: LINE CROSS LEFT and LINE CROSS RIGHT

Code
SELECT ST_LineCrossingDirection(lineA, lineB) As A_cross_B,
       ST_LineCrossingDirection(lineB, lineA) As B_cross_A
FROM (SELECT
  'LINESTRING(25 169,89 114,40 70,86 43)'::geometry As lineA,
  'LINESTRING (20 140,71 74,161 53)'::geometry As lineB
  ) As foo;
래스터 출력
A_cross_B | B_cross_A
-----------+-----------
        -1 |         1
Figure
Geometry figure for visual-st-linecrossingdirection-01

Example: LINE MULTICROSS END SAME FIRST LEFT and LINE MULTICROSS END SAME FIRST RIGHT

Code
SELECT ST_LineCrossingDirection(lineA, lineB) As A_cross_B,
       ST_LineCrossingDirection(lineB, lineA) As B_cross_A
FROM (SELECT
 'LINESTRING(25 169,89 114,40 70,86 43)'::geometry As lineA,
 'LINESTRING(171 154,20 140,71 74,161 53)'::geometry As lineB
  ) As foo;
래스터 출력
A_cross_B | B_cross_A
-----------+-----------
         3 |        -3
Figure
Geometry figure for visual-st-linecrossingdirection-02

Example: LINE MULTICROSS END LEFT and LINE MULTICROSS END RIGHT

Code
SELECT ST_LineCrossingDirection(lineA, lineB) As A_cross_B,
       ST_LineCrossingDirection(lineB, lineA) As B_cross_A
FROM (SELECT
  'LINESTRING(25 169,89 114,40 70,86 43)'::geometry As lineA,
  'LINESTRING(5 90,71 74,20 140,171 154)'::geometry As lineB
  ) As foo;
래스터 출력
A_cross_B | B_cross_A
-----------+-----------
        -2 |         2
Figure
Geometry figure for visual-st-linecrossingdirection-03

Example: Finds all streets that cross

Code

SELECT s1.gid, s2.gid, ST_LineCrossingDirection(s1.geom, s2.geom)
  FROM streets s1 CROSS JOIN streets s2
         ON (s1.gid != s2.gid AND s1.geom && s2.geom )
WHERE ST_LineCrossingDirection(s1.geom, s2.geom) 
> 0;


제목

ST_OrderingEquals — Tests if two geometries represent the same geometry and have points in the same directional order

요약

boolean ST_OrderingEquals(geometry A, geometry B);

설명

ST_OrderingEquals compares two geometries and returns t (TRUE) if the geometries are equal and the coordinates are in the same order; otherwise it returns f (FALSE).

[참고]

This function is implemented as per the ArcSDE SQL specification rather than SQL-MM. http://edndoc.esri.com/arcsde/9.1/sql_api/sqlapi3.htm#ST_OrderingEquals

This method implements the SQL/MM specification. SQL-MM 3: 5.1.43

예시

Code
SELECT ST_OrderingEquals('LINESTRING(0 0,10 10)',
'LINESTRING(0 0,5 5,10 10)');
래스터 출력
f
Figure
Geometry figure for visual-st-orderingequals-01
Code
SELECT ST_OrderingEquals('LINESTRING(0 0,10 10)',
'LINESTRING(0 0,10 10)');
래스터 출력
t
Figure
Geometry figure for visual-st-orderingequals-02
Code
SELECT ST_OrderingEquals('POLYGON((0 0,0 1,1 1,1 0,0 0))',
'POLYGON((0 0,1 0,1 1,0 1,0 0))');
래스터 출력
f
Figure
Geometry figure for visual-st-orderingequals-03

제목

ST_Overlaps — Tests if two geometries have the same dimension and intersect, but each has at least one point not in the other

요약

boolean ST_Overlaps(geometry A, geometry B);

설명

Returns TRUE if geometry A and B "spatially overlap". Two geometries overlap if they have the same dimension, their interiors intersect in that dimension. and each has at least one point inside the other (or equivalently, neither one covers the other). The overlaps relation is symmetric and irreflexive.

In mathematical terms: ST_Overlaps(A, B) ⇔ ( dim(A) = dim(B) = dim( Int(A) ⋂ Int(B) )) ∧ (A ⋂ B ≠ A) ∧ (A ⋂ B ≠ B)

[참고]

This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available on the geometries. To avoid index use, use the function _ST_Overlaps.

GEOS 모듈로 실행

Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION

NOTE: this is the "allowable" version that returns a boolean, not an integer.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.2 // s2.1.13.3

This method implements the SQL/MM specification. SQL-MM 3: 5.1.32

예시

ST_Overlaps returns TRUE in the following situations:

Two MultiPoints overlap when they share some, but not all, points.

Code
SELECT ST_Overlaps(a, b)
FROM (SELECT
  'MULTIPOINT ((20 20),(40 90),(80 130),(140 100),(110 40),(120 170),(150 70))'::geometry AS a,
  'MULTIPOINT ((180 10),(40 90),(80 130),(160 150),(110 40),(50 50),(50 160))'::geometry AS b
) AS example;
래스터 출력
t
Figure
Geometry figure for visual-st-overlaps-01

Two LineStrings overlap along part of their paths.

Code
SELECT ST_Overlaps(a, b)
FROM (SELECT
  'LINESTRING (10 10,40 90,70 110,140 110,170 130,190 190)'::geometry AS a,
  'LINESTRING (10 190,50 130,90 110,130 110,160 70,180 10)'::geometry AS b
) AS example;
래스터 출력
t
Figure
Geometry figure for visual-st-overlaps-02

Two Polygons overlap where their interiors intersect and neither contains the other.

Code
SELECT ST_Overlaps(a, b)
FROM (SELECT
  'POLYGON ((140 140,140 122,135 105,126 100,118 99,110 94,100 86,97 73,102 59,98 49,87 38,70 30,55 29,40 30,28 38,20 50,14 66,10 84,6 100,4 119,4 143,6 166,10 180,18 191,28 195,40 190,55 189,67 186,86 179,112 165,124 158,133 148,140 140),(48 177,40 177,30 174,24 166,22 159,25 155,30 153,40 154,45 157,52 162,53 169,51 174,48 177))'::geometry AS a,
  'POLYGON ((75 63,79 50,87 38,95 31,108 25,124 22,140 18,154 11,166 6,176 10,184 21,188 35,190 58,190 82,193 104,190 121,185 139,178 154,166 163,154 171,139 172,124 171,112 165,96 152,92 142,92 126,86 116,79 110,75 104,72 94,73 86,75 76,75 63))'::geometry AS b
) AS example;
래스터 출력
t
Figure
Geometry figure for visual-st-overlaps-03

A Point on a LineString is contained, but since it has lower dimension it does not overlap or cross.

Code
SELECT ST_Overlaps(a, b) AS overlaps, ST_Crosses(a, b) AS crosses,
       ST_Intersects(a, b) AS intersects, ST_Contains(b, a) AS b_contains_a
FROM (SELECT 'POINT (100 100)'::geometry As a,
             'LINESTRING (30 50,40 160,160 40,180 160)'::geometry  AS b) AS t
래스터 출력
overlaps | crosses | intersects | b_contains_a
---------+----------------------+--------------
f        | f       | t          | t
Figure
Geometry figure for visual-st-overlaps-04

A LineString that partly covers a Polygon intersects and crosses, but does not overlap since it has different dimension.

Code
SELECT ST_Overlaps(a, b) AS overlaps, ST_Crosses(a, b) AS crosses,
       ST_Intersects(a, b) AS intersects, ST_Contains(a, b) AS contains
FROM (SELECT 'POLYGON ((40 170,90 30,180 100,40 170))'::geometry AS a,
             'LINESTRING(10 10,190 190)'::geometry AS b) AS t;
래스터 출력
overlap | crosses | intersects | contains
---------+---------+------------+--------------
 f       | t       | t          | f
Figure
Geometry figure for visual-st-overlaps-05

Two Polygons that intersect but with neither contained by the other overlap, but do not cross because their intersection has the same dimension.

Code
SELECT ST_Overlaps(a, b) AS overlaps, ST_Crosses(a, b) AS crosses,
       ST_Intersects(a, b) AS intersects, ST_Contains(b, a) AS b_contains_a,
       ST_Dimension(a) AS dim_a, ST_Dimension(b) AS dim_b,
       ST_Dimension(ST_Intersection(a, b)) AS dim_int
FROM (SELECT 'POLYGON ((40 170,90 30,180 100,40 170))'::geometry AS a,
             'POLYGON ((110 180,20 60,130 90,110 180))'::geometry AS b) As t;
래스터 출력
overlaps | crosses | intersects | b_contains_a | dim_a | dim_b | dim_int
----------+---------+------------+--------------+-------+-------+-----------
 t        | f       | t          | f            |     2 |     2 |       2
Figure
Geometry figure for visual-st-overlaps-06

제목

ST_Relate — Tests if two geometries have a topological relationship matching an Intersection Matrix pattern, or computes their Intersection Matrix

요약

boolean ST_Relate(geometry geomA, geometry geomB, text intersectionMatrixPattern);

text ST_Relate(geometry geomA, geometry geomB);

text ST_Relate(geometry geomA, geometry geomB, integer boundaryNodeRule);

설명

These functions allow testing and evaluating the spatial (topological) relationship between two geometries, as defined by the Dimensionally Extended 9-Intersection Model (DE-9IM).

The DE-9IM is specified as a 9-element matrix indicating the dimension of the intersections between the Interior, Boundary and Exterior of two geometries. It is represented by a 9-character text string using the symbols 'F', '0', '1', '2' (e.g. 'FF1FF0102').

A specific kind of spatial relationship can be tested by matching the intersection matrix to an intersection matrix pattern. Patterns can include the additional symbols 'T' (meaning "intersection is non-empty") and '*' (meaning "any value"). Common spatial relationships are provided by the named functions ST_Contains, ST_ContainsProperly, ST_Covers, ST_CoveredBy, ST_Crosses, ST_Disjoint, ST_Equals, ST_Intersects, ST_Overlaps, ST_Touches, and ST_Within. Using an explicit pattern allows testing multiple conditions of intersects, crosses, etc in one step. It also allows testing spatial relationships which do not have a named spatial relationship function. For example, the relationship "Interior-Intersects" has the DE-9IM pattern T********, which is not evaluated by any named predicate.

For more information refer to 5.1절. “Determining Spatial Relationships”.

Variant 1: Tests if two geometries are spatially related according to the given intersectionMatrixPattern.

[참고]

Unlike most of the named spatial relationship predicates, this does NOT automatically include an index call. The reason is that some relationships are true for geometries which do NOT intersect (e.g. Disjoint). If you are using a relationship pattern that requires intersection, then include the && index call.

[참고]

It is better to use a named relationship function if available, since they automatically use a spatial index where one exists. Also, they may implement performance optimizations which are not available with full relate evaluation.

Variant 2: Returns the DE-9IM matrix string for the spatial relationship between the two input geometries. The matrix string can be tested for matching a DE-9IM pattern using ST_RelateMatch.

Variant 3: Like variant 2, but allows specifying a Boundary Node Rule. A boundary node rule allows finer control over whether the endpoints of MultiLineStrings are considered to lie in the DE-9IM Interior or Boundary. The boundaryNodeRule values are:

  • 1: OGC-Mod2 - line endpoints are in the Boundary if they occur an odd number of times. This is the rule defined by the OGC SFS standard, and is the default for ST_Relate.

  • 2: Endpoint - all endpoints are in the Boundary.

  • 3: MultivalentEndpoint - endpoints are in the Boundary if they occur more than once. In other words, the boundary is all the "attached" or "inner" endpoints (but not the "unattached/outer" ones).

  • 4: MonovalentEndpoint - endpoints are in the Boundary if they occur only once. In other words, the boundary is all the "unattached" or "outer" endpoints.

This function is not in the OGC spec, but is implied. see s2.1.13.2

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.2 // s2.1.13.3

This method implements the SQL/MM specification. SQL-MM 3: 5.1.25

GEOS 모듈로 실행

Enhanced: 2.0.0 - added support for specifying boundary node rule.

Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION

예시

Using the boolean-valued function to test spatial relationships.

Code
SELECT ST_Relate('POINT(1 2)', ST_Buffer('POINT(1 2)', 2), '0FFFFF212');
래스터 출력
t
Code
SELECT ST_Relate('POINT(1 2)', ST_Buffer('POINT(1 2)', 2), '*FF*FF212');
래스터 출력
t

Testing a custom spatial relationship pattern as a query condition, with && to enable using a spatial index.

Find compounds that properly intersect (not just touch) a poly (Interior Intersects)

Code
SELECT c.* , p.name As poly_name
    FROM polys AS p
    INNER JOIN compounds As c
          ON c.geom && p.geom
             AND ST_Relate(p.geom, c.geom, 'T********');

Computing the intersection matrix for spatial relationships.

Code
SELECT ST_Relate('POINT(1 2)',
ST_Buffer('POINT(1 2)', 2));
래스터 출력
0FFFFF212
Code
SELECT ST_Relate('LINESTRING(1 2,3 4)',
'LINESTRING(5 6,7 8)' );
래스터 출력
FF1FF0102
Figure
Geometry figure for visual-st-relate-04

Using different Boundary Node Rules to compute the spatial relationship between a LineString and a MultiLineString with a duplicate endpoint (3 3):

  • Using the OGC-Mod2 rule (1) the duplicate endpoint is in the interior of the MultiLineString, so the DE-9IM matrix entry [aB:bI] is 0 and [aB:bB] is F.

  • Using the Endpoint rule (2) the duplicate endpoint is in the boundary of the MultiLineString, so the DE-9IM matrix entry [aB:bI] is F and [aB:bB] is 0.

Code
WITH data AS (SELECT
  'LINESTRING(1 1,3 3)'::geometry AS a_line,
  'MULTILINESTRING((3 3,3 5),(3 3,5 3))'::geometry AS b_multiline
)
SELECT ST_Relate(a_line, b_multiline, 1) AS bnr_mod2,
       ST_Relate(a_line, b_multiline, 2) AS bnr_endpoint
    FROM data;
래스터 출력
bnr_mod2  | bnr_endpoint
-----------+--------------
 FF10F0102 | FF1F00102
Figure
Geometry figure for visual-st-relate-05

제목

ST_RelateMatch — Tests if a DE-9IM Intersection Matrix matches an Intersection Matrix pattern

요약

boolean ST_RelateMatch(text intersectionMatrix, text intersectionMatrixPattern);

설명

Tests if a Dimensionally Extended 9-Intersection Model (DE-9IM) intersectionMatrix value satisfies an intersectionMatrixPattern. Intersection matrix values can be computed by ST_Relate.

For more information refer to 5.1절. “Determining Spatial Relationships”.

GEOS 모듈로 실행

2.0.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT ST_RelateMatch('101202FFF', 'TTTTTTFFF') ;
래스터 출력
t

Patterns for common spatial relationships matched against intersection matrix values, for a line in various positions relative to a polygon

Code
SELECT pat.name AS relationship, pat.val AS pattern,
       mat.name AS position, mat.val AS matrix,
       ST_RelateMatch(mat.val, pat.val) AS match
    FROM (VALUES ( 'Equality', 'T1FF1FFF1' ),
                 ( 'Overlaps', 'T*T***T**' ),
                 ( 'Within', 'T*F**F***' ),
                 ( 'Disjoint', 'FF*FF****' )) AS pat(name, val)
    CROSS JOIN
        (VALUES  ('non-intersecting', 'FF1FF0212'),
                 ('overlapping', '1010F0212'),
                 ('inside', '1FF0FF212')) AS mat(name, val);
래스터 출력
relationship |  pattern  |     position     |  matrix   | match
--------------+-----------+------------------+-----------+-------
 Equality     | T1FF1FFF1 | non-intersecting | FF1FF0212 | f
 Equality     | T1FF1FFF1 | overlapping      | 1010F0212 | f
 Equality     | T1FF1FFF1 | inside           | 1FF0FF212 | f
 Overlaps     | T*T***T** | non-intersecting | FF1FF0212 | f
 Overlaps     | T*T***T** | overlapping      | 1010F0212 | t
 Overlaps     | T*T***T** | inside           | 1FF0FF212 | f
 Within       | T*F**F*** | non-intersecting | FF1FF0212 | f
 Within       | T*F**F*** | overlapping      | 1010F0212 | f
 Within       | T*F**F*** | inside           | 1FF0FF212 | t
 Disjoint     | FF*FF**** | non-intersecting | FF1FF0212 | t
 Disjoint     | FF*FF**** | overlapping      | 1010F0212 | f
 Disjoint     | FF*FF**** | inside           | 1FF0FF212 | f

제목

ST_Touches — Tests if two geometries have at least one point in common, but their interiors do not intersect

요약

boolean ST_Touches(geometry A, geometry B);

설명

Returns TRUE if A and B intersect, but their interiors do not intersect. Equivalently, A and B have at least one point in common, and the common points lie in at least one boundary. For Point/Point inputs the relationship is always FALSE, since points do not have a boundary.

In mathematical terms: ST_Touches(A, B) ⇔ (Int(A) ⋂ Int(B) = ∅) ∧ (A ⋂ B ≠ ∅)

This relationship holds if the DE-9IM Intersection Matrix for the two geometries matches one of:

  • FT*******

  • F**T*****

  • F***T****

[참고]

This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available on the geometries. To avoid using an index, use _ST_Touches instead.

Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.2 // s2.1.13.3

This method implements the SQL/MM specification. SQL-MM 3: 5.1.28

예시

The ST_Touches predicate returns TRUE in the following examples.

Two Polygons touching along a boundary segment.

Code
SELECT ST_Touches(a, b)
FROM (SELECT
  'POLYGON ((10 190,10 70,80 70,80 130,50 160,120 160,120 190,10 190))'::geometry AS a,
  'POLYGON ((80 110,140 140,190 110,180 40,140 10,80 50,80 70,80 110))'::geometry AS b
) AS example;
래스터 출력
t
Figure
Geometry figure for visual-st-touches-01

Two Polygons touching at a boundary point.

Code
SELECT ST_Touches(a, b)
FROM (SELECT
  'POLYGON ((10 190,10 70,80 70,80 130,50 160,120 160,120 190,10 190))'::geometry AS a,
  'POLYGON ((140 140,190 110,180 40,140 10,80 70,140 140))'::geometry AS b
) AS example;
래스터 출력
t
Figure
Geometry figure for visual-st-touches-02

A Polygon and a LineString touching at the line endpoint.

Code
SELECT ST_Touches(a, b)
FROM (SELECT
  'POLYGON ((80 10,50 40,50 90,80 130,140 120,160 70,140 30,80 10))'::geometry AS a,
  'LINESTRING (30 190,180 150,160 70)'::geometry AS b
) AS example;
래스터 출력
t
Figure
Geometry figure for visual-st-touches-03

Two LineStrings touching at their endpoints.

Code
SELECT ST_Touches(a, b)
FROM (SELECT
  'LINESTRING (10 10,60 140,140 190)'::geometry AS a,
  'LINESTRING (140 190,190 10)'::geometry AS b
) AS example;
래스터 출력
t
Figure
Geometry figure for visual-st-touches-04

Two LineStrings touching where an endpoint meets the other line.

Code
SELECT ST_Touches(a, b)
FROM (SELECT
  'LINESTRING (10 10,60 140,140 190)'::geometry AS a,
  'LINESTRING (60 140,190 10)'::geometry AS b
) AS example;
래스터 출력
t
Figure
Geometry figure for visual-st-touches-05

A Point touching a Polygon boundary.

Code
SELECT ST_Touches(a, b)
FROM (SELECT
  'POLYGON ((30 30,10 110,40 190,120 170,180 180,170 100,130 10,30 30))'::geometry AS a,
  'POINT (170 100)'::geometry AS b
) AS example;
래스터 출력
t
Figure
Geometry figure for visual-st-touches-06
Code
SELECT ST_Touches('LINESTRING(0 0,1 1,0 2)'::geometry, 'POINT(1 1)'::geometry);
래스터 출력
f
Figure
Geometry figure for visual-st-touches-07
Code
SELECT ST_Touches('LINESTRING(0 0,1 1,0 2)'::geometry, 'POINT(0 2)'::geometry);
래스터 출력
t
Figure
Geometry figure for visual-st-touches-08

제목

ST_Within — Tests if every point of A lies in B, and their interiors have a point in common

요약

boolean ST_Within(geometry A, geometry B);

설명

Returns TRUE if geometry A is within geometry B. A is within B if and only if all points of A lie inside (i.e. in the interior or boundary of) B (or equivalently, no points of A lie in the exterior of B), and the interiors of A and B have at least one point in common.

For this function to make sense, the source geometries must both be of the same coordinate projection, having the same SRID.

In mathematical terms: ST_Within(A, B) ⇔ (A ⋂ B = A) ∧ (Int(A) ⋂ Int(B) ≠ ∅)

The within relation is reflexive: every geometry is within itself. The relation is antisymmetric: if ST_Within(A,B) = true and ST_Within(B,A) = true, then the two geometries must be topologically equal (ST_Equals(A,B) = true).

ST_Within is the converse of ST_Contains. So, ST_Within(A,B) = ST_Contains(B,A).

[참고]

Because the interiors must have a common point, a subtlety of the definition is that lines and points lying fully in the boundary of polygons or lines are not within the geometry. For further details see Subtleties of OGC Covers, Contains, Within. The ST_CoveredBy predicate provides a more inclusive relationship.

[참고]

This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available on the geometries. To avoid index use, use the function _ST_Within.

GEOS 모듈로 실행

Enhanced: 2.3.0 Enhancement to PIP short-circuit for geometry extended to support MultiPoints with few points. Prior versions only supported point in polygon.

Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION

[중요]

Do not use this function with invalid geometries. You will get unexpected results.

NOTE: this is the "allowable" version that returns a boolean, not an integer.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.2 // s2.1.13.3 - a.Relate(b, 'T*F**F***')

This method implements the SQL/MM specification. SQL-MM 3: 5.1.30

예시

This example defines two concentric circles once in a CTE so the same inputs can be rendered and then reused in related predicate checks.

Code
WITH circles AS (
  SELECT ST_Buffer(center, 20) AS smallc,
         ST_Buffer(center, 40) AS bigc
  FROM (SELECT 'POINT(50 50)'::geometry AS center) AS p
)
SELECT smallc AS small_circle,
       bigc AS big_circle
FROM circles;
래스터 출력
POLYGON((70 50,69.616 46.098,68.478 42.346,66.629 38.889,64.142 35.858,61.111 33.371,57.654 31.522,53.902 30.384,50 30,46.098 30.384,42.346 31.522,38.889 33.371,35.858 35.858,33.371 38.889,31.522 42.346,30.384 46.098,30 50,30.384 53.902,31.522 57.654,33.371 61.111,35.858 64.142,38.889 66.629,42.346 68.478,46.098 69.616,50 70,53.902 69.616,57.654 68.478,61.111 66.629,64.142 64.142,66.629 61.111,68.478 57.654,69.616 53.902,70 50)) | POLYGON((90 50,89.231 42.196,86.955 34.693,83.259 27.777,78.284 21.716,72.223 16.741,65.307 13.045,57.804 10.769,50 10,42.196 10.769,34.693 13.045,27.777 16.741,21.716 21.716,16.741 27.777,13.045 34.693,10.769 42.196,10 50,10.769 57.804,13.045 65.307,16.741 72.223,21.716 78.284,27.777 83.259,34.693 86.955,42.196 89.231,50 90,57.804 89.231,65.307 86.955,72.223 83.259,78.284 78.284,83.259 72.223,86.955 65.307,89.231 57.804,90 50))
Figure
Geometry figure for visual-st-within-01

Using the same circles, ST_Within is reflexive on each circle, false from the larger circle into the smaller one, and true for ST_Union only when the union does not extend beyond the larger circle.

Code
WITH circles AS (
  SELECT ST_Buffer(center, 20) AS smallc,
         ST_Buffer(center, 40) AS bigc
  FROM (SELECT 'POINT(50 50)'::geometry AS center) AS p
)
SELECT
  ST_Within(smallc, smallc) AS smallinsmall,
  ST_Within(smallc, bigc) AS smallinbig,
  ST_Within(bigc, smallc) AS biginsmall,
  ST_Within(ST_Union(smallc, bigc), bigc) AS unioninbig,
  ST_Within(bigc, ST_Union(smallc, bigc)) AS biginunion,
  ST_Equals(bigc, ST_Union(smallc, bigc)) AS bigisunion
FROM circles;
래스터 출력
t | t | f | t | t | t
Figure
Geometry figure for visual-st-within-02

7.11.2. Distance Relationships

  • ST_3DDWithin — Tests if two 3D geometries are within a given 3D distance
  • ST_3DDFullyWithin — Tests if two 3D geometries are entirely within a given 3D distance
  • ST_DFullyWithin — Tests if a geometry is entirely inside a distance of another
  • ST_DWithin — Tests if two geometries are within a given distance
  • ST_PointInsideCircle — Tests if a point geometry is inside a circle defined by a center and radius

제목

ST_3DDWithin — Tests if two 3D geometries are within a given 3D distance

요약

boolean ST_3DDWithin(geometry g1, geometry g2, double precision distance_of_srid);

설명

Returns true if the 3D distance between two geometry values is no larger than distance distance_of_srid. The distance is specified in units defined by the spatial reference system of the geometries. For this function to make sense the source geometries must be in the same coordinate system (have the same SRID).

[참고]

This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available on the geometries.

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

This method implements the SQL/MM specification. SQL-MM ?

2.0.0 버전부터 사용할 수 있습니다.

예시

Compare the same transformed point and line in both 3D and 2D. The 3D test fails because the Z difference matters even though the 2D footprints are close enough.

Code
WITH sample AS (
  SELECT ST_Transform('SRID=4326;POINT(-72.1235 42.3521 4)'::geometry, 2163) AS input_point,
         ST_Transform(
           'SRID=4326;LINESTRING(-72.1260 42.45 15,-72.123 42.1546 20)'::geometry,
           2163
         ) AS input_line
)
SELECT ST_3DDWithin(input_point, input_line, 126.8) AS within_dist_3d,
       ST_DWithin(input_point, input_line, 126.8) AS within_dist_2d,
       input_point AS input_point,
       input_line AS input_line
FROM sample;
래스터 출력
-[ RECORD 1 ]--+----------------------------------------------------------------------------------------------------------------------------------
within_dist_3d | f
within_dist_2d | t
input_point    | POINT Z (-11774128.9 5237160.2 4)
input_line     | LINESTRING Z (-11774339.5 5243556.8 15,-11773706.7 5215256.3 20)

제목

ST_3DDFullyWithin — Tests if two 3D geometries are entirely within a given 3D distance

요약

boolean ST_3DDFullyWithin(geometry g1, geometry g2, double precision distance);

설명

Returns true if the 3D geometries are fully within the specified distance of one another. The distance is specified in units defined by the spatial reference system of the geometries. For this function to make sense, the source geometries must both be of the same coordinate projection, having the same SRID.

[참고]

This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available on the geometries.

2.0.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

예시

This example compares distance-within predicates in 2D and 3D. The point is distance-within the line in 3D, but the full 3D line is not within the same distance of the point.

Code
WITH data AS (
  SELECT
    'POINT(1 1 2)'::geometry AS geom_a,
    'LINESTRING(1 5 2,2 7 20,1 9 100,14 12 3)'::geometry AS geom_b
)
SELECT
  ST_3DDFullyWithin(geom_a, geom_b, 10) AS d3dfullywithin10,
  ST_3DDWithin(geom_a, geom_b, 10) AS d3dwithin10,
  ST_DFullyWithin(geom_a, geom_b, 20) AS d2dfullywithin20,
  ST_3DDFullyWithin(geom_a, geom_b, 20) AS d3dfullywithin20
FROM data;
래스터 출력
d3dfullywithin10 | d3dwithin10 | d2dfullywithin20 | d3dfullywithin20
------------------+-------------+------------------+------------------
 f                | t           | t                | f 
Figure
Geometry figure for visual-st-3ddfullywithin-01

제목

ST_DFullyWithin — Tests if a geometry is entirely inside a distance of another

요약

boolean ST_DFullyWithin(geometry g1, geometry g2, double precision distance);

설명

Returns true if g2 is entirely within distance of g1. Visually, the condition is true if g2 is contained within a distance buffer of g1. The distance is specified in units defined by the spatial reference system of the geometries.

[참고]

This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available on the geometries.

1.5.0 버전부터 사용할 수 있습니다.

Changed: 3.5.0 : the logic behind the function now uses a test of containment within a buffer, rather than the ST_MaxDistance algorithm. Results will differ from prior versions, but should be closer to user expectations.

예시

Code
SELECT
    ST_DFullyWithin(geom_a, geom_b, 10) AS DFullyWithin10,
    ST_DWithin(geom_a, geom_b, 10) AS DWithin10,
    ST_DFullyWithin(geom_a, geom_b, 20) AS DFullyWithin20
FROM (VALUES
    ('POINT(1 1)'::geometry, 'LINESTRING(1 5,2 7,1 9,14 12)'::geometry)
    ) AS v(geom_a, geom_b)
래스터 출력
dfullywithin10 | dwithin10 | dfullywithin20
----------------+-----------+----------------
 f              | t         | t
Figure
Geometry figure for visual-st-dfullywithin-01

제목

ST_DWithin — Tests if two geometries are within a given distance

요약

boolean ST_DWithin(geometry g1, geometry g2, double precision distance_of_srid);

boolean ST_DWithin(geography gg1, geography gg2, double precision distance_meters, boolean use_spheroid = true);

설명

Returns true if the geometries are within a given distance

For geometry: The distance is specified in units defined by the spatial reference system of the geometries. For this function to make sense, the source geometries must be in the same coordinate system (have the same SRID).

For geography: units are in meters and distance measurement defaults to use_spheroid = true. For faster evaluation use use_spheroid = false to measure on the sphere.

[참고]

Use ST_3DDWithin for 3D geometries.

[참고]

This function call includes a bounding box comparison that makes use of any indexes that are available on the geometries.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1.

Availability: 1.5.0 support for geography was introduced

Enhanced: 2.1.0 improved speed for geography. See Making Geography faster for details.

Enhanced: 2.1.0 support for curved geometries was introduced.

Prior to 1.3, ST_Expand was commonly used in conjunction with && and ST_Distance to test for distance, and in pre-1.3.4 this function used that logic. From 1.3.4, ST_DWithin uses a faster short-circuit distance function.

예시

This self-contained geometry example keeps the compared shapes visible while also returning the boolean results.

Code
WITH sample AS (
  SELECT ST_Buffer('POINT(100 90)'::geometry, 50, 'quad_segs=2') AS coverage,
         ST_Point(120, 120) AS inside_pt,
         ST_Point(170, 90) AS outside_pt
)
SELECT ST_DWithin(coverage, inside_pt, 0) AS inside_now,
       ST_DWithin(coverage, outside_pt, 10) AS outside_within_10,
       coverage AS coverage_geom,
       inside_pt AS inside_geom,
       outside_pt AS outside_geom
FROM sample;
래스터 출력
-[ RECORD 1 ]-----
inside_now        | t
outside_within_10 | f
coverage_geom     | POLYGON((150 90,135 55,100 40,65 55,50 90,65 125,100 140,135 125,150 90))
inside_geom       | POINT(120 120)
outside_geom      | POINT(170 90)
Figure
Geometry figure for visual-st-dwithin-01

Find the nearest hospital to each school. That is within 3000 units of the school. We do an ST_DWithin search to utilize indexes to limit our search list. That the non-indexable ST_Distance needs to process. If the units of the spatial reference is meters then units would be meters.

Code
SELECT DISTINCT ON (s.gid) s.gid, s.school_name, s.geom, h.hospital_name
  FROM schools s
    LEFT JOIN hospitals h ON ST_DWithin(s.geom, h.geom, 3000)
  ORDER BY s.gid, ST_Distance(s.geom, h.geom);

The schools with no close hospitals. Find all schools with no hospital within 3000 units away from the school. Units are in units of spatial reference (for example meters, feet, or degrees).

Code
SELECT s.gid, s.school_name
  FROM schools s
    LEFT JOIN hospitals h ON ST_DWithin(s.geom, h.geom, 3000)
  WHERE h.gid IS NULL;

Find locations more than 3000 units away from their nearest hospital. Use NOT EXISTS so that a location is returned only when no nearby hospital exists.

Code
SELECT l.location_name
  FROM locations l
  WHERE NOT EXISTS (
    SELECT 1
    FROM hospitals h
    WHERE ST_DWithin(l.geom, h.geom, 3000)
  );

Find broadcasting towers that a receiver with limited range can receive. Data is geometry in Spherical Mercator (SRID=3857), ranges are approximate.

Code
CREATE INDEX ON broadcasting_towers USING gist (geom);
CREATE INDEX ON broadcasting_towers USING gist (ST_Expand(geom, sending_range));

Query towers that a 4-kilometer receiver in Minsk Hackerspace can get. Note: two conditions are required because the shorter LEAST(b.sending_range, 4000) will not use an index.

Code
SELECT b.tower_id, b.geom
  FROM broadcasting_towers b
  WHERE ST_DWithin(b.geom, 'SRID=3857;POINT(3072163.4 7159374.1)', 4000)
    AND ST_DWithin(b.geom, 'SRID=3857;POINT(3072163.4 7159374.1)', b.sending_range);

제목

ST_PointInsideCircle — Tests if a point geometry is inside a circle defined by a center and radius

요약

boolean ST_PointInsideCircle(geometry a_point, float center_x, float center_y, float radius);

설명

Returns true if the geometry is a point and is inside the circle with center center_x,center_y and radius radius.

[주의]

Does not use spatial indexes. Use ST_DWithin instead.

Availability: 1.2

Changed: 2.2.0 In prior versions this was called ST_Point_Inside_Circle

예시

Code
SELECT ST_PointInsideCircle(ST_Point(1, 2), 0.5, 2, 3);
래스터 출력
t
Figure
Geometry figure for visual-st-pointinsidecircle-01

7.12. Measurement Functions

초록

These functions compute measurements of distance, area and angles. There are also functions to compute geometry values determined by measurements.

  • ST_Area — 도형의 기하학적 중심을 반환합니다.
  • ST_Azimuth — 두 도형 사이의 2차원 최단 라인을 반환합니다.
  • ST_Angle — 두 도형 사이의 3차원 최장(longest) 라인을 반환합니다.
  • ST_ClosestPoint — Returns the 2D point on g1 that is closest to g2. This is the first point of the shortest line from one geometry to the other.
  • ST_3DClosestPoint — g2에 가장 가까운 g1 상에 있는 3차원 포인트를 반환합니다. 해당 포인트는 3D 최단 라인의 첫 번째 포인트입니다.
  • ST_Distance — 두 도형 사이의 3차원 최장(longest) 라인을 반환합니다.
  • ST_3DDistance — 도형 유형에 대해, 두 도형 사이의 (SRS에 기반한) 3차원 데카르트 최단 거리를 투영 단위로 반환합니다.
  • ST_DistanceSphere — 특정 회전타원체가 주어진 두 경위도 도형 사이의 최단 거리를 반환합니다. PostGIS 1.5 미만 버전은 포인트만 지원했습니다.
  • ST_DistanceSpheroid — 특정 회전타원체가 주어진 두 경위도 도형 사이의 최단 거리를 반환합니다. PostGIS 1.5 미만 버전은 포인트만 지원했습니다.
  • ST_FrechetDistance — 두 도형 사이의 3차원 최단(shortest) 라인을 반환합니다.
  • ST_HausdorffDistance — 두 도형 사이의 3차원 최단(shortest) 라인을 반환합니다.
  • ST_Length — 도형의 기하학적 중심을 반환합니다.
  • ST_Length2D — 도형이 라인스트링 또는 멀티라인스트링일 경우 도형의 2차원 길이를 반환합니다. 이 함수는 ST_Length 와 동일합니다.
  • ST_3DLength — 도형의 기하학적 중심을 반환합니다.
  • ST_LengthSpheroid — 도형의 기하학적 중심을 반환합니다.
  • ST_LongestLine — 두 도형 사이의 3차원 최장(longest) 라인을 반환합니다.
  • ST_3DLongestLine — 두 도형 사이의 3차원 최장(longest) 라인을 반환합니다.
  • ST_MaxDistance — 두 도형 사이의 2차원 최장 거리를 투영 단위로 반환합니다.
  • ST_3DMaxDistance — 도형 유형에 대해, 두 도형 사이의 (SRS에 기반한) 3차원 데카르트 최장 거리를 투영 단위로 반환합니다.
  • ST_MinimumClearance — 도형의 튼튼함(robustness)의 척도인 도형의 최소 여유(clearance)를 반환합니다.
  • ST_MinimumClearanceLine — 포인트 2개로 이루어진, 도형의 최소 여유를 나타내는 라인스트링을 반환합니다.
  • ST_Perimeter — Returns the length of the boundary of a polygonal geometry or geography.
  • ST_Perimeter2D — Returns the 2D perimeter of a polygonal geometry. Alias for ST_Perimeter.
  • ST_3DPerimeter — 도형의 기하학적 중심을 반환합니다.
  • ST_ShortestLine — 두 도형 사이의 2차원 최단 라인을 반환합니다.
  • ST_3DShortestLine — 두 도형 사이의 3차원 최단(shortest) 라인을 반환합니다.

제목

ST_Area — 도형의 기하학적 중심을 반환합니다.

요약

float ST_Area(geometry g1);

float ST_Area(geography geog, boolean use_spheroid = true);

설명

도형이 폴리곤이나 멀티폴리곤일 경우 표면의 면적을 - ST_Surface 또는 ST_MultiSurface 함수의 면적 측정값을 - 반환합니다. 도형 유형의 경우, SRID가 지정한 단위로 2차원 데카르트 면적을 구합니다. 지리형 유형의 경우, 평방미터 단위로 곡면(curved surface)의 면적을 구합니다. 구체의 면적에 대해 덜 정확하지만 더 빠르게 측정하려면, ST_Area(geog,false) 함수를 이용하십시오.

개선 사항: 2.0.0 버전부터 2차원 다면체 표면(polyhedral surface)을 지원합니다.

개선 사항: 2.2.0 버전부터 회전타원체 측정시 정확도와 강력함을 향상시키기 위해 GeographicLib을 이용합니다. 이 새 기능의 장점을 취하려면 Proj 4.9.0 이상 버전이 필요합니다.

Changed: 3.0.0 - does not depend on SFCGAL anymore.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1.

This method implements the SQL/MM specification. SQL-MM 3: 8.1.2, 9.5.3

This function supports Polyhedral surfaces.

[참고]

다면체 표면의 경우, (2.5차원이 아니라) 2차원 다면체 표면만 지원합니다. 2.5차원일 경우 0이 아닌(non-zero) 답을 내놓을 수도 있지만, XY 평면상에 완벽하게 놓이는 면들의 면적만 반환하는 것입니다.

예시

매사추세츠 토지의 부지(plot)에 대해 평방피트 단위로 면적을 반환하고, 이에 환산값을 곱해서 평방미터 면적을 구합니다. EPSG:2249가 매사추세츠 주 피트 단위 평면이기 때문에 평방피트 단위의 값을 반환한다는 점에 주의하십시오.

Code
SELECT ST_Area(geom) AS sqft,
       ST_Area(geom) * 0.3048 ^ 2 AS sqm
FROM (
  SELECT 'SRID=2249;POLYGON((743238 2967416,743238 2967450,
          743265 2967450,743265.625 2967416,743238 2967416))'::geometry AS geom
) AS subquery;
래스터 출력
sqft   |     sqm
--------+-------------
928.625 | 86.27208552
Figure
Geometry figure for visual-st-area-01

Return area square feet and transform to Massachusetts state plane meters (EPSG:26986) to get square meters. Note this is in square feet because 2249 is Massachusetts State Plane Feet and transformed area is in square meters since EPSG:26986 is state plane Massachusetts meters.

Code
SELECT ST_Area(geom) AS sqft,
       round(ST_Area(ST_Transform(geom, 26986))::numeric, 6) AS sqm
FROM (
  SELECT 'SRID=2249;POLYGON((743238 2967416,743238 2967450,
          743265 2967450,743265.625 2967416,743238 2967416))'::geometry AS geom
) AS subquery;
래스터 출력
sqft   |    sqm
--------+-----------
928.625 | 86.272431
Figure
Geometry figure for visual-st-area-02

지리형 데이터 유형을 이용해서 평방피트 및 평방미터 면적을 반환합니다. 도형을 지리형으로 변환시킨다는 점에 주의하십시오(변환하기 전에 사용자 도형의 투영체가 WGS84 4326 경위도 좌표계인지 확인해야 합니다). 지리형은 항상 미터 단위로 측정됩니다. 이 예시는 그저 비교해보기 위한 보여주기에 불과합니다. 일반적으로 이미 사용자 테이블에 지리형 데이터 유형으로 저장되어 있을 겁니다.

Code
SELECT round((ST_Area(geog) / 0.3048 ^ 2)::numeric, 2) AS sqft_spheroid,
       round((ST_Area(geog, false) / 0.3048 ^ 2)::numeric, 2) AS sqft_sphere,
       round(ST_Area(geog)::numeric, 2) AS sqm_spheroid
FROM (
  SELECT ST_Transform(
           'SRID=2249;POLYGON((743238 2967416,743238 2967450,
           743265 2967450,743265.625 2967416,743238 2967416))'::geometry,
           4326
         )::geography AS geog
) AS subquery;
래스터 출력
sqft_spheroid | sqft_sphere | sqm_spheroid
----------------+-------------+--------------
         928.68 |      926.61 |        86.28

If your data is in geography already:

Code
SELECT ST_Area(geog) / 0.3048 ^ 2 AS sqft,
               ST_Area(the_geog) AS sqm
        FROM somegeogtable;

제목

ST_Azimuth — 두 도형 사이의 2차원 최단 라인을 반환합니다.

요약

float ST_Azimuth(geometry origin, geometry target);

float ST_Azimuth(geography origin, geography target);

설명

Returns the azimuth in radians of the target point from the origin point, or NULL if the two points are coincident. The azimuth angle is a positive clockwise angle referenced from the positive Y axis (geometry) or the North meridian (geography): North = 0; Northeast = π/4; East = π/2; Southeast = 3π/4; South = π; Southwest 5π/4; West = 3π/2; Northwest = 7π/4.

For the geography type, the azimuth solution is known as the inverse geodesic problem.

The azimuth is a mathematical concept defined as the angle between a reference vector and a point, with angular units in radians. The result value in radians can be converted to degrees using the PostgreSQL function degrees().

For offsetting lines relative to their direction, use ST_OffsetCurve. For projecting a point by distance and bearing, use ST_Project.

1.1.0 버전부터 사용할 수 있습니다.

개선 사항: 2.0.0 버전부터 지리형을 지원합니다.

개선 사항: 2.2.0 버전부터 회전타원체 측정시 정확도와 강력함을 향상시키기 위해 GeographicLib을 이용합니다. 이 새 기능의 장점을 취하려면 Proj 4.9.0 이상 버전이 필요합니다.

예시

도 단위의 도형 방위각

Code
SELECT degrees(ST_Azimuth(ST_Point(25, 45), ST_Point(75, 100))) AS degA_B,
       degrees(ST_Azimuth(ST_Point(75, 100), ST_Point(25, 45) )) AS degB_A;
래스터 출력
dega_b       |     degb_a
------------------+------------------
42.27368900609371 | 222.27368900609372

Compass direction labels can be computed from the azimuth.

Code
WITH directions(deg) AS (VALUES
  (0), (45), (90), (135), (180), (225), (270), (315)
),
bearings AS (
  SELECT deg,
         degrees(ST_Azimuth(ST_Point(0, 0),
                            ST_MakePoint(sin(radians(deg)),
                                         cos(radians(deg))))) AS azimuth
  FROM directions
)
SELECT deg,
       round(azimuth::numeric, 1) AS azimuth,
       (ARRAY['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW', 'N'])
         [floor((azimuth + 22.5) / 45)::int + 1] AS direction
FROM bearings
ORDER BY deg;
래스터 출력
deg | azimuth | direction
-----+---------+-----------
   0 |     0.0 | N
  45 |    45.0 | NE
  90 |    90.0 | E
 135 |   135.0 | SE
 180 |   180.0 | S
 225 |   225.0 | SW
 270 |   270.0 | W
 315 |   315.0 | NW

Azimuth from Point(25, 45) to Point(75, 100), shown against the positive Y axis (north).

Code
WITH points AS (
  SELECT 'POINT(25 45)'::geometry AS origin,
         'POINT(75 100)'::geometry AS target
)
SELECT round(degrees(ST_Azimuth(origin, target))::numeric, 6) AS degrees,
       ST_MakeLine(origin, ST_Translate(origin, 0, 105)) AS north,
       ST_MakeLine(origin, target) AS direction
FROM points;
래스터 출력
42.273689 | LINESTRING(25 45,25 150) | LINESTRING(25 45,75 100)
Figure
Geometry figure for visual-st-azimuth-03

Reverse azimuth from Point(75, 100) to Point(25, 45).

Code
WITH points AS (
  SELECT 'POINT(75 100)'::geometry AS origin,
         'POINT(25 45)'::geometry AS target
)
SELECT round(degrees(ST_Azimuth(origin, target))::numeric, 6) AS degrees,
       ST_MakeLine(origin, ST_Translate(origin, 0, 90)) AS north,
       ST_MakeLine(origin, target) AS direction
FROM points;
래스터 출력
222.273689 | LINESTRING(75 100,75 190) | LINESTRING(75 100,25 45)
Figure
Geometry figure for visual-st-azimuth-04

제목

ST_Angle — 두 도형 사이의 3차원 최장(longest) 라인을 반환합니다.

요약

float ST_Angle(geometry point1, geometry point2, geometry point3, geometry point4);

float ST_Angle(geometry line1, geometry line2);

설명

두 도형 사이의 3차원 최장(longest) 라인을 반환합니다.

Variant 1: computes the angle enclosed by the points P1-P2-P3. If a 4th point provided computes the angle points P1-P2 and P3-P4

Variant 2: computes the angle between two vectors S1-E1 and S2-E2, defined by the start and end points of the input lines

방위각은 참조 평면과 포인트 사이의 라디안 단위의 각도로 정의되는 수학적 개념입니다. PostgreSQL 내장 함수인 degrees()를 써서 라디안 단위를 도 단위로 변환할 수 있습니다. 예시 코드를 확인해보십시오.

Note that ST_Angle(P1,P2,P3) = ST_Angle(P2,P1,P2,P3).

Availability: 2.5.0

예시

폴리곤과 폴리곤 사이의 최장 라인

Code
SELECT degrees(ST_Angle('POINT(0 0)', 'POINT(10 10)', 'POINT(20 0)'));
래스터 출력
270
Figure
Geometry figure for visual-st-angle-01

Angle between vectors defined by four points

Code
SELECT degrees(ST_Angle('POINT (10 10)', 'POINT (0 0)', 'POINT(90 90)', 'POINT (100 80)'));
래스터 출력
269.9999999999999
Figure
Geometry figure for visual-st-angle-02

Angle between vectors defined by the start and end points of lines

Code
SELECT degrees(ST_Angle('LINESTRING(0 0,0.3 0.7,1 1)', 'LINESTRING(0 0,0.2 0.5,1 0)'));
래스터 출력
45
Figure
Geometry figure for visual-st-angle-03

제목

ST_ClosestPoint — Returns the 2D point on g1 that is closest to g2. This is the first point of the shortest line from one geometry to the other.

요약

geometry ST_ClosestPoint(geometry geom1, geometry geom2);

geography ST_ClosestPoint(geography geom1, geography geom2, boolean use_spheroid = true);

설명

Returns the 2-dimensional point on geom1 that is closest to geom2. This is the first point of the shortest line between the geometries (as computed by ST_ShortestLine).

[참고]

3차원 도형의 경우엔 ST_3DClosestPoint 함수를 이용하는 편이 좋습니다.

Enhanced: 3.4.0 - Support for geography.

1.5.0 버전부터 사용할 수 있습니다.

예시

The closest point for a Point and a LineString is the point itself. The closest point for a LineString and a Point is a point on the line.

Code
SELECT ST_ClosestPoint(pt, line) AS cp_pt_line, ST_ClosestPoint(line, pt) AS cp_line_pt
    FROM (SELECT 'POINT (160 40)'::geometry AS pt,
                 'LINESTRING (10 30,50 50,30 110,70 90,180 140,130 190)'::geometry AS line ) AS t;
래스터 출력
cp_pt_line   |                cp_line_pt
----------------+------------------------------------------
 POINT(160 40)  | POINT(125.75342465753425 115.34246575342466)
Figure
Geometry figure for visual-st-closestpoint-01

Find the closest point on polygon A to polygon B.

Code
WITH source AS (
  SELECT 'POLYGON ((190 150,20 10,160 70,190 150))'::geometry AS a,
         ST_Buffer('POINT(80 160)'::geometry, 30) AS b
)
SELECT b AS polygon_b,
       ST_ClosestPoint(a, b) AS closest_point
FROM source;
래스터 출력
POLYGON((110 160,109.424 154.147,107.716 148.519,104.944 143.333,101.213 138.787,96.667 135.056,91.481 132.284,85.853 130.576,80 130,74.147 130.576,68.519 132.284,63.333 135.056,58.787 138.787,55.056 143.333,52.284 148.519,50.576 154.147,50 160,50.576 165.853,52.284 171.481,55.056 176.667,58.787 181.213,63.333 184.944,68.519 187.716,74.147 189.424,80 190,85.853 189.424,91.481 187.716,96.667 184.944,101.213 181.213,104.944 176.667,107.716 171.481,109.424 165.853,110 160)) | POINT(131.59149149528952 101.89887534906195)
Figure
Geometry figure for visual-st-closestpoint-02

제목

ST_3DClosestPoint — g2에 가장 가까운 g1 상에 있는 3차원 포인트를 반환합니다. 해당 포인트는 3D 최단 라인의 첫 번째 포인트입니다.

요약

geometry ST_3DClosestPoint(geometry g1, geometry g2);

설명

g2에 가장 가까운 g1 상에 있는 3차원 포인트를 반환합니다. 해당 포인트는 3D 최단 라인의 첫 번째 포인트입니다. 3D 최단 라인의 3D 길이가 3D 거리입니다.

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

2.0.0 버전부터 사용할 수 있습니다.

변경 사항: 2.2.0 버전부터 2D 도형 두 개를 입력할 경우, (존재하지 않는 Z을 0으로 가정하는 예전 습성 대신) 2D 포인트를 반환합니다. 2D 및 3D의 경우, 더 이상 Z가 없을 때 Z를 0으로 가정하지 않습니다.

예시

Compare the 3D closest point to the 2D closest point for a LineString and a Point.

Code
WITH input AS (
  SELECT 'POINT(100 100 30)'::geometry AS pt,
         'LINESTRING (20 80 20,98 190 1,110 180 3,50 75 1000)'::geometry AS line
)
SELECT ST_3DClosestPoint(line, pt) AS cp3d_line_pt,
       ST_ClosestPoint(line, pt) AS cp2d_line_pt
FROM input;
래스터 출력
-[ RECORD 1 ]--+--------------------------------------------------------
cp3d_line_pt   | POINT(54.69937988676193 128.93502291722837 11.547586950660556)
cp2d_line_pt   | POINT(73.07692307692307 115.38461538461539)
Figure
Geometry figure for visual-st-3dclosestpoint-01

Compare the 3D closest point to the 2D closest point for a LineString and a MultiPoint.

Code
WITH input AS (
  SELECT 'MULTIPOINT(100 100 30,50 74 1000)'::geometry AS pt,
         'LINESTRING (20 80 20,98 190 1,110 180 3,50 75 900)'::geometry AS line
)
SELECT ST_3DClosestPoint(line, pt) AS cp3d_line_pt,
       ST_ClosestPoint(line, pt) AS cp2d_line_pt
FROM input;
래스터 출력
-[ RECORD 1 ]--+--------------------------------------------------------
cp3d_line_pt   | POINT(54.69937988676193 128.93502291722837 11.547586950660556)
cp2d_line_pt   | POINT(50 75)
Figure
Geometry figure for visual-st-3dclosestpoint-02

Compare the 3D closest point to the 2D closest point for a Polygon and a MultiLineString.

Code
WITH input AS (
  SELECT ST_GeomFromEWKT(
           'POLYGON((175 150 5,20 40 5,35 45 5,50 60 5,100 100 5,175 150 5))'
         ) AS poly,
         ST_GeomFromEWKT(
           'MULTILINESTRING((175 155 2,20 40 20,50 60 -2,125 100 1,175 155 1),
                            (1 10 2,5 20 1))'
         ) AS mline
)
SELECT ST_3DClosestPoint(poly, mline) AS cp3d,
       ST_ClosestPoint(poly, mline) AS cp2d
FROM input;
래스터 출력
-[ RECORD 1 ]--+---------------------------------------
cp3d           | POINT(40.45454545454545 53.63636363636364 5)
cp2d           | POINT(20 40)
Figure
Geometry figure for visual-st-3dclosestpoint-03

제목

ST_Distance — 두 도형 사이의 3차원 최장(longest) 라인을 반환합니다.

요약

float ST_Distance(geometry g1, geometry g2);

float ST_Distance(geography geog1, geography geog2, boolean use_spheroid = true);

설명

도형 유형에 대해, 두 도형 사이의 3차원 데카르트 최단 거리를 두 도형의 투영 단위(SRS 단위)로 반환합니다.

For geography types defaults to return the minimum geodesic distance between two geographies in meters, compute on the spheroid determined by the SRID. If use_spheroid is false, a faster spherical calculation is used.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1.

This method implements the SQL/MM specification. SQL-MM 3: 5.1.23

This method supports Circular Strings and Curves.

1.5.0 버전부터 지리형을 지원합니다. 대용량 또는 수많은 꼭짓점을 가진 도형을 더 잘 처리하기 위해 평면에 대한 속도를 향상시켰습니다.

Enhanced: 2.1.0 improved speed for geography. See Making Geography faster for details.

개선 사항: 2.1.0 버전부터 만곡 도형을 지원하기 시작했습니다.

개선 사항: 2.2.0 버전부터 회전타원체 측정시 정확도와 강력함을 향상시키기 위해 GeographicLib을 이용합니다. 이 새 기능의 장점을 취하려면 Proj 4.9.0 이상 버전이 필요합니다.

Changed: 3.0.0 - does not depend on SFCGAL anymore.

도형 예시

Geometry example - units in planar degrees 4326 is WGS 84 long lat, units are degrees.

Code
SELECT ST_Distance(
'SRID=4326;POINT(-72.1235 42.3521)'::geometry,
'SRID=4326;LINESTRING(-72.1260 42.45,-72.123 42.1546)'::geometry );
래스터 출력
0.00150567726382282

Geometry example - units in meters (SRID: 3857, proportional to pixels on popular web maps). Although the value is off, nearby ones can be compared correctly, which makes it a good choice for algorithms like KNN or KMeans.

Code
SELECT ST_Distance(
ST_Transform('SRID=4326;POINT(-72.1235 42.3521)'::geometry, 3857),
ST_Transform('SRID=4326;LINESTRING(-72.1260 42.45,-72.123 42.1546)'::geometry, 3857) );
래스터 출력
167.441410065196

Geometry example - units in meters (SRID: 3857 as above, but corrected by cos(lat) to account for distortion)

Code
SELECT ST_Distance(
ST_Transform('SRID=4326;POINT(-72.1235 42.3521)'::geometry, 3857),
ST_Transform('SRID=4326;LINESTRING(-72.1260 42.45,-72.123 42.1546)'::geometry, 3857)
        ) * cosd(42.3521);
래스터 출력
123.742351254151

Geometry example - units in meters (SRID: 26986 Massachusetts state plane meters) (most accurate for Massachusetts)

Code
SELECT ST_Distance(
ST_Transform('SRID=4326;POINT(-72.1235 42.3521)'::geometry, 26986),
ST_Transform('SRID=4326;LINESTRING(-72.1260 42.45,-72.123 42.1546)'::geometry, 26986) );
래스터 출력
123.797937878454

Geometry example - units in meters (SRID: 2163 US National Atlas Equal area) (least accurate)

Code
SELECT ST_Distance(
ST_Transform('SRID=4326;POINT(-72.1235 42.3521)'::geometry, 2163),
ST_Transform('SRID=4326;LINESTRING(-72.1260 42.45,-72.123 42.1546)'::geometry, 2163) );
래스터 출력
126.664256056812

지리형 예시

Same as geometry example but note units in meters - use sphere for slightly faster and less accurate computation.

Code
SELECT ST_Distance(gg1, gg2) As spheroid_dist, ST_Distance(gg1, gg2, false) As sphere_dist
FROM (SELECT
    'SRID=4326;POINT(-72.1235 42.3521)'::geography as gg1,
    'SRID=4326;LINESTRING(-72.1260 42.45,-72.123 42.1546)'::geography as gg2
    ) As foo  ;
래스터 출력
spheroid_dist   |   sphere_dist
------------------+------------------
 123.802076746848 | 123.475736916397

제목

ST_3DDistance — 도형 유형에 대해, 두 도형 사이의 (SRS에 기반한) 3차원 데카르트 최단 거리를 투영 단위로 반환합니다.

요약

float ST_3DDistance(geometry g1, geometry g2);

설명

도형 유형에 대해, 두 도형 사이의 3차원 데카르트 최단 거리를 두 도형의 투영 단위(SRS 단위)로 반환합니다.

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

This method implements the SQL/MM specification. SQL-MM ISO/IEC 13249-3

2.0.0 버전부터 사용할 수 있습니다.

변경 사항: 2.2.0 버전부터, 2D 및 3D의 경우 더 이상 Z가 없을 때 Z를 0으로 가정하지 않습니다.

Changed: 3.0.0 - SFCGAL version removed

예시

Geometry example - units in meters (SRID: 2163 US National Atlas Equal area) (3D point and line compared 2D point and line) Note that currently no vertical datum support so Z is not transformed and assumed to be same units as final.

Code
SELECT ST_3DDistance(
            ST_Transform('SRID=4326;POINT(-72.1235 42.3521 4)'::geometry, 2163),
                ST_Transform('SRID=4326;LINESTRING(-72.1260 42.45 15,-72.123 42.1546 20)'::geometry, 2163)
            ) As dist_3d,
            ST_Distance(
                ST_Transform('SRID=4326;POINT(-72.1235 42.3521)'::geometry, 2163),
                ST_Transform('SRID=4326;LINESTRING(-72.1260 42.45,-72.123 42.1546)'::geometry, 2163)
            ) As dist_2d;
래스터 출력
dist_3d      |     dist_2d
------------------+-----------------
 127.295059324629 | 126.66425605671

Multilinestring and polygon both 3D and 2D distance. Same example as 3D closest point example.

Code
SELECT ST_3DDistance(poly, mline) As dist3d,
    ST_Distance(poly, mline) As dist2d
        FROM (SELECT  'POLYGON((175 150 5,20 40 5,35 45 5,50 60 5,100 100 5,175 150 5))'::geometry as poly,
               'MULTILINESTRING((175 155 2,20 40 20,50 60 -2,125 100 1,175 155 1),(1 10 2,5 20 1))'::geometry as mline) as foo;
래스터 출력
dist3d       | dist2d
-------------------+--------
                 0 |      0
Figure
Geometry figure for visual-st-3ddistance-02

제목

ST_DistanceSphere — 특정 회전타원체가 주어진 두 경위도 도형 사이의 최단 거리를 반환합니다. PostGIS 1.5 미만 버전은 포인트만 지원했습니다.

요약

float ST_DistanceSphere(geometry geomlonlatA, geometry geomlonlatB, float8 radius=6371008);

설명

경위도 포인트 2개 사이의 최단 거리를 미터 단위로 반환합니다. SRID가 정의하는 회전타원체에서 추출한 반경을 가진 지구 구체를 이용합니다. ST_DistanceSpheroid 보다는 처리 속도가 빠르지만, 정확도는 떨어집니다. PostGIS 1.5 미만 버전에서는 포인트에 대해서만 구현돼 있었습니다.

1.5 버전부터 포인트가 아닌 다른 도형 유형을 지원하기 시작했습니다. 1.5 미만 버전에서는 포인트에 대해서만 구현돼 있었습니다.

변경 사항: 2.2.0 미만 버전에서는 ST_Distance_Sphere라는 명칭이었습니다.

예시

Code
WITH sample AS (
    SELECT
        ST_GeomFromText('LINESTRING(-118.584 38.374,-118.583 38.5)', 4326) AS geom,
        ST_GeomFromText('POINT(-118 38)', 4326) AS pt
)
SELECT
    round(ST_DistanceSphere(ST_Centroid(geom), pt)::numeric, 2) AS dist_meters,
    round(ST_Distance(
        ST_Transform(ST_Centroid(geom), 32611),
        ST_Transform(pt, 32611)
    )::numeric, 2) AS dist_utm11_meters,
    round(ST_Distance(ST_Centroid(geom), pt)::numeric, 5) AS dist_degrees,
    round(ST_Distance(
        ST_Transform(geom, 32611),
        ST_Transform(pt, 32611)
    )::numeric, 2) AS min_dist_line_point_meters
FROM sample;
래스터 출력
dist_meters | dist_utm11_meters | dist_degrees | min_dist_line_point_meters
-------------+-------------------+--------------+----------------------------
    70424.71 |          70438.00 |      0.72900 |                   65871.18
Figure
Geometry figure for visual-st-distancesphere-01

제목

ST_DistanceSpheroid — 특정 회전타원체가 주어진 두 경위도 도형 사이의 최단 거리를 반환합니다. PostGIS 1.5 미만 버전은 포인트만 지원했습니다.

요약

float ST_DistanceSpheroid(geometry geomlonlatA, geometry geomlonlatB, spheroid measurement_spheroid=WGS84);

설명

특정 회전타원체가 주어진 두 경위도 도형 사이의 최단 거리를 반환합니다. 주어진 회전타원체에 대한 설명은 ST_LengthSpheroid 를 참조하십시오. PostGIS 1.5 미만 버전은 포인트만 지원했습니다.

[참고]

현재 이 함수는 도형의 SRID를 찾아보지 않고 주어진 회전타원체의 좌표로 쓰여 있다고 가정할 것입니다. 이 함수의 이전 버전은 포인트만 지원했습니다.

1.5 버전부터 포인트가 아닌 다른 도형 유형을 지원하기 시작했습니다. 1.5 미만 버전에서는 포인트에 대해서만 구현돼 있었습니다.

변경 사항: 2.2.0 미만 버전에서는 ST_Distance_Spheroid라는 명칭이었습니다.

예시

Code
WITH input AS (
  SELECT ST_Centroid(
           ST_GeomFromText(
             'LINESTRING(-118.584 38.374,-118.583 38.5)', 4326
           )
         ) AS source,
         ST_GeomFromText('POINT(-118 38)', 4326) AS target
)
SELECT round(
         ST_DistanceSpheroid(
           source,
           target,
           'SPHEROID["WGS 84",6378137,298.257223563]'
         )::numeric,
         2
       ) AS dist_meters_spheroid,
       round(ST_DistanceSphere(source, target)::numeric, 2)
         AS dist_meters_sphere,
       round(
         ST_Distance(
           ST_Transform(source, 32611),
           ST_Transform(target, 32611)
         )::numeric,
         2
       ) AS dist_utm11_meters
FROM input;
래스터 출력
dist_meters_spheroid | dist_meters_sphere | dist_utm11_meters
----------------------+--------------------+-------------------
             70454.92 |           70424.71 |          70438.00
Figure
Geometry figure for visual-st-distance-spheroid-01

제목

ST_FrechetDistance — 두 도형 사이의 3차원 최단(shortest) 라인을 반환합니다.

요약

float ST_FrechetDistance(geometry g1, geometry g2, float densifyFrac = -1);

설명

Implements algorithm for computing the Fréchet distance restricted to discrete points for both geometries, based on Computing Discrete Fréchet Distance. The Fréchet distance is a measure of similarity between curves that takes into account the location and ordering of the points along the curves. Therefore it is often better than the Hausdorff distance.

When the optional densifyFrac is specified, this function performs a segment densification before computing the discrete Fréchet distance. The densifyFrac parameter sets the fraction by which to densify each segment. Each segment will be split into a number of equal-length subsegments, whose fraction of the total length is closest to the given fraction.

Units are in the units of the spatial reference system of the geometries.

[참고]

현재 구현된 함수는 불연속 위치로 꼭짓점만 지원합니다. 이를 임의 밀도의 포인트들을 사용할 수 있도록 확장할 수 있습니다.

[참고]

The smaller densifyFrac we specify, the more accurate Fréchet distance we get. But, the computation time and the memory usage increase with the square of the number of subsegments.

GEOS 모듈로 실행

Availability: 2.4.0 - requires GEOS >= 3.7.0

예시

Both lines are traversed from left to right. The first line is straight, while the second bows upward through its middle vertex. The point ordering matters, so keeping both inputs in the same direction makes the comparison clearer.

Code
WITH lines AS (
  SELECT 'LINESTRING (0 0,100 0)'::geometry AS baseline,
         'LINESTRING (0 0,50 50,100 0)'::geometry AS bowed
)
SELECT baseline AS baseline,
       bowed AS bowed,
       ST_FrechetDistance(baseline, bowed) AS discrete_distance,
       ST_FrechetDistance(baseline, bowed, 0.5) AS densified_distance
FROM lines;
래스터 출력
-[ RECORD 1 ]-----+----------------------------
baseline           | LINESTRING(0 0,100 0)
bowed              | LINESTRING(0 0,50 50,100 0)
discrete_distance  | 70.7106781186548
densified_distance | 50
Figure
Geometry figure for visual-st-frechetdistance-01

제목

ST_HausdorffDistance — 두 도형 사이의 3차원 최단(shortest) 라인을 반환합니다.

요약

float ST_HausdorffDistance(geometry g1, geometry g2);

float ST_HausdorffDistance(geometry g1, geometry g2, float densifyFrac);

설명

Returns the Hausdorff distance between two geometries. The Hausdorff distance is a measure of how similar or dissimilar 2 geometries are.

The function actually computes the "Discrete Hausdorff Distance". This is the Hausdorff distance computed at discrete points on the geometries. The densifyFrac parameter can be specified, to provide a more accurate answer by densifying segments before computing the discrete Hausdorff distance. Each segment is split into a number of equal-length subsegments whose fraction of the segment length is closest to the given fraction.

Units are in the units of the spatial reference system of the geometries.

[참고]

This algorithm is NOT equivalent to the standard Hausdorff distance. However, it computes an approximation that is correct for a large subset of useful cases. One important case is Linestrings that are roughly parallel to each other, and roughly equal in length. This is a useful metric for line matching.

1.5.0 버전부터 사용할 수 있습니다.

예시

Hausdorff distance and minimum distance between two lines. The Hausdorff witness segment from the original illustration is retained and its length is checked against the computed distance.

Code
WITH lines AS (
  SELECT 'LINESTRING (20 70,70 60,110 70,170 70)'::geometry AS geomA,
         'LINESTRING (20 90,130 90,60 100,190 100)'::geometry AS geomB,
         'LINESTRING (52.69230769230769 63.46153846153846,60 100)'::geometry AS hausdorff_segment
)
SELECT round(ST_HausdorffDistance(geomA, geomB)::numeric, 6) AS hausdorff_distance,
       round(ST_Distance(geomA, geomB)::numeric, 6) AS distance,
       round(ST_Length(hausdorff_segment)::numeric, 6) AS witness_length,
       ST_ShortestLine(geomA, geomB) AS distance_segment
FROM lines;
래스터 출력
37.262066 | 20.000000 | 37.262066 | LINESTRING(20 70,20 90)
Figure
Geometry figure for visual-st-hausdorffdistance-01

Example: Hausdorff distance with densification.

Code
SELECT ST_HausdorffDistance(
            'LINESTRING (130 0,0 0,0 150)'::geometry,
            'LINESTRING (10 10,10 150,130 10)'::geometry,
            0.5);
래스터 출력
70
Figure
Geometry figure for visual-st-hausdorffdistance-02

Example: For each building, find the parcel that best represents it. First we require that the parcel intersect with the building geometry. DISTINCT ON guarantees we get each building listed only once. ORDER BY .. ST_HausdorffDistance selects the parcel that is most similar to the building.

Code
SELECT DISTINCT ON (buildings.gid) buildings.gid, parcels.parcel_id
   FROM buildings
       INNER JOIN parcels
       ON ST_Intersects(buildings.geom, parcels.geom)
   ORDER BY buildings.gid, ST_HausdorffDistance(buildings.geom, parcels.geom);

제목

ST_Length — 도형의 기하학적 중심을 반환합니다.

요약

float ST_Length(geometry a_2dlinestring);

float ST_Length(geography geog, boolean use_spheroid = true);

설명

도형의 경우: 도형이 라인스트링, 멀티라인스트링, ST_Curve, ST_MultiCurve일 경우 도형의 2차원 데카르트 길이를 반환합니다. 면 도형의 경우 0을 반환합니다. 면 도형에 대해서는 ST_Perimeter 를 이용하십시오. 도형 유형의 경우, 도형의 공간 참조 시스템이 해당 길이의 측정 단위를 설정합니다.

For geography types: computation is performed using the inverse geodesic calculation. Units of length are in meters. The spheroid is specified by the SRID; when no SRID is provided, WGS84 is used. If use_spheroid = false, then the calculation is based on a sphere instead of a spheroid.

도형의 경우 이 함수는 현재 ST_Length2D와 동일하지만, 향후 더 높은 차원을 지원하기 위해 변경될 수도 있습니다.

변경 사항: 2.0.0 버전에서 중요한 변경이 이루어졌습니다. 2.0.0 이전 버전에서 이 함수에 폴리곤/멀티폴리곤 유형의 지리형을 입력하면 폴리곤/멀티폴리곤의 둘레를 반환했을 겁니다. 2.0.0 버전부터 도형 습성과 맞추기 위해 0을 반환하도록 변경됐습니다. 폴리곤의 둘레를 원한다면 ST_Perimeter 함수를 이용하십시오.

[참고]

지리형 측정시 기본값은 회전타원체 상의 측정입니다. 더 빠르지만 덜 정확한 구체를 이용하려면 ST_Length(gg,false); 를 쓰십시오.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.5.1

This method implements the SQL/MM specification. SQL-MM 3: 7.1.2, 9.3.4

1.5.0 버전부터 지리형을 지원합니다.

도형 예시

라인스트링의 길이를 피트 단위로 반환합니다. 투영체 EPSG:2249가 매사추세츠 주 피트 단위 평면이기 때문에 피트 단위라는 사실을 주의하십시오.

Code
SELECT ST_Length(ST_GeomFromText(
'LINESTRING(743238 2967416,743238 2967450,743265 2967450,
743265.625 2967416,743238 2967416)',
2249));
래스터 출력
122.63074400009504
Figure
Geometry figure for visual-st-length-01

This example transforms a WGS 84 LineString to Massachusetts State Plane meters.

Code
SELECT ST_Length(ST_Transform(
        'SRID=4326;LINESTRING(-72.1260 42.45,-72.1240 42.45666,-72.123 42.1546)'::geometry,
            26986
    )
);
래스터 출력
34309.4563576191
Figure
Geometry figure for visual-st-length-02

지리형 예시

WGS84 지리형 라인의 길이를 반환합니다.

This example uses the default spheroid calculation.

Code
SELECT ST_Length(the_geog) As length_spheroid, ST_Length(the_geog, false) As length_sphere
FROM (SELECT ST_GeographyFromText('SRID=4326;LINESTRING(-72.1260 42.45,-72.1240 42.45666,-72.123 42.1546)') As the_geog)
 As foo;
래스터 출력
length_spheroid  |  length_sphere
------------------+------------------
34310.5703627284 | 34346.20609607416
Figure
Geometry figure for visual-st-length-03

제목

ST_Length2D — 도형이 라인스트링 또는 멀티라인스트링일 경우 도형의 2차원 길이를 반환합니다. 이 함수는 ST_Length 와 동일합니다.

요약

float ST_Length2D(geometry a_2dlinestring);

설명

도형이 라인스트링 또는 멀티라인스트링일 경우 도형의 2차원 길이를 반환합니다. 이 함수는 ST_Length 와 동일합니다.


제목

ST_3DLength — 도형의 기하학적 중심을 반환합니다.

요약

float ST_3DLength(geometry a_3dlinestring);

설명

도형이 라인스트링 또는 멀티라인스트링일 경우 도형의 3차원 또는 2차원 길이를 반환합니다. 2차원 라인의 경우 2차원 길이만 반환할 것입니다(ST_Length 및 ST_Length2D와 동일합니다).

This function supports 3d and will not drop the z-index.

This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 7.1, 10.3

변경 사항: 2.0.0 미만 버전에서는 ST_Length3D라는 명칭이었습니다.

예시

3차원 케이블의 길이를 피트 단위로 반환합니다. 투영체 EPSG:2249가 매사추세츠 주 피트 단위 평면이기 때문에 피트 단위라는 사실을 주의하십시오.

Code
SELECT ST_3DLength(ST_GeomFromText(
'LINESTRING(743238 2967416 1,743238 2967450 1,743265 2967450 3,
743265.625 2967416 3,743238 2967416 3)',
2249));
래스터 출력
122.70471674145682
Figure
Geometry figure for visual-st-3dlength-01

제목

ST_LengthSpheroid — 도형의 기하학적 중심을 반환합니다.

요약

float ST_LengthSpheroid(geometry a_geometry, spheroid a_spheroid);

설명

Calculates the length or perimeter of a geometry on a spheroid. This is useful if the coordinates of the geometry are in longitude/latitude and a length is desired without reprojection. The spheroid is specified by a text value as follows:

SPHEROID[<NAME>,<SEMI-MAJOR AXIS>,<INVERSE FLATTENING>]

도형 예시

SPHEROID["GRS_1980",6378137,298.257222101]

1.2.2 버전부터 사용할 수 있습니다.

변경 사항: 2.2.0 미만 버전에서는 ST_Length_Spheroid라는 명칭이었으며, ST_3DLength_Spheroid라는 동일 함수가 있었습니다.

This function supports 3d and will not drop the z-index.

예시

Measure a table geometry directly on a spheroid when the coordinates are stored in longitude and latitude.

Code
SELECT ST_LengthSpheroid(
    geometry_column,
    'SPHEROID["GRS_1980",6378137,298.257222101]'
    )
FROM geometry_table;

This example measures a 2D MultiLineString and each component separately on the same spheroid.

Code
WITH sample AS (
  SELECT 'MULTILINESTRING((-118.584 38.374,-118.583 38.5),
          (-71.05957 42.3589,-71.061 43))'::geometry AS geom,
         CAST('SPHEROID["GRS_1980",6378137,298.257222101]' AS spheroid) AS sph_m
)
SELECT ST_LengthSpheroid(geom, sph_m) AS tot_len,
       ST_LengthSpheroid(ST_GeometryN(geom, 1), sph_m) AS len_line1,
       ST_LengthSpheroid(ST_GeometryN(geom, 2), sph_m) AS len_line2
FROM sample;
래스터 출력
tot_len      |    len_line1     |    len_line2
------------------+------------------+------------------
 85204.52077117894 | 13986.87252824332 | 71217.64824293563
Figure
Geometry figure for visual-st-length-spheroid-01

This example uses 3D input; Z contributes to the measured result.

Code
WITH sample AS (
  SELECT 'MULTILINESTRING((-118.584 38.374 20,-118.583 38.5 30),
          (-71.05957 42.3589 75,-71.061 43 90))'::geometry AS geom,
         CAST('SPHEROID["GRS_1980",6378137,298.257222101]' AS spheroid) AS sph_m
)
SELECT ST_LengthSpheroid(geom, sph_m) AS tot_len,
       ST_LengthSpheroid(ST_GeometryN(geom, 1), sph_m) AS len_line1,
       ST_LengthSpheroid(ST_GeometryN(geom, 2), sph_m) AS len_line2
FROM sample;
래스터 출력
tot_len      |    len_line1    |    len_line2
------------------+-----------------+------------------
 85204.52592562366 | 13986.876103023424 | 71217.64982260024
Figure
Geometry figure for visual-st-length-spheroid-02

제목

ST_LongestLine — 두 도형 사이의 3차원 최장(longest) 라인을 반환합니다.

요약

geometry ST_LongestLine(geometry g);

geometry ST_LongestLine(geometry g1, geometry g2);

설명

Returns the 2-dimensional longest line between the points of two geometries. The line returned starts on g1 and ends on g2.

The longest line always occurs between two vertices. The function returns the first longest line if more than one is found. The length of the line is equal to the distance returned by ST_MaxDistance.

If only one geometry is provided, or g1 and g2 are the same geometry, returns the line between the two vertices farthest apart in the geometry. The endpoints of the line lie on the circle computed by ST_MinimumBoundingCircle.

1.5.0 버전부터 사용할 수 있습니다.

Enhanced: 3.7.0 - support for a single geometry input.

예시

Longest line between a Point and a LineString.

Code
SELECT ST_LongestLine(
        'POINT (160 40)',
        'LINESTRING (10 30,50 50,30 110,70 90,180 140,130 190)' ) AS lline;
래스터 출력
LINESTRING(160 40,130 190)
Figure
Geometry figure for visual-st-longestline-01

Longest line between two polygons.

Code
SELECT ST_LongestLine(
        'POLYGON ((190 150,20 10,160 70,190 150))',
        ST_Buffer('POINT(80 160)', 30)
            ) AS llinewkt;
래스터 출력
LINESTRING(20 10,91.4805029709527 187.7163859753386)
Figure
Geometry figure for visual-st-longestline-02

Longest line across a single geometry. The length of the line is equal to the Maximum Distance. The endpoints of the line lie on the Minimum Bounding Circle.

Code
SELECT ST_LongestLine(geom) AS llinewkt,
                  ST_MaxDistance(geom) AS max_dist,
                  ST_Length(ST_LongestLine(geom)) AS lenll
FROM (SELECT 'POLYGON ((40 180,110 160,180 180,180 120,140 90,160 40,80 10,70 40,20 50,40 180),
              (60 140,99 77.5,90 140,60 140))'::geometry AS geom) AS t;
래스터 출력
llinewkt          |      max_dist      |       lenll
---------------------------+--------------------+--------------------
 LINESTRING(20 50,180 180) | 206.15528128088303 | 206.15528128088303
Figure
Geometry figure for visual-st-longestline-03

제목

ST_3DLongestLine — 두 도형 사이의 3차원 최장(longest) 라인을 반환합니다.

요약

geometry ST_3DLongestLine(geometry g1, geometry g2);

설명

두 도형 사이의 3차원 최장(longest) 라인을 반환합니다. 하나 이상의 최장 라인이 있을 경우, 이 함수는 첫 번째 최장 라인만 반환할 것입니다. 반환되는 라인은 항상 g1에서 시작해서 g2에서 끝납니다. 이 함수가 반환하는 라인의 3차원 길이는 ST_3DMaxDistance 함수가 g1과 g2에 대해 반환하는 길이와 언제나 동일합니다.

2.0.0 버전부터 사용할 수 있습니다.

변경 사항: 2.2.0 버전부터 2D 도형 두 개를 입력할 경우, (존재하지 않는 Z을 0으로 가정하는 예전 습성 대신) 2D 포인트를 반환합니다. 2D 및 3D의 경우, 더 이상 Z가 없을 때 Z를 0으로 가정하지 않습니다.

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

예시

Longest line between a LineString and a Point, comparing the 3D and 2D results.

Code
SELECT ST_3DLongestLine(line, pt) AS lol3d_line_pt, ST_LongestLine(line, pt) AS lol2d_line_pt
FROM (
    SELECT 'POINT(100 100 30)'::geometry AS pt,
           'LINESTRING (20 80 20,98 190 1,110 180 3,50 75 1000)'::geometry AS line
) AS foo;
래스터 출력
lol3d_line_pt           |       lol2d_line_pt
-----------------------------------+----------------------------
 LINESTRING(50 75 1000,100 100 30) | LINESTRING(98 190,100 100)
Figure
Geometry figure for visual-st-3dlongestline-01

Longest line between a LineString and a MultiPoint, comparing the 3D and 2D results.

Code
SELECT ST_3DLongestLine(line, pt) AS lol3d_line_pt, ST_LongestLine(line, pt) AS lol2d_line_pt
FROM (
    SELECT 'MULTIPOINT(100 100 30,50 74 1000)'::geometry AS pt,
           'LINESTRING (20 80 20,98 190 1,110 180 3,50 75 900)'::geometry AS line
) AS foo;
래스터 출력
lol3d_line_pt          |      lol2d_line_pt
---------------------------------+--------------------------
 LINESTRING(98 190 1,50 74 1000) | LINESTRING(98 190,50 74)
Figure
Geometry figure for visual-st-3dlongestline-02

Longest line between a Polygon and a MultiLineString, comparing the 3D and 2D results.

Code
SELECT ST_3DLongestLine(poly, mline) AS lol3d, ST_LongestLine(poly, mline) AS lol2d
FROM (
    SELECT ST_GeomFromEWKT(
               'POLYGON((175 150 5,20 40 5,35 45 5,50 60 5,100 100 5,175 150 5))'
           ) AS poly,
           ST_GeomFromEWKT(
               'MULTILINESTRING((175 155 2,20 40 20,50 60 -2,125 100 1,175 155 1),
               (1 10 2,5 20 1))'
           ) AS mline
) AS foo;
래스터 출력
lol3d             |          lol2d
------------------------------+--------------------------
 LINESTRING(175 150 5,1 10 2) | LINESTRING(175 150,1 10)
Figure
Geometry figure for visual-st-3dlongestline-03

제목

ST_MaxDistance — 두 도형 사이의 2차원 최장 거리를 투영 단위로 반환합니다.

요약

float ST_MaxDistance(geometry g);

float ST_MaxDistance(geometry g1, geometry g2);

설명

두 도형 사이의 2차원 최장 거리를 투영 단위로 반환합니다. g1과 g2가 동일한 도형일 경우 이 함수는 해당 도형 내에서 서로 가장 멀리 있는 두 꼭짓점 사이의 거리를 반환합니다.

If only one geometry is provided, or g1 and g2 are the same geometry, returns the distance between the two vertices farthest apart in that geometry.

1.5.0 버전부터 사용할 수 있습니다.

Enhanced: 3.7.0 - support for a single geometry input.

예시

포인트와 라인 사이의 최장 라인

Code
SELECT ST_MaxDistance('POINT(0 0)'::geometry, 'LINESTRING ( 2 0,0 2 )'::geometry);
래스터 출력
2
Figure
Geometry figure for visual-st-maxdistance-01
Code
SELECT ST_MaxDistance('POINT(0 0)'::geometry, 'LINESTRING ( 2 2,2 2 )'::geometry);
래스터 출력
2.82842712474619
Figure
Geometry figure for visual-st-maxdistance-02

Maximum distance between vertices of a single geometry.

Code
SELECT ST_MaxDistance('POLYGON ((10 10,10 0,0 0,10 10))'::geometry);
래스터 출력
14.142135623730951
Figure
Geometry figure for visual-st-maxdistance-03

제목

ST_3DMaxDistance — 도형 유형에 대해, 두 도형 사이의 (SRS에 기반한) 3차원 데카르트 최장 거리를 투영 단위로 반환합니다.

요약

float ST_3DMaxDistance(geometry g1, geometry g2);

설명

도형 유형에 대해, 두 도형 사이의 3차원 데카르트 최대 거리를 두 도형의 투영 단위(SRS 단위)로 반환합니다.

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

2.0.0 버전부터 사용할 수 있습니다.

변경 사항: 2.2.0 버전부터, 2D 및 3D의 경우 더 이상 Z가 없을 때 Z를 0으로 가정하지 않습니다.

예시

Geometry example - units in meters (SRID: 2163 US National Atlas Equal area) (3D point and line compared 2D point and line) Note that currently no vertical datum support so Z is not transformed and assumed to be same units as final.

Code
SELECT ST_3DMaxDistance(
            ST_Transform('SRID=4326;POINT(-72.1235 42.3521 10000)'::geometry, 2163),
                ST_Transform('SRID=4326;LINESTRING(-72.1260 42.45 15,-72.123 42.1546 20)'::geometry, 2163)
            ) As dist_3d,
            ST_MaxDistance(
                ST_Transform('SRID=4326;POINT(-72.1235 42.3521 10000)'::geometry, 2163),
                ST_Transform('SRID=4326;LINESTRING(-72.1260 42.45 15,-72.123 42.1546 20)'::geometry, 2163)
            ) As dist_2d;
래스터 출력
dist_3d      |     dist_2d
------------------+------------------
 24383.7467488441 | 22247.8472107251

제목

ST_MinimumClearance — 도형의 튼튼함(robustness)의 척도인 도형의 최소 여유(clearance)를 반환합니다.

요약

float ST_MinimumClearance(geometry g);

설명

(폴리곤일 경우) ST_IsValid 또는 (라인일 경우) ST_IsSimple 함수에 따라 유효성에 대한 기준을 만족시키지만, 텍스트 기반 형식(WKT, KML, GML GeoJSON 등) 또는 이중 정밀도 부동소수점 좌표를 이용하지 않는 바이너리 형식(MapInfo TAB 등)으로 변환하는 과정에서 일어날 수 있는 것처럼, 꼭짓점 가운데 하나가 살짝 이동하면 유효하지 않아지는 도형이 그렇게 희귀한 것은 아닙니다.

The minimum clearance is a quantitative measure of a geometry's robustness to change in coordinate precision. It is the largest distance by which vertices of the geometry can be moved without creating an invalid geometry. Larger values of minimum clearance indicate greater robustness.

도형이 e 라는 최소 여유를 가지고 있을 경우, 다음과 같이 말할 수 있습니다:

  • 도형 내부의 어떤 서로 다른 꼭짓점 2개도 e 보다 더 떨어져 있지 않습니다.

  • 종단점이 아닌 한 어떤 꼭짓점도 라인 선분에 e 보다 가까이 있을 수는 없습니다.

도형에 대해 최소 여유가 존재하지 않을 경우 (예를 들어 단일 포인트 또는 포인트들이 서로 동일한 멀티포인트인 경우) ST_MinimumClearance 함수는 무한을 반환할 것입니다.

To avoid validity issues caused by precision loss, ST_ReducePrecision can reduce coordinate precision while ensuring that polygonal geometry remains valid.

2.3.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT ST_MinimumClearance('POLYGON ((0 0,1 0,1 1,0.5 3.2e-4,0 0))');
래스터 출력
0.00032
Figure
Geometry figure for visual-st-minimumclearance-01

제목

ST_MinimumClearanceLine — 포인트 2개로 이루어진, 도형의 최소 여유를 나타내는 라인스트링을 반환합니다.

요약

Geometry ST_MinimumClearanceLine(geometry g);

설명

Returns the two-point LineString spanning a geometry's minimum clearance. If the geometry does not have a minimum clearance, LINESTRING EMPTY is returned.

GEOS 모듈로 실행

2.3.0 버전부터 사용할 수 있습니다. GEOS 3.6.0 이상 버전이 필요합니다.

예시

Code
SELECT ST_MinimumClearanceLine('POLYGON ((0 0,1 0,1 1,0.5 3.2e-4,0 0))');
래스터 출력
LINESTRING(0.5 0.00032,0.5 0)
                  
Figure
Geometry figure for visual-st-minimumclearanceline-01

제목

ST_Perimeter — Returns the length of the boundary of a polygonal geometry or geography.

요약

float ST_Perimeter(geometry g1);

float ST_Perimeter(geography geog, boolean use_spheroid = true);

설명

도형/지리형이 ST_Surface, ST_MultiSurface(폴리곤, 멀티폴리곤)일 경우 도형/지리형의 2차원 둘레를 반환합니다. 면이 없는 도형의 경우 0을 반환합니다. 선형 도형의 경우 ST_Length 를 이용하십시오. 도형 유형의 경우, 도형의 공간 참조 시스템이 해당 둘레의 측정 단위를 설정합니다.

For geography types, the calculations are performed using the inverse geodesic problem, where perimeter units are in meters. The spheroid is specified by the SRID; when no SRID is provided, WGS84 is used. If use_spheroid = false, then calculations will approximate a sphere instead of a spheroid.

이 함수는 현재 ST_Perimeter2D와 동일하지만, 향후 더 높은 차원을 지원하기 위해 변경될 수도 있습니다.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.5.1

This method implements the SQL/MM specification. SQL-MM 3: 8.1.3, 9.5.4

개선 사항: 2.0.0 버전부터 지리형을 지원합니다.

예시

Geometry.

폴리곤 및 멀티폴리곤의 둘레를 피트 단위로 반환합니다. 투영체 EPSG:2249가 매사추세츠 주 피트 단위 평면이기 때문에 피트 단위라는 사실을 주의하십시오.

Code
SELECT ST_Perimeter(ST_GeomFromText(
'POLYGON((743238 2967416,743238 2967450,743265 2967450,
743265.625 2967416,743238 2967416))',
2249));
래스터 출력
122.63074400009504
Figure
Geometry figure for visual-st-perimeter-01
Code
SELECT ST_Perimeter(ST_GeomFromText(
'MULTIPOLYGON(((763104.471273676 2949418.44119003,
763104.477769673 2949418.42538203,
763104.189609677 2949418.22343004,763104.471273676 2949418.44119003)),
((763104.471273676 2949418.44119003,763095.804579742 2949436.33850239,
763086.132105649 2949451.46730207,763078.452329651 2949462.11549407,
763075.354136904 2949466.17407812,763064.362142565 2949477.64291974,
763059.953961626 2949481.28983009,762994.637609571 2949532.04103014,
762990.568508415 2949535.06640477,762986.710889563 2949539.61421415,
763117.237897679 2949709.50493431,763235.236617789 2949617.95619822,
763287.718121842 2949562.20592617,763111.553321674 2949423.91664605,
763104.471273676 2949418.44119003)))',
2249));
래스터 출력
845.227713366825
Figure
Geometry figure for visual-st-perimeter-02

폴리곤 및 멀티폴리곤의 둘레를 미터 단위로 반환합니다. 지리형이기 때문에 투영체가 WGS84 경위도라는 점에 주의하십시오.

Code
SELECT  ST_Perimeter(geog) As per_meters, ST_Perimeter(geog)/0.3048 As per_ft
FROM ST_GeogFromText('POLYGON((-71.1776848522251 42.3902896512902,-71.1776843766326 42.3903829478009,
-71.1775844305465 42.3903826677917,-71.1775825927231 42.3902893647987,-71.1776848522251 42.3902896512902))') As geog;
래스터 출력
per_meters    |      per_ft
-----------------+------------------
37.37904625414049 | 122.63466618812497
Figure
Geometry figure for visual-st-perimeter-03

This example uses a MultiPolygon.

Code
SELECT  ST_Perimeter(geog) As per_meters, ST_Perimeter(geog, false) As per_sphere_meters, ST_Perimeter(geog)/0.3048 As per_ft
FROM ST_GeogFromText('MULTIPOLYGON(((-71.1044543107478 42.340674480411,-71.1044542869917 42.3406744369506,
-71.1044553562977 42.340673886454,-71.1044543107478 42.340674480411)),
((-71.1044543107478 42.340674480411,-71.1044860600303 42.3407237015564,-71.1045215770124 42.3407653385914,
-71.1045498002983 42.3407946553165,-71.1045611902745 42.3408058316308,-71.1046016507427 42.340837442371,
-71.104617893173 42.3408475056957,-71.1048586153981 42.3409875993595,-71.1048736143677 42.3409959528211,
-71.1048878050242 42.3410084812078,-71.1044020965803 42.3414730072048,
-71.1039672113619 42.3412202916693,-71.1037740497748 42.3410666421308,
-71.1044280218456 42.3406894151355,-71.1044543107478 42.340674480411)))') As geog;
래스터 출력
per_meters    | per_sphere_meters |      per_ft
------------------+-------------------+------------------
 257.634283683311 |  257.412311446337 | 845.256836231335
                        
Figure
Geometry figure for visual-st-perimeter-04

제목

ST_Perimeter2D — Returns the 2D perimeter of a polygonal geometry. Alias for ST_Perimeter.

요약

float ST_Perimeter2D(geometry geomA);

설명

도형이 폴리곤 또는 멀티폴리곤일 경우 도형의 2차원 둘레를 반환합니다.

[참고]

이 함수는 현재 ST_Perimeter 와 동일합니다. 향후 버전에서 ST_Perimeter 는 도형에 대해 최고 차원의 둘레를 반환할 수도 있습니다. 이는 아직 고려 대상입니다.


제목

ST_3DPerimeter — 도형의 기하학적 중심을 반환합니다.

요약

float ST_3DPerimeter(geometry geomA);

설명

도형이 폴리곤 또는 멀티폴리곤일 경우 도형의 3차원 둘레를 반환합니다. 2차원 도형의 경우 2차원 둘레를 반환할 것입니다.

This function supports 3d and will not drop the z-index.

This method implements the SQL/MM specification. SQL-MM ISO/IEC 13249-3: 8.1, 10.5

변경 사항: 2.0.0 미만 버전에서는 ST_Perimeter3D라는 명칭이었습니다.

예시

매사추세츠 주 피트 단위 평면에서 공중에 살짝 떠 있는 폴리곤의 둘레

Code
SELECT ST_3DPerimeter(geom), ST_Perimeter2D(geom), ST_Perimeter(geom) FROM
            (SELECT 'SRID=2249;POLYGON((743238 2967416 2,743238 2967450 1,
743265.625 2967416 1,743238 2967416 2))'::geometry As geom) As foo;
래스터 출력
ST_3DPerimeter  |  st_perimeter2d  |   st_perimeter
------------------+------------------+------------------
105.46579359767418 | 105.43299727218763 | 105.43299727218763
Figure
Geometry figure for visual-st-3dperimeter-01

제목

ST_ShortestLine — 두 도형 사이의 2차원 최단 라인을 반환합니다.

요약

geometry ST_ShortestLine(geometry geom1, geometry geom2);

geography ST_ShortestLine(geography geom1, geography geom2, boolean use_spheroid = true);

설명

Returns the 2-dimensional shortest line between two geometries. The line returned starts in geom1 and ends in geom2. If geom1 and geom2 intersect the result is a line with start and end at an intersection point. The length of the line is the same as ST_Distance returns for g1 and g2.

Enhanced: 3.4.0 - support for geography.

1.5.0 버전부터 사용할 수 있습니다.

예시

Shortest line between a Point and a LineString.

Code
SELECT ST_ShortestLine(
        'POINT (160 40)',
        'LINESTRING (10 30,50 50,30 110,70 90,180 140,130 190)') As sline;
래스터 출력
LINESTRING(160 40,125.75342465753425 115.34246575342466)
Figure
Geometry figure for visual-st-shortestline-01

Shortest line between polygons.

Code
SELECT ST_ShortestLine(
         'POLYGON ((190 150,20 10,160 70,190 150))',
         ST_Buffer('POINT(80 160)', 30)
                  ) AS llinewkt;
래스터 출력
LINESTRING(131.59149149528952 101.89887534906195,101.21320343559643 138.78679656440357)
Figure
Geometry figure for visual-st-shortestline-02

제목

ST_3DShortestLine — 두 도형 사이의 3차원 최단(shortest) 라인을 반환합니다.

요약

geometry ST_3DShortestLine(geometry g1, geometry g2);

설명

두 도형 사이의 3차원 최단(shortest) 라인을 반환합니다. 하나 이상의 최단 라인이 있을 경우, 이 함수는 첫 번째 최단 라인만 반환할 것입니다. g1과 g2가 단 한 개의 포인트에서만 교차할 경우, 이 함수는 교차점에서 시작하고 끝나는 라인을 반환할 것입니다. g1과 g2가 한 개 이상의 포인트에서 교차할 경우, 이 함수는 동일한 포인트에서 시작하고 끝나는 라인을 반환하지만 해당 포인트는 교차하는 포인트들 가운데 어떤 포인트라도 될 수 있습니다. 반환되는 라인은 항상 g1에서 시작해서 g2에서 끝납니다. 이 함수가 반환하는 라인의 3차원 길이는 ST_3DDistance 함수가 g1과 g2에 대해 반환하는 길이와 언제나 동일합니다.

2.0.0 버전부터 사용할 수 있습니다.

변경 사항: 2.2.0 버전부터 2D 도형 두 개를 입력할 경우, (존재하지 않는 Z을 0으로 가정하는 예전 습성 대신) 2D 포인트를 반환합니다. 2D 및 3D의 경우, 더 이상 Z가 없을 때 Z를 0으로 가정하지 않습니다.

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

예시

Compare the 3D shortest line to the 2D shortest line for a LineString and a Point.

Code
WITH input AS (
  SELECT 'POINT(100 100 30)'::geometry AS pt,
         'LINESTRING (20 80 20,98 190 1,110 180 3,50 75 1000)'::geometry AS line
)
SELECT ST_3DShortestLine(line, pt) AS shl3d_line_pt,
       ST_ShortestLine(line, pt) AS shl2d_line_pt
FROM input;
래스터 출력
-[ RECORD 1 ]--+--------------------------------------------------------------------------------
shl3d_line_pt  | LINESTRING(54.69937988676193 128.93502291722837 11.547586950660556,100 100 30)
shl2d_line_pt  | LINESTRING(73.07692307692307 115.38461538461539,100 100)
Figure
Geometry figure for visual-st-3dshortestline-01

Compare the 3D shortest line to the 2D shortest line for a LineString and a MultiPoint.

Code
WITH input AS (
  SELECT 'MULTIPOINT(100 100 30,50 74 1000)'::geometry AS pt,
         'LINESTRING (20 80 20,98 190 1,110 180 3,50 75 900)'::geometry AS line
)
SELECT ST_3DShortestLine(line, pt) AS shl3d_line_pt,
       ST_ShortestLine(line, pt) AS shl2d_line_pt
FROM input;
래스터 출력
-[ RECORD 1 ]--+--------------------------------------------------------------------------------
shl3d_line_pt  | LINESTRING(54.69937988676193 128.93502291722837 11.547586950660556,100 100 30)
shl2d_line_pt  | LINESTRING(50 75,50 74)
Figure
Geometry figure for visual-st-3dshortestline-02

Compare the 3D shortest line to the 2D shortest line for a Polygon and a MultiLineString.

Code
WITH input AS (
  SELECT ST_GeomFromEWKT(
           'POLYGON((175 150 5,20 40 5,35 45 5,50 60 5,100 100 5,175 150 5))'
         ) AS poly,
         ST_GeomFromEWKT(
           'MULTILINESTRING((175 155 2,20 40 20,50 60 -2,125 100 1,175 155 1),
                            (1 10 2,5 20 1))'
         ) AS mline
)
SELECT ST_3DShortestLine(poly, mline) AS shl3d,
       ST_ShortestLine(poly, mline) AS shl2d
FROM input;
래스터 출력
-[ RECORD 1 ]--+--------------------------------------------------------------------------------------
shl3d          | LINESTRING(40.45454545454545 53.63636363636364 5,40.45454545454545 53.63636363636364 5)
shl2d          | LINESTRING(20 40,20 40)
Figure
Geometry figure for visual-st-3dshortestline-03

7.13. Overlay Functions

초록

These functions compute results arising from the overlay of two geometries. These are also known as point-set theoretic boolean operations. Some related functions are also provided.

  • ST_ClipByBox2D — Computes the portion of a geometry falling within a rectangle.
  • ST_Difference — Computes a geometry representing the part of geometry A that does not intersect geometry B.
  • ST_Intersection — Computes a geometry representing the shared portion of geometries A and B.
  • ST_MemUnion — Aggregate function which unions geometries in a memory-efficent but slower way
  • ST_Node — Nodes a collection of lines.
  • ST_Split — Returns a collection of geometries created by splitting a geometry by another geometry.
  • ST_Subdivide — Computes a rectilinear subdivision of a geometry.
  • ST_SymDifference — Computes a geometry representing the portions of geometries A and B that do not intersect.
  • ST_UnaryUnion — Computes the union of the components of a single geometry.
  • ST_Union — Computes a geometry representing the point-set union of the input geometries.

제목

ST_ClipByBox2D — Computes the portion of a geometry falling within a rectangle.

요약

geometry ST_ClipByBox2D(geometry geom, box2d box);

설명

Clips a geometry by a 2D box in a fast and tolerant but possibly invalid way. Topologically invalid input geometries do not result in exceptions being thrown. The output geometry is not guaranteed to be valid (in particular, self-intersections for a polygon may be introduced).

GEOS 모듈로 실행

2.2.0 버전부터 사용할 수 있습니다.

예시

This example relies on the implicit cast from geometry to box2d for the second parameter.

Code
SELECT ST_ClipByBox2D(geom, ST_MakeEnvelope(0, 0, 10, 10)) FROM mytab;

제목

ST_Difference — Computes a geometry representing the part of geometry A that does not intersect geometry B.

요약

geometry ST_Difference(geometry geomA, geometry geomB, float8 gridSize = -1);

설명

Returns a geometry representing the part of geometry A that does not intersect geometry B. This is equivalent to A - ST_Intersection(A,B). If A is completely contained in B then an empty atomic geometry of appropriate type is returned.

[참고]

This is the only overlay function where input order matters. ST_Difference(A, B) always returns a portion of A.

If the optional gridSize parameter is given (GEOS-3.9.0 or higher required), all result vertices are guaranteed to fall on a snap-rounded grid of the specified size. Note that operations performed on a grid may contain small artifacts produced during grid alignment, see ST_ReducePrecision.

GEOS 모듈로 실행

Enhanced: 3.1.0 accept a gridSize parameter.

Requires GEOS >= 3.9.0 to use the gridSize parameter.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.3

This method implements the SQL/MM specification. SQL-MM 3: 5.1.20

This function supports 3d and will not drop the z-index. However, the result is computed using XY only. The result Z values are copied, averaged or interpolated.

예시

The difference of 2D linestrings.

Code
SELECT ST_Difference('LINESTRING(50 100,50 200)'::geometry,
        'LINESTRING(50 50,50 150)'::geometry
    );
래스터 출력
LINESTRING(50 150,50 200)
Figure
Geometry figure for visual-st-difference-01

The difference of 3D points.

Code
SELECT ST_Difference('MULTIPOINT(-118.58 38.38 5,-118.60 38.329 6,-118.614 38.281 7)' :: geometry,
 'POINT(-118.614 38.281 5)' :: geometry
);
래스터 출력
MULTIPOINT(-118.6 38.329 6,-118.58 38.38 5)
Figure
Geometry figure for visual-st-difference-02

제목

ST_Intersection — Computes a geometry representing the shared portion of geometries A and B.

요약

geometry ST_Intersection( geometry geomA , geometry geomB , float8 gridSize = -1 );

geography ST_Intersection( geography geogA , geography geogB );

설명

Returns a geometry representing the point-set intersection of two geometries. In other words, that portion of geometry A and geometry B that is shared between the two geometries.

If the geometries have no points in common (i.e. are disjoint) then an empty atomic geometry of appropriate type is returned.

If the optional gridSize parameter is given (GEOS-3.9.0 or higher required), all result vertices are guaranteed to fall on a snap-rounded grid of the specified size. Note that operations performed on a grid may contain small artifacts produced during grid alignment, see ST_ReducePrecision.

ST_Intersection in conjunction with ST_Intersects is useful for clipping geometries such as in bounding box, buffer, or region queries where you only require the portion of a geometry that is inside a country or region of interest.

[참고]

Spatial predicates such as ST_Intersects and overlay functions such as ST_Intersection are computed by different algorithms. For very close or nearly coincident coordinates, floating-point precision and geometric robustness may make a predicate return true while the computed intersection is empty, or place an intersection point slightly away from the input line. For repeatable overlay results, snap inputs to a suitable grid first, for example with ST_ReducePrecision, or use the gridSize parameter when all input vertices already lie on the grid.

[참고]

For geography this is a thin wrapper around the geometry implementation. It first determines the best SRID that fits the bounding box of the 2 geography objects (if geography objects are within one half zone UTM but not same UTM will pick one of those) (favoring UTM or Lambert Azimuthal Equal Area (LAEA) north/south pole, and falling back on mercator in worst case scenario) and then intersection in that best fit planar spatial ref and retransforms back to WGS84 geography.

[주의]

This function will drop the M coordinate values if present.

[주의]

If working with 3D geometries, you may want to use SFCGAL based CG_3DIntersection which does a proper 3D intersection for 3D geometries. Although this function works with Z-coordinate, it does an averaging of Z-Coordinate.

GEOS 모듈로 실행

Enhanced: 3.1.0 accept a gridSize parameter

Requires GEOS >= 3.9.0 to use the gridSize parameter

Changed: 3.0.0 does not depend on SFCGAL.

Availability: 1.5 support for geography data type was introduced.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.3

This method implements the SQL/MM specification. SQL-MM 3: 5.1.18

This function supports 3d and will not drop the z-index. However, the result is computed using XY only. The result Z values are copied, averaged or interpolated.

예시

Code
SELECT ST_Intersection('POINT(0 0)'::geometry, 'LINESTRING ( 2 0,0 2 )'::geometry);
래스터 출력
POINT EMPTY
Code
SELECT ST_Intersection('POINT(0 0)'::geometry, 'LINESTRING ( 0 0,0 2 )'::geometry);
래스터 출력
POINT(0 0)
Figure
Geometry figure for visual-st-intersection-02

Clip all lines (trails) by country. Here we assume country geom are POLYGON or MULTIPOLYGONS. NOTE: we are only keeping intersections that result in a LINESTRING or MULTILINESTRING because we don't care about trails that just share a point. The dump is needed to expand a geometry collection into individual single MULT* parts. The below is fairly generic and will work for polys, etc. by just changing the where clause.

Code
select clipped.gid, clipped.f_name, clipped_geom
from (
         select trails.gid, trails.f_name,
             (ST_Dump(ST_Intersection(country.geom, trails.geom))).geom clipped_geom
         from country
              inner join trails on ST_Intersects(country.geom, trails.geom)
     ) as clipped
where ST_Dimension(clipped.clipped_geom) = 1;

For polys e.g. polygon landmarks, you can also use the sometimes faster hack that buffering anything by 0.0 except a polygon results in an empty geometry collection. (So a geometry collection containing polys, lines and points buffered by 0.0 would only leave the polygons and dissolve the collection shell.)

Code
select poly.gid,
    ST_Multi(ST_Buffer(ST_Intersection(country.geom, poly.geom),
            0.0
        )
    ) clipped_geom
from country
     inner join poly on ST_Intersects(country.geom, poly.geom)
where not ST_IsEmpty(ST_Buffer(ST_Intersection(country.geom, poly.geom), 0.0));

Note this is not a true 3D intersection. It uses 2.5D geometries (geometries with Z ordinates, but where calculations are performed in 2D). The same input is compared with CG_3DIntersection, which performs a true 3D intersection.

Code
WITH data AS (
  SELECT 'LINESTRING Z (2 2 6,1.5 1.5 7,1 1 8,0.5 0.5 8,0 0 10)'::geometry AS input_linestring,
         'POLYGON Z ((0 0 8,0 1 8,1 1 8,1 0 8,0 0 8))'::geometry AS input_polygon
)
SELECT input_linestring AS input_linestring,
       input_polygon AS input_polygon,
       ST_Intersection(input_linestring, input_polygon) AS intersection_2d,
       CG_3DIntersection(input_linestring, input_polygon) AS intersection_3d
FROM data;
래스터 출력
LINESTRING Z (2 2 6,1.5 1.5 7,1 1 8,0.5 0.5 8,0 0 10) | POLYGON Z ((0 0 8,0 1 8,1 1 8,1 0 8,0 0 8)) | LINESTRING Z (1 1 8,0.5 0.5 8,0 0 10) | LINESTRING Z (1 1 8,0.5 0.5 8)
Figure
Geometry figure for visual-st-intersection-03

제목

ST_MemUnion — Aggregate function which unions geometries in a memory-efficent but slower way

요약

geometry ST_MemUnion(geometry set geomfield);

설명

An aggregate function that unions the input geometries, merging them to produce a result geometry with no overlaps. The output may be a single geometry, a MultiGeometry, or a Geometry Collection.

[참고]

Produces the same result as ST_Union, but uses less memory and more processor time. This aggregate function works by unioning the geometries incrementally, as opposed to the ST_Union aggregate which first accumulates an array and then unions the contents using a fast algorithm.

This function supports 3d and will not drop the z-index. However, the result is computed using XY only. The result Z values are copied, averaged or interpolated.

예시

Code
SELECT id,
       ST_MemUnion(geom) as singlegeom
FROM sometable f
GROUP BY id;

참고

ST_Union


제목

ST_Node — Nodes a collection of lines.

요약

geometry ST_Node(geometry geom);

설명

Returns a (Multi)LineString representing the fully noded version of a collection of linestrings. The noding preserves all of the input nodes, and introduces the least possible number of new nodes. The resulting linework is dissolved (duplicate lines are removed).

This is a good way to create fully-noded linework suitable for use as input to ST_Polygonize.

ST_UnaryUnion can also be used to node and dissolve linework. It provides an option to specify a gridSize, which can provide simpler and more robust output. See also ST_Union for an aggregate variant.

This function supports 3d and will not drop the z-index.

GEOS 모듈로 실행

2.0.0 버전부터 사용할 수 있습니다.

Changed: 2.4.0 this function uses GEOSNode internally instead of GEOSUnaryUnion. This may cause the resulting linestrings to have a different order and direction compared to PostGIS < 2.4.

예시

Noding a 3D LineString which self-intersects.

Code
SELECT ST_Node('LINESTRINGZ(0 0 0, 10 10 10, 0 10 5, 10 0 3)'::geometry) As  output;
래스터 출력
MULTILINESTRING Z ((0 0 0,5 5 4.5),(5 5 4.5,10 10 10,0 10 5,5 5 4.5),(5 5 4.5,10 0 3))
Figure
Geometry figure for visual-st-node-01

Noding two LineStrings which share common linework. Note that the result linework is dissolved.

Code
SELECT ST_Node('MULTILINESTRING ((2 5,2 1,7 1),(6 1,4 1,2 3,2 5))'::geometry) As  output;
래스터 출력
MULTILINESTRING((2 5,2 3),(2 3,2 1,4 1),(4 1,2 3),(4 1,6 1),(6 1,7 1))
Figure
Geometry figure for visual-st-node-02

제목

ST_Split — Returns a collection of geometries created by splitting a geometry by another geometry.

요약

geometry ST_Split(geometry input, geometry blade);

설명

The function supports splitting a LineString by a (Multi)Point, (Multi)LineString or (Multi)Polygon boundary, or a (Multi)Polygon by a LineString. When a (Multi)Polygon is used as as the blade, its linear components (the boundary) are used for splitting the input. The result geometry is always a collection.

This function is in a sense the opposite of ST_Union. Applying ST_Union to the returned collection should theoretically yield the original geometry (although due to numerical rounding this may not be exactly the case).

[참고]

If the the input and blade do not intersect due to numerical precision issues, the input may not be split as expected. To avoid this situation it may be necessary to snap the input to the blade first, using ST_Snap with a small tolerance.

Availability: 2.0.0 requires GEOS

Enhanced: 2.2.0 support for splitting a line by a multiline, a multipoint or (multi)polygon boundary was introduced.

Enhanced: 2.5.0 support for splitting a polygon by a multiline was introduced.

예시

Split a circular polygon by a diagonal line.

Code
SELECT
         ST_Split(
           ST_Buffer('POINT(100 90)'::geometry, 50),
           'LINESTRING(10 10,190 190)'::geometry
         );
래스터 출력
GEOMETRYCOLLECTION(POLYGON((150 90,149 80.2,146.2 70.9,141.6 62.2,135.4 54.6,127.8 48.4,119.1 43.8,109.8 41,100 40,90.2 41,80.9 43.8,72.2 48.4,64.6 54.6,60.1 60.1,129.9 129.9,135.4 125.4,141.6 117.8,146.2 109.1,149 99.8,150 90)), POLYGON((60.1 60.1,58.4 62.2,53.8 70.9,51 80.2,50 90,51 99.8,53.8 109.1,58.4 117.8,64.6 125.4,72.2 131.6,80.9 136.2,90.2 139,100 140,109.8 139,119.1 136.2,127.8 131.6,129.9 129.9,60.1 60.1)))
Figure
Geometry figure for visual-st-split-01

Split a MultiLineString by a Point, where the point lies exactly on both LineStrings elements.

Code
SELECT ST_Split('MULTILINESTRING((10 10,190 190),(15 15,30 30,100 90))',
    ST_Point(30, 30));
래스터 출력
GEOMETRYCOLLECTION(
    LINESTRING(10 10,30 30),
    LINESTRING(30 30,190 190),
    LINESTRING(15 15,30 30),
    LINESTRING(30 30,100 90)
)
Figure
Geometry figure for visual-st-split-02

Split a LineString by a Point, where the point does not lie exactly on the line. Shows using ST_Snap to snap the line to the point to allow it to be split.

Code
WITH data AS (SELECT
  'LINESTRING(0 0,100 100)'::geometry AS line,
  'POINT(51 50)':: geometry AS point
)
SELECT ST_Split(ST_Snap(line, point, 1), point) AS snapped_split,
       ST_Split(line, point) AS not_snapped_not_split
       FROM data;
래스터 출력
-[ RECORD 1 ]---------
snapped_split         | GEOMETRYCOLLECTION(LINESTRING(0 0,51 50), LINESTRING(51 50,100 100))
not_snapped_not_split | GEOMETRYCOLLECTION(LINESTRING(0 0,100 100))
Figure
Geometry figure for visual-st-split-03

제목

ST_Subdivide — Computes a rectilinear subdivision of a geometry.

요약

setof geometry ST_Subdivide(geometry geom, integer max_vertices=256, float8 gridSize = -1);

설명

Returns a set of geometries that are the result of dividing geom into parts using rectilinear lines, with each part containing no more than max_vertices.

max_vertices must be 5 or more, as 5 points are needed to represent a closed box.

If the optional gridSize parameter is given (GEOS-3.9.0 or higher required), all result vertices are guaranteed to fall on a snap-rounded grid of the specified size. Note that operations performed on a grid may contain small artifacts produced during grid alignment, see ST_ReducePrecision.

Point-in-polygon and other spatial operations are normally faster for indexed subdivided datasets. Since the bounding boxes for the parts usually cover a smaller area than the original geometry bbox, index queries produce fewer "hit" cases. The "hit" cases are faster because the spatial operations executed by the index recheck process fewer points.

[참고]

When casting a subdivided geometry to geography, the resulting geography may differ from the original. Subdivision adds vertices in planar (geometry) space. If vertices are inserted along the boundary, they will alter the geographical representation, where edges are interpreted as geodesic segments. To minimize distortion, first densify the geography using ST_Segmentize to add geodesic vertices, then cast to geometry before subdivision.

[참고]

This is a set-returning function (SRF) that return a set of rows containing single geometry values. It can be used in a SELECT list or a FROM clause to produce a result set with one record for each result geometry.

GEOS 모듈로 실행

2.2.0 버전부터 사용할 수 있습니다.

Enhanced: 2.5.0 reuses existing points on polygon split, vertex count is lowered from 8 to 5.

Enhanced: 3.1.0 accept a gridSize parameter.

Requires GEOS >= 3.9.0 to use the gridSize parameter

예시

Example: Subdivide a polygon into parts with no more than 10 vertices, and assign each part a unique id.

Code
SELECT row_number() OVER() As rn,geom As wkt
    FROM (SELECT ST_Subdivide('POLYGON((132 10,119 23,85 35,68 29,66 28,49 42,32 56,22 64,32 110,40 119,36 150,
        57 158,75 171,92 182,114 184,132 186,146 178,176 184,179 162,184 141,190 122,
        190 100,185 79,186 56,186 52,178 34,168 18,147 13,132 10))'::geometry, 10))  AS f(geom);
래스터 출력
rn │                                                      wkt
────┼────────────────────────────────────────────────────────────────────────────────────────────────────────────────
  1 │ POLYGON((85 35,68 29,66 28,32 56,22 64,29.82608695652174 100,119 100,119 23,85 35))
  2 │ POLYGON((186 52,178 34,168 18,147 13,132 10,119 23,119 56,186 56,186 52))
  3 │ POLYGON((185 79,186 56,119 56,119 100,190 100,185 79))
  4 │ POLYGON((40 119,36 150,57 158,75 171,92 182,114 184,114 100,29.82608695652174 100,32 110,40 119))
  5 │ POLYGON((132 186,146 178,176 184,179 162,184 141,190 122,190 100,114 100,114 184,132 186))
  
Figure
Geometry figure for visual-st-subdivide-01

Example: Densify a long geography line using ST_Segmentize(geography, distance), and use ST_Subdivide to split the resulting line into sublines of 8 vertices. Densification minimizes the impact of changes to the geography representation of a geometry when subdividing.

Code
SELECT ST_Subdivide(ST_Segmentize('LINESTRING(0 0,85 85)'::geography,
                          1200000)::geometry, 8);
래스터 출력
LINESTRING(0 0,0.487578359029357 5.57659056746196,0.984542144675897 11.1527721155093,1.50101059639722 16.7281035483571,1.94532113630331 21.25)
LINESTRING(1.94532113630331 21.25,2.04869538062779 22.3020741387339,2.64204641967673 27.8740533545155,3.29994062412787 33.443216802941,4.04836719489742 39.0084282520239,4.59890468420694 42.5)
LINESTRING(4.59890468420694 42.5,4.92498503922732 44.5680389206321,5.98737409390639 50.1195229244701,7.3290919767674 55.6587646879025,8.79638749938413 60.1969505994924)
LINESTRING(8.79638749938413 60.1969505994924,9.11375579533779 61.1785363177625,11.6558166691368 66.6648504160202,15.642041247655 72.0867690601745,22.8716627200212 77.3609628116894,24.6991785131552 77.8939011989848)
LINESTRING(24.6991785131552 77.8939011989848,39.4046096622744 82.1822848017636,44.7994523421035 82.5156766227011)
LINESTRING(44.7994523421035 82.5156766227011,85 85)
Figure
Geometry figure for visual-st-subdivide-02

Example: Subdivide the complex geometries of a table in-place. The original geometry records are deleted from the source table, and new records for each subdivided result geometry are inserted.

Code

WITH complex_areas_to_subdivide AS (
    DELETE from polygons_table
    WHERE ST_NPoints(geom) 
> 255
    RETURNING id, column1, column2, column3, geom
)
INSERT INTO polygons_table (fid, column1, column2, column3, geom)
    SELECT fid, column1, column2, column3,
           ST_Subdivide(geom, 255) as geom
    FROM complex_areas_to_subdivide;

Example: Create a new table containing subdivided geometries, retaining the key of the original geometry so that the new table can be joined to the source table. Since ST_Subdivide is a set-returning (table) function that returns a set of single-value rows, this syntax automatically produces a table with one row for each result part.

Code
CREATE TABLE subdivided_geoms AS
    SELECT pkey, ST_Subdivide(geom) AS geom
    FROM original_geoms;

제목

ST_SymDifference — Computes a geometry representing the portions of geometries A and B that do not intersect.

요약

geometry ST_SymDifference(geometry geomA, geometry geomB, float8 gridSize = -1);

설명

Returns a geometry representing the portions of geometries A and B that do not intersect. This is equivalent to ST_Union(A,B) - ST_Intersection(A,B). It is called a symmetric difference because ST_SymDifference(A,B) = ST_SymDifference(B,A).

If the optional gridSize parameter is given (GEOS-3.9.0 or higher required), all result vertices are guaranteed to fall on a snap-rounded grid of the specified size. Note that operations performed on a grid may contain small artifacts produced during grid alignment, see ST_ReducePrecision.

GEOS 모듈로 실행

Enhanced: 3.1.0 accept a gridSize parameter.

Requires GEOS >= 3.9.0 to use the gridSize parameter

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.3

This method implements the SQL/MM specification. SQL-MM 3: 5.1.21

This function supports 3d and will not drop the z-index. However, the result is computed using XY only. The result Z values are copied, averaged or interpolated.

예시

This example shows a 2D-safe symmetric difference of two LineStrings.

Code
SELECT ST_SymDifference('LINESTRING(50 100,50 200)',
        'LINESTRING(50 50,50 150)'
    );
래스터 출력
MULTILINESTRING((50 150,50 200),(50 50,50 100))
Figure
Geometry figure for visual-st-symdifference-01

In 3D, this example does not produce the expected result.

Code
SELECT ST_SymDifference('LINESTRING(1 2 1,1 4 2)',
    'LINESTRING(1 1 3,1 3 4)');
래스터 출력
MULTILINESTRING((1 3 4,1 4 2),(1 1 3,1 2 1))
Figure
Geometry figure for visual-st-symdifference-02

제목

ST_UnaryUnion — Computes the union of the components of a single geometry.

요약

geometry ST_UnaryUnion(geometry geom, float8 gridSize = -1);

설명

A single-input variant of ST_Union. The input may be a single geometry, a MultiGeometry, or a GeometryCollection. The union is applied to the individual elements of the input.

This function can be used to fix MultiPolygons which are invalid due to overlapping components. However, the input components must each be valid. An invalid input component such as a bow-tie polygon may cause an error. For this reason it may be better to use ST_MakeValid.

Another use of this function is to node and dissolve a collection of linestrings which cross or overlap to make them simple. (ST_Node also does this, but it does not provide the gridSize option.)

It is possible to combine ST_UnaryUnion with ST_Collect to fine-tune how many geometries are be unioned at once. This allows trading off between memory usage and compute time, striking a balance between ST_Union and ST_MemUnion.

If the optional gridSize parameter is given (GEOS-3.9.0 or higher required), all result vertices are guaranteed to fall on a snap-rounded grid of the specified size. Note that operations performed on a grid may contain small artifacts produced during grid alignment, see ST_ReducePrecision.

This function supports 3d and will not drop the z-index. However, the result is computed using XY only. The result Z values are copied, averaged or interpolated.

Enhanced: 3.1.0 accept a gridSize parameter.

Requires GEOS >= 3.9.0 to use the gridSize parameter

2.0.0 버전부터 사용할 수 있습니다.


제목

ST_Union — Computes a geometry representing the point-set union of the input geometries.

요약

geometry ST_Union(geometry g1, geometry g2);

geometry ST_Union(geometry g1, geometry g2, float8 gridSize);

geometry ST_Union(geometry[] g1_array);

geometry ST_Union(geometry set g1field);

geometry ST_Union(geometry set g1field, float8 gridSize);

설명

Unions the input geometries, merging geometry to produce a result geometry with no overlaps. The output may be an atomic geometry, a MultiGeometry, or a Geometry Collection. Comes in several variants:

Two-input variant: returns a geometry that is the union of two input geometries. If either input is NULL, then NULL is returned.

Array variant: returns a geometry that is the union of an array of geometries.

Aggregate variant: returns a geometry that is the union of a rowset of geometries. The ST_Union() function is an "aggregate" function in the terminology of PostgreSQL. That means that it operates on rows of data, in the same way the SUM() and AVG() functions do and like most aggregates, it also ignores NULL geometries.

See ST_UnaryUnion for a non-aggregate, single-input variant.

The ST_Union array and set variants use the fast Cascaded Union algorithm described in http://blog.cleverelephant.ca/2009/01/must-faster-unions-in-postgis-14.html

If the optional gridSize parameter is given (GEOS-3.9.0 or higher required), all result vertices are guaranteed to fall on a snap-rounded grid of the specified size. Note that operations performed on a grid may contain small artifacts produced during grid alignment, see ST_ReducePrecision.

[참고]

ST_Collect may sometimes be used in place of ST_Union, if the result is not required to be non-overlapping. ST_Collect is usually faster than ST_Union because it performs no processing on the collected geometries.

GEOS 모듈로 실행

ST_Union creates MultiLineString and does not sew LineStrings into a single LineString. Use ST_LineMerge to sew LineStrings.

NOTE: this function was formerly called GeomUnion(), which was renamed from "Union" because UNION is an SQL reserved word.

Enhanced: 3.1.0 accept a gridSize parameter.

Requires GEOS >= 3.9.0 to use the gridSize parameter

Changed: 3.0.0 does not depend on SFCGAL.

Availability: 1.4.0 - ST_Union was enhanced. ST_Union(geomarray) was introduced and also faster aggregate collection in PostgreSQL.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.3

[참고]

Aggregate version is not explicitly defined in OGC SPEC.

This method implements the SQL/MM specification. SQL-MM 3: 5.1.19 the z-index (elevation) when polygons are involved.

This function supports 3d and will not drop the z-index. However, the result is computed using XY only. The result Z values are copied, averaged or interpolated.

예시

Aggregate example

Code
SELECT id,
       ST_Union(geom) as singlegeom
FROM sometable f
GROUP BY id;
              

Non-Aggregate example

Code
SELECT ST_Union('POINT(1 2)'::geometry, 'POINT(-2 3)'::geometry);
래스터 출력
MULTIPOINT((1 2),(-2 3))
Figure
Geometry figure for visual-st-union-01
Code
SELECT ST_Union('POINT(1 2)'::geometry, 'POINT(1 2)'::geometry);
래스터 출력
POINT(1 2)
Figure
Geometry figure for visual-st-union-02

3D example - sort of supports 3D (and with mixed geometry types!)

Code
SELECT ST_Union(geom)
FROM (
    SELECT 'POLYGON Z((-7 4.2 5,-7.1 4.2 5,-7.1 4.3 5,-7 4.2 5))'::geometry geom
    UNION ALL
    SELECT 'POINT Z(5 5 5)'::geometry geom
    UNION ALL
    SELECT 'POINT Z(-2 3 1)'::geometry geom
    UNION ALL
    SELECT 'LINESTRING Z(5 5 5,10 10 10)'::geometry geom
) AS foo;
래스터 출력
GEOMETRYCOLLECTION(POINT(-2 3 1), LINESTRING(5 5 5,10 10 10), POLYGON((-7 4.2 5,-7.1 4.2 5,-7.1 4.3 5,-7 4.2 5)))
Figure
Geometry figure for visual-st-union-03

This 3D example does not mix dimensions.

Code
SELECT ST_Union(geom)
FROM (
    SELECT 'POLYGON((-7 4.2 2,-7.1 4.2 3,-7.1 4.3 2,-7 4.2 2))'::geometry geom
    UNION ALL
    SELECT 'POINT(5 5 5)'::geometry geom
    UNION ALL
    SELECT 'POINT(-2 3 1)'::geometry geom
    UNION ALL
    SELECT 'LINESTRING(5 5 5,10 10 10)'::geometry geom
) AS foo;
래스터 출력
GEOMETRYCOLLECTION(POINT(-2 3 1), LINESTRING(5 5 5,10 10 10), POLYGON((-7 4.2 2,-7.1 4.2 3,-7.1 4.3 2,-7 4.2 2)))
Figure
Geometry figure for visual-st-union-04

This example unions an array built from a query.

Code
SELECT ST_Union(ARRAY(SELECT geom FROM sometable));

This example unions an array of linestrings.

Code
SELECT ST_Union(ARRAY[
    'LINESTRING(1 2,3 4)'::geometry,
    'LINESTRING(4 5,5 6)'::geometry
]) As wktunion;
래스터 출력
MULTILINESTRING((1 2,3 4),(4 5,5 6))
Figure
Geometry figure for visual-st-union-05

7.14. 도형 공간 처리

초록

These functions compute geometric constructions, or alter geometry size or shape.

  • ST_Buffer — Computes a geometry covering all points within a given distance from a geometry.
  • ST_BuildArea — Creates a polygonal geometry formed by the linework of a geometry.
  • ST_Centroid — 도형의 기하학적 중심을 반환합니다.
  • ST_ChaikinSmoothing — Returns a smoothed version of a geometry, using the Chaikin algorithm
  • ST_CatmullRomSmoothing — Returns a smoothed version of a geometry, using the Catmull-Rom spline algorithm
  • ST_ConcaveHull — Computes a possibly concave geometry that contains all input geometry vertices
  • ST_ConvexHull — Computes the convex hull of a geometry.
  • ST_DelaunayTriangles — Returns the Delaunay triangulation of the vertices of a geometry.
  • ST_FilterByM — Removes vertices based on their M value
  • ST_GeneratePoints — Generates a multipoint of random points contained in a Polygon or MultiPolygon.
  • ST_GeometricMedian — 멀티 포인트의 기하학적 중심값(median)을 반환합니다.
  • ST_LineMerge — Return the lines formed by sewing together a MultiLineString.
  • ST_MaximumInscribedCircle — 도형의 기하학적 중심을 반환합니다.
  • ST_LargestEmptyCircle — Computes the largest circle not overlapping a geometry.
  • ST_MinimumBoundingCircle — Returns the smallest circle polygon that contains a geometry.
  • ST_MinimumBoundingRadius — Returns the center point and radius of the smallest circle that contains a geometry.
  • ST_OrientedEnvelope — Returns a minimum-area rectangle containing a geometry.
  • ST_OffsetCurve — Returns an offset line at a given distance and side from an input line.
  • ST_PointOnSurface — Computes a point guaranteed to lie in a polygon, or on a geometry.
  • ST_Polygonize — Computes a collection of polygons formed from the linework of a set of geometries.
  • ST_ReducePrecision — Returns a valid geometry with points rounded to a grid tolerance.
  • ST_SharedPaths — 두 입력 라인스트링/멀티라인스트링이 공유하는 경로를 담고 있는 집합을 반환합니다.
  • ST_Simplify — Returns a simplified representation of a geometry, using the Douglas-Peucker algorithm.
  • ST_SimplifyPreserveTopology — Returns a simplified and valid representation of a geometry, using the Douglas-Peucker algorithm.
  • ST_SimplifyPolygonHull — Computes a simplified topology-preserving outer or inner hull of a polygonal geometry.
  • ST_SimplifyVW — Returns a simplified representation of a geometry, using the Visvalingam-Whyatt algorithm
  • ST_SetEffectiveArea — Sets the effective area for each vertex, using the Visvalingam-Whyatt algorithm.
  • ST_TriangulatePolygon — Computes the constrained Delaunay triangulation of polygons
  • ST_VoronoiLines — Returns the boundaries of the Voronoi diagram of the vertices of a geometry.
  • ST_VoronoiPolygons — Returns the cells of the Voronoi diagram of the vertices of a geometry.

제목

ST_Buffer — Computes a geometry covering all points within a given distance from a geometry.

요약

geometry ST_Buffer(geometry g1, float radius_of_buffer, text buffer_style_parameters = '');

geometry ST_Buffer(geometry g1, float radius_of_buffer, integer num_seg_quarter_circle);

geography ST_Buffer(geography g1, float radius_of_buffer, text buffer_style_parameters);

geography ST_Buffer(geography g1, float radius_of_buffer, integer num_seg_quarter_circle);

설명

Computes a POLYGON or MULTIPOLYGON that represents all points whose distance from a geometry/geography is less than or equal to a given distance. A negative distance shrinks the geometry rather than expanding it. A negative distance may shrink a polygon completely, in which case POLYGON EMPTY is returned. For points and lines negative distances always return empty results.

For geometry, the distance is specified in the units of the Spatial Reference System of the geometry. For geography, the distance is specified in meters.

The optional third parameter controls the buffer accuracy and style. The accuracy of circular arcs in the buffer is specified as the number of line segments used to approximate a quarter circle (default is 8). The buffer style can be specified by providing a list of blank-separated key=value pairs as follows:

  • 'quad_segs=#' : number of line segments used to approximate a quarter circle (default is 8).

  • 'endcap=round|flat|square' : endcap style (defaults to "round"). 'butt' is accepted as a synonym for 'flat'.

  • 'join=round|mitre|bevel' : join style (defaults to "round"). 'miter' is accepted as a synonym for 'mitre'.

  • 'mitre_limit=#.#' : mitre ratio limit (only affects mitered join style). 'miter_limit' is accepted as a synonym for 'mitre_limit'.

  • 'side=both|left|right' : defaults to 'both'. 'left' or 'right' performs a single-sided buffer on the geometry, with the buffered side relative to the direction of the line. This is only applicable to LINESTRING geometry and does not affect POINT or POLYGON geometries. By default end caps are square when 'left' or 'right' are specified.

[참고]

For geography this is a thin wrapper around the geometry implementation. It determines a planar spatial reference system that best fits the bounding box of the geography object (trying UTM, Lambert Azimuthal Equal Area (LAEA) North/South pole, and finally Mercator ). The buffer is computed in the planar space, and then transformed back to WGS84. This may not produce the desired behavior if the input object is much larger than a UTM zone or crosses the dateline

[참고]

Buffer can handle invalid inputs and the output is always a valid polygonal geometry. Buffering by distance 0 is sometimes used as a way of repairing invalid polygons. ST_MakeValid is more suitable for this process as it can handle multi-polygons.

[참고]

Buffering is sometimes used to perform a within-distance search. For this use case it is more efficient to use ST_DWithin.

[참고]

This function ignores the Z dimension. It always gives a 2D result even when used on a 3D geometry.

Enhanced: 2.5.0 - ST_Buffer geometry support was enhanced to allow for side buffering specification side=both|left|right.

Availability: 1.5 - ST_Buffer was enhanced to support different endcaps and join types. These are useful for example to convert road linestrings into polygon roads with flat or square edges instead of rounded edges. Thin wrapper for geography was added.

GEOS 모듈로 실행

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.3

This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 5.1.30

예시

The textual results are rounded to whole coordinate units for readability. Each result remains available as text, while the manual initially favors the shared input/output figure.

quad_segs=8 (기본값)

Code
SELECT ST_Buffer(
  ST_GeomFromText('POINT(100 90)'),
  50, 'quad_segs=8');
래스터 출력
POLYGON((150 90,149 80,146 71,142 62,135 55,128 48,119 44,110 41,100 40,90 41,81 44,72 48,65 55,58 62,54 71,51 80,50 90,51 100,54 109,58 118,65 125,72 132,81 136,90 139,100 140,110 139,119 136,128 132,135 125,142 118,146 109,149 100,150 90))
Figure
Geometry figure for st-buffer-example-01

quad_segs=2

Code
SELECT ST_Buffer(
  ST_GeomFromText('POINT(100 90)'),
  50, 'quad_segs=2');
래스터 출력
POLYGON((150 90,135 55,100 40,65 55,50 90,65 125,100 140,135 125,150 90))
Figure
Geometry figure for st-buffer-example-02

endcap=round join=round (기본값)

Code
SELECT ST_Buffer(
  ST_GeomFromText('LINESTRING(50 50,150 150,150 50)'),
  10, 'endcap=round join=round');
래스터 출력
POLYGON((143 157,144 158,146 159,148 160,150 160,152 160,154 159,156 158,157 157,158 156,159 154,160 152,160 150,160 50,160 48,159 46,158 44,157 43,156 42,154 41,152 40,150 40,148 40,146 41,144 42,143 43,142 44,141 46,140 48,140 50,140 126,57 43,56 42,54 41,52 40,50 40,48 40,46 41,44 42,43 43,42 44,41 46,40 48,40 50,40 52,41 54,42 56,43 57,143 157))
Figure
Geometry figure for st-buffer-example-03

endcap=square

Code
SELECT ST_Buffer(
  ST_GeomFromText('LINESTRING(50 50,150 150,150 50)'),
  10, 'endcap=square join=round');
래스터 출력
POLYGON((143 157,144 158,146 159,148 160,150 160,152 160,154 159,156 158,157 157,158 156,159 154,160 152,160 150,160 50,160 40,140 40,140 126,57 43,50 36,36 50,143 157))
Figure
Geometry figure for st-buffer-example-04

endcap=flat

Code
SELECT ST_Buffer(
  ST_GeomFromText('LINESTRING(50 50,150 150,150 50)'),
  10, 'endcap=flat join=round');
래스터 출력
POLYGON((143 157,144 158,146 159,148 160,150 160,152 160,154 159,156 158,157 157,158 156,159 154,160 152,160 150,160 50,140 50,140 126,57 43,43 57,143 157))
Figure
Geometry figure for st-buffer-example-05

join=bevel

Code
SELECT ST_Buffer(
  ST_GeomFromText('LINESTRING(50 50,150 150,150 50)'),
  10, 'join=bevel');
래스터 출력
POLYGON((143 157,160 150,160 50,160 48,159 46,158 44,157 43,156 42,154 41,152 40,150 40,148 40,146 41,144 42,143 43,142 44,141 46,140 48,140 50,140 126,57 43,56 42,54 41,52 40,50 40,48 40,46 41,44 42,43 43,42 44,41 46,40 48,40 50,40 52,41 54,42 56,43 57,143 157))
Figure
Geometry figure for st-buffer-example-06

join=mitre mitre_limit=5.0 (마이터 제한 기본값)

Code
SELECT ST_Buffer(
  ST_GeomFromText('LINESTRING(50 50,150 150,150 50)'),
  10, 'join=mitre mitre_limit=5.0');
래스터 출력
POLYGON((160 174,160 50,160 48,159 46,158 44,157 43,156 42,154 41,152 40,150 40,148 40,146 41,144 42,143 43,142 44,141 46,140 48,140 50,140 126,57 43,56 42,54 41,52 40,50 40,48 40,46 41,44 42,43 43,42 44,41 46,40 48,40 50,40 52,41 54,42 56,43 57,160 174))
Figure
Geometry figure for st-buffer-example-07

join=mitre mitre_limit=1

Code
SELECT ST_Buffer(
  ST_GeomFromText('LINESTRING(50 50,150 150,150 50)'),
  10, 'join=mitre mitre_limit=1.0');
래스터 출력
POLYGON((148 162,160 157,160 50,160 48,159 46,158 44,157 43,156 42,154 41,152 40,150 40,148 40,146 41,144 42,143 43,142 44,141 46,140 48,140 50,140 126,57 43,56 42,54 41,52 40,50 40,48 40,46 41,44 42,43 43,42 44,41 46,40 48,40 50,40 52,41 54,42 56,43 57,148 162))
Figure
Geometry figure for st-buffer-example-08

side=left

Code
SELECT ST_Buffer(
  ST_GeomFromText('LINESTRING(50 50,150 150,150 50)'),
  10, 'side=left');
래스터 출력
POLYGON((150 50,150 150,50 50,43 57,143 157,144 158,146 159,148 160,150 160,152 160,154 159,156 158,157 157,158 156,159 154,160 152,160 150,160 50,150 50))
Figure
Geometry figure for st-buffer-example-09

side=right

Code
SELECT ST_Buffer(
  ST_GeomFromText('LINESTRING(50 50,150 150,150 50)'),
  10, 'side=right');
래스터 출력
POLYGON((50 50,150 150,150 50,140 50,140 126,57 43,50 50))
Figure
Geometry figure for st-buffer-example-10

side=left join=mitre

Code
SELECT ST_Buffer(
  ST_GeomFromText('LINESTRING(50 50,150 150,150 50)'),
  10, 'side=left join=mitre');
래스터 출력
POLYGON((150 50,150 150,50 50,43 57,160 174,160 50,150 50))
Figure
Geometry figure for st-buffer-example-11

right-hand winding, polygon boundary side=left

Code
SELECT ST_Buffer(
  ST_ForceRHR(ST_Boundary(ST_GeomFromText(
    'POLYGON ((50 50,50 150,150 150,150 50,50 50))'))),
  20, 'side=left');
래스터 출력
POLYGON((50 50,50 150,150 150,150 50,50 50))
Figure
Geometry figure for st-buffer-example-12

right-hand winding, polygon boundary side=right

Code
SELECT ST_Buffer(
  ST_ForceRHR(ST_Boundary(ST_GeomFromText(
    'POLYGON ((50 50,50 150,150 150,150 50,50 50))'))),
  20, 'side=right');
래스터 출력
POLYGON((50 50,50 70,50 150,150 150,150 50,70 50,50 50),(70 70,130 70,130 130,70 130,70 70))
Figure
Geometry figure for st-buffer-example-13
 

A buffered point approximates a circle. A buffered point forcing approximation of (see diagram) 2 points per quarter circle is poly with 8 sides (see diagram)

Code
SELECT ST_NPoints(ST_Buffer('POINT(100 90)'::geometry, 50)) As promisingcircle_pcount,
ST_NPoints(ST_Buffer('POINT(100 90)'::geometry, 50, 2)) As lamecircle_pcount;
래스터 출력
promisingcircle_pcount | lamecircle_pcount
------------------------+-------------------
             33 |                9

A lighter, less smooth circle using only 2 points per quarter circle is an octagon.

The following example creates a 100 meter octagon in NAD83 longitude/latitude by transforming to the Massachusetts state plane meter projection and then buffering. The figure shows the input and output in separate panels because the coordinates are in different SRIDs.

Code
WITH input AS (
  SELECT ST_SetSRID(ST_Point(-71.063526, 42.35785), 4269) AS point_4269
), projected AS (
  SELECT point_4269,
         ST_Transform(point_4269, 26986) AS point_26986
  FROM input
)
SELECT point_4269 AS input_point_4269,
       ST_Buffer(point_26986, 100, 2) AS octagon_26986
FROM projected;
래스터 출력
SRID=4269;POINT(-71.063526 42.35785) | SRID=26986;POLYGON((236057.5905746494 900908.7599186979,236028.30125276805 900838.0492405792,235957.5905746494 900808.7599186979,235886.87989653074 900838.0492405792,235857.5905746494 900908.7599186979,235886.87989653074 900979.4705968165,235957.5905746494 901008.7599186979,236028.30125276805 900979.4705968165,236057.5905746494 900908.7599186979))
Figure
Geometry figure for visual-st-buffer-15

Buffering a polygon by a positive distance and then by the same negative distance is a morphological closing operation. It can be useful for smoothing noisy boundaries, such as simplifying a coastline by removing narrow inlets and bays. The result intentionally changes the shape and area of the input, and the distance must be chosen in the units of the input SRS. For data in a geographic SRS, transform to a projected SRS suited to the operation first; for cartographic visualization in Web Mercator, using that display SRS can be appropriate.

Smooth a coastline using a 1 km closing operation, then simplify the result. The example uses Massachusetts State Plane meter units for the operation.

Code
WITH projected AS (
  SELECT id, ST_Transform(geom, 26986) AS geom
  FROM coast
),
closed AS (
  SELECT id, ST_Buffer(ST_Buffer(geom, 1000), -1000) AS geom
  FROM projected
)
SELECT id, ST_Transform(ST_SimplifyPreserveTopology(geom, 50), 4326) AS geom
FROM closed;

The same technique is described in Paul Ramsey's Removing Complexities. The final simplification step is optional; use ST_SimplifyPreserveTopology when polygonal validity matters, and check the result against the cartographic or analytical tolerance required by the application.

A small negative buffer can also be used as a heuristic to find narrow polygon spikes. The query below compares how much area and perimeter remain after erosion. A large erosion_index indicates that the perimeter dropped proportionally more than the area. This is only a preselection aid; the threshold and buffer distance must be chosen for the data units and the kind of spike being checked.

Code
WITH sample(id, geom) AS (
  VALUES
    ('plain', 'POLYGON((0 0,10 0,10 10,0 10,0 0))'::geometry),
    ('spike', 'POLYGON((0 0,10 0,10 10,5.2 10,5 16,4.8 10,0 10,0 0))'::geometry)
),
eroded AS (
  SELECT id, geom, ST_Buffer(geom, -0.5) AS eroded_geom
  FROM sample
),
scored AS (
  SELECT id,
         round((
           ST_Area(eroded_geom) / ST_Area(geom) /
           NULLIF(ST_Perimeter(eroded_geom) / ST_Perimeter(geom), 0)
         )::numeric, 3) AS erosion_index
  FROM eroded
  WHERE NOT ST_IsEmpty(eroded_geom)
)
SELECT id, erosion_index, erosion_index > 1.1 AS possible_spike
FROM scored
ORDER BY id;
래스터 출력
id   | erosion_index | possible_spike
-------+---------------+----------------
 plain |         0.900 | f
 spike |         1.147 | t
Figure
Geometry figure for visual-st-buffer-16

A variable-distance buffer can be approximated by buffering each vertex of a line by a distance interpolated along the line, building the convex hull for each consecutive pair of vertex buffers, and unioning the segment hulls. As with any geometry buffer, distances are in the units of the input SRS.

Taper a line buffer from 5 to 25 units along the line.

Code
WITH line AS (
  SELECT 'LINESTRING(0 0, 100 0, 160 40)'::geometry AS geom
),
vertices AS (
  SELECT (dump).path[1] AS n,
         (dump).geom AS geom,
         line.geom AS line_geom
  FROM line
  CROSS JOIN LATERAL ST_DumpPoints(line.geom) AS dump
),
radii AS (
  SELECT n,
         geom,
         5 + (25 - 5) * ST_LineLocatePoint(line_geom, geom) AS radius
  FROM vertices
),
segments AS (
  SELECT n,
         geom,
         radius,
         lead(geom) OVER (ORDER BY n) AS next_geom,
         lead(radius) OVER (ORDER BY n) AS next_radius
  FROM radii
)
SELECT ST_Union(
         ST_ConvexHull(
           ST_Collect(
             ST_Buffer(geom, radius),
             ST_Buffer(next_geom, next_radius)
           )
         )
       ) AS tapered_buffer
FROM segments
WHERE next_geom IS NOT NULL;
래스터 출력
POLYGON((96.758 -16.301,-0.975 -4.904,-1.913 -4.619,-2.778 -4.157,-3.536 -3.536,-4.157 -2.778,-4.619 -1.913,-4.904 -0.975,-5 0,-4.904 0.975,-4.619 1.913,-4.157 2.778,-3.536 3.536,-2.778 4.157,-1.913 4.619,-0.975 4.904,93.101 15.875,142.322 57.678,146.111 60.787,150.433 63.097,155.123 64.52,160 65,164.877 64.52,169.567 63.097,173.889 60.787,177.678 57.678,180.787 53.889,183.097 49.567,184.52 44.877,185 40,184.52 35.123,183.097 30.433,180.787 26.111,177.678 22.322,173.889 19.213,169.567 16.903,106.36 -15.355,103.242 -16.301,100 -16.62,96.758 -16.301))
Figure
Geometry figure for visual-st-buffer-17

제목

ST_BuildArea — Creates a polygonal geometry formed by the linework of a geometry.

요약

geometry ST_BuildArea(geometry geom);

설명

Creates an areal geometry formed by the constituent linework of the input geometry. The input can be a LineString, MultiLineString, Polygon, MultiPolygon or a GeometryCollection. The result is a Polygon or MultiPolygon, depending on input. If the input linework does not form polygons, NULL is returned.

Unlike ST_MakePolygon, this function accepts rings formed by multiple lines, and can form any number of polygons.

This function converts inner rings into holes. To turn inner rings into polygons as well, use ST_Polygonize.

[참고]

Input linework must be correctly noded for this function to work properly. ST_Node can be used to node lines.

If the input linework crosses, this function will produce invalid polygons. ST_MakeValid can be used to ensure the output is valid.

1.1.0 버전부터 사용할 수 있습니다.

예시

Building an area from five input lines.

Code
WITH data(geom) AS (VALUES
   ('LINESTRING (180 40,30 20,20 90)'::geometry),
  ('LINESTRING (180 40,160 160)'::geometry),
  ('LINESTRING (160 160,80 190,80 120,20 90)'::geometry),
  ('LINESTRING (80 60,120 130,150 80)'::geometry),
  ('LINESTRING (80 60,150 80)'::geometry)
)
SELECT ST_BuildArea(ST_Collect(geom )) AS wkt
    FROM data;
래스터 출력
POLYGON((180 40,30 20,20 90,80 120,80 190,160 160,180 40),(150 80,120 130,80 60,150 80))
Figure
Geometry figure for visual-st-buildarea-01

Create a donut from two circular polygons.

Code
WITH input AS (
  SELECT 'POINT(100 90)'::geometry AS geom
),
rings AS (
  SELECT ST_Buffer(geom, 25, 'quad_segs=1') AS inring,
         ST_Buffer(geom, 50, 'quad_segs=1') AS outring
  FROM input
)
SELECT inring AS inner_ring,
       outring AS outer_ring,
       ST_BuildArea(ST_Collect(inring, outring)) AS area
FROM rings;
래스터 출력
-[ RECORD 1 ]-----
inner_ring | POLYGON((125 90,100 65,75 90,100 115,125 90))
outer_ring | POLYGON((150 90,100 40,50 90,100 140,150 90))
area       | POLYGON((150 90,100 40,50 90,100 140,150 90),(125 90,100 115,75 90,100 65,125 90))
Figure
Geometry figure for visual-st-buildarea-02

Input linework that crosses at non-endpoint intersections must be noded before building areas:

Code
WITH lines(geom) AS (VALUES
  ('LINESTRING(36 35,45 307)'::geometry),
  ('LINESTRING(30 290,390 280)'::geometry),
  ('LINESTRING(320 60,300 310)'::geometry),
  ('LINESTRING(20 60,320 60)'::geometry),
  ('LINESTRING(120 140,168 225)'::geometry),
  ('LINESTRING(140 220,220 150,120 170)'::geometry)
),
noded AS (
  SELECT ST_Node(ST_UnaryUnion(ST_Collect(geom))) AS geom FROM lines
)
SELECT ST_BuildArea(geom) AS area
FROM noded;
래스터 출력
POLYGON((320 60,36.8 60,44.4 289.6,302.2 282.4,320 60),(156.9 205.3,135.2 167,220 150,156.9 205.3))
Figure
Geometry figure for visual-st-buildarea-03

참고

ST_Collect, ST_MakePolygon, ST_MakeValid, ST_Node, ST_Polygonize, ST_BdPolyFromText, ST_BdMPolyFromText (wrappers to this function with standard OGC interface)


제목

ST_Centroid — 도형의 기하학적 중심을 반환합니다.

요약

geometry ST_Centroid(geometry g1);

geography ST_Centroid(geography g1, boolean use_spheroid = true);

설명

Computes a point which is the geometric center of mass of a geometry. For [MULTI]POINTs, the centroid is the arithmetic mean of the input coordinates. For [MULTI]LINESTRINGs, the centroid is computed using the weighted length of each line segment. For [MULTI]POLYGONs, the centroid is computed in terms of area. If an empty geometry is supplied, an empty GEOMETRYCOLLECTION is returned. If NULL is supplied, NULL is returned. If CIRCULARSTRING or COMPOUNDCURVE are supplied, they are converted to linestring with CurveToLine first, then same than for LINESTRING

For mixed-dimension input, the result is equal to the centroid of the component Geometries of highest dimension (since the lower-dimension geometries contribute zero "weight" to the centroid).

Note that for polygonal geometries the centroid does not necessarily lie in the interior of the polygon. For example, see the diagram below of the centroid of a C-shaped polygon. To construct a point guaranteed to lie in the interior of a polygon use ST_PointOnSurface.

New in 2.3.0 : supports CIRCULARSTRING and COMPOUNDCURVE (using CurveToLine)

Availability: 2.4.0 support for geography was introduced.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1.

This method implements the SQL/MM specification. SQL-MM 3: 8.1.4, 9.5.5

예시

Centroid of a MultiPoint.

Code
SELECT ST_Centroid(
  'MULTIPOINT (8 24,10 92,12 154,17 68,28 10,29 52,29 84,55 50,56 24,131 14,160 180,189 180)');
래스터 출력
POINT(60.333 77.667)
Figure
Geometry figure for st-centroid-multipoint

Centroid of a LineString.

Code
SELECT ST_Centroid(
  'LINESTRING (190 160,10 190,40 90,20 70,10 10,30 40,30 10,110 40,70 10,110 10,140 40,140 10,160 30,180 10)');
래스터 출력
POINT(76.191 79.876)
Figure
Geometry figure for visual-st-centroid-02

Centroid of a Polygon.

Code
SELECT ST_Centroid(
  'POLYGON ((190 190,10 190,10 10,190 10,190 20,160 30,60 30,60 130,190 140,190 190))');
래스터 출력
POINT(80.251 113.405)
Figure
Geometry figure for visual-st-centroid-03

Centroid of the highest-dimension components of a GeometryCollection.

Code
SELECT ST_Centroid(
  'GEOMETRYCOLLECTION (POLYGON ((190 170,180 100,80 140,80 160,130 160,110 180,110 190,180 180,190 170)),
    LINESTRING (80 120,120 20,140 70,150 30,180 50,190 10),
    MULTIPOINT (19 150,22 49,30 13,32 101,45 35,67 88,75 16))');
래스터 출력
POINT(143.361 148.263)
Figure
Geometry figure for visual-st-centroid-04
Code
SELECT ST_Centroid(g)
FROM  ST_GeomFromText('CIRCULARSTRING(0 2,-1 1,0 0,0.5 0,1 0,2 1,1 2,0.5 2,0 2)')  AS g ;
래스터 출력
st_astext
-------------
 POINT(0.5 1)
(1 row)
Figure
Geometry figure for visual-st-centroid-05
Code
SELECT ST_Centroid(g)
FROM  ST_GeomFromText('COMPOUNDCURVE(CIRCULARSTRING(0 2,-1 1,0 0),(0 0,0.5 0,1 0), CIRCULARSTRING( 1 0,2 1,1 2),(1 2,0.5 2,0 2))' ) AS g;
래스터 출력
st_astext
-------------
 POINT(0.5 1)
(1 row)
Figure
Geometry figure for visual-st-centroid-06

Centroids of the parts of a MultiPolygon.

Code
SELECT ST_Collect(ST_Centroid(geom) ORDER BY path)
FROM ST_Dump('MULTIPOLYGON (
    ((0 0,0 1,1 1,1 0,0 0)),
    ((2 2,2 3,3 3,3 2,2 2))
  )'::geometry);
래스터 출력
MULTIPOINT((0.5 0.5),(2.5 2.5))
Figure
Geometry figure for visual-st-centroid-07

제목

ST_ChaikinSmoothing — Returns a smoothed version of a geometry, using the Chaikin algorithm

요약

geometry ST_ChaikinSmoothing(geometry geom, integer nIterations = 1, boolean preserveEndPoints = false);

설명

Smoothes a linear or polygonal geometry using Chaikin's algorithm. The degree of smoothing is controlled by the nIterations parameter. On each iteration, each interior vertex is replaced by two vertices located at 1/4 of the length of the line segments before and after the vertex. A reasonable degree of smoothing is provided by 3 iterations; the maximum is limited to 5.

If preserveEndPoints is true, the endpoints of Polygon rings are not smoothed. The endpoints of LineStrings are always preserved.

[참고]

The number of vertices doubles with each iteration, so the result geometry may have many more points than the input. To reduce the number of points use a simplification function on the result (see ST_Simplify, ST_SimplifyPreserveTopology and ST_SimplifyVW).

The result has interpolated values for the Z and M dimensions when present.

This function supports 3d and will not drop the z-index.

Availability: 2.5.0

예시

Smoothing a Polygon using 1, 2 and 3 iterations.

Code
SELECT n AS iterations, ST_ChaikinSmoothing(
    'POLYGON ((20 20,60 90,10 150,100 190,190 160,130 120,190 50,140 70,120 10,90 60,20 20))', n
  ) AS smoothed
FROM generate_series(1, 3) AS n;
래스터 출력
1 | POLYGON((30 37.5,50 72.5,47.5 105,22.5 135,32.5 160,77.5 180,122.5 182.5,167.5 167.5,175 150,145 130,145 102.5,175 67.5,177.5 55,152.5 65,135 55,125 25,112.5 22.5,97.5 47.5,72.5 50,37.5 30,30 37.5))
2 | POLYGON((35 46.25,45 63.75,49.375 80.625,48.125 96.875,41.25 112.5,28.75 127.5,25 141.25,30 153.75,43.75 165,66.25 175,88.75 180.625,111.25 181.875,133.75 178.75,156.25 171.25,169.375 163.125,173.125 154.375,167.5 145,152.5 135,145 123.125,145 109.375,152.5 93.75,167.5 76.25,175.625 64.375,176.875 58.125,171.25 57.5,158.75 62.5,148.125 62.5,139.375 57.5,132.5 47.5,127.5 32.5,121.875 24.375,115.625 23.125,108.75 28.75,101.25 41.25,91.25 48.125,78.75 49.375,63.75 45,46.25 35,35.625 31.875,31.875 35.625,35 46.25))
3 | POLYGON((37.5 50.625,42.5 59.375,46.09375 67.96875,48.28125 76.40625,49.0625 84.6875,48.4375 92.8125,46.40625 100.78125,42.96875 108.59375,38.125 116.25,31.875 123.75,27.8125 130.9375,25.9375 137.8125,26.25 144.375,28.75 150.625,33.4375 156.5625,40.3125 162.1875,49.375 167.5,60.625 172.5,71.875 176.40625,83.125 179.21875,94.375 180.9375,105.625 181.5625,116.875 181.09375,128.125 179.53125,139.375 176.875,150.625 173.125,159.53125 169.21875,166.09375 165.15625,170.3125 160.9375,172.1875 156.5625,171.71875 152.03125,168.90625 147.34375,163.75 142.5,156.25 137.5,150.625 132.03125,146.875 126.09375,145 119.6875,145 112.8125,146.875 105.46875,150.625 97.65625,156.25 89.375,163.75 80.625,169.53125 73.28125,173.59375 67.34375,175.9375 62.8125,176.5625 59.6875,175.46875 57.96875,172.65625 57.65625,168.125 58.75,161.875 61.25,156.09375 62.5,150.78125 62.5,145.9375 61.25,141.5625 58.75,137.65625 55,134.21875 50,131.25 43.75,128.75 36.25,126.09375 30.46875,123.28125 26.40625,120.3125 24.0625,117.1875 23.4375,113.90625 24.53125,110.46875 27.34375,106.875 31.875,103.125 38.125,98.75 42.96875,93.75 46.40625,88.125 48.4375,81.875 49.0625,75 48.28125,67.5 46.09375,59.375 42.5,50.625 37.5,43.59375 34.21875,38.28125 32.65625,34.6875 32.8125,32.8125 34.6875,32.65625 38.28125,34.21875 43.59375,37.5 50.625))
Figure
Geometry figure for visual-st-chaikinsmoothing-01

Smoothing a LineString using 1, 2 and 3 iterations.

Code
SELECT n AS iterations, ST_ChaikinSmoothing(
    'LINESTRING (10 140,80 130,100 190,190 150,140 20,120 120,50 30,30 100)', n
  ) AS smoothed
FROM generate_series(1, 3) AS n;
래스터 출력
1 | LINESTRING(10 140,62.5 132.5,85 145,95 175,122.5 180,167.5 160,177.5 117.5,152.5 52.5,135 45,125 95,102.5 97.5,67.5 52.5,45 47.5,30 100)
2 | LINESTRING(10 140,49.375 134.375,68.125 135.625,79.375 141.875,87.5 152.5,92.5 167.5,101.875 176.25,115.625 178.75,133.75 175,156.25 165,170 149.375,175 128.125,171.25 101.25,158.75 68.75,148.125 50.625,139.375 46.875,132.5 57.5,127.5 82.5,119.375 95.625,108.125 96.875,93.75 86.25,76.25 63.75,61.875 51.25,50.625 48.75,41.25 60.625,30 100)
3 | LINESTRING(10 140,39.53125 135.78125,54.0625 134.6875,63.4375 135.3125,70.9375 137.1875,76.5625 140.3125,81.40625 144.53125,85.46875 149.84375,88.75 156.25,91.25 163.75,94.84375 169.6875,99.53125 174.0625,105.3125 176.875,112.1875 178.125,120.15625 177.8125,129.21875 175.9375,139.375 172.5,150.625 167.5,159.6875 161.09375,166.5625 153.28125,171.25 144.0625,173.75 133.4375,174.0625 121.40625,172.1875 107.96875,168.125 93.125,161.875 76.875,156.09375 64.21875,150.78125 55.15625,145.9375 49.6875,141.5625 47.8125,137.65625 49.53125,134.21875 54.84375,131.25 63.75,128.75 76.25,125.46875 85.78125,121.40625 92.34375,116.5625 95.9375,110.9375 96.5625,104.53125 94.21875,97.34375 88.90625,89.375 80.625,80.625 69.375,72.65625 60.625,65.46875 54.375,59.0625 50.625,53.4375 49.375,48.28125 51.71875,43.59375 57.65625,38.4375 70.46875,30 100)
Figure
Geometry figure for visual-st-chaikinsmoothing-02

Smoothing a triangle shows the weakest visual change, so it is kept last.

Code
SELECT ST_ChaikinSmoothing(geom) smoothed
FROM (SELECT  'POLYGON((0 0,8 8,0 16,0 0))'::geometry geom) AS foo;
래스터 출력
POLYGON((2 2,6 6,6 10,2 14,0 12,0 4,2 2))
Figure
Geometry figure for visual-st-chaikinsmoothing-03

제목

ST_CatmullRomSmoothing — Returns a smoothed version of a geometry, using the Catmull-Rom spline algorithm

요약

geometry ST_CatmullRomSmoothing(geometry geom, integer nSegments = 5);

설명

Smoothes a linear or polygonal geometry using the Catmull-Rom spline algorithm. Unlike ST_ChaikinSmoothing, this is an interpolating spline: the output curve passes through every original vertex. Between each pair of consecutive original vertices, nSegments - 1 new intermediate points are inserted.

The nSegments parameter controls the density of the output. With nSegments = 5 (the default), each original span is divided into 5 sub-segments (inserting 4 new points per span). The minimum value is 2.

At least 4 input vertices are required to apply smoothing; geometries with fewer vertices are returned unchanged. Points and multipoints are always returned unchanged.

[참고]

The output vertex count grows as 1 + (N-1) * nSegments for open lines, and 1 + N * nSegments for closed rings, where N is the number of input vertices. For large geometries, use a simplification function on the result to reduce the number of points (see ST_Simplify, ST_SimplifyPreserveTopology and ST_SimplifyVW).

The result has interpolated values for the Z and M dimensions when present.

This function supports 3d and will not drop the z-index.

Availability: 3.6.0

예시

Smoothing a LineString using nSegments = 5 and 10.

Code
WITH input(geom) AS (VALUES
  ('LINESTRING (10 140,80 130,100 190,190 150,140 20,120 120,50 30,30 100)'::geometry)
)
SELECT ST_CatmullRomSmoothing(geom, 5) AS segments_5,
  ST_CatmullRomSmoothing(geom, 10) AS segments_10
FROM input;
래스터 출력
LINESTRING(10 140,24.8 136.88,40.4 132.64,55.6 128.96,69.2 127.52,80 130,86.08 139.12,88.24 153.76,89.36 169.84,92.32 183.28,100 190,115.76 189.84,137.68 185.52,160.72 177.28,179.84 165.36,190 150,188.48 126.08,178.64 93.44,164.56 59.76,150.32 32.72,140 20,134.88 28.32,132.24 52.56,130.16 82.64,126.72 108.48,120 120,108.4 111.6,93.2 90,76.8 63.6,61.6 40.8,50 30,42.8 33.76,38.4 46.48,35.6 64.32,33.2 83.44,30 100) | LINESTRING(10 140,17.225 138.685,24.8 136.88,32.575 134.795,40.4 132.64,48.125 130.625,55.6 128.96,62.675 127.855,69.2 127.52,75.025 128.165,80 130,83.71 133.615,86.08 139.12,87.47 146.005,88.24 153.76,88.75 161.875,89.36 169.84,90.43 177.145,92.32 183.28,95.39 187.735,100 190,106.795 190.455,115.76 189.84,126.265 188.185,137.68 185.52,149.375 181.875,160.72 177.28,171.085 171.765,179.84 165.36,186.355 158.095,190 150,190.535 139.61,188.48 126.08,184.345 110.37,178.64 93.44,171.875 76.25,164.56 59.76,157.205 44.93,150.32 32.72,144.415 24.09,140 20,137.01 21.54,134.88 28.32,133.37 39.08,132.24 52.56,131.25 67.5,130.16 82.64,128.73 96.72,126.72 108.48,123.89 116.66,120 120,114.8 117.975,108.4 111.6,101.1 101.925,93.2 90,85 76.875,76.8 63.6,68.9 51.225,61.6 40.8,55.2 33.375,50 30,45.975 30.52,42.8 33.76,40.325 39.24,38.4 46.48,36.875 55,35.6 64.32,34.425 73.96,33.2 83.44,31.775 92.28,30 100)
Figure
Geometry figure for visual-st-catmullromsmoothing-01

Smoothing a 4-point collinear line with default nSegments=5 shows the minimal change case.

Code
SELECT ST_CatmullRomSmoothing('LINESTRING(0 0,5 0,10 0,15 0)');
래스터 출력
LINESTRING(0 0,1 0,2 0,3 0,4 0,5 0,6 0,7 0,8 0,9 0,10 0,11 0,12 0,13 0,14 0,15 0)
Figure
Geometry figure for visual-st-catmullromsmoothing-02

Smoothing a Polygon using nSegments = 5 and 10. This larger example is kept last.

Code
WITH input(geom) AS (VALUES
  ('POLYGON ((20 20,60 90,10 150,100 190,190 160,130 120,190 50,140 70,120 10,90 60,20 20))'::geometry)
)
SELECT ST_CatmullRomSmoothing(geom, 5) AS segments_5,
  ST_CatmullRomSmoothing(geom, 10) AS segments_10
FROM input;
래스터 출력
POLYGON((20 20,22.4 27.12,32.4 40.56,45.2 57.44,56 74.88,60 90,53.52 102.96,39.76 115.68,24.24 127.92,12.48 139.44,10 150,19.04 160.4,35.92 170.8,57.28 180,79.76 186.8,100 190,120.4 188.64,143.2 183.52,164.8 176.08,181.6 167.76,190 160,185.68 153.12,171.04 146.16,152.56 138.64,136.72 130.08,130 120,136.08 106.48,150.64 89.84,168.16 72.96,183.12 58.72,190 50,186.56 49.52,176.48 55.36,163.12 63.44,149.84 69.68,140 70,134.24 61.36,130.32 46.48,127.28 29.92,124.16 16.24,120 10,115.28 14.4,110.64 26.4,105.36 41.2,98.72 54,90 60,76.8 56,59.6 45.2,42 32.4,27.6 22.4,20 20)) | POLYGON((20 20,19.95 22.59,22.4 27.12,26.75 33.23,32.4 40.56,38.75 48.75,45.2 57.44,51.15 66.27,56 74.88,59.15 82.91,60 90,58.015 96.495,53.52 102.96,47.205 109.365,39.76 115.68,31.875 121.875,24.24 127.92,17.545 133.785,12.48 139.44,9.735 144.855,10 150,13.33 155.125,19.04 160.4,26.71 165.675,35.92 170.8,46.25 175.625,57.28 180,68.59 183.775,79.76 186.8,90.37 188.925,100 190,109.675 189.88,120.4 188.64,131.725 186.46,143.2 183.52,154.375 180,164.8 176.08,174.025 171.94,181.6 167.76,187.075 163.72,190 160,189.535 156.54,185.68 153.12,179.245 149.68,171.04 146.16,161.875 142.5,152.56 138.64,143.905 134.52,136.72 130.08,131.815 125.26,130 120,131.635 113.81,136.08 106.48,142.645 98.37,150.64 89.84,159.375 81.25,168.16 72.96,176.305 65.33,183.12 58.72,187.915 53.49,190 50,189.32 48.715,186.56 49.52,182.14 51.905,176.48 55.36,170 59.375,163.12 63.44,156.26 67.045,149.84 69.68,144.28 70.835,140 70,136.83 66.745,134.24 61.36,132.11 54.415,130.32 46.48,128.75 38.125,127.28 29.92,125.79 22.435,124.16 16.24,122.27 11.905,120 10,117.585 10.95,115.28 14.4,112.995 19.75,110.64 26.4,108.125 33.75,105.36 41.2,102.255 48.15,98.72 54,94.665 58.15,90 60,84.125 59.15,76.8 56,68.475 51.15,59.6 45.2,50.625 38.75,42 32.4,34.175 26.75,27.6 22.4,22.725 19.95,20 20))
Figure
Geometry figure for visual-st-catmullromsmoothing-03

제목

ST_ConcaveHull — Computes a possibly concave geometry that contains all input geometry vertices

요약

geometry ST_ConcaveHull(geometry param_geom, float param_pctconvex, boolean param_allow_holes = false);

설명

A concave hull is a (usually) concave geometry which contains the input, and whose vertices are a subset of the input vertices. In the general case the concave hull is a Polygon. The concave hull of two or more collinear points is a two-point LineString. The concave hull of one or more identical points is a Point. The polygon will not contain holes unless the optional param_allow_holes argument is specified as true.

One can think of a concave hull as "shrink-wrapping" a set of points. This is different to the convex hull, which is more like wrapping a rubber band around the points. A concave hull generally has a smaller area and represents a more natural boundary for the input points.

The param_pctconvex controls the concaveness of the computed hull. A value of 1 produces the convex hull. Values between 1 and 0 produce hulls of increasing concaveness. A value of 0 produces a hull with maximum concaveness (but still a single polygon). Choosing a suitable value depends on the nature of the input data, but often values between 0.3 and 0.1 produce reasonable results.

[참고]

Technically, the param_pctconvex determines a length as a fraction of the difference between the longest and shortest edges in the Delaunay Triangulation of the input points. Edges longer than this length are "eroded" from the triangulation. The triangles remaining form the concave hull.

For point and linear inputs, the hull will enclose all the points of the inputs. For polygonal inputs, the hull will enclose all the points of the input and also all the areas covered by the input. If you want a point-wise hull of a polygonal input, convert it to points first using ST_Points.

This is not an aggregate function. To compute the concave hull of a set of geometries use ST_Collect (e.g. ST_ConcaveHull(ST_Collect(geom ), 0.80).

2.0.0 버전부터 사용할 수 있습니다.

Enhanced: 3.3.0, GEOS native implementation enabled for GEOS 3.11+

예시

Concave hull of a MultiPoint.

Code
SELECT ST_ConcaveHull('MULTIPOINT ((10 72),(53 76),(56 66),(63 58),(71 51),(81 48),(91 46),(101 45),(111 46),(121 47),(131 50),(140 55),(145 64),(144 74),(135 80),(125 83),(115 85),(105 87),(95 89),(85 91),(75 93),(65 95),(55 98),(45 102),(37 107),(29 114),(22 122),(19 132),(18 142),(21 151),(27 160),(35 167),(44 172),(54 175),(64 178),(74 180),(84 181),(94 181),(104 181),(114 181),(124 181),(134 179),(144 177),(153 173),(162 168),(171 162),(177 154),(182 145),(184 135),(139 132),(136 142),(128 149),(119 153),(109 155),(99 155),(89 155),(79 153),(69 150),(61 144),(63 134),(72 128),(82 125),(92 123),(102 121),(112 119),(122 118),(132 116),(142 113),(151 110),(161 106),(170 102),(178 96),(185 88),(189 78),(190 68),(189 58),(185 49),(179 41),(171 34),(162 29),(153 25),(143 23),(133 21),(123 19),(113 19),(102 19),(92 19),(82 19),(72 21),(62 22),(52 25),(43 29),(33 34),(25 41),(19 49),(14 58),(21 73),(31 74),(42 74),(173 134),(161 134),(150 133),(97 104),(52 117),(157 156),(94 171),(112 106),(169 73),(58 165),(149 40),(70 33),(147 157),(48 153),(140 96),(47 129),(173 55),(144 86),(159 67),(150 146),(38 136),(111 170),(124 94),(26 59),(60 41),(71 162),(41 64),(88 110),(122 34),(151 97),(157 56),(39 146),(88 33),(159 45),(47 56),(138 40),(129 165),(33 48),(106 31),(169 147),(37 122),(71 109),(163 89),(37 156),(82 170),(180 72),(29 142),(46 41),(59 155),(124 106),(157 80),(175 82),(56 50),(62 116),(113 95),(144 167))',
         0.1 );
래스터 출력
st_astext
-----------
POLYGON ((18 142, 21 151, 27 160, 35 167, 44 172, 54 175, 64 178, 74 180, 84 181, 94 181, 104 181, 114 181, 124 181, 134 179, 144 177, 153 173, 162 168, 171 162, 177 154, 182 145, 184 135, 173 134, 161 134, 150 133, 139 132, 136 142, 128 149, 119 153, 109 155, 99 155, 89 155, 79 153, 69 150, 61 144, 63 134, 72 128, 82 125, 92 123, 102 121, 112 119, 122 118, 132 116, 142 113, 151 110, 161 106, 170 102, 178 96, 185 88, 189 78, 190 68, 189 58, 185 49, 179 41, 171 34, 162 29, 153 25, 143 23, 133 21, 123 19, 113 19, 102 19, 92 19, 82 19, 72 21, 62 22, 52 25, 43 29, 33 34, 25 41, 19 49, 14 58, 10 72, 21 73, 31 74, 42 74, 53 76, 56 66, 63 58, 71 51, 81 48, 91 46, 101 45, 111 46, 121 47, 131 50, 140 55, 145 64, 144 74, 135 80, 125 83, 115 85, 105 87, 95 89, 85 91, 75 93, 65 95, 55 98, 45 102, 37 107, 29 114, 22 122, 19 132, 18 142))
(1 row)
Figure
Geometry figure for visual-st-concavehull-01

Concave hull of a MultiPoint, allowing holes.

Code
SELECT ST_ConcaveHull('MULTIPOINT ((132 64),(114 64),(99 64),(81 64),(63 64),(57 49),(52 36),(46 20),(37 20),(26 20),(32 36),(39 55),(43 69),(50 84),(57 100),(63 118),(68 133),(74 149),(81 164),(88 180),(101 180),(112 180),(119 164),(126 149),(132 131),(139 113),(143 100),(150 84),(157 69),(163 51),(168 36),(174 20),(163 20),(150 20),(143 36),(139 49),(132 64),(99 151),(92 138),(88 124),(81 109),(74 93),(70 82),(83 82),(99 82),(112 82),(126 82),(121 96),(114 109),(110 122),(103 138),(99 151),(34 27),(43 31),(48 44),(46 58),(52 73),(63 73),(61 84),(72 71),(90 69),(101 76),(123 71),(141 62),(166 27),(150 33),(159 36),(146 44),(154 53),(152 62),(146 73),(134 76),(143 82),(141 91),(130 98),(126 104),(132 113),(128 127),(117 122),(112 133),(119 144),(108 147),(119 153),(110 171),(103 164),(92 171),(86 160),(88 142),(79 140),(72 124),(83 131),(79 118),(68 113),(63 102),(68 93),(35 45))',
         0.15, true );
래스터 출력
st_astext
-----------
POLYGON ((43 69, 50 84, 57 100, 63 118, 68 133, 74 149, 81 164, 88 180, 101 180, 112 180, 119 164, 126 149, 132 131, 139 113, 143 100, 150 84, 157 69, 163 51, 168 36, 174 20, 163 20, 150 20, 143 36, 139 49, 132 64, 114 64, 99 64, 81 64, 63 64, 57 49, 52 36, 46 20, 37 20, 26 20, 32 36, 35 45, 39 55, 43 69), (88 124, 81 109, 74 93, 83 82, 99 82, 112 82, 121 96, 114 109, 110 122, 103 138, 92 138, 88 124))
(1 row)
Figure
Geometry figure for visual-st-concavehull-02

Comparing a concave hull of a Polygon to the concave hull of the constituent points. The hull respects the boundary of the polygon, whereas the points-based hull does not.

Code
WITH data(geom) AS (VALUES
   ('POLYGON ((10 90,39 85,61 79,50 90,80 80,95 55,25 60,90 45,70 16,63 38,60 10,50 30,43 27,30 10,20 20,10 90))'::geometry)
)
SELECT ST_ConcaveHull(geom, 0.1) AS polygon_hull,
       ST_ConcaveHull(ST_Points(geom), 0.1) AS points_hull
    FROM data;
래스터 출력
POLYGON((60 10,50 30,43 27,30 10,20 20,10 90,39 85,50 90,80 80,95 55,90 45,70 16,60 10)) | POLYGON((25 60,10 90,39 85,50 90,80 80,95 55,90 45,70 16,60 10,30 10,20 20,43 27,50 30,63 38,61 79,25 60))
Figure
Geometry figure for visual-st-concavehull-03

Using with ST_Collect to compute the concave hull of a geometry set.

This example estimates an infected area from point observations.

Code
SELECT disease_type,
    ST_ConcaveHull(ST_Collect(obs_pnt), 0.3 ) AS geom
  FROM disease_obs
  GROUP BY disease_type;

제목

ST_ConvexHull — Computes the convex hull of a geometry.

요약

geometry ST_ConvexHull(geometry geomA);

설명

Computes the convex hull of a geometry. The convex hull is the smallest convex geometry that encloses all geometries in the input.

One can think of the convex hull as the geometry obtained by wrapping an rubber band around a set of geometries. This is different from a concave hull which is analogous to "shrink-wrapping" the geometries. A convex hull is often used to determine an affected area based on a set of point observations.

In the general case the convex hull is a Polygon. The convex hull of two or more collinear points is a two-point LineString. The convex hull of one or more identical points is a Point.

This is not an aggregate function. To compute the convex hull of a set of geometries, use ST_Collect to aggregate them into a geometry collection (e.g. ST_ConvexHull(ST_Collect(geom)).

GEOS 모듈로 실행

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.3

This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 5.1.16

This function supports 3d and will not drop the z-index.

예시

Compute the convex hull of a MultiLineString and a MultiPoint.

Code
SELECT ST_ConvexHull(ST_Collect(ST_GeomFromText('MULTILINESTRING((100 190,10 8),(150 10,20 30))'),
            ST_GeomFromText('MULTIPOINT(50 5,150 30,50 10,10 10)')
            ));
래스터 출력
st_astext
-----------
POLYGON((50 5,10 8,10 10,100 190,150 30,150 10,50 5))
(1 row)
Figure
Geometry figure for visual-st-convexhull-01

Using with ST_Collect to compute the convex hulls of geometry sets.

This example returns an estimated infected area from point observations.

Code
SELECT d.disease_type,
    ST_ConvexHull(ST_Collect(d.geom)) As geom
    FROM disease_obs As d
    GROUP BY d.disease_type;

제목

ST_DelaunayTriangles — Returns the Delaunay triangulation of the vertices of a geometry.

요약

geometry ST_DelaunayTriangles(geometry g1, float tolerance = 0.0, int4 flags = 0);

설명

Computes the Delaunay triangulation of the vertices of the input geometry. The optional tolerance can be used to snap nearby input vertices together, which improves robustness in some situations. The result geometry is bounded by the convex hull of the input vertices. The result geometry representation is determined by the flags code:

  • 0 - a GEOMETRYCOLLECTION of triangular POLYGONs (default)

  • 1 - a MULTILINESTRING of the edges of the triangulation

  • 2 - A TIN of the triangulation

GEOS 모듈로 실행

2.1.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

Triangulation of the vertices of a polygon and a buffered point.

Code
WITH data AS (
  SELECT polygon, ST_Buffer(center, 20) AS point_buffer
  FROM (SELECT
    'POLYGON((175 150,20 40,50 60,125 100,175 150))'::geometry AS polygon,
    'POINT(110 170)'::geometry AS center
  ) AS input
)
SELECT ST_DelaunayTriangles(ST_Union(polygon, point_buffer)) AS triangles
FROM data;
래스터 출력
GEOMETRYCOLLECTION(POLYGON((96 184,93 181,96 156,96 184)), POLYGON((96 184,96 156,102 188,96 184)), POLYGON((96 184,102 188,99 187,96 184)), POLYGON((102 188,96 156,99 153,102 188)), POLYGON((102 188,99 153,102 152,102 188)), POLYGON((102 188,102 152,106 190,102 188)), POLYGON((106 190,102 152,106 150,106 190)), POLYGON((106 190,106 150,110 190,106 190)), POLYGON((110 190,106 150,110 150,110 190)), POLYGON((110 190,110 150,118 188,110 190)), POLYGON((110 190,118 188,114 190,110 190)), POLYGON((118 188,110 150,121 153,118 188)), POLYGON((118 188,121 153,121 187,118 188)), POLYGON((121 187,121 153,124 156,121 187)), POLYGON((121 187,124 156,124 184,121 187)), POLYGON((121 187,124 184,175 150,121 187)), POLYGON((175 150,124 184,127 181,175 150)), POLYGON((175 150,127 181,128 178,175 150)), POLYGON((175 150,128 178,130 174,175 150)), POLYGON((175 150,130 174,130 170,175 150)), POLYGON((175 150,130 170,130 166,175 150)), POLYGON((175 150,130 166,128 162,175 150)), POLYGON((175 150,128 162,127 159,175 150)), POLYGON((175 150,127 159,124 156,175 150)), POLYGON((175 150,124 156,125 100,175 150)), POLYGON((125 100,124 156,121 153,125 100)), POLYGON((125 100,121 153,118 152,125 100)), POLYGON((125 100,118 152,114 150,125 100)), POLYGON((125 100,114 150,110 150,125 100)), POLYGON((125 100,110 150,106 150,125 100)), POLYGON((125 100,106 150,102 152,125 100)), POLYGON((125 100,102 152,99 153,125 100)), POLYGON((125 100,99 153,50 60,125 100)), POLYGON((125 100,50 60,20 40,125 100)), POLYGON((20 40,50 60,90 166,20 40)), POLYGON((20 40,90 166,90 170,20 40)), POLYGON((20 40,90 170,90 174,20 40)), POLYGON((20 40,90 174,92 178,20 40)), POLYGON((92 178,90 174,90 170,92 178)), POLYGON((92 178,90 170,92 162,92 178)), POLYGON((92 178,92 162,93 159,92 178)), POLYGON((92 178,93 159,93 181,92 178)), POLYGON((93 181,93 159,96 156,93 181)), POLYGON((96 156,93 159,50 60,96 156)), POLYGON((96 156,50 60,99 153,96 156)), POLYGON((50 60,93 159,92 162,50 60)), POLYGON((50 60,92 162,90 166,50 60)), POLYGON((90 166,92 162,90 170,90 166)), POLYGON((110 150,114 150,121 153,110 150)), POLYGON((121 153,114 150,118 152,121 153)), POLYGON((124 156,127 159,130 166,124 156)), POLYGON((124 156,130 166,128 178,124 156)), POLYGON((124 156,128 178,124 184,124 156)), POLYGON((124 184,128 178,127 181,124 184)), POLYGON((128 178,130 166,130 170,128 178)), POLYGON((128 178,130 170,130 174,128 178)), POLYGON((130 166,127 159,128 162,130 166)))
Figure
Geometry figure for visual-st-delaunaytriangles-01

Triangulation edges returned as a MULTILINESTRING.

Code
WITH data AS (
  SELECT polygon, ST_Buffer(center, 20) AS point_buffer
  FROM (SELECT
    'POLYGON((175 150,20 40,50 60,125 100,175 150))'::geometry AS polygon,
    'POINT(110 170)'::geometry AS center
  ) AS input
)
SELECT ST_DelaunayTriangles(ST_Union(polygon, point_buffer), 0.001, 1) AS triangulation_edges
FROM data;
래스터 출력
MULTILINESTRING((121 187,175 150),(118 188,121 187),(114 190,118 188),(110 190,114 190),(106 190,110 190),(102 188,106 190),(99 187,102 188),(96 184,99 187),(93 181,96 184),(92 178,93 181),(20 40,92 178),(20 40,125 100),(125 100,175 150),(124 156,125 100),(124 156,175 150),(124 156,127 159),(127 159,175 150),(127 159,128 162),(128 162,175 150),(128 162,130 166),(130 166,175 150),(130 166,130 170),(130 170,175 150),(130 174,130 170),(130 174,175 150),(128 178,130 174),(128 178,175 150),(127 181,128 178),(127 181,175 150),(124 184,127 181),(124 184,175 150),(121 187,124 184),(124 156,124 184),(121 187,124 156),(121 153,124 156),(121 153,121 187),(118 188,121 153),(110 150,121 153),(110 150,118 188),(110 150,110 190),(110 190,118 188),(106 150,110 150),(106 150,110 190),(106 190,106 150),(102 152,106 150),(102 152,106 190),(102 152,102 188),(99 153,102 152),(99 153,102 188),(96 156,99 153),(96 156,102 188),(96 156,96 184),(96 184,102 188),(93 181,96 156),(93 159,96 156),(93 159,93 181),(92 178,93 159),(92 162,93 159),(92 162,92 178),(90 170,92 162),(90 170,92 178),(90 170,90 174),(90 174,92 178),(20 40,90 174),(20 40,90 170),(90 170,90 166),(20 40,90 166),(50 60,90 166),(20 40,50 60),(50 60,125 100),(50 60,99 153),(99 153,125 100),(50 60,96 156),(50 60,93 159),(50 60,92 162),(90 166,92 162),(102 152,125 100),(106 150,125 100),(110 150,125 100),(110 150,114 150),(114 150,125 100),(114 150,118 152),(118 152,125 100),(118 152,121 153),(121 153,125 100),(114 150,121 153),(124 184,128 178),(124 156,128 178),(128 178,130 166),(124 156,130 166),(127 159,130 166),(128 178,130 170))
Figure
Geometry figure for visual-st-delaunaytriangles-02

Triangulation of 42 points forming an L shape.

Code
WITH data AS (
  SELECT 'MULTIPOINT(14 14,34 14,54 14,74 14,94 14,114 14,134 14,
    150 14,154 14,154 6,134 6,114 6,94 6,74 6,54 6,34 6,
    14 6,10 6,8 6,7 7,6 8,6 10,6 30,6 50,6 70,6 90,6 110,6 130,
    6 150,6 170,6 190,6 194,14 194,14 174,14 154,14 134,14 114,
    14 94,14 74,14 54,14 34,14 14)'::geometry AS l_shape_points
)
SELECT ST_DelaunayTriangles(l_shape_points) AS triangles
FROM data;
래스터 출력
GEOMETRYCOLLECTION(POLYGON((6 194,6 190,14 194,6 194)), POLYGON((14 194,6 190,14 174,14 194)), POLYGON((14 194,14 174,154 14,14 194)), POLYGON((154 14,14 174,14 154,154 14)), POLYGON((154 14,14 154,150 14,154 14)), POLYGON((154 14,150 14,154 6,154 14)), POLYGON((154 6,150 14,134 6,154 6)), POLYGON((134 6,150 14,134 14,134 6)), POLYGON((134 6,134 14,114 14,134 6)), POLYGON((134 6,114 14,114 6,134 6)), POLYGON((114 6,114 14,94 14,114 6)), POLYGON((114 6,94 14,94 6,114 6)), POLYGON((94 6,94 14,74 14,94 6)), POLYGON((94 6,74 14,74 6,94 6)), POLYGON((74 6,74 14,54 14,74 6)), POLYGON((74 6,54 14,54 6,74 6)), POLYGON((54 6,54 14,34 14,54 6)), POLYGON((54 6,34 14,34 6,54 6)), POLYGON((34 6,34 14,14 14,34 6)), POLYGON((34 6,14 14,14 6,34 6)), POLYGON((14 6,14 14,10 6,14 6)), POLYGON((10 6,14 14,6 10,10 6)), POLYGON((10 6,6 10,7 7,10 6)), POLYGON((10 6,7 7,8 6,10 6)), POLYGON((7 7,6 10,6 8,7 7)), POLYGON((6 10,14 14,6 30,6 10)), POLYGON((6 30,14 14,14 34,6 30)), POLYGON((6 30,14 34,6 50,6 30)), POLYGON((6 50,14 34,14 54,6 50)), POLYGON((6 50,14 54,6 70,6 50)), POLYGON((6 70,14 54,14 74,6 70)), POLYGON((6 70,14 74,6 90,6 70)), POLYGON((6 90,14 74,14 94,6 90)), POLYGON((6 90,14 94,6 110,6 90)), POLYGON((6 110,14 94,14 114,6 110)), POLYGON((6 110,14 114,6 130,6 110)), POLYGON((6 130,14 114,14 134,6 130)), POLYGON((6 130,14 134,6 150,6 130)), POLYGON((6 150,14 134,14 154,6 150)), POLYGON((6 150,14 154,6 170,6 150)), POLYGON((6 170,14 154,14 174,6 170)), POLYGON((6 170,14 174,6 190,6 170)), POLYGON((14 154,14 134,150 14,14 154)), POLYGON((150 14,14 134,134 14,150 14)), POLYGON((134 14,14 134,114 14,134 14)), POLYGON((114 14,14 134,14 114,114 14)), POLYGON((114 14,14 114,94 14,114 14)), POLYGON((94 14,14 114,14 94,94 14)), POLYGON((94 14,14 94,74 14,94 14)), POLYGON((74 14,14 94,14 74,74 14)), POLYGON((74 14,14 74,54 14,74 14)), POLYGON((54 14,14 74,14 54,54 14)), POLYGON((54 14,14 54,34 14,54 14)), POLYGON((34 14,14 54,14 34,34 14)), POLYGON((34 14,14 34,14 14,34 14)))
Figure
Geometry figure for visual-st-delaunaytriangles-03

Example using vertices with Z values.

Code
SELECT ST_DelaunayTriangles(
  'MULTIPOINT Z(14 14 10,150 14 100,34 6 25,20 10 150)'::geometry);
래스터 출력
GEOMETRYCOLLECTION Z (POLYGON Z ((14 14 10,20 10 150,34 6 25,14 14 10)),POLYGON Z ((14 14 10,34 6 25,150 14 100,14 14 10)))

제목

ST_FilterByM — Removes vertices based on their M value

요약

geometry ST_FilterByM(geometry geom, double precision min, double precision max = null, boolean returnM = false);

설명

Filters out vertex points based on their M-value. Returns a geometry with only vertex points that have a M-value larger or equal to the min value and smaller or equal to the max value. If max-value argument is left out only min value is considered. If fourth argument is left out the m-value will not be in the resulting geometry. If resulting geometry have too few vertex points left for its geometry type an empty geometry will be returned. In a geometry collection geometries without enough points will just be left out silently.

This function is mainly intended to be used in conjunction with ST_SetEffectiveArea. ST_EffectiveArea sets the effective area of a vertex in its m-value. With ST_FilterByM it then is possible to get a simplified version of the geometry without any calculations, just by filtering

[참고]

There is a difference in what ST_SimplifyVW returns when not enough points meet the criteria compared to ST_FilterByM. ST_SimplifyVW returns the geometry with enough points while ST_FilterByM returns an empty geometry

[참고]

Note that the returned geometry might be invalid

[참고]

This function returns all dimensions, including the Z and M values

Availability: 2.5.0

예시

A linestring is filtered

Code
SELECT ST_FilterByM(geom, 30) simplified
FROM (SELECT  ST_SetEffectiveArea('LINESTRING(5 2,3 8,6 20,7 25,10 10)'::geometry) geom) As foo;
래스터 출력
LINESTRING(5 2,7 25,10 10)
Figure
Geometry figure for visual-st-filterbym-01

제목

ST_GeneratePoints — Generates a multipoint of random points contained in a Polygon or MultiPolygon.

요약

geometry ST_GeneratePoints(geometry g, integer npoints, integer seed = 0);

설명

ST_GeneratePoints generates a multipoint consisting of a given number of pseudo-random points which lie within the input area. The optional seed is used to regenerate a deterministic sequence of points, and must be greater than zero.

2.3.0 버전부터 사용할 수 있습니다.

Enhanced: 3.0.0, added seed parameter

예시

Generate 12 points inside a buffered LineString using the deterministic seed 1996.

Code
WITH source AS (
  SELECT ST_Buffer(ST_GeomFromText('LINESTRING(50 50,150 150,150 50)'),
           10, 'endcap=round join=round') AS geom
)
SELECT geom AS area,
       ST_GeneratePoints(geom, 12, 1996) AS points
FROM source;
래스터 출력
POLYGON((142.929 157.071,144.444 158.315,146.173 159.239,148.049 159.808,150 160,151.951 159.808,153.827 159.239,155.556 158.315,157.071 157.071,158.315 155.556,159.239 153.827,159.808 151.951,160 150,160 50,159.808 48.049,159.239 46.173,158.315 44.444,157.071 42.929,155.556 41.685,153.827 40.761,151.951 40.192,150 40,148.049 40.192,146.173 40.761,144.444 41.685,142.929 42.929,141.685 44.444,140.761 46.173,140.192 48.049,140 50,140 125.858,57.071 42.929,55.556 41.685,53.827 40.761,51.951 40.192,50 40,48.049 40.192,46.173 40.761,44.444 41.685,42.929 42.929,41.685 44.444,40.761 46.173,40.192 48.049,40 50,40.192 51.951,40.761 53.827,41.685 55.556,42.929 57.071,142.929 157.071)) | MULTIPOINT((97.546 111.15),(155.206 69.56),(101.94 114.818),(90.308 91.125),(151.257 106.401),(143.12 120.461),(152.952 146.697),(119.774 123.985),(148.672 40.92),(54.376 45.337),(150.667 88.153),(129.634 120.578))
Figure
Geometry figure for visual-st-generatepoints-01

Given a table of polygons s, return 12 individual points per polygon. Results will be different each time you run.

Code
SELECT s.id, dp.path[1] AS pt_id, dp.geom
FROM s, ST_DumpPoints(ST_GeneratePoints(s.geom, 12)) AS dp;

Generate dot-density points from a polygon table, using the absolute value of an attribute as the number of points and keeping the sign of the attribute for styling.

Code
SELECT z.id,
       CASE WHEN z.count_delta < 0 THEN -1 ELSE 1 END AS sign,
       dp.path[1] AS pt_id,
       dp.geom
FROM zones AS z
CROSS JOIN LATERAL ST_DumpPoints(
    ST_GeneratePoints(z.geom, abs(z.count_delta)::integer, z.id + 1)
) AS dp
WHERE z.count_delta <> 0;

제목

ST_GeometricMedian — 멀티 포인트의 기하학적 중심값(median)을 반환합니다.

요약

geometry ST_GeometricMedian ( geometry geom, float8 tolerance = NULL, int max_iter = 10000, boolean fail_if_not_converged = false);

설명

Computes the approximate geometric median of a MultiPoint geometry using the Weiszfeld algorithm. The geometric median is the point minimizing the sum of distances to the input points. It provides a centrality measure that is less sensitive to outlier points than the centroid (center of mass).

The algorithm iterates until the distance change between successive iterations is less than the supplied tolerance parameter. If this condition has not been met after max_iterations iterations, the function produces an error and exits, unless fail_if_not_converged is set to false (the default).

If a tolerance argument is not provided, the tolerance value is calculated based on the extent of the input geometry.

If present, the input point M values are interpreted as their relative weights.

2.3.0 버전부터 사용할 수 있습니다.

Enhanced: 2.5.0 Added support for M as weight of points.

This function supports 3d and will not drop the z-index.

This function supports M coordinates.

예시

Compare the geometric median and centroid of a MultiPoint.

Code
WITH test AS (
SELECT 'MULTIPOINT((10 10),(10 40),(40 10),(190 190))'::geometry geom)
SELECT
  ST_Centroid(geom) centroid,
  ST_GeometricMedian(geom) median
FROM test;
래스터 출력
centroid      |                 median
--------------------+----------------------------------------
   POINT(62.5 62.5) | POINT(25.01778421249728 25.01778421249728)
(1 row)
Figure
Geometry figure for st-geometricmedian-example

제목

ST_LineMerge — Return the lines formed by sewing together a MultiLineString.

요약

geometry ST_LineMerge(geometry amultilinestring);

geometry ST_LineMerge(geometry amultilinestring, boolean directed);

설명

Returns a LineString or MultiLineString formed by joining together the line elements of a MultiLineString. Lines are joined at their endpoints at 2-way intersections. Lines are not joined across intersections of 3-way or greater degree.

If directed is TRUE, then ST_LineMerge will not change point order within LineStrings, so lines with opposite directions will not be merged

[참고]

Only use with MultiLineString/LineStrings. Other geometry types return an empty GeometryCollection

GEOS 모듈로 실행

Enhanced: 3.3.0 accept a directed parameter.

Requires GEOS >= 3.11.0 to use the directed parameter.

1.1.0 버전부터 사용할 수 있습니다.

[주의]

This function strips the M dimension.

예시

Cardinality 2

Nodes with cardinality 2 are merged away.

Code
SELECT ST_LineMerge('MULTILINESTRING((10 160,60 120),(120 140,60 120),(120 140,180 120))'
);
래스터 출력
LINESTRING(10 160,60 120,120 140,180 120)
Figure
Geometry figure for visual-st-linemerge-01

Cardinality 3 or More

Lines are not merged across intersections with degree > 2.

Code
SELECT ST_LineMerge('MULTILINESTRING((10 160,60 120),(120 140,60 120),(120 140,180 120),(100 180,120 140))'
);
래스터 출력
MULTILINESTRING((10 160,60 120,120 140),(100 180,120 140),(120 140,180 120))
Figure
Geometry figure for visual-st-linemerge-02

Non-Touching Lines

If merging is not possible due to non-touching lines, the original MultiLineString is returned.

Code
SELECT ST_LineMerge('MULTILINESTRING((-29 -27,-30 -29.7,-36 -31,-45 -33),(-45.2 -33.2,-46 -32))'
);
래스터 출력
MULTILINESTRING((-45.2 -33.2,-46 -32),(-29 -27,-30 -29.7,-36 -31,-45 -33))
Figure
Geometry figure for visual-st-linemerge-03

Directed Parameter

Lines with opposite directions are not merged if directed is TRUE.

Code
SELECT ST_LineMerge('MULTILINESTRING((60 30,10 70),(120 50,60 30),(120 50,180 30))',
TRUE);
래스터 출력
MULTILINESTRING((120 50,60 30,10 70),(120 50,180 30))
Figure
Geometry figure for visual-st-linemerge-04

Z-dimension Handling

Code
SELECT ST_LineMerge('MULTILINESTRING((-29 -27 11,-30 -29.7 10,-36 -31 5,-45 -33 6),(-29 -27 12,-30 -29.7 5),(-45 -33 1,-46 -32 11))'
        );
래스터 출력
LINESTRING Z (-30 -29.7 5,-29 -27 11,-30 -29.7 10,-36 -31 5,-45 -33 1,-46 -32 11)
Figure
Geometry figure for visual-st-linemerge-05

제목

ST_MaximumInscribedCircle — 도형의 기하학적 중심을 반환합니다.

요약

(geometry, geometry, double precision) ST_MaximumInscribedCircle(geometry geom);

설명

Finds the largest circle that is contained within a (multi)polygon, or which does not overlap any lines and points. Returns a record with fields:

  • center - center point of the circle

  • nearest - a point on the geometry nearest to the center

  • radius - radius of the circle

For polygonal inputs, the circle is inscribed within the boundary rings, using the internal rings as boundaries. For linear and point inputs, the circle is inscribed within the convex hull of the input, using the input lines and points as further boundaries.

Availability: 3.1.0.

Requires GEOS >= 3.9.0.

예시

Maximum inscribed circle of a polygon. Center, nearest point, radius, circle, and radius line are returned.

Code
WITH mic AS (
  SELECT * FROM ST_MaximumInscribedCircle(
    'POLYGON ((40 180,110 160,180 180,180 120,140 90,160 40,80 10,70 40,20 50,40 180),
              (60 140,50 90,90 140,60 140))')
)
SELECT round(radius::numeric, 3) AS radius,
       ST_SnapToGrid(center, 1) AS center,
       ST_SnapToGrid(nearest, 1) AS nearest,
       ST_SnapToGrid(ST_Buffer(center, radius), 1) AS circle,
       ST_SnapToGrid(ST_MakeLine(center, nearest), 1) AS radius_line
FROM mic;
래스터 출력
-[ RECORD 1 ]-----
radius      | 45.189
center      | POINT(97 76)
nearest     | POINT(62 105)
circle      | POLYGON((142 76,141 68,139 59,135 51,129 44,122 39,114 35,106 32,97 31,88 32,80 35,72 39,65 44,59 51,55 59,53 68,52 76,53 85,55 94,59 101,65 108,72 114,80 118,88 121,97 122,106 121,114 118,122 114,129 108,135 101,139 94,141 85,142 76))
radius_line | LINESTRING(97 76,62 105)
Figure
Geometry figure for visual-st-maximuminscribedcircle-01

Maximum inscribed circle of a MultiLineString.

Code
WITH mic AS (
  SELECT * FROM ST_MaximumInscribedCircle(
    'MULTILINESTRING((100 40,10 150),(10 160,100 150),(190 150,80 40))')
)
SELECT round(radius::numeric, 3) AS radius,
       ST_SnapToGrid(center, 1) AS center,
       ST_SnapToGrid(nearest, 1) AS nearest,
       ST_SnapToGrid(ST_Buffer(center, radius), 1) AS circle,
       ST_SnapToGrid(ST_MakeLine(center, nearest), 1) AS radius_line
FROM mic;
래스터 출력
-[ RECORD 1 ]-----
radius      | 39.924
center      | POINT(94 110)
nearest     | POINT(63 85)
circle      | POLYGON((134 110,133 103,131 95,127 88,122 82,116 77,109 74,102 71,94 71,86 71,79 74,72 77,66 82,61 88,57 95,55 103,54 110,55 118,57 126,61 133,66 139,72 144,79 147,86 150,94 150,102 150,109 147,116 144,122 139,127 133,131 126,133 118,134 110))
radius_line | LINESTRING(94 110,63 85)
Figure
Geometry figure for visual-st-maximuminscribedcircle-02

제목

ST_LargestEmptyCircle — Computes the largest circle not overlapping a geometry.

요약

(geometry, geometry, double precision) ST_LargestEmptyCircle(geometry geom, double precision tolerance=0.0, geometry boundary=POINT EMPTY);

설명

Finds the largest circle which does not overlap a set of point and line obstacles. (Polygonal geometries may be included as obstacles, but only their boundary lines are used.) The center of the circle is constrained to lie inside a polygonal boundary, which by default is the convex hull of the input geometry. The circle center is the point in the interior of the boundary which has the farthest distance from the obstacles. The circle itself is provided by the center point and a nearest point lying on an obstacle determining the circle radius.

The circle center is determined to a given accuracy specified by a distance tolerance, using an iterative algorithm. If the accuracy distance is not specified a reasonable default is used.

Returns a record with fields:

  • center - center point of the circle

  • nearest - a point on the geometry nearest to the center

  • radius - radius of the circle

To find the largest empty circle in the interior of a polygon, see ST_MaximumInscribedCircle.

Availability: 3.4.0.

Requires GEOS >= 3.9.0.

예시

Largest empty circle within a set of lines.

Code
WITH obstacles(geom) AS (VALUES ('MULTILINESTRING (
        (10 100,60 180,130 150,190 160),
        (20 50,70 70,90 20,110 40),
        (160 30,100 100,180 100))'::geometry)),
circle AS (
  SELECT result.*
  FROM obstacles
  CROSS JOIN LATERAL ST_LargestEmptyCircle(obstacles.geom) AS result
)
SELECT round(radius::numeric, 6) AS radius,
       ST_SnapToGrid(center, 1) AS center,
       ST_SnapToGrid(nearest, 1) AS nearest,
       ST_SnapToGrid(ST_MakeLine(center, nearest), 1) AS radius_line,
       ST_SnapToGrid(ST_Buffer(center, radius), 1) AS circle
FROM circle;
래스터 출력
-[ RECORD 1 ]-----
radius      | 39.260545
center      | POINT(62 108)
nearest     | POINT(70 70)
radius_line | LINESTRING(62 108,70 70)
circle      | POLYGON((101 108,100 101,98 93,94 87,89 81,83 76,77 72,69 70,62 69,54 70,47 72,40 76,34 81,29 87,25 93,23 101,22 108,23 116,25 123,29 130,34 136,40 141,47 145,54 147,62 148,69 147,77 145,83 141,89 136,94 130,98 123,100 116,101 108))
Figure
Geometry figure for visual-st-largestemptycircle-01

Largest empty circle within a set of points, constrained to lie in a polygon. The constraint polygon boundary is included both as an obstacle and as the constraint for the circle center.

Code
WITH inputs(points, boundary) AS (VALUES (
  'MULTIPOINT ((70 50),(60 130),(130 150),(80 90))'::geometry,
  'POLYGON ((90 190,10 100,60 10,190 40,120 100,190 180,90 190))'::geometry
)),
circle AS (
  SELECT result.*
  FROM inputs
  CROSS JOIN LATERAL ST_LargestEmptyCircle(
    ST_Collect(points, boundary), 0, boundary
  ) AS result
)
SELECT round(radius::numeric, 6) AS radius,
       ST_SnapToGrid(center, 1) AS center,
       ST_SnapToGrid(nearest, 1) AS nearest,
       ST_SnapToGrid(ST_MakeLine(center, nearest), 1) AS radius_line,
       ST_SnapToGrid(ST_Buffer(center, radius), 1) AS circle
FROM circle;
래스터 출력
-[ RECORD 1 ]-----
radius      | 19.903876
center      | POINT(97 100)
nearest     | POINT(80 90)
radius_line | LINESTRING(97 100,80 90)
circle      | POLYGON((117 100,117 96,116 92,114 89,111 86,108 83,105 82,101 80,97 80,93 80,90 82,86 83,83 86,81 89,79 92,78 96,77 100,78 104,79 108,81 111,83 114,86 116,90 118,93 119,97 120,101 119,105 118,108 116,111 114,114 111,116 108,117 104,117 100))
Figure
Geometry figure for visual-st-largestemptycircle-02

제목

ST_MinimumBoundingCircle — Returns the smallest circle polygon that contains a geometry.

요약

geometry ST_MinimumBoundingCircle(geometry geomA, integer num_segs_per_qt_circ=48);

설명

Returns the smallest circle polygon that contains a geometry.

[참고]

사분원 당 구간 48개라는 기본값으로 원에 가까운 폴리곤을 생성합니다. 이 폴리곤이 최소 경계 원(minimum bounding circle)의 근사치이기 때문에, 입력 도형 안에 있는 포인트 몇 개는 폴리곤 내부에 담기지 않을 수도 있습니다. 구간의 개수를 늘리면 성능을 거의 저하시키지 않고도 근사치를 향상시킬 수 있습니다. 폴리곤 근사치가 적당하지 않은 경우, ST_MinimumBoundingRadius 함수를 사용할 수도 있습니다.

Use with ST_Collect to get the minimum bounding circle of a set of geometries.

To compute two points lying on the minimum circle (the "maximum diameter") use ST_LongestLine.

폴리곤의 면적을 최소 경계 원의 면적으로 나눈 비율을 종종 루크(Roeck) 테스트라고 부릅니다.

GEOS 모듈로 실행

1.4.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT d.disease_type,
ST_MinimumBoundingCircle(ST_Collect(d.geom)) As geom
FROM disease_obs As d
GROUP BY d.disease_type;

Minimum bounding circle of a point and linestring, using 8 segments to approximate a quarter circle.

Code
SELECT ST_MinimumBoundingCircle(ST_Collect('LINESTRING(55 75,125 150)',
ST_Point(20, 80)), 8
) As wktmbc;
래스터 출력
POLYGON((72.5 178.4024474346694,84.86920388664029 177.18418718546332,96.76306620464646 173.57622349601382,107.72451249529237 167.71720838753708,117.33230052487836 159.83230052487838,125.21720838753708 150.22451249529237,131.07622349601382 139.26306620464646,134.68418718546332 127.3692038866403,135.9024474346694 115,134.68418718546332 102.63079611335971,131.07622349601382 90.73693379535354,125.21720838753708 79.77548750470766,117.33230052487838 70.16769947512164,107.72451249529237 62.282791612462916,96.76306620464648 56.42377650398619,84.86920388664032 52.815812814536685,72.50000000000001 51.59755256533059,60.13079611335969 52.815812814536685,48.236933795353536 56.42377650398618,37.27548750470765 62.28279161246291,27.667699475121637 70.16769947512162,19.782791612462923 79.77548750470763,13.923776503986204 90.7369337953535,10.315812814536692 102.63079611335968,9.097552565330588 114.99999999999999,10.315812814536685 127.3692038866403,13.923776503986197 139.2630662046465,19.78279161246291 150.22451249529234,27.667699475121623 159.83230052487835,37.275487504707634 167.71720838753708,48.236933795353494 173.5762234960138,60.13079611335967 177.18418718546332,72.5 178.4024474346694))
Figure
Geometry figure for visual-st-minimumboundingcircle-01

제목

ST_MinimumBoundingRadius — Returns the center point and radius of the smallest circle that contains a geometry.

요약

(geometry, double precision) ST_MinimumBoundingRadius(geometry geom);

설명

Computes the center point and radius of the smallest circle that contains a geometry. Returns a record with fields:

  • center - center point of the circle

  • radius - radius of the circle

Use with ST_Collect to get the minimum bounding circle of a set of geometries.

To compute two points lying on the minimum circle (the "maximum diameter") use ST_LongestLine.

2.3.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT center, radius FROM ST_MinimumBoundingRadius('POLYGON((26426 65078,26531 65242,26075 65136,26096 65427,26426 65078))');
래스터 출력
st_astext                 |      radius
------------------------------------------+------------------
 POINT(26284.84180271327 65267.114509082545) | 247.43604559140655
Figure
Geometry figure for visual-st-minimumboundingradius-01

제목

ST_OrientedEnvelope — Returns a minimum-area rectangle containing a geometry.

요약

geometry ST_OrientedEnvelope( geometry geom );

설명

Returns the minimum-area rotated rectangle enclosing a geometry. Note that more than one such rectangle may exist. May return a Point or LineString in the case of degenerate inputs.

Availability: 2.5.0.

Requires GEOS >= 3.6.0.

예시

Code
SELECT ST_OrientedEnvelope('MULTIPOINT ((0 0),(-1 -1),(3 2))');
래스터 출력
POLYGON((3 2,-1 -1,-1.12 -0.84,2.88 2.16,3 2))
Figure
Geometry figure for visual-st-orientedenvelope-01

Oriented envelope of a Point and LineString.

Code
SELECT ST_OrientedEnvelope(ST_Collect('LINESTRING(55 75,125 150)',
                ST_Point(20, 80))
                ) As wktenv;
래스터 출력
POLYGON((20 80,125 150,138.0769230769241 130.38461538461573,33.07692307692291 60.384615384615195,20 80))
Figure
Geometry figure for visual-st-orientedenvelope-02

제목

ST_OffsetCurve — Returns an offset line at a given distance and side from an input line.

요약

geometry ST_OffsetCurve(geometry line, float signed_distance, text style_parameters='');

설명

Return an offset line at a given distance and side from an input line. All points of the returned geometries are not further than the given distance from the input geometry. Useful for computing parallel lines about a center line.

For positive distance the offset is on the left side of the input line and retains the same direction. For a negative distance it is on the right side and in the opposite direction.

거리의 단위는 공간 참조 시스템의 단위로 측정됩니다.

Note that output may be a MULTILINESTRING or EMPTY for some jigsaw-shaped input geometries.

다음과 같이 연산을 조정하기 위해 선택적인 세 번째 파라미터로 공백으로 구분된 키=값 쌍의 목록을 설정할 수 있습니다:

  • 'quad_segs=#' : 사분원(quarter circle)의 근사치를 계산하는 데 쓰이는 선분의 개수(기본값은 8)

  • 'join=round|mitre|bevel' : 접합 스타일(기본값은 "원형(round)"). '마이터(mitre)'의 동의어로 '마이터(miter)'도 쓸 수 있습니다.

  • 'mitre_limit=#.#' : 마이터 비율 제한(마이터 접합 스타일만 영향을 받습니다). 'mitre_limit'의 동의어로 'miter_limit'도 쓸 수 있습니다.

GEOS 모듈로 실행

Behavior changed in GEOS 3.11 so offset curves now have the same direction as the input line, for both positive and negative offsets.

2.0 버전부터 사용할 수 있습니다.

Enhanced: 2.5 - added support for GEOMETRYCOLLECTION and MULTILINESTRING

[참고]

This function ignores the Z dimension. It always gives a 2D result even when used on a 3D geometry.

예시

Compute an open buffer around roads.

Code
SELECT ST_Union(
 ST_OffsetCurve(f.geom, f.width/2, 'quad_segs=4 join=round'),
 ST_OffsetCurve(f.geom, -f.width/2, 'quad_segs=4 join=round')
) as track
FROM someroadstable;

                

Offset 15 units with quad_segs=4 join=round.

Code
SELECT ST_OffsetCurve(
    ST_GeomFromText('LINESTRING(164 16,144 16,124 16,104 16,84 16,64 16,
    44 16,24 16,20 16,18 16,17 17,
    16 18,16 20,16 40,16 60,16 80,16 100,
    16 120,16 140,16 160,16 180,16 195)'),
    15, 'quad_segs=4 join=round');
래스터 출력
LINESTRING(164 1,18 1,15.073645169758077 1.288220793951544,
    12.259748514523654 2.141807012330698,9.66644650470597 3.527955815461818,
    7.393398282201788 5.393398282201788,5.393398282201788 7.393398282201788,
    3.527955815461818 9.66644650470597,2.141807012330696 12.259748514523654,
    1.288220793951544 15.073645169758075,1 18,1 195)
Figure
Geometry figure for visual-st-offsetcurve-01

Offset -15 units with quad_segs=4 join=round.

Code
SELECT ST_OffsetCurve(
    geom,
    -15,
    'quad_segs=4 join=round') As notsocurvy
    FROM ST_GeomFromText('LINESTRING(164 16,144 16,124 16,104 16,84 16,64 16,
    44 16,24 16,20 16,18 16,17 17,
    16 18,16 20,16 40,16 60,16 80,16 100,
    16 120,16 140,16 160,16 180,16 195)') As geom;
래스터 출력
LINESTRING(164 31,31 31,31 195)
Figure
Geometry figure for visual-st-offsetcurve-02

Apply two negative offsets to obtain a smoother curve; the distances combine to -45 units.

Code
SELECT ST_OffsetCurve(
    ST_OffsetCurve(
        geom,
        -30,
        'quad_segs=4 join=round'),
    -15,
    'quad_segs=4 join=round') As morecurvy
    FROM ST_GeomFromText('LINESTRING(164 16,144 16,124 16,104 16,84 16,64 16,
    44 16,24 16,20 16,18 16,17 17,
    16 18,16 20,16 40,16 60,16 80,16 100,
    16 120,16 140,16 160,16 180,16 195)') As geom;
래스터 출력
LINESTRING(164 61,61 61,61 195)
Figure
Geometry figure for visual-st-offsetcurve-03

Collect the positive offset and the double-offset to produce parallel curves.

Code
SELECT ST_Collect(
    ST_OffsetCurve(geom, 15, 'quad_segs=4 join=round'),
    ST_OffsetCurve(
        ST_OffsetCurve(
            geom,
            -30,
            'quad_segs=4 join=round'),
        -15,
        'quad_segs=4 join=round')
) As parallel_curves
    FROM ST_GeomFromText('LINESTRING(164 16,144 16,124 16,104 16,84 16,64 16,
    44 16,24 16,20 16,18 16,17 17,
    16 18,16 20,16 40,16 60,16 80,16 100,
    16 120,16 140,16 160,16 180,16 195)') As geom;
래스터 출력
MULTILINESTRING((164 1,18 1,15.073645169758077 1.288220793951544,
12.259748514523654 2.141807012330698,9.66644650470597 3.527955815461818,
7.393398282201788 5.393398282201788,5.393398282201788 7.393398282201788,
3.527955815461818 9.66644650470597,2.141807012330696 12.259748514523654,
1.288220793951544 15.073645169758075,1 18,1 195),(164 61,61 61,61 195))
Figure
Geometry figure for visual-st-offsetcurve-04

Offset 15 units with a bevel join.

Code
SELECT ST_OffsetCurve(
    ST_GeomFromText('LINESTRING(164 16,144 16,124 16,104 16,84 16,64 16,
    44 16,24 16,20 16,18 16,17 17,
    16 18,16 20,16 40,16 60,16 80,16 100,
    16 120,16 140,16 160,16 180,16 195)'),
        15, 'quad_segs=4 join=bevel');
래스터 출력
LINESTRING(164 1,18 1,7.393398282201788 5.393398282201788,
    5.393398282201788 7.393398282201788,1 18,1 195)
Figure
Geometry figure for visual-st-offsetcurve-05

Collect offsets on both sides using a mitre join and a mitre limit of 2.2.

Code
SELECT ST_Collect(
    ST_OffsetCurve(geom, 15, 'quad_segs=4 join=mitre mitre_limit=2.2'),
    ST_OffsetCurve(geom, -15, 'quad_segs=4 join=mitre mitre_limit=2.2')
    )
    FROM ST_GeomFromText('LINESTRING(164 16,144 16,124 16,104 16,84 16,64 16,
    44 16,24 16,20 16,18 16,17 17,
    16 18,16 20,16 40,16 60,16 80,16 100,
    16 120,16 140,16 160,16 180,16 195)') As geom;
래스터 출력
MULTILINESTRING((164 1,11.786796564403577 1,1 11.786796564403577,1 195),
    (164 31,31 31,31 195))
Figure
Geometry figure for visual-st-offsetcurve-06

참고

ST_Buffer


제목

ST_PointOnSurface — Computes a point guaranteed to lie in a polygon, or on a geometry.

요약

geometry ST_PointOnSurface(geometry g1);

설명

Returns a POINT which is guaranteed to lie in the interior of a surface (POLYGON, MULTIPOLYGON, and CURVEPOLYGON). In PostGIS this function also works on line and point geometries.

This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.14.2 // s3.2.18.2

This method implements the SQL/MM specification. SQL-MM 3: 8.1.5, 9.5.6. The specifications define ST_PointOnSurface for surface geometries only. PostGIS extends the function to support all common geometry types. Other databases (Oracle, DB2, ArcSDE) seem to support this function only for surfaces. SQL Server 2008 supports all common geometry types.

This function supports 3d and will not drop the z-index.

예시

Point on surface of a MultiPoint.

Code
SELECT ST_PointOnSurface(
  'MULTIPOINT (8 24,10 92,12 154,17 68,28 10,29 52,29 84,55 50,56 24,131 14,160 180,189 180)');
래스터 출력
POINT(55 50)
Figure
Geometry figure for st-pointonsurface-multipoint

Point on surface of a LineString.

Code
SELECT ST_PointOnSurface(
  'LINESTRING (190 160,10 190,40 90,20 70,10 10,30 40,30 10,110 40,70 10,110 10,140 40,140 10,160 30,180 10)');
래스터 출력
POINT(40 90)
Figure
Geometry figure for visual-st-pointonsurface-02

Point on surface of a Polygon.

Code
SELECT ST_PointOnSurface(
  'POLYGON ((190 190,10 190,10 10,190 10,190 20,160 30,60 30,60 130,190 140,190 190))');
래스터 출력
POINT(35 80)
Figure
Geometry figure for visual-st-pointonsurface-03

Point on surface of the highest-dimension components of a GeometryCollection.

Code
SELECT ST_PointOnSurface(
  'GEOMETRYCOLLECTION (POLYGON ((190 170,180 100,80 140,80 160,130 160,110 180,110 190,180 180,190 170)),
    LINESTRING (80 120,120 20,140 70,150 30,180 50,190 10),
    MULTIPOINT (19 150,22 49,30 13,32 101,45 35,67 88,75 16))');
래스터 출력
POINT(133.571 150)
Figure
Geometry figure for visual-st-pointonsurface-04
Code
SELECT ST_PointOnSurface('LINESTRING(0 5 1,0 0 1,0 10 2)');
래스터 출력
st_asewkt
--------------
 POINT(0 0 1)
(1 row)
Figure
Geometry figure for visual-st-pointonsurface-05

Example: The result of ST_PointOnSurface is guaranteed to lie within polygons, whereas the point computed by ST_Centroid may be outside.

Code
SELECT ST_PointOnSurface(geom) AS pt_on_surf, ST_Centroid(geom) AS centroid
    FROM (SELECT 'POLYGON ((130 120,120 190,30 140,50 20,190 20,
                      170 100,90 60,90 130,130 120))'::geometry AS geom) AS t;
래스터 출력
pt_on_surf    |                  centroid
-----------------+---------------------------------------------
 POINT(62.5 110) | POINT(100.18264840182648 85.11415525114155)
Figure
Geometry figure for visual-st-pointonsurface-06

제목

ST_Polygonize — Computes a collection of polygons formed from the linework of a set of geometries.

요약

geometry ST_Polygonize(geometry set geomfield);

geometry ST_Polygonize(geometry[] geom_array);

설명

Creates a GeometryCollection containing the polygons formed by the linework of a set of geometries. If the input linework does not form any polygons, an empty GeometryCollection is returned.

This function creates polygons covering all delimited areas. If the result is intended to form a valid polygonal geometry, use ST_BuildArea to prevent holes being filled.

[참고]

The input linework must be correctly noded for this function to work properly. To ensure input is noded use ST_Node on the input geometry before polygonizing.

[참고]

GeometryCollections can be difficult to handle with external tools. Use ST_Dump to convert the polygonized result into separate polygons.

GEOS 모듈로 실행

1.0.0RC1 버전부터 사용할 수 있습니다.

예시

Polygonize a set of input lines.

Code
WITH data(geom) AS (
  VALUES
    ('LINESTRING (180 40,30 20,20 90)'::geometry),
    ('LINESTRING (180 40,160 160)'::geometry),
    ('LINESTRING (80 60,120 130,150 80)'::geometry),
    ('LINESTRING (80 60,150 80)'::geometry),
    ('LINESTRING (20 90,70 70,80 130)'::geometry),
    ('LINESTRING (80 130,160 160)'::geometry),
    ('LINESTRING (20 90,20 160,70 190)'::geometry),
    ('LINESTRING (70 190,80 130)'::geometry),
    ('LINESTRING (70 190,160 160)'::geometry)
)
SELECT ST_Polygonize(geom)
FROM data;
래스터 출력
GEOMETRYCOLLECTION(POLYGON((180 40,30 20,20 90,70 70,80 130,160 160,180 40),(150 80,120 130,80 60,150 80)), POLYGON((80 60,120 130,150 80,80 60)), POLYGON((80 130,70 70,20 90,20 160,70 190,80 130)), POLYGON((160 160,80 130,70 190,160 160)))
Figure
Geometry figure for visual-st-polygonize-01

Polygonizing two polygon coverages and transferring attributes to the resultants:

Code
WITH poly_a(id, geom) AS (VALUES
  ('a1', 'POLYGON ((0 0, 4 0, 4 4, 0 4, 0 0))'::geometry),
  ('a2', 'POLYGON ((4 0, 8 0, 8 4, 4 4, 4 0))'::geometry)
),
poly_b(id, geom) AS (VALUES
  ('b1', 'POLYGON ((0 0, 8 0, 8 2, 0 2, 0 0))'::geometry),
  ('b2', 'POLYGON ((0 2, 8 2, 8 4, 0 4, 0 2))'::geometry)
),
lines AS (
  SELECT ST_Boundary(geom) AS geom FROM poly_a
  UNION ALL
  SELECT ST_Boundary(geom) FROM poly_b
),
noded AS (
  SELECT ST_UnaryUnion(ST_Collect(geom)) AS geom FROM lines
),
cells AS (
  SELECT (ST_Dump(ST_Polygonize(geom))).geom AS geom FROM noded
)
SELECT a.id AS id_a,
       b.id AS id_b,
       c.geom AS geom
FROM cells AS c
LEFT JOIN poly_a AS a ON ST_Within(ST_PointOnSurface(c.geom), a.geom)
LEFT JOIN poly_b AS b ON ST_Within(ST_PointOnSurface(c.geom), b.geom)
WHERE a.id IS NOT NULL OR b.id IS NOT NULL
ORDER BY id_a, id_b;
래스터 출력
id_a | id_b |              geom
------+------+--------------------------------
 a1   | b1   | POLYGON((4 0,0 0,0 2,4 2,4 0))
 a1   | b2   | POLYGON((4 4,4 2,0 2,0 4,4 4))
 a2   | b1   | POLYGON((4 0,4 2,8 2,8 0,4 0))
 a2   | b2   | POLYGON((4 2,4 4,8 4,8 2,4 2))
Figure
Geometry figure for visual-st-polygonize-02

Polygonizing a table of linestrings:

Code
SELECT ST_Polygonize(geom_4269) As geomtextrep
FROM (SELECT geom_4269 FROM ma.suffolk_edges) As foo;
래스터 출력
geomtextrep
-------------
 SRID=4269;GEOMETRYCOLLECTION(POLYGON((-71.040878 42.285678,-71.040943 42.2856,-71.04096 42.285752,-71.040878 42.285678)),
 POLYGON((-71.17166 42.353675,-71.172026 42.354044,-71.17239 42.354358,-71.171794 42.354971,-71.170511 42.354855,
 -71.17112 42.354238,-71.17166 42.353675)))
(1 row)

Use ST_Dump to dump out the polygonize geoms into individual polygons.

Code
SELECT (ST_Dump(t.polycoll)).geom AS geomtextrep
FROM (SELECT ST_Polygonize(geom_4269) AS polycoll
    FROM (SELECT geom_4269 FROM ma.suffolk_edges)
        As foo) AS t;
래스터 출력
geomtextrep
-------------
 SRID=4269;POLYGON((-71.040878 42.285678,-71.040943 42.2856,-71.04096 42.285752,
-71.040878 42.285678))
 SRID=4269;POLYGON((-71.17166 42.353675,-71.172026 42.354044,-71.17239 42.354358,
-71.171794 42.354971,-71.170511 42.354855,-71.17112 42.354238,-71.17166 42.353675))
(2 rows)

제목

ST_ReducePrecision — Returns a valid geometry with points rounded to a grid tolerance.

요약

geometry ST_ReducePrecision(geometry g, float8 gridsize);

설명

Returns a valid geometry with all points rounded to the provided grid tolerance, and features below the tolerance removed.

Unlike ST_SnapToGrid the returned geometry will be valid, with no ring self-intersections or collapsed components.

Precision reduction can be used to:

  • match coordinate precision to the data accuracy

  • reduce the number of coordinates needed to represent a geometry

  • ensure valid geometry output to formats which use lower precision (e.g. text formats such as WKT, GeoJSON or KML when the number of output decimal places is limited).

  • export valid geometry to systems which use lower or limited precision (e.g. SDE, Oracle tolerance value)

Availability: 3.1.0.

Requires GEOS >= 3.9.0.

예시

Code
SELECT ST_ReducePrecision('POINT(1.412 19.323)', 0.1);
래스터 출력
POINT(1.4 19.3)
Figure
Geometry figure for visual-st-reduceprecision-01
Code
SELECT ST_ReducePrecision('POINT(1.412 19.323)', 1.0);
래스터 출력
POINT(1 19)
Figure
Geometry figure for visual-st-reduceprecision-02
Code
SELECT ST_ReducePrecision('POINT(1.412 19.323)', 10);
래스터 출력
POINT(0 20)
Figure
Geometry figure for visual-st-reduceprecision-03

Precision reduction can reduce number of vertices

Code
SELECT ST_ReducePrecision('LINESTRING (10 10,19.6 30.1,20 30,20.3 30,40 40)', 1);
래스터 출력
LINESTRING (10 10, 20 30, 40 40)
Figure
Geometry figure for visual-st-reduceprecision-04

Precision reduction splits polygons if needed to ensure validity

Code
WITH data(geom) AS (
  VALUES ('POLYGON ((10 10,60 60.1,70 30,40 40,50 10,10 10))'::geometry)
)
SELECT geom AS input,
       ST_ReducePrecision(geom, 10) AS reduced
FROM data;
래스터 출력
-[ RECORD 1 ]------------------------------------------------
input   | POLYGON((10 10,60 60.1,70 30,40 40,50 10,10 10))
reduced | MULTIPOLYGON(((10 10,40 40,50 10,10 10)),((40 40,60 60,70 30,40 40)))
Figure
Geometry figure for visual-st-reduceprecision-05

제목

ST_SharedPaths — 두 입력 라인스트링/멀티라인스트링이 공유하는 경로를 담고 있는 집합을 반환합니다.

요약

geometry ST_SharedPaths(geometry lineal1, geometry lineal2);

설명

두 입력 도형이 공유하는 경로를 담고 있는 집합을 반환합니다. 동일한 방향을 향하는 경로가 이 집합의 첫 번째 요소이며, 반대 방향을 향하는 경로가 두 번째 요소입니다. 경로 그 자체는 첫 번째 도형의 방향을 따릅니다.

GEOS 모듈로 실행

2.0.0 버전부터 사용할 수 있습니다.

예시: 공유된 경로 찾기

Adjacent shared path segments may be returned as separate or merged LineStrings depending on the GEOS version.

Find the shared paths of a MultiLineString and a LineString.

Code
SELECT ST_SharedPaths(ST_GeomFromText('MULTILINESTRING((26 125,26 200,126 200,126 125,26 125),
      (51 150,101 150,76 175,51 150))'),
   ST_GeomFromText('LINESTRING(151 100,126 156.25,126 125,101 150,76 175)')
   )
래스터 출력
GEOMETRYCOLLECTION(MULTILINESTRING((126 156.25,126 125),
(101 150,76 175)),MULTILINESTRING EMPTY)
Figure
Geometry figure for visual-st-sharedpaths-01

Flip the LineString orientation to return the same paths in the opposite-direction member.

Code
SELECT ST_SharedPaths(ST_GeomFromText('LINESTRING(76 175,101 150,126 125,126 156.25,151 100)'),
   ST_GeomFromText('MULTILINESTRING((26 125,26 200,126 200,126 125,26 125),
       (51 150,101 150,76 175,51 150))')
    )
래스터 출력
GEOMETRYCOLLECTION(MULTILINESTRING EMPTY,
MULTILINESTRING((76 175,101 150),(126 125,126 156.25)))
Figure
Geometry figure for visual-st-sharedpaths-02

제목

ST_Simplify — Returns a simplified representation of a geometry, using the Douglas-Peucker algorithm.

요약

geometry ST_Simplify(geometry geom, float tolerance);

geometry ST_Simplify(geometry geom, float tolerance, boolean preserveCollapsed);

설명

Computes a simplified representation of a geometry using the Douglas-Peucker algorithm. The simplification tolerance is a distance value, in the units of the input SRS. Simplification removes vertices which are within the tolerance distance of the simplified linework. The result may not be valid even if the input is.

The function can be called with any kind of geometry (including GeometryCollections), but only line and polygon elements are simplified. Endpoints of linear geometry are preserved.

The preserveCollapsed flag retains small geometries that would otherwise be removed at the given tolerance. For example, if a 1m long line is simplified with a 10m tolerance, when preserveCollapsed is true the line will not disappear. This flag is useful for rendering purposes, to prevent very small features disappearing from a map.

[참고]

The returned geometry may lose its simplicity (see ST_IsSimple), topology may not be preserved, and polygonal results may be invalid (see ST_IsValid). Use ST_SimplifyPreserveTopology to preserve topology and ensure validity.

[참고]

This function does not preserve boundaries shared between polygons. Use ST_CoverageSimplify if this is required.

1.2.2 버전부터 사용할 수 있습니다.

예시

A circle simplified with a medium tolerance becomes an octagon, and with a large tolerance disappears.

Code
SELECT ST_NPoints(geom) AS np_before,
     ST_NPoints(ST_Simplify(geom, 0.1)) AS np01_notbadcircle,
     ST_NPoints(ST_Simplify(geom, 0.5)) AS np05_notquitecircle,
     ST_NPoints(ST_Simplify(geom, 1)) AS np1_octagon,
     ST_NPoints(ST_Simplify(geom, 10)) AS np10_gone,
     (ST_Simplify(geom, 100) is null) AS  np100_geometrygoesaway
FROM (SELECT ST_Buffer('POINT(1 3)', 10, 12) As geom) AS t;
래스터 출력
-[ RECORD 1 ]------------
np_before                | 49
np01_notbadcircle        | 33
np05_notquitecircle      | 17
np1_octagon              | 9
np10_gone                | null
np100_geometrygoesaway   | t

Simplifying a set of lines. Lines may intersect after simplification.

Code
SELECT ST_Simplify('MULTILINESTRING ((20 180,20 150,50 150,50 100,110 150,150 140,170 120),(20 10,80 30,90 120),(90 120,130 130),(130 130,130 70,160 40,180 60,180 90,140 80),(50 40,70 40,80 70,70 60,60 60,50 50,50 40))'::geometry,
40);
래스터 출력
MULTILINESTRING((20 180,50 100,170 120),(20 10,90 120),(90 120,130 130),(130 130,160 40,180 90,140 80),(50 40,80 70,50 40))
Figure
Geometry figure for visual-st-simplify-02

Simplifying a MultiPolygon. Polygonal results may be invalid.

Code
SELECT ST_Simplify('MULTIPOLYGON (((90 110,80 180,50 160,10 170,10 140,20 110,90 110)),((40 80,100 100,120 160,170 180,190 70,140 10,110 40,60 40,40 80),(180 70,170 110,142.5 128.5,128.5 77.5,90 60,180 70)))'::geometry,
40);
래스터 출력
MULTIPOLYGON(((90 110,80 180,10 170,20 110,90 110)),((40 80,170 180,140 10,40 80),(180 70,142.5 128.5,90 60,180 70)))
Figure
Geometry figure for visual-st-simplify-03

제목

ST_SimplifyPreserveTopology — Returns a simplified and valid representation of a geometry, using the Douglas-Peucker algorithm.

요약

geometry ST_SimplifyPreserveTopology(geometry geom, float tolerance);

설명

Computes a simplified representation of a geometry using a variant of the Douglas-Peucker algorithm which limits simplification to ensure the result has the same topology as the input. The simplification tolerance is a distance value, in the units of the input SRS. Simplification removes vertices which are within the tolerance distance of the simplified linework, as long as topology is preserved. The result will be valid and simple if the input is.

The function can be called with any kind of geometry (including GeometryCollections), but only line and polygon elements are simplified. For polygonal inputs, the result will have the same number of rings (shells and holes), and the rings will not cross. Ring endpoints may be simplified. For linear inputs, the result will have the same number of lines, and lines will not intersect if they did not do so in the original geometry. Endpoints of linear geometry are preserved.

[참고]

This function does not preserve boundaries shared between polygons. Use ST_CoverageSimplify if this is required.

GEOS 모듈로 실행

1.3.3 버전부터 사용할 수 있습니다.

예시

For the same example as ST_Simplify, ST_SimplifyPreserveTopology prevents the geometry from disappearing.

Code
SELECT  ST_NPoints(geom) AS np_before,
        ST_NPoints(ST_SimplifyPreserveTopology(geom, 0.1)) AS np01_notbadcircle,
        ST_NPoints(ST_SimplifyPreserveTopology(geom, 0.5)) AS np05_notquitecircle,
        ST_NPoints(ST_SimplifyPreserveTopology(geom, 1))   AS np1_octagon,
        ST_NPoints(ST_SimplifyPreserveTopology(geom, 10))  AS np10_minimal,
        ST_NPoints(ST_SimplifyPreserveTopology(geom, 100)) AS np100_minimal
FROM (SELECT ST_Buffer('POINT(1 3)', 10, 12) AS geom) AS t;
래스터 출력
np_before | np01_notbadcircle | np05_notquitecircle | np1_octagon | np10_minimal | np100_minimal
-----------+-------------------+---------------------+-------------+--------------+---------------
        49 |                33 |                  17 |           9 |            4 |             4

Simplifying a set of lines, preserving topology of non-intersecting lines.

Code
SELECT ST_SimplifyPreserveTopology('MULTILINESTRING ((20 180,20 150,50 150,50 100,110 150,150 140,170 120),(20 10,80 30,90 120),(90 120,130 130),(130 130,130 70,160 40,180 60,180 90,140 80),(50 40,70 40,80 70,70 60,60 60,50 50,50 40))'::geometry,
40);
래스터 출력
MULTILINESTRING((20 180,50 100,110 150,170 120),(20 10,80 30,90 120),(90 120,130 130),(130 130,130 70,160 40,180 90,140 80),(50 40,70 40,80 70,60 60,50 40))
Figure
Geometry figure for visual-st-simplifypreservetopology-02

Simplifying a MultiPolygon, preserving topology of shells and holes.

Code
SELECT ST_SimplifyPreserveTopology('MULTIPOLYGON (((90 110,80 180,50 160,10 170,10 140,20 110,90 110)),((40 80,100 100,120 160,170 180,190 70,140 10,110 40,60 40,40 80),(180 70,170 110,142.5 128.5,128.5 77.5,90 60,180 70)))'::geometry,
40);
래스터 출력
MULTIPOLYGON(((90 110,80 180,10 170,20 110,90 110)),((40 80,100 100,170 180,190 70,140 10,40 80),(180 70,142.5 128.5,90 60,180 70)))
Figure
Geometry figure for visual-st-simplifypreservetopology-03

제목

ST_SimplifyPolygonHull — Computes a simplified topology-preserving outer or inner hull of a polygonal geometry.

요약

geometry ST_SimplifyPolygonHull(geometry param_geom, float vertex_fraction, boolean is_outer = true);

설명

Computes a simplified topology-preserving outer or inner hull of a polygonal geometry. An outer hull completely covers the input geometry. An inner hull is completely covered by the input geometry. The result is a polygonal geometry formed by a subset of the input vertices. MultiPolygons and holes are handled and produce a result with the same structure as the input.

The reduction in vertex count is controlled by the vertex_fraction parameter, which is a number in the range 0 to 1. Lower values produce simpler results, with smaller vertex count and less concaveness. For both outer and inner hulls a vertex fraction of 1.0 produces the original geometry. For outer hulls a value of 0.0 produces the convex hull (for a single polygon); for inner hulls it produces a triangle.

The simplification process operates by progressively removing concave corners that contain the least amount of area, until the vertex count target is reached. It prevents edges from crossing, so the result is always a valid polygonal geometry.

To get better results with geometries that contain relatively long line segments, it might be necessary to "segmentize" the input, as shown below.

GEOS 모듈로 실행

Availability: 3.3.0.

Requires GEOS >= 3.11.0.

예시

Outer hull of a Polygon.

Code
SELECT ST_SimplifyPolygonHull(
  'POLYGON ((131 158,136 163,161 165,173 156,179 148,169 140,186 144,190 137,185 131,174 128,174 124,166 119,158 121,158 115,165 107,161 97,166 88,166 79,158 57,145 57,112 53,111 47,93 43,90 48,88 40,80 39,68 32,51 33,40 31,39 34,49 38,34 38,25 34,28 39,36 40,44 46,24 41,17 41,14 46,19 50,33 54,21 55,13 52,11 57,22 60,34 59,41 68,75 72,62 77,56 70,46 72,31 69,46 76,52 82,47 84,56 90,66 90,64 94,56 91,33 97,36 100,23 100,22 107,29 106,31 112,46 116,36 118,28 131,53 132,59 127,62 131,76 130,80 135,89 137,87 143,73 145,80 150,88 150,85 157,99 162,116 158,115 165,123 165,122 170,134 164,131 158))'::geometry,
  0.3
);
래스터 출력
POLYGON((161 165,173 156,186 144,190 137,185 131,174 124,166 119,166 79,158 57,68 32,40 31,25 34,17 41,14 46,11 57,56 91,33 97,23 100,22 107,28 131,80 135,73 145,85 157,99 162,122 170,161 165))
Figure
Geometry figure for visual-st-simplifypolygonhull-01

Inner hull of a Polygon.

Code
SELECT ST_SimplifyPolygonHull(
  'POLYGON ((131 158,136 163,161 165,173 156,179 148,169 140,186 144,190 137,185 131,174 128,174 124,166 119,158 121,158 115,165 107,161 97,166 88,166 79,158 57,145 57,112 53,111 47,93 43,90 48,88 40,80 39,68 32,51 33,40 31,39 34,49 38,34 38,25 34,28 39,36 40,44 46,24 41,17 41,14 46,19 50,33 54,21 55,13 52,11 57,22 60,34 59,41 68,75 72,62 77,56 70,46 72,31 69,46 76,52 82,47 84,56 90,66 90,64 94,56 91,33 97,36 100,23 100,22 107,29 106,31 112,46 116,36 118,28 131,53 132,59 127,62 131,76 130,80 135,89 137,87 143,73 145,80 150,88 150,85 157,99 162,116 158,115 165,123 165,122 170,134 164,131 158))'::geometry,
  0.3, false
);
래스터 출력
POLYGON((131 158,116 158,99 162,89 137,76 130,59 127,28 131,46 116,36 100,64 94,75 72,41 68,33 54,68 32,90 48,112 53,145 57,158 57,161 97,158 115,158 121,190 137,169 140,179 148,161 165,131 158))
Figure
Geometry figure for visual-st-simplifypolygonhull-02

Outer hull simplification of a MultiPolygon, with segmentization.

Code
WITH letters AS (
  SELECT ST_Letters('xt') AS geom
)
SELECT geom AS input,
  ST_SimplifyPolygonHull(ST_Segmentize(geom, 2.0), 0.1) AS outer_hull
FROM letters;
래스터 출력
MULTIPOLYGON(((18.3 57.6,20.7 51,23.3 41.9,26 51,28.4 57.6,45.4 57.6,33.1 28.8,46.6 0,29.5 0,26.6 6.7,23.3 16.3,19.8 6.3,17.1 0,0 0,13.5 28.8,1.3 57.6,18.3 57.6)),((77.808 15.2,82.208 15.2,83.508 16,83.508 -0.9,82.108 -0.2,76.808 -0.2,76.108 -0.2,75.408 -0.2,74.608 -0.1,73.908 -0.1,73.208 0,72.508 0,71.808 0.1,71.108 0.2,70.408 0.3,69.708 0.5,69.008 0.6,68.408 0.9,67.708 1.1,67.008 1.4,66.408 1.7,65.708 2,65.108 2.4,64.408 2.8,63.808 3.2,63.208 3.7,62.608 4.1,62.108 4.7,61.508 5.2,61.008 5.8,60.508 6.4,60.008 7.1,59.508 7.8,59.108 8.6,58.708 9.5,58.308 10.4,57.908 11.3,57.608 12.3,57.608 42.7,52.208 42.7,51.108 41.8,51.108 58.9,52.208 57.9,57.608 57.9,57.608 74.4,56.508 75.4,74.408 75.4,73.308 74.2,73.308 57.9,81.408 57.9,82.508 58.9,82.508 41.8,81.408 42.7,73.308 42.7,73.308 17.7,73.408 17.4,73.608 17.2,73.808 16.9,74.008 16.7,74.208 16.5,74.408 16.3,74.708 16.1,75.008 15.9,75.308 15.7,75.608 15.6,76.008 15.5,76.308 15.4,76.708 15.3,77.008 15.2,77.408 15.2,77.808 15.2))) | MULTIPOLYGON(((45.4 57.6,44.631 55.8,33.869 30.6,46.6 0,29.5 0,19.8 6.3,18.45 3.15,17.1 0,0 0,10.969 23.4,9.688 37.8,2.062 55.8,1.3 57.6,45.4 57.6)),((83.508 16,83.508 -0.9,72.508 0,71.108 0.2,70.408 0.3,69.008 0.6,67.708 1.1,67.008 1.4,65.708 2,64.408 2.8,63.808 3.2,62.608 4.1,61.508 5.2,60.508 6.4,59.508 7.8,59.108 8.6,58.308 10.4,57.908 11.3,57.608 12.3,51.108 41.8,51.108 58.9,56.508 75.4,74.408 75.4,82.508 58.9,83.508 16)))
Figure
Geometry figure for visual-st-simplifypolygonhull-03

제목

ST_SimplifyVW — Returns a simplified representation of a geometry, using the Visvalingam-Whyatt algorithm

요약

geometry ST_SimplifyVW(geometry geom, float tolerance);

설명

Returns a simplified representation of a geometry using the Visvalingam-Whyatt algorithm. The simplification tolerance is an area value, in squared units of the input SRS. Simplification removes vertices which form "corners" with area less than the tolerance. The result may not be valid even if the input is.

The function can be called with any kind of geometry (including GeometryCollections), but only line and polygon elements are simplified. Endpoints of linear geometry are preserved.

[참고]

The returned geometry may lose its simplicity (see ST_IsSimple), topology may not be preserved, and polygonal results may be invalid (see ST_IsValid). Use ST_SimplifyPreserveTopology to preserve topology and ensure validity. ST_CoverageSimplify also preserves topology and validity.

This is a general-purpose simplification function. It may remove narrow polygon spikes when their effective area is below the tolerance, but it is not a dedicated spike-removal or polygon-repair operation. Use ST_IsValid to check the result and ST_MakeValid to repair invalid polygonal output if needed.

This function does not preserve boundaries shared between polygons. Use ST_CoverageSimplify if this is required.

이 함수는 3차원을 처리하며, 세 번째 차원이 결과에 영향을 미칠 것입니다.

2.2.0 버전부터 사용할 수 있습니다.

예시

This polygon has a narrow spike whose effective area is small enough to be removed by a tolerance of 20 square units.

Code
SELECT geom AS original, ST_SimplifyVW(geom, 20) AS simplified
FROM (SELECT 'POLYGON((0 0,10 0,10 10,5.2 10,5 16,4.8 10,0 10,0 0))'::geometry AS geom) AS t;
래스터 출력
POLYGON((0 0,10 0,10 10,5.2 10,5 16,4.8 10,0 10,0 0)) | POLYGON((0 0,10 0,10 10,0 10,0 0))
Figure
Geometry figure for visual-st-simplifyvw-01

A LineString is simplified with a minimum-area tolerance of 30. For a linear simplification using ST_Simplify, a comparable tolerance would be a length in input-SRS units, so the value here is roughly that linear tolerance squared.

Code
SELECT ST_SimplifyVW(geom, 30) simplified
  FROM (SELECT 'LINESTRING(5 2,3 8,6 20,7 25,10 10)'::geometry AS geom) AS t;
래스터 출력
LINESTRING(5 2,7 25,10 10)
Figure
Geometry figure for visual-st-simplifyvw-02

Simplifying a line.

Code
SELECT ST_SimplifyVW('LINESTRING (10 10,50 40,30 70,50 60,70 80,50 110,100 100,90 140,100 180,150 170,170 140,190 90,180 40,110 40,150 20)'::geometry,
1600);
래스터 출력
LINESTRING(10 10,100 100,100 180,150 170,190 90,150 20)
Figure
Geometry figure for visual-st-simplifyvw-03

Simplifying a polygon.

Code
SELECT ST_SimplifyVW('POLYGON ((20 20,50 60,20 120,40 170,80 180,120 140,180 180,160 130,180 100,180 30,130 70,150 10,20 20))'::geometry,
1600);
래스터 출력
POLYGON((20 20,20 120,80 180,160 130,180 30,20 20))
Figure
Geometry figure for visual-st-simplifyvw-04

제목

ST_SetEffectiveArea — Sets the effective area for each vertex, using the Visvalingam-Whyatt algorithm.

요약

geometry ST_SetEffectiveArea(geometry geom, float threshold = 0, integer set_area = 1);

설명

비스베일링검-와이어트 알고리즘을 이용해서 각 꼭짓점에 대한 유효 범위를 설정합니다. 유효 범위는 꼭짓점의 M값으로 저장됩니다. 선택적인 "임계" 파라미터를 설정할 경우, 임계치 이상의 유효 범위를 가진 꼭짓점만을 담고 있는 단순화된 도형을 반환할 것입니다.

임계치를 설정할 경우 이 함수를 서버측 단순화 작업에 이용할 수 있습니다. 또다른 옵션은 임계치를 0으로 설정하는 것입니다. 이럴 경우, 유효 범위를 M값으로 가진 전체 도형을 반환하는데, 이 도형을 클라이언트측에서 매우 빨리 단순화하는 데 쓸 수 있습니다.

실제로는 [멀티]라인, [멀티]폴리곤과만 작동하지만, 어떤 종류의 도형도 입력할 수 있다고 해도 과언은 아닙니다. 객체별 기반으로 단순화 작업을 하기 때문에 이 함수에 도형 집합도 입력할 수 있습니다.

[참고]

반환되는 도형이 단순성을 잃을 수도 있다는 점에 주의하십시오(ST_IsSimple 참조).

[참고]

위상(topology)이 보전되지 않아 유효하지 않은 도형이 반환될 수도 있습니다. 위상을 유지하려면 ST_SimplifyPreserveTopology 함수를 이용하십시오.

[참고]

출력 도형은 M값으로 가지고 있던 정보를 모두 잃게 될 것입니다.

[참고]

이 함수는 3차원을 처리하며, 세 번째 차원이 유효 범위에 영향을 미칠 것입니다.

2.2.0 버전부터 사용할 수 있습니다.

예시

라인스트링의 유효 범위를 계산합니다. 임계치를 0으로 설정하기 때문에, 입력 도형 안에 있는 모든 꼭짓점을 반환합니다.

Code
SELECT ST_SetEffectiveArea(geom) AS all_pts,
       ST_SetEffectiveArea(geom, 30) AS threshold_30
FROM (SELECT  'LINESTRING(5 2,3 8,6 20,7 25,10 10)'::geometry geom) As foo;
래스터 출력
-[ RECORD 1 ]------------------
all_pts      | LINESTRING M (5 2 3.4e+38,3 8 29,6 20 1.5,7 25 49.5,10 10 3.4e+38)
threshold_30 | LINESTRING M (5 2 3.4e+38,7 25 49.5,10 10 3.4e+38)
Figure
Geometry figure for visual-st-seteffectivearea-01

제목

ST_TriangulatePolygon — Computes the constrained Delaunay triangulation of polygons

요약

geometry ST_TriangulatePolygon(geometry geom);

설명

Computes the constrained Delaunay triangulation of polygons. Holes and Multipolygons are supported.

The "constrained Delaunay triangulation" of a polygon is a set of triangles formed from the vertices of the polygon, and covering it exactly, with the maximum total interior angle over all possible triangulations. It provides the "best quality" triangulation of the polygon.

Availability: 3.3.0.

Requires GEOS >= 3.11.0.

예시

Triangulation of a square.

Code
SELECT ST_TriangulatePolygon('POLYGON((0 0,0 1,1 1,1 0,0 0))');
래스터 출력
GEOMETRYCOLLECTION(POLYGON((0 0,0 1,1 1,0 0)), POLYGON((1 1,1 0,0 0,1 1)))
Figure
Geometry figure for visual-st-triangulatepolygon-01

Triangulation of the letter P.

Code
SELECT ST_TriangulatePolygon('POLYGON ((26 17,31 19,34 21,37 24,38 29,39 43,39 161,38 172,36 176,34 179,30 181,25 183,10 185,10 190,100 190,121 189,139 187,154 182,167 177,177 169,184 161,189 152,190 141,188 128,186 123,184 117,180 113,176 108,170 104,164 101,151 96,136 92,119 89,100 89,86 89,73 89,73 39,74 32,75 27,77 23,79 20,83 18,89 17,106 15,106 10,10 10,10 15,26 17),(152 147,151 152,149 157,146 162,142 166,137 169,132 172,126 175,118 177,109 179,99 180,89 180,80 179,76 178,74 176,73 171,73 100,85 99,91 99,102 99,112 100,121 102,128 104,134 107,139 110,143 114,147 118,149 123,151 128,153 141,152 147))'
);
래스터 출력
GEOMETRYCOLLECTION (POLYGON ((10 10, 10 15, 26 17, 10 10)), POLYGON ((25 183, 10 185, 10 190, 25 183)), POLYGON ((126 175, 121 189, 139 187, 126 175)), POLYGON ((137 169, 139 187, 154 182, 137 169)), POLYGON ((149 157, 167 177, 177 169, 149 157)), POLYGON ((153 141, 189 152, 190 141, 153 141)), POLYGON ((153 141, 188 128, 186 123, 153 141)), POLYGON ((186 123, 184 117, 180 113, 186 123)), POLYGON ((149 123, 176 108, 170 104, 149 123)), POLYGON ((147 118, 164 101, 151 96, 147 118)), POLYGON ((121 102, 136 92, 119 89, 121 102)), POLYGON ((85 99, 73 89, 73 100, 85 99)), POLYGON ((89 17, 106 15, 106 10, 89 17)), POLYGON ((83 18, 10 10, 26 17, 83 18)), POLYGON ((100 190, 25 183, 10 190, 100 190)), POLYGON ((121 189, 109 179, 100 190, 121 189)), POLYGON ((189 152, 152 147, 184 161, 189 152)), POLYGON ((153 141, 190 141, 188 128, 153 141)), POLYGON ((147 118, 170 104, 164 101, 147 118)), POLYGON ((139 110, 151 96, 136 92, 139 110)), POLYGON ((73 89, 85 99, 86 89, 73 89)), POLYGON ((83 18, 89 17, 106 10, 83 18)), POLYGON ((83 18, 26 17, 31 19, 83 18)), POLYGON ((100 190, 30 181, 25 183, 100 190)), POLYGON ((189 152, 153 141, 152 147, 189 152)), POLYGON ((176 108, 151 128, 180 113, 176 108)), POLYGON ((91 99, 86 89, 85 99, 91 99)), POLYGON ((10 10, 83 18, 106 10, 10 10)), POLYGON ((76 178, 100 190, 80 179, 76 178)), POLYGON ((86 89, 91 99, 100 89, 86 89)), POLYGON ((79 20, 83 18, 31 19, 79 20)), POLYGON ((102 99, 100 89, 91 99, 102 99)), POLYGON ((34 21, 79 20, 31 19, 34 21)), POLYGON ((112 100, 100 89, 102 99, 112 100)), POLYGON ((37 24, 79 20, 34 21, 37 24)), POLYGON ((100 89, 112 100, 119 89, 100 89)), POLYGON ((79 20, 37 24, 77 23, 79 20)), POLYGON ((119 89, 112 100, 121 102, 119 89)), POLYGON ((77 23, 37 24, 75 27, 77 23)), POLYGON ((136 92, 121 102, 128 104, 136 92)), POLYGON ((38 29, 75 27, 37 24, 38 29)), POLYGON ((134 107, 136 92, 128 104, 134 107)), POLYGON ((75 27, 38 29, 74 32, 75 27)), POLYGON ((139 110, 136 92, 134 107, 139 110)), POLYGON ((74 32, 38 29, 73 39, 74 32)), POLYGON ((151 96, 139 110, 143 114, 151 96)), POLYGON ((39 43, 73 39, 38 29, 39 43)), POLYGON ((151 96, 143 114, 147 118, 151 96)), POLYGON ((73 39, 39 43, 73 89, 73 39)), POLYGON ((170 104, 147 118, 149 123, 170 104)), POLYGON ((73 89, 39 43, 73 100, 73 89)), POLYGON ((176 108, 149 123, 151 128, 176 108)), POLYGON ((39 161, 73 100, 39 43, 39 161)), POLYGON ((180 113, 151 128, 186 123, 180 113)), POLYGON ((73 100, 39 161, 73 171, 73 100)), POLYGON ((186 123, 151 128, 153 141, 186 123)), POLYGON ((38 172, 73 171, 39 161, 38 172)), POLYGON ((151 152, 184 161, 152 147, 151 152)), POLYGON ((73 171, 38 172, 74 176, 73 171)), POLYGON ((184 161, 151 152, 177 169, 184 161)), POLYGON ((36 176, 74 176, 38 172, 36 176)), POLYGON ((149 157, 177 169, 151 152, 149 157)), POLYGON ((34 179, 74 176, 36 176, 34 179)), POLYGON ((146 162, 167 177, 149 157, 146 162)), POLYGON ((74 176, 34 179, 76 178, 74 176)), POLYGON ((167 177, 146 162, 154 182, 167 177)), POLYGON ((30 181, 76 178, 34 179, 30 181)), POLYGON ((154 182, 146 162, 142 166, 154 182)), POLYGON ((100 190, 76 178, 30 181, 100 190)), POLYGON ((154 182, 142 166, 137 169, 154 182)), POLYGON ((80 179, 100 190, 89 180, 80 179)), POLYGON ((139 187, 137 169, 132 172, 139 187)), POLYGON ((100 190, 99 180, 89 180, 100 190)), POLYGON ((139 187, 132 172, 126 175, 139 187)), POLYGON ((100 190, 109 179, 99 180, 100 190)), POLYGON ((121 189, 126 175, 118 177, 121 189)), POLYGON ((121 189, 118 177, 109 179, 121 189)))
Figure
Geometry figure for visual-st-triangulatepolygon-02

Triangulation of the polygon used in the CG_Tesselate example.

Code
SELECT ST_TriangulatePolygon('POLYGON (( 10 190,10 70,80 70,80 130,50 160,120 160,120 190,10 190 ))'::geometry
);
래스터 출력
GEOMETRYCOLLECTION(POLYGON((50 160,120 190,120 160,50 160)),
POLYGON((10 70,80 130,80 70,10 70)),
POLYGON((50 160,10 70,10 190,50 160)),
POLYGON((120 190,50 160,10 190,120 190)),
POLYGON((80 130,10 70,50 160,80 130)))
Figure
Geometry figure for visual-st-triangulatepolygon-03

제목

ST_VoronoiLines — Returns the boundaries of the Voronoi diagram of the vertices of a geometry.

요약

geometry ST_VoronoiLines( geometry geom , float8 tolerance = 0.0 , geometry extend_to = NULL );

설명

Computes a two-dimensional Voronoi diagram from the vertices of the supplied geometry and returns the boundaries between cells in the diagram as a MultiLineString. Returns null if input geometry is null. Returns an empty geometry collection if the input geometry contains only one vertex. Returns an empty geometry collection if the extend_to envelope has zero area.

선택할 수 있는 파라미터:

  • tolerance: The distance within which vertices will be considered equivalent. Robustness of the algorithm can be improved by supplying a nonzero tolerance distance. (default = 0.0)

  • extend_to: If present, the diagram is extended to cover the envelope of the supplied geometry, unless smaller than the default envelope (default = NULL, default envelope is the bounding box of the input expanded by about 50%).

GEOS 모듈로 실행

2.3.0 버전부터 사용할 수 있습니다.

예시

Voronoi diagram lines with a tolerance of 30 units.

Code
SELECT ST_VoronoiLines('MULTIPOINT (50 30,60 30,100 100,10 150,110 120)'::geometry,
            30) AS geom;
래스터 출력
MULTILINESTRING((135.555555555556 270,36.8181818181818 92.2727272727273),(36.8181818181818 92.2727272727273,-110 43.3333333333333),(230 -45.7142857142858,36.8181818181818 92.2727272727273))
Figure
Geometry figure for visual-st-voronoilines-01

제목

ST_VoronoiPolygons — Returns the cells of the Voronoi diagram of the vertices of a geometry.

요약

geometry ST_VoronoiPolygons( geometry geom , float8 tolerance = 0.0 , geometry extend_to = NULL );

설명

Computes a two-dimensional Voronoi diagram from the vertices of the supplied geometry. The result is a GEOMETRYCOLLECTION of POLYGONs that covers an envelope larger than the extent of the input vertices. Returns null if input geometry is null. Returns an empty geometry collection if the input geometry contains only one vertex. Returns an empty geometry collection if the extend_to envelope has zero area.

선택할 수 있는 파라미터:

  • tolerance: The distance within which vertices will be considered equivalent. Robustness of the algorithm can be improved by supplying a nonzero tolerance distance. (default = 0.0)

  • extend_to: If present, the diagram is extended to cover the envelope of the supplied geometry, unless smaller than the default envelope (default = NULL, default envelope is the bounding box of the input expanded by about 50%).

GEOS 모듈로 실행

2.3.0 버전부터 사용할 수 있습니다.

예시

Points overlaid on top of the Voronoi diagram.

Code
SELECT ST_VoronoiPolygons('MULTIPOINT (50 30,60 30,100 100,10 150,110 120)'::geometry
            ) AS geom;
래스터 출력
GEOMETRYCOLLECTION(POLYGON((-110 270,100.5 270,59.34782608695652 132.82608695652175,36.81818181818182 92.27272727272727,-110 43.33333333333332,-110 270)),
POLYGON((-110 -90,-110 43.33333333333332,36.81818181818182 92.27272727272727,55 79.28571428571429,55 -90,-110 -90)),
POLYGON((230 -20.71428571428572,55 79.28571428571429,36.81818181818182 92.27272727272727,59.34782608695652 132.82608695652175,230 47.50000000000001,230 -20.71428571428572)), POLYGON((230 -90,55 -90,55 79.28571428571429,230 -20.71428571428572,230 -90)),
POLYGON((230 270,230 47.50000000000001,59.34782608695652 132.82608695652175,100.5 270,230 270)))
Figure
Geometry figure for visual-st-voronoipolygons-01

Voronoi diagram with a tolerance of 30 units.

Code
SELECT ST_VoronoiPolygons('MULTIPOINT (50 30,60 30,100 100,10 150,110 120)'::geometry,
            30) AS geom;
래스터 출력
GEOMETRYCOLLECTION(POLYGON((-110 270,135.55555555555557 270,36.81818181818182 92.27272727272727,-110 43.33333333333332,-110 270)),
POLYGON((230 270,230 -45.71428571428574,36.81818181818182 92.27272727272727,135.55555555555557 270,230 270)),
POLYGON((230 -90,-110 -90,-110 43.33333333333332,36.81818181818182 92.27272727272727,230 -45.71428571428574,230 -90)))
Figure
Geometry figure for visual-st-voronoipolygons-02

7.15. Coverages

초록

These functions operate on sets of polygonal geometry that form "implicit coverages". To form a valid coverage polygons must not overlap, and the vertices of adjacent edges must match exactly. Coverages are fast to process, and can be operated on with window functions, which retain the coverage topology inside the window partition while altering the edges.

  • ST_CoverageInvalidEdges — Window function that finds locations where polygons fail to form a valid coverage.
  • ST_CoverageClean — Computes a clean (edge matched, non-overlapping, gap-cleared) polygonal coverage, given a non-clean input.
  • ST_CoverageSimplify — Window function that simplifies the edges of a polygonal coverage.
  • ST_CoverageEdges — Computes the unique edges of a polygonal coverage.
  • ST_CoverageUnion — Computes the union of a set of polygons forming a coverage by removing shared edges.

제목

ST_CoverageInvalidEdges — Window function that finds locations where polygons fail to form a valid coverage.

요약

geometry ST_CoverageInvalidEdges(geometry winset geom, float8 tolerance = 0);

설명

A window function which checks if the polygons in the window partition form a valid polygonal coverage. It returns linear indicators showing the location of invalid edges (if any) in each polygon.

A set of valid polygons is a valid coverage if the following conditions hold:

  • Non-overlapping - polygons do not overlap (their interiors do not intersect)

  • Edge-Matched - vertices along shared edges are identical

As a window function a value is returned for every input polygon. For polygons which violate one or more of the validity conditions the return value is a MULTILINESTRING containing the problematic edges. Coverage-valid polygons return the value NULL. Non-polygonal or empty geometries also produce NULL values.

The conditions allow a valid coverage to contain holes (gaps between polygons), as long as the surrounding polygons are edge-matched. However, very narrow gaps are often undesirable. If the tolerance parameter is specified with a non-zero distance, edges forming narrower gaps will also be returned as invalid.

The polygons being checked for coverage validity must also be valid geometries. This can be checked with ST_IsValid.

Availability: 3.4.0

Requires GEOS >= 3.12.0

예시

Invalid edges caused by overlap and non-matching vertices.

Code
WITH coverage(id, geom) AS (VALUES
  (1, 'POLYGON ((10 190,30 160,40 110,100 70,120 10,10 10,10 190))'::geometry),
  (2, 'POLYGON ((100 190,10 190,30 160,40 110,50 80,74 110.5,100 130,140 120,140 160,100 190))'::geometry),
  (3, 'POLYGON ((140 190,190 190,190 80,140 80,140 190))'::geometry),
  (4, 'POLYGON ((180 40,120 10,100 70,140 80,190 80,180 40))'::geometry)
)
SELECT id, ST_CoverageInvalidEdges(geom) OVER ()
  FROM coverage;
래스터 출력
id |               st_astext
----+---------------------------------------
  1 | LINESTRING (40 110, 100 70)
  2 | MULTILINESTRING ((100 130, 140 120, 140 160, 100 190), (40 110, 50 80, 74 110.5))
  3 | LINESTRING (140 80, 140 190)
  4 | null
Figure
Geometry figure for visual-st-coverageinvalidedges-01

This example tests the entire table for coverage validity.

Code
SELECT true = ALL (
    SELECT ST_CoverageInvalidEdges(geom) OVER () IS NULL
    FROM coverage
    );
      

제목

ST_CoverageClean — Computes a clean (edge matched, non-overlapping, gap-cleared) polygonal coverage, given a non-clean input.

요약

geometry ST_CoverageClean(geometry winset geom, float8 gapMaximumWidth = 0, float8 snappingDistance = -1, text overlapMergeStrategy = 'MERGE_LONGEST_BORDER');

설명

A window function which adjusts the edges of a set of valid polygonal geometries to produce a clean coverage. Cleaning involves:

  • snapping vertices and edges to remove small discrepancies and ensure common edges are identically noded

  • merging overlaps into a parent polygon

  • merging narrow gaps into adjacent polygons

gapMaximumWidth controls which gaps between polygons are merged. Gaps with width <= this distance are merged into an adjacent polygon.

snappingDistance controls snapping of vertices and edges. The default (-1) automatically determines a snapping distance based on the input extent. Set to 0.0 to turn off snapping.

overlapMergeStrategy specifies how overlaps are merged into a parent polygon:

  • MERGE_LONGEST_BORDER - merges into polygon with longest common border

  • MERGE_MAX_AREA - merges into polygon with maximum area

  • MERGE_MIN_AREA - merges into polygon with minimum area

  • MERGE_MIN_INDEX - merges into polygon with smallest input index (defined by order of input polygons)

The result is a clean polygonal coverage that will pass validation by ST_CoverageInvalidEdges and can be input to coverage processing functions.

[참고]

To aid in determining a maximum gap width, gaps can be computed by cleaning with gapMaximumWidth = > 0 and using ST_CoverageUnion to union the result coverage. Holes in the union correspond to gaps in the original dataset. Gap widths can be measured by extracting the holes as polygons and running ST_MaximumInscribedCircle on them; the gap width is twice the computed radius.

Availability: 3.6.0 - requires GEOS >= 3.14.0

예시

Clean a coverage containing overlaps and narrow gaps, and compare the cleaned polygons with the original invalid edges.

Code
WITH coverage(id, geom) AS (VALUES
  (1, 'POLYGON ((10 190,30 160,27 134.5,40 110,122 47,120 10,10 10,10 190))'::geometry),
  (2, 'POLYGON ((150 190,10 190,30 160,50 140,40 110,50 80,130 70,135 111,140 130,140 160,150 190))'::geometry),
  (3, 'POLYGON ((140 190,190 190,190 80,140 80,140 190))'::geometry),
  (4, 'POLYGON ((190 10,120 10,97 77,160 90,170 70,190 80,190 10))'::geometry)
), processed AS (
  SELECT id,
         ST_CoverageClean(geom, 1) OVER () AS cleaned,
         ST_CoverageInvalidEdges(geom) OVER () AS invalid_edges
  FROM coverage
)
SELECT ST_Collect(cleaned ORDER BY id) AS cleaned,
       ST_Collect(invalid_edges ORDER BY id) AS invalid_edges
FROM processed;
래스터 출력
MULTIPOLYGON(((10 10,10 190,30 160,27 134.5,40 110,84.7 75.7,102 62.3,120 10,10 10)),((140 190,140 160,140 130,135 111,131.7 84.2,97 77,98 74,84.7 75.7,40 110,50 140,30 160,10 190,140 190)),((190 190,190 80,165 80,140 80,140 85.9,140 130,140 160,140 190,150 190,190 190)),((190 10,120 10,102 62.3,98 74,97 77,131.7 84.2,140 85.9,140 80,165 80,170 70,190 80,190 10))) | MULTILINESTRING((40 110,122 47,120 10),(40 110,50 80,130 70,135 111,140 130,140 160,150 190,10 190),(190 80,140 80,140 190,190 190),(120 10,97 77,160 90,170 70))
Figure
Geometry figure for visual-st-coverageclean-01

제목

ST_CoverageSimplify — Window function that simplifies the edges of a polygonal coverage.

요약

geometry ST_CoverageSimplify(geometry winset geom, float8 tolerance, boolean simplifyBoundary = true);

설명

A window function which simplifies the edges of polygons in a polygonal coverage. The simplification preserves the coverage topology. This means the simplified output polygons are consistent along shared edges, and still form a valid coverage.

The simplification uses a variant of the Visvalingam–Whyatt algorithm. The tolerance parameter has units of distance, and is roughly equal to the square root of triangular areas to be simplified.

To simplify only the "internal" edges of the coverage (those that are shared by two polygons) set the simplifyBoundary parameter to false.

Use this function to simplify adjacent polygon layers when shared boundaries must remain edge-matched. For a single geometry where only self-intersection and ring validity matter, see ST_SimplifyPreserveTopology.

[참고]

If the input is not a valid coverage there may be unexpected artifacts in the output (such as boundary intersections, or separated boundaries which appeared to be shared). Use ST_CoverageInvalidEdges to determine if a coverage is valid.

Availability: 3.4.0

Requires GEOS >= 3.12.0

예시

Simplify a polygonal coverage while preserving shared boundaries.

Code
WITH coverage(id, geom) AS (VALUES
  (1, 'POLYGON ((160 150,110 130,90 100,90 70,60 60,50 10,30 30,40 50,25 40,10 60,30 100,30 120,20 170,60 180,90 190,130 180,130 160,160 150),(40 160,50 140,66 125,60 100,80 140,90 170,60 160,40 160))'::geometry),
  (2, 'POLYGON ((40 160,60 160,90 170,80 140,60 100,66 125,50 140,40 160))'::geometry),
  (3, 'POLYGON ((110 130,160 50,140 50,120 33,90 30,50 10,60 60,90 70,90 100,110 130))'::geometry),
  (4, 'POLYGON ((160 150,150 120,160 90,160 50,110 130,160 150))'::geometry)
)
SELECT id, ST_CoverageSimplify(geom, 30) OVER ()
  FROM coverage;
래스터 출력
id |               st_astext
----+---------------------------------------
  1 | POLYGON ((160 150, 110 130, 50 10, 10 60, 20 170, 90 190, 160 150), (40 160, 66 125, 90 170, 40 160))
  2 | POLYGON ((40 160, 66 125, 90 170, 40 160))
  3 | POLYGON ((110 130, 160 50, 50 10, 110 130))
  4 | POLYGON ((160 150, 160 50, 110 130, 160 150))
Figure
Geometry figure for visual-st-coveragesimplify-01

제목

ST_CoverageEdges — Computes the unique edges of a polygonal coverage.

요약

geometry ST_CoverageEdges(geometry geom, integer edgetype = 0);

geometry ST_CoverageEdges(geometry[] geoms, integer edgetype = 0);

설명

Returns a MultiLineString representing the unique edges of a polygonal coverage. A polygonal coverage is a set of non-overlapping polygons where adjacent polygons have matching vertices along shared edges.

The edgetype parameter can be used to select which edges are returned:

  • 0 (ALL) - all unique edges (default)

  • 1 (EXTERIOR) - only exterior edges (non-shared)

  • 2 (INTERIOR) - only interior edges (shared)

Availability: 3.7.0

Requires GEOS >= 3.15.0

예시

This example returns all unique edges of a coverage.

Code
WITH coverage(geom) AS (
  VALUES (
    'GEOMETRYCOLLECTION(
      POLYGON((0 0,10 0,10 10,0 10,0 0)),
      POLYGON((10 0,20 0,20 10,10 10,10 0))
    )'::geometry
  )
)
SELECT geom AS input_coverage,
       ST_CoverageEdges(geom) AS all_edges
FROM coverage;
래스터 출력
-[ RECORD 1 ]--+----------------------------------------------------------------------------------------------
input_coverage | GEOMETRYCOLLECTION(POLYGON((0 0,10 0,10 10,0 10,0 0)),POLYGON((10 0,20 0,20 10,10 10,10 0)))
all_edges      | MULTILINESTRING((10 0,10 10),(10 10,0 10,0 0,10 0),(10 0,20 0,20 10,10 10))

This example returns only the interior shared edges of a coverage.

Code
WITH coverage(geom) AS (
  VALUES (
    'GEOMETRYCOLLECTION(
      POLYGON((0 0,10 0,10 10,0 10,0 0)),
      POLYGON((10 0,20 0,20 10,10 10,10 0))
    )'::geometry
  )
)
SELECT geom AS input_coverage,
       ST_CoverageEdges(geom, 2) AS shared_edges
FROM coverage;
래스터 출력
-[ RECORD 1 ]--+----------------------------------------------------------------------------------------------
input_coverage | GEOMETRYCOLLECTION(POLYGON((0 0,10 0,10 10,0 10,0 0)),POLYGON((10 0,20 0,20 10,10 10,10 0)))
shared_edges   | MULTILINESTRING((10 0,10 10))

제목

ST_CoverageUnion — Computes the union of a set of polygons forming a coverage by removing shared edges.

요약

geometry ST_CoverageUnion(geometry set geom);

설명

An aggregate function which unions a set of polygons forming a polygonal coverage. The result is a polygonal geometry covering the same area as the coverage. This function produces the same result as ST_Union, but uses the coverage structure to compute the union much faster.

[참고]

If the input is not a valid coverage there may be unexpected artifacts in the output (such as unmerged or overlapping polygons). Use ST_CoverageInvalidEdges to determine if a coverage is valid.

Availability: 3.4.0 - requires GEOS >= 3.8.0

예시

Union a polygonal coverage.

Code
WITH coverage(id, geom) AS (VALUES
  (1, 'POLYGON ((10 10,10 150,80 190,110 150,90 110,40 110,50 60,10 10))'::geometry),
  (2, 'POLYGON ((120 10,10 10,50 60,100 70,120 10))'::geometry),
  (3, 'POLYGON ((140 80,120 10,100 70,40 110,90 110,110 150,140 80))'::geometry),
  (4, 'POLYGON ((140 190,120 170,140 130,160 150,140 190))'::geometry),
  (5, 'POLYGON ((180 160,170 140,140 130,160 150,140 190,180 160))'::geometry)
)
SELECT ST_CoverageUnion(geom) AS wkt
  FROM coverage;
래스터 출력
MULTIPOLYGON(((10 150,80 190,110 150,140 80,120 10,10 10,10 150),(50 60,100 70,40 110,50 60)),((120 170,140 190,180 160,170 140,140 130,120 170)))
Figure
Geometry figure for visual-st-coverageunion-01

7.16. Affine Transformations

초록

These functions change the position and shape of geometries using affine transformations.

  • ST_Affine — Apply a 3D affine transformation to a geometry.
  • ST_Rotate — Rotates a geometry about an origin point.
  • ST_RotateX — Rotates a geometry about the X axis.
  • ST_RotateY — Rotates a geometry about the Y axis.
  • ST_RotateZ — Rotates a geometry about the Z axis.
  • ST_Scale — Scales a geometry by given factors.
  • ST_Translate — Translates a geometry by given offsets.
  • ST_TransScale — Translates and scales a geometry by given offsets and factors.

제목

ST_Affine — Apply a 3D affine transformation to a geometry.

요약

geometry ST_Affine(geometry geomA, float a, float b, float c, float d, float e, float f, float g, float h, float i, float xoff, float yoff, float zoff);

geometry ST_Affine(geometry geomA, float a, float b, float d, float e, float xoff, float yoff);

설명

Applies a 3D affine transformation to the geometry to do things like translate, rotate, scale in one step.

Version 1: The call

Code
ST_Affine(geom, a, b, c, d, e, f, g, h, i, xoff, yoff, zoff) 

represents the transformation matrix

Code
/ a  b  c  xoff \
| d  e  f  yoff |
| g  h  i  zoff |
\ 0  0  0     1 /

and the vertices are transformed as follows:

Code
x' = a*x + b*y + c*z + xoff
y' = d*x + e*y + f*z + yoff
z' = g*x + h*y + i*z + zoff

All of the translate / scale functions below are expressed via such an affine transformation.

Version 2: Applies a 2d affine transformation to the geometry. The call

Code
ST_Affine(geom, a, b, d, e, xoff, yoff)

represents the transformation matrix

Code
/  a  b  0  xoff  \       /  a  b  xoff  \
|  d  e  0  yoff  | rsp.  |  d  e  yoff  |
|  0  0  1     0  |       \  0  0     1  /
\  0  0  0     1  /

and the vertices are transformed as follows:

Code
x' = a*x + b*y + xoff
y' = d*x + e*y + yoff
z' = z 

This method is a subcase of the 3D method above.

개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다.

Availability: 1.1.2. Name changed from Affine to ST_Affine in 1.2.2

[참고]

1.3.4 미만 버전에서 이 함수에 만곡 도형(curve)을 담고 있는 도형을 입력하면 충돌이 일어났습니다. 1.3.4 버전부터 이 버그가 해결됐습니다.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

예시

Rotate a 3D line 180 degrees about the z axis. Note this is long-hand for doing ST_Rotate();

Code
SELECT ST_Affine(geom, cos(pi()), -sin(pi()), 0, sin(pi()), cos(pi()), 0, 0, 0, 1, 0, 0, 0) As using_affine,
    ST_Rotate(geom, pi()) As using_rotate
   FROM (SELECT 'LINESTRING(1 2 3,1 4 3)'::geometry As geom) As foo;
래스터 출력
using_affine         |        using_rotate
-----------------------------+-----------------------------
 LINESTRING(-1 -2 3,-1 -4 3) | LINESTRING(-1 -2 3,-1 -4 3)
(1 row)
Figure
Geometry figure for visual-st-affine-01

Rotate a 3D line 180 degrees in both the x and z axis.

Code
SELECT ST_Affine(geom, cos(pi()), -sin(pi()), 0, sin(pi()), cos(pi()), -sin(pi()), 0, sin(pi()), cos(pi()), 0, 0, 0)
    FROM (SELECT 'LINESTRING(1 2 3,1 4 3)'::geometry As geom) As foo;
래스터 출력
LINESTRING(-1 -2 -3,-1 -4 -3)
Figure
Geometry figure for visual-st-affine-02

제목

ST_Rotate — Rotates a geometry about an origin point.

요약

geometry ST_Rotate(geometry geomA, float rotRadians);

geometry ST_Rotate(geometry geomA, float rotRadians, float x0, float y0);

geometry ST_Rotate(geometry geomA, float rotRadians, geometry pointOrigin);

설명

Rotates geometry rotRadians counter-clockwise about the origin point. The rotation origin can be specified either as a POINT geometry, or as x and y coordinates. If the origin is not specified, the geometry is rotated about POINT(0 0).

개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다.

Enhanced: 2.0.0 additional parameters for specifying the origin of rotation were added.

Availability: 1.1.2. Name changed from Rotate to ST_Rotate in 1.2.2

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

This example rotates a geometry by 180 degrees.

Code
SELECT ST_Rotate('LINESTRING (50 160,50 50,100 50)'::geometry, pi());
래스터 출력
LINESTRING(-50 -160,-50 -50,-100 -50)
Figure
Geometry figure for visual-st-rotate-01

This example rotates a geometry 30 degrees counter-clockwise around x=50, y=160.

Code
SELECT ST_Rotate('LINESTRING (50 160,50 50,100 50)'::geometry, pi()/6, 50, 160);
래스터 출력
LINESTRING(50 160,105 64.737206,148.30127 89.737206)
Figure
Geometry figure for visual-st-rotate-02

This example rotates a geometry 60 degrees clockwise around its centroid.

Code
SELECT ST_Rotate(geom, -pi()/3, ST_Centroid(geom))
FROM (SELECT 'LINESTRING (50 160,50 50,100 50)'::geometry AS geom) AS foo;
래스터 출력
LINESTRING(116.4225 130.6721,21.1597 75.6721,46.1597 32.3708)
Figure
Geometry figure for visual-st-rotate-03

제목

ST_RotateX — Rotates a geometry about the X axis.

요약

geometry ST_RotateX(geometry geomA, float rotRadians);

설명

Rotates a geometry geomA - rotRadians about the X axis.

[참고]

ST_RotateX(geomA, rotRadians) is short-hand for ST_Affine(geomA, 1, 0, 0, 0, cos(rotRadians), -sin(rotRadians), 0, sin(rotRadians), cos(rotRadians), 0, 0, 0).

개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다.

Availability: 1.1.2. Name changed from RotateX to ST_RotateX in 1.2.2

This function supports Polyhedral surfaces.

This function supports 3d and will not drop the z-index.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

This example rotates a line 90 degrees around the X axis.

Code
SELECT ST_RotateX('LINESTRING(1 2 3,1 1 1)', pi()/2);
래스터 출력
LINESTRING(1 -3 2,1 -1 1)
Figure
Geometry figure for visual-st-rotatex-01

제목

ST_RotateY — Rotates a geometry about the Y axis.

요약

geometry ST_RotateY(geometry geomA, float rotRadians);

설명

Rotates a geometry geomA - rotRadians about the y axis.

[참고]

ST_RotateY(geomA, rotRadians) is short-hand for ST_Affine(geomA, cos(rotRadians), 0, sin(rotRadians), 0, 1, 0, -sin(rotRadians), 0, cos(rotRadians), 0, 0, 0).

Availability: 1.1.2. Name changed from RotateY to ST_RotateY in 1.2.2

개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다.

This function supports Polyhedral surfaces.

This function supports 3d and will not drop the z-index.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

This example rotates a line 90 degrees around the Y axis.

Code
SELECT ST_RotateY('LINESTRING(1 2 3,1 1 1)', pi()/2);
래스터 출력
LINESTRING(3 2 -1,1 1 -1)
Figure
Geometry figure for visual-st-rotatey-01

제목

ST_RotateZ — Rotates a geometry about the Z axis.

요약

geometry ST_RotateZ(geometry geomA, float rotRadians);

설명

Rotates a geometry geomA - rotRadians about the Z axis.

[참고]

This is a synonym for ST_Rotate

[참고]

ST_RotateZ(geomA, rotRadians) is short-hand for SELECT ST_Affine(geomA, cos(rotRadians), -sin(rotRadians), 0, sin(rotRadians), cos(rotRadians), 0, 0, 0, 1, 0, 0, 0).

개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다.

Availability: 1.1.2. Name changed from RotateZ to ST_RotateZ in 1.2.2

[참고]

1.3.4 미만 버전에서 이 함수에 만곡 도형(curve)을 담고 있는 도형을 입력하면 충돌이 일어났습니다. 1.3.4 버전부터 이 버그가 해결됐습니다.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

This example rotates a line 90 degrees around the Z axis.

Code
SELECT ST_RotateZ('LINESTRING(1 2 3,1 1 1)', pi()/2);
래스터 출력
LINESTRING(-2 1 3,-1 1 1)
Figure
Geometry figure for visual-st-rotatez-01

This example rotates a curved circle around the Z axis.

Code
SELECT ST_RotateZ(geom, pi()/2)
FROM (SELECT ST_LineToCurve(ST_Buffer('POINT(234 567)'::geometry, 3)) As geom) As foo;
래스터 출력
CURVEPOLYGON(CIRCULARSTRING(-567 237.00000000000003,-567 231.00000000000003,-567 237.00000000000003))
Figure
Geometry figure for visual-st-rotatez-02

제목

ST_Scale — Scales a geometry by given factors.

요약

geometry ST_Scale(geometry geomA, float XFactor, float YFactor, float ZFactor);

geometry ST_Scale(geometry geomA, float XFactor, float YFactor);

geometry ST_Scale(geometry geom, geometry factor);

geometry ST_Scale(geometry geom, geometry factor, geometry origin);

설명

Scales the geometry to a new size by multiplying the ordinates with the corresponding factor parameters.

The version taking a geometry as the factor parameter allows passing a 2d, 3dm, 3dz or 4d point to set scaling factor for all supported dimensions. Missing dimensions in the factor point are equivalent to no scaling the corresponding dimension.

The three-geometry variant allows a "false origin" for the scaling to be passed in. This allows "scaling in place", for example using the centroid of the geometry as the false origin. Without a false origin, scaling takes place relative to the actual origin, so all coordinates are just multiplied by the scale factor.

[참고]

1.3.4 미만 버전에서 이 함수에 만곡 도형(curve)을 담고 있는 도형을 입력하면 충돌이 일어났습니다. 1.3.4 버전부터 이 버그가 해결됐습니다.

Availability: 1.1.0.

개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다.

Enhanced: 2.2.0 support for scaling all dimension (factor parameter) was introduced.

Enhanced: 2.5.0 support for scaling relative to a local origin (origin parameter) was introduced.

This function supports Polyhedral surfaces.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

This function supports M coordinates.

예시

This example scales X, Y, and Z values.

Code
SELECT ST_Scale('LINESTRING(1 2 3,1 1 1)', 0.5, 0.75, 0.8);
래스터 출력
LINESTRING(0.5 1.5 2.4,0.5 0.75 0.8)
Figure
Geometry figure for visual-st-scale-01

This example scales X and Y values.

Code
SELECT ST_Scale('LINESTRING(1 2 3,1 1 1)', 0.5, 0.75);
래스터 출력
LINESTRING(0.5 1.5 3,0.5 0.75 1)
Figure
Geometry figure for visual-st-scale-02

This example scales X, Y, Z, and M values.

Code
SELECT ST_Scale('LINESTRING(1 2 3 4,1 1 1 1)',
    ST_MakePoint(0.5, 0.75, 2, -1));
래스터 출력
LINESTRING(0.5 1.5 6 -4,0.5 0.75 2 -1)
Figure
Geometry figure for visual-st-scale-03

This example scales X and Y values using a false origin.

Code
SELECT ST_Scale('LINESTRING(1 1,2 2)', 'POINT(2 2)', 'POINT(1 1)'::geometry);
래스터 출력
LINESTRING(1 1,3 3)
Figure
Geometry figure for visual-st-scale-04

제목

ST_Translate — Translates a geometry by given offsets.

요약

geometry ST_Translate(geometry g1, float deltax, float deltay);

geometry ST_Translate(geometry g1, float deltax, float deltay, float deltaz);

설명

Returns a new geometry whose coordinates are translated delta x,delta y,delta z units. Units are based on the units defined in spatial reference (SRID) for this geometry. M coordinates are preserved.

[참고]

1.3.4 미만 버전에서 이 함수에 만곡 도형(curve)을 담고 있는 도형을 입력하면 충돌이 일어났습니다. 1.3.4 버전부터 이 버그가 해결됐습니다.

1.2.2 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

This function supports M coordinates.

예시

Move a point 1 degree longitude

Code
SELECT ST_Translate(ST_GeomFromText('POINT(-71.01 42.37)', 4326), 1, 0) AS wgs_transgeomtxt;
래스터 출력
POINT(-70.01 42.37)

Move a linestring 1 degree longitude and 1/2 degree latitude

Code
SELECT ST_Translate(ST_GeomFromText('LINESTRING(-71.01 42.37,-71.11 42.38)', 4326), 1, 0.5) AS wgs_transgeomtxt;
래스터 출력
LINESTRING(-70.01 42.87,-70.11 42.88)
Figure
Geometry figure for visual-st-translate-02

Move a 3d point

Code
SELECT ST_Translate(CAST('POINT(0 0 0)' AS geometry), 5, 12, 3);
래스터 출력
POINT(5 12 3)

Move points with a measure coordinate

Code
SELECT ST_Translate('POINTM(0 0 11)', 5, 12);
래스터 출력
POINTM(5 12 11)
Figure
Geometry figure for visual-st-translate-04
Code
SELECT ST_Translate('POINT(0 0 7 11)', 5, 12, 3);
래스터 출력
POINT(5 12 10 11)

Move a curve and a point

Code
SELECT ST_Translate(ST_Collect('CURVEPOLYGON(CIRCULARSTRING(4 3,3.12 0.878,1 0,-1.121 5.1213,6 7,8 9,4 3))', 'POINT(1 3)'), 1, 2);
래스터 출력
GEOMETRYCOLLECTION(CURVEPOLYGON(CIRCULARSTRING(5 5,4.12 2.878,2 2,-0.121 7.1213,7 9,9 11,5 5)), POINT(2 5))
Figure
Geometry figure for visual-st-translate-06

제목

ST_TransScale — Translates and scales a geometry by given offsets and factors.

요약

geometry ST_TransScale(geometry geomA, float deltaX, float deltaY, float XFactor, float YFactor);

설명

Translates the geometry using the deltaX and deltaY args, then scales it using the XFactor, YFactor args, working in 2D only.

[참고]

ST_TransScale(geomA, deltaX, deltaY, XFactor, YFactor) is short-hand for ST_Affine(geomA, XFactor, 0, 0, 0, YFactor, 0, 0, 0, 1, deltaX*XFactor, deltaY*YFactor, 0).

[참고]

1.3.4 미만 버전에서 이 함수에 만곡 도형(curve)을 담고 있는 도형을 입력하면 충돌이 일어났습니다. 1.3.4 버전부터 이 버그가 해결됐습니다.

Availability: 1.1.0.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

예시

Code
SELECT ST_TransScale('LINESTRING(1 2 3,1 1 1)', 0.5, 1, 1, 2);
래스터 출력
LINESTRING(1.5 6 3,1.5 4 1)
Figure
Geometry figure for visual-st-transscale-01

This example buffers a point to approximate a circle, converts it to a curve, translates it by 1,2, and scales it by 3,4.

Code
SELECT ST_TransScale(ST_LineToCurve(ST_Buffer('POINT(234 567)', 3)), 1, 2, 3, 4);
래스터 출력
CURVEPOLYGON(CIRCULARSTRING(714 2276,696 2276,714 2276))
Figure
Geometry figure for visual-st-transscale-02

7.17. Clustering Functions

초록

These functions implement clustering algorithms for sets of geometries.

  • ST_ClusterDBSCAN — Window function that returns a cluster id for each input geometry using the DBSCAN algorithm.
  • ST_ClusterIntersecting — Aggregate function that clusters input geometries into connected sets.
  • ST_ClusterIntersectingWin — Window function that returns a cluster id for each input geometry, clustering input geometries into connected sets.
  • ST_ClusterRelateWin — Window function that returns a cluster id for each input geometry, clustering input geometries into connected sets using the relate pattern to determine whether the geometries are connected.
  • ST_MinimumSpanningTree — Window function that returns a tree id for each input geometry, clustering input geometries into connected trees using the Minimum Spanning Tree algorithm.
  • ST_ClusterKMeans — Window function that returns a cluster id for each input geometry using the K-means algorithm.
  • ST_ClusterWithin — Aggregate function that clusters geometries by separation distance.
  • ST_ClusterWithinWin — Window function that returns a cluster id for each input geometry, clustering using separation distance.

제목

ST_ClusterDBSCAN — Window function that returns a cluster id for each input geometry using the DBSCAN algorithm.

요약

integer ST_ClusterDBSCAN(geometry winset geom, float8 eps, integer minpoints);

설명

A window function that returns a cluster number for each input geometry, using the 2D Density-based spatial clustering of applications with noise (DBSCAN) algorithm. Unlike ST_ClusterKMeans, it does not require the number of clusters to be specified, but instead uses the desired distance (eps) and density (minpoints) parameters to determine each cluster.

An input geometry is added to a cluster if it is either:

  • A "core" geometry, that is within eps distance of at least minpoints input geometries (including itself); or

  • A "border" geometry, that is within eps distance of a core geometry.

Note that border geometries may be within eps distance of core geometries in more than one cluster. Either assignment would be correct, so the border geometry will be arbitrarily assigned to one of the available clusters. In this situation it is possible for a correct cluster to be generated with fewer than minpoints geometries. To ensure deterministic assignment of border geometries (so that repeated calls to ST_ClusterDBSCAN will produce identical results) use an ORDER BY clause in the window definition. Ambiguous cluster assignments may differ from other DBSCAN implementations.

[참고]

Geometries that do not meet the criteria to join any cluster are assigned a cluster number of NULL.

2.3.0 버전부터 사용할 수 있습니다.

This method supports Circular Strings and Curves.

예시

Cluster polygons within 50 units of each other, requiring at least two polygons per cluster. The isolated polygon is reported as noise.

Code
WITH input(name, geom) AS (
  VALUES
    ('A1', ST_MakeEnvelope(0, 0, 10, 10)),
    ('A2', ST_MakeEnvelope(30, 0, 40, 10)),
    ('B1', ST_MakeEnvelope(100, 0, 110, 10)),
    ('B2', ST_MakeEnvelope(130, 0, 140, 10)),
    ('noise', ST_MakeEnvelope(250, 0, 260, 10))
), clustered AS (
  SELECT name,
         geom,
         ST_ClusterDBSCAN(geom, eps => 50, minpoints => 2)
           OVER (ORDER BY name) AS cid
  FROM input
)
SELECT COALESCE(cid::text, 'noise') AS cluster,
       string_agg(name, ',' ORDER BY name) AS members,
       ST_Collect(geom ORDER BY name) AS cluster_geom
FROM clustered
GROUP BY cid
ORDER BY cid NULLS LAST;
래스터 출력
0 | A1,A2 | MULTIPOLYGON(((0 0,0 10,10 10,10 0,0 0)),((30 0,30 10,40 10,40 0,30 0)))
1 | B1,B2 | MULTIPOLYGON(((100 0,100 10,110 10,110 0,100 0)),((130 0,130 10,140 10,140 0,130 0)))
noise | noise | MULTIPOLYGON(((250 0,250 10,260 10,260 0,250 0)))
Figure
Geometry figure for visual-st-clusterdbscan-01

A example showing combining parcels with the same cluster number into geometry collections.

Code
SELECT cid, ST_Collect(geom) AS cluster_geom, array_agg(parcel_id) AS ids_in_cluster FROM (
    SELECT parcel_id, ST_ClusterDBSCAN(geom, eps => 0.5, minpoints => 5) over () AS cid, geom
    FROM parcels) sq
GROUP BY cid;
    

제목

ST_ClusterIntersecting — Aggregate function that clusters input geometries into connected sets.

요약

geometry[] ST_ClusterIntersecting(geometry set g);

설명

An aggregate function that returns an array of GeometryCollections partitioning the input geometries into connected clusters that are disjoint. Each geometry in a cluster intersects at least one other geometry in the cluster, and does not intersect any geometry in other clusters.

2.2.0 버전부터 사용할 수 있습니다.

예시

Code
WITH testdata AS
  (SELECT unnest(
           ARRAY['LINESTRING (0 0,1 1)'::geometry,
           'LINESTRING (5 5,4 4)'::geometry,
           'LINESTRING (6 6,7 7)'::geometry,
           'LINESTRING (0 0,-1 -1)'::geometry,
           'POLYGON ((0 0,4 0,4 4,0 4,0 0))'::geometry]) AS geom)

SELECT unnest(ST_ClusterIntersecting(geom)) FROM testdata;
래스터 출력
GEOMETRYCOLLECTION(LINESTRING(0 0,1 1),LINESTRING(5 5,4 4),LINESTRING(0 0,-1 -1),POLYGON((0 0,4 0,4 4,0 4,0 0)))
GEOMETRYCOLLECTION(LINESTRING(6 6,7 7))
Figure
Geometry figure for visual-st-clusterintersecting-01

제목

ST_ClusterIntersectingWin — Window function that returns a cluster id for each input geometry, clustering input geometries into connected sets.

요약

integer ST_ClusterIntersectingWin(geometry winset geom);

설명

A window function that builds connected clusters of geometries that intersect. It is possible to traverse all geometries in a cluster without leaving the cluster. The return value is the cluster number that the geometry argument participates in, or null for null inputs.

Availability: 3.4.0

예시

Return an explicit cluster id for each input geometry. Using the conventional cid alias keeps the geometry column ready for color-by-cluster rendering.

Code
WITH testdata(id, geom) AS (
  VALUES (1, 'LINESTRING (0 0,1 1)'::geometry),
         (2, 'LINESTRING (5 5,4 4)'::geometry),
         (3, 'LINESTRING (6 6,7 7)'::geometry),
         (4, 'LINESTRING (0 0,-1 -1)'::geometry),
         (5, 'POLYGON ((0 0,4 0,4 4,0 4,0 0))'::geometry)
), clustered AS (
  SELECT id,
         geom,
         ST_ClusterIntersectingWin(geom) OVER () AS cid
  FROM testdata
)
SELECT id,
       geom AS geom_wkt,
       cid
FROM clustered
ORDER BY id;
래스터 출력
id |            geom_wkt            | cid
----+--------------------------------+-----
  1 | LINESTRING(0 0,1 1)            |   0
  2 | LINESTRING(5 5,4 4)            |   0
  3 | LINESTRING(6 6,7 7)            |   1
  4 | LINESTRING(0 0,-1 -1)          |   0
  5 | POLYGON((0 0,4 0,4 4,0 4,0 0)) |   0
Figure
Geometry figure for visual-st-clusterintersectingwin-01

제목

ST_ClusterRelateWin — Window function that returns a cluster id for each input geometry, clustering input geometries into connected sets using the relate pattern to determine whether the geometries are connected.

요약

integer ST_ClusterRelateWin(geometry winset geom, text relate_matrix);

설명

A window function that builds connected clusters of geometries that intersect. Geometries are added to a cluster if they share a pairwise DE9IM relationship with another member of the cluster. With this function it is possible to build a cluster of all objects that touch at boundaries, but exclude those that merely overlap.

Availability: 3.7.0

예시

This collection of line strings would form a single cluster using ST_ClusterIntersectingWin, but using ST_ClusterRelateWin can be clustered into three groups that connect only via their end points.

Code
WITH data(id, geom) AS (
  VALUES (1, 'LINESTRING(0 0,1 1)'::geometry),
         (2, 'LINESTRING(2 2,1 1)'::geometry),
         (3, 'LINESTRING(0 1,1 0)'::geometry),
         (4, 'LINESTRING(0 1,0 4)'::geometry),
         (5, 'LINESTRING(2 2,2 4)'::geometry),
         (6, 'LINESTRING(1.5 2.5,2.5 3.5)'::geometry)
), clustered AS (
  SELECT id, geom,
         ST_ClusterRelateWin(geom, '****0****') OVER () AS cluster
  FROM data
)
SELECT cluster,
       string_agg(id::text, ',' ORDER BY id) AS members,
       ST_Collect(geom ORDER BY id) AS cluster_geom
FROM clustered
GROUP BY cluster
ORDER BY cluster;
래스터 출력
0 | 1,2,5 | MULTILINESTRING((0 0,1 1),(2 2,1 1),(2 2,2 4))
1 | 3,4 | MULTILINESTRING((0 1,1 0),(0 1,0 4))
2 | 6 | MULTILINESTRING((1.5 2.5,2.5 3.5))
Figure
Geometry figure for visual-st-clusterrelatewin-01

제목

ST_MinimumSpanningTree — Window function that returns a tree id for each input geometry, clustering input geometries into connected trees using the Minimum Spanning Tree algorithm.

요약

integer ST_MinimumSpanningTree(geometry winset geom);

설명

A window function that builds connected graphs of line strings based on the Minimum Spanning Tree (MST) of the input geometries. The return value is the cluster number that the geometry argument participates in, or zero if it is not part of the minimum tree.

The Minimum Spanning Tree connects all geometries in the window partition such that the total length of the connecting lines is minimized. If the graph is not fully connected (e.g. infinite distance between some geometries), it produces a Minimum Spanning Forest, and each connected component is assigned a unique tree ID.

Availability: 3.7.0

Requires GEOS >= 3.15.0

예시

These six edges describe a square with both diagonals. The minimum spanning tree keeps three edges and excludes the rest.

Code
WITH edges(id, geom) AS (
  VALUES
    (1, 'LINESTRING(0 0,1 0)'::geometry),
    (2, 'LINESTRING(0 0,0 1)'::geometry),
    (3, 'LINESTRING(1 1,0 1)'::geometry),
    (4, 'LINESTRING(1 1,1 0)'::geometry),
    (5, 'LINESTRING(0 0,1 1)'::geometry),
    (6, 'LINESTRING(1 0,0 1)'::geometry)
), marked AS (
  SELECT id,
         geom,
         ST_MinimumSpanningTree(geom) OVER (ORDER BY id) AS tree_id
  FROM edges
)
SELECT string_agg(id::text, ',' ORDER BY id)
         FILTER (WHERE tree_id > 0) AS tree_edge_ids,
       ST_Collect(geom ORDER BY id)
         FILTER (WHERE tree_id > 0) AS tree_edges,
       string_agg(id::text, ',' ORDER BY id)
         FILTER (WHERE tree_id = 0) AS excluded_edge_ids,
       ST_Collect(geom ORDER BY id)
         FILTER (WHERE tree_id = 0) AS excluded_edges
FROM marked;
래스터 출력
-[ RECORD 1 ]-----
tree_edge_ids     | 1,2,3
tree_edges        | MULTILINESTRING((0 0,1 0),(0 0,0 1),(1 1,0 1))
excluded_edge_ids | 4,5,6
excluded_edges    | MULTILINESTRING((1 1,1 0),(0 0,1 1),(1 0,0 1))

제목

ST_ClusterKMeans — Window function that returns a cluster id for each input geometry using the K-means algorithm.

요약

integer ST_ClusterKMeans( geometry winset geom , integer k , float8 max_radius );

설명

Returns K-means cluster number for each input geometry. The distance used for clustering is the distance between the centroids for 2D geometries, and distance between bounding box centers for 3D geometries. For POINT inputs, M coordinate will be treated as weight of input and has to be larger than 0.

max_radius, if set, will cause ST_ClusterKMeans to generate more clusters than k ensuring that no cluster in output has radius larger than max_radius. This is useful in reachability analysis.

Enhanced: 3.2.0 Support for max_radius

Enhanced: 3.1.0 Support for 3D geometries and weights

2.3.0 버전부터 사용할 수 있습니다.

예시

Define the parcel geometries once in a CTE and reuse them across the executable examples.

Parcels color-coded by cluster number (cid).

Code
WITH parcels(parcel_id, geom) AS (
  VALUES
    ('A1', ST_MakeEnvelope(0, 0, 10, 10)),
    ('A2', ST_MakeEnvelope(10, 0, 20, 10)),
    ('B1', ST_MakeEnvelope(100, 0, 110, 10)),
    ('B2', ST_MakeEnvelope(110, 0, 120, 10)),
    ('C1', ST_MakeEnvelope(200, 0, 210, 10)),
    ('C2', ST_MakeEnvelope(210, 0, 220, 10))
), clustered AS (
  SELECT parcel_id,
         geom,
         ST_ClusterKMeans(geom, 3) OVER (ORDER BY parcel_id) AS cid
  FROM parcels
)
SELECT cid,
       string_agg(parcel_id, ',' ORDER BY parcel_id) AS parcels,
       ST_Union(geom) AS cluster_geom
FROM clustered
GROUP BY cid
ORDER BY cid;
래스터 출력
0 | C1,C2 | POLYGON((200 10,210 10,220 10,220 0,210 0,200 0,200 10))
1 | A1,A2 | POLYGON((0 10,10 10,20 10,20 0,10 0,0 0,0 10))
2 | B1,B2 | POLYGON((100 10,110 10,120 10,120 0,110 0,100 0,100 10))
Figure
Geometry figure for visual-st-clusterkmeans-01

Partitioning parcel clusters by type:

Code
WITH parcel_geoms AS (
  SELECT geom
  FROM ST_Subdivide(
    ST_Buffer('SRID=3857;LINESTRING(40 100,98 100,100 150,60 90)'::geometry,
              40, 'endcap=square'),
    12) AS geom
), parcels AS (
  SELECT lpad(row_number() OVER (ORDER BY ST_YMin(geom), ST_XMin(geom))::text, 3, '0') AS parcel_id,
         geom,
         ('{residential,commercial}'::text[])[1 + mod(row_number() OVER (ORDER BY ST_YMin(geom), ST_XMin(geom)), 2)] AS type
  FROM parcel_geoms
)
SELECT ST_ClusterKMeans(geom, 3) over (PARTITION BY type) AS cid,
       parcel_id,
       type,
       ST_SnapToGrid(geom, 1) AS parcel_geom
FROM parcels
ORDER BY type, parcel_id;
래스터 출력
cid | parcel_id |    type     | parcel_geom
-----+-----------+-------------+--------------------------------------------------------------
   0 | 001       | commercial  | POLYGON((33 60,0 60,0 98,71 98,71 35,33 60))
   2 | 003       | commercial  | POLYGON((106 98,138 98,137 91,134 84,131 77,126 71,120 66,113 63,106 61,106 98))
   2 | 005       | commercial  | POLYGON((140 148,138 98,72 98,72 148,140 148))
   1 | 007       | commercial  | POLYGON((109 189,116 187,123 183,129 178,134 171,137 164,139 156,140 148,109 148,109 189))
   0 | 002       | residential | POLYGON((71 98,106 98,106 61,98 60,88 60,71 35,71 98))
   2 | 004       | residential | POLYGON((0 98,0 140,45 140,67 172,72 178,72 98,0 98))
   1 | 006       | residential | POLYGON((72 178,78 183,85 187,93 189,101 190,109 189,109 148,72 148,72 178))
Figure
Geometry figure for visual-st-clusterkmeans-02

Example: Clustering a preaggregated planetary-scale data population dataset using 3D clustering and weighting. Identify at least 20 regions based on Kontur Population Data that do not span more than 3000 km from their center:

Code
CREATE TABLE kontur_population_3000km_clusters AS
SELECT
    geom,
    ST_ClusterKMeans(
        ST_Force4D(
            ST_Transform(ST_Force3D(geom), 4978),
            mvalue => population
        ),
        20,
        max_radius => 3000000
    ) OVER () AS cid
FROM kontur_population;

The clustering produces 46 regions. Clusters are centered at well-populated regions such as New York and Moscow. Greenland forms one cluster, several island clusters span the antimeridian, and cluster edges follow the Earth's curvature.

Kontur population clustered with 3000 km maximum radius.

Cluster weighted city populations on the Earth in geocentric coordinates. The maximum radius is specified in meters, while the returned geometries stay in WGS 84 for display.

Code
WITH population(place, population, geom) AS (
  VALUES
    ('Boston', 5.0, ST_SetSRID(ST_Point(-71.06, 42.36), 4326)),
    ('New York', 20.0, ST_SetSRID(ST_Point(-74.01, 40.71), 4326)),
    ('London', 15.0, ST_SetSRID(ST_Point(-0.13, 51.51), 4326)),
    ('Paris', 11.0, ST_SetSRID(ST_Point(2.35, 48.86), 4326)),
    ('Osaka', 19.0, ST_SetSRID(ST_Point(135.50, 34.69), 4326)),
    ('Tokyo', 37.0, ST_SetSRID(ST_Point(139.69, 35.68), 4326)),
    ('Melbourne', 5.0, ST_SetSRID(ST_Point(144.96, -37.81), 4326)),
    ('Sydney', 5.0, ST_SetSRID(ST_Point(151.21, -33.87), 4326))
), clustered AS (
  SELECT place,
         geom,
         ST_ClusterKMeans(
           ST_Force4D(
             ST_Transform(ST_Force3D(geom), 4978),
             mvalue => population
           ),
           4,
           max_radius => 3000000
         ) OVER (ORDER BY place) AS cid
  FROM population
)
SELECT cid,
       string_agg(place, ', ' ORDER BY place) AS places,
       ST_Collect(geom ORDER BY place) AS cluster_geom
FROM clustered
GROUP BY cid
ORDER BY cid;
래스터 출력
0 | Melbourne, Sydney | MULTIPOINT((144.96 -37.81),(151.21 -33.87))
1 | Boston, New York | MULTIPOINT((-71.06 42.36),(-74.01 40.71))
2 | Osaka, Tokyo | MULTIPOINT((135.5 34.69),(139.69 35.68))
3 | London, Paris | MULTIPOINT((-0.13 51.51),(2.35 48.86))
Figure
Geometry figure for visual-st-clusterkmeans-03

제목

ST_ClusterWithin — Aggregate function that clusters geometries by separation distance.

요약

geometry[] ST_ClusterWithin(geometry set g, float8 distance);

설명

An aggregate function that returns an array of GeometryCollections, where each collection is a cluster containing some input geometries. Clustering partitions the input geometries into sets in which each geometry is within the specified distance of at least one other geometry in the same cluster. Distances are Cartesian distances in the units of the SRID.

ST_ClusterWithin is equivalent to running ST_ClusterDBSCAN with minpoints => 0.

2.2.0 버전부터 사용할 수 있습니다.

This method supports Circular Strings and Curves.

예시

Code
WITH testdata AS
  (SELECT unnest(ARRAY['LINESTRING (0 0,1 1)'::geometry,
               'LINESTRING (5 5,4 4)'::geometry,
               'LINESTRING (6 6,7 7)'::geometry,
               'LINESTRING (0 0,-1 -1)'::geometry,
               'POLYGON ((0 0,4 0,4 4,0 4,0 0))'::geometry]) AS geom)

SELECT unnest(ST_ClusterWithin(geom, 1.4)) FROM testdata;
래스터 출력
GEOMETRYCOLLECTION(LINESTRING(0 0,1 1),LINESTRING(5 5,4 4),LINESTRING(0 0,-1 -1),POLYGON((0 0,4 0,4 4,0 4,0 0)))
GEOMETRYCOLLECTION(LINESTRING(6 6,7 7))
Figure
Geometry figure for visual-st-clusterwithin-01

제목

ST_ClusterWithinWin — Window function that returns a cluster id for each input geometry, clustering using separation distance.

요약

integer ST_ClusterWithinWin(geometry winset geom, float8 distance);

설명

A window function that returns a cluster number for each input geometry. Clustering partitions the geometries into sets in which each geometry is within the specified distance of at least one other geometry in the same cluster. Distances are Cartesian distances in the units of the SRID.

ST_ClusterWithinWin is equivalent to running ST_ClusterDBSCAN with minpoints => 0.

Availability: 3.4.0

This method supports Circular Strings and Curves.

예시

Code
WITH testdata AS (
  SELECT id, geom::geometry FROM (
  VALUES  (1, 'LINESTRING (0 0,1 1)'),
          (2, 'LINESTRING (5 5,4 4)'),
          (3, 'LINESTRING (6 6,7 7)'),
          (4, 'LINESTRING (0 0,-1 -1)'),
          (5, 'POLYGON ((0 0,4 0,4 4,0 4,0 0))')) AS t(id, geom)
)
SELECT id,
  geom,
  ST_ClusterWithinWin(geom, 1.4) OVER () AS cluster
FROM testdata;
래스터 출력
id |           st_astext            | cluster
----+--------------------------------+---------
  1 | LINESTRING(0 0,1 1)            |       0
  2 | LINESTRING(5 5,4 4)            |       0
  3 | LINESTRING(6 6,7 7)            |       1
  4 | LINESTRING(0 0,-1 -1)          |       0
  5 | POLYGON((0 0,4 0,4 4,0 4,0 0)) |       0
Figure
Geometry figure for visual-st-clusterwithinwin-01

7.18. Bounding Box Functions

초록

These functions produce or operate on bounding boxes. They can also provide and accept geometry values, by using automatic or explicit casts.

See also 13.7절. “PostGIS Box Functions”.

  • Box2D — Returns a BOX2D representing the 2D extent of a geometry.
  • Box3D — Returns a BOX3D representing the 3D extent of a geometry.
  • ST_EstimatedExtent — Returns the estimated extent of a spatial table.
  • ST_Expand — Returns a bounding box expanded from another bounding box or a geometry.
  • ST_Extent — Aggregate function that returns the bounding box of geometries.
  • ST_3DExtent — Aggregate function that returns the 3D bounding box of geometries.
  • ST_MakeBox2D — Creates a BOX2D defined by two 2D point geometries.
  • ST_3DMakeBox — Creates a BOX3D defined by two 3D point geometries.
  • ST_XMax — Returns the X maxima of a 2D or 3D bounding box or a geometry.
  • ST_XMin — Returns the X minima of a 2D or 3D bounding box or a geometry.
  • ST_YMax — Returns the Y maxima of a 2D or 3D bounding box or a geometry.
  • ST_YMin — Returns the Y minima of a 2D or 3D bounding box or a geometry.
  • ST_ZMax — Returns the Z maxima of a 2D or 3D bounding box or a geometry.
  • ST_ZMin — Returns the Z minima of a 2D or 3D bounding box or a geometry.
  • ST_XSize — Returns the X size of a 2D or 3D bounding box or a geometry.
  • ST_YSize — Returns the Y size of a 2D or 3D bounding box or a geometry.
  • ST_ZSize — Returns the Z size of a 2D or 3D bounding box or a geometry.
  • ST_MMin — Returns the M minima of a geometry.
  • ST_MMax — Returns the M maxima of a geometry.
  • ST_MSize — Returns the M size of a geometry.

제목

Box2D — Returns a BOX2D representing the 2D extent of a geometry.

요약

box2d Box2D(geometry geom);

설명

Returns a box2d representing the 2D extent of the geometry.

개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

Code
SELECT Box2D('LINESTRING(1 2,3 4,5 6)'::geometry);
래스터 출력
BOX(1 2,5 6)
Figure
Geometry figure for visual-box2d-01
Code
SELECT Box2D('CIRCULARSTRING(220268 150415,220227 150505,220227 150406)'::geometry);
래스터 출력
BOX(220186.99512189245 150406,220288.24878054656 150506.12682932706)
Figure
Geometry figure for visual-box2d-02

제목

Box3D — Returns a BOX3D representing the 3D extent of a geometry.

요약

box3d Box3D(geometry geom);

설명

Returns a box3d representing the 3D extent of the geometry.

개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

This function supports 3d and will not drop the z-index.

예시

Code
SELECT Box3D('LINESTRING(1 2 3,3 4 5,5 6 5)'::geometry);
래스터 출력
BOX3D(1 2 3,5 6 5)
Figure
Geometry figure for visual-box3d-01
Code
SELECT Box3D('CIRCULARSTRING(220268 150415 1,220227 150505 1,220227 150406 1)'::geometry);
래스터 출력
BOX3D(220186.99512189245 150406 1,220288.24878054656 150506.12682932706 1)
Figure
Geometry figure for visual-box3d-02

제목

ST_EstimatedExtent — Returns the estimated extent of a spatial table.

요약

box2d ST_EstimatedExtent(text schema_name, text table_name, text geocolumn_name, boolean parent_only);

box2d ST_EstimatedExtent(text schema_name, text table_name, text geocolumn_name);

box2d ST_EstimatedExtent(text table_name, text geocolumn_name);

설명

Returns the estimated extent of a spatial table as a box2d. The current schema is used if not specified. The estimated extent is taken from the geometry column's statistics. This is usually much faster than computing the exact extent of the table using ST_Extent or ST_3DExtent.

The default behavior is to also use statistics collected from child tables (tables with INHERITS) if available. If parent_only is set to TRUE, only statistics for the given table are used and child tables are ignored.

For PostgreSQL >= 8.0.0 statistics are gathered by VACUUM ANALYZE and the result extent will be about 95% of the actual one. For PostgreSQL < 8.0.0 statistics are gathered by running update_geometry_stats() and the result extent is exact.

[참고]

In the absence of statistics (empty table or no ANALYZE called) this function returns NULL. Prior to version 1.5.4 an exception was thrown instead.

[참고]

Escaping names for tables and/or namespaces that include special characters and quotes may require special handling. A user notes: "For schemas and tables, use identifier escaping rules to produce a double-quoted string, and afterwards remove the first and last double-quote character. For geometry column pass as is."

1.0.0 버전부터 사용할 수 있습니다.

Changed: 2.1.0. Up to 2.0.x this was called ST_Estimated_Extent.

This method supports Circular Strings and Curves.

예시

Code
SELECT ST_EstimatedExtent('ny', 'edges', 'geom');
래스터 출력
st_estimatedextent
--------------------------------------------------
 BOX(-8877653 4912316,-8010225.5 5589284)
(1 row)
Code
SELECT ST_EstimatedExtent('feature_poly', 'geom');
래스터 출력
st_estimatedextent
---------------------------------------------------------------------
 BOX(-124.659652709961 24.6830825805664,-67.7798080444336 49.0012092590332)
(1 row)

제목

ST_Expand — Returns a bounding box expanded from another bounding box or a geometry.

요약

geometry ST_Expand(geometry geom, float units_to_expand);

geometry ST_Expand(geometry geom, float dx, float dy, float dz=0, float dm=0);

box2d ST_Expand(box2d box, float units_to_expand);

box2d ST_Expand(box2d box, float dx, float dy);

box3d ST_Expand(box3d box, float units_to_expand);

box3d ST_Expand(box3d box, float dx, float dy, float dz=0);

설명

Returns a bounding box expanded from the bounding box of the input, either by specifying a single distance with which the box should be expanded on both axes, or by specifying an expansion distance for each axis. Uses double-precision. Can be used for distance queries, or to add a bounding box filter to a query to take advantage of a spatial index.

In addition to the version of ST_Expand accepting and returning a geometry, variants are provided that accept and return box2d and box3d data types.

Distances are in the units of the spatial reference system of the input.

ST_Expand is similar to ST_Buffer, except while buffering expands a geometry in all directions, ST_Expand expands the bounding box along each axis.

[참고]

Pre version 1.3, ST_Expand was used in conjunction with ST_Distance to do indexable distance queries. For example, geom && ST_Expand('POINT(10 20)', 10) AND ST_Distance(geom, 'POINT(10 20)') < 10. This has been replaced by the simpler and more efficient ST_DWithin function.

Availability: 1.5.0 behavior changed to output double precision instead of float4 coordinates.

개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다.

Enhanced: 2.3.0 support was added to expand a box by different amounts in different dimensions.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

[참고]

Examples below use US National Atlas Equal Area (SRID=2163) which is a meter projection

10-meter expanded box around bbox of a linestring.

Code
SELECT CAST(ST_Expand(ST_GeomFromText('LINESTRING(2312980 110676,2312923 110701,2312892 110714)', 2163), 10) As box2d);
래스터 출력
BOX(2312882 110666,2312990 110724)
Figure
Geometry figure for visual-st-expand-01

This example expands a 3D box by 10 meters.

Code
SELECT ST_Expand(CAST('BOX3D(778783 2951741 1,794875 2970042.61545891 10)' AS box3d), 10)
래스터 출력
BOX3D(778773 2951731 -9,794885 2970052.61545891 20)

This example renders the text representation of a 10-meter expanded box around a point geometry.

Code
SELECT ST_Expand('SRID=2163;POINT(2312980 110676)'::geometry, 10);
래스터 출력
SRID=2163;POLYGON((2312970 110666,2312970 110686,2312990 110686,2312990 110666,2312970 110666))
Figure
Geometry figure for visual-st-expand-03

제목

ST_Extent — Aggregate function that returns the bounding box of geometries.

요약

box2d ST_Extent(geometry set geomfield);

설명

An aggregate function that returns a box2d bounding box that bounds a set of geometries.

The bounding box coordinates are in the spatial reference system of the input geometries.

ST_Extent is similar in concept to Oracle Spatial/Locator's SDO_AGGR_MBR.

[참고]

ST_Extent returns boxes with only X and Y ordinates even with 3D geometries. To return XYZ ordinates use ST_3DExtent.

[참고]

The returned box3d value does not include a SRID. Use ST_SetSRID to convert it into a geometry with SRID metadata. The SRID is the same as the input geometries.

개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

[참고]

Examples below use Massachusetts State Plane ft (SRID=2249)

Code
SELECT ST_Extent(geom) AS bextent FROM sometable;
래스터 출력
BOX(739651.875 2908247.25,794875.8125 2970042.75)

Return extent of each geometry category.

Code
SELECT ST_Extent(geom) as bextent
FROM sometable
GROUP BY category ORDER BY category;
래스터 출력
bextent                       |         name
----------------------------------------------------+----------------
 BOX(778783.5625 2951741.25,794875.8125 2970042.75) | A
 BOX(751315.8125 2919164.75,765202.6875 2935417.25) | B
 BOX(739651.875 2917394.75,756688.375 2935866)      | C

This example converts the extent back into a geometry and renders its extended text representation.

Code
SELECT ST_SetSRID(ST_Extent(geom), 2249) AS bextent FROM sometable;
래스터 출력
SRID=2249;POLYGON((739651.875 2908247.25,739651.875 2970042.75,794875.8125 2970042.75,
794875.8125 2908247.25,739651.875 2908247.25))
        

제목

ST_3DExtent — Aggregate function that returns the 3D bounding box of geometries.

요약

box3d ST_3DExtent(geometry set geomfield);

설명

An aggregate function that returns a box3d (includes Z ordinate) bounding box that bounds a set of geometries.

The bounding box coordinates are in the spatial reference system of the input geometries.

[참고]

The returned box3d value does not include a SRID. Use ST_SetSRID to convert it into a geometry with SRID metadata. The SRID is the same as the input geometries.

개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다.

Changed: 2.0.0 In prior versions this used to be called ST_Extent3D

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

Code
SELECT ST_3DExtent(foo.geom) As b3extent
FROM (SELECT ST_MakePoint(x, y, z) As geom
    FROM generate_series(1, 3) As x
        CROSS JOIN generate_series(1, 2) As y
        CROSS JOIN generate_series(0, 2) As Z) As foo;
래스터 출력
BOX3D(1 1 0,3 2 2)

This example returns the extent of several elevated CircularStrings.

Code
SELECT ST_3DExtent(foo.geom) As b3extent
FROM (SELECT ST_Translate(ST_Force3DZ(ST_LineToCurve(ST_Buffer(ST_Point(x, y), 1))), 0, 0, z) As geom
    FROM generate_series(1, 3) As x
        CROSS JOIN generate_series(1, 2) As y
        CROSS JOIN generate_series(0, 2) As Z) As foo;
래스터 출력
BOX3D(0 0 0,4 3 2)

제목

ST_MakeBox2D — Creates a BOX2D defined by two 2D point geometries.

요약

box2d ST_MakeBox2D(geometry pointLowLeft, geometry pointUpRight);

설명

Creates a box2d defined by two Point geometries. This is useful for doing range queries.

예시

Return all features that fall within or partly reside in a US National Atlas coordinate bounding box. It is assumed here that the geometries are stored with SRID=2163 (US National Atlas equal area).

Code
SELECT feature_id, feature_name, geom
FROM features
WHERE geom && ST_SetSRID(
  ST_MakeBox2D(
    ST_Point(-989502.1875, 528439.5625),
    ST_Point(-987121.375, 529933.1875)
  ),
  2163
);

제목

ST_3DMakeBox — Creates a BOX3D defined by two 3D point geometries.

요약

box3d ST_3DMakeBox(geometry point3DLowLeftBottom, geometry point3DUpRightTop);

설명

Creates a box3d defined by two 3D Point geometries.

This function supports 3D and will not drop the z-index.

Changed: 2.0.0 In prior versions this used to be called ST_MakeBox3D

예시

Code
SELECT ST_3DMakeBox(ST_MakePoint(-989502.1875, 528439.5625, 10),
    ST_MakePoint(-987121.375 , 529933.1875, 10))
래스터 출력
BOX3D(-989502.1875 528439.5625 10,-987121.375 529933.1875 10)

제목

ST_XMax — Returns the X maxima of a 2D or 3D bounding box or a geometry.

요약

float ST_XMax(box3d aGeomorBox2DorBox3D);

설명

Returns the X maxima of a 2D or 3D bounding box or a geometry.

[참고]

Although this function is only defined for box3d, it also works for box2d and geometry values due to automatic casting. However, it will not accept a geometry or box2d text representation, since those do not auto-cast.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

예시

Code
SELECT ST_XMax('BOX3D(1 2 3,4 5 6)');
래스터 출력
4
Code
SELECT ST_XMax('LINESTRING(1 3 4,5 6 7)'::geometry);
래스터 출력
5
Figure
Geometry figure for visual-st-xmax-02
Code
SELECT ST_XMax(CAST('BOX(-3 2,3 4)' AS box2d));
래스터 출력
3

Observe THIS DOES NOT WORK because it will try to auto-cast the string representation to a BOX3D.

Code
SELECT ST_XMax('LINESTRING(1 3,5 6)');
래스터 출력
ERROR: BOX3D parser - doesn't start with BOX3D(
Code
SELECT ST_XMax('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)'::geometry);
래스터 출력
220288.248780547
Figure
Geometry figure for visual-st-xmax-05

제목

ST_XMin — Returns the X minima of a 2D or 3D bounding box or a geometry.

요약

float ST_XMin(box3d aGeomorBox2DorBox3D);

설명

Returns the X minima of a 2D or 3D bounding box or a geometry.

[참고]

Although this function is only defined for box3d, it also works for box2d and geometry values due to automatic casting. However it will not accept a geometry or box2d text representation, since those do not auto-cast.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

예시

Code
SELECT ST_XMin('BOX3D(1 2 3,4 5 6)');
래스터 출력
1
Code
SELECT ST_XMin('LINESTRING(1 3 4,5 6 7)'::geometry);
래스터 출력
1
Figure
Geometry figure for visual-st-xmin-02
Code
SELECT ST_XMin(CAST('BOX(-3 2,3 4)' AS box2d));
래스터 출력
-3

Observe THIS DOES NOT WORK because it will try to auto-cast the string representation to a BOX3D.

Code
SELECT ST_XMin('LINESTRING(1 3,5 6)');
래스터 출력
ERROR: BOX3D parser - doesn't start with BOX3D(
Code
SELECT ST_XMin('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)'::geometry);
래스터 출력
220186.995121892
Figure
Geometry figure for visual-st-xmin-05

제목

ST_YMax — Returns the Y maxima of a 2D or 3D bounding box or a geometry.

요약

float ST_YMax(box3d aGeomorBox2DorBox3D);

설명

Returns the Y maxima of a 2D or 3D bounding box or a geometry.

[참고]

Although this function is only defined for box3d, it also works for box2d and geometry values due to automatic casting. However it will not accept a geometry or box2d text representation, since those do not auto-cast.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

예시

Code
SELECT ST_YMax('BOX3D(1 2 3,4 5 6)');
래스터 출력
5
Code
SELECT ST_YMax('LINESTRING(1 3 4,5 6 7)'::geometry);
래스터 출력
6
Figure
Geometry figure for visual-st-ymax-02
Code
SELECT ST_YMax(CAST('BOX(-3 2,3 4)' AS box2d));
래스터 출력
4

Observe THIS DOES NOT WORK because it will try to auto-cast the string representation to a BOX3D.

Code
SELECT ST_YMax('LINESTRING(1 3,5 6)');
래스터 출력
ERROR: BOX3D parser - doesn't start with BOX3D(
Code
SELECT ST_YMax('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)'::geometry);
래스터 출력
150506.126829327
Figure
Geometry figure for visual-st-ymax-05

제목

ST_YMin — Returns the Y minima of a 2D or 3D bounding box or a geometry.

요약

float ST_YMin(box3d aGeomorBox2DorBox3D);

설명

Returns the Y minima of a 2D or 3D bounding box or a geometry.

[참고]

Although this function is only defined for box3d, it also works for box2d and geometry values due to automatic casting. However it will not accept a geometry or box2d text representation, since those do not auto-cast.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

예시

Code
SELECT ST_YMin('BOX3D(1 2 3,4 5 6)');
래스터 출력
2
Code
SELECT ST_YMin('LINESTRING(1 3 4,5 6 7)'::geometry);
래스터 출력
3
Figure
Geometry figure for visual-st-ymin-02
Code
SELECT ST_YMin(CAST('BOX(-3 2,3 4)' AS box2d));
래스터 출력
2

Observe THIS DOES NOT WORK because it will try to auto-cast the string representation to a BOX3D.

Code
SELECT ST_YMin('LINESTRING(1 3,5 6)');
래스터 출력
ERROR: BOX3D parser - doesn't start with BOX3D(
Code
SELECT ST_YMin('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)'::geometry);
래스터 출력
150406
Figure
Geometry figure for visual-st-ymin-05

제목

ST_ZMax — Returns the Z maxima of a 2D or 3D bounding box or a geometry.

요약

float ST_ZMax(box3d aGeomorBox2DorBox3D);

설명

Returns the Z maxima of a 2D or 3D bounding box or a geometry.

[참고]

Although this function is only defined for box3d, it also works for box2d and geometry values due to automatic casting. However it will not accept a geometry or box2d text representation, since those do not auto-cast.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

예시

Code
SELECT ST_ZMax('BOX3D(1 2 3,4 5 6)');
래스터 출력
6
Code
SELECT ST_ZMax('LINESTRING(1 3 4,5 6 7)'::geometry);
래스터 출력
7
Figure
Geometry figure for visual-st-zmax-02
Code
SELECT ST_ZMax('BOX3D(-3 2 1,3 4 1)');
래스터 출력
1

Observe THIS DOES NOT WORK because it will try to auto-cast the string representation to a BOX3D.

Code
SELECT ST_ZMax('LINESTRING(1 3 4,5 6 7)');
래스터 출력
ERROR: BOX3D parser - doesn't start with BOX3D(
Code
SELECT ST_ZMax('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)'::geometry);
래스터 출력
3
Figure
Geometry figure for visual-st-zmax-05

제목

ST_ZMin — Returns the Z minima of a 2D or 3D bounding box or a geometry.

요약

float ST_ZMin(box3d aGeomorBox2DorBox3D);

설명

Returns the Z minima of a 2D or 3D bounding box or a geometry.

[참고]

Although this function is only defined for box3d, it also works for box2d and geometry values due to automatic casting. However it will not accept a geometry or box2d text representation, since those do not auto-cast.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

예시

Code
SELECT ST_ZMin('BOX3D(1 2 3,4 5 6)');
래스터 출력
3
Code
SELECT ST_ZMin('LINESTRING(1 3 4,5 6 7)'::geometry);
래스터 출력
4
Figure
Geometry figure for visual-st-zmin-02
Code
SELECT ST_ZMin('BOX3D(-3 2 1,3 4 1)');
래스터 출력
1

Observe THIS DOES NOT WORK because it will try to auto-cast the string representation to a BOX3D.

Code
SELECT ST_ZMin('LINESTRING(1 3 4,5 6 7)');
래스터 출력
ERROR: BOX3D parser - doesn't start with BOX3D(
Code
SELECT ST_ZMin('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)'::geometry);
래스터 출력
1
Figure
Geometry figure for visual-st-zmin-05

제목

ST_XSize — Returns the X size of a 2D or 3D bounding box or a geometry.

요약

float ST_XSize(box3d aGeomorBox2DorBox3D);

설명

Returns the X size of a 2D or 3D bounding box or a geometry, computed as ST_XMax(aGeomorBox2DorBox3D) - ST_XMin(aGeomorBox2DorBox3D).

[참고]

Although this function is only defined for box3d, it also works for box2d and geometry values due to automatic casting. However it will not accept a geometry or box2d text representation, since those do not auto-cast.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

Availability: 3.7.0

예시

Code
SELECT ST_XSize('BOX3D(1 2 3,4 5 6)');
래스터 출력
3
Code
SELECT ST_XSize('LINESTRING(1 3,5 6)'::geometry);
래스터 출력
4
Figure
Geometry figure for visual-st-xsize-02

제목

ST_YSize — Returns the Y size of a 2D or 3D bounding box or a geometry.

요약

float ST_YSize(box3d aGeomorBox2DorBox3D);

설명

Returns the Y size of a 2D or 3D bounding box or a geometry, computed as ST_YMax(aGeomorBox2DorBox3D) - ST_YMin(aGeomorBox2DorBox3D).

[참고]

Although this function is only defined for box3d, it also works for box2d and geometry values due to automatic casting. However it will not accept a geometry or box2d text representation, since those do not auto-cast.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

Availability: 3.7.0

예시

Code
SELECT ST_YSize('BOX3D(1 2 3,4 5 6)');
래스터 출력
3
Code
SELECT ST_YSize('LINESTRING(1 3,5 6)'::geometry);
래스터 출력
3
Figure
Geometry figure for visual-st-ysize-02

제목

ST_ZSize — Returns the Z size of a 2D or 3D bounding box or a geometry.

요약

float ST_ZSize(box3d aGeomorBox2DorBox3D);

설명

Returns the Z size of a 2D or 3D bounding box or a geometry, computed as ST_ZMax(aGeomorBox2DorBox3D) - ST_ZMin(aGeomorBox2DorBox3D).

[참고]

Although this function is only defined for box3d, it also works for box2d and geometry values due to automatic casting. However it will not accept a geometry or box2d text representation, since those do not auto-cast.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

Availability: 3.7.0

예시

Code
SELECT ST_ZSize('BOX3D(1 2 3,4 5 6)');
래스터 출력
3
Code
SELECT ST_ZSize('LINESTRING(1 3 4,5 6 7)'::geometry);
래스터 출력
3
Figure
Geometry figure for visual-st-zsize-02

제목

ST_MMin — Returns the M minima of a geometry.

요약

float ST_MMin(geometry geom);

설명

Returns the M minima of a geometry, or null if the geometry lacks M values.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

예시

Code
SELECT ST_MMin('POINT M (1 2 3)');
래스터 출력
3

제목

ST_MMax — Returns the M maxima of a geometry.

요약

float ST_MMax(geometry geom);

설명

Returns the M maxima of a geometry, or null if the geometry lacks M values.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

예시

Code
SELECT ST_MMax('POINT M (1 2 3)');
래스터 출력
3

제목

ST_MSize — Returns the M size of a geometry.

요약

float ST_MSize(geometry geom);

설명

Returns the M size of a geometry, computed as ST_MMax(geom) - ST_MMin(geom), or null if the geometry lacks M values.

This function supports 3d and will not drop the z-index.

This method supports Circular Strings and Curves.

Availability: 3.7.0

예시

Code
SELECT ST_MSize('LINESTRING M (1 2 3,4 6 8)');
래스터 출력
5
Figure
Geometry figure for visual-st-msize-01

7.19. 선형 참조(Linear Referencing)

초록

These functions measure and locate events along linear features. They support the classic linear referencing workflow of expressing positions as fractions or measures along routes and of projecting those measures back into spatial coordinates.

제목

ST_LineInterpolatePoint — Returns a point interpolated along a line at a fractional location.

요약

geometry ST_LineInterpolatePoint(geometry a_linestring, float8 a_fraction);

geography ST_LineInterpolatePoint(geography a_linestring, float8 a_fraction, boolean use_spheroid = true);

설명

라인을 따라 보간된 포인트를 반환합니다. 첫 번째 인수는 라인스트링이어야 합니다. 두 번째 인수는 0과 1 사이의 Float8 데이터형으로 라인스트링의 전체 길이에서 포인트가 위치해야 하는 비율을 의미합니다.

포인트에 가장 가까운 라인의 위치를 계산하는 방법에 대해서는 ST_LineLocatePoint 를 참조하십시오.

[참고]

This function computes points in 2D and then interpolates values for Z and M, while ST_3DLineInterpolatePoint computes points in 3D and only interpolates the M value.

[참고]

1.1.1 배포판부터 이 함수는 M 및 Z값(이 있을 경우)도 보간합니다. 이전 배포판에서는 두 값을 0.0으로 고정시켰습니다.

0.8.2 버전부터 사용할 수 있습니다. 1.1.1 버전에서 Z과 M 좌표를 지원합니다.

변경 사항: 2.1.0 미만 버전, 즉 2.0.x 버전까지 이 함수의 명칭은 ST_Line_Interpolate_Point였습니다.

This function supports 3d and will not drop the z-index.

예시

This example returns the point 20 percent along a line.

Code
SELECT ST_LineInterpolatePoint(
'LINESTRING(25 50,100 125,150 190)',
0.2);
래스터 출력
POINT(51.5974135047432 76.5974135047432)
Figure
Geometry figure for visual-st-lineinterpolatepoint-01

The mid-point of a 3D line:

Code
SELECT ST_LineInterpolatePoint(
'LINESTRING(1 2 3,4 5 6,6 7 8)',
0.5);
래스터 출력
POINT(3.5 4.5 5.5)
Figure
Geometry figure for visual-st-lineinterpolatepoint-02

The closest point on a line to a point:

Code
SELECT ST_LineInterpolatePoint(
    line.geom,
    ST_LineLocatePoint(line.geom, 'POINT(4 3)'))
FROM (SELECT 'LINESTRING(1 2,4 5,6 7)'::geometry As geom) AS line;
래스터 출력
POINT(3 4)
Figure
Geometry figure for visual-st-lineinterpolatepoint-03

An interpolated point can be offset to the left or right of a line by using ST_OffsetCurve before interpolation. This is useful for locating an address point beside a street centerline.

Code
WITH street AS (
    SELECT 'LINESTRING(0 0, 10 0)'::geometry AS geom,
           100 AS from_num,
           200 AS to_num
)
SELECT
    ST_LineInterpolatePoint(
        ST_OffsetCurve(geom, -2),
        (160 - from_num)::float8 / (to_num - from_num)
    ) AS interpolated_offset_point
FROM street;
래스터 출력
interpolated_offset_point
---------------------------
 POINT(6 -2)
Figure
Geometry figure for visual-st-lineinterpolatepoint-04

제목

ST_3DLineInterpolatePoint — Returns a point interpolated along a 3D line at a fractional location.

요약

geometry ST_3DLineInterpolatePoint(geometry a_linestring, float8 a_fraction);

설명

라인을 따라 보간된 포인트를 반환합니다. 첫 번째 인수는 라인스트링이어야 합니다. 두 번째 인수는 0과 1 사이의 Float8 데이터형으로 라인스트링의 전체 길이에서 포인트가 위치해야 하는 비율을 의미합니다.

[참고]

ST_LineInterpolatePoint computes points in 2D and then interpolates the values for Z and M, while this function computes points in 3D and only interpolates the M value.

2.1.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

예시

Return point 20% along 3D line

Code
SELECT ST_3DLineInterpolatePoint(
'LINESTRING(25 50 70,100 125 90,150 190 200)',
0.20);
래스터 출력
POINT Z (59.06758929108215 84.06758929108216 79.0846904776219)
Figure
Geometry figure for visual-st-3dlineinterpolatepoint-01

제목

ST_LineInterpolatePoints — Returns points interpolated along a line at a fractional interval.

요약

geometry ST_LineInterpolatePoints(geometry a_linestring, float8 a_fraction, boolean repeat);

geography ST_LineInterpolatePoints(geography a_linestring, float8 a_fraction, boolean use_spheroid = true, boolean repeat = true);

설명

Returns one or more points interpolated along a line at a fractional interval. The first argument must be a LINESTRING. The second argument is a float8 between 0 and 1 representing the spacing between the points as a fraction of line length. If the third argument is false, at most one point will be constructed (which is equivalent to ST_LineInterpolatePoint.)

If the result has zero or one points, it is returned as a POINT. If it has two or more points, it is returned as a MULTIPOINT.

Availability: 2.5.0

This function supports 3d and will not drop the z-index.

This function supports M coordinates.

예시

This example returns points every 20 percent along a two-dimensional line.

Code
SELECT ST_LineInterpolatePoints(
'LINESTRING(25 50,100 125,150 190)',
0.20);
래스터 출력
MULTIPOINT((51.5974135047432 76.5974135047432),(78.1948270094864 103.194827009486),(104.132163186446 130.37181214238),(127.066081593223 160.18590607119),(150 190))
Figure
Geometry figure for visual-st-lineinterpolatepoints-01

제목

ST_LineLocatePoint — Returns the fractional location of the closest point on a line to a point.

요약

float8 ST_LineLocatePoint(geometry a_linestring, geometry a_point);

float8 ST_LineLocatePoint(geography a_linestring, geography a_point, boolean use_spheroid = true);

설명

입력 포인트에 가장 가까운 위치에 있는 라인스트링 상의 포인트를 나타내는 2차원 라인 전체 길이의 비율을 0에서 1 사이의 부동소수점 데이터형(float)으로 반환합니다.

반환된 위치를 이용해서 포인트(ST_LineInterpolatePoint) 또는 부분 스트링(ST_LineSubstring)을 추출할 수 있습니다.

이 함수는 주소의 개수의 근사치를 구하는 데 유용합니다.

1.1.0 버전부터 사용할 수 있습니다.

변경 사항: 2.1.0 미만 버전, 즉 2.0.x 버전까지 이 함수의 명칭은 ST_Line_Locate_Point였습니다.

예시

This example approximates the street number of a house by locating the closest point on a street line. The subquery generates sample house and street data, and ST_DWithin excludes houses that are too far from the street.

Code
SELECT house_loc As as_text_house_loc,
    startstreet_num +
        CAST( (endstreet_num - startstreet_num)
            * ST_LineLocatePoint(street_line, house_loc) As integer) As street_num
FROM
(SELECT 'LINESTRING(1 2,3 4)'::geometry As street_line,
    ST_Point(x*1.01, y*1.03) As house_loc, 10 As startstreet_num,
        20 As endstreet_num
FROM generate_series(1, 3) x CROSS JOIN generate_series(2, 4) As y)
As foo
WHERE ST_DWithin(street_line, house_loc, 0.2);
래스터 출력
as_text_house_loc | street_num
-------------------+------------
 POINT(1.01 2.06)  |         10
 POINT(2.02 3.09)  |         15
 POINT(3.03 4.12)  |         20
Figure
Geometry figure for visual-st-linelocatepoint-01

This example finds the closest point on a line to a point or other geometry.

Code
SELECT ST_LineInterpolatePoint(
    foo.the_line,
    ST_LineLocatePoint(foo.the_line, 'POINT(4 3)'::geometry))
FROM (SELECT 'LINESTRING(1 2,4 5,6 7)'::geometry As the_line) As foo;
래스터 출력
POINT(3 4)
Figure
Geometry figure for visual-st-linelocatepoint-02

This example locates the closest segment and point on a LineString.

Code
WITH data AS (
  SELECT
    'LINESTRING (0 0, 10 10, 20 20, 30 30)'::geometry AS line,
    'POINT(15 15.1)'::geometry AS pt
),
segments AS (
  SELECT
    s.i,
    d.pt,
    ST_MakeLine(ST_PointN(d.line, s.i), ST_PointN(d.line, s.i + 1)) AS segment
  FROM data AS d
  CROSS JOIN LATERAL generate_series(1, ST_NumPoints(d.line) - 1) AS s(i)
)
SELECT
  i AS segment_number,
  round(ST_Distance(segment, pt)::numeric, 3) AS distance,
  ST_ClosestPoint(segment, pt) AS closest_point
FROM segments
ORDER BY ST_Distance(segment, pt)
LIMIT 1;
래스터 출력
segment_number | distance |   closest_point
----------------+----------+--------------------
              2 |    0.071 | POINT(15.05 15.05)
Figure
Geometry figure for visual-st-linelocatepoint-03

제목

ST_LineSubstring — Returns the part of a line between two fractional locations.

요약

geometry ST_LineSubstring(geometry a_linestring, float8 startfraction, float8 endfraction);

geography ST_LineSubstring(geography a_linestring, float8 startfraction, float8 endfraction);

설명

Computes the line which is the section of the input line starting and ending at the given fractional locations. The first argument must be a LINESTRING. The second and third arguments are values in the range [0, 1] representing the start and end locations. For geometry inputs, the fractions are measured in 2D line length. The Z and M values are interpolated for added endpoints if present.

'시작'과 '끝'이 동일한 값일 경우 이 함수는 ST_LineInterpolatePoint 함수와 같아집니다.

[참고]

This only works with LINESTRINGs. To use on contiguous MULTILINESTRINGs first join them with ST_LineMerge.

[참고]

1.1.1 배포판부터 이 함수는 M 및 Z값(이 있을 경우)도 보간합니다. 이전 배포판에서는 두 값을 설정하지 않았습니다.

Enhanced: 3.4.0 - Support for geography was introduced.

변경 사항: 2.1.0 미만 버전, 즉 2.0.x 버전까지 이 함수의 명칭은 ST_Line_Substring이었습니다.

1.1.0 버전부터 사용할 수 있습니다. 1.1.1 버전부터 Z 및 M을 지원합니다.

This function supports 3d and will not drop the z-index.

예시

Extract the middle third of a LineString, from 0.333 to 0.666.

Code
SELECT ST_LineSubstring(
'LINESTRING (20 180,50 20,90 80,120 40,180 150)',
0.333,
0.666);
래스터 출력
LINESTRING (45.17311810399485 45.74337011202746, 50 20, 90 80, 112.97593050157862 49.36542599789519)
Figure
Geometry figure for visual-st-linesubstring-01

If start and end locations are the same, the result is a POINT.

Code
SELECT ST_LineSubstring(
'LINESTRING(25 50,100 125,150 190)',
0.333,
0.333);
래스터 출력
POINT(69.28469348539744 94.28469348539744)
Figure
Geometry figure for visual-st-linesubstring-02

A query to cut a LineString into sections of length 100 or shorter. It uses generate_series() with a CROSS JOIN LATERAL to produce the equivalent of a FOR loop.

The final generated step is filtered out when the line length is an exact multiple of the requested section length.

Code
WITH data(id, geom) AS (VALUES
        ( 'A', 'LINESTRING( 0 0, 200 0)'::geometry ),
        ( 'B', 'LINESTRING( 0 100, 350 100)'::geometry ),
        ( 'C', 'LINESTRING( 0 200, 50 200)'::geometry )
    )
SELECT id, i,
       ST_LineSubstring(geom, startfrac, LEAST( endfrac, 1 )) AS geom
FROM (
    SELECT id, geom, ST_Length(geom) len, 100 sublen FROM data
    ) AS d
CROSS JOIN LATERAL (
    SELECT i, (sublen * i) / len AS startfrac,
              (sublen * (i+1)) / len AS endfrac
    FROM generate_series(0, floor( len / sublen )::integer ) AS t(i)
    WHERE (sublen * i) / len <
> 1.0
    ) AS d2;
래스터 출력
id | i |            geom
----+---+-----------------------------
 A  | 0 | LINESTRING(0 0,100 0)
 A  | 1 | LINESTRING(100 0,200 0)
 B  | 0 | LINESTRING(0 100,100 100)
 B  | 1 | LINESTRING(100 100,200 100)
 B  | 2 | LINESTRING(200 100,300 100)
 B  | 3 | LINESTRING(300 100,350 100)
 C  | 0 | LINESTRING(0 200,50 200)
Figure
Geometry figure for visual-st-linesubstring-03

Split a LineString by points by locating the points along the line, adding the 0 and 1 endpoints, and extracting substrings between adjacent locations.

Code
WITH data AS (
  SELECT 'LINESTRING(0 0, 10 0)'::geometry AS line,
         'MULTIPOINT((2 0),(5 0),(8 0))'::geometry AS points
),
fractions AS (
  SELECT 0.0 AS fraction
  UNION ALL
  SELECT 1.0
  UNION ALL
  SELECT ST_LineLocatePoint(line, (dp).geom)
  FROM data
  CROSS JOIN LATERAL ST_Dump(points) AS dp
),
ordered AS (
  SELECT DISTINCT fraction
  FROM fractions
),
segments AS (
  SELECT fraction AS start_fraction,
         lead(fraction) OVER (ORDER BY fraction) AS end_fraction
  FROM ordered
)
SELECT row_number() OVER (ORDER BY start_fraction) AS segment_id,
       ST_LineSubstring(line, start_fraction, end_fraction) AS geom
FROM data
CROSS JOIN segments
WHERE end_fraction IS NOT NULL
  AND start_fraction <
> end_fraction
ORDER BY start_fraction;
래스터 출력
segment_id |         geom
------------+----------------------
          1 | LINESTRING(0 0,2 0)
          2 | LINESTRING(2 0,5 0)
          3 | LINESTRING(5 0,8 0)
          4 | LINESTRING(8 0,10 0)
Figure
Geometry figure for visual-st-linesubstring-04

Geography implementation measures along a spheroid, geometry along a line

Code
SELECT ST_LineSubstring(
'LINESTRING(-118.2436 34.0522,-71.0570 42.3611)'::geography,
0.333,
0.666) AS geog_sub,
ST_LineSubstring(
    'LINESTRING(-118.2436 34.0522,-71.0570 42.3611)'::geometry,
    0.333,
    0.666) AS geom_sub;
래스터 출력
-[ RECORD 1 ]----------
geog_sub | LINESTRING(-103.911641 38.931128,-87.941787 41.831072)
geom_sub | LINESTRING(-102.530462 36.819064,-86.817324 39.585927)
Figure
Geometry figure for visual-st-linesubstring-05

For geometry inputs, the fractional locations are based on the 2D length of the line, even when the input has Z values. The resulting Z values are interpolated along the selected 2D location.

Code
WITH data AS (
  SELECT 'LINESTRING Z (0 0 0,0 2 5,0 10 10)'::geometry AS geom
)
SELECT ST_Length(geom) AS length_2d,
       ST_3DLength(geom) AS length_3d,
       ST_LineSubstring(geom, 0, 0.5) AS substring
FROM data;
래스터 출력
length_2d |    length_3d     |              substring
-----------+------------------+-------------------------------------
        10 | 14.819145939191106 | LINESTRING Z (0 0 0,0 2 5,0 5 6.875)
Figure
Geometry figure for visual-st-linesubstring-06

제목

ST_LocateAlong — Returns the point(s) on a geometry that match a measure value.

요약

geometry ST_LocateAlong(geometry geom_with_measure, float8 measure, float8 offset = 0);

설명

Returns the location(s) along a measured geometry that have the given measure values. The result is a Point or MultiPoint. Polygonal inputs are not supported.

If offset is provided, the result is offset to the left or right of the input line by the specified distance. A positive offset will be to the left, and a negative one to the right.

[참고]

Use this function only for linear geometries with an M component

The semantic is specified by the ISO/IEC 13249-3 SQL/MM Spatial standard.

1.1.0 버전부터 예전 명칭인 ST_Locate_Along_Measure로 사용할 수 있습니다.

변경 사항: 2.0.0 미만 버전에서는 ST_Locate_Along_Measure라는 명칭이었습니다. 예전 명칭은 더 지원되지 않고 곧 삭제될 예정이지만, 아직은 사용할 수 있습니다.

This function supports M coordinates.

This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 5.1.13

예시

Code
SELECT ST_LocateAlong(
'MULTILINESTRINGM((1 2 3, 3 4 2, 9 4 3),(1 2 3, 5 4 5))'::geometry,
3);
래스터 출력
MULTIPOINT M ((1 2 3),(9 4 3),(1 2 3))
Figure
Geometry figure for visual-st-locatealong-01

제목

ST_LocateBetween — Returns the portions of a geometry that match a measure range.

요약

geometry ST_LocateBetween(geometry geom, float8 measure_start, float8 measure_end, float8 offset = 0);

설명

설정한 척도와 일치하는 요소들을 가진 파생 도형 집합의 값을 반환합니다. 폴리곤 구성 요소는 지원되지 않습니다.

오프셋을 설정할 경우, 그 결과 입력 라인에서 설정한 단위 개수만큼 왼쪽 또는 오른쪽에 오프셋 도형 집합을 출력할 것입니다. 양의 오프셋은 왼쪽, 음의 오프셋은 오른쪽으로 출력할 것입니다.

Clipping a non-convex POLYGON may produce invalid geometry.

The semantic is specified by the ISO/IEC 13249-3 SQL/MM Spatial standard.

1.1.0 버전부터 예전 명칭인 ST_Locate_Between_Measures로 사용할 수 있습니다.

변경 사항: 2.0.0 미만 버전에서는 ST_Locate_Along_Measure라는 명칭이었습니다. 예전 명칭은 더 지원되지 않고 곧 삭제될 예정이지만, 아직은 사용할 수 있습니다.

Enhanced: 3.0.0 - added support for POLYGON, TIN, TRIANGLE.

This function supports M coordinates.

This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 5.1

예시

Code
SELECT ST_LocateBetween(
'MULTILINESTRING M ((1 2 3,3 4 2,9 4 3),(1 2 3,5 4 5))'::geometry,
1.5,
3);
래스터 출력
GEOMETRYCOLLECTION M (LINESTRING M (1 2 3,3 4 2,9 4 3),POINT M (1 2 3))
Figure
Geometry figure for visual-st-locatebetween-01

Extract the section between measures 2 and 8, offset to the left. Because the clipped line and the offset result share the same coordinate space, this example is intended for a single overlay panel rather than separate side-by-side figures.

Code
SELECT ST_LocateBetween(
ST_AddMeasure(
    'LINESTRING (20 180,50 20,100 120,180 20)',
    0,
    10),
2,
8,
20);
래스터 출력
MULTILINESTRING((54.49835 104.53427,58.700561 82.122481,82.111456 128.944272,84.248937 132.324934,87.01637 135.21267,90.303073 137.491987,93.977598 139.071724,97.892984 139.888702,101.892639 139.910247,105.816599 139.135495,109.507928 137.595434,112.818995 135.351657,115.617376 132.493901,145.310173 95.377905))
Figure
Geometry figure for visual-st-locatebetween-02

제목

ST_LocateBetweenElevations — Returns the portions of a geometry that lie in an elevation (Z) range.

요약

geometry ST_LocateBetweenElevations(geometry geom, float8 elevation_start, float8 elevation_end);

설명

Returns a geometry (collection) with the portions of a geometry that lie in an elevation (Z) range.

Clipping a non-convex POLYGON may produce invalid geometry.

1.4.0 버전부터 사용할 수 있습니다.

Enhanced: 3.0.0 - added support for POLYGON, TIN, TRIANGLE.

This function supports 3d and will not drop the z-index.

예시

Code
SELECT ST_LocateBetweenElevations(
'LINESTRING(1 2 3,4 5 6)'::geometry,
2,
4);
래스터 출력
MULTILINESTRING Z ((1 2 3,2 3 4))
Figure
Geometry figure for visual-st-locatebetweenelevations-01
Code
SELECT ST_LocateBetweenElevations(
'LINESTRING(1 2 6,4 5 -1,7 8 9)',
6,
9) As ewelev;
래스터 출력
GEOMETRYCOLLECTION Z (POINT Z (1 2 6),LINESTRING Z (6.1 7.1 6,7 8 9))
Figure
Geometry figure for visual-st-locatebetweenelevations-02

제목

ST_InterpolatePoint — 입력 포인트에 가까운 포인트에서 도형의 척도 차원(M 차원)의 값을 반환합니다.

요약

float8 ST_InterpolatePoint(geometry linear_geom_with_measure, geometry point);

설명

Returns an interpolated measure value of a linear measured geometry at the location closest to the given point.

[참고]

Use this function only for linear geometries with an M component

2.0.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

예시

Code
SELECT ST_InterpolatePoint(
'LINESTRING M (0 0 0,10 0 20)',
'POINT(5 5)');
래스터 출력
10
Figure
Geometry figure for visual-st-interpolatepoint-01

제목

ST_3DInterpolatePoint — Returns the interpolated measure of a geometry closest to a point in 3D.

요약

float8 ST_3DInterpolatePoint(geometry linear_geom_with_measure, geometry point);

설명

Returns the interpolated measure value of a linear ZM geometry at the location closest to the given point, using 3D (XYZ) distance for the projection. Use this function when the geometry has significant Z variation, such as flight trajectories, where ST_InterpolatePoint would give incorrect results by ignoring the Z dimension.

[참고]

The line must have both Z and M dimensions. The point should have a Z dimension.

Availability: 3.7.0

This function supports 3d and will not drop the z-index.

예시

This example interpolates on a line rising diagonally in Z, using a point at the 3D midpoint.

Code
SELECT ST_3DInterpolatePoint(
'LINESTRING ZM (0 0 0 0,10 0 10 20)',
'POINT Z (5 0 5)');
래스터 출력
10
Figure
Geometry figure for visual-st-3dinterpolatepoint-01

This example uses a vertical line with zero XY extent, where 3D projection works but 2D projection does not.

Code
SELECT ST_3DInterpolatePoint(
'LINESTRING ZM (0 0 0 0,0 0 10 100)',
'POINT Z (5 5 5)');
래스터 출력
50
Figure
Geometry figure for visual-st-3dinterpolatepoint-02

제목

ST_AddMeasure — Interpolates measures along a linear geometry.

요약

geometry ST_AddMeasure(geometry geom_mline, float8 measure_start, float8 measure_end);

설명

시작점과 종단점 사이의 선형적으로 보간된 척도 요소들을 가진 파생 도형을 반환합니다. 도형이 척도 차원을 가지고 있지 않을 경우, 척도 차원을 추가합니다. 도형이 척도 차원을 가지고 있을 경우, 새 값들로 덮어 씁니다. 라인스트링과 멀티라인스트링만 지원합니다.

1.5.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

예시

Code
SELECT ST_AddMeasure(
'LINESTRING(1 0,2 0,4 0)',
1,
4) As ewelev;
래스터 출력
LINESTRING M (1 0 1,2 0 2,4 0 4)
Figure
Geometry figure for visual-st-addmeasure-01
Code
SELECT ST_AddMeasure(
'LINESTRING(1 0 4,2 0 4,4 0 4)',
10,
40) As ewelev;
래스터 출력
LINESTRING ZM (1 0 4 10,2 0 4 20,4 0 4 40)
Figure
Geometry figure for visual-st-addmeasure-02
Code
SELECT ST_AddMeasure(
'LINESTRINGM(1 0 4, 2 0 4, 4 0 4)',
10,
40) As ewelev;
래스터 출력
LINESTRING M (1 0 10,2 0 20,4 0 40)
Figure
Geometry figure for visual-st-addmeasure-03
Code
SELECT ST_AddMeasure(
'MULTILINESTRINGM((1 0 4, 2 0 4, 4 0 4),(1 0 4, 2 0 4, 4 0 4))',
10,
70) As ewelev;
래스터 출력
MULTILINESTRING M ((1 0 10,2 0 20,4 0 40),(1 0 40,2 0 50,4 0 70))
Figure
Geometry figure for visual-st-addmeasure-04

7.20. Trajectory Functions

초록

These functions support working with trajectories. A trajectory is a linear geometry with increasing measures (M value) on each coordinate. Spatio-temporal data can be modeled by using relative times (such as the epoch) as the measure values.

  • ST_IsValidTrajectory — Tests if the geometry is a valid trajectory.
  • ST_ClosestPointOfApproach — Returns a measure at the closest point of approach of two trajectories.
  • ST_DistanceCPA — Returns the distance between the closest point of approach of two trajectories.
  • ST_CPAWithin — Tests if the closest point of approach of two trajectories is within the specified distance.

제목

ST_IsValidTrajectory — Tests if the geometry is a valid trajectory.

요약

boolean ST_IsValidTrajectory(geometry line);

설명

Tests if a geometry encodes a valid trajectory. A valid trajectory is represented as a LINESTRING with measures (M values). The measure values must increase from each vertex to the next.

Valid trajectories are expected as input to spatio-temporal functions like ST_ClosestPointOfApproach

2.2.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

예시

This example constructs a valid trajectory.

Code
SELECT ST_IsValidTrajectory(ST_MakeLine(ST_MakePointM(0, 0, 1),
ST_MakePointM(0, 1, 2)));
래스터 출력
t

This example constructs an invalid trajectory.

Code
SELECT ST_IsValidTrajectory(ST_MakeLine(ST_MakePointM(0, 0, 1), ST_MakePointM(0, 1, 0)));
래스터 출력
NOTICE:  Measure of vertex 1 (0) not bigger than measure of vertex 0 (1)
f

제목

ST_ClosestPointOfApproach — Returns a measure at the closest point of approach of two trajectories.

요약

float8 ST_ClosestPointOfApproach(geometry track1, geometry track2);

설명

Returns the smallest measure at which points interpolated along the given trajectories are the least distance apart.

Inputs must be valid trajectories as checked by ST_IsValidTrajectory. Null is returned if the trajectories do not overlap in their M ranges.

To obtain the actual points at the computed measure use ST_LocateAlong .

2.2.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

예시

Return the time in which two objects moving between 10:00 and 11:00 are closest to each other and their distance at that point.

Code
WITH inp AS ( SELECT
  ST_AddMeasure('LINESTRING Z (0 0 0,10 0 5)'::geometry,
    extract(epoch from timestamp '2015-05-26 10:00' AT TIME ZONE 'UTC'),
    extract(epoch from timestamp '2015-05-26 11:00' AT TIME ZONE 'UTC')
  ) a,
  ST_AddMeasure('LINESTRING Z (0 2 10,12 1 2)'::geometry,
    extract(epoch from timestamp '2015-05-26 10:00' AT TIME ZONE 'UTC'),
    extract(epoch from timestamp '2015-05-26 11:00' AT TIME ZONE 'UTC')
  ) b
), cpa AS (
  SELECT ST_ClosestPointOfApproach(a, b) m FROM inp
), points AS (
  SELECT ST_GeometryN(ST_LocateAlong(a, m), 1) pa,
         ST_GeometryN(ST_LocateAlong(b, m), 1) pb
  FROM inp, cpa
)
SELECT to_timestamp(m) AT TIME ZONE 'UTC' t,
       ST_3DDistance(pa, pb) distance,
       pa AS pa, pb AS pb
FROM points, cpa;
래스터 출력
-[ RECORD 1 ]-----------------------------
t        | 2015-05-26 10:45:31.034483
distance | 1.9652147377620688
pa       | POINT ZM (7.59 0 3.79 1432637131.03)
pb       | POINT ZM (9.1 1.24 3.93 1432637131.03)
Figure
Geometry figure for visual-st-closestpointofapproach-01

제목

ST_DistanceCPA — Returns the distance between the closest point of approach of two trajectories.

요약

float8 ST_DistanceCPA(geometry track1, geometry track2);

설명

Returns the distance (in 2D) between two trajectories at their closest point of approach.

Inputs must be valid trajectories as checked by ST_IsValidTrajectory. Null is returned if the trajectories do not overlap in their M ranges.

2.2.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

예시

Return the minimum distance of two objects moving between 10:00 and 11:00.

Code
WITH inp AS ( SELECT
  ST_AddMeasure('LINESTRING Z (0 0 0,10 0 5)'::geometry,
    extract(epoch from timestamp '2015-05-26 10:00' AT TIME ZONE 'UTC'),
    extract(epoch from timestamp '2015-05-26 11:00' AT TIME ZONE 'UTC')
  ) a,
  ST_AddMeasure('LINESTRING Z (0 2 10,12 1 2)'::geometry,
    extract(epoch from timestamp '2015-05-26 10:00' AT TIME ZONE 'UTC'),
    extract(epoch from timestamp '2015-05-26 11:00' AT TIME ZONE 'UTC')
  ) b
)
SELECT ST_DistanceCPA(a, b) distance FROM inp;
래스터 출력
1.9652147377620688
Figure
Geometry figure for visual-st-distancecpa-01

제목

ST_CPAWithin — Tests if the closest point of approach of two trajectories is within the specified distance.

요약

boolean ST_CPAWithin(geometry track1, geometry track2, float8 dist);

설명

Tests whether two moving objects have ever been closer than the specified distance.

Inputs must be valid trajectories as checked by ST_IsValidTrajectory. False is returned if the trajectories do not overlap in their M ranges.

2.2.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

예시

Code
WITH inp AS ( SELECT
  ST_AddMeasure('LINESTRING Z (0 0 0,10 0 5)'::geometry,
    extract(epoch from timestamp '2015-05-26 10:00' AT TIME ZONE 'UTC'),
    extract(epoch from timestamp '2015-05-26 11:00' AT TIME ZONE 'UTC')
  ) a,
  ST_AddMeasure('LINESTRING Z (0 2 10,12 1 2)'::geometry,
    extract(epoch from timestamp '2015-05-26 10:00' AT TIME ZONE 'UTC'),
    extract(epoch from timestamp '2015-05-26 11:00' AT TIME ZONE 'UTC')
  ) b
)
SELECT ST_CPAWithin(a, b, 2), ST_DistanceCPA(a, b) distance FROM inp;
래스터 출력
st_cpawithin |     distance
--------------+------------------
 t            | 1.9652147377620688
Figure
Geometry figure for visual-st-cpawithin-01

7.21. Version Functions

초록

These functions report and upgrade PostGIS versions.

제목

PostGIS_Extensions_Upgrade — Packages and upgrades PostGIS extensions (e.g. postgis_raster, postgis_topology, postgis_sfcgal) to given or latest version.

요약

text PostGIS_Extensions_Upgrade(text target_version=null);

설명

Packages and upgrades PostGIS extensions to given or latest version. Only extensions you have installed in the database will be packaged and upgraded if needed. Reports full PostGIS version and build configuration infos after. This is short-hand for doing multiple CREATE EXTENSION .. FROM unpackaged and ALTER EXTENSION .. UPDATE for each PostGIS extension. Currently only tries to upgrade extensions postgis, postgis_raster, postgis_sfcgal, and postgis_topology.

Availability: 2.5.0

Changed: 3.4.0 to add target_version argument.

Changed: 3.3.0 support for upgrades from any PostGIS version. Does not work on all systems.

Changed: 3.0.0 to repackage loose extensions and support postgis_raster.

예시

Code
SELECT PostGIS_Extensions_Upgrade();
래스터 출력
NOTICE:  Packaging extension postgis
NOTICE:  Packaging extension postgis_raster
NOTICE:  Packaging extension postgis_sfcgal
NOTICE:  Extension postgis_topology is not available or not packagable for some reason

제목

PostGIS_Full_Version — Reports full PostGIS version and build configuration infos.

요약

text PostGIS_Full_Version();

설명

Reports full PostGIS version and build configuration infos. Also informs about synchronization between libraries and scripts suggesting upgrades as needed.

Enhanced: 3.4.0 now includes extra PROJ configurations NETWORK_ENABLED, URL_ENDPOINT and DATABASE_PATH of proj.db location

예시

Code
SELECT PostGIS_Full_Version();
래스터 출력
POSTGIS="3.7.0dev 3.7.0alpha1-477-ga9004e778" [EXTENSION] PGSQL="180" GEOS="3.15.0beta1" SFCGAL="2.3.0" PROJ="9.8.1 NETWORK_ENABLED=OFF URL_ENDPOINT=https://cdn.proj.org DATABASE_PATH=/usr/share/proj/proj.db" GDAL="GDAL 3.13.1, released 2026/06/01" LIBXML="2.15.3"

제목

PostGIS_GEOS_Version — Returns the version number of the GEOS library.

요약

text PostGIS_GEOS_Version();

설명

Returns the version number of the GEOS library, or NULL if GEOS support is not enabled.

예시

Code
SELECT PostGIS_GEOS_Version();
래스터 출력
3.12.0dev-CAPI-1.18.0

제목

PostGIS_GEOS_Compiled_Version — Returns the version number of the GEOS library against which PostGIS was built.

요약

text PostGIS_GEOS_Compiled_Version();

설명

Returns the version number of the GEOS library, or against which PostGIS was built.

Availability: 3.4.0

예시

Code
SELECT PostGIS_GEOS_Compiled_Version();
래스터 출력
3.12.0

제목

PostGIS_Liblwgeom_Version — Returns the version number of the liblwgeom library. This should match the version of PostGIS.

요약

text PostGIS_Liblwgeom_Version();

설명

Returns the version number of the liblwgeom library/

예시

Code
SELECT PostGIS_Liblwgeom_Version();
래스터 출력
3.4.0dev 3.3.0rc2-993-g61bdf43a7

제목

PostGIS_LibXML_Version — Returns the version number of the libxml2 library.

요약

text PostGIS_LibXML_Version();

설명

Returns the version number of the LibXML2 library.

1.5 버전부터 사용할 수 있습니다.

예시

Code
SELECT PostGIS_LibXML_Version();
래스터 출력
2.9.10

제목

PostGIS_LibJSON_Version — Returns the version number of the libjson-c library.

요약

text PostGIS_LibJSON_Version();

설명

Returns the version number of the LibJSON-C library.

예시

Code
SELECT PostGIS_LibJSON_Version();
래스터 출력
0.17

제목

PostGIS_Lib_Build_Date — Returns build date of the PostGIS library.

요약

text PostGIS_Lib_Build_Date();

설명

Returns build date of the PostGIS library.

예시

Code
SELECT PostGIS_Lib_Build_Date();
래스터 출력
2023-06-22 03:56:11

제목

PostGIS_Lib_Version — Returns the version number of the PostGIS library.

요약

text PostGIS_Lib_Version();

설명

Returns the version number of the PostGIS library.

예시

Code
SELECT PostGIS_Lib_Version();
래스터 출력
3.4.0dev

제목

PostGIS_PROJ_Version — Returns the version number of the PROJ4 library.

요약

text PostGIS_PROJ_Version();

설명

Returns the version number of the PROJ library and some configuration options of proj.

Enhanced: 3.4.0 now includes NETWORK_ENABLED, URL_ENDPOINT and DATABASE_PATH of proj.db location

예시

Code
SELECT PostGIS_PROJ_Version();
래스터 출력
7.2.1 NETWORK_ENABLED=OFF URL_ENDPOINT=https://cdn.proj.org USER_WRITABLE_DIRECTORY=/tmp/proj DATABASE_PATH=/usr/share/proj/proj.db

제목

PostGIS_PROJ_Compiled_Version — Returns the version number of the PROJ library against which PostGIS was built.

요약

text PostGIS_PROJ_Compiled_Version();

설명

Returns the version number of the PROJ library, or against which PostGIS was built.

Availability: 3.5.0

예시

Code
SELECT PostGIS_PROJ_Compiled_Version();
래스터 출력
9.1.1

제목

PostGIS_Wagyu_Version — Returns the version number of the internal Wagyu library.

요약

text PostGIS_Wagyu_Version();

설명

Returns the version number of the internal Wagyu library, or NULL if Wagyu support is not enabled.

예시

Code
SELECT PostGIS_Wagyu_Version();
래스터 출력
0.5.0 (Internal)

제목

PostGIS_Scripts_Build_Date — Returns build date of the PostGIS scripts.

요약

text PostGIS_Scripts_Build_Date();

설명

Returns build date of the PostGIS scripts.

1.0.0RC1 버전부터 사용할 수 있습니다.

예시

Code
SELECT PostGIS_Scripts_Build_Date();
래스터 출력
2023-06-22 03:56:11

제목

PostGIS_Scripts_Installed — Returns version of the PostGIS scripts installed in this database.

요약

text PostGIS_Scripts_Installed();

설명

Returns version of the PostGIS scripts installed in this database.

[참고]

If the output of this function doesn't match the output of PostGIS_Scripts_Released you probably missed to properly upgrade an existing database. See the Upgrading section for more info.

Availability: 0.9.0

예시

Code
SELECT PostGIS_Scripts_Installed();
래스터 출력
3.4.0dev 3.3.0rc2-993-g61bdf43a7

제목

PostGIS_Scripts_Released — Returns the version number of the postgis.sql script released with the installed PostGIS lib.

요약

text PostGIS_Scripts_Released();

설명

Returns the version number of the postgis.sql script released with the installed PostGIS lib.

[참고]

Starting with version 1.1.0 this function returns the same value of PostGIS_Lib_Version. Kept for backward compatibility.

Availability: 0.9.0

예시

Code
SELECT PostGIS_Scripts_Released();
래스터 출력
3.4.0dev 3.3.0rc2-993-g61bdf43a7

제목

PostGIS_Version — Returns PostGIS version number and compile-time options.

요약

text PostGIS_Version();

설명

Returns PostGIS version number and compile-time options.

예시

Code
SELECT PostGIS_Version();
래스터 출력
3.4 USE_GEOS=1 USE_PROJ=1 USE_STATS=1

7.22. PostGIS GUC(Grand Unified Custom Variable)

초록

이 단원에서 사용자 지정 PostGIS GUC(Grand Unified Custom Variable)에 대해 설명합니다. 전체(global), 데이터베이스, 세션, 또는 상호처리(transaction) 단계에서 GUC를 설정할 수 있습니다. 전체 또는 데이터베이스 단계에서 설정하는 편이 가장 좋습니다.

For more examples of usage refer to SQL SET and SQL ALTER SYSTEM

  • postgis.gdal_datapath — GDAL의 GDAL_DATA 옵션의 값을 할당하는 설정 옵션입니다. 설정하지 않을 경우, 환경적으로 설정된 GDAL_DATA 변수를 사용합니다.
  • postgis.gdal_enabled_drivers — PostGIS 환경에서 사용할 수 있는 GDAL 드라이버를 설정하는 설정 옵션입니다. GDAL 설정 변수 GDAL_SKIP에 영향을 미칩니다.
  • postgis.enable_outdb_rasters — DB 외부 래스터 밴드에 접근할 수 있게 해주는 불 설정 옵션입니다.
  • postgis.gdal_vsi_options — DB 외부 래스터 밴드에 접근할 수 있게 해주는 불 설정 옵션입니다.
  • postgis.gdal_cpl_debug — A boolean configuration to turn logging of GDAL debug messages on and off.

제목

postgis.gdal_datapath — GDAL의 GDAL_DATA 옵션의 값을 할당하는 설정 옵션입니다. 설정하지 않을 경우, 환경적으로 설정된 GDAL_DATA 변수를 사용합니다.

설명

GDAL의 GDAL_DATA 옵션의 값을 설정하기 위한 PostgreSQL GUC 변수입니다. postgis.gdal_datapath 값은 GDAL의 데이터 파일을 가리키는 완전한 물리적 경로여야 합니다.

이 설정 옵션은 GDAL의 데이터 파일 경로가 쉽게 변경할 수 없도록 기록(hard-coded)되지 않은 윈도우 플랫폼에서 가장 쓸모가 있습니다. GDAL의 데이터 파일이 GDAL의 예상 경로에 없을 때 이 옵션을 설정해야 합니다.

[참고]

PostgreSQL의 설정 파일 postgresql.conf 안에서 이 옵션을 설정할 수 있습니다. 또 연결이나 상호처리 단계에서도 설정할 수 있습니다.

2.2.0 버전부터 사용할 수 있습니다.

[참고]

GDAL의 설정 옵션 페이지에서 GDAL_DATA에 대한 추가 정보를 찾아볼 수 있습니다.

예시

postgis.gdal_datapath 를 설정한 다음 재설정해보십시오.

Code
SET postgis.gdal_datapath TO '/usr/local/share/gdal.hidden';
SET postgis.gdal_datapath TO default;
                

특정 데이터베이스를 대상으로 윈도우 상에서 설정해보십시오.

Code
ALTER DATABASE gisdb
SET postgis.gdal_datapath = 'C:/Program Files/PostgreSQL/9.3/gdal-data';

제목

postgis.gdal_enabled_drivers — PostGIS 환경에서 사용할 수 있는 GDAL 드라이버를 설정하는 설정 옵션입니다. GDAL 설정 변수 GDAL_SKIP에 영향을 미칩니다.

설명

PostGIS 환경에서 사용할 수 있는 GDAL 드라이버를 설정하는 설정 옵션입니다. GDAL 설정 변수 GDAL_SKIP에 영향을 미칩니다. PostgreSQL의 설정 파일 postgresql.conf 안에서 이 옵션을 설정할 수 있습니다. 또 연결이나 상호처리 단계에서도 설정할 수 있습니다.

PostgreSQL을 구동시키는 과정에서 사용할 수 있는 드라이버 목록과 함께 환경 변수 POSTGIS_GDAL_ENABLED_DRIVERS 를 패스(pass)시켜 postgis.gdal_enabled_drivers 의 초기값을 설정할 수도 있습니다.

드라이버의 축약명 또는 코드를 통해 활성화된 GDAL 특화 드라이버를 지정할 수 있습니다. 드라이버의 축약명 또는 코드는 GDAL 래스터 형식 에서 찾을 수 있습니다. 각 드라이버 사이에 공백을 삽입하면 복수의 드라이버를 지정할 수 있습니다.

[참고]

postgis.gdal_enabled_drivers 를 위해 사용할 수 있는 특별 코드가 세 개 있습니다. 이 코드들은 대소문자를 구분합니다.

  • DISABLE_ALL 은 모든 GDAL 드라이버를 비활성화시킵니다. DISABLE_ALL 이 있을 경우, postgis.gdal_enabled_drivers 안에 있는 다른 모든 값을 무시합니다.

  • ENABLE_ALL 은 모든 GDAL 드라이버를 활성화시킵니다.

  • VSICURL 은 GDAL의 /vsicurl/ 가상 파일 시스템을 활성화시킵니다.

postgis.gdal_enabled_drivers 가 DISABLE_ALL로 성정됐을 경우, DB 외부 래스터, ST_FromGDALRaster(), ST_AsGDALRaster(), ST_AsTIFF(), ST_AsJPEG() 그리고 ST_AsPNG()를 사용하려 한다면 모두 오류 메시지를 보게 될 것입니다.

[참고]

표준 PostGIS 설치시, postgis.gdal_enabled_drivers 는 DISABLE_ALL로 설정됩니다.

[참고]

GDAL_SKIP에 대한 추가 정보는 GDAL의 Configuration Options 에서 찾아볼 수 있습니다.

2.2.0 버전부터 사용할 수 있습니다.

예시

Set and reset postgis.gdal_enabled_drivers for the current session.

Code
SET postgis.gdal_enabled_drivers = 'ENABLE_ALL';
SET postgis.gdal_enabled_drivers = default;
                

Set specific drivers for all new connections to a database.

Code
ALTER DATABASE mygisdb SET postgis.gdal_enabled_drivers TO 'GTiff PNG JPEG';

Set the default for the whole database cluster to enable all drivers. This requires superuser access. Also note that database, session, and user settings override this.

This example writes the setting to postgres.auto.conf.

Code
ALTER SYSTEM SET postgis.gdal_enabled_drivers TO 'ENABLE_ALL';

Reload the PostgreSQL configuration so the changed setting is applied.

Code
SELECT pg_reload_conf();

제목

postgis.enable_outdb_rasters — DB 외부 래스터 밴드에 접근할 수 있게 해주는 불 설정 옵션입니다.

설명

DB 외부 래스터 밴드에 접근할 수 있게 해주는 불 설정 옵션입니다. PostgreSQL의 설정 파일 postgresql.conf 안에서 이 옵션을 설정할 수 있습니다. 또 연결이나 상호처리 단계에서도 설정할 수 있습니다.

PostgreSQL을 구동시키는 과정에서 0이 아닌 값과 함께 환경 변수 POSTGIS_ENABLE_OUTDB_RASTERS 를 패스(pass)시켜 postgis.enable_outdb_rasters 의 초기값을 설정할 수도 있습니다.

[참고]

postgis.enable_outdb_rasters 가 참이라 할지라도, GUC postgis.enable_outdb_rasters 가 접근 가능한 래스터 형식을 결정합니다.

[참고]

표준 PostGIS 설치시, postgis.enable_outdb_rasters 는 거짓으로 설정됩니다.

2.2.0 버전부터 사용할 수 있습니다.

예시

Set and reset postgis.enable_outdb_rasters for the current session.

Code
SET postgis.enable_outdb_rasters TO True;
SET postgis.enable_outdb_rasters = default;
SET postgis.enable_outdb_rasters = True;
SET postgis.enable_outdb_rasters = False;
                

Set the default for all new connections to a database.

Code
ALTER DATABASE gisdb SET postgis.enable_outdb_rasters = true;

Set the default for the whole database cluster. This requires superuser access. Also note that database, session, and user settings override this.

This example writes the setting to postgres.auto.conf.

Code
ALTER SYSTEM SET postgis.enable_outdb_rasters = true;

Reload the PostgreSQL configuration so the changed setting is applied.

Code
SELECT pg_reload_conf();

제목

postgis.gdal_vsi_options — DB 외부 래스터 밴드에 접근할 수 있게 해주는 불 설정 옵션입니다.

설명

A string configuration to set options used when working with an out-db raster. Configuration options control things like how much space GDAL allocates to local data cache, whether to read overviews, and what access keys to use for remote out-db data sources.

Availability: 3.2.0

예시

postgis.enable_outdb_rasters 를 설정한 다음 재설정해보십시오.

Code
SET postgis.gdal_vsi_options = 'AWS_ACCESS_KEY_ID=xxxxxxxxxxxxxxx AWS_SECRET_ACCESS_KEY=yyyyyyyyyyyyyyyyyyyyyyyyyy';

Set postgis.gdal_vsi_options just for the current transaction using the LOCAL keyword:

Code
SET LOCAL postgis.gdal_vsi_options = 'AWS_ACCESS_KEY_ID=xxxxxxxxxxxxxxx AWS_SECRET_ACCESS_KEY=yyyyyyyyyyyyyyyyyyyyyyyyyy';

제목

postgis.gdal_cpl_debug — A boolean configuration to turn logging of GDAL debug messages on and off.

설명

By default, GDAL logging is printed to stderr, and lower level debug messages are not printed at all. Turning this GUC to true will cause GDAL logging to be sent into the PostgreSQL logging stream, so you can see more or less of it by altering the client_min_message PostgreSQL GUC.

Availability: 3.6.0

7.23. Troubleshooting Functions

초록

These functions are utilities for troubleshooting and repairing geometry data. They are only needed if the geometry data is corrupted in some way, which should never happen under normal circumstances.

  • PostGIS_AddBBox — 도형에 경계 상자를 추가합니다.
  • PostGIS_DropBBox — 도형으로부터 경계 상자 캐시를 삭제합니다.
  • PostGIS_HasBBox — 해당 도형의 경계 상자가 캐시화된 경우 참을 반환하고, 그렇지 않을 경우 거짓을 반환합니다.

제목

PostGIS_AddBBox — 도형에 경계 상자를 추가합니다.

요약

geometry PostGIS_AddBBox(geometry geomA);

설명

도형에 경계 상자를 추가합니다. 이렇게 하면 경계 상자 기반 쿼리의 속도가 빨라지지만, 도형의 용량은 늘어날 것입니다.

[참고]

경계 상자는 도형에 자동적으로 추가되기 때문에 일반적으로 이 함수가 필요하지는 않습니다. 생성된 경계 상자에 어떤 이유로든 오류가 발생했거나, 또는 경계 상자가 없는 구버전 도형을 사용하는 경우, 옛 경계 상자를 삭제하고 다시 추가해야 합니다.

This method supports Circular Strings and Curves.

예시

Code
UPDATE sometable
SET geom =  PostGIS_AddBBox(geom)
WHERE PostGIS_HasBBox(geom) = false;

제목

PostGIS_DropBBox — 도형으로부터 경계 상자 캐시를 삭제합니다.

요약

geometry PostGIS_DropBBox(geometry geomA);

설명

도형으로부터 경계 상자 캐시를 삭제합니다. 이렇게 하면 도형 용량이 줄어들지만, 경계 상자 기반 쿼리는 느려집니다. 오류가 발생한 경계 상자를 삭제하는 데에도 이 함수를 이용합니다. 경계 상자 캐시에 오류가 발생했다는 숨길 수 없는 증거는, 사용자가 ST_Intersects 및 다른 관계성 쿼리를 실행했을 때 당연히 참을 반환해야 할 도형들을 배제하는 경우입니다.

[참고]

경계 상자는 도형에 자동적으로 추가되어 쿼리의 속도를 향상시키기 때문에 일반적으로는 이 함수가 필요하지 않습니다. 생성된 경계 상자에 어떤 이유로든 오류가 발생했거나, 또는 경계 상자가 없는 구버전 도형을 사용하는 경우, 옛 경계 상자를 삭제하고 다시 추가해야 합니다. 8.3에서 8.3.6 버전 사이에서, 도형을 변경했을 때 경계 상자 캐시를 항상 재계산하지 않거나 덤프/리로드 작업 없이 새로운 버전으로 업그레이드시 이미 오류가 발생한 경계 상자를 수정하지 못 하는 등 이런 종류의 오류 발생이 관찰됐습니다. 따라서 다음 쿼리를 통해 오류를 직접 수정하고 경계 상자를 다시 추가하거나, 또는 덤프/리로드 작업을 할 수 있습니다.

This method supports Circular Strings and Curves.

예시

This example drops cached bounding boxes where the stored box is wrong. Applying Box2D to ST_AsBinary forces a fresh box calculation, while Box2D on the table geometry reads the cached box.

Code
UPDATE sometable
SET geom =  PostGIS_DropBBox(geom)
WHERE Not (Box2D(ST_AsBinary(geom)) = Box2D(geom));
래스터 출력
UPDATE ...

After dropping corrupt cached boxes, re-add them where needed.

Code
UPDATE sometable
SET geom =  PostGIS_AddBBox(geom)
WHERE Not PostGIS_HasBBOX(geom);
래스터 출력
UPDATE ...

제목

PostGIS_HasBBox — 해당 도형의 경계 상자가 캐시화된 경우 참을 반환하고, 그렇지 않을 경우 거짓을 반환합니다.

요약

boolean PostGIS_HasBBox(geometry geomA);

설명

해당 도형의 경계 상자가 캐시화된 경우 참을 반환하고, 그렇지 않을 경우 거짓을 반환합니다. 캐시 작업을 제어하려면 PostGIS_AddBBoxPostGIS_DropBBox 를 이용하십시오.

This method supports Circular Strings and Curves.

예시

Code
SELECT geom
FROM sometable WHERE PostGIS_HasBBox(geom) = false;

8장. SFCGAL Functions Reference

SFCGAL은 고급 2D 및 3D 함수를 제공하는 CGAL을 둘러싼 C++ 래퍼(wrapper) 라이브러리입니다. 강력한 기능을 위해, 도형 좌표가 정밀한 유리수 표현식을 가지고 있습니다.

SFCGAL 홈페이지 http://www.sfcgal.org 에서 이 라이브러리의 설치 지침을 찾아볼 수 있습니다. 함수들을 로드하려면 확장 프로그램 postgis_sfcgal을 생성하십시오.

8.1. SFCGAL Management Functions

초록

This section lists functions for determining version of SFCGAL and library dependencies you are running.

제목

postgis_sfcgal_version — 실행중인 SFCGAL의 버전을 반환합니다.

요약

text postgis_sfcgal_version(void);

설명

실행중인 SFCGAL의 버전을 반환합니다.

2.1.0 버전부터 사용할 수 있습니다.

This method needs SFCGAL backend.


제목

postgis_sfcgal_full_version — Returns the full version of SFCGAL in use including CGAL and Boost versions

요약

text postgis_sfcgal_version(void);

설명

Returns the full version of SFCGAL in use including CGAL and Boost versions

Availability: 3.3.0

This method needs SFCGAL backend.

8.2. SFCGAL Accessors and Setters

초록

These functions access or set properties of geometries. Geometries primarily supported by these functions are TINS and Polyhedral Surfaces.

  • CG_ForceLHR — LHR(Left Hand Reverse; 시계 방향) 방향을 강제합니다.
  • CG_IsPlanar — 표면이 평면인지 아닌지 확인합니다.
  • CG_IsSolid — 도형이 입체인지 테스트합니다. 어떤 유효성 검사도 수행하지 않습니다.
  • CG_MakeSolid — 도형을 입체로 지정합니다. 어떤 확인 작업도 수행하지 않습니다. 유효한 입체를 얻으려면, 입력 도형이 닫힌 다면체 표면 또는 닫힌 TIN이어야만 합니다.
  • CG_Orientation — 표면의 방향(orientation)을 결정합니다.
  • CG_Area — Calculates the area of a geometry
  • CG_3DArea — 3차원 표면 도형의 면적을 계산합니다. 입체일 경우 0을 반환할 것입니다.
  • CG_Volume — Computes the volume of a 3D geometry. Closed surfaces can have non-zero volume.

제목

CG_ForceLHR — LHR(Left Hand Reverse; 시계 방향) 방향을 강제합니다.

요약

geometry CG_ForceLHR(geometry geom);

설명

Returns an equivalent geometry whose polygonal components follow the left-hand rule: exterior rings are counter-clockwise and interior rings are clockwise. Rings are reversed as needed; coordinates and dimensionality are preserved. The input must be valid.

Availability: 3.5.0

This method needs SFCGAL backend.

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

Reorient a polygon and its hole to the left-hand rule.

Code
WITH data AS (
  SELECT 'POLYGON((0 0,0 4,4 4,4 0,0 0),
                  (1 1,3 1,3 3,1 3,1 1))'::geometry AS geom
)
SELECT geom AS input_polygon,
       CG_ForceLHR(geom) AS lhr_polygon,
       ST_IsPolygonCCW(geom) AS input_is_lhr,
       ST_IsPolygonCCW(CG_ForceLHR(geom)) AS output_is_lhr
FROM data;
래스터 출력
POLYGON((0 0,0 4,4 4,4 0,0 0),(1 1,3 1,3 3,1 3,1 1)) | POLYGON((0 0,4 0,4 4,0 4,0 0),(1 1,1 3,3 3,3 1,1 1)) | f | t
Figure
Geometry figure for visual-cg-forcelhr-01

제목

CG_IsPlanar — 표면이 평면인지 아닌지 확인합니다.

요약

boolean CG_IsPlanar(geometry geom);

설명

Tests whether the input geometry lies in a single plane in 3D.

Availability: 3.5.0

This method needs SFCGAL backend.

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).


제목

CG_IsSolid — 도형이 입체인지 테스트합니다. 어떤 유효성 검사도 수행하지 않습니다.

요약

boolean CG_IsSolid(geometry geom1);

설명

Returns true when the input carries the solid flag, such as a geometry produced by CG_MakeSolid. A closed PolyhedralSurface remains a surface until it is explicitly converted. This tests the representation, not shell closure or validity; no validity check is performed.

Availability: 3.5.0

This method needs SFCGAL backend.

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

Compare the same closed shell before and after converting it to a solid.

Code
WITH data AS (
  SELECT 'POLYHEDRALSURFACE Z (
    ((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)),
    ((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)),
    ((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)),
    ((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)),
    ((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)),
    ((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1))
  )'::geometry AS geom
)
SELECT CG_IsSolid(geom) AS shell_is_solid,
       CG_IsSolid(CG_MakeSolid(geom)) AS solid_is_solid
FROM data;
래스터 출력
f | t
Figure
Geometry figure for visual-cg-issolid-01

제목

CG_MakeSolid — 도형을 입체로 지정합니다. 어떤 확인 작업도 수행하지 않습니다. 유효한 입체를 얻으려면, 입력 도형이 닫힌 다면체 표면 또는 닫힌 TIN이어야만 합니다.

요약

geometry CG_MakeSolid(geometry geom1);

설명

Marks a PolyhedralSurface or TIN as a solid. The input is expected to describe a closed shell; the function sets the solid representation and does not validate the shell.

Availability: 3.5.0

This method needs SFCGAL backend.

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).


제목

CG_Orientation — 표면의 방향(orientation)을 결정합니다.

요약

integer CG_Orientation(geometry geom);

설명

이 함수는 폴리곤에만 적용됩니다. 폴리곤이 반시계 방향이면 -1을, 시계 방향이면 1을 반환합니다.

Availability: 3.5.0

This method needs SFCGAL backend.

This function supports 3d and will not drop the z-index.


제목

CG_Area — Calculates the area of a geometry

요약

double precision CG_Area( geometry geom );

설명

Calculates the area of a geometry.

Performed by the SFCGAL module

[참고]

NOTE: this function returns a double precision value representing the area.

Availability: 3.5.0

This method needs SFCGAL backend.

도형 예시

Code
SELECT CG_Area('Polygon ((0 0,0 5,5 5,5 0,0 0),(1 1,2 1,2 2,1 2,1 1),(3 3,4 3,4 4,3 4,3 3))');
래스터 출력
23
Figure
Geometry figure for visual-cg-area-01

제목

CG_3DArea — 3차원 표면 도형의 면적을 계산합니다. 입체일 경우 0을 반환할 것입니다.

요약

floatCG_3DArea(geometry geom1);

설명

Availability: 3.5.0

This method needs SFCGAL backend.

This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 8.1, 10.5

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

주의: 기본적으로 KWT로부터 빌드된 다면체 표면은 표면 도형이지 입체가 아닙니다. 따라서 표면 면적을 구할 수 있습니다. 입체로 변환하면, 면적을 구할 수 없습니다.

Code
SELECT CG_3DArea(geom) As cube_surface_area,
CG_3DArea(CG_MakeSolid(geom)) As solid_surface_area
FROM (SELECT 'POLYHEDRALSURFACE( ((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)),
((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)),
((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)),
((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)),
((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)),
((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1)) )'::geometry) As f(geom);
래스터 출력
cube_surface_area │ solid_surface_area
──────────────────┼────────────────────
6                 │ 0

제목

CG_Volume — Computes the volume of a 3D geometry. Closed surfaces can have non-zero volume.

요약

float CG_Volume(geometry geom1);

설명

Availability: 3.5.0

This method needs SFCGAL backend.

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 9.1 (same as CG_3DVolume)

Closed surface geometries can have non-zero volume. Use CG_MakeSolid when the geometry value itself must carry the solid flag.

예시

A closed polyhedral surface has volume. CG_MakeSolid makes the solid representation explicit.

Code
SELECT CG_Volume(geom) As cube_surface_vol,
CG_Volume(CG_MakeSolid(geom)) As solid_surface_vol
FROM (SELECT 'POLYHEDRALSURFACE( ((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)),
((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)),
((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)),
((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)),
((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)),
((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1)) )'::geometry) As f(geom);
래스터 출력
cube_surface_vol │ solid_surface_vol
─────────────────┼──────────────────
1                │ 1
Figure
Geometry figure for visual-cg-volume-01

8.3. SFCGAL Processing and Relationship Functions

제목

CG_Intersection — Computes the intersection of two geometries

요약

geometry CG_Intersection( geometry geomA , geometry geomB );

설명

Computes the intersection of two geometries.

Performed by the SFCGAL module

[참고]

NOTE: this function returns a geometry representing the intersection.

Availability: 3.5.0

This method needs SFCGAL backend.

도형 예시

Code
SELECT CG_Intersection('LINESTRING(0 0,5 5)', 'LINESTRING(5 0,0 5)');
래스터 출력
POINT(2.5 2.5)
Figure
Geometry figure for visual-cg-intersection-01

제목

CG_Intersects — Tests if two geometries intersect (they have at least one point in common)

요약

boolean CG_Intersects( geometry geomA , geometry geomB );

설명

Returns true if two geometries intersect. Geometries intersect if they have any point in common.

Performed by the SFCGAL module

[참고]

NOTE: this is the "allowable" version that returns a boolean, not an integer.

Availability: 3.5.0

This method needs SFCGAL backend.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

도형 예시

Code
SELECT CG_Intersects('POINT(0 0)'::geometry, 'LINESTRING ( 2 0,0 2 )'::geometry);
래스터 출력
f
Figure
Geometry figure for visual-cg-intersects-01
Code
SELECT CG_Intersects('POINT(0 0)'::geometry, 'LINESTRING ( 0 0,0 2 )'::geometry);
래스터 출력
t
Figure
Geometry figure for visual-cg-intersects-02

제목

CG_3DIntersects — Tests if two 3D geometries intersect

요약

boolean CG_3DIntersects( geometry geomA , geometry geomB );

설명

Tests if two 3D geometries intersect. 3D geometries intersect if they have any point in common in the three-dimensional space.

Performed by the SFCGAL module

[참고]

NOTE: this is the "allowable" version that returns a boolean, not an integer.

Availability: 3.5.0

This method needs SFCGAL backend.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

도형 예시

Code
SELECT CG_3DIntersects('POINT(1.2 0.1 0)', 'POLYHEDRALSURFACE(((0 0 0,0.5 0.5 0,1 0 0,1 1 0,0 1 0,0 0 0)),((1 0 0,2 0 0,2 1 0,1 1 0,1 0 0),(1.2 0.2 0,1.2 0.8 0,1.8 0.8 0,1.8 0.2 0,1.2 0.2 0)))');
래스터 출력
t
Figure
Geometry figure for visual-cg-3dintersects-01

제목

CG_Difference — Computes the geometric difference between two geometries

요약

geometry CG_Difference( geometry geomA , geometry geomB );

설명

Computes the geometric difference between two geometries. The resulting geometry is a set of points that are present in geomA but not in geomB.

Performed by the SFCGAL module

[참고]

NOTE: this function returns a geometry.

Availability: 3.5.0

This method needs SFCGAL backend.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

도형 예시

Code
SELECT CG_Difference('POLYGON((0 0,0 1,1 1,1 0,0 0))'::geometry, 'LINESTRING(0 0,2 2)'::geometry);
래스터 출력
POLYGON((0 0,1 0,1 1,0 1,0 0))
Figure
Geometry figure for visual-cg-difference-01

제목

CG_3DDifference — 3차원 차이를 수행합니다.

요약

geometry CG_3DDifference(geometry geom1, geometry geom2);

설명

geom2의 일부분이 아닌 geom1의 부분을 반환합니다.

Availability: 3.5.0

This method needs SFCGAL backend.

This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 5.1

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

Subtract a smaller tetrahedral solid and render the two inputs and the actual remaining solid separately.

Code
WITH data AS (
  SELECT CG_MakeSolid('POLYHEDRALSURFACE Z (
    ((0 0 0,0 4 0,4 0 0,0 0 0)),
    ((0 0 0,4 0 0,0 0 4,0 0 0)),
    ((0 0 0,0 0 4,0 4 0,0 0 0)),
    ((4 0 0,0 4 0,0 0 4,4 0 0))
  )'::geometry) AS outer_solid
), solids AS (
  SELECT outer_solid,
         ST_Scale(outer_solid, 0.5, 0.5, 0.5) AS inner_solid
  FROM data
)
SELECT outer_solid AS input_outer,
       inner_solid AS input_inner,
       CG_3DDifference(outer_solid, inner_solid) AS difference
FROM solids;
래스터 출력
POLYHEDRALSURFACE Z (((0 0 0,0 4 0,4 0 0,0 0 0)),((0 0 0,4 0 0,0 0 4,0 0 0)),((0 0 0,0 0 4,0 4 0,0 0 0)),((4 0 0,0 4 0,0 0 4,4 0 0))) | POLYHEDRALSURFACE Z (((0 0 0,0 2 0,2 0 0,0 0 0)),((0 0 0,2 0 0,0 0 2,0 0 0)),((0 0 0,0 0 2,0 2 0,0 0 0)),((2 0 0,0 2 0,0 0 2,2 0 0))) | POLYHEDRALSURFACE Z (((0 2 0,4 0 0,2 0 0,0 2 0)),((0 0 2,2 0 0,0 0 4,0 0 2)),((0 0 2,0 4 0,0 2 0,0 0 2)),((4 0 0,0 4 0,0 0 4,4 0 0)),((4 0 0,0 2 0,0 4 0,4 0 0)),((2 0 0,4 0 0,0 0 4,2 0 0)),((0 4 0,0 0 2,0 0 4,0 4 0)),((0 0 2,0 2 0,2 0 0,0 0 2)))
Figure
Geometry figure for visual-cg-3ddifference-01

제목

CG_Distance — Computes the minimum distance between two geometries

요약

double precision CG_Distance( geometry geomA , geometry geomB );

설명

Computes the minimum distance between two geometries.

Performed by the SFCGAL module

[참고]

NOTE: this function returns a double precision value representing the distance.

Availability: 3.5.0

This method needs SFCGAL backend.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

도형 예시

Code
SELECT CG_Distance('LINESTRING(0.0 0.0,-1.0 -1.0)', 'LINESTRING(3.0 4.0,4.0 5.0)');
래스터 출력
5
Figure
Geometry figure for visual-cg-distance-01

제목

CG_3DDistance — Computes the minimum 3D distance between two geometries

요약

double precision CG_3DDistance( geometry geomA , geometry geomB );

설명

Computes the minimum 3D distance between two geometries.

Performed by the SFCGAL module

[참고]

NOTE: this function returns a double precision value representing the 3D distance.

Availability: 3.5.0

This method needs SFCGAL backend.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

도형 예시

Code
SELECT CG_3DDistance('LINESTRING(-1.0 0.0 2.0,1.0 0.0 3.0)', 'TRIANGLE((-4.0 0.0 1.0,4.0 0.0 1.0,0.0 4.0 1.0,-4.0 0.0 1.0))');
래스터 출력
1
Figure
Geometry figure for visual-cg-3ddistance-01

제목

CG_3DConvexHull — 면 도형의 근사 중심축을 계산합니다.

요약

geometry CG_3DConvexHull(geometry geom1);

설명

Computes the smallest convex three-dimensional geometry that contains the input. Unlike ST_ConvexHull, this function uses Z coordinates when constructing the hull.

Availability: 3.5.0

This method needs SFCGAL backend.

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

Compute the 3D convex hull of a 3D LineString.

Code
WITH data AS (
  SELECT 'LINESTRING Z(0 0 5,1 5 3,5 7 6,9 5 3,5 7 5,6 3 5)'::geometry AS source_line
)
SELECT CG_3DConvexHull(source_line) AS convex_hull
FROM data;
래스터 출력
POLYHEDRALSURFACE Z (((1 5 3,9 5 3,0 0 5,1 5 3)),((1 5 3,0 0 5,5 7 6,1 5 3)),((5 7 6,5 7 5,1 5 3,5 7 6)),((0 0 5,6 3 5,5 7 6,0 0 5)),((6 3 5,9 5 3,5 7 6,6 3 5)),((0 0 5,9 5 3,6 3 5,0 0 5)),((9 5 3,5 7 5,5 7 6,9 5 3)),((1 5 3,5 7 5,9 5 3,1 5 3)))
Figure
Geometry figure for visual-cg-3dconvexhull-01

Compare the extruded source geometry with its 3D convex hull.

Code
WITH footprints(label, geom, height) AS (VALUES
  ('C', 'POLYGON((0 0,0 8,5 8,5 6,2 6,2 2,5 2,5 0,0 0))'::geometry, 3),
  ('H', 'POLYGON((7 0,9 0,9 3,12 3,12 0,14 0,14 8,12 8,12 5,9 5,9 8,7 8,7 0))'::geometry, 7)
), parts AS (
  SELECT label, CG_Extrude(geom, 0, 0, height) AS geom
  FROM footprints
), shapes AS (
  SELECT ST_Collect(geom ORDER BY label) AS source_geometry
  FROM parts
)
SELECT
  source_geometry AS input_source_geometry,
  CG_3DConvexHull(source_geometry) AS convex_hull
FROM shapes;
래스터 출력
-[ RECORD 1 ]----------
input_source_geometry | GEOMETRYCOLLECTION(POLYHEDRALSURFACE(((0 0 0,0 8 0,5 8 0,5 6 0,2 6 0,2 2 0,5 2 0,5 0 0,0 0 0)),((0 0 3,5 0 3,5 2 3,2 2 3,2 6 3,5 6 3,5 8 3,0 8 3,0 0 3)),((0 0 0,0 0 3,0 8 3,0 8 0,0 0 0)),((0 8 0,0 8 3,5 8 3,5 8 0,0 8 0)),((5 8 0,5 8 3,5 6 3,5 6 0,5 8 0)),((5 6 0,5 6 3,2 6 3,2 6 0,5 6 0)),((2 6 0,2 6 3,2 2 3,2 2 0,2 6 0)),((2 2 0,2 2 3,5 2 3,5 2 0,2 2 0)),((5 2 0,5 2 3,5 0 3,5 0 0,5 2 0)),((5 0 0,5 0 3,0 0 3,0 0 0,5 0 0))), POLYHEDRALSURFACE(((7 0 0,7 8 0,9 8 0,9 5 0,12 5 0,12 8 0,14 8 0,14 0 0,12 0 0,12 3 0,9 3 0,9 0 0,7 0 0)),((7 0 7,9 0 7,9 3 7,12 3 7,12 0 7,14 0 7,14 8 7,12 8 7,12 5 7,9 5 7,9 8 7,7 8 7,7 0 7)),((7 0 0,7 0 7,7 8 7,7 8 0,7 0 0)),((7 8 0,7 8 7,9 8 7,9 8 0,7 8 0)),((9 8 0,9 8 7,9 5 7,9 5 0,9 8 0)),((9 5 0,9 5 7,12 5 7,12 5 0,9 5 0)),((12 5 0,12 5 7,12 8 7,12 8 0,12 5 0)),((12 8 0,12 8 7,14 8 7,14 8 0,12 8 0)),((14 8 0,14 8 7,14 0 7,14 0 0,14 8 0)),((14 0 0,14 0 7,12 0 7,12 0 0,14 0 0)),((12 0 0,12 0 7,12 3 7,12 3 0,12 0 0)),((12 3 0,12 3 7,9 3 7,9 3 0,12 3 0)),((9 3 0,9 3 7,9 0 7,9 0 0,9 3 0)),((9 0 0,9 0 7,7 0 7,7 0 0,9 0 0))))
convex_hull           | POLYHEDRALSURFACE(((14 8 7,14 0 0,14 8 0,14 8 7)),((14 0 7,7 8 7,7 0 7,14 0 7)),((0 8 3,7 8 7,0 8 0,0 8 3)),((0 0 3,7 8 7,0 8 3,0 0 3)),((0 0 3,0 8 3,0 0 0,0 0 3)),((7 0 7,7 8 7,0 0 3,7 0 7)),((14 0 7,14 0 0,14 8 7,14 0 7)),((7 0 7,14 0 0,14 0 7,7 0 7)),((14 8 7,7 8 7,14 0 7,14 8 7)),((0 0 0,0 8 3,0 8 0,0 0 0)),((0 0 0,14 0 0,0 0 3,0 0 0)),((0 0 3,14 0 0,7 0 7,0 0 3)),((0 8 0,14 0 0,0 0 0,0 8 0)),((14 8 0,14 0 0,0 8 0,14 8 0)),((14 8 0,7 8 7,14 8 7,14 8 0)),((0 8 0,7 8 7,14 8 0,0 8 0)))
Figure
Geometry figure for visual-cg-3dconvexhull-02

제목

CG_3DIntersection — 3차원 교차를 수행합니다.

요약

geometry CG_3DIntersection(geometry geom1, geometry geom2);

설명

geom1과 geom2가 공유하는 부분을 도형으로 반환합니다.

Availability: 3.5.0

This method needs SFCGAL backend.

This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 5.1

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

3D linestrings and polygons can intersect in a 3D segment.

Code
WITH data AS (
  SELECT 'LINESTRING Z (2 2 6,1.5 1.5 7,1 1 8,0.5 0.5 8,0 0 10)'::geometry AS input_linestring,
         'POLYGON Z ((0 0 8,0 1 8,1 1 8,1 0 8,0 0 8))'::geometry AS input_polygon
)
SELECT input_linestring AS input_linestring,
       input_polygon AS input_polygon,
       CG_3DIntersection(input_linestring, input_polygon) AS intersection
FROM data;
래스터 출력
LINESTRING Z (2 2 6,1.5 1.5 7,1 1 8,0.5 0.5 8,0 0 10) | POLYGON Z ((0 0 8,0 1 8,1 1 8,1 0 8,0 0 8)) | LINESTRING Z (1 1 8,0.5 0.5 8)
Figure
Geometry figure for visual-cg-3dintersection-01

Intersect a cube shell with a vertical polygon.

Code
WITH data AS (
  SELECT 'POLYHEDRALSURFACE Z(
    ((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)),
    ((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)),
    ((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)),
    ((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)),
    ((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)),
    ((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1))
  )'::geometry AS input_cube,
  'POLYGON Z ((0 0 0,0 0 0.5,0 0.5 0.5,0 0.5 0,0 0 0))'::geometry AS input_polygon
)
SELECT input_cube AS input_cube,
       input_polygon AS input_polygon,
       CG_3DIntersection(input_cube, input_polygon) AS intersection
FROM data;
래스터 출력
POLYHEDRALSURFACE Z (((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)),((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)),((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)),((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)),((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)),((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1))) | POLYGON Z ((0 0 0,0 0 0.5,0 0.5 0.5,0 0.5 0,0 0 0)) | TIN Z (((0 0 0,0 0 0.5,0 0.5 0.5,0 0 0)),((0 0.5 0,0 0 0,0 0.5 0.5,0 0.5 0)))
Figure
Geometry figure for visual-cg-3dintersection-02

A smaller solid contained by a larger solid remains volumetric after intersection.

Code
WITH data AS (
  SELECT CG_MakeSolid('POLYHEDRALSURFACE Z (
    ((0 0 0,0 4 0,4 0 0,0 0 0)),
    ((0 0 0,4 0 0,0 0 4,0 0 0)),
    ((0 0 0,0 0 4,0 4 0,0 0 0)),
    ((4 0 0,0 4 0,0 0 4,4 0 0))
  )'::geometry) AS outer_solid
), solids AS (
  SELECT outer_solid,
         ST_Scale(outer_solid, 0.5, 0.5, 0.5) AS inner_solid
  FROM data
)
SELECT outer_solid AS input_outer,
       inner_solid AS input_inner,
       CG_3DIntersection(outer_solid, inner_solid) AS intersection
FROM solids;
래스터 출력
POLYHEDRALSURFACE Z (((0 0 0,0 4 0,4 0 0,0 0 0)),((0 0 0,4 0 0,0 0 4,0 0 0)),((0 0 0,0 0 4,0 4 0,0 0 0)),((4 0 0,0 4 0,0 0 4,4 0 0))) | POLYHEDRALSURFACE Z (((0 0 0,0 2 0,2 0 0,0 0 0)),((0 0 0,2 0 0,0 0 2,0 0 0)),((0 0 0,0 0 2,0 2 0,0 0 0)),((2 0 0,0 2 0,0 0 2,2 0 0))) | POLYHEDRALSURFACE Z (((0 0 0,0 2 0,2 0 0,0 0 0)),((0 0 0,0 0 2,0 2 0,0 0 0)),((2 0 0,0 0 2,0 0 0,2 0 0)),((2 0 0,0 2 0,0 0 2,2 0 0)))
Figure
Geometry figure for visual-cg-3dintersection-03

제목

CG_Union — Computes the union of two geometries

요약

geometry CG_Union( geometry geomA , geometry geomB );

설명

Computes the union of two geometries.

Performed by the SFCGAL module

[참고]

NOTE: this function returns a geometry representing the union.

Availability: 3.5.0

This method needs SFCGAL backend.

도형 예시

Code
SELECT CG_Union('POINT(.5 0)', 'LINESTRING(-1 0,1 0)');
래스터 출력
LINESTRING(-1 0,0.5 0,1 0)
Figure
Geometry figure for visual-cg-union-01

제목

CG_3DUnion — Perform 3D union using postgis_sfcgal.

요약

geometry CG_3DUnion(geometry geom1, geometry geom2);

geometry CG_3DUnion(geometry set g1field);

설명

Availability: 3.5.0

This method needs SFCGAL backend.

This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 5.1

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

Aggregate variant: returns a geometry that is the 3D union of a rowset of geometries. The CG_3DUnion() function is an "aggregate" function in the terminology of PostgreSQL. That means that it operates on rows of data, in the same way the SUM() and AVG() functions do and like most aggregates, it also ignores NULL geometries.

예시

Union two overlapping tetrahedral solids.

Code
WITH solids AS (
  SELECT CG_MakeSolid('POLYHEDRALSURFACE Z (
           ((0 0 0,4 0 0,0 4 0,0 0 0)),
           ((0 0 0,0 0 4,4 0 0,0 0 0)),
           ((0 0 0,0 4 0,0 0 4,0 0 0)),
           ((4 0 0,0 0 4,0 4 0,4 0 0)))'::geometry) AS geom1,
         CG_MakeSolid('POLYHEDRALSURFACE Z (
           ((2 0 0,6 0 0,2 4 0,2 0 0)),
           ((2 0 0,2 0 4,6 0 0,2 0 0)),
           ((2 0 0,2 4 0,2 0 4,2 0 0)),
           ((6 0 0,2 0 4,2 4 0,6 0 0)))'::geometry) AS geom2
)
SELECT CG_3DUnion(geom1, geom2) AS union_result
FROM solids;
래스터 출력
POLYHEDRALSURFACE Z (((2 0 0,0 0 0,2 2 0,2 0 0)),((2 0 2,0 0 0,2 0 0,2 0 2)),((0 0 4,0 4 0,0 0 0,0 0 4)),((2 0 2,0 4 0,0 0 4,2 0 2)),((0 4 0,2 2 0,0 0 0,0 4 0)),((2 2 0,0 4 0,2 0 2,2 2 0)),((0 0 0,2 0 2,0 0 4,0 0 0)),((4 0 0,2 0 0,2 2 0,4 0 0)),((4 0 0,2 0 2,2 0 0,4 0 0)),((4 0 0,2 2 0,6 0 0,4 0 0)),((2 0 2,4 0 0,2 0 4,2 0 2)),((2 0 2,2 4 0,2 2 0,2 0 2)),((2 4 0,2 0 4,6 0 0,2 4 0)),((2 2 0,2 4 0,6 0 0,2 2 0)),((2 4 0,2 0 2,2 0 4,2 4 0)),((4 0 0,6 0 0,2 0 4,4 0 0)))
Figure
Geometry figure for visual-cg-3dunion-01

제목

CG_AlphaShape — Computes an Alpha-shape enclosing a geometry

요약

geometry CG_AlphaShape(geometry geom, float alpha, boolean allow_holes = false);

설명

Computes the Alpha-Shape of the points in a geometry. An alpha-shape is a (usually) concave polygonal geometry which contains all the vertices of the input, and whose vertices are a subset of the input vertices. An alpha-shape provides a closer fit to the shape of the input than the shape produced by the convex hull.

The "closeness of fit" is controlled by the alpha parameter, which can have values from 0 to infinity. Smaller alpha values produce more concave results. Alpha values greater than some data-dependent value produce the convex hull of the input.

[참고]

Following the CGAL implementation, the alpha value is the square of the radius of the disc used in the Alpha-Shape algorithm to "erode" the Delaunay Triangulation of the input points. See CGAL Alpha-Shapes for more information. This is different from the original definition of alpha-shapes, which defines alpha as the radius of the eroding disc.

The computed shape does not contain holes unless the optional allow_holes argument is specified as true.

This function effectively computes a concave hull of a geometry in a similar way to ST_ConcaveHull, but uses CGAL and a different algorithm.

Availability: 3.5.0 - requires SFCGAL >= 1.4.1.

This method needs SFCGAL backend.

예시

The original point cloud and the alpha-shape share one comparison frame.

Code
WITH data AS (
  SELECT 'MULTIPOINT((63 84),(76 88),(68 73),(53 18),(91 50),(81 70),
(88 29),(24 82),(32 51),(37 23),(27 54),(84 19),(75 87),(44 42),(77 67),(90 30),(36 61),(32 65),
(81 47),(88 58),(68 73),(49 95),(81 60),(87 50),
(78 16),(79 21),(30 22),(78 43),(26 85),(48 34),(35 35),(36 40),(31 79),(83 29),(27 84),(52 98),(72 95),(85 71),
(75 84),(75 77),(81 29),(77 73),(41 42),(83 72),(23 36),(89 53),(27 57),(57 97),(27 77),(39 88),(60 81),
(80 72),(54 32),(55 26),(62 22),(70 20),(76 27),(84 35),(87 42),(82 54),(83 64),(69 86),(60 90),(50 86),(43 80),(36 73),
(36 68),(40 75),(24 67),(23 60),(26 44),(28 33),(40 32),(43 19),(65 16),(73 16),(38 46),(31 59),(34 86),(45 90),(64 97))'::geometry AS input_points
)
SELECT input_points AS input_points,

         CG_AlphaShape(input_points, 80.2) AS alpha_shape
FROM data;
래스터 출력
MULTIPOINT((63 84),(76 88),(68 73),(53 18),(91 50),(81 70),(88 29),(24 82),(32 51),(37 23),(27 54),(84 19),(75 87),(44 42),(77 67),(90 30),(36 61),(32 65),(81 47),(88 58),(68 73),(49 95),(81 60),(87 50),(78 16),(79 21),(30 22),(78 43),(26 85),(48 34),(35 35),(36 40),(31 79),(83 29),(27 84),(52 98),(72 95),(85 71),(75 84),(75 77),(81 29),(77 73),(41 42),(83 72),(23 36),(89 53),(27 57),(57 97),(27 77),(39 88),(60 81),(80 72),(54 32),(55 26),(62 22),(70 20),(76 27),(84 35),(87 42),(82 54),(83 64),(69 86),(60 90),(50 86),(43 80),(36 73),(36 68),(40 75),(24 67),(23 60),(26 44),(28 33),(40 32),(43 19),(65 16),(73 16),(38 46),(31 59),(34 86),(45 90),(64 97)) | MULTIPOLYGON(((89 53,88 58,85 71,83 72,75 84,76 88,72 95,64 97,57 97,52 98,49 95,45 90,39 88,34 86,26 85,24 82,27 77,24 67,23 60,27 54,26 44,23 36,28 33,30 22,37 23,43 19,53 18,65 16,73 16,78 16,84 19,88 29,90 30,87 42,91 50,89 53)))
Figure
Geometry figure for visual-cg-alphashape-01

The same point cloud can produce a shape with a hole when holes are allowed.

Code
WITH data AS (
  SELECT 'MULTIPOINT((63 84),(76 88),(68 73),(53 18),(91 50),(81 70),(88 29),(24 82),(32 51),(37 23),(27 54),(84 19),(75 87),(44 42),(77 67),(90 30),(36 61),(32 65),(81 47),(88 58),(68 73),(49 95),(81 60),(87 50),
(78 16),(79 21),(30 22),(78 43),(26 85),(48 34),(35 35),(36 40),(31 79),(83 29),(27 84),(52 98),(72 95),(85 71),
(75 84),(75 77),(81 29),(77 73),(41 42),(83 72),(23 36),(89 53),(27 57),(57 97),(27 77),(39 88),(60 81),
(80 72),(54 32),(55 26),(62 22),(70 20),(76 27),(84 35),(87 42),(82 54),(83 64),(69 86),(60 90),(50 86),(43 80),(36 73),
(36 68),(40 75),(24 67),(23 60),(26 44),(28 33),(40 32),(43 19),(65 16),(73 16),(38 46),(31 59),(34 86),(45 90),(64 97))'::geometry AS input_points
)
SELECT input_points AS input_points,

         CG_AlphaShape(input_points, 100.1, true) AS alpha_shape
FROM data;
래스터 출력
MULTIPOINT((63 84),(76 88),(68 73),(53 18),(91 50),(81 70),(88 29),(24 82),(32 51),(37 23),(27 54),(84 19),(75 87),(44 42),(77 67),(90 30),(36 61),(32 65),(81 47),(88 58),(68 73),(49 95),(81 60),(87 50),(78 16),(79 21),(30 22),(78 43),(26 85),(48 34),(35 35),(36 40),(31 79),(83 29),(27 84),(52 98),(72 95),(85 71),(75 84),(75 77),(81 29),(77 73),(41 42),(83 72),(23 36),(89 53),(27 57),(57 97),(27 77),(39 88),(60 81),(80 72),(54 32),(55 26),(62 22),(70 20),(76 27),(84 35),(87 42),(82 54),(83 64),(69 86),(60 90),(50 86),(43 80),(36 73),(36 68),(40 75),(24 67),(23 60),(26 44),(28 33),(40 32),(43 19),(65 16),(73 16),(38 46),(31 59),(34 86),(45 90),(64 97)) | MULTIPOLYGON(((89 53,88 58,85 71,83 72,75 84,76 88,72 95,64 97,57 97,52 98,49 95,45 90,39 88,34 86,26 85,24 82,27 77,24 67,23 60,27 54,26 44,23 36,28 33,30 22,43 19,53 18,65 16,73 16,78 16,84 19,90 30,87 42,91 50,89 53),(36 68,40 75,43 80,60 81,68 73,77 67,81 60,82 54,81 47,78 43,76 27,62 22,54 32,44 42,38 46,36 61,36 68)))
Figure
Geometry figure for visual-cg-alphashape-02

The second documented point cloud also produces a holed alpha-shape.

Code
WITH data AS (
  SELECT 'MULTIPOINT ((132 64),(114 64),(99 64),(81 64),(63 64),(57 49),(52 36),(46 20),(37 20),(26 20),(32 36),(39 55),(43 69),(50 84),(57 100),(63 118),(68 133),(74 149),(81 164),(88 180),(101 180),(112 180),(119 164),(126 149),(132 131),(139 113),(143 100),(150 84),(157 69),(163 51),(168 36),(174 20),(163 20),(150 20),(143 36),(139 49),(132 64),(99 151),(92 138),(88 124),(81 109),(74 93),(70 82),(83 82),(99 82),(112 82),(126 82),(121 96),(114 109),(110 122),(103 138),(99 151),(34 27),(43 31),(48 44),(46 58),(52 73),(63 73),(61 84),(72 71),(90 69),(101 76),(123 71),(141 62),(166 27),(150 33),(159 36),(146 44),(154 53),(152 62),(146 73),(134 76),(143 82),(141 91),(130 98),(126 104),(132 113),(128 127),(117 122),(112 133),(119 144),(108 147),(119 153),(110 171),(103 164),(92 171),(86 160),(88 142),(79 140),(72 124),(83 131),(79 118),(68 113),(63 102),(68 93),(35 45))'::geometry AS input_points
)
SELECT input_points AS input_points,

         CG_AlphaShape(input_points, 102.2, true) AS alpha_shape
FROM data;
래스터 출력
MULTIPOINT((132 64),(114 64),(99 64),(81 64),(63 64),(57 49),(52 36),(46 20),(37 20),(26 20),(32 36),(39 55),(43 69),(50 84),(57 100),(63 118),(68 133),(74 149),(81 164),(88 180),(101 180),(112 180),(119 164),(126 149),(132 131),(139 113),(143 100),(150 84),(157 69),(163 51),(168 36),(174 20),(163 20),(150 20),(143 36),(139 49),(132 64),(99 151),(92 138),(88 124),(81 109),(74 93),(70 82),(83 82),(99 82),(112 82),(126 82),(121 96),(114 109),(110 122),(103 138),(99 151),(34 27),(43 31),(48 44),(46 58),(52 73),(63 73),(61 84),(72 71),(90 69),(101 76),(123 71),(141 62),(166 27),(150 33),(159 36),(146 44),(154 53),(152 62),(146 73),(134 76),(143 82),(141 91),(130 98),(126 104),(132 113),(128 127),(117 122),(112 133),(119 144),(108 147),(119 153),(110 171),(103 164),(92 171),(86 160),(88 142),(79 140),(72 124),(83 131),(79 118),(68 113),(63 102),(68 93),(35 45)) | MULTIPOLYGON(((168 36,163 51,157 69,150 84,143 100,139 113,132 131,126 149,119 164,112 180,101 180,88 180,81 164,74 149,68 133,63 118,57 100,50 84,43 69,39 55,35 45,32 36,26 20,37 20,46 20,52 36,57 49,63 64,81 64,90 69,99 64,114 64,132 64,139 49,143 36,150 20,163 20,174 20,168 36),(81 109,88 124,92 138,103 138,110 122,114 109,121 96,112 82,99 82,83 82,74 93,81 109)))
Figure
Geometry figure for visual-cg-alphashape-03

제목

CG_ApproxConvexPartition — Computes approximal convex partition of the polygon geometry

요약

geometry CG_ApproxConvexPartition(geometry geom);

설명

Computes approximal convex partition of the polygon geometry (using a triangulation).

[참고]

A partition of a polygon P is a set of polygons such that the interiors of the polygons do not intersect and the union of the polygons is equal to the interior of the original polygon P. CG_ApproxConvexPartition and CG_GreeneApproxConvexPartition functions produce approximately optimal convex partitions. Both these functions produce convex decompositions by first decomposing the polygon into simpler polygons; CG_ApproxConvexPartition uses a triangulation and CG_GreeneApproxConvexPartition a monotone partition. These two functions both guarantee that they will produce no more than four times the optimal number of convex pieces but they differ in their runtime complexities. Though the triangulation-based approximation algorithm often results in fewer convex pieces, this is not always the case.

Availability: 3.5.0 - requires SFCGAL >= 1.5.0.

Requires SFCGAL >= 1.5.0

This method needs SFCGAL backend.

예시

Approximate convex partition of the same polygon used by the other partition examples.

Code
WITH data AS (
  SELECT 'POLYGON((156 150,83 181,89 131,148 120,107 61,32 159,0 45,41 86,45 1,177 2,67 24,109 31,170 60,180 110,156 150))'::geometry AS input_polygon
)
SELECT input_polygon AS input_polygon,
       CG_ApproxConvexPartition(input_polygon) AS partition
FROM data;
래스터 출력
POLYGON((156 150,83 181,89 131,148 120,107 61,32 159,0 45,41 86,45 1,177 2,67 24,109 31,170 60,180 110,156 150)) | GEOMETRYCOLLECTION(POLYGON((156 150,83 181,89 131,148 120,156 150)), POLYGON((32 159,0 45,41 86,32 159)), POLYGON((107 61,32 159,41 86,107 61)), POLYGON((45 1,177 2,67 24,45 1)), POLYGON((41 86,45 1,67 24,41 86)), POLYGON((107 61,41 86,67 24,109 31,107 61)), POLYGON((148 120,107 61,109 31,170 60,148 120)), POLYGON((156 150,148 120,170 60,180 110,156 150)))
Figure
Geometry figure for visual-cg-approxconvexpartition-01

제목

CG_ApproximateMedialAxis — 면 도형의 근사 중심축을 계산합니다.

요약

geometry CG_ApproximateMedialAxis(geometry geom);

geometry CG_ApproximateMedialAxis(geometry geom, boolean projected);

설명

Return an approximate medial axis for the areal input based on its straight skeleton. Uses an SFCGAL specific API when built against a capable version (1.2.0+). Otherwise the function is just a wrapper around CG_StraightSkeleton (slower case).

When projected is true, free endpoints of the medial axis are extended to reach the polygon boundary (projected medial axis). Requires SFCGAL 2.3.0+. When built against an older SFCGAL version, a notice is emitted and the non-projected result is returned instead.

Availability: 3.5.0

Availability: 3.7.0 - projected parameter. Requires SFCGAL >= 2.3.0 for projected result; falls back to non-projected with a notice on older versions.

[참고]

This function ignores the Z dimension. It always gives a 2D result even when used on a 3D geometry.

This method needs SFCGAL backend.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

A polygon and its approximate medial axis.

Code
WITH data AS (
  SELECT 'POLYGON((190 190,10 190,10 10,190 10,190 20,160 30,60 30,60 130,190 140,190 190))'::geometry AS polygon
)
SELECT polygon AS input_polygon,
       CG_ApproximateMedialAxis(polygon) AS medial_axis
FROM data;
래스터 출력
POLYGON((190 190,10 190,10 10,190 10,190 20,160 30,60 30,60 130,190 140,190 190)) | MULTILINESTRING((184.189 15.811,158.377 20),(50 20,158.377 20),(50 20,35 35),(35 153.151,35 35),(35 153.151,40.697 159.303),(164.04 164.04,40.697 159.303))
Figure
Geometry figure for visual-cg-approximatemedialaxis-01

This example computes the projected medial axis with free endpoints extended to the polygon boundary.

Code
SELECT CG_ApproximateMedialAxis('POLYGON((0 0,2 0,2 1,0 1,0 0))', true);
래스터 출력
MULTILINESTRING((0 0.5,0.5 0.5,1.5 0.5,2 0.5))
Figure
Geometry figure for visual-cg-approximatemedialaxis-02

제목

CG_GenerateFlatRoof — Generate a flat (box) roof from a footprint polygon.

요약

geometry CG_GenerateFlatRoof(geometry geom, float8 height);

설명

Generate a flat (box-shaped) roof as a 3D PolyhedralSurface Z from a 2D footprint polygon. The roof height above the ground plane is given by height (default 3.0).

Availability: 3.7.0 - requires SFCGAL >= 2.3.0.

This method needs SFCGAL backend.

This function supports Polyhedral surfaces.

예시

Generate a flat roof two units above a rectangular footprint.

Code
WITH data AS (
  SELECT 'POLYGON((0 0,5 0,5 4,0 4,0 0))'::geometry AS footprint
)
SELECT CG_GenerateFlatRoof(footprint, 2.0) AS roof
FROM data;
래스터 출력
POLYHEDRALSURFACE Z (((0 0 0,0 4 0,5 4 0,5 0 0,0 0 0)),((0 0 2,5 0 2,5 4 2,0 4 2,0 0 2)),((0 0 0,0 0 2,0 4 2,0 4 0,0 0 0)),((0 4 0,0 4 2,5 4 2,5 4 0,0 4 0)),((5 4 0,5 4 2,5 0 2,5 0 0,5 4 0)),((5 0 0,5 0 2,0 0 2,0 0 0,5 0 0)))
Figure
Geometry figure for visual-cg-generateflatroof-01

제목

CG_GenerateHippedRoof — Generate a hipped roof from a footprint polygon.

요약

geometry CG_GenerateHippedRoof(geometry geom, float8 height);

설명

Generate a hipped roof as a 3D PolyhedralSurface Z from a 2D footprint polygon. All sides slope upward to meet at a ridge or apex. The roof height is given by height (default 3.0).

Availability: 3.7.0 - requires SFCGAL >= 2.3.0.

This method needs SFCGAL backend.

This function supports Polyhedral surfaces.

예시

The footprint and hipped roof are shown side-by-side so the generated 3D faces do not hide behind the input footprint.

Code
WITH data AS (
  SELECT 'POLYGON((0 0,5 0,5 4,0 4,0 0))'::geometry AS input_footprint
)
SELECT input_footprint AS input_footprint,
       CG_GenerateHippedRoof(input_footprint, 2.0) AS hipped_roof
FROM data;
래스터 출력
POLYGON((0 0,5 0,5 4,0 4,0 0)) | POLYHEDRALSURFACE Z (((0 4 0,5 4 0,5 0 0,0 0 0,0 4 0)),((0 4 0,0 0 0,2 2 2,0 4 0)),((0 0 0,5 0 0,3 2 2,2 2 2,0 0 0)),((5 0 0,5 4 0,3 2 2,5 0 0)),((5 4 0,0 4 0,2 2 2,3 2 2,5 4 0)))
Figure
Geometry figure for visual-cg-generatehippedroof-01

제목

CG_GenerateGableRoof — Generate a gable roof from a footprint polygon.

요약

geometry CG_GenerateGableRoof(geometry geom, float8 height, float8 slope_angle);

설명

Generate a gable roof as a 3D PolyhedralSurface Z from a 2D footprint polygon. Two opposite sides are vertical gable ends; the other two sides slope to a horizontal ridge. height sets the ridge height above the ground (default 3.0) and slope_angle controls the pitch in degrees (default 30.0). The SRID of the input geometry is preserved.

Availability: 3.7.0 - requires SFCGAL >= 2.3.0.

This method needs SFCGAL backend.

This function supports Polyhedral surfaces.

예시

Generate a gable roof using a height of 2 and a 30 degree slope.

Code
WITH data AS (
  SELECT 'POLYGON((0 0,5 0,5 4,0 4,0 0))'::geometry AS footprint
)
SELECT CG_GenerateGableRoof(footprint, 2.0, 30.0) AS roof
FROM data;
래스터 출력
POLYHEDRALSURFACE Z (((5 4 0,5 0 0,0 0 0,0 4 0,5 4 0)),((0 4 0,0 0 0,0 2 1.155,0 4 0)),((0 0 0,5 0 0,5 2 1.155,0 2 1.155,0 0 0)),((5 0 0,5 4 0,5 2 1.155,5 0 0)),((5 4 0,0 4 0,0 2 1.155,5 2 1.155,5 4 0)))
Figure
Geometry figure for visual-cg-generategableroof-01

제목

CG_GenerateSkillionRoof — Generate a skillion (single-slope) roof from a footprint polygon.

요약

geometry CG_GenerateSkillionRoof(geometry geom, float8 height, float8 slope_angle, integer primary_edge_index);

설명

Generate a skillion (single-slope, shed-style) roof as a 3D PolyhedralSurface Z from a 2D footprint polygon. The entire roof surface slopes in one direction. height sets the maximum ridge height (default 3.0), slope_angle sets the pitch in degrees (default 30.0), and primary_edge_index selects which polygon edge defines the high side (0-based, default 0).

When the combination of height and slope_angle would cause a side wall to vanish (the slope reaches the far edge before the full height is achieved), that face is omitted from the result. This means the number of output patches can vary depending on the parameters — a lower height relative to the footprint depth produces more faces than a taller, steeper configuration.

Availability: 3.7.0 - requires SFCGAL >= 2.3.0.

This method needs SFCGAL backend.

This function supports Polyhedral surfaces.

예시

Height 2.0 produces 6 faces (all walls present); height 4.0 produces 5 faces (one side wall is filtered out because the slope reaches the far edge before the full height).

Code
SELECT
  ST_NumPatches(CG_GenerateSkillionRoof(
    'POLYGON((0 0,5 0,5 4,0 4,0 0))', 2.0)) AS "height 2",
  ST_NumPatches(CG_GenerateSkillionRoof(
    'POLYGON((0 0,5 0,5 4,0 4,0 0))', 4.0)) AS "height 4";
래스터 출력
6 | 5

The height 2.0 result is shown with its footprint.

Code
WITH data AS (
  SELECT 'POLYGON((0 0,5 0,5 4,0 4,0 0))'::geometry AS footprint
)
SELECT CG_GenerateSkillionRoof(footprint, 2.0) AS roof
FROM data;
래스터 출력
POLYHEDRALSURFACE Z (((0 4 0,5 4 0,5 0 0,0 0 0,0 4 0)),((5 0 2,5 4 2,3.464 4 2,3.464 0 2,5 0 2)),((0 4 0,0 0 0,3.464 0 2,3.464 4 2,0 4 0)),((0 0 0,5 0 0,5 0 2,3.464 0 2,0 0 0)),((5 0 0,5 4 0,5 4 2,5 0 2,5 0 0)),((5 4 0,0 4 0,3.464 4 2,5 4 2,5 4 0)))
Figure
Geometry figure for visual-cg-generateskillionroof-02

제목

CG_GenerateRoof — Generate a roof of the requested type from a footprint polygon.

요약

geometry CG_GenerateRoof(geometry geom, text roof_type, float8 height, float8 slope_angle, integer primary_edge_index);

설명

Generate a roof as a 3D PolyhedralSurface Z from a 2D footprint polygon. The roof_type parameter selects the roof style (default 'HIPPED'):

  • FLAT — flat box roof.

  • HIPPED — hipped roof (all sides slope to apex).

  • GABLE — gable roof (two sloping sides, two vertical ends).

  • SKILLION — single-slope (shed) roof.

height sets the roof height (default 3.0), slope_angle sets the pitch in degrees (default 30.0), and primary_edge_index selects the reference edge for skillion roofs (default 0).

Availability: 3.7.0 - requires SFCGAL >= 2.3.0.

This method needs SFCGAL backend.

This function supports Polyhedral surfaces.

예시

The generic dispatcher returns the same 3D roofs as the specialized helpers for the same footprint.

Code
WITH data AS (
  SELECT 'POLYGON((0 0,4 0,4 4,0 4,0 0))'::geometry AS input_footprint
)
SELECT input_footprint AS input_footprint,
       CG_GenerateRoof(input_footprint, 'HIPPED', 2.0, 30.0, 0) AS hipped_roof,
       CG_GenerateRoof(input_footprint, 'FLAT', 2.0, 30.0, 0) AS flat_roof
FROM data;
래스터 출력
POLYGON((0 0,4 0,4 4,0 4,0 0)) | POLYHEDRALSURFACE Z (((0 4 0,4 4 0,4 0 0,0 0 0,0 4 0)),((0 4 0,0 0 0,2 2 2,0 4 0)),((0 0 0,4 0 0,2 2 2,0 0 0)),((4 0 0,4 4 0,2 2 2,4 0 0)),((4 4 0,0 4 0,2 2 2,4 4 0))) | POLYHEDRALSURFACE Z (((0 0 0,0 4 0,4 4 0,4 0 0,0 0 0)),((0 0 2,4 0 2,4 4 2,0 4 2,0 0 2)),((0 0 0,0 0 2,0 4 2,0 4 0,0 0 0)),((0 4 0,0 4 2,4 4 2,4 4 0,0 4 0)),((4 4 0,4 4 2,4 0 2,4 0 0,4 4 0)),((4 0 0,4 0 2,0 0 2,0 0 0,4 0 0)))
Figure
Geometry figure for visual-cg-generateroof-01

제목

CG_PolygonRepair — Repair an invalid polygon or multipolygon.

요약

geometry CG_PolygonRepair(geometry geom, text rule);

설명

Repair an invalid polygon or multipolygon using CGAL's 2D Polygon Repair algorithm. Returns a MultiPolygon.

The rule parameter controls the repair strategy:

  • EVEN_ODD (default) — areas covered an odd number of times are kept. Available with CGAL 6.0+.

  • NON_ZERO — areas with non-zero winding number are kept. Requires CGAL 6.1+.

  • UNION — union of all input polygons. Requires CGAL 6.1+.

  • INTERSECTION — intersection of all input polygons. Requires CGAL 6.1+.

Availability: 3.7.0 - requires SFCGAL >= 2.3.0 and CGAL >= 6.0.

This method needs SFCGAL backend.

This function supports Polyhedral surfaces.

예시

Repair a self-intersecting bowtie polygon with the default EVEN_ODD rule.

Code
WITH data AS (
  SELECT 'POLYGON((0 0,2 2,2 0,0 2,0 0))'::geometry AS input_polygon
)
SELECT input_polygon AS input_polygon,
       CG_PolygonRepair(input_polygon) AS repaired_polygon
FROM data;
래스터 출력
POLYGON((0 0,2 2,2 0,0 2,0 0)) | MULTIPOLYGON(((0 0,1 1,0 2,0 0)),((1 1,2 0,2 2,1 1)))
Figure
Geometry figure for visual-cg-polygonrepair-01

With the UNION rule, all winding area is kept. This rule requires CGAL 6.1 or later.

Code
WITH data AS (
  SELECT 'POLYGON((0 0,2 2,2 0,0 2,0 0))'::geometry AS input_polygon
)
SELECT input_polygon AS input_polygon,
       CG_PolygonRepair(input_polygon, 'UNION') AS repaired_polygon
FROM data;
래스터 출력
POLYGON((0 0,2 2,2 0,0 2,0 0)) | MULTIPOLYGON(((0 0,1 1,0 2,0 0)))
Figure
Geometry figure for visual-cg-polygonrepair-02

제목

CG_ConstrainedDelaunayTriangles — Return a constrained Delaunay triangulation around the given input geometry.

요약

geometry CG_ConstrainedDelaunayTriangles(geometry g1);

설명

Return a Constrained Delaunay triangulation around the vertices of the input geometry. Output is a TIN.

This method needs SFCGAL backend.

2.1.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

예시

Constrained Delaunay triangulation of the polygon and buffered point.

Code
SELECT
  CG_ConstrainedDelaunayTriangles(
    ST_Union(
      'POLYGON((175 150,20 40,50 60,125 100,175 150))'::geometry,
      ST_Buffer('POINT(110 170)'::geometry, 20)
    )
  );
래스터 출력
TIN(((50 60,175 150,20 40,50 60)),((125 100,50 60,20 40,125 100)),((50 60,125 100,175 150,50 60)),((130 170,129.6 166.1,175 150,130 170)),((128.5 162.3,175 150,129.6 166.1,128.5 162.3)),((130 170,124.1 155.9,129.6 166.1,130 170)),((126.6 158.9,175 150,128.5 162.3,126.6 158.9)),((129.6 166.1,126.6 158.9,128.5 162.3,129.6 166.1)),((124.1 155.9,175 150,126.6 158.9,124.1 155.9)),((129.6 166.1,124.1 155.9,126.6 158.9,129.6 166.1)),((121.1 153.4,175 150,124.1 155.9,121.1 153.4)),((110 150,121.1 153.4,124.1 155.9,110 150)),((117.7 151.5,175 150,121.1 153.4,117.7 151.5)),((113.9 150.4,117.7 151.5,121.1 153.4,113.9 150.4)),((113.9 150.4,175 150,117.7 151.5,113.9 150.4)),((20 40,113.9 150.4,110 150,20 40)),((20 40,175 150,113.9 150.4,20 40)),((20 40,110 150,106.1 150.4,20 40)),((113.9 150.4,121.1 153.4,110 150,113.9 150.4)),((20 40,106.1 150.4,102.3 151.5,20 40)),((110 150,124.1 155.9,128.5 177.7,110 150)),((20 40,102.3 151.5,98.9 153.4,20 40)),((106.1 150.4,110 150,98.9 153.4,106.1 150.4)),((20 40,98.9 153.4,95.9 155.9,20 40)),((102.3 151.5,106.1 150.4,98.9 153.4,102.3 151.5)),((20 40,95.9 155.9,93.4 158.9,20 40)),((98.9 153.4,110 150,95.9 155.9,98.9 153.4)),((20 40,93.4 158.9,91.5 162.3,20 40)),((95.9 155.9,110 150,102.3 188.5,95.9 155.9)),((20 40,91.5 162.3,90.4 166.1,20 40)),((93.4 158.9,95.9 155.9,91.5 162.3,93.4 158.9)),((20 40,90.4 166.1,90 170,20 40)),((91.5 162.3,95.9 155.9,90 170,91.5 162.3)),((20 40,90 170,90.4 173.9,20 40)),((90.4 166.1,91.5 162.3,90 170,90.4 166.1)),((20 40,90.4 173.9,91.5 177.7,20 40)),((90 170,95.9 155.9,102.3 188.5,90 170)),((90.4 173.9,90 170,91.5 177.7,90.4 173.9)),((91.5 177.7,90 170,102.3 188.5,91.5 177.7)),((93.4 181.1,91.5 177.7,95.9 184.1,93.4 181.1)),((95.9 184.1,91.5 177.7,102.3 188.5,95.9 184.1)),((98.9 186.6,95.9 184.1,102.3 188.5,98.9 186.6)),((102.3 188.5,110 150,128.5 177.7,102.3 188.5)),((106.1 189.6,102.3 188.5,110 190,106.1 189.6)),((110 190,102.3 188.5,117.7 188.5,110 190)),((113.9 189.6,110 190,117.7 188.5,113.9 189.6)),((117.7 188.5,102.3 188.5,128.5 177.7,117.7 188.5)),((121.1 186.6,124.1 184.1,175 150,121.1 186.6)),((121.1 186.6,117.7 188.5,124.1 184.1,121.1 186.6)),((124.1 184.1,126.6 181.1,175 150,124.1 184.1)),((124.1 184.1,117.7 188.5,128.5 177.7,124.1 184.1)),((126.6 181.1,128.5 177.7,175 150,126.6 181.1)),((126.6 181.1,124.1 184.1,128.5 177.7,126.6 181.1)),((128.5 177.7,129.6 173.9,175 150,128.5 177.7)),((128.5 177.7,124.1 155.9,130 170,128.5 177.7)),((129.6 173.9,130 170,175 150,129.6 173.9)),((129.6 173.9,128.5 177.7,130 170,129.6 173.9)))
Figure
Geometry figure for visual-cg-constraineddelaunaytriangles-01

ST_DelaunayTriangles applied to the same input. Triangle edges cross polygon boundaries.

Code
SELECT
  ST_DelaunayTriangles(
    ST_Union(
      'POLYGON((175 150,20 40,50 60,125 100,175 150))'::geometry,
      ST_Buffer('POINT(110 170)'::geometry, 20)
    )
  );
래스터 출력
GEOMETRYCOLLECTION(POLYGON((95.9 184.1,93.4 181.1,95.9 155.9,95.9 184.1)), POLYGON((95.9 184.1,95.9 155.9,102.3 188.5,95.9 184.1)), POLYGON((95.9 184.1,102.3 188.5,98.9 186.6,95.9 184.1)), POLYGON((102.3 188.5,95.9 155.9,98.9 153.4,102.3 188.5)), POLYGON((102.3 188.5,98.9 153.4,102.3 151.5,102.3 188.5)), POLYGON((102.3 188.5,102.3 151.5,106.1 189.6,102.3 188.5)), POLYGON((106.1 189.6,102.3 151.5,106.1 150.4,106.1 189.6)), POLYGON((106.1 189.6,106.1 150.4,110 190,106.1 189.6)), POLYGON((110 190,106.1 150.4,110 150,110 190)), POLYGON((110 190,110 150,117.7 188.5,110 190)), POLYGON((110 190,117.7 188.5,113.9 189.6,110 190)), POLYGON((117.7 188.5,110 150,121.1 153.4,117.7 188.5)), POLYGON((117.7 188.5,121.1 153.4,121.1 186.6,117.7 188.5)), POLYGON((121.1 186.6,121.1 153.4,124.1 155.9,121.1 186.6)), POLYGON((121.1 186.6,124.1 155.9,124.1 184.1,121.1 186.6)), POLYGON((121.1 186.6,124.1 184.1,175 150,121.1 186.6)), POLYGON((175 150,124.1 184.1,126.6 181.1,175 150)), POLYGON((175 150,126.6 181.1,128.5 177.7,175 150)), POLYGON((175 150,128.5 177.7,129.6 173.9,175 150)), POLYGON((175 150,129.6 173.9,130 170,175 150)), POLYGON((175 150,130 170,129.6 166.1,175 150)), POLYGON((175 150,129.6 166.1,128.5 162.3,175 150)), POLYGON((175 150,128.5 162.3,126.6 158.9,175 150)), POLYGON((175 150,126.6 158.9,124.1 155.9,175 150)), POLYGON((175 150,124.1 155.9,125 100,175 150)), POLYGON((125 100,124.1 155.9,121.1 153.4,125 100)), POLYGON((125 100,121.1 153.4,117.7 151.5,125 100)), POLYGON((125 100,117.7 151.5,113.9 150.4,125 100)), POLYGON((125 100,113.9 150.4,110 150,125 100)), POLYGON((125 100,110 150,106.1 150.4,125 100)), POLYGON((125 100,106.1 150.4,102.3 151.5,125 100)), POLYGON((125 100,102.3 151.5,98.9 153.4,125 100)), POLYGON((125 100,98.9 153.4,50 60,125 100)), POLYGON((125 100,50 60,20 40,125 100)), POLYGON((20 40,50 60,90.4 166.1,20 40)), POLYGON((20 40,90.4 166.1,90 170,20 40)), POLYGON((20 40,90 170,90.4 173.9,20 40)), POLYGON((20 40,90.4 173.9,91.5 177.7,20 40)), POLYGON((91.5 177.7,90.4 173.9,90 170,91.5 177.7)), POLYGON((91.5 177.7,90 170,91.5 162.3,91.5 177.7)), POLYGON((91.5 177.7,91.5 162.3,93.4 158.9,91.5 177.7)), POLYGON((91.5 177.7,93.4 158.9,93.4 181.1,91.5 177.7)), POLYGON((93.4 181.1,93.4 158.9,95.9 155.9,93.4 181.1)), POLYGON((95.9 155.9,93.4 158.9,50 60,95.9 155.9)), POLYGON((95.9 155.9,50 60,98.9 153.4,95.9 155.9)), POLYGON((50 60,93.4 158.9,91.5 162.3,50 60)), POLYGON((50 60,91.5 162.3,90.4 166.1,50 60)), POLYGON((90.4 166.1,91.5 162.3,90 170,90.4 166.1)), POLYGON((110 150,113.9 150.4,121.1 153.4,110 150)), POLYGON((121.1 153.4,113.9 150.4,117.7 151.5,121.1 153.4)), POLYGON((124.1 155.9,126.6 158.9,129.6 166.1,124.1 155.9)), POLYGON((124.1 155.9,129.6 166.1,128.5 177.7,124.1 155.9)), POLYGON((124.1 155.9,128.5 177.7,124.1 184.1,124.1 155.9)), POLYGON((124.1 184.1,128.5 177.7,126.6 181.1,124.1 184.1)), POLYGON((128.5 177.7,129.6 166.1,130 170,128.5 177.7)), POLYGON((128.5 177.7,130 170,129.6 173.9,128.5 177.7)), POLYGON((129.6 166.1,126.6 158.9,128.5 162.3,129.6 166.1)))
Figure
Geometry figure for visual-cg-constraineddelaunaytriangles-02

제목

CG_Extrude — 표면을 관련 입체로 돌출시킵니다.

요약

geometry CG_Extrude(geometry geom, float x, float y, float z);

설명

Extrudes the input along the vector (x, y, z) and connects it to its translated copy. Extrusion can raise the dimensionality of the result, for example from a surface to a volume.

Availability: 3.5.0

This method needs SFCGAL backend.

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

The figures use ST_Affine to project Z diagonally into XY after extrusion. The returned geometry from CG_Extrude remains a 3D PolyhedralSurface.

Extruding an octagonal Polygon 30 units along Z.

Code
WITH data AS (
  SELECT ST_Buffer('POINT(100 90)'::geometry, 50, 'quad_segs=2') AS geom
), projected AS (
  SELECT ST_Force2D(ST_Affine(geom,
           1, 0, 0.5, 0, 1, 0.5, 0, 0, 0, 0, 0, 0)) AS input_geom,
         ST_Force2D(ST_Affine(CG_Extrude(geom, 0, 0, 30),
           1, 0, 0.5, 0, 1, 0.5, 0, 0, 0, 0, 0, 0)) AS output_geom
  FROM data
)
SELECT input_geom AS input_geometry,
       output_geom AS extruded_projection
FROM projected;
래스터 출력
POLYGON((150 90,135.355 54.645,100 40,64.645 54.645,50 90,64.645 125.355,100 140,135.355 125.355,150 90)) | POLYHEDRALSURFACE(((150 90,135.355 54.645,100 40,64.645 54.645,50 90,64.645 125.355,100 140,135.355 125.355,150 90)),((165 105,150.355 140.355,115 155,79.645 140.355,65 105,79.645 69.645,115 55,150.355 69.645,165 105)),((150 90,165 105,150.355 69.645,135.355 54.645,150 90)),((135.355 54.645,150.355 69.645,115 55,100 40,135.355 54.645)),((100 40,115 55,79.645 69.645,64.645 54.645,100 40)),((64.645 54.645,79.645 69.645,65 105,50 90,64.645 54.645)),((50 90,65 105,79.645 140.355,64.645 125.355,50 90)),((64.645 125.355,79.645 140.355,115 155,100 140,64.645 125.355)),((100 140,115 155,150.355 140.355,135.355 125.355,100 140)),((135.355 125.355,150.355 140.355,165 105,150 90,135.355 125.355)))
Figure
Geometry figure for visual-cg-extrude-01

Extruding a LineString 10 units along Z.

Code
WITH data AS (
  SELECT 'LINESTRING(50 50,100 90,95 150)'::geometry AS geom
), projected AS (
  SELECT ST_Force2D(ST_Affine(geom,
           1, 0, 0.5, 0, 1, 0.5, 0, 0, 0, 0, 0, 0)) AS input_geom,
         ST_Force2D(ST_Affine(CG_Extrude(geom, 0, 0, 10),
           1, 0, 0.5, 0, 1, 0.5, 0, 0, 0, 0, 0, 0)) AS output_geom
  FROM data
)
SELECT input_geom AS input_geometry,
       output_geom AS extruded_projection
FROM projected;
래스터 출력
LINESTRING(50 50,100 90,95 150) | POLYHEDRALSURFACE(((50 50,100 90,105 95,55 55,50 50)),((100 90,95 150,100 155,105 95,100 90)))
Figure
Geometry figure for visual-cg-extrude-02

제목

CG_ExtrudeStraightSkeleton — Straight Skeleton Extrusion

요약

geometry CG_ExtrudeStraightSkeleton(geometry geom, float roof_height, float body_height = 0);

설명

Computes an extrusion with a maximal height of the polygon geometry.

[참고]

Perhaps the first (historically) use-case of straight skeletons: given a polygonal roof, the straight skeleton directly gives the layout of each tent. If each skeleton edge is lifted from the plane a height equal to its offset distance, the resulting roof is "correct" in that water will always fall down to the contour edges (the roof's border), regardless of where it falls on the roof. The function computes this extrusion aka "roof" on a polygon. If the argument body_height > 0, so the polygon is extruded like with CG_Extrude(polygon, 0, 0, body_height). The result is an union of these polyhedralsurfaces.

Availability: 3.5.0 - requires SFCGAL >= 1.5.0.

Requires SFCGAL >= 1.5.0

This method needs SFCGAL backend.

예시

Extrude a polygon with a hole into a body and straight-skeleton roof.

Code
WITH data AS (
  SELECT 'POLYGON ((0 0,5 0,5 5,4 5,4 4,0 4,0 0),(1 1,1 2,2 2,2 1,1 1))'::geometry AS input_polygon
)
SELECT input_polygon AS input_polygon,
       CG_ExtrudeStraightSkeleton(input_polygon, 3.0, 2.0) AS straight_skeleton_extrusion
FROM data;
래스터 출력
POLYGON((0 0,5 0,5 5,4 5,4 4,0 4,0 0),(1 1,1 2,2 2,2 1,1 1)) | POLYHEDRALSURFACE Z (((0 0 0,0 4 0,4 4 0,4 5 0,5 5 0,5 0 0,0 0 0),(1 1 0,2 1 0,2 2 0,1 2 0,1 1 0)),((0 0 0,0 0 2,0 4 2,0 4 0,0 0 0)),((0 4 0,0 4 2,4 4 2,4 4 0,0 4 0)),((4 4 0,4 4 2,4 5 2,4 5 0,4 4 0)),((4 5 0,4 5 2,5 5 2,5 5 0,4 5 0)),((5 5 0,5 5 2,5 0 2,5 0 0,5 5 0)),((5 0 0,5 0 2,0 0 2,0 0 0,5 0 0)),((1 1 0,1 1 2,2 1 2,2 1 0,1 1 0)),((2 1 0,2 1 2,2 2 2,2 2 0,2 1 0)),((2 2 0,2 2 2,1 2 2,1 2 0,2 2 0)),((1 2 0,1 2 2,1 1 2,1 1 0,1 2 0)),((0 4 2,0 0 2,0.5 0.5 2.5,0.5 2.5 2.5,1 3 3,0 4 2)),((0 0 2,5 0 2,3.5 1.5 3.5,2.5 0.5 2.5,0.5 0.5 2.5,0 0 2)),((5 0 2,5 5 2,4.5 4.5 2.5,4.5 3.5 2.5,3.5 2.5 3.5,3.5 1.5 3.5,5 0 2)),((5 5 2,4 5 2,4.5 4.5 2.5,5 5 2)),((4 5 2,4 4 2,4.5 3.5 2.5,4.5 4.5 2.5,4 5 2)),((4 4 2,0 4 2,1 3 3,3 3 3,3.5 2.5 3.5,4.5 3.5 2.5,4 4 2)),((2 1 2,1 1 2,0.5 0.5 2.5,2.5 0.5 2.5,2 1 2)),((1 1 2,1 2 2,0.5 2.5 2.5,0.5 0.5 2.5,1 1 2)),((1 2 2,2 2 2,3 3 3,1 3 3,0.5 2.5 2.5,1 2 2)),((2 2 2,2 1 2,2.5 0.5 2.5,3.5 1.5 3.5,3.5 2.5 3.5,3 3 3,2 2 2)))
Figure
Geometry figure for visual-cg-extrudestraightskeleton-01

제목

CG_GreeneApproxConvexPartition — Computes approximal convex partition of the polygon geometry

요약

geometry CG_GreeneApproxConvexPartition(geometry geom);

설명

Computes approximal monotone convex partition of the polygon geometry.

[참고]

A partition of a polygon P is a set of polygons such that the interiors of the polygons do not intersect and the union of the polygons is equal to the interior of the original polygon P. CG_ApproxConvexPartition and CG_GreeneApproxConvexPartition functions produce approximately optimal convex partitions. Both these functions produce convex decompositions by first decomposing the polygon into simpler polygons; CG_ApproxConvexPartition uses a triangulation and CG_GreeneApproxConvexPartition a monotone partition. These two functions both guarantee that they will produce no more than four times the optimal number of convex pieces but they differ in their runtime complexities. Though the triangulation-based approximation algorithm often results in fewer convex pieces, this is not always the case.

Availability: 3.5.0 - requires SFCGAL >= 1.5.0.

Requires SFCGAL >= 1.5.0

This method needs SFCGAL backend.

예시

Greene's monotone-based approximation uses the same polygon and stays directly comparable in one panel.

Code
WITH data AS (
  SELECT 'POLYGON((156 150,83 181,89 131,148 120,107 61,32 159,0 45,41 86,45 1,177 2,67 24,109 31,170 60,180 110,156 150))'::geometry AS input_polygon
)
SELECT input_polygon AS input_polygon,
       CG_GreeneApproxConvexPartition(input_polygon) AS partition
FROM data;
래스터 출력
POLYGON((156 150,83 181,89 131,148 120,107 61,32 159,0 45,41 86,45 1,177 2,67 24,109 31,170 60,180 110,156 150)) | GEOMETRYCOLLECTION(POLYGON((32 159,0 45,41 86,32 159)), POLYGON((45 1,177 2,67 24,45 1)), POLYGON((67 24,109 31,170 60,107 61,67 24)), POLYGON((41 86,45 1,67 24,41 86)), POLYGON((107 61,32 159,41 86,67 24,107 61)), POLYGON((148 120,107 61,170 60,148 120)), POLYGON((148 120,170 60,180 110,156 150,148 120)), POLYGON((156 150,83 181,89 131,148 120,156 150)))
Figure
Geometry figure for visual-cg-greeneapproxconvexpartition-01

제목

CG_MinkowskiSum — 민코프스키 합계를 수행합니다.

요약

geometry CG_MinkowskiSum(geometry geom1, geometry geom2);

설명

이 함수는 폴리곤과, 포인트, 라인 또는 폴리곤의 2차원 민코프스키 합계를 수행합니다.

두 도형 A와 B의 민코프스키 합계란 A와 B에 있는 모든 포인트를 합한, 모든 포인트들의 집합입니다. 민코프스키 합계는 운동 계획(motion planning) 및 CAD(computer-aided design) 분야에서 자주 사용됩니다. 자세한 내용은 Wikipedia Minkowski addition 을 참조하십시오.

첫 번째 파라미터는 어떤 2차원 도형(포인트, 라인스트링, 폴리곤)도 될 수 있습니다. 만약 3차원 도형을 입력할 경우, Z 좌표를 0으로 강제해서 2차원으로 변환하기 때문에 유효하지 않은 도형으로 변할 가능성이 있습니다. 두 번째 파라미터는 2차원 폴리곤이어야만 합니다.

구현하는 데 CGAL 2D Minkowskisum 을 활용합니다.

Availability: 3.5.0

This method needs SFCGAL backend.

예시

Minkowski sum of a LineString and a circular polygon. The line crosses the polygon, and the result sweeps the polygon along the line.

Code
WITH data AS (
  SELECT ST_MakeLine(ST_Point(10, 10), ST_Point(100, 100)) AS line,
         ST_Buffer('POINT(50 50)'::geometry, 30) AS circle
)
SELECT line AS input_line,
       circle AS input_circle,
       CG_MinkowskiSum(line, circle) AS minkowski_sum
FROM data;
래스터 출력
LINESTRING(10 10,100 100) | POLYGON((80 50,79.424 44.147,77.716 38.519,74.944 33.333,71.213 28.787,66.667 25.056,61.481 22.284,55.853 20.576,50 20,44.147 20.576,38.519 22.284,33.333 25.056,28.787 28.787,25.056 33.333,22.284 38.519,20.576 44.147,20 50,20.576 55.853,22.284 61.481,25.056 66.667,28.787 71.213,33.333 74.944,38.519 77.716,44.147 79.424,50 80,55.853 79.424,61.481 77.716,66.667 74.944,71.213 71.213,74.944 66.667,77.716 61.481,79.424 55.853,80 50)) | MULTIPOLYGON(((179.424 155.853,177.716 161.481,174.944 166.667,171.213 171.213,166.667 174.944,161.481 177.716,155.853 179.424,150 180,144.147 179.424,138.519 177.716,133.333 174.944,128.787 171.213,38.787 81.213,35.056 76.667,32.284 71.481,30.576 65.853,30 60,30.576 54.147,32.284 48.519,35.056 43.333,38.787 38.787,43.333 35.056,48.519 32.284,54.147 30.576,60 30,65.853 30.576,71.481 32.284,76.667 35.056,81.213 38.787,171.213 128.787,174.944 133.333,177.716 138.519,179.424 144.147,180 150,179.424 155.853)))
Figure
Geometry figure for visual-cg-minkowskisum-01

Minkowski sum of a MultiPoint and a polygon. The result contains one translated copy of the polygon for each point.

Code
WITH data AS (
  SELECT 'MULTIPOINT(25 50,70 25)'::geometry AS points,
         'POLYGON((130 150,20 40,50 60,125 100,130 150))'::geometry AS polygon
)
SELECT points AS input_points,
       polygon AS input_polygon,
       CG_MinkowskiSum(points, polygon) AS minkowski_sum
FROM data;
래스터 출력
MULTIPOINT((25 50),(70 25)) | POLYGON((130 150,20 40,50 60,125 100,130 150)) | MULTIPOLYGON(((45 90,75 110,150 150,155 200,45 90)),((90 65,120 85,195 125,200 175,90 65)))
Figure
Geometry figure for visual-cg-minkowskisum-02

제목

CG_OptimalAlphaShape — Computes an Alpha-shape enclosing a geometry using an "optimal" alpha value.

요약

geometry CG_OptimalAlphaShape(geometry geom, boolean allow_holes = false, integer nb_components = 1);

설명

Computes the "optimal" alpha-shape of the points in a geometry. The alpha-shape is computed using a value of α chosen so that:

  1. the number of polygon elements is equal to or smaller than nb_components (which defaults to 1)

  2. all input points are contained in the shape

The result will not contain holes unless the optional allow_holes argument is specified as true.

Availability: 3.5.0 - requires SFCGAL >= 1.4.1.

This method needs SFCGAL backend.

예시

The original point cloud and the optimal alpha-shape share one comparison frame.

Code
WITH data AS (
  SELECT 'MULTIPOINT((63 84),(76 88),(68 73),(53 18),(91 50),(81 70),
(88 29),(24 82),(32 51),(37 23),(27 54),(84 19),(75 87),(44 42),(77 67),(90 30),(36 61),(32 65),
(81 47),(88 58),(68 73),(49 95),(81 60),(87 50),
(78 16),(79 21),(30 22),(78 43),(26 85),(48 34),(35 35),(36 40),(31 79),(83 29),(27 84),(52 98),(72 95),(85 71),
(75 84),(75 77),(81 29),(77 73),(41 42),(83 72),(23 36),(89 53),(27 57),(57 97),(27 77),(39 88),(60 81),
(80 72),(54 32),(55 26),(62 22),(70 20),(76 27),(84 35),(87 42),(82 54),(83 64),(69 86),(60 90),(50 86),(43 80),(36 73),
(36 68),(40 75),(24 67),(23 60),(26 44),(28 33),(40 32),(43 19),(65 16),(73 16),(38 46),(31 59),(34 86),(45 90),(64 97))'::geometry AS input_points
)
SELECT input_points AS input_points,

         CG_OptimalAlphaShape(input_points) AS optimal_alpha_shape
FROM data;
래스터 출력
MULTIPOINT((63 84),(76 88),(68 73),(53 18),(91 50),(81 70),(88 29),(24 82),(32 51),(37 23),(27 54),(84 19),(75 87),(44 42),(77 67),(90 30),(36 61),(32 65),(81 47),(88 58),(68 73),(49 95),(81 60),(87 50),(78 16),(79 21),(30 22),(78 43),(26 85),(48 34),(35 35),(36 40),(31 79),(83 29),(27 84),(52 98),(72 95),(85 71),(75 84),(75 77),(81 29),(77 73),(41 42),(83 72),(23 36),(89 53),(27 57),(57 97),(27 77),(39 88),(60 81),(80 72),(54 32),(55 26),(62 22),(70 20),(76 27),(84 35),(87 42),(82 54),(83 64),(69 86),(60 90),(50 86),(43 80),(36 73),(36 68),(40 75),(24 67),(23 60),(26 44),(28 33),(40 32),(43 19),(65 16),(73 16),(38 46),(31 59),(34 86),(45 90),(64 97)) | MULTIPOLYGON(((89 53,88 58,83 64,85 71,83 72,75 77,75 84,76 88,72 95,64 97,57 97,52 98,49 95,45 90,39 88,34 86,26 85,24 82,27 77,24 67,23 60,27 54,26 44,23 36,28 33,30 22,37 23,43 19,53 18,65 16,73 16,78 16,84 19,88 29,90 30,87 42,91 50,89 53)))
Figure
Geometry figure for visual-cg-optimalalphashape-01

Allowing holes keeps the same outer shell but carves a central hole.

Code
WITH data AS (
  SELECT 'MULTIPOINT((63 84),(76 88),(68 73),(53 18),(91 50),(81 70),(88 29),(24 82),(32 51),(37 23),(27 54),(84 19),(75 87),(44 42),(77 67),(90 30),(36 61),(32 65),(81 47),(88 58),(68 73),(49 95),(81 60),(87 50),
(78 16),(79 21),(30 22),(78 43),(26 85),(48 34),(35 35),(36 40),(31 79),(83 29),(27 84),(52 98),(72 95),(85 71),
(75 84),(75 77),(81 29),(77 73),(41 42),(83 72),(23 36),(89 53),(27 57),(57 97),(27 77),(39 88),(60 81),
(80 72),(54 32),(55 26),(62 22),(70 20),(76 27),(84 35),(87 42),(82 54),(83 64),(69 86),(60 90),(50 86),(43 80),(36 73),
(36 68),(40 75),(24 67),(23 60),(26 44),(28 33),(40 32),(43 19),(65 16),(73 16),(38 46),(31 59),(34 86),(45 90),(64 97))'::geometry AS input_points
)
SELECT input_points AS input_points,

         CG_OptimalAlphaShape(input_points, allow_holes => true) AS optimal_alpha_shape
FROM data;
래스터 출력
MULTIPOINT((63 84),(76 88),(68 73),(53 18),(91 50),(81 70),(88 29),(24 82),(32 51),(37 23),(27 54),(84 19),(75 87),(44 42),(77 67),(90 30),(36 61),(32 65),(81 47),(88 58),(68 73),(49 95),(81 60),(87 50),(78 16),(79 21),(30 22),(78 43),(26 85),(48 34),(35 35),(36 40),(31 79),(83 29),(27 84),(52 98),(72 95),(85 71),(75 84),(75 77),(81 29),(77 73),(41 42),(83 72),(23 36),(89 53),(27 57),(57 97),(27 77),(39 88),(60 81),(80 72),(54 32),(55 26),(62 22),(70 20),(76 27),(84 35),(87 42),(82 54),(83 64),(69 86),(60 90),(50 86),(43 80),(36 73),(36 68),(40 75),(24 67),(23 60),(26 44),(28 33),(40 32),(43 19),(65 16),(73 16),(38 46),(31 59),(34 86),(45 90),(64 97)) | MULTIPOLYGON(((89 53,88 58,83 64,85 71,83 72,75 77,75 84,76 88,72 95,64 97,57 97,52 98,49 95,45 90,39 88,34 86,26 85,24 82,27 77,24 67,23 60,27 54,26 44,23 36,28 33,30 22,37 23,43 19,53 18,65 16,73 16,78 16,84 19,88 29,90 30,87 42,91 50,89 53),(36 68,40 75,43 80,50 86,60 81,68 73,77 67,81 60,82 54,81 47,78 43,81 29,76 27,70 20,62 22,55 26,54 32,48 34,44 42,38 46,36 61,36 68)))
Figure
Geometry figure for visual-cg-optimalalphashape-02

제목

CG_OptimalConvexPartition — Computes an optimal convex partition of the polygon geometry

요약

geometry CG_OptimalConvexPartition(geometry geom);

설명

Computes an optimal convex partition of the polygon geometry.

[참고]

A partition of a polygon P is a set of polygons such that the interiors of the polygons do not intersect and the union of the polygons is equal to the interior of the original polygon P. CG_OptimalConvexPartition produces a partition that is optimal in the number of pieces.

Availability: 3.5.0 - requires SFCGAL >= 1.5.0.

Requires SFCGAL >= 1.5.0

This method needs SFCGAL backend.

예시

The optimal convex partition uses the same polygon and produces the smallest documented piece count.

Code
WITH data AS (
  SELECT 'POLYGON((156 150,83 181,89 131,148 120,107 61,32 159,0 45,41 86,45 1,177 2,67 24,109 31,170 60,180 110,156 150))'::geometry AS input_polygon
)
SELECT input_polygon AS input_polygon,
       CG_OptimalConvexPartition(input_polygon) AS partition
FROM data;
래스터 출력
POLYGON((156 150,83 181,89 131,148 120,107 61,32 159,0 45,41 86,45 1,177 2,67 24,109 31,170 60,180 110,156 150)) | GEOMETRYCOLLECTION(POLYGON((156 150,83 181,89 131,148 120,156 150)), POLYGON((32 159,0 45,41 86,32 159)), POLYGON((45 1,177 2,67 24,45 1)), POLYGON((41 86,45 1,67 24,41 86)), POLYGON((107 61,32 159,41 86,67 24,109 31,107 61)), POLYGON((148 120,107 61,109 31,170 60,180 110,148 120)), POLYGON((156 150,148 120,180 110,156 150)))
Figure
Geometry figure for visual-cg-optimalconvexpartition-01

제목

CG_StraightSkeleton — 도형으로부터 직선 골격(straight skeleton)을 계산합니다.

요약

geometry CG_StraightSkeleton(geometry geom, boolean use_distance_as_m = false);

설명

Computes the straight skeleton of a polygon by tracing the inward propagation of its edges. When use_distance_as_m is true, the M coordinate of each output point stores its distance from the input boundary.

Availability: 3.5.0

Requires SFCGAL >= 1.3.8 for option use_distance_as_m

This method needs SFCGAL backend.

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

Code
WITH data AS (
  SELECT 'POLYGON((190 190,10 190,10 10,190 10,190 20,160 30,60 30,60 130,190 140,190 190))'::geometry AS polygon
)
SELECT CG_StraightSkeleton(polygon) AS straight_skeleton
FROM data;
래스터 출력
MULTILINESTRING((190 190,164.03987973986756 164.03987973986756),(10 190,40.697077206292434 159.30292279370755),(10 10,35 35),(190 10,184.18861169915812 15.811388300841896),(190 20,184.18861169915812 15.811388300841896),(160 30,158.3772233983162 20),(60 30,50 20),(60 130,35 153.15077848154866),(190 140,164.03987973986756 164.03987973986756),(184.18861169915812 15.811388300841896,158.3772233983162 20),(50 20,158.3772233983162 20),(50 20,35 35),(35 153.15077848154866,35 35),(35 153.15077848154866,40.697077206292434 159.30292279370755),(164.03987973986756 164.03987973986756,40.697077206292434 159.30292279370755))
Figure
Geometry figure for visual-cg-straightskeleton-01
Code
WITH data AS (
  SELECT 'POLYGON((0 0,1 0,1 1,0 1,0 0))'::geometry AS polygon
)
SELECT CG_StraightSkeleton(polygon, true) AS straight_skeleton_with_m
FROM data;
래스터 출력
MULTILINESTRING M ((0 0 0,0.5 0.5 0.5),(1 0 0,0.5 0.5 0.5),(1 1 0,0.5 0.5 0.5),(0 1 0,0.5 0.5 0.5))
Figure
Geometry figure for visual-cg-straightskeleton-02

Note that valid inputs with rings that touch at a single point will raise an error.

Code
SELECT CG_StraightSkeleton('POLYGON((0 0,3 0,3 3,0 3,0 0),(0 0,1 2,2 1,0 0))'));
래스터 출력
NOTICE:  During straight_skeleton(A) :
NOTICE:    with A: POLYGON((0/1 0/1,3/1 0/1,3/1 3/1,0/1 3/1,0/1 0/1),(0/1 0/1,1/1 2/1,2/1 1/1,0/1 0/1))
ERROR:  straight skeleton of Polygon with point touching rings is not implemented.

제목

CG_Tesselate — 폴리곤 또는 다면체 표면의 표면 다듬기(tessellation) 작업을 수행한 다음 TIN 또는 TIN 집합으로 반환합니다.

요약

geometry CG_Tesselate(geometry geom);

설명

[멀티]폴리곤 또는 다면체 표면 같은 표면 도형을 입력받아 삼각형을 이용한 다듬기(모자이크) 과정을 거친 TIN 표현식을 반환합니다.

[참고]

ST_TriangulatePolygon does similar to this function except that it returns a geometry collection of polygons instead of a TIN and also only works with 2D geometries.

Availability: 3.5.0

This method needs SFCGAL backend.

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

Tessellation divides each face of a cube into triangles.

Code
WITH data AS (
  SELECT 'POLYHEDRALSURFACE Z( ((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)),
((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)),((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)),
((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)),
((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)),((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1)) )'::geometry AS cube
)
SELECT CG_Tesselate(cube) AS tessellation
FROM data;
래스터 출력
TIN Z (((0 0 0,0 0 1,0 1 1,0 0 0)),((0 1 0,0 0 0,0 1 1,0 1 0)),((0 0 0,0 1 0,1 1 0,0 0 0)),((1 0 0,0 0 0,1 1 0,1 0 0)),((0 0 1,1 0 0,1 0 1,0 0 1)),((0 0 1,0 0 0,1 0 0,0 0 1)),((1 1 0,1 1 1,1 0 1,1 1 0)),((1 0 0,1 1 0,1 0 1,1 0 0)),((0 1 0,0 1 1,1 1 1,0 1 0)),((1 1 0,0 1 0,1 1 1,1 1 0)),((0 1 1,1 0 1,1 1 1,0 1 1)),((0 1 1,0 0 1,1 0 1,0 1 1)))
Figure
Geometry figure for visual-cg-tesselate-01

Tessellation of a Polygon.

Code
WITH data AS (
  SELECT 'POLYGON((10 190,10 70,80 70,80 130,50 160,120 160,120 190,10 190))'::geometry AS polygon
)
SELECT polygon AS input_polygon,
       CG_Tesselate(polygon) AS tessellation
FROM data;
래스터 출력
POLYGON((10 190,10 70,80 70,80 130,50 160,120 160,120 190,10 190)) | TIN(((80 130,10 70,80 70,80 130)),((50 160,10 190,10 70,50 160)),((80 130,50 160,10 70,80 130)),((120 160,120 190,50 160,120 160)),((120 190,10 190,50 160,120 190)))
Figure
Geometry figure for visual-cg-tesselate-02

제목

CG_Triangulate — Triangulates a polygonal geometry

요약

geometry CG_Triangulate( geometry geom );

설명

Triangulates a polygonal geometry.

Performed by the SFCGAL module

[참고]

NOTE: this function returns a geometry representing the triangulated result.

Availability: 3.5.0

This method needs SFCGAL backend.

도형 예시

Code
SELECT CG_Triangulate(
  'POLYGON((0 0,1 0,1 1,0 1,0 0),
            (0.2 0.2,0.2 0.8,0.8 0.8,0.8 0.2,0.2 0.2))'
);
래스터 출력
TIN(((0.8 0.2,0.2 0.2,1 0,0.8 0.2)),((0.2 0.2,0 0,1 0,0.2 0.2)),((1 1,0.8 0.8,0.8 0.2,1 1)),((0 1,0 0,0.2 0.2,0 1)),((0 1,0.2 0.8,1 1,0 1)),((0 1,0.2 0.2,0.2 0.8,0 1)),((0.2 0.8,0.8 0.8,1 1,0.2 0.8)),((0.2 0.8,0.2 0.2,0.8 0.2,0.2 0.8)),((1 1,0.8 0.2,1 0,1 1)),((0.8 0.8,0.2 0.8,0.8 0.2,0.8 0.8)))
Figure
Geometry figure for visual-cg-triangulate-01

제목

CG_Visibility — Compute a visibility polygon from a point or a segment in a polygon geometry

요약

geometry CG_Visibility(geometry polygon, geometry point);

geometry CG_Visibility(geometry polygon, geometry pointA, geometry pointB);

설명

Returns the portion of a polygon visible from an observer point, or from the observer segment defined by pointA and pointB.

Availability: 3.5.0 - requires SFCGAL >= 1.5.0.

Requires SFCGAL >= 1.5.0

This method needs SFCGAL backend.

This function supports 3d and will not drop the z-index.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

예시

Visibility from a point inside a polygon with holes.

Code
WITH data AS (
  SELECT 'POLYGON((23.5 23.5,23.5 173.5,173.5 173.5,173.5 23.5,23.5 23.5),(108 98,108 36,156 37,155 99,108 98),(107 157.5,107 106.5,135 107.5,133 127.5,143.5 127.5,143.5 108.5,153.5 109.5,151.5 166,107 157.5),(41 95.5,41 35,100.5 36,98.5 68,78.5 68,77.5 96.5,41 95.5),(39 150,40 104,97.5 106.5,95.5 152,39 150))'::geometry AS polygon,
         'POINT(91 87)'::geometry AS observer
)
SELECT ST_Collect(polygon, observer) AS input_scene,
       CG_Visibility(polygon, observer) AS visibility
FROM data;
래스터 출력
GEOMETRYCOLLECTION(POLYGON((23.5 23.5,23.5 173.5,173.5 173.5,173.5 23.5,23.5 23.5),(108 98,108 36,156 37,155 99,108 98),(107 157.5,107 106.5,135 107.5,133 127.5,143.5 127.5,143.5 108.5,153.5 109.5,151.5 166,107 157.5),(41 95.5,41 35,100.5 36,98.5 68,78.5 68,77.5 96.5,41 95.5),(39 150,40 104,97.5 106.5,95.5 152,39 150)), POINT(91 87)) | POLYGON((78.5 68,98.5 68,108 43.93333333333334,108 98,121.96219931271477 107.03436426116838,107 106.5,107 135,97.5 106.5,65.28017241379311 105.09913793103448,77.5 96.5,78.5 68))
Figure
Geometry figure for visual-cg-visibility-01

Visibility from a segment inside the same polygon.

Code
WITH data AS (
  SELECT 'POLYGON((23.5 23.5,23.5 173.5,173.5 173.5,173.5 23.5,23.5 23.5),(108 98,108 36,156 37,155 99,108 98),(107 157.5,107 106.5,135 107.5,133 127.5,143.5 127.5,143.5 108.5,153.5 109.5,151.5 166,107 157.5),(41 95.5,41 35,100.5 36,98.5 68,78.5 68,77.5 96.5,41 95.5),(39 150,40 104,97.5 106.5,95.5 152,39 150))'::geometry AS polygon,
         'LINESTRING(78.5 68,98.5 68)'::geometry AS observer
)
SELECT ST_Collect(polygon, observer) AS input_scene,
       CG_Visibility(polygon,
                     ST_StartPoint(observer),
                     ST_EndPoint(observer)) AS visibility
FROM data;
래스터 출력
GEOMETRYCOLLECTION(POLYGON((23.5 23.5,23.5 173.5,173.5 173.5,173.5 23.5,23.5 23.5),(108 98,108 36,156 37,155 99,108 98),(107 157.5,107 106.5,135 107.5,133 127.5,143.5 127.5,143.5 108.5,153.5 109.5,151.5 166,107 157.5),(41 95.5,41 35,100.5 36,98.5 68,78.5 68,77.5 96.5,41 95.5),(39 150,40 104,97.5 106.5,95.5 152,39 150)), LINESTRING(78.5 68,98.5 68)) | POLYGON((78.5 68,98.5 68,100.5 36,101.28125 23.5,111.7109375 23.5,108 36,108 98,110.73389524382901 106.63335340156533,107 106.5,107 157.5,108.51955307262571 173.5,95.75974025974025 173.5,97.5 106.5,70.9811529933481 105.3470066518847,77.5 96.5,78.5 68))
Figure
Geometry figure for visual-cg-visibility-02

제목

CG_YMonotonePartition — Computes y-monotone partition of the polygon geometry

요약

geometry CG_YMonotonePartition(geometry geom);

설명

Computes y-monotone partition of the polygon geometry.

[참고]

A partition of a polygon P is a set of polygons such that the interiors of the polygons do not intersect and the union of the polygons is equal to the interior of the original polygon P. A y-monotone polygon is a polygon whose vertices v1,…,vn can be divided into two chains v1,…,vk and vk,…,vn,v1, such that any horizontal line intersects either chain at most once. This algorithm does not guarantee a bound on the number of polygons produced with respect to the optimal number.

Availability: 3.5.0 - requires SFCGAL >= 1.5.0.

Requires SFCGAL >= 1.5.0

This method needs SFCGAL backend.

예시

The same polygon can also be partitioned into y-monotone pieces for downstream processing.

Code
WITH data AS (
  SELECT 'POLYGON((156 150,83 181,89 131,148 120,107 61,32 159,0 45,41 86,45 1,177 2,67 24,109 31,170 60,180 110,156 150))'::geometry AS input_polygon
)
SELECT input_polygon AS input_polygon,
       CG_YMonotonePartition(input_polygon) AS partition
FROM data;
래스터 출력
POLYGON((156 150,83 181,89 131,148 120,107 61,32 159,0 45,41 86,45 1,177 2,67 24,109 31,170 60,180 110,156 150)) | GEOMETRYCOLLECTION(POLYGON((32 159,0 45,41 86,32 159)), POLYGON((107 61,32 159,41 86,45 1,177 2,67 24,109 31,170 60,107 61)), POLYGON((156 150,83 181,89 131,148 120,107 61,170 60,180 110,156 150)))
Figure
Geometry figure for visual-cg-ymonotonepartition-01

제목

CG_StraightSkeletonPartition — Computes the straight skeleton partition of a polygon.

요약

geometry CG_StraightSkeletonPartition(geometry geom, boolean auto_orientation);

설명

Computes the straight skeleton partition of the input polygon geometry geom. The straight skeleton is a partitioning of the polygon into faces formed by tracing the collapse of its edges. If auto_orientation is set to true, the function will automatically adjust the orientation of the input polygon to ensure correct results.

Availability: 3.6.0 - requires SFCGAL >= 2.0.0.

This method needs SFCGAL backend.

예시

Code
SELECT CG_StraightSkeletonPartition('POLYGON((0 0,4 0,2 2,0 0))', true);
래스터 출력
POLYHEDRALSURFACE(((0 0,2 0.82842712474619,2 2,0 0)),((4 0,2 0.82842712474619,0 0,4 0)),((2 2,2 0.82842712474619,4 0,2 2)))
Figure
Geometry figure for visual-cg-straightskeletonpartition-01

Straight skeleton partition of a polygon.

Code
WITH data AS (
  SELECT 'POLYGON((190 190,10 190,10 10,190 10,190 20,160 30,60 30,60 130,190 140,190 190))'::geometry AS polygon
)
SELECT polygon AS input_polygon,
       CG_StraightSkeletonPartition(polygon, true) AS skeleton_partition
FROM data;
래스터 출력
POLYGON((190 190,10 190,10 10,190 10,190 20,160 30,60 30,60 130,190 140,190 190)) | POLYHEDRALSURFACE(((190 190,164.04 164.04,190 140,190 190)),((10 190,40.697 159.303,164.04 164.04,190 190,10 190)),((10 10,35 35,35 153.151,40.697 159.303,10 190,10 10)),((190 10,184.189 15.811,158.377 20,50 20,35 35,10 10,190 10)),((190 20,184.189 15.811,190 10,190 20)),((160 30,158.377 20,184.189 15.811,190 20,160 30)),((60 30,50 20,158.377 20,160 30,60 30)),((60 130,35 153.151,35 35,50 20,60 30,60 130)),((190 140,164.04 164.04,40.697 159.303,35 153.151,60 130,190 140)))
Figure
Geometry figure for visual-cg-straightskeletonpartition-02

제목

CG_3DBuffer — Computes a 3D buffer around a geometry.

요약

geometry CG_3DBuffer(geometry geom, float8 radius, integer segments, integer buffer_type);

설명

Generates a 3D buffer around the input geometry geom with a specified radius. The buffer is constructed in 3D space, creating a volumetric representation of the geometry's surroundings. The segments parameter defines the number of segments used to approximate the curved sections of the buffer, with a minimum value of 4 segments required. The buffer_type specifies the type of buffer to create: 0: Rounded buffer (default) 1: Flat buffer 2: Square buffer

Input geometry must be a Point or LineString.

Availability: 3.6.0 - requires SFCGAL >= 2.0.0

This method needs SFCGAL backend.

예시

Code
SELECT CG_3DBuffer('POINT(0 0 0)', 1, 8, 0);
래스터 출력
POLYHEDRALSURFACE Z (((0 0 1, 0.5 -0.5 0.71, 0 -0.71 0.71, 0 0 1)), ... )

A rounded point buffer using 32 segments.

Code
SELECT
  'POINT(100 90)'::geometry AS input_geometry,
  CG_3DBuffer('POINT(100 90)'::geometry, 50, 32, 0) AS buffer;
래스터 출력
POINT(100 90) | POLYHEDRALSURFACE Z (((74 133 0,66 126 7,78 133 12,74 133 0)),((60 115 15,71 124 21,66 126 7,60 115 15)),((85 130 25,78 133 12,71 124 21,85 130 25)),((66 126 7,71 124 21,78 133 12,66 126 7)),((57 90 26,64 97 34,57 102 22,57 90 26)),((75 105 40,66 111 29,64 97 34,75 105 40)),((60 115 15,57 102 22,66 111 29,60 115 15)),((64 97 34,66 111 29,57 102 22,64 97 34)),((100 116 43,93 124 36,88 112 43,100 116 43)),((85 130 25,79 119 34,93 124 36,85 130 25)),((75 105 40,88 112 43,79 119 34,75 105 40)),((93 124 36,79 119 34,88 112 43,93 124 36)),((60 115 15,66 111 29,71 124 21,60 115 15)),((75 105 40,79 119 34,66 111 29,75 105 40)),((85 130 25,71 124 21,79 119 34,85 130 25)),((66 111 29,79 119 34,71 124 21,66 111 29)),((74 133 0,78 133 12,85 138 0,74 133 0)),((85 130 25,92 138 13,78 133 12,85 130 25)),((100 140 0,85 138 0,92 138 13,100 140 0)),((78 133 12,92 138 13,85 138 0,78 133 12)),((100 116 43,107 124 36,93 124 36,100 116 43)),((115 130 25,100 133 26,107 124 36,115 130 25)),((85 130 25,93 124 36,100 133 26,85 130 25)),((107 124 36,100 133 26,93 124 36,107 124 36)),((126 133 0,115 138 0,122 133 12,126 133 0)),((100 140 0,108 138 13,115 138 0,100 140 0)),((115 130 25,122 133 12,108 138 13,115 130 25)),((115 138 0,108 138 13,122 133 12,115 138 0)),((85 130 25,100 133 26,92 138 13,85 130 25)),((115 130 25,108 138 13,100 133 26,115 130 25)),((100 140 0,92 138 13,108 138 13,100 140 0)),((100 133 26,108 138 13,92 138 13,100 133 26)),((74 133 0,85 138 0,78 133 -12,74 133 0)),((100 140 0,92 138 -13,85 138 0,100 140 0)),((85 130 -25,78 133 -12,92 138 -13,85 130 -25)),((85 138 0,92 138 -13,78 133 -12,85 138 0)),((126 133 0,122 133 -12,115 138 0,126 133 0)),((115 130 -25,108 138 -13,122 133 -12,115 130 -25)),((100 140 0,115 138 0,108 138 -13,100 140 0)),((122 133 -12,108 138 -13,115 138 0,122 133 -12)),((100 116 -43,93 124 -36,107 124 -36,100 116 -43)),((85 130 -25,100 133 -26,93 124 -36,85 130 -25)),((115 130 -25,107 124 -36,100 133 -26,115 130 -25)),((93 124 -36,100 133 -26,107 124 -36,93 124 -36)),((100 140 0,108 138 -13,92 138 -13,100 140 0)),((115 130 -25,100 133 -26,108 138 -13,115 130 -25)),((85 130 -25,92 138 -13,100 133 -26,85 130 -25)),((108 138 -13,100 133 -26,92 138 -13,108 138 -13)),((74 133 0,78 133 -12,66 126 -7,74 133 0)),((85 130 -25,71 124 -21,78 133 -12,85 130 -25)),((60 115 -15,66 126 -7,71 124 -21,60 115 -15)),((78 133 -12,71 124 -21,66 126 -7,78 133 -12)),((100 116 -43,88 112 -43,93 124 -36,100 116 -43)),((75 105 -40,79 119 -34,88 112 -43,75 105 -40)),((85 130 -25,93 124 -36,79 119 -34,85 130 -25)),((88 112 -43,79 119 -34,93 124 -36,88 112 -43)),((57 90 -26,57 102 -22,64 97 -34,57 90 -26)),((60 115 -15,66 111 -29,57 102 -22,60 115 -15)),((75 105 -40,64 97 -34,66 111 -29,75 105 -40)),((57 102 -22,66 111 -29,64 97 -34,57 102 -22)),((85 130 -25,79 119 -34,71 124 -21,85 130 -25)),((75 105 -40,66 111 -29,79 119 -34,75 105 -40)),((60 115 -15,71 124 -21,66 111 -29,60 115 -15)),((79 119 -34,66 111 -29,71 124 -21,79 119 -34)),((74 133 0,66 126 -7,66 126 7,74 133 0)),((60 115 -15,57 116 0,66 126 -7,60 115 -15)),((60 115 15,66 126 7,57 116 0,60 115 15)),((66 126 -7,57 116 0,66 126 7,66 126 -7)),((57 90 -26,52 90 -15,57 102 -22,57 90 -26)),((50 90 0,52 103 -8,52 90 -15,50 90 0)),((60 115 -15,57 102 -22,52 103 -8,60 115 -15)),((52 90 -15,52 103 -8,57 102 -22,52 90 -15)),((57 90 26,57 102 22,52 90 15,57 90 26)),((60 115 15,52 103 8,57 102 22,60 115 15)),((50 90 0,52 90 15,52 103 8,50 90 0)),((57 102 22,52 103 8,52 90 15,57 102 22)),((60 115 -15,52 103 -8,57 116 0,60 115 -15)),((50 90 0,52 103 8,52 103 -8,50 90 0)),((60 115 15,57 116 0,52 103 8,60 115 15)),((52 103 -8,52 103 8,57 116 0,52 103 -8)),((126 133 0,122 133 12,134 126 7,126 133 0)),((115 130 25,129 124 21,122 133 12,115 130 25)),((140 115 15,134 126 7,129 124 21,140 115 15)),((122 133 12,129 124 21,134 126 7,122 133 12)),((100 116 43,112 112 43,107 124 36,100 116 43)),((125 105 40,121 119 34,112 112 43,125 105 40)),((115 130 25,107 124 36,121 119 34,115 130 25)),((112 112 43,121 119 34,107 124 36,112 112 43)),((143 90 26,143 102 22,136 97 34,143 90 26)),((140 115 15,134 111 29,143 102 22,140 115 15)),((125 105 40,136 97 34,134 111 29,125 105 40)),((143 102 22,134 111 29,136 97 34,143 102 22)),((115 130 25,121 119 34,129 124 21,115 130 25)),((125 105 40,134 111 29,121 119 34,125 105 40)),((140 115 15,129 124 21,134 111 29,140 115 15)),((121 119 34,134 111 29,129 124 21,121 119 34)),((100 116 43,88 112 43,100 105 48,100 116 43)),((75 105 40,87 98 48,88 112 43,75 105 40)),((100 90 50,100 105 48,87 98 48,100 90 50)),((88 112 43,87 98 48,100 105 48,88 112 43)),((57 90 26,64 83 34,64 97 34,57 90 26)),((75 75 40,74 90 43,64 83 34,75 75 40)),((75 105 40,64 97 34,74 90 43,75 105 40)),((64 83 34,74 90 43,64 97 34,64 83 34)),((100 64 43,100 75 48,88 68 43,100 64 43)),((100 90 50,87 82 48,100 75 48,100 90 50)),((75 75 40,88 68 43,87 82 48,75 75 40)),((100 75 48,87 82 48,88 68 43,100 75 48)),((75 105 40,74 90 43,87 98 48,75 105 40)),((75 75 40,87 82 48,74 90 43,75 75 40)),((100 90 50,87 98 48,87 82 48,100 90 50)),((74 90 43,87 82 48,87 98 48,74 90 43)),((57 90 26,52 90 15,57 78 22,57 90 26)),((50 90 0,52 77 8,52 90 15,50 90 0)),((60 65 15,57 78 22,52 77 8,60 65 15)),((52 90 15,52 77 8,57 78 22,52 90 15)),((57 90 -26,57 78 -22,52 90 -15,57 90 -26)),((60 65 -15,52 77 -8,57 78 -22,60 65 -15)),((50 90 0,52 90 -15,52 77 -8,50 90 0)),((57 78 -22,52 77 -8,52 90 -15,57 78 -22)),((74 47 0,66 54 7,66 54 -7,74 47 0)),((60 65 15,57 64 0,66 54 7,60 65 15)),((60 65 -15,66 54 -7,57 64 0,60 65 -15)),((66 54 7,57 64 0,66 54 -7,66 54 7)),((50 90 0,52 77 -8,52 77 8,50 90 0)),((60 65 -15,57 64 0,52 77 -8,60 65 -15)),((60 65 15,52 77 8,57 64 0,60 65 15)),((52 77 -8,57 64 0,52 77 8,52 77 -8)),((57 90 -26,64 97 -34,64 83 -34,57 90 -26)),((75 105 -40,74 90 -43,64 97 -34,75 105 -40)),((75 75 -40,64 83 -34,74 90 -43,75 75 -40)),((64 97 -34,74 90 -43,64 83 -34,64 97 -34)),((100 116 -43,100 105 -48,88 112 -43,100 116 -43)),((100 90 -50,87 98 -48,100 105 -48,100 90 -50)),((75 105 -40,88 112 -43,87 98 -48,75 105 -40)),((100 105 -48,87 98 -48,88 112 -43,100 105 -48)),((100 64 -43,88 68 -43,100 75 -48,100 64 -43)),((75 75 -40,87 82 -48,88 68 -43,75 75 -40)),((100 90 -50,100 75 -48,87 82 -48,100 90 -50)),((88 68 -43,87 82 -48,100 75 -48,88 68 -43)),((75 105 -40,87 98 -48,74 90 -43,75 105 -40)),((100 90 -50,87 82 -48,87 98 -48,100 90 -50)),((75 75 -40,74 90 -43,87 82 -48,75 75 -40)),((87 98 -48,87 82 -48,74 90 -43,87 98 -48)),((100 116 -43,107 124 -36,112 112 -43,100 116 -43)),((115 130 -25,121 119 -34,107 124 -36,115 130 -25)),((125 105 -40,112 112 -43,121 119 -34,125 105 -40)),((107 124 -36,121 119 -34,112 112 -43,107 124 -36)),((126 133 0,134 126 -7,122 133 -12,126 133 0)),((140 115 -15,129 124 -21,134 126 -7,140 115 -15)),((115 130 -25,122 133 -12,129 124 -21,115 130 -25)),((134 126 -7,129 124 -21,122 133 -12,134 126 -7)),((143 90 -26,136 97 -34,143 102 -22,143 90 -26)),((125 105 -40,134 111 -29,136 97 -34,125 105 -40)),((140 115 -15,143 102 -22,134 111 -29,140 115 -15)),((136 97 -34,134 111 -29,143 102 -22,136 97 -34)),((115 130 -25,129 124 -21,121 119 -34,115 130 -25)),((140 115 -15,134 111 -29,129 124 -21,140 115 -15)),((125 105 -40,121 119 -34,134 111 -29,125 105 -40)),((129 124 -21,134 111 -29,121 119 -34,129 124 -21)),((126 47 0,134 54 7,122 47 12,126 47 0)),((140 65 15,129 56 21,134 54 7,140 65 15)),((115 50 25,122 47 12,129 56 21,115 50 25)),((134 54 7,129 56 21,122 47 12,134 54 7)),((143 90 26,136 83 34,143 78 22,143 90 26)),((125 75 40,134 69 29,136 83 34,125 75 40)),((140 65 15,143 78 22,134 69 29,140 65 15)),((136 83 34,134 69 29,143 78 22,136 83 34)),((100 64 43,107 56 36,112 68 43,100 64 43)),((115 50 25,121 61 34,107 56 36,115 50 25)),((125 75 40,112 68 43,121 61 34,125 75 40)),((107 56 36,121 61 34,112 68 43,107 56 36)),((140 65 15,134 69 29,129 56 21,140 65 15)),((125 75 40,121 61 34,134 69 29,125 75 40)),((115 50 25,129 56 21,121 61 34,115 50 25)),((134 69 29,121 61 34,129 56 21,134 69 29)),((126 47 0,122 47 12,115 42 0,126 47 0)),((115 50 25,108 42 13,122 47 12,115 50 25)),((100 40 0,115 42 0,108 42 13,100 40 0)),((122 47 12,108 42 13,115 42 0,122 47 12)),((100 64 43,93 56 36,107 56 36,100 64 43)),((85 50 25,100 47 26,93 56 36,85 50 25)),((115 50 25,107 56 36,100 47 26,115 50 25)),((93 56 36,100 47 26,107 56 36,93 56 36)),((74 47 0,85 42 0,78 47 12,74 47 0)),((100 40 0,92 42 13,85 42 0,100 40 0)),((85 50 25,78 47 12,92 42 13,85 50 25)),((85 42 0,92 42 13,78 47 12,85 42 0)),((115 50 25,100 47 26,108 42 13,115 50 25)),((85 50 25,92 42 13,100 47 26,85 50 25)),((100 40 0,108 42 13,92 42 13,100 40 0)),((100 47 26,92 42 13,108 42 13,100 47 26)),((126 47 0,115 42 0,122 47 -12,126 47 0)),((100 40 0,108 42 -13,115 42 0,100 40 0)),((115 50 -25,122 47 -12,108 42 -13,115 50 -25)),((115 42 0,108 42 -13,122 47 -12,115 42 0)),((74 47 0,78 47 -12,85 42 0,74 47 0)),((85 50 -25,92 42 -13,78 47 -12,85 50 -25)),((100 40 0,85 42 0,92 42 -13,100 40 0)),((78 47 -12,92 42 -13,85 42 0,78 47 -12)),((100 64 -43,107 56 -36,93 56 -36,100 64 -43)),((115 50 -25,100 47 -26,107 56 -36,115 50 -25)),((85 50 -25,93 56 -36,100 47 -26,85 50 -25)),((107 56 -36,100 47 -26,93 56 -36,107 56 -36)),((100 40 0,92 42 -13,108 42 -13,100 40 0)),((85 50 -25,100 47 -26,92 42 -13,85 50 -25)),((115 50 -25,108 42 -13,100 47 -26,115 50 -25)),((92 42 -13,100 47 -26,108 42 -13,92 42 -13)),((126 47 0,122 47 -12,134 54 -7,126 47 0)),((115 50 -25,129 56 -21,122 47 -12,115 50 -25)),((140 65 -15,134 54 -7,129 56 -21,140 65 -15)),((122 47 -12,129 56 -21,134 54 -7,122 47 -12)),((100 64 -43,112 68 -43,107 56 -36,100 64 -43)),((125 75 -40,121 61 -34,112 68 -43,125 75 -40)),((115 50 -25,107 56 -36,121 61 -34,115 50 -25)),((112 68 -43,121 61 -34,107 56 -36,112 68 -43)),((143 90 -26,143 78 -22,136 83 -34,143 90 -26)),((140 65 -15,134 69 -29,143 78 -22,140 65 -15)),((125 75 -40,136 83 -34,134 69 -29,125 75 -40)),((143 78 -22,134 69 -29,136 83 -34,143 78 -22)),((115 50 -25,121 61 -34,129 56 -21,115 50 -25)),((125 75 -40,134 69 -29,121 61 -34,125 75 -40)),((140 65 -15,129 56 -21,134 69 -29,140 65 -15)),((121 61 -34,134 69 -29,129 56 -21,121 61 -34)),((126 47 0,134 54 -7,134 54 7,126 47 0)),((140 65 -15,143 64 0,134 54 -7,140 65 -15)),((140 65 15,134 54 7,143 64 0,140 65 15)),((134 54 -7,143 64 0,134 54 7,134 54 -7)),((143 90 -26,148 90 -15,143 78 -22,143 90 -26)),((150 90 0,148 77 -8,148 90 -15,150 90 0)),((140 65 -15,143 78 -22,148 77 -8,140 65 -15)),((148 90 -15,148 77 -8,143 78 -22,148 90 -15)),((143 90 26,143 78 22,148 90 15,143 90 26)),((140 65 15,148 77 8,143 78 22,140 65 15)),((150 90 0,148 90 15,148 77 8,150 90 0)),((143 78 22,148 77 8,148 90 15,143 78 22)),((140 65 -15,148 77 -8,143 64 0,140 65 -15)),((150 90 0,148 77 8,148 77 -8,150 90 0)),((140 65 15,143 64 0,148 77 8,140 65 15)),((148 77 -8,148 77 8,143 64 0,148 77 -8)),((100 64 43,112 68 43,100 75 48,100 64 43)),((125 75 40,113 82 48,112 68 43,125 75 40)),((100 90 50,100 75 48,113 82 48,100 90 50)),((112 68 43,113 82 48,100 75 48,112 68 43)),((143 90 26,136 97 34,136 83 34,143 90 26)),((125 105 40,126 90 43,136 97 34,125 105 40)),((125 75 40,136 83 34,126 90 43,125 75 40)),((136 97 34,126 90 43,136 83 34,136 97 34)),((100 116 43,100 105 48,112 112 43,100 116 43)),((100 90 50,113 98 48,100 105 48,100 90 50)),((125 105 40,112 112 43,113 98 48,125 105 40)),((100 105 48,113 98 48,112 112 43,100 105 48)),((125 75 40,126 90 43,113 82 48,125 75 40)),((125 105 40,113 98 48,126 90 43,125 105 40)),((100 90 50,113 82 48,113 98 48,100 90 50)),((126 90 43,113 98 48,113 82 48,126 90 43)),((74 47 0,78 47 12,66 54 7,74 47 0)),((85 50 25,71 56 21,78 47 12,85 50 25)),((60 65 15,66 54 7,71 56 21,60 65 15)),((78 47 12,71 56 21,66 54 7,78 47 12)),((100 64 43,88 68 43,93 56 36,100 64 43)),((75 75 40,79 61 34,88 68 43,75 75 40)),((85 50 25,93 56 36,79 61 34,85 50 25)),((88 68 43,79 61 34,93 56 36,88 68 43)),((57 90 26,57 78 22,64 83 34,57 90 26)),((60 65 15,66 69 29,57 78 22,60 65 15)),((75 75 40,64 83 34,66 69 29,75 75 40)),((57 78 22,66 69 29,64 83 34,57 78 22)),((85 50 25,79 61 34,71 56 21,85 50 25)),((75 75 40,66 69 29,79 61 34,75 75 40)),((60 65 15,71 56 21,66 69 29,60 65 15)),((79 61 34,66 69 29,71 56 21,79 61 34)),((100 64 -43,93 56 -36,88 68 -43,100 64 -43)),((85 50 -25,79 61 -34,93 56 -36,85 50 -25)),((75 75 -40,88 68 -43,79 61 -34,75 75 -40)),((93 56 -36,79 61 -34,88 68 -43,93 56 -36)),((74 47 0,66 54 -7,78 47 -12,74 47 0)),((60 65 -15,71 56 -21,66 54 -7,60 65 -15)),((85 50 -25,78 47 -12,71 56 -21,85 50 -25)),((66 54 -7,71 56 -21,78 47 -12,66 54 -7)),((57 90 -26,64 83 -34,57 78 -22,57 90 -26)),((75 75 -40,66 69 -29,64 83 -34,75 75 -40)),((60 65 -15,57 78 -22,66 69 -29,60 65 -15)),((64 83 -34,66 69 -29,57 78 -22,64 83 -34)),((85 50 -25,71 56 -21,79 61 -34,85 50 -25)),((60 65 -15,66 69 -29,71 56 -21,60 65 -15)),((75 75 -40,79 61 -34,66 69 -29,75 75 -40)),((71 56 -21,66 69 -29,79 61 -34,71 56 -21)),((143 90 -26,136 83 -34,136 97 -34,143 90 -26)),((125 75 -40,126 90 -43,136 83 -34,125 75 -40)),((125 105 -40,136 97 -34,126 90 -43,125 105 -40)),((136 83 -34,126 90 -43,136 97 -34,136 83 -34)),((100 64 -43,100 75 -48,112 68 -43,100 64 -43)),((100 90 -50,113 82 -48,100 75 -48,100 90 -50)),((125 75 -40,112 68 -43,113 82 -48,125 75 -40)),((100 75 -48,113 82 -48,112 68 -43,100 75 -48)),((100 116 -43,112 112 -43,100 105 -48,100 116 -43)),((125 105 -40,113 98 -48,112 112 -43,125 105 -40)),((100 90 -50,100 105 -48,113 98 -48,100 90 -50)),((112 112 -43,113 98 -48,100 105 -48,112 112 -43)),((125 75 -40,113 82 -48,126 90 -43,125 75 -40)),((100 90 -50,113 98 -48,113 82 -48,100 90 -50)),((125 105 -40,126 90 -43,113 98 -48,125 105 -40)),((113 82 -48,113 98 -48,126 90 -43,113 82 -48)),((143 90 26,148 90 15,143 102 22,143 90 26)),((150 90 0,148 103 8,148 90 15,150 90 0)),((140 115 15,143 102 22,148 103 8,140 115 15)),((148 90 15,148 103 8,143 102 22,148 90 15)),((143 90 -26,143 102 -22,148 90 -15,143 90 -26)),((140 115 -15,148 103 -8,143 102 -22,140 115 -15)),((150 90 0,148 90 -15,148 103 -8,150 90 0)),((143 102 -22,148 103 -8,148 90 -15,143 102 -22)),((126 133 0,134 126 7,134 126 -7,126 133 0)),((140 115 15,143 116 0,134 126 7,140 115 15)),((140 115 -15,134 126 -7,143 116 0,140 115 -15)),((134 126 7,143 116 0,134 126 -7,134 126 7)),((150 90 0,148 103 -8,148 103 8,150 90 0)),((140 115 -15,143 116 0,148 103 -8,140 115 -15)),((140 115 15,148 103 8,143 116 0,140 115 15)),((148 103 -8,143 116 0,148 103 8,148 103 -8)))
Figure
Geometry figure for visual-cg-3dbuffer-02

A coarser rounded point buffer using 5 segments.

Code
SELECT
  'POINT(100 90)'::geometry AS input_geometry,
  CG_3DBuffer('POINT(100 90)'::geometry, 50, 5, 0) AS buffer;
래스터 출력
POINT(100 90) | POLYHEDRALSURFACE Z (((74 133 0,60 115 15,85 130 25,74 133 0)),((57 90 26,75 105 40,60 115 15,57 90 26)),((100 116 43,85 130 25,75 105 40,100 116 43)),((60 115 15,75 105 40,85 130 25,60 115 15)),((74 133 0,85 130 25,100 140 0,74 133 0)),((100 116 43,115 130 25,85 130 25,100 116 43)),((126 133 0,100 140 0,115 130 25,126 133 0)),((85 130 25,115 130 25,100 140 0,85 130 25)),((74 133 0,100 140 0,85 130 -25,74 133 0)),((126 133 0,115 130 -25,100 140 0,126 133 0)),((100 116 -43,85 130 -25,115 130 -25,100 116 -43)),((100 140 0,115 130 -25,85 130 -25,100 140 0)),((74 133 0,85 130 -25,60 115 -15,74 133 0)),((100 116 -43,75 105 -40,85 130 -25,100 116 -43)),((57 90 -26,60 115 -15,75 105 -40,57 90 -26)),((85 130 -25,75 105 -40,60 115 -15,85 130 -25)),((74 133 0,60 115 -15,60 115 15,74 133 0)),((57 90 -26,50 90 0,60 115 -15,57 90 -26)),((57 90 26,60 115 15,50 90 0,57 90 26)),((60 115 -15,50 90 0,60 115 15,60 115 -15)),((126 133 0,115 130 25,140 115 15,126 133 0)),((100 116 43,125 105 40,115 130 25,100 116 43)),((143 90 26,140 115 15,125 105 40,143 90 26)),((115 130 25,125 105 40,140 115 15,115 130 25)),((100 116 43,75 105 40,100 90 50,100 116 43)),((57 90 26,75 75 40,75 105 40,57 90 26)),((100 64 43,100 90 50,75 75 40,100 64 43)),((75 105 40,75 75 40,100 90 50,75 105 40)),((57 90 26,50 90 0,60 65 15,57 90 26)),((57 90 -26,60 65 -15,50 90 0,57 90 -26)),((74 47 0,60 65 15,60 65 -15,74 47 0)),((50 90 0,60 65 -15,60 65 15,50 90 0)),((57 90 -26,75 105 -40,75 75 -40,57 90 -26)),((100 116 -43,100 90 -50,75 105 -40,100 116 -43)),((100 64 -43,75 75 -40,100 90 -50,100 64 -43)),((75 105 -40,100 90 -50,75 75 -40,75 105 -40)),((100 116 -43,115 130 -25,125 105 -40,100 116 -43)),((126 133 0,140 115 -15,115 130 -25,126 133 0)),((143 90 -26,125 105 -40,140 115 -15,143 90 -26)),((115 130 -25,140 115 -15,125 105 -40,115 130 -25)),((126 47 0,140 65 15,115 50 25,126 47 0)),((143 90 26,125 75 40,140 65 15,143 90 26)),((100 64 43,115 50 25,125 75 40,100 64 43)),((140 65 15,125 75 40,115 50 25,140 65 15)),((126 47 0,115 50 25,100 40 0,126 47 0)),((100 64 43,85 50 25,115 50 25,100 64 43)),((74 47 0,100 40 0,85 50 25,74 47 0)),((115 50 25,85 50 25,100 40 0,115 50 25)),((126 47 0,100 40 0,115 50 -25,126 47 0)),((74 47 0,85 50 -25,100 40 0,74 47 0)),((100 64 -43,115 50 -25,85 50 -25,100 64 -43)),((100 40 0,85 50 -25,115 50 -25,100 40 0)),((126 47 0,115 50 -25,140 65 -15,126 47 0)),((100 64 -43,125 75 -40,115 50 -25,100 64 -43)),((143 90 -26,140 65 -15,125 75 -40,143 90 -26)),((115 50 -25,125 75 -40,140 65 -15,115 50 -25)),((126 47 0,140 65 -15,140 65 15,126 47 0)),((143 90 -26,150 90 0,140 65 -15,143 90 -26)),((143 90 26,140 65 15,150 90 0,143 90 26)),((140 65 -15,150 90 0,140 65 15,140 65 -15)),((100 64 43,125 75 40,100 90 50,100 64 43)),((143 90 26,125 105 40,125 75 40,143 90 26)),((100 116 43,100 90 50,125 105 40,100 116 43)),((125 75 40,125 105 40,100 90 50,125 75 40)),((74 47 0,85 50 25,60 65 15,74 47 0)),((100 64 43,75 75 40,85 50 25,100 64 43)),((57 90 26,60 65 15,75 75 40,57 90 26)),((85 50 25,75 75 40,60 65 15,85 50 25)),((100 64 -43,85 50 -25,75 75 -40,100 64 -43)),((74 47 0,60 65 -15,85 50 -25,74 47 0)),((57 90 -26,75 75 -40,60 65 -15,57 90 -26)),((85 50 -25,60 65 -15,75 75 -40,85 50 -25)),((143 90 -26,125 75 -40,125 105 -40,143 90 -26)),((100 64 -43,100 90 -50,125 75 -40,100 64 -43)),((100 116 -43,125 105 -40,100 90 -50,100 116 -43)),((125 75 -40,100 90 -50,125 105 -40,125 75 -40)),((143 90 26,150 90 0,140 115 15,143 90 26)),((143 90 -26,140 115 -15,150 90 0,143 90 -26)),((126 133 0,140 115 15,140 115 -15,126 133 0)),((150 90 0,140 115 -15,140 115 15,150 90 0)))
Figure
Geometry figure for visual-cg-3dbuffer-03

A rounded buffer around a line using 32 segments.

Code
SELECT
  'LINESTRING(50 50,150 150,150 50)'::geometry AS input_geometry,
  CG_3DBuffer('LINESTRING(50 50,150 150,150 50)'::geometry, 10, 32, 0) AS buffer;
래스터 출력
LINESTRING(50 50,150 150,150 50) | POLYHEDRALSURFACE Z (((40 50 3,40 50 0,40 47 2,40 50 3)),((40 47 2,40 50 0,40 47 -2,40 47 2)),((40 47 -2,40 50 0,40 50 -3,40 47 -2)),((40 50 -3,40 50 0,40 53 -2,40 50 -3)),((40 53 -2,40 50 0,40 53 2,40 53 -2)),((40 53 2,40 50 0,40 50 3,40 53 2)),((40 53 2,40 50 3,41 52 4,40 53 2)),((41 52 4,40 50 3,41 50 5,41 52 4)),((41 50 5,40 50 3,41 48 4,41 50 5)),((41 48 4,40 50 3,40 47 2,41 48 4)),((40 47 2,40 47 -2,41 45 0,40 47 2)),((41 48 4,40 47 2,42 45 3,41 48 4)),((42 45 3,40 47 2,41 45 0,42 45 3)),((41 45 0,40 47 -2,42 45 -3,41 45 0)),((42 45 -3,40 47 -2,41 48 -4,42 45 -3)),((40 47 -2,40 50 -3,41 48 -4,40 47 -2)),((41 48 -4,40 50 -3,41 50 -5,41 48 -4)),((41 50 -5,40 50 -3,41 52 -4,41 50 -5)),((41 52 -4,40 50 -3,40 53 -2,41 52 -4)),((41 55 0,40 53 -2,40 53 2,41 55 0)),((41 52 -4,40 53 -2,42 55 -3,41 52 -4)),((42 55 -3,40 53 -2,41 55 0,42 55 -3)),((41 55 0,40 53 2,42 55 3,41 55 0)),((42 55 3,40 53 2,41 52 4,42 55 3)),((42 55 3,41 52 4,43 54 6,42 55 3)),((43 54 6,41 52 4,43 51 7,43 54 6)),((43 51 7,41 52 4,41 50 5,43 51 7)),((43 51 7,41 50 5,43 49 7,43 51 7)),((41 50 5,41 48 4,43 49 7,41 50 5)),((43 49 7,41 48 4,43 46 6,43 49 7)),((43 46 6,41 48 4,42 45 3,43 46 6)),((42 45 3,41 45 0,43 43 1,42 45 3)),((43 43 1,41 45 0,43 43 -1,43 43 1)),((43 43 -1,41 45 0,42 45 -3,43 43 -1)),((43 46 6,42 45 3,44 43 4,43 46 6)),((44 43 4,42 45 3,43 43 1,44 43 4)),((44 43 -4,42 45 -3,43 46 -6,44 43 -4)),((42 45 -3,41 48 -4,43 46 -6,42 45 -3)),((43 43 -1,42 45 -3,44 43 -4,43 43 -1)),((43 46 -6,41 48 -4,43 49 -7,43 46 -6)),((43 49 -7,41 48 -4,41 50 -5,43 49 -7)),((43 49 -7,41 50 -5,43 51 -7,43 49 -7)),((41 50 -5,41 52 -4,43 51 -7,41 50 -5)),((43 51 -7,41 52 -4,43 54 -6,43 51 -7)),((43 54 -6,41 52 -4,42 55 -3,43 54 -6)),((42 55 -3,41 55 0,43 57 -1,42 55 -3)),((43 57 -1,41 55 0,43 57 1,43 57 -1)),((43 57 1,41 55 0,42 55 3,43 57 1)),((43 54 -6,42 55 -3,44 57 -4,43 54 -6)),((44 57 -4,42 55 -3,43 57 -1,44 57 -4)),((43 57 1,42 55 3,44 57 4,43 57 1)),((44 57 4,42 55 3,43 54 6,44 57 4)),((43 54 6,46 56 7,44 57 4,43 54 6)),((44 57 4,46 56 7,146 156 7,44 57 4)),((44 57 4,146 156 7,144 157 4,44 57 4)),((46 56 7,43 54 6,45 53 8,46 56 7)),((43 54 6,43 51 7,45 53 8,43 54 6)),((45 53 8,43 51 7,45 50 9,45 53 8)),((43 51 7,43 49 7,45 50 9,43 51 7)),((45 50 9,43 49 7,45 47 8,45 50 9)),((45 47 8,43 49 7,43 46 6,45 47 8)),((45 47 8,43 46 6,46 44 7,45 47 8)),((46 44 7,43 46 6,44 43 4,46 44 7)),((43 43 1,43 43 -1,45 41 0,43 43 1)),((44 43 4,43 43 1,46 41 2,44 43 4)),((46 41 2,43 43 1,45 41 0,46 41 2)),((45 41 0,43 43 -1,46 41 -2,45 41 0)),((46 41 -2,43 43 -1,44 43 -4,46 41 -2)),((46 44 7,44 43 4,47 42 5,46 44 7)),((47 42 5,44 43 4,46 41 2,47 42 5)),((47 42 -5,44 43 -4,46 44 -7,47 42 -5)),((44 43 -4,43 46 -6,46 44 -7,44 43 -4)),((46 41 -2,44 43 -4,47 42 -5,46 41 -2)),((46 44 -7,43 46 -6,45 47 -8,46 44 -7)),((43 46 -6,43 49 -7,45 47 -8,43 46 -6)),((45 47 -8,43 49 -7,45 50 -9,45 47 -8)),((45 50 -9,43 49 -7,43 51 -7,45 50 -9)),((45 50 -9,43 51 -7,45 53 -8,45 50 -9)),((45 53 -8,43 51 -7,43 54 -6,45 53 -8)),((45 53 -8,43 54 -6,46 56 -7,45 53 -8)),((43 54 -6,44 57 -4,46 56 -7,43 54 -6)),((46 56 -7,44 57 -4,144 157 -4,46 56 -7)),((46 56 -7,144 157 -4,146 156 -7,46 56 -7)),((43 57 -1,43 57 1,143 157 -1,43 57 -1)),((143 157 -1,43 57 1,143 157 1,143 157 -1)),((43 57 -1,143 157 -1,44 57 -4,43 57 -1)),((44 57 -4,143 157 -1,144 157 -4,44 57 -4)),((43 57 1,44 57 4,143 157 1,43 57 1)),((143 157 1,44 57 4,144 157 4,143 157 1)),((146 159 2,143 157 1,144 157 4,146 159 2)),((146 159 2,144 157 4,147 158 5,146 159 2)),((147 158 5,144 157 4,146 156 7,147 158 5)),((46 56 7,45 53 8,145 153 8,46 56 7)),((146 156 7,46 56 7,145 153 8,146 156 7)),((147 158 5,146 156 7,149 157 7,147 158 5)),((149 157 7,146 156 7,148 154 9,149 157 7)),((146 156 7,145 153 8,148 154 9,146 156 7)),((145 153 8,45 53 8,48 54 9,145 153 8)),((148 154 9,145 153 8,48 54 9,148 154 9)),((48 54 9,45 53 8,47 52 10,48 54 9)),((45 53 8,45 50 9,47 52 10,45 53 8)),((47 52 10,45 50 9,47 48 10,47 52 10)),((47 48 10,45 50 9,45 47 8,47 48 10)),((47 48 10,45 47 8,48 46 9,47 48 10)),((48 46 9,45 47 8,46 44 7,48 46 9)),((48 46 9,46 44 7,49 43 7,48 46 9)),((49 43 7,46 44 7,47 42 5,49 43 7)),((46 41 2,45 41 0,47 40 0,46 41 2)),((47 40 0,45 41 0,46 41 -2,47 40 0)),((47 42 5,46 41 2,48 40 3,47 42 5)),((48 40 3,46 41 2,47 40 0,48 40 3)),((48 40 -3,46 41 -2,47 42 -5,48 40 -3)),((47 40 0,46 41 -2,48 40 -3,47 40 0)),((49 43 7,47 42 5,50 41 5,49 43 7)),((50 41 5,47 42 5,48 40 3,50 41 5)),((50 41 -5,47 42 -5,49 43 -7,50 41 -5)),((47 42 -5,46 44 -7,49 43 -7,47 42 -5)),((48 40 -3,47 42 -5,50 41 -5,48 40 -3)),((49 43 -7,46 44 -7,48 46 -9,49 43 -7)),((46 44 -7,45 47 -8,48 46 -9,46 44 -7)),((48 46 -9,45 47 -8,47 48 -10,48 46 -9)),((45 47 -8,45 50 -9,47 48 -10,45 47 -8)),((47 48 -10,45 50 -9,47 52 -10,47 48 -10)),((47 52 -10,45 50 -9,45 53 -8,47 52 -10)),((47 52 -10,45 53 -8,48 54 -9,47 52 -10)),((45 53 -8,145 153 -8,48 54 -9,45 53 -8)),((48 54 -9,145 153 -8,148 154 -9,48 54 -9)),((45 53 -8,46 56 -7,145 153 -8,45 53 -8)),((145 153 -8,46 56 -7,146 156 -7,145 153 -8)),((148 154 -9,145 153 -8,146 156 -7,148 154 -9)),((148 154 -9,146 156 -7,149 157 -7,148 154 -9)),((149 157 -7,146 156 -7,147 158 -5,149 157 -7)),((146 156 -7,144 157 -4,147 158 -5,146 156 -7)),((147 158 -5,144 157 -4,146 159 -2,147 158 -5)),((144 157 -4,143 157 -1,146 159 -2,144 157 -4)),((146 159 -2,143 157 -1,145 159 0,146 159 -2)),((145 159 0,143 157 -1,143 157 1,145 159 0)),((145 159 0,143 157 1,146 159 2,145 159 0)),((147 160 0,145 159 0,146 159 2,147 160 0)),((147 160 0,146 159 2,148 160 3,147 160 0)),((148 160 3,146 159 2,147 158 5,148 160 3)),((148 160 3,147 158 5,150 159 5,148 160 3)),((150 159 5,147 158 5,149 157 7,150 159 5)),((150 159 5,149 157 7,151 157 7,150 159 5)),((151 157 7,149 157 7,150 155 9,151 157 7)),((149 157 7,148 154 9,150 155 9,149 157 7)),((48 54 9,47 52 10,147 152 10,48 54 9)),((148 154 9,48 54 9,147 152 10,148 154 9)),((150 155 9,148 154 9,150 153 10,150 155 9)),((148 154 9,147 152 10,150 153 10,148 154 9)),((147 152 10,47 52 10,50 50 10,147 152 10)),((150 150 10,147 152 10,50 50 10,150 150 10)),((47 52 10,47 48 10,50 50 10,47 52 10)),((50 50 10,47 48 10,50 47 10,50 50 10)),((50 47 10,47 48 10,48 46 9,50 47 10)),((50 47 10,48 46 9,50 45 9,50 47 10)),((50 45 9,48 46 9,49 43 7,50 45 9)),((50 45 9,49 43 7,51 43 7,50 45 9)),((51 43 7,49 43 7,50 41 5,51 43 7)),((48 40 3,47 40 0,50 40 0,48 40 3)),((50 40 0,47 40 0,48 40 -3,50 40 0)),((50 41 5,48 40 3,52 40 3,50 41 5)),((52 40 3,48 40 3,50 40 0,52 40 3)),((50 40 0,48 40 -3,52 40 -3,50 40 0)),((52 40 -3,48 40 -3,50 41 -5,52 40 -3)),((51 43 7,50 41 5,53 42 5,51 43 7)),((53 42 5,50 41 5,52 40 3,53 42 5)),((52 40 -3,50 41 -5,53 42 -5,52 40 -3)),((53 42 -5,50 41 -5,51 43 -7,53 42 -5)),((50 41 -5,49 43 -7,51 43 -7,50 41 -5)),((51 43 -7,49 43 -7,50 45 -9,51 43 -7)),((49 43 -7,48 46 -9,50 45 -9,49 43 -7)),((50 45 -9,48 46 -9,50 47 -10,50 45 -9)),((48 46 -9,47 48 -10,50 47 -10,48 46 -9)),((50 47 -10,47 48 -10,50 50 -10,50 47 -10)),((50 50 -10,47 48 -10,47 52 -10,50 50 -10)),((47 52 -10,147 152 -10,50 50 -10,47 52 -10)),((50 50 -10,147 152 -10,150 150 -10,50 50 -10)),((47 52 -10,48 54 -9,147 152 -10,47 52 -10)),((147 152 -10,48 54 -9,148 154 -9,147 152 -10)),((150 153 -10,147 152 -10,148 154 -9,150 153 -10)),((150 153 -10,148 154 -9,150 155 -9,150 153 -10)),((150 155 -9,148 154 -9,149 157 -7,150 155 -9)),((150 155 -9,149 157 -7,151 157 -7,150 155 -9)),((151 157 -7,149 157 -7,150 159 -5,151 157 -7)),((149 157 -7,147 158 -5,150 159 -5,149 157 -7)),((150 159 -5,147 158 -5,148 160 -3,150 159 -5)),((147 158 -5,146 159 -2,148 160 -3,147 158 -5)),((148 160 -3,146 159 -2,147 160 0,148 160 -3)),((146 159 -2,145 159 0,147 160 0,146 159 -2)),((148 160 -3,147 160 0,150 160 0,148 160 -3)),((150 160 0,147 160 0,148 160 3,150 160 0)),((150 160 0,148 160 3,152 160 3,150 160 0)),((152 160 3,148 160 3,150 159 5,152 160 3)),((152 160 3,150 159 5,153 158 5,152 160 3)),((153 158 5,150 159 5,151 157 7,153 158 5)),((153 158 5,151 157 7,154 156 7,153 158 5)),((154 156 7,151 157 7,152 154 9,154 156 7)),((151 157 7,150 155 9,152 154 9,151 157 7)),((150 155 9,150 153 10,152 154 9,150 155 9)),((150 153 10,147 152 10,150 150 10,150 153 10)),((152 154 9,150 153 10,153 152 10,152 154 9)),((150 153 10,150 150 10,153 152 10,150 153 10)),((150 150 10,150 50 10,153 48 10,150 150 10)),((153 152 10,150 150 10,153 48 10,153 152 10)),((147 143 10,147 48 10,150 50 10,147 143 10)),((150 150 10,147 143 10,150 50 10,150 150 10)),((150 150 10,50 50 10,53 48 10,150 150 10)),((147 143 10,150 150 10,53 48 10,147 143 10)),((50 50 10,50 47 10,53 48 10,50 50 10)),((53 48 10,50 47 10,52 46 9,53 48 10)),((50 47 10,50 45 9,52 46 9,50 47 10)),((52 46 9,50 45 9,51 43 7,52 46 9)),((52 46 9,51 43 7,54 44 7,52 46 9)),((54 44 7,51 43 7,53 42 5,54 44 7)),((52 40 3,50 40 0,53 40 0,52 40 3)),((53 40 0,50 40 0,52 40 -3,53 40 0)),((53 42 5,52 40 3,54 41 2,53 42 5)),((54 41 2,52 40 3,53 40 0,54 41 2)),((53 40 0,52 40 -3,54 41 -2,53 40 0)),((54 41 -2,52 40 -3,53 42 -5,54 41 -2)),((54 44 7,53 42 5,56 43 4,54 44 7)),((56 43 4,53 42 5,54 41 2,56 43 4)),((54 41 -2,53 42 -5,56 43 -4,54 41 -2)),((56 43 -4,53 42 -5,54 44 -7,56 43 -4)),((53 42 -5,51 43 -7,54 44 -7,53 42 -5)),((54 44 -7,51 43 -7,52 46 -9,54 44 -7)),((51 43 -7,50 45 -9,52 46 -9,51 43 -7)),((52 46 -9,50 45 -9,50 47 -10,52 46 -9)),((52 46 -9,50 47 -10,53 48 -10,52 46 -9)),((53 48 -10,50 47 -10,50 50 -10,53 48 -10)),((50 50 -10,150 150 -10,53 48 -10,50 50 -10)),((53 48 -10,150 150 -10,147 143 -10,53 48 -10)),((147 48 -10,147 143 -10,150 50 -10,147 48 -10)),((150 50 -10,147 143 -10,150 150 -10,150 50 -10)),((150 50 -10,150 150 -10,153 48 -10,150 50 -10)),((153 48 -10,150 150 -10,153 152 -10,153 48 -10)),((153 152 -10,150 150 -10,150 153 -10,153 152 -10)),((150 150 -10,147 152 -10,150 153 -10,150 150 -10)),((153 152 -10,150 153 -10,152 154 -9,153 152 -10)),((152 154 -9,150 153 -10,150 155 -9,152 154 -9)),((152 154 -9,150 155 -9,151 157 -7,152 154 -9)),((152 154 -9,151 157 -7,154 156 -7,152 154 -9)),((154 156 -7,151 157 -7,153 158 -5,154 156 -7)),((151 157 -7,150 159 -5,153 158 -5,151 157 -7)),((153 158 -5,150 159 -5,152 160 -3,153 158 -5)),((150 159 -5,148 160 -3,152 160 -3,150 159 -5)),((152 160 -3,148 160 -3,150 160 0,152 160 -3)),((152 160 -3,150 160 0,153 160 0,152 160 -3)),((153 160 0,150 160 0,152 160 3,153 160 0)),((153 160 0,152 160 3,154 159 2,153 160 0)),((154 159 2,152 160 3,153 158 5,154 159 2)),((154 159 2,153 158 5,156 157 4,154 159 2)),((156 157 4,153 158 5,154 156 7,156 157 4)),((156 157 4,154 156 7,157 154 6,156 157 4)),((157 154 6,154 156 7,155 153 8,157 154 6)),((154 156 7,152 154 9,155 153 8,154 156 7)),((155 153 8,152 154 9,153 152 10,155 153 8)),((155 153 8,153 152 10,155 150 9,155 153 8)),((153 152 10,153 48 10,155 50 9,153 152 10)),((155 150 9,153 152 10,155 50 9,155 150 9)),((150 50 10,150 47 10,153 48 10,150 50 10)),((155 50 9,153 48 10,155 47 8,155 50 9)),((153 48 10,152 46 9,155 47 8,153 48 10)),((153 48 10,150 47 10,152 46 9,153 48 10)),((150 50 10,147 48 10,150 47 10,150 50 10)),((145 138 9,145 50 9,147 48 10,145 138 9)),((145 138 9,145 138 9,147 48 10,145 138 9)),((147 143 10,145 138 9,147 48 10,147 143 10)),((53 48 10,52 46 9,145 138 9,53 48 10)),((147 143 10,53 48 10,145 138 9,147 143 10)),((147 48 10,145 50 9,145 47 8,147 48 10)),((150 47 10,147 48 10,148 46 9,150 47 10)),((147 48 10,145 47 8,148 46 9,147 48 10)),((145 138 9,52 46 9,55 47 8,145 138 9)),((145 138 9,145 138 9,55 47 8,145 138 9)),((144 136 8,145 138 9,55 47 8,144 136 8)),((55 47 8,52 46 9,54 44 7,55 47 8)),((55 47 8,54 44 7,143 133 7,55 47 8)),((144 136 8,55 47 8,143 133 7,144 136 8)),((143 133 7,54 44 7,56 43 4,143 133 7)),((143 133 7,143 133 7,56 43 4,143 133 7)),((141 128 4,141 130 5,56 43 4,141 128 4)),((141 130 5,143 133 7,56 43 4,141 130 5)),((54 41 2,53 40 0,55 41 0,54 41 2)),((55 41 0,53 40 0,54 41 -2,55 41 0)),((56 43 4,54 41 2,57 43 1,56 43 4)),((57 43 1,54 41 2,55 41 0,57 43 1)),((55 41 0,54 41 -2,57 43 -1,55 41 0)),((57 43 -1,54 41 -2,56 43 -4,57 43 -1)),((141 128 4,56 43 4,57 43 1,141 128 4)),((140 127 3,141 128 4,57 43 1,140 127 3)),((140 126 1,140 127 3,57 43 1,140 126 1)),((57 43 -1,56 43 -4,141 128 -4,57 43 -1)),((140 126 -1,57 43 -1,140 127 -3,140 126 -1)),((140 127 -3,57 43 -1,141 128 -4,140 127 -3)),((56 43 -4,54 44 -7,143 133 -7,56 43 -4)),((141 130 -5,56 43 -4,143 133 -7,141 130 -5)),((143 133 -7,56 43 -4,143 133 -7,143 133 -7)),((141 128 -4,56 43 -4,141 130 -5,141 128 -4)),((54 44 -7,55 47 -8,143 133 -7,54 44 -7)),((143 133 -7,55 47 -8,144 136 -8,143 133 -7)),((54 44 -7,52 46 -9,55 47 -8,54 44 -7)),((52 46 -9,145 138 -9,55 47 -8,52 46 -9)),((55 47 -8,145 138 -9,145 138 -9,55 47 -8)),((55 47 -8,145 138 -9,144 136 -8,55 47 -8)),((52 46 -9,53 48 -10,145 138 -9,52 46 -9)),((145 138 -9,53 48 -10,147 143 -10,145 138 -9)),((145 50 -9,145 138 -9,147 48 -10,145 50 -9)),((147 48 -10,145 138 -9,145 138 -9,147 48 -10)),((147 48 -10,145 138 -9,147 143 -10,147 48 -10)),((150 47 -10,147 48 -10,150 50 -10,150 47 -10)),((153 48 -10,150 47 -10,150 50 -10,153 48 -10)),((145 47 -8,145 50 -9,147 48 -10,145 47 -8)),((148 46 -9,145 47 -8,147 48 -10,148 46 -9)),((148 46 -9,147 48 -10,150 47 -10,148 46 -9)),((155 47 -8,153 48 -10,155 50 -9,155 47 -8)),((153 48 -10,153 152 -10,155 50 -9,153 48 -10)),((155 50 -9,153 152 -10,155 150 -9,155 50 -9)),((152 46 -9,150 47 -10,153 48 -10,152 46 -9)),((155 47 -8,152 46 -9,153 48 -10,155 47 -8)),((155 150 -9,153 152 -10,155 153 -8,155 150 -9)),((153 152 -10,152 154 -9,155 153 -8,153 152 -10)),((155 153 -8,152 154 -9,154 156 -7,155 153 -8)),((155 153 -8,154 156 -7,157 154 -6,155 153 -8)),((157 154 -6,154 156 -7,156 157 -4,157 154 -6)),((154 156 -7,153 158 -5,156 157 -4,154 156 -7)),((156 157 -4,153 158 -5,154 159 -2,156 157 -4)),((153 158 -5,152 160 -3,154 159 -2,153 158 -5)),((154 159 -2,152 160 -3,153 160 0,154 159 -2)),((154 159 -2,153 160 0,155 159 0,154 159 -2)),((155 159 0,153 160 0,154 159 2,155 159 0)),((155 159 0,154 159 2,157 157 1,155 159 0)),((157 157 1,154 159 2,156 157 4,157 157 1)),((157 157 1,156 157 4,158 155 3,157 157 1)),((158 155 3,156 157 4,157 154 6,158 155 3)),((158 155 3,157 154 6,159 152 4,158 155 3)),((159 152 4,157 154 6,157 151 7,159 152 4)),((157 154 6,155 153 8,157 151 7,157 154 6)),((157 151 7,155 153 8,155 150 9,157 151 7)),((155 150 9,155 50 9,157 49 7,155 150 9)),((157 151 7,155 150 9,157 49 7,157 151 7)),((155 50 9,155 47 8,157 49 7,155 50 9)),((150 47 10,150 45 9,152 46 9,150 47 10)),((150 47 10,148 46 9,150 45 9,150 47 10)),((157 49 7,155 47 8,157 46 6,157 49 7)),((155 47 8,154 44 7,157 46 6,155 47 8)),((155 47 8,152 46 9,154 44 7,155 47 8)),((152 46 9,151 43 7,154 44 7,152 46 9)),((152 46 9,150 45 9,151 43 7,152 46 9)),((143 133 7,143 49 7,145 50 9,143 133 7)),((143 133 7,143 133 7,145 50 9,143 133 7)),((145 138 9,144 136 8,145 50 9,145 138 9)),((144 136 8,143 133 7,145 50 9,144 136 8)),((145 50 9,143 49 7,145 47 8,145 50 9)),((145 47 8,143 49 7,143 46 6,145 47 8)),((148 46 9,145 47 8,146 44 7,148 46 9)),((145 47 8,143 46 6,146 44 7,145 47 8)),((150 45 9,148 46 9,149 43 7,150 45 9)),((148 46 9,146 44 7,149 43 7,148 46 9)),((141 50 5,143 49 7,141 130 5,141 50 5)),((141 130 5,143 49 7,143 133 7,141 130 5)),((140 50 3,141 50 5,140 127 3,140 50 3)),((141 128 4,141 50 5,141 130 5,141 128 4)),((140 127 3,141 50 5,141 128 4,140 127 3)),((57 43 1,55 41 0,57 43 -1,57 43 1)),((57 43 1,57 43 -1,140 126 -1,57 43 1)),((140 126 1,57 43 1,140 126 0,140 126 1)),((140 126 0,57 43 1,140 126 -1,140 126 0)),((140 50 0,140 50 3,140 126 0,140 50 0)),((140 126 1,140 50 3,140 127 3,140 126 1)),((140 126 0,140 50 3,140 126 1,140 126 0)),((140 50 0,140 126 0,140 50 -3,140 50 0)),((140 50 -3,140 126 0,140 126 -1,140 50 -3)),((140 50 -3,140 126 -1,140 127 -3,140 50 -3)),((140 50 -3,140 127 -3,141 50 -5,140 50 -3)),((141 50 -5,140 127 -3,141 128 -4,141 50 -5)),((141 50 -5,141 128 -4,141 130 -5,141 50 -5)),((141 50 -5,141 130 -5,143 49 -7,141 50 -5)),((143 49 -7,141 130 -5,143 133 -7,143 49 -7)),((143 49 -7,143 133 -7,145 50 -9,143 49 -7)),((145 50 -9,143 133 -7,143 133 -7,145 50 -9)),((145 50 -9,143 133 -7,144 136 -8,145 50 -9)),((144 136 -8,145 138 -9,145 50 -9,144 136 -8)),((145 47 -8,143 49 -7,145 50 -9,145 47 -8)),((150 45 -9,148 46 -9,150 47 -10,150 45 -9)),((152 46 -9,150 45 -9,150 47 -10,152 46 -9)),((143 46 -6,143 49 -7,145 47 -8,143 46 -6)),((146 44 -7,143 46 -6,145 47 -8,146 44 -7)),((146 44 -7,145 47 -8,148 46 -9,146 44 -7)),((149 43 -7,146 44 -7,148 46 -9,149 43 -7)),((149 43 -7,148 46 -9,150 45 -9,149 43 -7)),((157 46 -6,155 47 -8,157 49 -7,157 46 -6)),((157 49 -7,155 47 -8,155 50 -9,157 49 -7)),((154 44 -7,152 46 -9,155 47 -8,154 44 -7)),((157 46 -6,154 44 -7,155 47 -8,157 46 -6)),((155 50 -9,155 150 -9,157 49 -7,155 50 -9)),((157 49 -7,155 150 -9,157 151 -7,157 49 -7)),((155 150 -9,155 153 -8,157 151 -7,155 150 -9)),((151 43 -7,150 45 -9,152 46 -9,151 43 -7)),((154 44 -7,151 43 -7,152 46 -9,154 44 -7)),((157 151 -7,155 153 -8,157 154 -6,157 151 -7)),((157 151 -7,157 154 -6,159 152 -4,157 151 -7)),((159 152 -4,157 154 -6,158 155 -3,159 152 -4)),((157 154 -6,156 157 -4,158 155 -3,157 154 -6)),((158 155 -3,156 157 -4,157 157 -1,158 155 -3)),((156 157 -4,154 159 -2,157 157 -1,156 157 -4)),((157 157 -1,154 159 -2,155 159 0,157 157 -1)),((157 157 -1,155 159 0,157 157 1,157 157 -1)),((159 155 0,157 157 -1,157 157 1,159 155 0)),((159 155 0,157 157 1,158 155 3,159 155 0)),((159 155 0,158 155 3,160 153 2,159 155 0)),((160 153 2,158 155 3,159 152 4,160 153 2)),((160 153 2,159 152 4,160 150 3,160 153 2)),((159 152 4,159 150 5,160 150 3,159 152 4)),((159 152 4,157 151 7,159 150 5,159 152 4)),((157 151 7,157 49 7,159 50 5,157 151 7)),((159 150 5,157 151 7,159 50 5,159 150 5)),((159 50 5,157 49 7,159 48 4,159 50 5)),((157 49 7,157 46 6,159 48 4,157 49 7)),((150 45 9,149 43 7,151 43 7,150 45 9)),((159 48 4,157 46 6,158 45 3,159 48 4)),((157 46 6,156 43 4,158 45 3,157 46 6)),((157 46 6,154 44 7,156 43 4,157 46 6)),((154 44 7,153 42 5,156 43 4,154 44 7)),((154 44 7,151 43 7,153 42 5,154 44 7)),((151 43 7,149 43 7,150 41 5,151 43 7)),((151 43 7,150 41 5,153 42 5,151 43 7)),((141 50 5,141 48 4,143 49 7,141 50 5)),((143 49 7,141 48 4,143 46 6,143 49 7)),((143 46 6,141 48 4,142 45 3,143 46 6)),((146 44 7,143 46 6,144 43 4,146 44 7)),((143 46 6,142 45 3,144 43 4,143 46 6)),((149 43 7,146 44 7,147 42 5,149 43 7)),((146 44 7,144 43 4,147 42 5,146 44 7)),((149 43 7,147 42 5,150 41 5,149 43 7)),((141 50 5,140 50 3,141 48 4,141 50 5)),((140 50 3,140 50 0,140 47 2,140 50 3)),((141 48 4,140 50 3,140 47 2,141 48 4)),((140 47 2,140 50 0,140 47 -2,140 47 2)),((140 47 -2,140 50 0,140 50 -3,140 47 -2)),((141 48 -4,140 50 -3,141 50 -5,141 48 -4)),((140 47 -2,140 50 -3,141 48 -4,140 47 -2)),((143 49 -7,141 48 -4,141 50 -5,143 49 -7)),((143 46 -6,141 48 -4,143 49 -7,143 46 -6)),((151 43 -7,149 43 -7,150 45 -9,151 43 -7)),((142 45 -3,141 48 -4,143 46 -6,142 45 -3)),((144 43 -4,142 45 -3,143 46 -6,144 43 -4)),((144 43 -4,143 46 -6,146 44 -7,144 43 -4)),((147 42 -5,144 43 -4,146 44 -7,147 42 -5)),((147 42 -5,146 44 -7,149 43 -7,147 42 -5)),((150 41 -5,149 43 -7,151 43 -7,150 41 -5)),((150 41 -5,147 42 -5,149 43 -7,150 41 -5)),((158 45 -3,157 46 -6,159 48 -4,158 45 -3)),((159 48 -4,157 46 -6,157 49 -7,159 48 -4)),((156 43 -4,154 44 -7,157 46 -6,156 43 -4)),((158 45 -3,156 43 -4,157 46 -6,158 45 -3)),((159 48 -4,157 49 -7,159 50 -5,159 48 -4)),((159 50 -5,157 49 -7,157 151 -7,159 50 -5)),((159 150 -5,159 50 -5,157 151 -7,159 150 -5)),((153 42 -5,151 43 -7,154 44 -7,153 42 -5)),((156 43 -4,153 42 -5,154 44 -7,156 43 -4)),((159 150 -5,157 151 -7,159 152 -4,159 150 -5)),((153 42 -5,150 41 -5,151 43 -7,153 42 -5)),((160 150 -3,159 150 -5,159 152 -4,160 150 -3)),((160 150 -3,159 152 -4,160 153 -2,160 150 -3)),((159 152 -4,158 155 -3,160 153 -2,159 152 -4)),((160 153 -2,158 155 -3,159 155 0,160 153 -2)),((158 155 -3,157 157 -1,159 155 0,158 155 -3)),((160 153 -2,159 155 0,160 153 2,160 153 -2)),((160 150 0,160 153 -2,160 153 2,160 150 0)),((160 150 0,160 153 2,160 150 3,160 150 0)),((159 150 5,159 50 5,160 50 3,159 150 5)),((160 150 3,159 150 5,160 50 3,160 150 3)),((160 150 3,160 50 3,160 50 0,160 150 3)),((160 150 0,160 150 3,160 50 0,160 150 0)),((160 50 3,159 50 5,159 48 4,160 50 3)),((160 50 3,159 48 4,160 47 2,160 50 3)),((159 48 4,158 45 3,160 47 2,159 48 4)),((160 47 2,158 45 3,159 45 0,160 47 2)),((158 45 3,157 43 1,159 45 0,158 45 3)),((158 45 3,156 43 4,157 43 1,158 45 3)),((156 43 4,154 41 2,157 43 1,156 43 4)),((156 43 4,153 42 5,154 41 2,156 43 4)),((153 42 5,152 40 3,154 41 2,153 42 5)),((153 42 5,150 41 5,152 40 3,153 42 5)),((150 41 5,147 42 5,148 40 3,150 41 5)),((150 41 5,148 40 3,152 40 3,150 41 5)),((141 48 4,140 47 2,142 45 3,141 48 4)),((142 45 3,140 47 2,141 45 0,142 45 3)),((144 43 4,142 45 3,143 43 1,144 43 4)),((142 45 3,141 45 0,143 43 1,142 45 3)),((147 42 5,144 43 4,146 41 2,147 42 5)),((144 43 4,143 43 1,146 41 2,144 43 4)),((147 42 5,146 41 2,148 40 3,147 42 5)),((140 47 2,140 47 -2,141 45 0,140 47 2)),((141 45 0,140 47 -2,142 45 -3,141 45 0)),((142 45 -3,140 47 -2,141 48 -4,142 45 -3)),((143 43 -1,141 45 0,142 45 -3,143 43 -1)),((143 43 -1,142 45 -3,144 43 -4,143 43 -1)),((146 41 -2,143 43 -1,144 43 -4,146 41 -2)),((146 41 -2,144 43 -4,147 42 -5,146 41 -2)),((148 40 -3,146 41 -2,147 42 -5,148 40 -3)),((148 40 -3,147 42 -5,150 41 -5,148 40 -3)),((152 40 -3,150 41 -5,153 42 -5,152 40 -3)),((152 40 -3,148 40 -3,150 41 -5,152 40 -3)),((159 45 0,158 45 -3,160 47 -2,159 45 0)),((160 47 -2,158 45 -3,159 48 -4,160 47 -2)),((157 43 -1,156 43 -4,158 45 -3,157 43 -1)),((159 45 0,157 43 -1,158 45 -3,159 45 0)),((160 47 -2,159 48 -4,160 50 -3,160 47 -2)),((159 48 -4,159 50 -5,160 50 -3,159 48 -4)),((154 41 -2,153 42 -5,156 43 -4,154 41 -2)),((157 43 -1,154 41 -2,156 43 -4,157 43 -1)),((160 50 -3,159 50 -5,159 150 -5,160 50 -3)),((160 150 -3,160 50 -3,159 150 -5,160 150 -3)),((154 41 -2,152 40 -3,153 42 -5,154 41 -2)),((160 50 0,160 50 -3,160 150 -3,160 50 0)),((160 150 0,160 50 0,160 150 -3,160 150 0)),((160 150 -3,160 153 -2,160 150 0,160 150 -3)),((160 50 3,160 47 2,160 50 0,160 50 3)),((160 50 0,160 47 -2,160 50 -3,160 50 0)),((160 47 2,160 47 -2,160 50 0,160 47 2)),((160 47 2,159 45 0,160 47 -2,160 47 2)),((157 43 1,157 43 -1,159 45 0,157 43 1)),((157 43 1,155 41 0,157 43 -1,157 43 1)),((157 43 1,154 41 2,155 41 0,157 43 1)),((154 41 2,153 40 0,155 41 0,154 41 2)),((154 41 2,152 40 3,153 40 0,154 41 2)),((152 40 3,148 40 3,150 40 0,152 40 3)),((152 40 3,150 40 0,153 40 0,152 40 3)),((148 40 3,146 41 2,147 40 0,148 40 3)),((148 40 3,147 40 0,150 40 0,148 40 3)),((143 43 1,141 45 0,143 43 -1,143 43 1)),((143 43 1,143 43 -1,145 41 0,143 43 1)),((146 41 2,143 43 1,145 41 0,146 41 2)),((146 41 2,145 41 0,147 40 0,146 41 2)),((145 41 0,143 43 -1,146 41 -2,145 41 0)),((147 40 0,145 41 0,146 41 -2,147 40 0)),((147 40 0,146 41 -2,148 40 -3,147 40 0)),((150 40 0,148 40 -3,152 40 -3,150 40 0)),((150 40 0,147 40 0,148 40 -3,150 40 0)),((153 40 0,152 40 -3,154 41 -2,153 40 0)),((153 40 0,150 40 0,152 40 -3,153 40 0)),((155 41 0,154 41 -2,157 43 -1,155 41 0)),((155 41 0,153 40 0,154 41 -2,155 41 0)))
Figure
Geometry figure for visual-cg-3dbuffer-04

A square buffer around the same line using 32 segments.

Code
SELECT
  'LINESTRING(50 50,150 150,150 50)'::geometry AS input_geometry,
  CG_3DBuffer('LINESTRING(50 50,150 150,150 50)'::geometry, 10, 32, 2) AS buffer;
래스터 출력
LINESTRING(50 50,150 150,150 50) | POLYHEDRALSURFACE Z (((50 36 0,50 36 -2,140 126 -2,140 126 0,50 36 0)),((140 126 -2,50 36 -2,49 36 -4,141 128 -4,140 126 -2)),((141 128 -4,49 36 -4,49 37 -6,142 130 -6,141 128 -4)),((142 130 -6,49 37 -6,48 38 -7,143 133 -7,142 130 -6)),((143 133 -7,48 38 -7,47 39 -8,144 137 -8,143 133 -7)),((144 137 -8,47 39 -8,46 40 -9,146 141 -9,144 137 -8)),((146 141 -9,46 40 -9,44 42 -10,148 145 -10,146 141 -9)),((148 145 -10,44 42 -10,43 43 -10,150 150 -10,148 145 -10)),((150 150 -10,43 43 -10,42 44 -10,152 155 -10,150 150 -10)),((152 155 -10,42 44 -10,40 46 -9,154 159 -9,152 155 -10)),((154 159 -9,40 46 -9,39 47 -8,156 163 -8,154 159 -9)),((156 163 -8,39 47 -8,38 48 -7,157 167 -7,156 163 -8)),((157 167 -7,38 48 -7,37 49 -6,158 170 -6,157 167 -7)),((158 170 -6,37 49 -6,36 49 -4,159 172 -4,158 170 -6)),((159 172 -4,36 49 -4,36 50 -2,160 174 -2,159 172 -4)),((160 174 -2,36 50 -2,36 50 -1e-15,160 174 -1e-15,160 174 -2)),((160 174 -1e-15,36 50 -1e-15,36 50 2,160 174 2,160 174 -1e-15)),((160 174 2,36 50 2,36 49 4,159 172 4,160 174 2)),((159 172 4,36 49 4,37 49 6,158 170 6,159 172 4)),((158 170 6,37 49 6,38 48 7,157 167 7,158 170 6)),((157 167 7,38 48 7,39 47 8,156 163 8,157 167 7)),((156 163 8,39 47 8,40 46 9,154 159 9,156 163 8)),((154 159 9,40 46 9,42 44 10,152 155 10,154 159 9)),((152 155 10,42 44 10,43 43 10,150 150 10,152 155 10)),((150 150 10,43 43 10,44 42 10,148 145 10,150 150 10)),((148 145 10,44 42 10,46 40 9,146 141 9,148 145 10)),((146 141 9,46 40 9,47 39 8,144 137 8,146 141 9)),((144 137 8,47 39 8,48 38 7,143 133 7,144 137 8)),((143 133 7,48 38 7,49 37 6,142 130 6,143 133 7)),((142 130 6,49 37 6,49 36 4,141 128 4,142 130 6)),((141 128 4,49 36 4,50 36 2,140 126 2,141 128 4)),((50 36 0,140 126 0,140 126 2,50 36 2,50 36 0)),((140 126 0,140 126 -2,140 40 -2,140 40 0,140 126 0)),((140 40 -2,140 126 -2,141 128 -4,141 40 -4,140 40 -2)),((141 40 -4,141 128 -4,142 130 -6,142 40 -6,141 40 -4)),((142 40 -6,142 130 -6,143 133 -7,143 40 -7,142 40 -6)),((143 40 -7,143 133 -7,144 137 -8,144 40 -8,143 40 -7)),((144 40 -8,144 137 -8,146 141 -9,146 40 -9,144 40 -8)),((146 40 -9,146 141 -9,148 145 -10,148 40 -10,146 40 -9)),((148 40 -10,148 145 -10,150 150 -10,150 40 -10,148 40 -10)),((150 40 -10,150 150 -10,152 155 -10,152 40 -10,150 40 -10)),((152 40 -10,152 155 -10,154 159 -9,154 40 -9,152 40 -10)),((154 40 -9,154 159 -9,156 163 -8,156 40 -8,154 40 -9)),((156 40 -8,156 163 -8,157 167 -7,157 40 -7,156 40 -8)),((157 40 -7,157 167 -7,158 170 -6,158 40 -6,157 40 -7)),((158 40 -6,158 170 -6,159 172 -4,159 40 -4,158 40 -6)),((159 40 -4,159 172 -4,160 174 -2,160 40 -2,159 40 -4)),((160 40 -2,160 174 -2,160 174 -1e-15,160 40 -1e-15,160 40 -2)),((160 40 -1e-15,160 174 -1e-15,160 174 2,160 40 2,160 40 -1e-15)),((160 40 2,160 174 2,159 172 4,159 40 4,160 40 2)),((159 40 4,159 172 4,158 170 6,158 40 6,159 40 4)),((158 40 6,158 170 6,157 167 7,157 40 7,158 40 6)),((157 40 7,157 167 7,156 163 8,156 40 8,157 40 7)),((156 40 8,156 163 8,154 159 9,154 40 9,156 40 8)),((154 40 9,154 159 9,152 155 10,152 40 10,154 40 9)),((152 40 10,152 155 10,150 150 10,150 40 10,152 40 10)),((150 40 10,150 150 10,148 145 10,148 40 10,150 40 10)),((148 40 10,148 145 10,146 141 9,146 40 9,148 40 10)),((146 40 9,146 141 9,144 137 8,144 40 8,146 40 9)),((144 40 8,144 137 8,143 133 7,143 40 7,144 40 8)),((143 40 7,143 133 7,142 130 6,142 40 6,143 40 7)),((142 40 6,142 130 6,141 128 4,141 40 4,142 40 6)),((141 40 4,141 128 4,140 126 2,140 40 2,141 40 4)),((140 126 0,140 40 0,140 40 2,140 126 2,140 126 0)),((50 36 -2,50 36 0,50 36 2,49 36 4,49 37 6,48 38 7,47 39 8,46 40 9,44 42 10,43 43 10,42 44 10,40 46 9,39 47 8,38 48 7,37 49 6,36 49 4,36 50 2,36 50 -1e-15,36 50 -2,36 49 -4,37 49 -6,38 48 -7,39 47 -8,40 46 -9,42 44 -10,43 43 -10,44 42 -10,46 40 -9,47 39 -8,48 38 -7,49 37 -6,49 36 -4,50 36 -2)),((140 40 0,140 40 -2,141 40 -4,142 40 -6,143 40 -7,144 40 -8,146 40 -9,148 40 -10,150 40 -10,152 40 -10,154 40 -9,156 40 -8,157 40 -7,158 40 -6,159 40 -4,160 40 -2,160 40 -1e-15,160 40 2,159 40 4,158 40 6,157 40 7,156 40 8,154 40 9,152 40 10,150 40 10,148 40 10,146 40 9,144 40 8,143 40 7,142 40 6,141 40 4,140 40 2,140 40 0)))
Figure
Geometry figure for visual-cg-3dbuffer-05

제목

CG_Rotate — Rotates a geometry by a given angle around the origin (0,0).

요약

geometry CG_Rotate(geometry geom, float8 angle);

설명

Rotates the input geometry geom by angle radians around the origin point (0,0). The rotation is performed in 2D space; Z coordinates are not modified. Positive angles rotate the geometry counter-clockwise.

Availability: 3.6.0 - requires SFCGAL >= 2.0.0

This method needs SFCGAL backend.

예시

Code
SELECT CG_Rotate('LINESTRING(1 0,0 1)', pi()/2);
래스터 출력
LINESTRING(6.123233995736766e-17 1,-1 6.123233995736766e-17)
Figure
Geometry figure for visual-cg-rotate-01

제목

CG_2DRotate — Rotates a geometry by a given angle around a specified point in 2D.

요약

geometry CG_2DRotate(geometry geom, float8 angle, float8 cx, float8 cy);

설명

Rotates the input geometry geom by angle radians around the point (cx, cy). The rotation is performed in 2D space; Z coordinates are dropped. Positive angles rotate the geometry counter-clockwise.

Availability: 3.6.0 - requires SFCGAL >= 2.0.0

This method needs SFCGAL backend.

예시

Code
SELECT CG_2DRotate('POINT(1 0)', pi()/2, 1, 1);
래스터 출력
POINT(2 1)
Figure
Geometry figure for visual-cg-2drotate-01

제목

CG_3DRotate — Rotates a geometry in 3D space around an axis vector.

요약

geometry CG_3DRotate(geometry geom, float8 angle, float8 ax, float8 ay, float8 az);

설명

Rotates the input geometry geom by angle radians around an axis defined by the vector (ax, ay, az) passing through the origin (0,0,0).

Availability: 3.6.0 - requires SFCGAL >= 2.0.0

This method needs SFCGAL backend.

This function supports 3d and will not drop the z-index.

예시

Code
SELECT CG_3DRotate('POINT(1 0 0)', pi()/2, 0, 0, 1);
래스터 출력
POINT Z (6.123233995736766e-17 1 0)
Figure
Geometry figure for visual-cg-3drotate-01

제목

CG_RotateX — Rotates a geometry around the X-axis by a given angle.

요약

geometry CG_RotateX(geometry geom, float8 angle);

설명

Rotates the input geometry geom by angle radians around the X-axis.

Availability: 3.6.0 - requires SFCGAL >= 2.0.0

This method needs SFCGAL backend.

This function supports 3d and will not drop the z-index.

예시

Code
SELECT CG_RotateX('POINT(0 1 0)', pi()/2);
래스터 출력
POINT Z (0 6.123233995736766e-17 1)
Figure
Geometry figure for visual-cg-rotatex-01

제목

CG_RotateY — Rotates a geometry around the Y-axis by a given angle.

요약

geometry CG_RotateY(geometry geom, float8 angle);

설명

Rotates the input geometry geom by angle radians around the Y-axis passing.

Availability: 3.6.0 - requires SFCGAL >= 2.0.0

This method needs SFCGAL backend.

This function supports 3d and will not drop the z-index.

예시

Code
SELECT CG_RotateY('POINT(1 0 0)', pi()/2);
래스터 출력
POINT Z (6.123233995736766e-17 0 -1)
Figure
Geometry figure for visual-cg-rotatey-01

제목

CG_RotateZ — Rotates a geometry around the Z-axis by a given angle.

요약

geometry CG_RotateZ(geometry geom, float8 angle);

설명

Rotates the input geometry geom by angle radians around the Z-axis.

Availability: 3.6.0 - requires SFCGAL >= 2.0.0

This method needs SFCGAL backend.

This function supports 3d and will not drop the z-index.

예시

Code
SELECT CG_RotateZ('POINT(1 0 0)', pi()/2);
래스터 출력
POINT Z (6.123233995736766e-17 1 0)
Figure
Geometry figure for visual-cg-rotatez-01

제목

CG_Scale — Scales a geometry uniformly in all dimensions by a given factor.

요약

geometry CG_Scale(geometry geom, float8 factor);

설명

Scales the input geometry geom by a uniform scale factor in all dimensions (X, Y, and Z). The scaling is performed relative to the origin point (0,0,0).

Availability: 3.6.0 - requires SFCGAL >= 2.0.0

This method needs SFCGAL backend.

예시

Code
SELECT CG_Scale('LINESTRING(1 1,2 2)', 2);
래스터 출력
LINESTRING(2 2,4 4)
Figure
Geometry figure for visual-cg-scale-01

제목

CG_3DScale — Scales a geometry by separate factors along X, Y, and Z axes.

요약

geometry CG_3DScale(geometry geom, float8 factorX, float8 factorY, float8 factorZ);

설명

Scales the input geometry geom by different factors along the X, Y, and Z axes. The scaling is performed relative to the origin point (0,0,0).

Availability: 3.6.0 - requires SFCGAL >= 2.0.0

This method needs SFCGAL backend.

This function supports 3d and will not drop the z-index.

예시

Code
SELECT CG_3DScale('POINT(1 1 1)', 2, 3, 4);
래스터 출력
POINT Z (2 3 4)
Figure
Geometry figure for visual-cg-3dscale-01

제목

CG_3DScaleAroundCenter — Scales a geometry in 3D space around a specified center point.

요약

geometry CG_3DScaleAroundCenter(geometry geom, float8 factorX, float8 factorY, float8 factorZ, float8 centerX, float8 centerY, float8 centerZ);

설명

Scales the input geometry geom by different factors along the X, Y, and Z axes, relative to a specified center point (centerX, centerY, centerZ).

Availability: 3.6.0 - requires SFCGAL >= 2.0.0

This method needs SFCGAL backend.

This function supports 3d and will not drop the z-index.

예시

Code
SELECT CG_3DScaleAroundCenter('POINT(2 2 2)', 0.5, 0.5, 0.5, 1, 1, 1);
래스터 출력
POINT Z (1.5 1.5 1.5)
Figure
Geometry figure for visual-cg-3dscalearoundcenter-01

제목

CG_Translate — Translates (moves) a geometry by given offsets in 2D space.

요약

geometry CG_Translate(geometry geom, float8 deltaX, float8 deltaY);

설명

Translates the input geometry geom by adding deltaX to the X coordinates and deltaY to the Y coordinates. Z coordinates are dropped.

Availability: 3.6.0 - requires SFCGAL >= 2.0.0

This method needs SFCGAL backend.

예시

Code
SELECT CG_Translate('LINESTRING(1 1,2 2)', 1, -1);
래스터 출력
LINESTRING(2 0,3 1)
Figure
Geometry figure for visual-cg-translate-01

제목

CG_3DTranslate — Translates (moves) a geometry by given offsets in 3D space.

요약

geometry CG_3DTranslate(geometry geom, float8 deltaX, float8 deltaY, float8 deltaZ);

설명

Translates the input geometry geom by adding deltaX to the X coordinates, deltaY to the Y coordinates, and deltaZ to the Z coordinates.

Availability: 3.6.0 - requires SFCGAL >= 2.0.0

This method needs SFCGAL backend.

This function supports 3d and will not drop the z-index.

예시

Code
SELECT CG_3DTranslate('POINT(1 1 1)', 1, -1, 2);
래스터 출력
POINT Z (2 0 3)
Figure
Geometry figure for visual-cg-3dtranslate-01

제목

CG_Simplify — Reduces the complexity of a geometry while preserving essential features and Z/M values.

요약

geometry CG_Simplify(geometry geom, double precision threshold, boolean preserveTopology = false);

설명

Simplifies a geometry using SFCGAL's simplification algorithm, which reduces the number of points or vertices while preserving the essential features of the geometry. This function preserves Z and M values during simplification.

The algorithm is based on constrained triangulation and uses the CGAL Polyline Simplification 2 library with additional handling to preserve Z and M coordinates. When topology is preserved and geometries intersect, Z and M values are interpolated at intersection points.

This function works well with 3D terrain-like geometries (2.5D) but is not designed for vertical surfaces like walls.

Availability: 3.6.0 - requires SFCGAL >= 2.1.0

This method needs SFCGAL backend.

This function supports 3d and will not drop the z-index.

This function supports M coordinates.

Parameters

geom

Input geometry

threshold

Maximum distance threshold (in geometry unit) for simplification. The higher this value, the more simplified the resulting geometry will be.

preserveTopology

If set to true, the function ensures that the topology of the geometry is preserved. When geometries intersect in this mode, Z and M values at intersection points are interpolated. The default value is false.

Return Value

Returns a simplified geometry with preserved Z and M values.

예시

This example simplifies a polygon with a threshold of 0.5.

Code
SELECT CG_Simplify(
    'POLYGON((0 0,0 1,0.1 1,0.2 1,0.3 1,0.4 1,0.5 1,1 1,1 0,0 0))',
    0.5
  );
래스터 출력
POLYGON((0 0,0 1,1 1,1 0,0 0))
Figure
Geometry figure for visual-cg-simplify-01

Preserving topology can keep additional support points in a mixed ZM collection.

Code
SELECT CG_Simplify(
    'GEOMETRYCOLLECTION ZM(
      LINESTRING ZM(-1 -1 3 4,0 0 10 100,1 1 20 200,0 2 15 150,0 5 30 300,2 19 25 250,-4 20 15 150),
      POLYGON ZM((0 0 10 100,1 1 20 200,0 2 15 150,0 5 30 300,2 19 25 250,-4 20 15 150,0 0 10 100))
    )',
    2,
    false
  );
래스터 출력
GEOMETRYCOLLECTION ZM (LINESTRING ZM (-1 -1 3 4,2 19 25 250,-4 20 15 150),POLYGON ZM ((0 0 10 100,2 19 25 250,-4 20 15 150,0 0 10 100)))
Figure
Geometry figure for visual-cg-simplify-02

The topology-preserving variant keeps the shared anchor point at the collection intersection.

Code
SELECT CG_Simplify(
    'GEOMETRYCOLLECTION ZM(
      LINESTRING ZM(-1 -1 3 4,0 0 10 100,1 1 20 200,0 2 15 150,0 5 30 300,2 19 25 250,-4 20 15 150),
      POLYGON ZM((0 0 10 100,1 1 20 200,0 2 15 150,0 5 30 300,2 19 25 250,-4 20 15 150,0 0 10 100))
    )',
    2,
    true
  );
래스터 출력
GEOMETRYCOLLECTION ZM (LINESTRING ZM (-1 -1 3 4,0 0 10 100,2 19 25 250,-4 20 15 150),POLYGON ZM ((0 0 10 100,2 19 25 250,-4 20 15 150,0 0 10 100)))
Figure
Geometry figure for visual-cg-simplify-03

Compare simplification with and without topology preservation, using a threshold of 50.

Code
WITH data AS (
  SELECT ST_GeomFromText('GEOMETRYCOLLECTION(
    POLYGON((88.46 158.85,90.77 171.54,147.31 173.85,146.15 145,173.85 119.62,146.15 103.46,112.69 118.46,91.92 93.08,65.38 101.15,34.23 121.92,41.15 142.69,49.23 143.85,88.46 158.85)),
    POLYGON((112.69 118.46,146.15 103.46,190 60.77,185.38 43.46,126.54 26.15,83.85 28.46,67.69 64.23,43.46 58.46,10 83.85,34.23 121.92,65.38 101.15,91.92 93.08,112.69 118.46)))
  ') AS geom
)
SELECT geom AS input_geometry,
       CG_Simplify(geom, 50, true) AS topology_preserved,
       CG_Simplify(geom, 50, false) AS topology_not_preserved
FROM data;
래스터 출력
GEOMETRYCOLLECTION(POLYGON((88.46 158.85,90.77 171.54,147.31 173.85,146.15 145,173.85 119.62,146.15 103.46,112.69 118.46,91.92 93.08,65.38 101.15,34.23 121.92,41.15 142.69,49.23 143.85,88.46 158.85)), POLYGON((112.69 118.46,146.15 103.46,190 60.77,185.38 43.46,126.54 26.15,83.85 28.46,67.69 64.23,43.46 58.46,10 83.85,34.23 121.92,65.38 101.15,91.92 93.08,112.69 118.46))) | GEOMETRYCOLLECTION(POLYGON((88.46 158.85,147.31 173.85,146.15 103.46,112.69 118.46,34.23 121.92,88.46 158.85)), POLYGON((112.69 118.46,146.15 103.46,185.38 43.46,10 83.85,34.23 121.92,112.69 118.46))) | GEOMETRYCOLLECTION(POLYGON((88.46 158.85,173.85 119.62,34.23 121.92,88.46 158.85)), POLYGON((112.69 118.46,190 60.77,10 83.85,112.69 118.46)))
Figure
Geometry figure for visual-cg-simplify-04

제목

CG_3DAlphaWrapping — Computes a 3D Alpha-wrapping strictly enclosing a geometry.

요약

geometry CG_3DAlphaWrapping(geometry geom, integer relative_alpha, integer relative_offset);

설명

Computes the 3D Alpha Wrapping of the points in a geometry. An alpha wrapping is a watertight and orientable surface mesh that strictly encloses the input. It can be seen as an extension or refinement of an alpha-shape.

The relative_alpha parameter controls which features will appear in the output. It can have values from 0 to infinity. Higher relative_alpha values produce coarser wraps; lower values retain more detail.

The relative_offset parameter controls the tightness of the result. It can have values from 0 to infinity. If this parameter is set to 0, its value is automatically determined based on the relative_alpha parameter.

Availability: 3.6.0 - requires SFCGAL >= 2.1.0

This method needs SFCGAL backend.

This function supports 3d and will not drop the z-index.

예시

Wrap a tetrahedral surface and show the native 3D input beside the actual enclosing mesh.

Code
WITH data AS (
  SELECT 'POLYHEDRALSURFACE Z (
    ((0 0 0,4 0 0,0 4 0,0 0 0)),
    ((0 0 0,0 0 4,4 0 0,0 0 0)),
    ((0 0 0,0 4 0,0 0 4,0 0 0)),
    ((4 0 0,0 0 4,0 4 0,4 0 0))
  )'::geometry AS input_geometry
)
SELECT input_geometry AS input_geometry,
       CG_3DAlphaWrapping(input_geometry, 1)
         AS wrapped_geometry
FROM data;
래스터 출력
POLYHEDRALSURFACE Z (((0 0 0,4 0 0,0 4 0,0 0 0)),((0 0 0,0 0 4,4 0 0,0 0 0)),((0 0 0,0 4 0,0 0 4,0 0 0)),((4 0 0,0 0 4,0 4 0,4 0 0))) | POLYHEDRALSURFACE Z (((-0.193 0.127 4,-0.035 -0.228 4.004,0.087 0.087 4.195,-0.193 0.127 4)),((0.083 0.082 3.801,0.087 0.087 4.195,-0.035 -0.228 4.004,0.083 0.082 3.801)),((0.087 0.087 4.195,0.083 0.082 3.801,-0.193 0.127 4,0.087 0.087 4.195)),((0.048 3.84 0.16,3.867 0.133 0.133,0.091 3.926 -0.199,0.048 3.84 0.16)),((3.92 0.08 -0.201,0.037 -0.007 -0.228,0.091 3.926 -0.199,3.92 0.08 -0.201)),((3.867 0.133 0.133,3.92 0.08 -0.201,0.091 3.926 -0.199,3.867 0.133 0.133)),((3.867 0.133 0.133,3.877 -0.195 0.012,4.228 -0.006 0.037,3.867 0.133 0.133)),((3.867 0.133 0.133,4.228 -0.006 0.037,3.92 0.08 -0.201,3.867 0.133 0.133)),((3.877 -0.195 0.012,3.92 0.08 -0.201,4.228 -0.006 0.037,3.877 -0.195 0.012)),((0.012 -0.196 0.121,-0.035 -0.228 4.004,-0.202 0.079 0.078,0.012 -0.196 0.121)),((-0.202 0.079 0.078,0.037 -0.007 -0.228,0.012 -0.196 0.121,-0.202 0.079 0.078)),((3.867 0.133 0.133,0.083 0.082 3.801,3.877 -0.195 0.012,3.867 0.133 0.133)),((0.091 3.926 -0.199,0.101 4.199 0.06,0.048 3.84 0.16,0.091 3.926 -0.199)),((0.101 4.199 0.06,-0.228 4.028 -0.021,0.048 3.84 0.16,0.101 4.199 0.06)),((0.091 3.926 -0.199,-0.228 4.028 -0.021,0.101 4.199 0.06,0.091 3.926 -0.199)),((3.867 0.133 0.133,0.048 3.84 0.16,0.083 0.082 3.801,3.867 0.133 0.133)),((3.877 -0.195 0.012,0.037 -0.007 -0.228,3.92 0.08 -0.201,3.877 -0.195 0.012)),((0.012 -0.196 0.121,0.037 -0.007 -0.228,3.877 -0.195 0.012,0.012 -0.196 0.121)),((0.083 0.082 3.801,0.048 3.84 0.16,-0.193 0.127 4,0.083 0.082 3.801)),((-0.228 4.028 -0.021,-0.193 0.127 4,0.048 3.84 0.16,-0.228 4.028 -0.021)),((-0.228 4.028 -0.021,-0.202 0.079 0.078,-0.193 0.127 4,-0.228 4.028 -0.021)),((-0.202 0.079 0.078,-0.035 -0.228 4.004,-0.193 0.127 4,-0.202 0.079 0.078)),((3.877 -0.195 0.012,0.083 0.082 3.801,-0.035 -0.228 4.004,3.877 -0.195 0.012)),((0.012 -0.196 0.121,3.877 -0.195 0.012,-0.035 -0.228 4.004,0.012 -0.196 0.121)),((0.091 3.926 -0.199,0.037 -0.007 -0.228,-0.228 4.028 -0.021,0.091 3.926 -0.199)),((-0.228 4.028 -0.021,0.037 -0.007 -0.228,-0.202 0.079 0.078,-0.228 4.028 -0.021)))
Figure
Geometry figure for visual-cg-3dalphawrapping-01

제목

CG_NurbsCurveInterpolate — Creates an interpolating NURBS curve passing through all given data points

요약

geometry CG_NurbsCurveInterpolate(geometry data_points, integer degree);

설명

Creates a NURBS curve that interpolates through all provided data points. The resulting curve passes exactly through each point in the input geometry.

Parameters:

  • data_points - A LINESTRING geometry containing the points to interpolate through.

  • degree - Polynomial degree of the NURBS curve (typically 2 or 3).

Availability: 3.7.0 - requires SFCGAL >= 2.3.0.

This method needs SFCGAL backend.

This function supports 3d and will not drop the z-index.

예시

Interpolate a degree-3 NURBS curve through four 2D points.

Code
WITH data AS (
  SELECT 'LINESTRING(0 0,2 5,5 3,8 1)'::geometry AS input_points
)
SELECT input_points AS input_points,
       CG_NurbsCurveInterpolate(input_points, 3) AS interpolated_curve
FROM data;
래스터 출력
LINESTRING(0 0,2 5,5 3,8 1) | NURBSCURVE(DEGREE 3, CONTROLPOINTS(NURBSPOINT(WEIGHTEDPOINT(0 0),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT(-0.43 10.29),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT(4.95 1.9),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT(8 1),WEIGHT 1)),KNOTS (KNOT(0,4), KNOT(1,4)))
Figure
Geometry figure for visual-cg-nurbscurveinterpolate-01

Interpolate a 3D degree-3 NURBS curve through the documented control points.

Code
WITH data AS (
  SELECT 'LINESTRING Z (0 0 0,2 5 2,5 3 1,8 1 0)'::geometry AS input_points
)
SELECT input_points AS input_points,
       CG_NurbsCurveInterpolate(input_points, 3) AS interpolated_curve
FROM data;
래스터 출력
LINESTRING Z (0 0 0,2 5 2,5 3 1,8 1 0) | NURBSCURVE Z (DEGREE 3,CONTROLPOINTS Z (NURBSPOINT(WEIGHTEDPOINT Z (0 0 0),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT Z (-0.43 10.29 4.36),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT Z (4.95 1.9 0.54),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT Z (8 1 0),WEIGHT 1)),KNOTS (KNOT(0,4), KNOT(1,4)))
Figure
Geometry figure for visual-cg-nurbscurveinterpolate-02

제목

CG_NurbsCurveApproximate — Creates an approximating NURBS curve fitting data points within a tolerance

요약

geometry CG_NurbsCurveApproximate(geometry data_points, integer degree, float8 tolerance, integer max_control_points=100);

설명

Creates a NURBS curve that approximates the given data points within the specified tolerance. Unlike interpolation, the curve does not necessarily pass through all points but provides a smooth fit with fewer control points.

Parameters:

  • data_points - A LINESTRING geometry containing the points to approximate.

  • degree - Polynomial degree of the NURBS curve.

  • tolerance - Maximum allowed distance between the curve and data points.

  • max_control_points - Optional maximum number of control points (default: 100). Limits curve complexity.

Availability: 3.7.0 - requires SFCGAL >= 2.3.0.

This method needs SFCGAL backend.

This function supports 3d and will not drop the z-index.

예시

Approximate noisy 2D data with a degree-2 curve and a tolerance of 0.5.

Code
WITH data AS (
  SELECT 'LINESTRING(0 0,1 2.1,2 1.9,3 3.2,4 2.8,5 1)'::geometry AS input_points
)
SELECT input_points AS input_points,
       CG_NurbsCurveApproximate(input_points, 2, 0.5) AS approximated_curve
FROM data;
래스터 출력
LINESTRING(0 0,1 2.1,2 1.9,3 3.2,4 2.8,5 1) | NURBSCURVE(DEGREE 2, CONTROLPOINTS(NURBSPOINT(WEIGHTEDPOINT(0 0),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT(-0.05 2.64),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT(2.24 1.65),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT(2.79 3.48),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT(4.84 2.43),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT(5 1),WEIGHT 1)),KNOTS (KNOT(0,3), KNOT(0.35,1), KNOT(0.51,1), KNOT(0.68,1), KNOT(1,3)))
Figure
Geometry figure for visual-cg-nurbscurveapproximate-01

Approximate a 3D point set while preserving the Z dimension in the fitted curve.

Code
WITH data AS (
  SELECT 'LINESTRING Z (0 0 0,1 2 1,2 3 2,3 2 1,4 1 0,5 0 0)'::geometry AS input_points
)
SELECT input_points AS input_points,
       CG_NurbsCurveApproximate(input_points, 3, 0.1) AS approximated_curve
FROM data;
래스터 출력
LINESTRING Z (0 0 0,1 2 1,2 3 2,3 2 1,4 1 0,5 0 0) | NURBSCURVE Z (DEGREE 3,CONTROLPOINTS Z (NURBSPOINT(WEIGHTEDPOINT Z (0 0 0),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT Z (0.18 -0.15 -1.29),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT Z (1.49 4.36 3.35),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT Z (3.33 1.33 0.38),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT Z (4.34 0.83 -0.44),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT Z (5 0 0),WEIGHT 1)),KNOTS (KNOT(0,4), KNOT(0.46,1), KNOT(0.64,1), KNOT(1,4)))
Figure
Geometry figure for visual-cg-nurbscurveapproximate-02

제목

CG_NurbsCurveDerivative — Computes the derivative (tangent, curvature) of a NURBS curve at a given parameter

요약

geometry CG_NurbsCurveDerivative(geometry nurbscurve, float8 parameter, integer derivative_order);

설명

Computes the derivative of a NURBS curve at a specific parameter value. The derivative represents the rate of change at that point:

  • Order 1: Tangent vector (direction and speed)

  • Order 2: Curvature vector (how the tangent changes)

  • Order 3: Third-order derivative (supported maximum)

Parameters:

  • nurbscurve - A NURBS curve geometry.

  • parameter - Parameter value for evaluation (typically 0.0 to 1.0).

  • derivative_order - Order of derivative to compute (1, 2, or 3).

Returns a POINT geometry representing the derivative vector at the specified parameter.

Availability: 3.7.0 - requires SFCGAL >= 2.3.0.

This method needs SFCGAL backend.

This function supports 3d and will not drop the z-index.

예시

The first derivative gives the tangent vector at the evaluation parameter.

Code
WITH data AS (
  SELECT 'NURBSCURVE (2, (0.00 0.00, 5.00 10.00, 10.00 0.00))'::geometry AS input_curve
)
SELECT input_curve AS input_curve,
       CG_NurbsCurveDerivative(input_curve, 0.5, 1) AS tangent
FROM data;
래스터 출력
NURBSCURVE(DEGREE 2, CONTROLPOINTS(NURBSPOINT(WEIGHTEDPOINT(0 0),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT(5 10),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT(10 0),WEIGHT 1)),KNOTS (KNOT(0,3), KNOT(1,3))) | POINT Z (10 0 0)
Figure
Geometry figure for visual-cg-nurbscurvederivative-01

The second derivative exposes curvature change for a higher-degree curve.

Code
WITH data AS (
  SELECT 'NURBSCURVE (3, (0.00 0.00, 2.00 8.00, 5.00 5.00, 8.00 2.00, 10.00 0.00))'::geometry AS input_curve
)
SELECT input_curve AS input_curve,
       CG_NurbsCurveDerivative(input_curve, 0.5, 2) AS curvature
FROM data;
래스터 출력
NURBSCURVE(DEGREE 3, CONTROLPOINTS(NURBSPOINT(WEIGHTEDPOINT(0 0),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT(2 8),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT(5 5),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT(8 2),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT(10 0),WEIGHT 1)),KNOTS (KNOT(0,4), KNOT(0.5,1), KNOT(1,4))) | POINT Z (9 -9 0)
Figure
Geometry figure for visual-cg-nurbscurvederivative-02

The same derivative call also works for 3D NURBS curves.

Code
WITH data AS (
  SELECT 'NURBSCURVE Z (2, (0.00 0.00 0.00, 5.00 10.00 5.00, 10.00 0.00 0.00))'::geometry AS input_curve
)
SELECT input_curve AS input_curve,
       CG_NurbsCurveDerivative(input_curve, 0.5, 1) AS tangent
FROM data;
래스터 출력
NURBSCURVE Z (DEGREE 2,CONTROLPOINTS Z (NURBSPOINT(WEIGHTEDPOINT Z (0 0 0),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT Z (5 10 5),WEIGHT 1), NURBSPOINT(WEIGHTEDPOINT Z (10 0 0),WEIGHT 1)),KNOTS (KNOT(0,3), KNOT(1,3))) | POINT Z (10 0 0)
Figure
Geometry figure for visual-cg-nurbscurvederivative-03

8.4. Deprecated SFCGAL Function Aliases

These ST_ names remain available for compatibility and emit deprecation notices. Their entries contain only the legacy signature and migration link. Use the corresponding CG_ pages for behavior, examples, and geometry support details.

제목

ST_3DIntersection — Deprecated alias for CG_3DIntersection.

요약

geometry ST_3DIntersection(geometry geom1, geometry geom2);

Description

[주의]

ST_3DIntersection is deprecated as of 3.5.0. Use CG_3DIntersection instead.

Availability: 2.1.0

This method needs SFCGAL backend.


제목

ST_3DDifference — Deprecated alias for CG_3DDifference.

요약

geometry ST_3DDifference(geometry geom1, geometry geom2);

Description

[주의]

ST_3DDifference is deprecated as of 3.5.0. Use CG_3DDifference instead.

Availability: 2.2.0

This method needs SFCGAL backend.


제목

ST_3DUnion — Deprecated alias for CG_3DUnion.

요약

geometry ST_3DUnion(geometry geom1, geometry geom2);

geometry ST_3DUnion(geometry set g1field);

Description

[주의]

ST_3DUnion is deprecated as of 3.5.0. Use CG_3DUnion instead.

Availability: 2.2.0

This method needs SFCGAL backend.


제목

ST_Tesselate — Deprecated alias for CG_Tesselate.

요약

geometry ST_Tesselate(geometry geom);

Description

[주의]

ST_Tesselate is deprecated as of 3.5.0. Use CG_Tesselate instead.

Availability: 2.1.0

This method needs SFCGAL backend.


제목

ST_3DArea — Deprecated alias for CG_3DArea.

요약

floatST_3DArea(geometry geom1);

Description

[주의]

ST_3DArea is deprecated as of 3.5.0. Use CG_3DArea instead.

Availability: 2.1.0

This method needs SFCGAL backend.


제목

ST_Extrude — Deprecated alias for CG_Extrude.

요약

geometry ST_Extrude(geometry geom, float x, float y, float z);

Description

[주의]

ST_Extrude is deprecated as of 3.5.0. Use CG_Extrude instead.

Availability: 2.1.0

This method needs SFCGAL backend.


제목

ST_ForceLHR — Deprecated alias for CG_ForceLHR.

요약

geometry ST_ForceLHR(geometry geom);

Description

[주의]

ST_ForceLHR is deprecated as of 3.5.0. Use CG_ForceLHR instead.

Availability: 2.1.0

This method needs SFCGAL backend.


제목

ST_Orientation — Deprecated alias for CG_Orientation.

요약

integer ST_Orientation(geometry geom);

Description

[주의]

ST_Orientation is deprecated as of 3.5.0. Use CG_Orientation instead.

Availability: 2.1.0

This method needs SFCGAL backend.


제목

ST_MinkowskiSum — Deprecated alias for CG_MinkowskiSum.

요약

geometry ST_MinkowskiSum(geometry geom1, geometry geom2);

Description

[주의]

ST_MinkowskiSum is deprecated as of 3.5.0. Use CG_MinkowskiSum instead.

Availability: 2.1.0

This method needs SFCGAL backend.


제목

ST_StraightSkeleton — Deprecated alias for CG_StraightSkeleton.

요약

geometry ST_StraightSkeleton(geometry geom);

Description

[주의]

ST_StraightSkeleton is deprecated as of 3.1.0. Use CG_StraightSkeleton instead.

Availability: 2.1.0

This method needs SFCGAL backend.


제목

ST_ApproximateMedialAxis — Deprecated alias for CG_ApproximateMedialAxis.

요약

geometry ST_ApproximateMedialAxis(geometry geom);

Description

[주의]

ST_ApproximateMedialAxis is deprecated as of 3.5.0. Use CG_ApproximateMedialAxis instead.

Availability: 2.2.0

This method needs SFCGAL backend.


제목

ST_IsPlanar — Deprecated alias for CG_IsPlanar.

요약

boolean ST_IsPlanar(geometry geom);

Description

[주의]

ST_IsPlanar is deprecated as of 3.5.0. Use CG_IsPlanar instead.

Availability: 2.2.0: This was documented in 2.1.0 but got accidentally left out in 2.1 release.

This method needs SFCGAL backend.


제목

ST_Volume — Deprecated alias for CG_Volume.

요약

float ST_Volume(geometry geom1);

Description

[주의]

ST_Volume is deprecated as of 3.5.0. Use CG_Volume instead.

Availability: 2.2.0

This method needs SFCGAL backend.


제목

ST_MakeSolid — Deprecated alias for CG_MakeSolid.

요약

geometry ST_MakeSolid(geometry geom1);

Description

[주의]

ST_MakeSolid is deprecated as of 3.5.0. Use CG_MakeSolid instead.

Availability: 2.2.0

This method needs SFCGAL backend.


제목

ST_IsSolid — Deprecated alias for CG_IsSolid.

요약

boolean ST_IsSolid(geometry geom1);

Description

[주의]

ST_IsSolid is deprecated as of 3.5.0. Use CG_IsSolid instead.

Availability: 2.2.0

This method needs SFCGAL backend.


제목

ST_ConstrainedDelaunayTriangles — Deprecated alias for CG_ConstrainedDelaunayTriangles.

요약

geometry ST_ConstrainedDelaunayTriangles(geometry g1);

Description

[주의]

ST_ConstrainedDelaunayTriangles is deprecated as of 3.5.0. Use CG_ConstrainedDelaunayTriangles instead.

Availability: 3.0.0

This method needs SFCGAL backend.


제목

ST_3DConvexHull — Deprecated alias for CG_3DConvexHull.

요약

geometry ST_3DConvexHull(geometry geom1);

Description

[주의]

ST_3DConvexHull is deprecated as of 3.5.0. Use CG_3DConvexHull instead.

Availability: 3.3.0

This method needs SFCGAL backend.


제목

ST_AlphaShape — Deprecated alias for CG_AlphaShape.

요약

geometry ST_AlphaShape(geometry geom, float alpha , boolean allow_holes = false );

Description

[주의]

ST_AlphaShape is deprecated as of 3.5.0. Use CG_AlphaShape instead.

This method needs SFCGAL backend.


제목

ST_OptimalAlphaShape — Deprecated alias for CG_OptimalAlphaShape.

요약

geometry ST_OptimalAlphaShape(geometry geom, boolean allow_holes = false , integer nb_components = 1 );

Description

[주의]

ST_OptimalAlphaShape is deprecated as of 3.5.0. Use CG_OptimalAlphaShape instead.

Availability: 3.3.0 - requires SFCGAL >= 1.4.1.

This method needs SFCGAL backend.

9장. 지형(topology)

PostGIS 지형 유형 및 함수는 표면(face), 가장자리(edge), 노드(node)와 같은 위상기하학적 객체를 관리했습니다.

Sandro Santilli's presentation at PostGIS Day Paris 2011 conference gives a good synopsis of PostGIS Topology and where it is headed Topology with PostGIS 2.0 slide deck.

Vincent Picavet provides a good synopsis and overview of what is Topology, how is it used, and various FOSS4G tools that support it in PostGIS Topology PGConf EU 2012.

An example of a topologically based GIS database is the US Census Topologically Integrated Geographic Encoding and Referencing System (TIGER) database. If you want to experiment with PostGIS topology and need some data.

The PostGIS topology module has existed for a long time but was not always part of the official documentation. Extensive cleanup removed deprecated functions, fixed known usability issues, documented the features and functions, added new functionality, and improved SQL-MM compliance.

This chapter is the maintained reference for the topology module, including its primitive tables, TopoGeometry type, topology management functions, editing functions, validation functions, and conversion helpers.

이 모듈과 관련된 모든 함수 및 테이블이 topology 라는 스키마에 설치돼 있습니다.

SQL/MM 표준이 정의하는 함수들은 접두사 ST_ 가 붙은 명칭을 가지고 있으며, PostGIS에 특화된 함수들의 명칭에는 접두사가 붙지 않습니다.

Topology support is built by default and can be disabled by specifying the --without-topology configure option at build time as described in 2장. PostGIS 설치

9.1. Topology Primitive Tables

The core primitives of any topology are stored in the edge_data, node, and face tables that live in the schema created by CreateTopology. Each row of edge_data represents an oriented edge: it records a directed curve from start_node to end_node together with the identifier of the face encountered on the left of that direction (left_face) and the face encountered on the right (right_face). The same geometric segment may therefore appear twice—once for each orientation—when it belongs to two faces.

The next_left_edge and next_right_edge columns complete this orientation information by encoding how to keep walking around a face. They store signed integers whose absolute value is the identifier of the next oriented edge and whose sign determines whether the stored orientation has to be followed as-is or reversed when traversing. Formally, the following rules hold for every edge e:

  • abs(next_left_edge) is the identifier of the edge reached by continuing around the face that lies to the left of e. If the value is positive the walk continues from the end node of e along the stored orientation of the referenced edge; if it is negative the referenced edge must be followed backwards so that the shared face remains on the walker’s left.

  • abs(next_right_edge) analogously follows the boundary of the face located on the right of e. A positive value means that the next edge is taken with its recorded orientation starting from the end node of e, whereas a negative value instructs to traverse the referenced edge in reverse, starting from its end node, so that the right-hand face is preserved.

  • A zero value indicates that the edge is dangling on the corresponding side (for example an isolated edge whose incident face is the universal face 0). The abs_next_left_edge and abs_next_right_edge columns exposed by the edge view are convenience projections of these absolute values.

This representation is a variant of a doubly connected edge list and is exploited by many topology routines. Functions such as GetRingEdges and ValidateTopology rely on it to reconstruct face boundaries and to diagnose inconsistencies—hence the “invalid next_left_edge” and “invalid next_right_edge” diagnostics reported during validation. Constructors like AddEdge initialise the next_* attributes with trivial self references, while editing routines including ST_AddEdgeModFace and ST_RemEdgeModFace update the links as edges are inserted or removed. Other bulk operations (for example Polygonize) may intentionally leave the fields unset, which is why the documentation flags their behaviour explicitly.

9.2. 지형 유형

초록

이 단원에서 PostGIS 지형이 설치한 PostgreSQL 데이터 유형을 소개합니다. 사용자 지정 함수를 설계할 때 특히 중요한 이 유형들의 형변환 습성(cast behavior)을 설명한다는 점에 주의하십시오.

  • getfaceedges_returntype — A composite type that consists of a sequence number and an edge number.
  • TopoGeometry — A composite type representing a topologically defined geometry.
  • validatetopology_returntype — A composite type that consists of an error message and id1 and id2 to denote location of error. This is the return type for ValidateTopology.

제목

getfaceedges_returntype — A composite type that consists of a sequence number and an edge number.

Description

A composite type that consists of a sequence number and an edge number. This is the return type for ST_GetFaceEdges and GetNodeEdges functions.

  1. sequence 는 정수형입니다: 지형 스키마 및 SRID를 정의하는 topology.topology 테이블에 정의돼 있는 지형을 참조하십시오.

  2. edge 는 정수형입니다: 경계선의 식별자입니다.


제목

TopoGeometry — A composite type representing a topologically defined geometry.

Description

특정 지형 레이어에 있는, 특정 유형 및 특정 ID를 가진 지형 도형을 참조하는 합성 유형입니다. TopoGeometry를 구성하는 요소는 topology_id, layer_id, id, type 정수형 속성입니다.

  1. topology_id 는 정수형입니다: 지형 스키마 및 SRID를 정의하는 topology.topology 테이블에 정의돼 있는 지형을 참조하십시오.

  2. layer_id 는 정수형입니다: TopoGeometry가 속해 있는 레이어 테이블의 layer_id입니다. topology_id 와 layer_id를 조합하면 topology.layers 테이블에 유일한 참조(unique reference)를 제공합니다.

  3. id 는 정수형입니다: 해당 지형 레이어에 지형 도형을 유일하게 정의하는, 자동 생성된 순차 번호입니다.

  4. 1에서 4까지의 type 정수가 도형 유형을 정의합니다. 1: [멀티]포인트, 2: [멀티]라인, 3: [멀티]폴리곤, 4: 도형 집합.

형변환 습성

이 단원에서 이런 데이터 유형에 사용할 수 있는 자동 형변환은 물론 명시적인 형변환도 소개합니다.

형변환 결과습성
도형자동적

제목

validatetopology_returntype — A composite type that consists of an error message and id1 and id2 to denote location of error. This is the return type for ValidateTopology.

Description

오류 메시지 및 정수형 2개로 이루어진 합성 유형입니다. ValidateTopology 함수가 확인 오류 및 해당 오류에 연관된 지형 객체들의 ID를 표시하는 id1과 id2를 나타내는 이 집합을 반환합니다.

FieldTypeDescription
errorvarchar

Denotes the type of error.

Current error descriptors are: coincident nodes, edge crosses node, edge not simple, edge end node geometry mismatch, edge start node geometry mismatch, face overlaps face, face within face.

id1integerDenotes the identifier of the edge, face, or node in error.
id2integerFor errors that involve two objects, denotes the secondary edge or node.

9.3. 지형 도메인

초록

이 단원에서 PostGIS 지형이 설치한 PostgreSQL 도메인을 소개합니다. 함수가 반환하는 유형 또는 테이블 열 등, 도메인을 객체 유형처럼 이용할 수 있습니다. 도메인과 유형의 차이점은, 도메인이 확인 제약조건으로 묶여 있는 기존 유형이라는 점입니다.

  • TopoElement — 일반적으로 TopoGeometry 구성 요소를 식별하는 데 쓰이는 정수형 2개의 배열입니다.
  • TopoElementArray — An array of TopoElement objects.

제목

TopoElement — 일반적으로 TopoGeometry 구성 요소를 식별하는 데 쓰이는 정수형 2개의 배열입니다.

Description

단순 또는 계층 TopoGeometry 의 구성 요소 1개를 표현하는 데 쓰이는 정수형 2개의 배열입니다.

단순 TopoGeometry의 경우, 배열의 첫 번째 요소가 지형적 원시형(topological primitive)의 식별자를 나타내고 두 번째 요소가 그 유형(1: node, 2: edge, 3: face)을 나타냅니다. 계층 TopoGeometry의 경우 배열의 첫 번째 요소가 자식 TopoGeometry의 식별자를 나타내고 두 번째 요소가 해당 레이어 식별자를 나타냅니다.

[참고]

어떤 계층 TopoGeometry가 주어지더라도, 모든 자식 TopoGeometry 요소들은, 해당 TopoGeometry의 레이어에 대해 topology.layer 레코드에 지정된 동일한 자식 레이어에서 나옵니다.

예시

Code
SELECT te[1] AS id, te[2] AS type FROM
( SELECT ARRAY[1, 2]::topology.topoelement AS te ) f;
래스터 출력
id | type
----+------
  1 |    2
                 
Code
SELECT ARRAY[1, 2]::topology.topoelement;
래스터 출력
te
-------
 {1,2}
                 

This example shows what happens when casting a three-element array to topology.topoelement. The domain requires a two-element array, so the dimension check fails.

Code
SELECT ARRAY[1, 2, 3]::topology.topoelement;
래스터 출력
ERROR:  value for domain topology.topoelement violates check constraint "dimensions"

제목

TopoElementArray — An array of TopoElement objects.

Description

1개 이상의 TopoElement 객체들의 배열로, 일반적으로 TopoElement 객체의 구성 요소들을 넘겨주는 데 쓰입니다.

예시

Code
SELECT '{{1,2},{4,3}}'::topology.topoelementarray AS tea;
래스터 출력
{{1,2},{4,3}}

This is the more verbose equivalent.

Code
SELECT ARRAY[ARRAY[1, 2], ARRAY[4, 3]]::topology.topoelementarray AS tea;
래스터 출력
{{1,2},{4,3}}

This example uses the array aggregate function packaged with topology.

Code
SELECT topology.TopoElementArray_Agg(ARRAY[e, t] ORDER BY e, t) As tea
FROM generate_series(1, 4) As e CROSS JOIN generate_series(1, 3) As t;
                 
래스터 출력
{{1,1},{1,2},{1,3},{2,1},{2,2},{2,3},{3,1},{3,2},{3,3},{4,1},{4,2},{4,3}}
Code
SELECT '{{1,2,4},{3,4,5}}'::topology.topoelementarray AS tea;
래스터 출력
ERROR:  value for domain topology.topoelementarray violates check constraint "dimensions"

9.4. 지형 및 TopoGeometry 관리

초록

이 단원에서 새로운 지형 스키마를 빌드하고, 지형이 유효한지 확인하고, TopoGeometry 열을 관리하기 위한 지형 함수들을 소개합니다.

  • AddTopoGeometryColumn — 기존 테이블에 TopoGeometry 열을 추가하고, topology.layer에 이 새 열을 레이어로 추가하며, 새 layer_id를 반환합니다.
  • RenameTopoGeometryColumn — Renames a topogeometry column
  • DropTopology — 이용에 주의하십시오: 지형 스키마를 삭제하고 topology.topology 테이블에서 해당 참조를, 그리고 geometry_columns 테이블에서 해당 스키마에 있는 테이블의 참조를 삭제합니다.
  • RenameTopology — Renames a topology
  • DropTopoGeometryColumnschema_name 스키마 안의 table_name 명칭의 테이블에서 Topogeometry 열을 삭제하고 topology.layer 테이블에서 해당 열을 등록 해제합니다.
  • FixCorruptTopoGeometryColumn — Fixes topogeometry corruption caused by upgrade to postgis_topology 3.6.0 and higher
  • Populate_Topology_Layer — Adds missing entries to topology.layer table by reading metadata from topo tables.
  • TopologySummary — Takes a topology name and provides summary totals of types of objects in topology.
  • ValidateTopology — Returns a set of validatetopology_returntype objects detailing issues with topology.
  • ValidateTopologyRelation — Returns info about invalid topology relation records
  • ValidateTopologyPrecision — Returns non-precise vertices in the topology.
  • MakeTopologyPrecise — Snap topology vertices to precision grid.
  • FindTopology — Returns a topology record by different means.
  • FindLayer — Returns a topology.layer record by different means.
  • TotalTopologySize — Total disk space used by the specified topology, including all indexes and TOAST data.
  • UpgradeTopology — Upgrades the specified topology to support large ids (int8) for topology and primitive ids.

제목

AddTopoGeometryColumn — 기존 테이블에 TopoGeometry 열을 추가하고, topology.layer에 이 새 열을 레이어로 추가하며, 새 layer_id를 반환합니다.

요약

integer AddTopoGeometryColumn(name topology_name, name schema_name, name table_name, name column_name, varchar feature_type, integer child_layer);

integer AddTopoGeometryColumn(name topology_name, regclass tab, name column_name, integer layer_id, varchar feature_type, integer child_layer);

Description

각 TopoGeometry 객체는 특정 지형의 특정 레이어에 속합니다. TopoGeometry 객체를 생성하기 전에 해당 지형 레이어를 생성해야 합니다. 지형 레이어란 지형과 피처 테이블의 조합입니다. 유형 및 계층 정보도 담고 있습니다. AddTopoGeometryColumn() 함수를 이용해서 레이어를 생성해보겠습니다:

이 함수는 요청한 열을 테이블에 추가하고 topology.layer 테이블에 레코드를 주어진 모든 정보와 함께 추가할 것입니다.

[child_layer]를 따로 설정하지 않을 (또는 NULL로 설정할) 경우, 해당 레이어가 (원시형 지형 요소들로 이루어진) 기본 TopoGeometry를 담을 것입니다. 그렇지 않을 경우, 이 레이어는 (child_layer에서 나온 TopoGeometry들로 이루어진) 계층 TopoGeometry를 담을 것입니다.

레이어를 생성했다면 (AddTopoGeometryColumn 함수가 레이어의 ID를 반환합니다) 해당 레이어에 TopoGeometry 객체를 작성할 준비가 된 것입니다.

Valid feature_types are: POINT, MULTIPOINT, LINE, MULTILINE, POLYGON, MULTIPOLYGON, COLLECTION

Availability: 1.1

예시

This example creates the new table in the ma_topo schema. The table could be created in a different schema, in which case topology_name and schema_name would be different.

Code
CREATE SCHEMA ma;
CREATE TABLE ma.parcels(gid serial, parcel_id varchar(20) PRIMARY KEY, address text);
SELECT topology.AddTopoGeometryColumn('ma_topo', 'ma', 'parcels', 'topo', 'POLYGON');
Code
CREATE SCHEMA ri;
CREATE TABLE ri.roads(gid serial PRIMARY KEY, road_name text);
SELECT topology.AddTopoGeometryColumn('ri_topo', 'ri', 'roads', 'topo', 'LINE');

제목

RenameTopoGeometryColumn — Renames a topogeometry column

요약

topology.layer RenameTopoGeometryColumn(regclass layer_table, name feature_column, name new_name);

Description

This function changes the name of an existing TopoGeometry column ensuring metadata information about it is updated accordingly.

Availability: 3.4.0

예시

Code
SELECT topology.RenameTopoGeometryColumn('public.parcels', 'topogeom', 'tgeom');

제목

DropTopology — 이용에 주의하십시오: 지형 스키마를 삭제하고 topology.topology 테이블에서 해당 참조를, 그리고 geometry_columns 테이블에서 해당 스키마에 있는 테이블의 참조를 삭제합니다.

요약

integer DropTopology(varchar topology_schema_name);

Description

지형 스키마를 삭제하고 topology.topology 테이블에서 해당 참조를, 그리고 geometry_columns 테이블에서 해당 스키마에 있는 테이블의 참조를 삭제합니다. 이 함수는 사용자의 관심 데이터를 파괴할 수도 있으니 주의해서 사용해야 합니다. 스키마가 존재하지 않을 경우, 해당 스키마의 명칭으로 된 참조 항목만 제거합니다.

Availability: 1.1

예시

ma_topo 스키마를 삭제하고 topology.topology와 geometry_columns에 있는 모든 해당 스키마의 참조를 차례로 제거합니다.

Code
SELECT topology.DropTopology('ma_topo');

제목

RenameTopology — Renames a topology

요약

varchar RenameTopology(varchar old_name, varchar new_name);

Description

Renames a topology schema, updating its metadata record in the topology.topology table.

Availability: 3.4.0

예시

Rename a topology from topo_stage to topo_prod.

Code
SELECT topology.RenameTopology('topo_stage', 'topo_prod');

제목

DropTopoGeometryColumn — schema_name 스키마 안의 table_name 명칭의 테이블에서 Topogeometry 열을 삭제하고 topology.layer 테이블에서 해당 열을 등록 해제합니다.

요약

text DropTopoGeometryColumn(varchar schema_name, varchar table_name, varchar column_name);

Description

schema_name 스키마 안의 table_name 명칭의 테이블에서 Topogeometry 열을 삭제하고 topology.layer 테이블에서 해당 열을 등록 해제합니다. 삭제 상태의 요약문을 반환합니다. 주의: 참조 무결성 확인 작업을 건너뛰기 위해 삭제하기 전에 먼저 모든 값을 NULL로 설정합니다.

Availability: 1.1

예시

Code
SELECT topology.DropTopoGeometryColumn('ma_topo', 'parcel_topo', 'topo');

제목

FixCorruptTopoGeometryColumn — Fixes topogeometry corruption caused by upgrade to postgis_topology 3.6.0 and higher

요약

text FixCorruptTopoGeometryColumn(name layerSchema, name layerTable, name layerColumn );

Description

When upgrading from PostGIS topology <3.6.0 to version >3.6.0+, the topogeometry column definition was changed. This caused corruption in topogeometries created before the upgrade. This function fixes this corruption in affected tables.

The function refuses to process tables with expression or partial indexes; drop or rebuild those indexes manually around the repair.

Availability: 3.6.1

예시

Fix all topology columns

Code
SELECT topology.FixCorruptTopoGeometryColumn(schema_name, table_name, feature_column)
    FROM topology.layer;
                

제목

Populate_Topology_Layer — Adds missing entries to topology.layer table by reading metadata from topo tables.

요약

setof record Populate_Topology_Layer();

Description

Adds missing entries to the topology.layer table by inspecting topology constraints on tables. This function is useful for fixing up entries in topology catalog after restores of schemas with topo data.

It returns the list of entries created. Returned columns are schema_name, table_name, feature_column.

2.3.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT CreateTopology('strk_topo');
CREATE SCHEMA strk;
CREATE TABLE strk.parcels(gid serial, parcel_id varchar(20) PRIMARY KEY, address text);
SELECT topology.AddTopoGeometryColumn('strk_topo', 'strk', 'parcels', 'topo', 'POLYGON');
래스터 출력
createtopology
----------------
              1
(1 row)

CREATE SCHEMA
CREATE TABLE
 addtopogeometrycolumn
-----------------------
                     1
(1 row)

This query returns no records because the feature is already registered.

Code
SELECT *
FROM topology.Populate_Topology_Layer();
래스터 출력
(0 rows)

Rebuild the topology layer catalog.

Code
TRUNCATE TABLE topology.layer;
래스터 출력
TRUNCATE TABLE
Code
SELECT *
FROM topology.Populate_Topology_Layer();
래스터 출력
schema_name | table_name | feature_column
-------------+------------+----------------
 strk        | parcels    | topo
(1 row)
Code
SELECT topology_id, layer_id,
       schema_name AS sn, table_name AS tn, feature_column AS fc
FROM topology.layer;
래스터 출력
topology_id | layer_id |  sn  |   tn    |  fc
-------------+----------+------+---------+------
           1 |        1 | strk | parcels | topo
(1 row)

제목

TopologySummary — Takes a topology name and provides summary totals of types of objects in topology.

요약

text TopologySummary(varchar topology_schema_name);

Description

Takes a topology name and provides summary totals of types of objects in topology.

2.0.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT topology.TopologySummary('city_data');
래스터 출력
Topology city_data (329), SRID 4326, precision: 0
22 nodes, 24 edges, 10 faces, 29 topogeoms in 5 layers
Layer 1, type Polygonal (3), 9 topogeoms
 Deploy: features.land_parcels.feature
Layer 2, type Puntal (1), 8 topogeoms
 Deploy: features.traffic_signs.feature
Layer 3, type Lineal (2), 8 topogeoms
 Deploy: features.city_streets.feature
Layer 4, type Polygonal (3), 3 topogeoms
 Hierarchy level 1, child layer 1
 Deploy: features.big_parcels.feature
Layer 5, type Puntal (1), 1 topogeoms
 Hierarchy level 1, child layer 2
 Deploy: features.big_signs.feature

제목

ValidateTopology — Returns a set of validatetopology_returntype objects detailing issues with topology.

요약

setof validatetopology_returntype ValidateTopology(varchar toponame, geometry bbox);

Description

Returns a set of validatetopology_returntype objects detailing issues with topology, optionally limiting the check to the area specified by the bbox parameter.

List of possible errors, what they mean and what the returned ids represent are displayed below:

오류id1id2Meaning
coincident nodesIdentifier of first node.Identifier of second node.Two nodes have the same geometry.
edge crosses node(노드를 가로지르는 경계선)Identifier of the edge.Identifier of the node.An edge has a node in its interior. See ST_Relate.
invalid edge(유효하지 않은 경계선)Identifier of the edge. An edge geometry is invalid. See ST_IsValid.
edge not simple(단순하지 않은 경계선)Identifier of the edge. An edge geometry has self-intersections. See ST_IsSimple.
edge crosses edge(경계선을 가로지르는 경계선)Identifier of first edge.Identifier of second edge.Two edges have an interior intersection. See ST_Relate.
edge start node geometry mismatch(경계선의 시작 노드 도형 불일치)Identifier of the edge.Identifier of the indicated start node. The geometry of the node indicated as the starting node for an edge does not match the first point of the edge geometry. See ST_StartPoint.
edge end node geometry mismatch(경계선의 종단 노드 도형 불일치)Identifier of the edge.Identifier of the indicated end node. The geometry of the node indicated as the ending node for an edge does not match the last point of the edge geometry. See ST_EndPoint.
face without edges(경계선이 없는 표면)Identifier of the orphaned face.  No edge reports an existing face on either of its sides (left_face, right_face).
face has no rings(고리가 없는 표면)Identifier of the partially-defined face.  Edges reporting a face on their sides do not form a ring.
face has wrong mbrIdentifier of the face with wrong mbr cache.  Minimum bounding rectangle of a face does not match minimum bounding box of the collection of edges reporting the face on their sides.
hole not in advertised faceSigned identifier of an edge, identifying the ring. See GetRingEdges.  A ring of edges reporting a face on its exterior is contained in different face.
not-isolated node has not- containing_faceIdentifier of the ill-defined node.  A node which is reported as being on the boundary of one or more edges is indicating a containing face.
isolated node has containing_faceIdentifier of the ill-defined node.  A node which is not reported as being on the boundary of any edges is lacking the indication of a containing face.
isolated node has wrong containing_faceIdentifier of the misrepresented node.  A node which is not reported as being on the boundary of any edges indicates a containing face which is not the actual face containing it. See GetFaceContainingPoint.
invalid next_right_edgeIdentifier of the misrepresented edge. Signed id of the edge which should be indicated as the next right edge. The edge indicated as the next edge encountered walking on the right side of an edge is wrong.
invalid next_left_edgeIdentifier of the misrepresented edge. Signed id of the edge which should be indicated as the next left edge. The edge indicated as the next edge encountered walking on the left side of an edge is wrong.
mixed face labeling in ringSigned identifier of an edge, identifying the ring. See GetRingEdges.  Edges in a ring indicate conflicting faces on the walking side. This is also known as a "Side Location Conflict".
non-closed ringSigned identifier of an edge, identifying the ring. See GetRingEdges.  A ring of edges formed by following next_left_edge/next_right_edge attributes starts and ends on different nodes.
face has multiple shellsIdentifier of the contended face. Signed identifier of an edge, identifying the ring. See GetRingEdges. More than a one ring of edges indicate the same face on its interior.

1.0.0 버전부터 사용할 수 있습니다.

개선 사항: 2.0.0 버전에서 경계선 가로지르기 탐지를 더 효율적으로 개선하고, 이전 버전에 존재했던 긍정 오류(false positive)를 해결했습니다.

변경 사항: 2.2.0 버전에서 'edge crosses node'를 오류 설명문과 일치시키기 위해 id1과 id2의 값을 서로 바꿨습니다.

Changed: 3.2.0 added optional bbox parameter, perform face labeling and edge linking checks.

예시

Code
SELECT * FROM topology.ValidateTopology('ma_topo');
래스터 출력
error        | id1 | id2
-------------------+-----+-----
face without edges |   1 |

제목

ValidateTopologyRelation — Returns info about invalid topology relation records

요약

setof record ValidateTopologyRelation(varchar toponame);

Description

Returns a set records giving information about invalidities in the relation table of the topology.

Availability: 3.2.0


제목

ValidateTopologyPrecision — Returns non-precise vertices in the topology.

요약

geometry ValidateTopologyPrecision(name toponame, geometry bbox, float8 gridSize);

Description

Returns all vertices that are not rounded to the topology or given gridSize as a puntal geometry, optionally limiting the check to the area specified by the bbox parameter.

Availability: 3.6.0

예시

Code
SELECT g
FROM topology.ValidateTopologyPrecision(
    'city_data',
    gridSize =
> 2,
    bbox =
> ST_MakeEnvelope(0, 0, 20, 20)
) g;
래스터 출력
MULTIPOINT(9 6,9 14)
Figure
Geometry figure for visual-validatetopologyprecision-01

제목

MakeTopologyPrecise — Snap topology vertices to precision grid.

요약

void MakeTopologyPrecise(name toponame, geometry bbox, float8 gridSize);

Description

Snaps all vertices of a topology to the topology precision grid or to the grid whose size is specified with the gridSize parameter, optionally limiting the operation to the objects intersecting the area specified by the bbox parameter.

Using a gridSize larger than the smallest edge extent raises an exception rather than collapsing the edge into an empty geometry. This safeguards adjacent topological relationships by preventing precision snapping from removing primitives altogether.

[참고]

Snapping could make the topology invalid, so it is recommended to check the outcome of operation with ValidateTopology.

Availability: 3.6.0

예시

Code
SELECT topology.MakeTopologyPrecise(
    'city_data',
    gridSize =
> 2
);

제목

FindTopology — Returns a topology record by different means.

요약

topology FindTopology(topogeometry topogeom);

topology FindTopology(regclass layerTable, name layerColumn);

topology FindTopology(name layerSchema, name layerTable, name layerColumn);

topology FindTopology(text topoName);

topology FindTopology(int id);

Description

Takes a topology identifier or the identifier of a topology-related object and returns a topology.topology record.

Availability: 3.2.0

예시

Code
SELECT name(FindTopology('features.land_parcels', 'feature'));
래스터 출력
city_data

참고

FindLayer


제목

FindLayer — Returns a topology.layer record by different means.

요약

topology.layer FindLayer(topogeometry tg);

topology.layer FindLayer(regclass layer_table, name feature_column);

topology.layer FindLayer(name schema_name, name table_name, name feature_column);

topology.layer FindLayer(integer topology_id, integer layer_id);

Description

Takes a layer identifier or the identifier of a topology-related object and returns a topology.layer record.

Availability: 3.2.0

예시

Code
SELECT layer_id(FindLayer('features.land_parcels', 'feature'));
래스터 출력
1

제목

TotalTopologySize — Total disk space used by the specified topology, including all indexes and TOAST data.

요약

int8 TotalTopologySize(name toponame);

Description

Takes a topology name and provides the total disk space used by all its tables, including indexes and TOAST data.

Availability: 3.6.0

예시

Code
SELECT topology.TopologySummary('city_data');
래스터 출력
Topology city_data (329), SRID 4326, precision: 0
22 nodes, 24 edges, 10 faces, 29 topogeoms in 5 layers
Layer 1, type Polygonal (3), 9 topogeoms
 Deploy: features.land_parcels.feature
Layer 2, type Puntal (1), 8 topogeoms
 Deploy: features.traffic_signs.feature
Layer 3, type Lineal (2), 8 topogeoms
 Deploy: features.city_streets.feature
Layer 4, type Polygonal (3), 3 topogeoms
 Hierarchy level 1, child layer 1
 Deploy: features.big_parcels.feature
Layer 5, type Puntal (1), 1 topogeoms
 Hierarchy level 1, child layer 2
 Deploy: features.big_signs.feature

제목

UpgradeTopology — Upgrades the specified topology to support large ids (int8) for topology and primitive ids.

요약

void UpgradeTopology(name toponame);

Description

Takes a topology name and upgrades it to support large ids (int8) for topology and primitive ids. The function upgrades the following: - face (face_id column from int4 to int8, face_id_seq from int4 to int8) - node (node_id column from int4 to int8, containing_face column from int4 to int8, node_id_seq from int4 to int8) - edge_data (edge_id column from int4 to int8, edge_data_edge_id_seq from int4 to int8, left_face and right_face columns from int4 to int8, start_node and end_node columns from int4 to int8, next_left_edge and next_right_edge columns from int4 to int8) - relation (topogeo_id column from int4 to int8, element_id from int4 to int8) - topology (useslargeids column set to true)

Availability: 3.6.0

예시

Code
SELECT topology.UpgradeTopology('city_data');

9.5. Topology Statistics Management

초록

This section discusses management of database statistics during topology building.

Adding elements to a topology triggers many database queries for finding existing edges that will be split, adding nodes and updating edges that will node with the new linework. For this reason it is useful that statistics about the data in the topology tables are up-to-date.

PostGIS Topology population and editing functions do not automatically update the statistics because a updating stats after each and every change in a topology would be overkill, so it is the caller's duty to take care of that.

[참고]

That the statistics updated by autovacuum will NOT be visible to transactions which started before autovacuum process completed, so long-running transactions will need to run ANALYZE themselves, to use updated statistics.

9.6. 지형 작성자

초록

이 단원에서 새 지형을 생성하기 위한 지형 함수에 대해 설명합니다.

  • CreateTopology — Creates a new topology schema and registers it in the topology.topology table.
  • CopyTopology — Makes a copy of a topology (nodes, edges, faces, layers and TopoGeometries) into a new schema
  • ST_InitTopoGeo — Creates a new topology schema and registers it in the topology.topology table.
  • ST_CreateTopoGeo — 텅 빈 입력 지형에 도형들의 집합을 추가한 다음 작업 성공 여부를 상세하게 설명하는 메시지를 반환합니다.
  • TopoGeo_AddPoint — 허용 오차를 이용해서 그리고 기존 경계선을 분할(split)하기도 해서 기존 지형에 포인트를 추가합니다.
  • TopoGeo_AddLineString — Adds a linestring to an existing topology using a tolerance and possibly splitting existing edges/faces.
  • TopoGeo_AddPolygon — Adds a polygon to an existing topology using a tolerance and possibly splitting existing edges/faces. Returns face identifiers.
  • TopoGeo_LoadGeometry — Load a geometry into an existing topology, snapping and splitting as needed.

제목

CreateTopology — Creates a new topology schema and registers it in the topology.topology table.

요약

integer CreateTopology(name topology_schema_name, integer srid, double precision prec=0, boolean hasz=false, integer topoid=0, boolean useslargeids=false);

Description

Creates a new topology schema with name topology_name and registers it in the topology.topology table. Topologies must be uniquely named. The topology tables (edge_data, face, node,and relation are created in the schema. It returns the id of the topology.

The srid is the spatial reference system SRID for the topology. The SRID defaults to -1 (unknown) if not specified.

The tolerance prec is measured in the units of the spatial reference system. The tolerance defaults to 0.

hasz defaults to false if not specified.

topoid optional explicit identifier (allows deterministic topology id assignment, needs to be unique)

useslargeids optional, defaults to false. If true, the topology will be created to support large ids (int8) for topology and primitive ids.

This is similar to the SQL/MM ST_InitTopoGeo but has more functionality.

Availability: 1.1

Enhanced: 2.0 added support for hasZ.

Enhanced: 3.6.0 added topoid and usesLargeIDs parameters.

예시

Create a topology schema called ma_topo that stores edges and nodes in Massachusetts State Plane-meters (SRID = 26986). The tolerance represents 0.5 meters since the spatial reference system is meter-based.

Code
SELECT topology.CreateTopology('ma_topo', 26986, 0.5);

Create a topology for Rhode Island called ri_topo in spatial reference system State Plane-feet (SRID = 3438)

Code
SELECT topology.CreateTopology('ri_topo', 3438) AS topoid;
래스터 출력
2

제목

CopyTopology — Makes a copy of a topology (nodes, edges, faces, layers and TopoGeometries) into a new schema

요약

integer CopyTopology(varchar existing_topology_name, varchar new_name);

Description

Creates a new topology with name new_name, with SRID and precision copied from existing_topology_name The nodes, edges and faces in existing_topology_name are copied into the new topology, as well as Layers and their associated TopoGeometries.

[참고]

The new rows in the topology.layer table contain synthetic values for schema_name, table_name and feature_column. This is because the TopoGeometry objects exist only as a definition and are not yet available in a user-defined table.

2.0.0 버전부터 사용할 수 있습니다.

예시

Make a backup of a topology called ma_topo.

Code
SELECT topology.CopyTopology('ma_topo', 'ma_topo_backup');

제목

ST_InitTopoGeo — Creates a new topology schema and registers it in the topology.topology table.

요약

text ST_InitTopoGeo(varchar topology_schema_name);

Description

This is the SQL-MM equivalent of CreateTopology. It lacks options for spatial reference system and tolerance. it returns a text description of the topology creation, instead of the topology id.

Availability: 1.1

This method implements the SQL/MM specification. SQL-MM 3 Topo-Geo and Topo-Net 3: Routine Details: X.3.17

예시

Code
SELECT topology.ST_InitTopoGeo('topo_schema_to_create') AS topocreation;
래스터 출력
Topology-Geometry 'topo_schema_to_create' (id:7) created.

제목

ST_CreateTopoGeo — 텅 빈 입력 지형에 도형들의 집합을 추가한 다음 작업 성공 여부를 상세하게 설명하는 메시지를 반환합니다.

요약

text ST_CreateTopoGeo(varchar atopology, geometry acollection);

Description

텅 빈 입력 지형에 도형들의 집합을 추가한 다음 작업 성공 여부를 상세하게 설명하는 메시지를 반환합니다.

텅 빈 지형을 채우는 데 유용합니다.

2.0 버전부터 사용할 수 있습니다.

This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details -- X.3.18

예시

Populate the topology.

Code
SELECT topology.ST_CreateTopoGeo(
'ri_topo',
ST_GeomFromText(
 'MULTILINESTRING((384744 236928,384750 236923,384769 236911,384799 236895,384811 236890,384833 236884,
 384844 236882,384866 236881,384879 236883,384954 236898,385087 236932,385117 236938,
 385167 236938,385203 236941,385224 236946,385233 236950,385241 236956,385254 236971,
 385260 236979,385268 236999,385273 237018,385273 237037,385271 237047,385267 237057,
 385225 237125,385210 237144,385192 237161,385167 237192,385162 237202,385159 237214,
 385159 237227,385162 237241,385166 237256,385196 237324,385209 237345,385234 237375,
 385237 237383,385238 237399,385236 237407,385227 237419,385213 237430,385193 237439,
 385174 237451,385170 237455,385169 237460,385171 237475,385181 237503,385190 237521,
 385200 237533,385206 237538,385213 237541,385221 237542,385235 237540,385242 237541,
 385249 237544,385260 237555,385270 237570,385289 237584,385292 237589,385291 237596,385284 237630))',
 3438)
 );
래스터 출력
Topology ri_topo populated

Create the tables and topogeometries.

Code
CREATE TABLE ri.roads(gid serial PRIMARY KEY, road_name text);

SELECT topology.AddTopoGeometryColumn('ri_topo', 'ri', 'roads', 'topo', 'LINE');

제목

TopoGeo_AddPoint — 허용 오차를 이용해서 그리고 기존 경계선을 분할(split)하기도 해서 기존 지형에 포인트를 추가합니다.

요약

bigint TopoGeo_AddPoint(varchar atopology, geometry apoint, float8 tolerance);

Description

Adds a point to an existing topology and returns its identifier. The given point will snap to existing nodes or edges within given tolerance. An existing edge may be split by the snapped point.

2.0.0 버전부터 사용할 수 있습니다.


제목

TopoGeo_AddLineString — Adds a linestring to an existing topology using a tolerance and possibly splitting existing edges/faces.

요약

SETOF bigint TopoGeo_AddLineString(varchar atopology, geometry aline, float8 tolerance, int max_edges);

Description

Adds a linestring to an existing topology and returns a set of signed edge identifiers forming it up (negative identifies mean the edge goes in the opposite direction of the input linestring).

The given line will snap to existing nodes or edges within given tolerance. Existing edges and faces may be split by the line. New nodes and faces may be added, in addition to new edges.

The returned edge identifiers may be either existing edges or newly created edges as needed to fully represent the input line as closely as possible.

The number of newly created edges (either covering space previously uncovered or resulting from split of existing edges) may be limited by the max_edges parameter.

[참고]

When adding many lines, the load order can have a large impact on performance because each call checks the line against topology elements already loaded. In bulk workflows, adding large closed or enclosing lines before smaller contained lines can avoid expensive later splits. For loading a collection in one call, see TopoGeo_LoadGeometry.

[참고]

Updating statistics about topologies being loaded via this function is up to caller, see maintaining statistics during topology editing and population.

2.0.0 버전부터 사용할 수 있습니다.

Enhanced: 3.2.0 added support for returning signed identifier.

Enhanced: 3.7.0 added support for limiting the number of new edges created in the topology.


제목

TopoGeo_AddPolygon — Adds a polygon to an existing topology using a tolerance and possibly splitting existing edges/faces. Returns face identifiers.

요약

SETOF bigint TopoGeo_AddPolygon(varchar atopology, geometry apoly, float8 tolerance);

Description

Adds a polygon to an existing topology and returns a set of face identifiers forming it up. The boundary of the given polygon will snap to existing nodes or edges within given tolerance. Existing edges and faces may be split by the boundary of the new polygon.

[참고]

Updating statistics about topologies being loaded via this function is up to caller, see maintaining statistics during topology editing and population.

2.0.0 버전부터 사용할 수 있습니다.


제목

TopoGeo_LoadGeometry — Load a geometry into an existing topology, snapping and splitting as needed.

요약

void TopoGeo_LoadGeometry(varchar atopology, geometry ageom, float8 tolerance);

Description

Loads a geometry into an existing topology. The given geometry will snap to existing nodes or edges within given tolerance. Existing edges and faces may be split as a consequence of the load.

[참고]

Updating statistics about topologies being loaded via this function is up to caller, see maintaining statistics during topology editing and population.

Availability: 3.5.0

9.7. 지형 편집자

초록

이 단원에서 경계선, 표면, 노드를 추가하고, 이동하고, 삭제하고, 분할하기 위한 지형 함수에 대해 설명합니다. ISO SQL/MM이 이 단원의 모든 함수를 정의합니다.

  • ST_AddIsoNode — 지형 안의 표면에 고립된(isolated) 노드를 추가하고 새 노드의 ID를 반환합니다. 표면이 NULL일 경우, 그래도 노드를 생성합니다.
  • ST_AddIsoEdge — 지형에 두 개의 고립된 기존 노드 anodeanothernode 를 연결하는 alinestring 도형이 정의하는 고립된 경계선을 추가하고 새 경계선의 ID를 반환합니다.
  • ST_AddEdgeNewFaces — 새 경계선을 추가하고, 그 과정에서 경계선이 표면을 분할할 경우, 원본 표면을 삭제하고 새 표면 2개로 교체합니다.
  • ST_AddEdgeModFace — 새 경계선을 추가하고, 그 과정에서 경계선이 표면을 분할할 경우, 원본 표면을 수정하고 새 표면을 추가합니다.
  • ST_RemEdgeNewFace — 경계선을 제거하고, 제거한 경계선이 두 표면을 분할하고 있을 경우, 원본 표면들을 삭제하고 새 표면 하나로 대체합니다.
  • ST_RemEdgeModFace — Removes an edge, and if the edge separates two faces deletes one face and modifies the other face to cover the space of both.
  • ST_ChangeEdgeGeom — 지형 구조를 건드리는 일 없이 경계선의 형상을 변경합니다.
  • ST_ModEdgeSplit — 기존 경계선을 따라 새 노드를 추가한 다음, 원본 경계선을 수정하고 새 경계선을 추가해서 경계선을 분할합니다.
  • ST_ModEdgeHeal — Heals two edges by deleting the node connecting them, modifying the first edge and deleting the second edge. Returns the id of the deleted node.
  • ST_NewEdgeHeal — Heals two edges by deleting the node connecting them, deleting both edges, and replacing them with an edge whose direction is the same as the first edge provided.
  • ST_MoveIsoNode — Moves an isolated node in a topology from one point to another. If new apoint geometry exists as a node an error is thrown. Returns description of move.
  • ST_NewEdgesSplit — 기존 경계선을 따라 새 노드를 추가한 다음, 원본 경계선을 삭제하고 새 경계선 2개로 교체해서 경계선을 분할합니다. 새 경계선들을 결합하는 새로 생성된 노드의 ID를 반환합니다.
  • ST_RemoveIsoNode — 고립된 노드를 제거하고 작업 내용을 설명하는 메시지를 반환합니다. 노드가 고립되지 않은 (경계선의 시작점이나 종단점인) 경우, 예외가 발생합니다.
  • ST_RemoveIsoEdge — Removes an isolated edge and returns description of action. If the edge is not isolated, then an exception is thrown.

제목

ST_AddIsoNode — 지형 안의 표면에 고립된(isolated) 노드를 추가하고 새 노드의 ID를 반환합니다. 표면이 NULL일 경우, 그래도 노드를 생성합니다.

요약

bigint ST_AddIsoNode(varchar atopology, bigint aface, geometry apoint);

Description

atopology 지형의 aface ID(faceid)를 가진 기존 표면에 포인트 위치가 apoint 인 고립된 노드를 추가하고 새 노드의 ID(nodeid)를 반환합니다.

포인트 도형과 지형의 공간 참조 시스템(SRID)이 다를 경우, apoint 가 포인트 도형이 아닐 경우, 포인트가 NULL일 경우, 또는 포인트가 기존 경계선과 (또는 외곽선일지라도) 교차하는 경우 예외가 발생합니다. 해당 포인트의 위치에 이미 노드가 존재할 경우에도 예외가 발생합니다.

aface 가 NULL이 아닌데 apoint 가 표면 내부에 있지 않을 경우, 예외가 발생합니다.

Availability: 1.1

This method implements the SQL/MM specification. SQL-MM: Topo-Net Routines: X+1.3.1

예시


제목

ST_AddIsoEdge — 지형에 두 개의 고립된 기존 노드 anodeanothernode 를 연결하는 alinestring 도형이 정의하는 고립된 경계선을 추가하고 새 경계선의 ID를 반환합니다.

요약

bigint ST_AddIsoEdge(varchar atopology, bigint anode, bigint anothernode, geometry alinestring);

Description

지형에 두 개의 고립된 기존 노드 anodeanothernode 를 연결하는 alinestring 도형이 정의하는 고립된 경계선을 추가하고 새 경계선의 ID(edgeid)를 반환합니다.

alinestring 도형과 지형의 공간 참조 시스템(SRID)이 다를 경우, 입력 인수 가운데 하나라도 NULL일 경우, 하나 이상의 표면이 노드를 담고 있을 경우, 또는 노드가 기존 경계선의 시작 또는 종단 노드일 경우, 예외가 발생합니다.

alinestringanodeanothernode 가 속해 있는 표면 내부에 없을 경우, 예외가 발생합니다.

anodeanothernodealinestring 의 시작점 및 종단점이 아닐 경우 예외가 발생합니다.

Availability: 1.1

This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.4

예시


제목

ST_AddEdgeNewFaces — 새 경계선을 추가하고, 그 과정에서 경계선이 표면을 분할할 경우, 원본 표면을 삭제하고 새 표면 2개로 교체합니다.

요약

bigint ST_AddEdgeNewFaces(varchar atopology, bigint anode, bigint anothernode, geometry acurve);

Description

새 경계선을 추가하고, 그 과정에서 경계선이 표면을 분할할 경우, 원본 표면을 삭제하고 새 표면 2개로 교체합니다. 새로 추가된 경계선의 ID를 반환합니다.

모든 기존의 결합된 경계선 및 관계성을 결과에 맞춰 업데이트합니다.

어떤 인수가 NULL일 경우, 주어진 노드들이 알려지지 않은 경우(노드가 이미 지형 스키마의 node 테이블에 존재해야 합니다), acurveLINESTRING 이 아닐 경우, anodeanothernodeacurve 의 시작점 및 종단점이 아닐 경우 오류가 발생합니다.

acurve 도형과 지형의 공간 참조 시스템(SRID)이 다를 경우 예외가 발생합니다.

2.0 버전부터 사용할 수 있습니다.

This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.12

예시


제목

ST_AddEdgeModFace — 새 경계선을 추가하고, 그 과정에서 경계선이 표면을 분할할 경우, 원본 표면을 수정하고 새 표면을 추가합니다.

요약

bigint ST_AddEdgeModFace(varchar atopology, bigint anode, bigint anothernode, geometry acurve);

Description

새 경계선을 추가하고, 그 과정에서 경계선이 표면을 분할할 경우, 원본 표면을 수정하고 새 표면을 추가합니다.

[참고]

가능한 경우, 새 경계선의 왼쪽에 새 표면을 생성할 것입니다. 왼쪽의 표면이 (무한한) 세계 표면(universe face)이어야 할 경우 이는 불가능할 것입니다.

새로 추가된 경계선의 ID를 반환합니다.

모든 기존의 결합된 경계선 및 관계성을 결과에 맞춰 업데이트합니다.

어떤 인수가 NULL일 경우, 주어진 노드들이 알려지지 않은 경우(노드가 이미 지형 스키마의 node 테이블에 존재해야 합니다), acurveLINESTRING 이 아닐 경우, anodeanothernodeacurve 의 시작점 및 종단점이 아닐 경우 오류가 발생합니다.

acurve 도형과 지형의 공간 참조 시스템(SRID)이 다를 경우 예외가 발생합니다.

2.0 버전부터 사용할 수 있습니다.

This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.13

예시


제목

ST_RemEdgeNewFace — 경계선을 제거하고, 제거한 경계선이 두 표면을 분할하고 있을 경우, 원본 표면들을 삭제하고 새 표면 하나로 대체합니다.

요약

bigint ST_RemEdgeNewFace(varchar atopology, bigint anedge);

Description

경계선을 제거하고, 제거한 경계선이 두 표면을 분할하고 있을 경우, 원본 표면들을 삭제하고 새 표면 하나로 대체합니다.

새로 생성된 표면의 ID를 반환하거나, 또는 새 표면이 생성되지 않은 경우 NULL을 반환합니다. 제거한 경계선이 세계 표면에 매달려 있거나, 고립돼 있거나, 또는 (세계 표면이 다른 쪽의 표면을 침범하게 할 수 있게) 갇혀 있을 경우 새 표면을 생성할 수 없습니다.

모든 기존의 결합된 경계선 및 관계성을 결과에 맞춰 업데이트합니다.

Refuses to remove an edge participating in the definition of an existing TopoGeometry. Refuses to heal two faces if any TopoGeometry is defined by only one of them (and not the other).

어떤 인수가 NULL일 경우, 주어진 경계선이 알려지지 않은 경우(경계선이 이미 지형 스키마의 edge 테이블에 존재해야 합니다), 지형 명칭이 유효하지 않은 경우 오류가 발생합니다.

2.0 버전부터 사용할 수 있습니다.

This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.14

예시


제목

ST_RemEdgeModFace — Removes an edge, and if the edge separates two faces deletes one face and modifies the other face to cover the space of both.

요약

bigint ST_RemEdgeModFace(varchar atopology, bigint anedge);

Description

Removes an edge, and if the removed edge separates two faces deletes one face and modifies the other face to cover the space of both. Preferentially keeps the face on the right, to be consistent with ST_AddEdgeModFace. Returns the id of the face which is preserved.

모든 기존의 결합된 경계선 및 관계성을 결과에 맞춰 업데이트합니다.

Refuses to remove an edge participating in the definition of an existing TopoGeometry. Refuses to heal two faces if any TopoGeometry is defined by only one of them (and not the other).

어떤 인수가 NULL일 경우, 주어진 경계선이 알려지지 않은 경우(경계선이 이미 지형 스키마의 edge 테이블에 존재해야 합니다), 지형 명칭이 유효하지 않은 경우 오류가 발생합니다.

2.0 버전부터 사용할 수 있습니다.

This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.15

예시


제목

ST_ChangeEdgeGeom — 지형 구조를 건드리는 일 없이 경계선의 형상을 변경합니다.

요약

text ST_ChangeEdgeGeom(varchar atopology, bigint anedge, geometry acurve);

Description

지형 구조를 건드리는 일 없이 경계선의 형상을 변경합니다.

If any arguments are null, the given edge does not exist in the edge table of the topology schema, the acurve is not a LINESTRING, or the modification would change the underlying topology then an error is thrown.

acurve 도형과 지형의 공간 참조 시스템(SRID)이 다를 경우 예외가 발생합니다.

acurve 가 단순 도형이 아닐 경우, 오류가 발생합니다.

예전 위치에서 새 위치로 경계선을 이동시킬 때 장애물에 부딪히는 경우 오류가 발생합니다.

1.1.0 버전부터 사용할 수 있습니다.

개선 사항: 2.0.0버전부터 지형의 일관성을 강제합니다.

This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details X.3.6

예시

Code
SELECT topology.ST_ChangeEdgeGeom(
    'ma_topo',
    1,
        ST_GeomFromText(
            'LINESTRING(227591.9 893900.4,227622.6 893844.3,227641.6 893816.6,227704.5 893778.5)',
            26986)
);
래스터 출력
Edge 1 changed

제목

ST_ModEdgeSplit — 기존 경계선을 따라 새 노드를 추가한 다음, 원본 경계선을 수정하고 새 경계선을 추가해서 경계선을 분할합니다.

요약

bigint ST_ModEdgeSplit(varchar atopology, bigint anedge, geometry apoint);

Description

기존 경계선을 따라 새 노드를 추가한 다음, 원본 경계선을 수정하고 새 경계선을 추가해서 경계선을 분할합니다. 기존의 모든 결합된 경계선들 및 관계성을 새로이 분할된 경계선들에 맞춰 업데이트합니다. 새로 추가된 노드의 식별자를 반환합니다.

Availability: 1.1

변경 사항: 2.0 미만 버전에서, 이 함수는 ST_ModEdgesSplit이라는 잘못된 명칭이었습니다.

This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.9

예시

Add an edge to split.

Code
SELECT topology.AddEdge('ma_topo', ST_GeomFromText('LINESTRING(227592 893910,227600 893910)', 26986)) AS edgeid;
래스터 출력
3

Split the edge with a new node.

Code
SELECT topology.ST_ModEdgeSplit('ma_topo', 3, ST_SetSRID(ST_Point(227594, 893910), 26986)) AS node_id;
래스터 출력
7

제목

ST_ModEdgeHeal — Heals two edges by deleting the node connecting them, modifying the first edge and deleting the second edge. Returns the id of the deleted node.

요약

bigint ST_ModEdgeHeal(varchar atopology, bigint anedge, bigint anotheredge);

Description

Heals two edges by deleting the node connecting them, modifying the first edge and deleting the second edge. Returns the id of the deleted node. Updates all existing joined edges and relationships accordingly.

2.0 버전부터 사용할 수 있습니다.

This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.9


제목

ST_NewEdgeHeal — Heals two edges by deleting the node connecting them, deleting both edges, and replacing them with an edge whose direction is the same as the first edge provided.

요약

bigint ST_NewEdgeHeal(varchar atopology, bigint anedge, bigint anotheredge);

Description

Heals two edges by deleting the node connecting them, deleting both edges, and replacing them with an edge whose direction is the same as the first edge provided. Returns the id of the new edge replacing the healed ones. Updates all existing joined edges and relationships accordingly.

2.0 버전부터 사용할 수 있습니다.

This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X.3.9


제목

ST_MoveIsoNode — Moves an isolated node in a topology from one point to another. If new apoint geometry exists as a node an error is thrown. Returns description of move.

요약

text ST_MoveIsoNode(varchar atopology, bigint anode, geometry apoint);

Description

지형 안에 있는 고립된 노드를 어떤 위치에서 다른 위치로 이동합니다. 새 apoint 도형의 위치에 노드가 존재할 경우 오류가 발생합니다.

If any arguments are null, the apoint is not a point, the existing node is not isolated (is a start or end point of an existing edge), new node location intersects an existing edge (even at the end points) or the new location is in a different face (since 3.2.0) then an exception is thrown.

포인트 도형과 지형의 공간 참조 시스템(SRID)이 다를 경우 예외가 발생합니다.

2.0.0 버전부터 사용할 수 있습니다.

Enhanced: 3.2.0 ensures the nod cannot be moved in a different face

This method implements the SQL/MM specification. SQL-MM: Topo-Net Routines: X.3.2

예시

Add an isolated node with no face.

Code
SELECT topology.ST_AddIsoNode('ma_topo', NULL, ST_GeomFromText('POINT(227579 893916)', 26986)) AS nodeid;
래스터 출력
7

Move the new node.

Code
SELECT topology.ST_MoveIsoNode('ma_topo', 7, ST_GeomFromText('POINT(227579.5 893916.5)', 26986)) AS descrip;
래스터 출력
Isolated Node 7 moved to location 227579.5,893916.5

제목

ST_NewEdgesSplit — 기존 경계선을 따라 새 노드를 추가한 다음, 원본 경계선을 삭제하고 새 경계선 2개로 교체해서 경계선을 분할합니다. 새 경계선들을 결합하는 새로 생성된 노드의 ID를 반환합니다.

요약

bigint ST_NewEdgesSplit(varchar atopology, bigint anedge, geometry apoint);

Description

기존 경계선을 따라 apoint 포인트 위치에 새 노드를 생성한 다음, 다음, 원본 경계선을 삭제하고 새 경계선 2개로 교체해서 경계선 ID anedge 인 경계선을 분할합니다. 새 경계선들을 결합하는 새로 생성된 노드의 ID를 반환합니다. 기존의 모든 결합된 경계선들 및 관계성을 분할된 경계선에 맞춰 업데이트합니다.

포인트 도형과 지형의 공간 참조 시스템(SRID)이 다를 경우, apoint 가 포인트 도형이 아닐 경우, 포인트가 NULL일 경우, 해당 포인트의 위치에 이미 노드가 존재할 경우, 경계선이 기존 경계선과 일치하지 않을 경우, 또는 포인트가 경계선 안에 있지 않을 경우 예외가 발생합니다.

Availability: 1.1

This method implements the SQL/MM specification. SQL-MM: Topo-Net Routines: X.3.8

예시

Add an edge to split.

Code
SELECT topology.AddEdge('ma_topo', ST_GeomFromText('LINESTRING(227575 893917,227592 893900)', 26986)) AS edgeid;
래스터 출력
2

Split the new edge.

Code
SELECT topology.ST_NewEdgesSplit('ma_topo', 2, ST_GeomFromText('POINT(227578.5 893913.5)', 26986)) AS newnodeid;
래스터 출력
6

제목

ST_RemoveIsoNode — 고립된 노드를 제거하고 작업 내용을 설명하는 메시지를 반환합니다. 노드가 고립되지 않은 (경계선의 시작점이나 종단점인) 경우, 예외가 발생합니다.

요약

text ST_RemoveIsoNode(varchar atopology, bigint anode);

Description

고립된 노드를 제거하고 작업 내용을 설명하는 메시지를 반환합니다. 노드가 고립되지 않은 (경계선의 시작점이나 종단점인) 경우, 예외가 발생합니다.

Availability: 1.1

This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X+1.3.3

예시

Remove an isolated node with no face.

Code
SELECT topology.ST_RemoveIsoNode('ma_topo', 7) AS result;
래스터 출력
Isolated node 7 removed

제목

ST_RemoveIsoEdge — Removes an isolated edge and returns description of action. If the edge is not isolated, then an exception is thrown.

요약

text ST_RemoveIsoEdge(varchar atopology, bigint anedge);

Description

Removes an isolated edge and returns description of action. If the edge is not isolated, then an exception is thrown.

Availability: 1.1

This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details: X+1.3.3

예시

Remove an isolated edge with no face.

Code
SELECT topology.ST_RemoveIsoEdge('ma_topo', 7) AS result;
래스터 출력
Isolated edge 7 removed

9.8. 지형 접근자

  • GetEdgeByPoint — Finds the edge-id of an edge that intersects a given point.
  • GetFaceByPoint — Finds face intersecting a given point.
  • GetFaceContainingPoint — Finds the face containing a point.
  • GetNodeByPoint — Finds the node-id of a node at a point location.
  • GetTopologyID — 지형의 명칭을 입력받아 topology.topology 테이블에 있는 지형의 ID를 반환합니다.
  • GetTopologySRID — 지형의 명칭을 입력받아 topology.topology 테이블에 있는 지형의 SRID를 반환합니다.
  • GetTopologyName — 지형의 ID를 입력받아 지형(스키마)의 명칭을 반환합니다.
  • ST_GetFaceEdgesaface 의 경계를 이루는 정렬된 경계선들의 집합을 반환합니다.
  • ST_GetFaceGeometry — 입력 지형으로부터 설정된 표면 ID를 가진 폴리곤을 반환합니다.
  • GetRingEdges — 입력 경계선 쪽을 따라 탐색한 부호가 있는 경계선 식별자들의 정렬된 집합을 반환합니다.
  • GetNodeEdges — 입력 노드를 따르는 경계선들의 정렬된 집합을 반환합니다.
  • FindVertexSegmentPairsBelowDistance — Find pairs of topology vertex/segment that are closer than tolerated distance

제목

GetEdgeByPoint — Finds the edge-id of an edge that intersects a given point.

요약

bigint GetEdgeByPoint(varchar atopology, geometry apoint, float8 tol1);

Description

Retrieves the id of an edge that intersects a Point.

이 함수는 지형, 포인트, 그리고 허용 오차를 입력받아 정수(edgeid)를 반환합니다. tolerance = 0일 경우 포인트와 경계선이 교차해야 합니다.

If apoint doesn't intersect an edge, returns 0 (zero).

If use tolerance > 0 and there is more than one edge near the point then an exception is thrown.

[참고]

이 함수는 tolerance = 0일 경우 ST_Intersects를, 그렇지 않을 경우 ST_DWithin을 이용합니다.

GEOS 모듈로 실행

2.0.0 버전부터 사용할 수 있습니다.

예시

다음 예시들은 AddEdge 에서 생성한 경계선들을 사용합니다.

Code
SELECT topology.GetEdgeByPoint('ma_topo', geom, 1) As with1mtol, topology.GetEdgeByPoint('ma_topo', geom, 0) As withnotol
FROM ST_GeomFromEWKT('SRID=26986;POINT(227622.6 893843)') As geom;
래스터 출력
with1mtol | withnotol
-----------+-----------
         2 |         0

This query errors because two or more edges are found.

Code
SELECT topology.GetEdgeByPoint('ma_topo', geom, 1) As nearnode
FROM ST_GeomFromEWKT('SRID=26986;POINT(227591.9 893900.4)') As geom;
래스터 출력
ERROR:  Two or more edges found

제목

GetFaceByPoint — Finds face intersecting a given point.

요약

bigint GetFaceByPoint(varchar atopology, geometry apoint, float8 tol1);

Description

Finds a face referenced by a Point, with given tolerance.

The function will effectively look for a face intersecting a circle having the point as center and the tolerance as radius.

If no face intersects the given query location, 0 is returned (universal face).

If more than one face intersect the query location an exception is thrown.

2.0.0 버전부터 사용할 수 있습니다.

Enhanced: 3.2.0 more efficient implementation and clearer contract, stops working with invalid topologies.

예시

Code
SELECT topology.GetFaceByPoint('ma_topo', geom, 10) As with1mtol, topology.GetFaceByPoint('ma_topo', geom, 0) As withnotol
FROM ST_GeomFromEWKT('POINT(234604.6 899382.0)') As geom;
래스터 출력
with1mtol | withnotol
-----------+-----------
         1 |         0

This query errors because two or more faces are found.

Code
SELECT topology.GetFaceByPoint('ma_topo', geom, 1) As nearnode
FROM ST_GeomFromEWKT('POINT(227591.9 893900.4)') As geom;
래스터 출력
ERROR:  Two or more faces found

제목

GetFaceContainingPoint — Finds the face containing a point.

요약

bigint GetFaceContainingPoint(text atopology, geometry apoint);

Description

Returns the id of the face containing a point.

An exception is thrown if the point falls on a face boundary.

[참고]

The function relies on a valid topology, using edge linking and face labeling.

Availability: 3.2.0


제목

GetNodeByPoint — Finds the node-id of a node at a point location.

요약

bigint GetNodeByPoint(varchar atopology, geometry apoint, float8 tol1);

Description

Retrieves the id of a node at a point location.

The function returns an integer (id-node) given a topology, a POINT and a tolerance. If tolerance = 0 means exact intersection, otherwise retrieves the node from an interval.

If apoint doesn't intersect a node, returns 0 (zero).

If use tolerance > 0 and there is more than one node near the point then an exception is thrown.

[참고]

이 함수는 tolerance = 0일 경우 ST_Intersects를, 그렇지 않을 경우 ST_DWithin을 이용합니다.

GEOS 모듈로 실행

2.0.0 버전부터 사용할 수 있습니다.

예시

다음 예시들은 AddEdge 에서 생성한 경계선들을 사용합니다.

Code
SELECT topology.GetNodeByPoint('ma_topo', geom, 1) As nearnode
FROM ST_GeomFromEWKT('SRID=26986;POINT(227591.9 893900.4)') As geom;
래스터 출력
2

This query errors because the tolerance matches two or more nodes.

Code
SELECT topology.GetNodeByPoint('ma_topo', geom, 1000) As too_much_tolerance
FROM ST_GeomFromEWKT('SRID=26986;POINT(227591.9 893900.4)') As geom;
래스터 출력
ERROR:  Two or more nodes found

제목

GetTopologyID — 지형의 명칭을 입력받아 topology.topology 테이블에 있는 지형의 ID를 반환합니다.

요약

integer GetTopologyID(varchar toponame);

Description

지형의 명칭을 입력받아 topology.topology 테이블에 있는 지형의 ID를 반환합니다.

Availability: 1.1

예시

Code
SELECT topology.GetTopologyID('ma_topo') AS topo_id;
래스터 출력
1

제목

GetTopologySRID — 지형의 명칭을 입력받아 topology.topology 테이블에 있는 지형의 SRID를 반환합니다.

요약

integer GetTopologyID(varchar toponame);

Description

지형의 명칭을 입력받아 topology.topology 테이블에 있는 지형의 공간 참조 식별자를 반환합니다.

2.0.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT topology.GetTopologySRID('ma_topo') AS srid;
래스터 출력
4326

제목

GetTopologyName — 지형의 ID를 입력받아 지형(스키마)의 명칭을 반환합니다.

요약

varchar GetTopologyName(integer topology_id);

Description

지형의 지형 ID를 입력받아 topology.topology 테이블에서 지형의 지형명(스키마)을 반환합니다.

Availability: 1.1

예시

Code
SELECT topology.GetTopologyName(1) AS topo_name;
래스터 출력
ma_topo

제목

ST_GetFaceEdges — aface 의 경계를 이루는 정렬된 경계선들의 집합을 반환합니다.

요약

getfaceedges_returntype ST_GetFaceEdges(varchar atopology, bigint aface);

Description

aface 의 경계를 이루는 정렬된 경계선들의 집합을 반환합니다. 각 출력물은 순차(sequence) 및 경계선 ID(edgeid)로 이루어집니다. 순차 번호는 1부터 시작합니다.

각 고리의 경계선을 가장 작은 식별자를 가진 경계선부터 열거합니다. 경계선의 순서는 왼손 법칙을 따릅니다(각 경계선의 왼쪽 방향으로 표면의 경계선을 구성하게 됩니다).

2.0 버전부터 사용할 수 있습니다.

This method implements the SQL/MM specification. SQL-MM 3 Topo-Geo and Topo-Net 3: Routine Details: X.3.5

예시

This query returns the edges that bound face 1.

Code
SELECT (topology.ST_GetFaceEdges('tt', 1)).*;
래스터 출력
sequence | edge
----------+------
        1 |   -4
        2 |    5
        3 |    7
        4 |   -6
        5 |    1
        6 |    2
        7 |    3

This query returns the sequence, edge identifier, and geometry of the edges that bound face 1. Use ST_GetFaceGeometry if only the geometry and sequence are needed.

Code
SELECT t.seq, t.edge, geom
FROM topology.ST_GetFaceEdges('tt', 1) As t(seq, edge)
    INNER JOIN tt.edge AS e ON abs(t.edge) = e.edge_id;

제목

ST_GetFaceGeometry — 입력 지형으로부터 설정된 표면 ID를 가진 폴리곤을 반환합니다.

요약

geometry ST_GetFaceGeometry(varchar atopology, bigint aface);

Description

입력 지형으로부터 설정된 표면 ID를 가진 폴리곤을 반환합니다. 표면을 구성하는 경계선들로부터 폴리곤을 빌드합니다.

Availability: 1.1

This method implements the SQL/MM specification. SQL-MM 3 Topo-Geo and Topo-Net 3: Routine Details: X.3.16

예시

This query returns the WKT of the polygon added with AddFace.

Code
SELECT topology.ST_GetFaceGeometry('ma_topo', 1) AS facegeomwkt;
래스터 출력
POLYGON((234776.9 899563.7,234896.5 899456.7,234914 899436.4,234946.6 899356.9,
234872.5 899328.7,234891 899285.4,234992.5 899145,234890.6 899069,
234755.2 899255.4,234612.7 899379.4,234776.9 899563.7))
Figure
Geometry figure for visual-st-getfacegeometry-01

참고

AddFace


제목

GetRingEdges — 입력 경계선 쪽을 따라 탐색한 부호가 있는 경계선 식별자들의 정렬된 집합을 반환합니다.

요약

getfaceedges_returntype GetRingEdges(varchar atopology, bigint aring, integer max_edges=null);

Description

입력 경계선 쪽을 따라 탐색한 부호가 있는 경계선 식별자들의 정렬된 집합을 반환합니다. 각 출력물은 순차(sequence) 및 부호가 있는 경계선 ID(edgeid)로 이루어집니다. 순차 번호는 1부터 시작합니다.

양의 부호를 가진 경계선 ID를 넘겨줄 경우, 해당 경계선의 왼쪽에서 탐색을 시작해서 경계선의 방향으로 진행합니다. 음의 부호를 가진 경계선 ID를 넘겨줄 경우, 해당 경계선의 오른쪽에서 탐색을 시작해서 경계선 방향의 반대로 진행합니다.

max_edges 가 NULL이 아닐 경우 함수가 해당 개수 이상의 레코드를 반환하지 않습니다. 유효하지 않을 수도 있는 지형을 처리할 때 이 파라미터를 안전 장치로 쓸 수 있다는 의미입니다.

[참고]

이 함수는 메타데이터를 링크하는 경계선 고리를 이용합니다.

2.0.0 버전부터 사용할 수 있습니다.


제목

GetNodeEdges — 입력 노드를 따르는 경계선들의 정렬된 집합을 반환합니다.

요약

getfaceedges_returntype GetNodeEdges(varchar atopology, bigint anode);

Description

입력 노드를 따르는 경계선들의 정렬된 집합을 반환합니다. 각 출력물은 순차 및 부호를 가진 경계선 ID로 구성됩니다. 순차 번호는 1부터 시작합니다. 양의 부호를 가진 경계선은 입력 노드로부터 시작합니다. 음의 부호를 가진 경계선은 입력 노드로 끝납니다. 페쇄형 경계선은 두 번 (두 부호를 가지고) 표출될 것입니다. 북쪽부터 시작하는 시계 방향으로 정렬됩니다.

[참고]

이 함수는 정렬 순서를 메타데이터에서 추출하기보다 계산하기 때문에 경계선 고리 링크를 빌드하는 데 유용합니다.

2.0 버전부터 사용할 수 있습니다.


제목

FindVertexSegmentPairsBelowDistance — Find pairs of topology vertex/segment that are closer than tolerated distance

요약

setof record FindVertexSegmentPairsBelowDistance(varchar atopology, float8 tolerance);

Description

Returns a relation in which each tuple is a pair of vertex/segment where the vertex is NOT an endpoint of the segment but the distance between them is below the given tolerance.

Availability: 3.7

9.9. 지형 공간 처리

초록

이 단원에서 비표준적인 방법으로 지형을 공간 처리하기 위한 함수에 대해 설명합니다.

  • Polygonize — Finds and registers all faces defined by topology edges.
  • AddNode — 설정한 지형 스키마의 노드 테이블에 포인트 노드를 추가하고 새 노드의 노드 ID(nodeid)를 반환합니다. 새 포인트 위치에 이미 노드가 존재할 경우, 기존 노드 ID를 반환합니다.
  • AddEdge — 설정한 지형 스키마의 경계선 테이블에 라인스트링 경계선을 추가하고, 설정한 라인스트링 도형을 이용해서 포인트 노드 테이블에 경계선의 시작점 및 종단점을 추가한 다음 새 (또는 기존) 경계선의 경계선 ID(edgeid)를 반환합니다.
  • AddFace — 지형에 표면 원시형(face primitive)을 등록하고 그 식별자를 반환합니다.
  • ST_Simplify — 더글러스-패커(Douglas-Peucker) 알고리즘을 통해 입력 TopoGeometry 의 "단순화된" 도형 버전을 반환합니다.
  • RemoveUnusedPrimitives — Removes topology primitives which not needed to define existing TopoGeometry objects.

제목

Polygonize — Finds and registers all faces defined by topology edges.

요약

text Polygonize(varchar toponame);

Description

Registers all faces that can be built out a topology edge primitives.

입력 지형이 스스로 교차하는 경계선을 가지고 있지 않다고 가정합니다.

[참고]

이미 알려진 표면을 인식하기 때문에, 동일한 지형에 대해 Polygonize 함수를 반복해서 호출하는 편이 안전합니다.

[참고]

이 함수는 edge 테이블의 next_left_edge 및 next_right_edge 항목을 이용하지도 설정하지도 않습니다.

2.0.0 버전부터 사용할 수 있습니다.


제목

AddNode — 설정한 지형 스키마의 노드 테이블에 포인트 노드를 추가하고 새 노드의 노드 ID(nodeid)를 반환합니다. 새 포인트 위치에 이미 노드가 존재할 경우, 기존 노드 ID를 반환합니다.

요약

bigint AddNode(varchar toponame, geometry apoint, boolean allowEdgeSplitting=false, boolean computeContainingFace=false);

Description

설정한 지형 스키마의 노드 테이블에 포인트 노드를 추가합니다. AddEdge 함수를 호출할 때 경계선의 시작점 및 종단점을 자동적으로 추가하므로, 경계선의 노드를 따로 추가할 필요는 없습니다.

새 노드를 가로지르는 경계선이 있을 경우, allowEdgeSplitting 파라미터 값에 따라 예외가 발생하거나 또는 해당 경계선을 분할합니다.

computeContainingFace 가 참일 경우 새로 추가된 노드를 정확히 담고 있는 표면을 계산합니다.

[참고]

apoint 도형의 위치에 이미 노드가 존재할 경우, 새 노드를 추가하지 않고 기존 노드 ID(nodeid)를 반환합니다.

2.0.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT topology.AddNode('ma_topo', ST_GeomFromText('POINT(227641.6 893816.5)', 26986)) AS nodeid;
래스터 출력
4

제목

AddEdge — 설정한 지형 스키마의 경계선 테이블에 라인스트링 경계선을 추가하고, 설정한 라인스트링 도형을 이용해서 포인트 노드 테이블에 경계선의 시작점 및 종단점을 추가한 다음 새 (또는 기존) 경계선의 경계선 ID(edgeid)를 반환합니다.

요약

bigint AddEdge(varchar toponame, geometry aline);

Description

설정한 라인스트링 도형을 이용해서 설정한 toponame 스키마의 경계선 테이블에 경계선을, 노드 테이블에 경계선의 노드를 추가한 다음 새 (또는 기존) 레코드의 경계선 ID(edgeid)를 반환합니다. 새로 추가된 경계선은 양쪽에 "세계(universe)" 표면을 가지며 자기 자신에게 링크합니다.

[참고]

기존 라인스트링 경계선이 aline 도형을 가로지르거나, 중첩하거나, 또는 담고 있을 경우 오류가 발생하고 경계선을 추가하지 않습니다.

[참고]

aline 도형의 srid 와 지형에 대해 정의된 srid 가 동일해야만 합니다. 그렇지 않을 경우 유효하지 않은 공간 참조 시스템 오류가 발생할 것입니다.

GEOS 모듈로 실행

[주의]

AddEdge is deprecated as of 3.5.0. Use TopoGeo_AddLineString instead.

2.0.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT topology.AddEdge('ma_topo', ST_GeomFromText('LINESTRING(227575.8 893917.2,227591.9 893900.4)', 26986)) AS edgeid;
래스터 출력
1
Code
SELECT topology.AddEdge('ma_topo', ST_GeomFromText('LINESTRING(227591.9 893900.4,227622.6 893844.2,227641.6 893816.5,227704.5 893778.5)', 26986)) AS edgeid;
래스터 출력
2

This query errors because the edge intersects an existing edge away from the endpoints.

Code
SELECT topology.AddEdge('ma_topo', ST_GeomFromText('LINESTRING(227591.2 893900,227591.9 893900.4,227704.5 893778.5)', 26986)) AS edgeid;
래스터 출력
ERROR:  Edge intersects (not on endpoints) with existing edge 1

제목

AddFace — 지형에 표면 원시형(face primitive)을 등록하고 그 식별자를 반환합니다.

요약

bigint AddFace(varchar toponame, geometry apolygon, boolean force_new=false);

Description

지형에 표면 원시형(face primitive)을 등록하고 그 식별자를 반환합니다.

새로 추가된 표면의 left_face 및 right_face 항목이 정확한 값을 가지도록 그 외곽선을 형성하는 경계선들 및 표면이 담고 있는 경계선들을 업데이트합니다. 표면이 담고 있는 고립된 노드들도 containing_face 항목이 정확한 값을 가지도록 업데이트할 것입니다.

[참고]

이 함수는 edge 테이블의 next_left_edge 및 next_right_edge 항목을 이용하지도 설정하지도 않습니다.

대상 지형이 유효하다고 (자체 교차하는 경계선을 담고 있지 않다고) 가정합니다. 기존 경계선들이 폴리곤 외곽선을 완전하게 정의하고 있지 않거나, 또는 폴리곤이 기존 표면과 중첩할 경우 예외가 발생합니다.

apolygon 도형과 동일한 표면이 이미 존재할 경우, force_new 가 (기본값인) 거짓이면 기존 표면의 표면 ID를 반환하고, force_new 가 참이면 새로 등록된 표면에 새 ID를 할당할 것입니다.

[참고]

기존 표면을 새로 등록할 경우 (force_new = true) 경계선, 노드, 관계성 테이블에 있는 기존 표면에 대한 예전 참조들을 해결하기 위한 어떤 작동도 하지 않을 것입니다. 또 기존 표면 레코드의 MBR 항목도 업데이트하지 않을 것입니다. 호출자가 해결해야 할 문제입니다.

[참고]

apolygon 도형의 srid 와 지형에 대해 정의된 srid 가 동일해야만 합니다. 그렇지 않을 경우 유효하지 않은 공간 참조 시스템 오류가 발생할 것입니다.

2.0.0 버전부터 사용할 수 있습니다.

예시

First add the edges using generate_series as an iterator. This query only works for polygons with fewer than 10000 points because of the maximum value in generate_series.

Code
SELECT topology.AddEdge('ma_topo', ST_MakeLine(ST_PointN(geom,i), ST_PointN(geom, i + 1) )) As edgeid
FROM (
  SELECT ST_NPoints(geom) AS npt, geom
  FROM (
    SELECT ST_Boundary(ST_GeomFromText('POLYGON((234896.5 899456.7,234914 899436.4,234946.6 899356.9,234872.5 899328.7,
                234891 899285.4,234992.5 899145, 234890.6 899069,234755.2 899255.4,
                234612.7 899379.4,234776.9 899563.7,234896.5 899456.7))', 26986) )  As geom
  ) AS geoms
) AS facen
CROSS JOIN generate_series(1,10000) AS i
WHERE i < npt;
래스터 출력
3
4
5
6
7
8
9
10
11
12

Then add the face.

Code
SELECT topology.AddFace(
    'ma_topo',
    ST_GeomFromText(
    'POLYGON((234896.5 899456.7,234914 899436.4,234946.6 899356.9,234872.5 899328.7,
    234891 899285.4,234992.5 899145, 234890.6 899069,234755.2 899255.4,
    234612.7 899379.4,234776.9 899563.7,234896.5 899456.7))',
    26986) ) As faceid;
래스터 출력
1

제목

ST_Simplify — 더글러스-패커(Douglas-Peucker) 알고리즘을 통해 입력 TopoGeometry 의 "단순화된" 도형 버전을 반환합니다.

요약

geometry ST_Simplify(topogeometry tg, float8 tolerance);

Description

각 구성 요소의 경계선에 더글러스-패커(Douglas-Peucker) 알고리즘을 작용해서 입력 TopoGeometry 의 "단순화된" 도형 버전을 반환합니다.

[참고]

반환된 도형이 단순하지 않거나, 유효하지 않을 수도 있습니다.

단순성/유효성을 유지하는 데 구성 요소의 경계선을 분할하는 것이 도움이 될 수도 있습니다.

GEOS 모듈로 실행

2.1.0 버전부터 사용할 수 있습니다.


제목

RemoveUnusedPrimitives — Removes topology primitives which not needed to define existing TopoGeometry objects.

요약

bigint RemoveUnusedPrimitives(text topology_name, geometry bbox);

Description

Finds all primitives (nodes, edges, faces) that are not strictly needed to represent existing TopoGeometry objects and removes them, maintaining topology validity (edge linking, face labeling) and TopoGeometry space occupation.

No new primitive identifiers are created, but rather existing primitives are expanded to include merged faces (upon removing edges) or healed edges (upon removing nodes).

Availability: 3.3.0

9.10. TopoGeometry 작성자

초록

이 단원에서 새 TopoGeometry를 생성하기 위한 지형 함수에 대해 설명합니다.

  • CreateTopoGeom — 지형 요소 배열로부터 새 지형 도형 객체를 생성합니다. tg_type은 1: [멀티]포인트, 2: [멀티]라인, 3: [멀티]폴리곤, 4: 도형 집합입니다.
  • toTopoGeom — Converts a simple Geometry into a topo geometry.
  • TopoElementArray_Agg — Returns a topoelementarray for a set of element_id, type arrays (topoelements).
  • TopoElement — Converts a topogeometry to a topoelement.

제목

CreateTopoGeom — 지형 요소 배열로부터 새 지형 도형 객체를 생성합니다. tg_type은 1: [멀티]포인트, 2: [멀티]라인, 3: [멀티]폴리곤, 4: 도형 집합입니다.

요약

topogeometry CreateTopoGeom(varchar toponame, integer tg_type, integer layer_id, topoelementarray tg_objs, bigint tg_id);

topogeometry CreateTopoGeom(varchar toponame, integer tg_type, integer layer_id);

Description

Creates a topogeometry object for layer denoted by layer_id and registers it in the relations table in the toponame schema.

tg_type is an integer: 1:[multi]point (punctal), 2:[multi]line (lineal), 3:[multi]poly (areal), 4:collection. layer_id is the layer id in the topology.layer table.

노드들의 집합이 점형 레이어를 형성하고, 경계선들의 집합이 선형 레이어를 형성하고, 표면들의 집합이 면형 레이어를 형성하며, 노드, 경계선, 표면의 혼합 집합이 도형 집합을 형성할 수 있습니다.

구성 요소 배열을 생략하면 텅 빈 TopoGeometry 객체를 생성합니다.

Availability: 1.1

예시

Form from existing edges.

Create a topogeom in ri_topo schema for layer 2 (our ri_roads), of type (2) LINE, for the first edge (we loaded in ST_CreateTopoGeo).

Code
INSERT INTO ri.ri_roads(road_name, topo)
VALUES (
    'Unknown',
    topology.CreateTopoGeom(
        'ri_topo',
        2,
        2,
        '{{1,2}}'::topology.topoelementarray
    )
);

Convert an areal geometry to best guess topogeometry.

표면들의 집합으로 형성돼야 하는 도형을 가지고 있다고 해봅시다. 예를 들어 blockgroups 테이블이 있는데 각 블록 그룹의 TopoGeometry를 알고 싶습니다. 데이터가 완벽하게 정렬돼 있다면, 다음과 같이 할 수 있습니다:

Create the topogeometry column.

Code
SELECT topology.AddTopoGeometryColumn(
'topo_boston',
'boston', 'blockgroups', 'topo', 'POLYGON');

래스터 출력
1

Update the column assuming everything is perfectly aligned with the edges.

Code
UPDATE boston.blockgroups AS bg
SET topo = topology.CreateTopoGeom(
    'topo_boston',
    3,
    1,
    foo.bfaces
)
FROM (
    SELECT
        b.gid,
        topology.TopoElementArray_Agg(ARRAY[f.face_id, 3]) AS bfaces
    FROM boston.blockgroups AS b
    INNER JOIN topo_boston.face AS f
        ON b.geom && f.mbr
    WHERE ST_Covers(
        b.geom,
        topology.ST_GetFaceGeometry('topo_boston', f.face_id)
    )
    GROUP BY b.gid
) AS foo
WHERE foo.gid = bg.gid;

The world is rarely perfect, so this version allows some error. It counts a face if 50 percent of it falls within the expected block group boundary.

Code
WITH candidate_faces AS (
    SELECT
        b.gid,
        b.geom AS block_geom,
        f.face_id,
        topology.ST_GetFaceGeometry('topo_boston', f.face_id) AS face_geom
    FROM boston.blockgroups AS b
    INNER JOIN topo_boston.face AS f
        ON b.geom && f.mbr
),
block_faces AS (
    SELECT
        gid,
        topology.TopoElementArray_Agg(ARRAY[face_id, 3]) AS bfaces
    FROM candidate_faces
    WHERE ST_Covers(block_geom, face_geom)
        OR (
            ST_Intersects(block_geom, face_geom)
            AND ST_Area(ST_Intersection(block_geom, face_geom))
                
> ST_Area(face_geom) * 0.5
        )
    GROUP BY gid
)
UPDATE boston.blockgroups AS bg
SET topo = topology.CreateTopoGeom(
    'topo_boston',
    3,
    1,
    block_faces.bfaces
)
FROM block_faces
WHERE block_faces.gid = bg.gid;

To convert the topogeometry back to a denormalized geometry aligned with faces and edges, cast the topogeometry to a geometry. The resulting geometries are aligned with the TIGER street centerlines.

Code
UPDATE boston.blockgroups SET new_geom = topo::geometry;

제목

toTopoGeom — Converts a simple Geometry into a topo geometry.

요약

topogeometry toTopoGeom(geometry geom, varchar toponame, integer layer_id, float8 tolerance=-1);

topogeometry toTopoGeom(geometry geom, topogeometry topogeom, float8 tolerance=-1);

Description

단순 도형을 TopoGeometry 로 변환합니다.

기저 지형에 입력 도형을 표현해야 하는 지형 원시형을 추가할 것입니다. 이 지형 원시형이 기존 지형을 분할할 수도 있습니다. 분할된 지형들은 relation 테이블에서 출력 TopoGeometry와 관련될 것입니다.

기존 TopoGeometry 객체는 (topogeom 을 설정할 경우 제외할 수도 있습니다) 자기 형상을 유지할 것입니다.

When tolerance is given it will be used to snap the input geometry to existing primitives. The special value -1 (default) means use the topology precision as tolerance.

변종 1의 경우 입력 지형(toponame)의 입력 레이어(layer_id)에 대해 새 TopoGeometry를 생성할 것입니다.

변종 2의 경우, 기존 TopoGeometry(toponame)에 작업중 생성된 원시형을 추가할 것입니다. 기존 TopoGeometry의 최종 형상에 공간을 추가할 수도 있습니다. 새 형상이 예전 형상을 완전히 대체하도록 하려면 clearTopoGeom 을 참조하십시오.

2.0 버전부터 사용할 수 있습니다.

개선 사항: 2.1.0 버전에서 기존 TopoGeometry를 입력받는 버전을 추가했습니다.

Changed: 3.7.0 changes meaning of tolerance 0 to really mean 0 and -1 (new default) to request using the topology precision.

예시

다음은 완전히 자급자족하는 독립적인 작업 흐름(workflow)입니다.

Create the topology without allowing any tolerance.

Code
SELECT topology.CreateTopology('topo_boston_test', 2249);

Create a new table.

Code
CREATE TABLE nei_topo(gid serial primary key, nei varchar(30));

Add a topogeometry column to the new table.

Code
SELECT topology.AddTopoGeometryColumn('topo_boston_test', 'public', 'nei_topo', 'topo', 'MULTIPOLYGON') AS new_layer_id;
래스터 출력
1

Use the new layer identifier to populate the topogeometry column.

Code
INSERT INTO nei_topo(nei, topo)
SELECT nei, topology.toTopoGeom(geom, 'topo_boston_test', 1)
FROM neighborhoods
WHERE gid BETWEEN 1 and 15;

Verify what happened.

Code
SELECT * FROM
    topology.TopologySummary('topo_boston_test');
래스터 출력
Topology topo_boston_test (5), SRID 2249, precision 0
61 nodes, 87 edges, 35 faces, 15 topogeoms in 1 layers
Layer 1, type Polygonal (3), 15 topogeoms
 Deploy: public.nei_topo.topo

Shrink all TopoGeometry polygons by 10 meters.

Code
UPDATE nei_topo SET topo = toTopoGeom(ST_Buffer(topo, -10), clearTopoGeom(topo), 0);
        

Find faces that are left without any TopoGeometry reference after the shrink operation.

Code
SELECT ST_GetFaceGeometry('topo_boston_test', f.face_id)
  FROM topo_boston_test.face f
  WHERE f.face_id 
> 0
  AND NOT EXISTS (
    SELECT * FROM topo_boston_test.relation
    WHERE layer_id = 1 AND element_id = f.face_id
  );
        

제목

TopoElementArray_Agg — Returns a topoelementarray for a set of element_id, type arrays (topoelements).

요약

topoelementarray TopoElementArray_Agg(topoelement set tefield);

Description

TopoElement 집합으로부터 TopoElementArray 를 생성하는 데 쓰입니다.

2.0.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT topology.TopoElementArray_Agg(ARRAY[e, t] ORDER BY e, t) As tea
FROM generate_series(1, 3) As e CROSS JOIN generate_series(1, 4) As t;
래스터 출력
{{1,1},{1,2},{1,3},{1,4},{2,1},{2,2},{2,3},{2,4},{3,1},{3,2},{3,3},{3,4}}

제목

TopoElement — Converts a topogeometry to a topoelement.

요약

topoelement TopoElement(topogeometry topo);

Description

Converts a TopoGeometry to a TopoElement.

Availability: 3.4.0

예시

다음은 완전히 자급자족하는 독립적인 작업 흐름(workflow)입니다.

Return the TopoElement representation of each topogeometry.

Code
SELECT TopoElement(topo)
FROM neighborhoods;

Use a cast to aggregate topogeometries into a TopoElementArray.

Code
SELECT topology.TopoElementArray_Agg(topo::topoelement)
FROM neighborhoods
GROUP BY city;

9.11. TopoGeometry 편집자

초록

이 단원에서 기존 지형을 편집하기 위한 지형 함수에 대해 설명합니다.

제목

clearTopoGeom — Clears the content of a topo geometry.

요약

topogeometry clearTopoGeom(topogeometry topogeom);

Description

TopoGeometry 의 내용을 지워서 텅 빈 TopoGeometry 로 바꿉니다. toTopoGeom 함수와 결합해서 기존 객체 및 더 높은 계층 레벨에 있는 모든 의존적인 객체의 형상을 교체하는 데 가장 유용합니다.

2.1 버전부터 사용할 수 있습니다.

예시

Shrink all TopoGeometry polygons by 10 meters.

Code
UPDATE nei_topo SET topo = toTopoGeom(ST_Buffer(topo, -10), clearTopoGeom(topo), 0);

참고

toTopoGeom


제목

TopoGeom_addElement — Adds an element to the definition of a TopoGeometry.

요약

topogeometry TopoGeom_addElement(topogeometry tg, topoelement el);

Description

TopoGeometry 객체의 정의에 TopoElement 를 추가합니다. 해당 요소가 정의에 이미 존재하더라도 오류가 발생하지 않습니다.

2.3 버전부터 사용할 수 있습니다.

예시

Add edge 5 to TopoGeometry tg.

Code
UPDATE mylayer SET tg = TopoGeom_addElement(tg, '{5,2}');

제목

TopoGeom_remElement — Removes an element from the definition of a TopoGeometry.

요약

topogeometry TopoGeom_remElement(topogeometry tg, topoelement el);

Description

TopoGeometry 객체의 정의에서 TopoElement 를 제거합니다.

2.3 버전부터 사용할 수 있습니다.

예시

Remove face 43 from TopoGeometry tg.

Code
UPDATE mylayer SET tg = TopoGeom_remElement(tg, '{43,3}');

제목

TopoGeom_addTopoGeom — Adds element of a TopoGeometry to the definition of another TopoGeometry.

요약

topogeometry TopoGeom_addTopoGeom(topogeometry tgt, topogeometry src);

Description

Adds the elements of a TopoGeometry to the definition of another TopoGeometry, possibly changing its cached type (type attribute) to a collection, if needed to hold all elements in the source object.

The two TopoGeometry objects need be defined against the *same* topology and, if hierarchically defined, need be composed by elements of the same child layer.

Availability: 3.2

예시

Set an overall TopoGeometry value to be composed of all elements from specific TopoGeometry values.

Code
UPDATE mylayer SET tg_overall = TopoGeom_addTopoGeom(
    TopoGeom_addTopoGeom(
        clearTopoGeom(tg_overall),
        tg_specific1
    ),
    tg_specific2
);
                

제목

toTopoGeom — Adds a geometry shape to an existing topo geometry.

Description

Refer to toTopoGeom.

9.12. TopoGeometry 접근자

  • GetTopoGeomElementArray — Returns a topoelementarray (an array of topoelements) containing the topological elements and type of the given TopoGeometry (primitive elements).
  • GetTopoGeomElements — Returns a set of topoelement objects containing the topological element_id,element_type of the given TopoGeometry (primitive elements).
  • ST_SRID — Returns the spatial reference identifier for a topogeometry.

제목

GetTopoGeomElementArray — Returns a topoelementarray (an array of topoelements) containing the topological elements and type of the given TopoGeometry (primitive elements).

요약

topoelementarray GetTopoGeomElementArray(varchar toponame, integer layer_id, bigint tg_id);

topoelementarray GetTopoGeomElementArray(topogeometry tg);

Description

지형의 요소 및 입력 TopoGeometry 의 유형(원시형 요소)를 담고 있는 TopoElementArray 를 반환합니다. 이 함수는 요소들을 데이터셋이 아니라 배열로 반환한다는 점만 제외하면 GetTopoGeomElements 함수와 비슷합니다.

tg_id는 topology.layer 테이블에 있는 layer_id 가 지정하는 레이어 안의 지형이 가지고 있는 TopoGeometry 객체의 TopoGeometry ID입니다.

Availability: 1.1

예시


제목

GetTopoGeomElements — Returns a set of topoelement objects containing the topological element_id,element_type of the given TopoGeometry (primitive elements).

요약

setof topoelement GetTopoGeomElements(varchar toponame, integer layer_id, bigint tg_id);

setof topoelement GetTopoGeomElements(topogeometry tg);

Description

Returns a set of element_id,element_type (topoelements) corresponding to primitive topology elements TopoElement (1: nodes, 2: edges, 3: faces) that a given topogeometry object in toponame schema is composed of.

tg_id는 topology.layer 테이블에 있는 layer_id 가 지정하는 레이어 안의 지형이 가지고 있는 TopoGeometry 객체의 TopoGeometry ID입니다.

2.0.0 버전부터 사용할 수 있습니다.

예시


제목

ST_SRID — Returns the spatial reference identifier for a topogeometry.

요약

integer ST_SRID(topogeometry tg);

Description

Returns the spatial reference identifier of the topology containing the TopoGeometry.

The identifier is recorded for the topology when it is created and refers to an entry in 4.5절. “SPATIAL_REF_SYS 테이블과 공간 참조 시스템”.

Availability: 3.2.0

예시

Return the SRID of a TopoGeometry stored in the ri_topo topology.

Code
SELECT topology.ST_SRID(topo) AS srid
FROM ri.roads
WHERE road_name = 'Unknown';
래스터 출력
srid
------
 3438

9.13. TopoGeometry 출력물

  • AsGML — TopoGeometry의 GML 표현식을 반환합니다.
  • AsTopoJSON — TopoGeometry의 TopoJSON 표현식을 반환합니다.

제목

AsGML — TopoGeometry의 GML 표현식을 반환합니다.

요약

text AsGML(topogeometry tg);

text AsGML(topogeometry tg, text nsprefix_in);

text AsGML(topogeometry tg, regclass visitedTable);

text AsGML(topogeometry tg, regclass visitedTable, text nsprefix);

text AsGML(topogeometry tg, text nsprefix_in, integer precision, integer options);

text AsGML(topogeometry tg, text nsprefix_in, integer precision, integer options, regclass visitedTable);

text AsGML(topogeometry tg, text nsprefix_in, integer precision, integer options, regclass visitedTable, text idprefix);

text AsGML(topogeometry tg, text nsprefix_in, integer precision, integer options, regclass visitedTable, text idprefix, int gmlversion);

Description

TopoGeometry의 GML 표현식을 GML3 버전 서식으로 반환합니다. nsprefix_in 을 따로 설정하지 않을 경우 gml 접두사를 이용합니다. nsprefix에 대해 텅 빈 문자열을 넘겨줄 경우 무자격(non-qualified) 네임스페이스를 반환합니다. 정확도(기본값 15) 및 옵션(기본값 1) 파라미터를 설정한 경우, 손대는 일 없이 ST_AsGML 함수에 대한 기저 호출에 그대로 넘겨줍니다.

visitedTable 파라미터는 접근한 노드 및 경계선 요소를 추적하는 데 쓰이기 때문에, 설정할 경우, 정의를 복제하는 게 아니라 교차 참조(xlink:xref)를 이용합니다. 정수형 항목 'element_type' 및 'element_id' (적어도) 2개가 테이블에 있어야 합니다. 함수 호출자는 입력 테이블에 대해 읽기 및 쓰기 권한을 가지고 있어야만 합니다. 최상의 성능을 내려면, element_typeelement_id 에, 이 순서대로, 인덱스를 정의해야 합니다. 항목들에 유일한 제약조건을 추가하면 이 인덱스를 자동적으로 생성할 것입니다. 다음은 그 예시입니다:

Code
CREATE TABLE visited (
  element_type integer, element_id integer,
  unique(element_type, element_id)
);

idprefix 파라미터를 설정할 경우, 노드 및 경계선 태그 식별자에 접두사를 붙일 것입니다.

gmlver 파라미터를 설정할 경우, 기저 ST_AsGML 함수에 해당 파라미터를 넘겨줄 것입니다. 기본값은 3입니다.

2.0.0 버전부터 사용할 수 있습니다.

예시

다음 예시는 CreateTopoGeom 에서 생성한 지형 도형을 사용합니다.

Code
SELECT topology.AsGML(topo) As rdgml
  FROM ri.roads
  WHERE road_name = 'Unknown';
래스터 출력
<gml:TopoCurve>
    <gml:directedEdge>
        <gml:Edge gml:id="E1">
            <gml:directedNode orientation="-">
                <gml:Node gml:id="N1"/>
            </gml:directedNode>
            <gml:directedNode
></gml:directedNode>
            <gml:curveProperty>
                <gml:Curve srsName="urn:ogc:def:crs:EPSG::3438">
                    <gml:segments>
                        <gml:LineStringSegment>
                            <gml:posList srsDimension="2"
>384744 236928 384750 236923 384769 236911 384799 236895 384811 236890
                            384833 236884 384844 236882 384866 236881 384879 236883 384954 236898 385087 236932 385117 236938
                            385167 236938 385203 236941 385224 236946 385233 236950 385241 236956 385254 236971
                            385260 236979 385268 236999 385273 237018 385273 237037 385271 237047 385267 237057 385225 237125
                            385210 237144 385192 237161 385167 237192 385162 237202 385159 237214 385159 237227 385162 237241
                            385166 237256 385196 237324 385209 237345 385234 237375 385237 237383 385238 237399 385236 237407
                            385227 237419 385213 237430 385193 237439 385174 237451 385170 237455 385169 237460 385171 237475
                            385181 237503 385190 237521 385200 237533 385206 237538 385213 237541 385221 237542 385235 237540 385242 237541
                            385249 237544 385260 237555 385270 237570 385289 237584 385292 237589 385291 237596 385284 237630</gml:posList>
                        </gml:LineStringSegment>
                    </gml:segments>
                </gml:Curve>
            </gml:curveProperty>
        </gml:Edge>
    </gml:directedEdge>
</gml:TopoCurve>

이전 예시와 동일하지만 네임스페이스를 쓰지 않습니다.

Code
SELECT topology.AsGML(topo,'') As rdgml
  FROM ri.roads
  WHERE road_name = 'Unknown';
래스터 출력
<TopoCurve>
    <directedEdge>
        <Edge id="E1">
            <directedNode orientation="-">
                <Node id="N1"/>
            </directedNode>
            <directedNode
></directedNode>
            <curveProperty>
                <Curve srsName="urn:ogc:def:crs:EPSG::3438">
                    <segments>
                        <LineStringSegment>
                            <posList srsDimension="2"
>384744 236928 384750 236923 384769 236911 384799 236895 384811 236890
                            384833 236884 384844 236882 384866 236881 384879 236883 384954 236898 385087 236932 385117 236938
                            385167 236938 385203 236941 385224 236946 385233 236950 385241 236956 385254 236971
                            385260 236979 385268 236999 385273 237018 385273 237037 385271 237047 385267 237057 385225 237125
                            385210 237144 385192 237161 385167 237192 385162 237202 385159 237214 385159 237227 385162 237241
                            385166 237256 385196 237324 385209 237345 385234 237375 385237 237383 385238 237399 385236 237407
                            385227 237419 385213 237430 385193 237439 385174 237451 385170 237455 385169 237460 385171 237475
                            385181 237503 385190 237521 385200 237533 385206 237538 385213 237541 385221 237542 385235 237540 385242 237541
                            385249 237544 385260 237555 385270 237570 385289 237584 385292 237589 385291 237596 385284 237630</posList>
                         </LineStringSegment>
                    </segments>
                </Curve>
            </curveProperty>
        </Edge>
    </directedEdge>
</TopoCurve>

제목

AsTopoJSON — TopoGeometry의 TopoJSON 표현식을 반환합니다.

요약

text AsTopoJSON(topogeometry tg, regclass edgeMapTable);

Description

TopoGeometry의 TopoJSON 표현식을 반환합니다. edgeMapTable 이 NULL이 아닐 경우, 경계선 식별자를 원호(arc) 인덱스에 매핑하는 탐색/저장(lookup/storage)으로 쓰일 것입니다. 최종 문서에 조밀한(compact) "원호" 배열을 사용할 수 있게 하기 위해서입니다.

테이블을 설정할 경우, 테이블이 "순차(serial)" 유형 "arc_id" 항목과 정수형 "edge_id" 항목을 가지고 있어야 합니다. 코드가 "edge_id"에 대해 테이블을 쿼리할 것이므로 해당 항목에 인덱스를 추가하는 편이 좋습니다.

[참고]

TopoJSON 출력물에서는 원호 인덱스가 0-기반이지만 "edgeMapTable" 테이블에서는 1-기반입니다.

완전한 TopoJSON 문서는, 이 함수가 반환하는 토막 정보(snippet)에 더해, 일부 헤더와 함께 실제 원호를 담고 있어야 할 것입니다. TopoJSON 사양서 를 참조하십시오.

2.1.0 버전부터 사용할 수 있습니다.

개선 사항: 2.2.1 버전부터 점형(puntal) 입력을 지원하기 시작했습니다.

예시

Create a temporary edge map for the TopoJSON output.

Code
CREATE TEMP TABLE edgemap(arc_id serial, edge_id int unique);

Build the TopoJSON header, objects, arcs, and footer.

Code
SELECT '{ "type": "Topology", "transform": { "scale": [1,1], "translate": [0,0] }, "objects": {'

UNION ALL SELECT '"' || feature_name || '": ' || AsTopoJSON(feature, 'edgemap')
FROM features.big_parcels WHERE feature_name = 'P3P4';

WITH edges AS (
  SELECT m.arc_id, e.geom FROM edgemap m, city_data.edge e
  WHERE e.edge_id = m.edge_id
), points AS (
  SELECT arc_id, (ST_DumpPoints(geom)).* FROM edges
), compare AS (
  SELECT p2.arc_id,
         CASE WHEN p1.path IS NULL THEN p2.geom
              ELSE ST_Translate(p2.geom, -ST_X(p1.geom), -ST_Y(p1.geom))
         END AS geom
  FROM points p2 LEFT OUTER JOIN points p1
  ON ( p1.arc_id = p2.arc_id AND p2.path[1] = p1.path[1]+1 )
  ORDER BY arc_id, p2.path
), arcsdump AS (
  SELECT arc_id, (regexp_matches(ST_AsGeoJSON(geom), '\[.*\]'))[1] as t
  FROM compare
), arcs AS (
  SELECT arc_id, '[' || array_to_string(array_agg(t), ',') || ']' as a FROM arcsdump
  GROUP BY arc_id
  ORDER BY arc_id
)
SELECT '}, "arcs": [' UNION ALL
SELECT array_to_string(array_agg(a), E',\n') from arcs

UNION ALL SELECT ']}'::text as t;
래스터 출력
{ "type": "Topology", "transform": { "scale": [1,1], "translate": [0,0] }, "objects": {
"P3P4": { "type": "MultiPolygon", "arcs": [[[-1]],[[6,5,-5,-4,-3,1]]]}
}, "arcs": [
 [[25,30],[6,0],[0,10],[-14,0],[0,-10],[8,0]],
 [[35,6],[0,8]],
 [[35,6],[12,0]],
 [[47,6],[0,8]],
 [[47,14],[0,8]],
 [[35,22],[12,0]],
 [[35,14],[0,8]]
 ]}

9.14. 지형 공간 관계성

초록

이 단원에서 TopoGeometry와 지형 원시형 사이의 관계를 확인하는 데 쓰이는 지형 함수에 대해 설명합니다.

  • Equals — 두 TopoGeometry가 동일한 지형 원시형으로 이루어졌을 경우 참을 반환합니다.
  • Intersects — 두 TopoGeometry에서 나온 원시형의 쌍 가운데 하나라도 교차할 경우 참을 반환합니다.

제목

Equals — 두 TopoGeometry가 동일한 지형 원시형으로 이루어졌을 경우 참을 반환합니다.

요약

boolean Equals(topogeometry tg1, topogeometry tg2);

Description

두 TopoGeometry가 동일한 지형 원시형(표면, 경계선, 노드)으로 이루어졌을 경우 참을 반환합니다.

[참고]

이 함수는 도형 집합인 TopoGeometry를 지원하지 않습니다. 또 서로 다른 지형으로 이루어진 두 TopoGeometry를 비교하지 못 합니다.

1.1.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

예시

The following example uses the nei_topo table created in the toTopoGeom examples.

Code
SELECT topology.Equals(a.topo, b.topo)
FROM nei_topo AS a
JOIN nei_topo AS b ON b.gid = a.gid
WHERE a.gid = 1;
래스터 출력
t

제목

Intersects — 두 TopoGeometry에서 나온 원시형의 쌍 가운데 하나라도 교차할 경우 참을 반환합니다.

요약

boolean Intersects(topogeometry tg1, topogeometry tg2);

Description

두 TopoGeometry에서 나온 원시형의 쌍 가운데 하나라도 교차할 경우 참을 반환합니다.

[참고]

This function not supported for topogeometries that are geometry collections. It also can not compare topogeometries from different topologies. Also not currently supported for hierarchical topogeometries (topogeometries composed of other topogeometries).

1.1.0 버전부터 사용할 수 있습니다.

This function supports 3d and will not drop the z-index.

예시

The following example uses the nei_topo table created in the toTopoGeom examples.

Code
SELECT topology.Intersects(a.topo, b.topo)
FROM nei_topo AS a
JOIN nei_topo AS b ON b.gid = a.gid
WHERE a.gid = 1;
래스터 출력
t

9.15. Importing and exporting Topologies

Once you have created topologies, and maybe associated topological layers, you might want to export them into a file-based format for backup or transfer into another database.

Using the standard dump/restore tools of PostgreSQL is problematic because topologies are composed by a set of tables (4 for primitives, an arbitrary number for layers) and records in metadata tables (topology.topology and topology.layer). Additionally, topology identifiers are not univoque across databases so that parameter of your topology will need to be changes upon restoring it.

In order to simplify export/restore of topologies a pair of executables are provided: pgtopo_export and pgtopo_import. Example usage:

Code
pgtopo_export dev_db topo1 | pgtopo_import topo1 | psql staging_db

9.15.1. Using the Topology exporter

The pgtopo_export script takes the name of a database and a topology and outputs a dump file which can be used to import the topology (and associated layers) into a new database.

By default pgtopo_export writes the dump file to the standard output so that it can be piped to pgtopo_import or redirected to a file (refusing to write to terminal). You can optionally specify an output filename with the -f commandline switch.

By default pgtopo_export includes a dump of all layers defined against the given topology. This may be more data than you need, or may be non-working (in case your layer tables have complex dependencies) in which case you can request skipping the layers with the --skip-layers switch and deal with those separately.

Invoking pgtopo_export with the --help (or -h for short) switch will always print short usage string.

The dump file format is a compressed tar archive of a pgtopo_export directory containing at least a pgtopo_dump_version file with format version info. As of version 1 the directory contains tab-delimited CSV files with data of the topology primitive tables (node, edge_data, face, relation), the topology and layer records associated with it and (unless --skip-layers is given) a custom-format PostgreSQL dump of tables reported as being layers of the given topology.

9.15.2. Using the Topology importer

The pgtopo_import script takes a pgtopo_export format topology dump and a name to give to the topology to be created and outputs an SQL script reconstructing the topology and associated layers.

The generated SQL file will contain statements that create a topology with the given name, load primitive data in it, restores and registers all topology layers by properly linking all TopoGeometry values to their correct topology.

By default pgtopo_import reads the dump from the standard input so that it can be used in conjunction with pgtopo_export in a pipeline. You can optionally specify an input filename with the -f commandline switch.

By default pgtopo_import includes in the output SQL file the code to restore all layers found in the dump.

This may be unwanted or non-working in case your target database already have tables with the same name as the ones in the dump. In that case you can request skipping the layers with the --skip-layers switch and deal with those separately (or later).

SQL to only load and link layers to a named topology can be generated using the --only-layers switch. This can be useful to load layers AFTER resolving the naming conflicts or to link layers to a different topology (say a spatially-simplified version of the starting topology).

If the target topology already exists and you want it dropped upfront you can pass the --drop-topology switch (since PostGIS-3.6.0).

10장. 래스터 데이터의 관리, 쿼리 및 응용

10.1. 래스터 로드 및 생성

대부분의 경우, 사용자는 패키징되어 있는 raster2pgsql 래스터 로더를 통해 기존 래스터 파일을 로드해서 PostGIS 래스터를 생성할 것입니다.

10.1.1. raster2pgsql을 이용해 래스터를 로드하기

The raster2pgsql is a raster loader executable that loads GDAL supported raster formats into SQL suitable for loading into a PostGIS raster table. It is capable of loading folders of raster files as well as creating overviews of rasters.

Since the raster2pgsql is compiled as part of PostGIS most often (unless you compile your own GDAL library), the raster types supported by the executable will be the same as those compiled in the GDAL dependency library. To get a list of raster types your particular raster2pgsql supports use the -G switch.

[참고]

정렬된 래스터 집합에서 특정 인자(factor)의 오버뷰를 성생하는 경우, 오버뷰들이 정렬되지 않을 수도 있습니다. http://trac.osgeo.org/postgis/ticket/1764 페이지에서 오버뷰가 정렬되지 않는 예시를 찾아볼 수 있습니다.

10.1.1.1. Example Usage

로더를 통해 입력 파일을 생성하고 100x100 타일 뭉치로 나누어 업로드하는 세션의 예시는 다음과 같습니다:

The loader assigns SRID 4326, creates an index and standard constraints, analyzes the loaded table, records source filenames, and stores the input rasters in 100 by 100 pixel tiles.

Code
raster2pgsql -s 4326 -I -C -M -F -t 100x100 *.tif public.demelevation 
> elev.sql
psql -d gisdb -f elev.sql
[참고]

If you do not specify the schema as part of the target table name, the table will be created in the default schema of the database or user you are connecting with.

UNIX 파이프를 이용하면 변환 및 업로드 작업을 한 번에 끝낼 수 있습니다:

Code
raster2pgsql -s 4326 -I -C -M -F -t 100x100 \
  *.tif public.demelevation |
  psql -d gisdb

매사추세츠 주의 미터 단위 항공사진 타일 래스터들을 aerial 이라는 스키마로 로드하고, 전체 뷰와 2레벨 및 4레벨 오버뷰 테이블을 생성한 다음, 복사 모드를 통해 (중간 단계 파일 없이 DB로 직접) 삽입하며, 강제로 모든 작업을 상호처리하지 않도록 -e 플래그를 사용하십시오(작업이 완료되길 기다리지 않고 테이블에 들어오는 데이터를 바로 살펴보고자 할 때 유용합니다). 래스터를 128x128 픽셀 타일로 분절한 다음 래스터 제약조건을 적용하십시오. 테이블 삽입 대신 복사 모드를 이용하십시오. 타일들이 잘라져 나온 타일 파일명을 담을 수 있도록 -F 플래그로 "filename"이라는 필드를 포함시키십시오.

Code
raster2pgsql -I -C -e -Y -F -s 26986 -t 128x128 -l 2,4 \
  bostonaerials2008/*.jpg aerials.boston |
  psql -U postgres -d gisdb -h localhost -p 5432

List the raster formats supported by this build:

Code
raster2pgsql -G

The -G command outputs a list something like:

래스터 출력
Available GDAL raster formats:
  Virtual Raster
  GeoTIFF
  National Imagery Transmission Format
  Raster Product Format TOC format
  ECRG TOC format
  Erdas Imagine Images (.img)
  CEOS SAR Image
  CEOS Image
  ...
  Arc/Info Export E00 GRID
  ZMap Plus Grid
  NOAA NGS Geoid Height Grids

10.1.1.2. raster2pgsql options

Long options that take values also accept the --option=value spelling.

-?, --help

도움말 화면을 표출합니다. 어떤 인수도 쓰지 않을 경우에도 도움말이 표출될 것입니다.

-G, --gdal-formats

지원하는 래스터 형식을 나열합니다.

c|a|d|p -- 이들은 상호배타적인 옵션들입니다:

-c

새 테이블을 생성한 다음 래스터(들)로 해당 테이블을 채웁니다. 이것이 기본 모드입니다.

-a

기존 테이블에 래스터(들)을 추가합니다.

-d

기존 테이블을 삭제하고, 새 테이블을 생성한 다음 래스터(들)로 해당 테이블을 채웁니다.

-p

준비 모드로, 테이블만 생성합니다.

--if-not-exists

Use IF NOT EXISTS for table creation in -c and -p modes. When -I or --create-index is also specified, use IF NOT EXISTS for index creation too. This option cannot be used with -d. Append mode requires an explicit creation action.

Atomic loader actions

The short modes are presets over explicit actions. The equivalent long options are --drop-table, --create-table, --load-data, --create-index, --add-constraints, --vacuum, --analyze, and --no-transaction. Add --if-not-exists to make active creation actions use IF NOT EXISTS. --drop-table emits DROP TABLE IF EXISTS before the selected actions. With no mode specified, the default create/load actions still apply.

래스터 공간 처리: 래스터 카탈로그에 제대로 등록하기 위한 제약조건 적용

-C, --add-constraints

raster_columns 뷰에 래스터를 제대로 등록하기 위한 SRID, 픽셀 크기 등의 래스터 제약조건을 적용합니다.

-x, --no-extent

Disable setting the max extent constraint. Only applied if -C or --add-constraints is also used.

-r, --regular-blocking

Set the constraints (spatially unique and coverage tile) for regular blocking. Only applied if -C or --add-constraints is also used.

래스터 공간 처리: 입력 래스터 데이터셋을 조작하는 데 쓰이는 선택적 파라미터

-s, --srid [<FROM_SRID>:]<SRID>

Assign the output raster to the specified SRID. When FROM_SRID is also provided, raster2pgsql marks the input raster with FROM_SRID and emits SQL that reprojects the raster to the target SRID. If the source SRID is omitted or is zero, the raster metadata will be checked to determine an appropriate source SRID. Reprojection cannot be used with copy mode.

-b, --band BAND

래스터에서 밴드의 (1-기반) 인덱스를 추출합니다. 하나 이상의 밴드 인덱스가 있을 경우, 쉼표(,)로 구분하십시오. 지정하지 않는 경우 래스터의 모든 밴드를 추출합니다.

-t, --tile-size TILE_SIZE

테이블 행 한 개당 하나씩 삽입되도록 래스터를 타일로 자릅니다. TILE_SIZE 는 너비x높이로 표현되거나, 또는 "auto" 값으로 설정하면 로더가 첫 번째 래스터를 이용해 적당한 크기를 계산해서 모든 래스터에 적용합니다.

-P, --pad

맨 오른쪽 및 맨 아래 타일들의 여백을 메꿔넣어(padding) 모든 타일이 동일한 너비와 높이를 갖도록 보장합니다.

-R, --register

래스터를 파일 시스템 (DB 외부) 래스터로 등록합니다.

데이터베이스에 래스터의 (픽셀이 아니라) 메타데이터 및 경로 위치만 저장될 것입니다.

-l, --overview-factor OVERVIEW_FACTOR

Create overview of the raster. For more than one factor, separate with comma(,). Overview table name follows the pattern o_overview factor_table, where overview factor is a placeholder for numerical overview factor and table is replaced with the base table name. If a source raster already has an overview with matching dimensions, that overview is reused. Created overview is stored in the database and is not affected by -R. Note that your generated sql file will contain both the main table and overview tables.

-N, --nodata NODATA

"NODATA" 값이 없는 밴드에 사용할 NODATA 값입니다.

데이터베이스 객체를 조작하는 데 이용되는 선택적 파라미터들

-f, --raster-column COLUMN

저장될 래스터 열의 명칭을 설정합니다. 기본값은 'rast'입니다.

-F, --filename

파일명을 담은 열을 추가합니다.

-n, --filename-column COLUMN

파일명 열의 명칭을 설정합니다. -F 플래그와 함께 써야 합니다.

-q, --quote

PostgreSQL 식별자를 따옴표로 감쌉니다.

-I

Alias for --create-index.

--create-index

Create a GiST index on the raster column at the end of this raster2pgsql run. With repeated -a append runs, create the index on the final run or after loading; add --if-not-exists to make reruns tolerate an existing index.

-M

래스터 테이블을 빈공간 분석(vacuum analyze)합니다.

-k, --skip-nodata-check

Keeps empty tiles and skips NODATA value checks for each raster band. Note you save time in checking, but could end up with far more junk rows in your database and those junk rows are not marked as empty tiles.

-T, --tablespace tablespace

새 테이블 용 테이블스페이스를 설정합니다. -X 플래그를 함께 사용하지 않으면 (기본 키를 포함한) 인덱스들이 여전히 기본 테이블스페이스를 사용할 것이라는 점에 주의하십시오.

-X, --index-tablespace tablespace

테이블의 새 인덱스 용 테이블스페이스를 설정합니다. -I 플래그를 함께 사용하면 기본 키와 공간 인덱스에 함께 적용됩니다.

-Y, --copy [MAX_ROWS_PER_COPY]

Use copy statements instead of insert statements. Optionally specify max_rows_per_copy; default 50 when not specified.

-e, --no-transaction

각 선언문을 개별적으로 실행하며, 상호처리(transaction)를 이용하지 않습니다.

-E, --endian ENDIAN

생성된 래스터 바이너리 산출물의 메모리 내부 데이터 순서(endianness)를 조정합니다. XDR은 0, 기본값인 NDR은 1로 설정하십시오. 현재, NDR 산출물만 지원합니다.

-V, --wkb-version version

산출물 형식의 버전을 설정합니다. 기본값은 0입니다. 현재, 0만 지원합니다.

10.1.2. PostGIS 래스터 함수를 이용해 래스터 생성하기

사용자가 래스터와 래스터 테이블을 데이터베이스 내부에 생성하려 하는 경우가 많을 것입니다. 그런 작업을 위한, 넘치고도 남을 많은 함수가 있습니다. 일반적인 단계는 다음과 같습니다.

  1. 새 래스터 레코드를 담을 래스터 열을 가진 테이블을 다음과 같이 생성하십시오:

    Code
    CREATE TABLE myrasters(rid serial primary key, rast raster);
  2. 해당 목표를 도와줄 함수가 많이 있습니다. 다른 래스터에서 파생되지 않은 래스터를 생성하는 경우, ST_MakeEmptyRaster 함수와 ST_AddBand 함수를 순서대로 사용하는 편이 좋습니다.

    도형으로부터도 래스터를 생성할 수 있습니다. 그러려면 ST_AsRaster 함수를, 아마도 ST_Union , ST_MapAlgebraFct 또는 맵 대수(algebra) 함수 계열의 어떤 함수와도 같은 다른 함수와 함께 사용하는 편이 좋습니다.

    기존 테이블로부터 새 래스터 테이블을 생성하는 데에는 더욱 많은 선택지가 있습니다. 예를 들어 ST_Transform 함수를 사용하면 기존 테이블과는 다른 투영이 적용된 래스터 테이블을 생성할 수 있습니다.

  3. 일단 사용자 테이블을 채우는 작업을 마쳤다면, 다음과 같이 래스터 열에 대해 공간 인덱스를 생성하는 편이 좋습니다:

    Code
    CREATE INDEX myrasters_rast_st_convexhull_idx ON myrasters USING gist(ST_ConvexHull(rast));

    래스터 연산자 대부분이 래스터의 볼록 껍질(convex hull)을 기반으로 하기 때문에 ST_ConvexHull 함수를 사용했다는 점에 주의하십시오.

    [참고]

    PostGIS 2.0 미만 버전에서 래스터는 볼록 껍질보다는 엔벨로프(envelop)를 기반으로 하고 있었습니다. 공간 인덱스가 제대로 작동하려면 구식 인덱스를 삭제하고 볼록 껍질 기반 인덱스로 대체해야 합니다.

  4. AddRasterConstraints 를 이용해 래스터 제약조건 적용

10.1.3. Using "out db" cloud rasters

The raster2pgsql tool uses GDAL to access raster data, and can take advantage of a key GDAL feature: the ability to read from rasters that are stored remotely in cloud "object stores" (e.g. AWS S3, Google Cloud Storage).

Efficient use of cloud stored rasters requires the use of a "cloud optimized" format. The most well-known and widely used is the "cloud optimized GeoTIFF" format. Using a non-cloud format, like a JPEG, or an un-tiled TIFF will result in very poor performance, as the system will have to download the entire raster each time it needs to access a subset.

First, load your raster into the cloud storage of your choice. Once it is loaded, you will have a URI to access it with, either an "http" URI, or sometimes a URI specific to the service. (e.g., "s3://bucket/object"). To access non-public buckets, you will need to supply GDAL config options to authenticate your connection. Note that this command is reading from the cloud raster and writing to the database.

Code
AWS_ACCESS_KEY_ID=xxxxxxxxxxxxxxxxxxxx \
AWS_SECRET_ACCESS_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx \
raster2pgsql \
  -s 990000 \
  -t 256x256 \
  -I \
  -R \
  /vsis3/your.bucket.com/your_file.tif \
  your_table \
  | psql your_db

Once the table is loaded, you need to give the database permission to read from remote rasters, by setting two permissions, postgis.enable_outdb_rasters and postgis.gdal_enabled_drivers.

Code
SET postgis.enable_outdb_rasters = true;
SET postgis.gdal_enabled_drivers TO 'ENABLE_ALL';
    

To make the changes sticky, set them directly on your database. You will need to re-connect to experience the new settings.

Code
ALTER DATABASE your_db SET postgis.enable_outdb_rasters = true;
ALTER DATABASE your_db SET postgis.gdal_enabled_drivers TO 'ENABLE_ALL';
    

For non-public rasters, you may have to provide access keys to read from the cloud rasters. The same keys you used to write the raster2pgsql call can be set for use inside the database, with the postgis.gdal_vsi_options configuration. Note that multiple options can be set by space-separating the key=value pairs.

Code
SET postgis.gdal_vsi_options = 'AWS_ACCESS_KEY_ID=xxxxxxxxxxxxxxxxxxxx
AWS_SECRET_ACCESS_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

Once you have the data loaded and permissions set you can interact with the raster table like any other raster table, using the same functions. The database will handle all the mechanics of connecting to the cloud data when it needs to read pixel data.

10.2. 래스터 카탈로그

PostGIS와 함께 패키징되는 래스터 카탈로그 뷰는 두 개입니다. 두 뷰 모두 래스터 테이블의 제약조건에 내장된 정보를 활용합니다. 제약조건이 강제적이기 때문에, 결과적으로 카탈로그 뷰는 언제나 테이블 내부의 래스터 데이터와 일관성을 유지합니다.

  1. raster_columns 이 뷰는 사용자 데이터베이스에 있는 모든 래스터 테이블 열을 카탈로그화합니다.

  2. raster_overviews 이 뷰는 더 세밀한 테이블을 위한 오버뷰 역할을 하는 사용자 데이터베이스에 있는 모든 래스터 테이블 열을 카탈로그화합니다. 로드 과정에서 -l 스위치를 사용할 경우 이 테이블 유형을 생성합니다.

10.2.1. 래스터 열 카탈로그

raster_columns 는 사용자 데이터베이스에 있는 모든 래스터 테이블 열의 래스터 유형 카탈로그입니다. 래스터 열 카탈로그는 테이블에 대한 제약조건을 활용하기 때문에, 설령 사용자가 다른 데이터베이스의 백업으로부터 래스터 테이블을 하나 복원했다 하더라도, 카탈로그 정보는 언제나 일관성을 유지합니다. 다음은 raster_columns 카탈로그 안에 존재하는 열들입니다.

로더를 통해 사용자 테이블을 생성하지 않았거나 로드 과정에서 -C 플래그 설정을 잊었을 경우, 테이블 생성 후에 raster_columns 카탈로그가 사용자의 래스터 타일에 관한 일반 정보를 등록하도록 AddRasterConstraints 함수를 통해 제약조건을 강제할 수 있습니다.

  • r_table_catalog 테이블을 담고 있는 데이터베이스입니다. 이 열은 언제나 현재 데이터베이스를 읽어들일 것입니다.

  • r_table_schema 래스터 테이블이 속해 있는 데이터베이스 스키마입니다.

  • r_table_name 래스터 테이블 명입니다.

  • r_raster_column 래스터 유형의 r_table_name 테이블 안에 있는 열입니다. PostGIS는 사용자가 테이블 하나 당 몇 개의 래스터 열을 가질 수 있는지 제한하지 않기 때문에, 래스터 테이블 하나를 각각 다른 래스터 열로 몇 번이고 나열할 수 있습니다.

  • srid 래스터의 공간 참조 식별자입니다. 4.5절. “SPATIAL_REF_SYS 테이블과 공간 참조 시스템” 목록에 있는 항목이어야 합니다.

  • scale_x 기하하적 공간 좌표와 픽셀의 비례(축척)입니다. 래스터 열에 있는 모든 타일이 동일한 scale_x 를 가지며, scale_x 제약조건이 적용될 경우에만 사용할 수 있습니다. 자세한 내용은 ST_ScaleX 를 참조하십시오.

  • scale_y 기하하적 공간 좌표와 픽셀의 비례(축척)입니다. 래스터 열에 있는 모든 타일이 동일한 scale_y 를 가지며, scale_y 제약조건이 적용될 경우에만 사용할 수 있습니다. 자세한 내용은 ST_ScaleY 를 참조하십시오.

  • blocksize_x 각 래스터 타일의 너비(가로 방향의 픽셀 개수)입니다. 자세한 사항은 ST_Width 를 참조하십시오.

  • blocksize_y 각 래스터 타일의 높이(세로 방향의 픽셀 개수)입니다. 자세한 사항은 ST_Height 를 참조하십시오.

  • same_alignment 모든 래스터 타일이 동일한 방향으로 정렬된 경우 참인 불 값입니다. 자세한 내용은 ST_SameAlignment 를 참조하십시오.

  • regular_blocking 래스터 열이 공간적 유일성 제약조건 및 커버리지 타일 제약조건을 가질 경우, 해당 값은 참입니다. 그 외의 경우는 거짓이 됩니다.

  • num_bands 사용자 래스터 집합의 각 타일이 내장한 밴드의 개수입니다. 다음 열과 동일한 정보를 제공합니다. ST_NumBands

  • pixel_types 각 밴드에 대한 픽셀 유형을 정의하는 배열입니다. 이 배열에는 사용자 밴드 개수와 동일한 개수의 요소들이 들어갈 것입니다. pixel_types는 다음 ST_BandPixelType 에서 정의된 픽셀 유형 가운데 하나입니다.

  • nodata_values 각 밴드에 대한 nodata_value 를 의미하는 배정밀도(double precision) 수(數)입니다. 이 배열에는 사용자 밴드 개수와 동일한 개수의 요소들이 들어갈 것입니다. 이 숫자는 대부분의 연산에서 무시되어야 할 각 밴드에 대한 픽셀 값을 정의합니다. 이 정보는 ST_BandNoDataValue 가 제공하는 정보와 유사합니다.

  • out_db 데이터베이스 외부에서 래스터 밴드 데이터를 유지하는지 여부를 보여주는 불 값 플래그의 배열입니다. 이 배열에는 사용자 밴드 개수와 동일한 개수의 요소들이 들어갈 것입니다.

  • extent 사용자 래스터 집합이 포함하는 모든 래스터 열의 범위(extent)입니다. 해당 집합의 범위를 변경시킬 추가 데이터를 로드할 계획이라면, 로드 작업 전에 DropRasterConstraints 함수를 실행하고 작업 후에 AddRasterConstraints 함수로 제약조건을 다시 적용시키는 편이 좋습니다.

  • spatial_index 래스터 열이 공간 인덱스를 가진 경우 참인 불 값입니다.

10.2.2. 래스터 오버뷰

raster_overviews 는 오버뷰에 이용되는 래스터 테이블 열에 관한 정보 및 오버뷰 활용시 알면 유용한 추가 정보를 카탈로그화합니다. 오버뷰 테이블은 raster_columnsraster_overviews 양쪽에 모두 카탈로그화됩니다. 오버뷰가 나름대로 래스터이긴 하지만, 동시에 고해상도 테이블의 저해상도 썸네일이라는 추가적인 특별 목적을 담당하고 있기 때문입니다. 래스터 로드 작업중 -l 스위치를 사용하면 주 래스터 테이블과 함께 오버뷰 테이블을 생성합니다. 또는 AddOverviewConstraints 함수를 통해 직접 생성할 수도 있습니다.

오버뷰 테이블은 다른 래스터 테이블과 동일한 제약조건은 물론 오직 오버뷰에 특화된 제약조건에 관한 추가 정보도 포함합니다.

[참고]

raster_overviews 에 담긴 정보는 raster_columns 의 정보를 복제한 것이 아닙니다. raster_columns 에서 현재 오버뷰 테이블에 관한 정보를 얻어야 할 경우 raster_overviewsraster_columns 을 함께 연결(join)시켜 필요한 완전한 정보를 얻으십시오.

오버뷰의 주된 존재 이유는 다음 두 가지입니다:

  1. 빠른 매핑 확대를 위해 흔히 핵심 테이블의 저해상도 모사를 이용합니다.

  2. 고해상도 페어런트보다 오버뷰를 기반으로 하는 계산이 일반적으로 더 빠릅니다. 레코드 개수도 더 적고 각 픽셀이 커버하는 면적도 더 크기 때문입니다. 오버뷰가 지원하는 고해상도 테이블 대상 계산보다야 정확하지 않지만, 어림잡이(rule-of-thumb) 계산의 경우 오버뷰도 충분할 수 있습니다.

raster_overviews 카탈로그는 다음과 같은 정보 열을 포함합니다.

  • o_table_catalog 오버뷰 테이블을 담고 있는 데이터베이스입니다. 이 열은 언제나 현재 데이터베이스를 읽어들일 것입니다.

  • o_table_schema 오버뷰 테이블이 속해 있는 데이터베이스 스키마입니다.

  • o_table_name 오버뷰 테이블 명입니다.

  • o_raster_column 오버뷰 테이블이 담고 있는 래스터 열입니다.

  • r_table_catalog 해당 오버뷰 서비스를 담고 있는 래스터 테이블 카탈로그입니다. 이 열은 언제나 현재 데이터베이스를 읽어들일 것입니다.

  • r_table_schema 해당 오버뷰 서비스가 속해 있는 래스터 테이블 스키마입니다.

  • r_table_name 해당 오버뷰가 서비스하는 래스터 테이블 명입니다.

  • r_raster_column 해당 오버뷰가 서비스하는 래스터 열입니다.

  • overview_factor 오버뷰 테이블의 피라미드 레벨입니다. 숫자가 커질수록 테이블의 해상도는 낮아집니다. raster2pgsql은 이미지 폴더를 받아 각 이미지 파일의 오버뷰를 계산하고 개별적으로 로드합니다. 항상 레벨 1을 원 파일로 가정합니다. 레벨 2는 각 타일이 원래 이미지 4장을 모사하게 됩니다. 따라서 예를 들어 사용자가 125x125로 뭉치려는 5000x5000픽셀 이미지 파일들이 있는 폴더의 경우, 각 이미지 파일에 대해 사용자의 기저 테이블이 (5000*5000)/(125*125) = 1600 레코드를 담게 되고, 사용자의 o_2 (l=2) 테이블이 최대 (1600/2^2) = 400행, o_3 (l=3) 테이블은 최대 (1600/2^3) = 200행의 레코드를 담게 될 것입니다. 사용자 픽셀 수가 사용자 타일로 나눌 수 있는 숫자가 아닐 경우, 몇몇 파편(scrap) 타일(완전히 채워지지 않은 타일)을 얻게 될 것입니다. raster2pgsql이 생성한 각 오버뷰 타일의 픽셀 개수가 해당 페어런트와 동일한 개수이지만, 각 픽셀이 표현하는 영역이 더 넓은 (원 이미지의 2^overview_factor 픽셀에 해당하는) 저해상도라는 점에 주의하십시오.

10.3. PostGIS 래스터를 이용하는 사용자 지정 응용 프로그램 빌드하기

The fact that PostGIS raster provides you with SQL functions to render rasters in known image formats gives you a lot of options for rendering them. For example you can use OpenOffice / LibreOffice for rendering as demonstrated in Rendering PostGIS Raster graphics with LibreOffice Base Reports. In addition you can use a wide variety of languages as demonstrated in this section.

10.3.1. 다른 래스터 함수와 함께 ST_AsPNG를 이용해서 PHP 예제를 출력하기

이 단원에서, PHP PostgreSQL 드라이버와 ST_AsGDALRaster 계열 함수를 사용해서 래스터의 1, 2, 3 밴드를 PHP 요청 스트림(request stream)으로 출력하는 방법을 설명할 것입니다. 이후 PHP 요청 스트림을 "img src" HTML 태그로 임베딩할 수 있습니다.

예시 쿼리는 여러 래스터 함수를 함께 결합(combine)해서 특정 WGS84 경계 상자와 교차하는 모든 타일을 얻은 다음, ST_Union 함수를 통해 교차하는 타일들과 반환되는 모든 밴드를 통합(union)해서, ST_Transform 함수를 이용해 사용자가 지정한 투영으로 변환한 후, ST_AsPNG 함수로 결과값을 PNG 파일로 출력하는 방법을 보여줍니다.

You would call the script with http://mywebserver/test_raster.php?srid=2249 to get the raster image in Massachusetts state plane feet.

Code
<?php
$conn_str = 'dbname=mydb host=localhost port=5432 user=myuser password=mypwd';
$dbconn = pg_connect($conn_str);
header('Content-Type: image/png');

if (!empty($_REQUEST['srid']) &amp;&amp; is_numeric($_REQUEST['srid'])) {
    $input_srid = intval($_REQUEST['srid']);
} else {
    $input_srid = 26986;
}

$sql = "SET bytea_output = 'escape';
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
    )
)";

$result = pg_query($sql);
$row = pg_fetch_row($result);
pg_free_result($result);
if ($row === false) return;
echo pg_unescape_bytea($row[0]);
?>

10.3.2. 다른 래스터 함수와 함께 ST_AsPNG를 이용해서 ASP.NET C# 예제를 출력하기

In this section, we'll demonstrate how to use Npgsql PostgreSQL .NET driver and the ST_AsGDALRaster family of functions to output band 1,2,3 of a raster to the HTTP response stream so it can be embedded in an img tag.

이 예제를 실행하려면 npgsql PostgreSQL .NET 드라이버가 필요합니다. http://npgsql.projects.postgresql.org/ 에서 최신 버전을 다운로드할 수 있습니다. 최신 버전을 다운로드해서 사용자의 ASP.NET bin 폴더에 넣기만 하면 준비가 끝납니다.

예시 쿼리는 여러 래스터 함수를 함께 결합(combine)해서 특정 WGS84 경계 상자와 교차하는 모든 타일을 얻은 다음, ST_Union 함수를 통해 교차하는 타일들과 반환되는 모든 밴드를 통합(union)해서, ST_Transform 함수를 이용해 사용자가 지정한 투영으로 변환한 후, ST_AsPNG 함수로 결과값을 PNG 파일로 출력하는 방법을 보여줍니다.

이 예제는 C#으로 실행된다는 점만 제회하면 10.3.1절. “다른 래스터 함수와 함께 ST_AsPNG를 이용해서 PHP 예제를 출력하기” 예제와 동일합니다.

You would call the handler with http://mywebserver/TestRaster.ashx?srid=2249 to get the raster image in Massachusetts state plane feet.

web.config connection string section:

Code
<connectionStrings>
    <add name="DSN"
        connectionString="server=localhost;database=mydb;Port=5432;User Id=myuser;password=mypwd"/>
</connectionStrings>

Code for TestRaster.ashx:

Code
<%@ 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 {
            string connectionString = System.Configuration.ConfigurationManager
                .ConnectionStrings["DSN"].ConnectionString;
            using (NpgsqlConnection conn = new NpgsqlConnection(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));


                result = (byte[]) command.ExecuteScalar();
                conn.Close();
            }

        }
        catch (Exception ex)
        {
            result = null;
            context.Response.Write(ex.Message.Trim());
        }
        return result;
    }
}

10.3.3. 래스터 쿼리를 이미지 파일로 출력하는 Java 콘솔 응용 프로그램

이미지 한 장을 반환해서 지정된 파일로 출력하는 쿼리를 이용하는 단순한 Java 콘솔 응용 프로그램입니다.

http://jdbc.postgresql.org/download.html에서 최신 PostgreSQL JDBC 드라이버를 다운로드할 수 있습니다.

You can compile the following code with commands like:

Code
CLASSPATH=".:../postgresql.jar" javac SaveQueryImage.java
jar cfm SaveQueryImage.jar Manifest.txt *.class

And call it from the command line with something like:

Code
java -jar SaveQueryImage.jar \
  "SELECT ST_AsPNG(ST_AsRaster(ST_Buffer(ST_Point(1, 5), 10, 'quad_segs=2'), 150, 150, '8BUI', 100));" \
  "test.png"

Manifest.txt:

Code
Class-Path: postgresql-9.0-801.jdbc4.jar
Main-Class: SaveQueryImage

Code for SaveQueryImage.java:

Code
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.io.*;

public class SaveQueryImage {
  public static void main(String[] argv) {
      System.out.println("Checking if Driver is registered with DriverManager.");

      try {
        //java.sql.DriverManager.registerDriver (new org.postgresql.Driver());
        Class.forName("org.postgresql.Driver");
      }
      catch (ClassNotFoundException cnfe) {
        System.out.println("Couldn't find the driver!");
        cnfe.printStackTrace();
        System.exit(1);
      }

      Connection conn = null;

      try {
        conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/mydb", "myuser", "mypwd");
        conn.setAutoCommit(false);

        PreparedStatement sGetImg = conn.prepareStatement(argv[0]);

        ResultSet rs = sGetImg.executeQuery();

        FileOutputStream fout;
        try
        {
            rs.next();
            /** Output to file name requested by user **/
            fout = new FileOutputStream(new File(argv[1]) );
            fout.write(rs.getBytes(1));
            fout.close();
        }
        catch(Exception e)
        {
            System.out.println("Can't create file");
            e.printStackTrace();
        }

        rs.close();
        sGetImg.close();
        conn.close();
      }
      catch (SQLException se) {
        System.out.println("Couldn't connect: print out a stack trace and exit.");
        se.printStackTrace();
        System.exit(1);
      }
  }
}

10.3.4. PLPython을 이용해서 SQL을 통해 이미지를 덤프하기

서버 디렉터리에 각 레코드를 파일로 생성하는 PLPython 저장 함수입니다. PLPython을 설치해야 합니다. PLPythonu와 PLPythonu3u 모두 잘 작동할 것입니다.

Code
CREATE OR REPLACE FUNCTION write_file (param_bytes bytea, param_filepath text)
RETURNS text
AS $$
f = open(param_filepath, 'wb+')
f.write(param_bytes)
return param_filepath
$$ LANGUAGE plpythonu;

Write out 5 images to the PostgreSQL server in varying sizes. The PostgreSQL daemon account needs write access to the folder; this echoes back the file names created.

Code
SELECT write_file(
    ST_AsPNG(
        ST_AsRaster(
            ST_Buffer(ST_Point(1, 5), j * 5, 'quad_segs=2'),
            150 * j,
            150 * j,
            '8BUI',
            100
        )
    ),
    'C:/temp/slices' || j || '.png'
)
FROM generate_series(1, 5) AS j;
래스터 출력
write_file
---------------------
 C:/temp/slices1.png
 C:/temp/slices2.png
 C:/temp/slices3.png
 C:/temp/slices4.png
 C:/temp/slices5.png

10.3.5. PSQL을 이용해서 래스터 출력하기

Sadly PSQL doesn't have easy to use built-in functionality for outputting binaries. This is a bit of a hack that piggy backs on PostgreSQL somewhat legacy large object support. To use it, first launch your psql command line connected to your database.

파이썬 접근법과는 달리, 이 접근법은 사용자의 로컬 시스템에 파일을 생성합니다.

Code
SELECT
    oid,
    lowrite(lo_open(oid, 131072), png) AS num_bytes
FROM (VALUES (
    lo_create(0),
    ST_AsPNG((SELECT rast FROM aerials.boston WHERE rid = 1))
)) AS v(oid, png);
래스터 출력
oid   | num_bytes
---------+-----------
 2630819 |     74860

Note the large object OID and export it to a file on your local computer, replacing the example path with the desired file path.

Code
\lo_export 2630819 'C:/temp/aerial_samp.png'

This deletes the file from large object storage in the database.

Code
SELECT lo_unlink(2630819);

11장. 래스트 참조문서

raster is a PostGIS type for storing and analyzing raster data.

래스터 파일에서 래스터를 로드하려면 10.1절. “래스터 로드 및 생성” 를 참조하십시오.

Some examples in this reference use a raster table of dummy data, created with the following code:

Code
CREATE TABLE dummy_rast(rid integer, rast raster);
INSERT INTO dummy_rast(rid, rast)
VALUES (1,
('01' -- little endian (uint8 ndr)
||
'0000' -- version (uint16 0)
||
'0000' -- nBands (uint16 0)
||
'0000000000000040' -- scaleX (float64 2)
||
'0000000000000840' -- scaleY (float64 3)
||
'000000000000E03F' -- ipX (float64 0.5)
||
'000000000000E03F' -- ipY (float64 0.5)
||
'0000000000000000' -- skewX (float64 0)
||
'0000000000000000' -- skewY (float64 0)
||
'00000000' -- SRID (int32 0)
||
'0A00' -- width (uint16 10)
||
'1400' -- height (uint16 20)
)::raster
),
-- Raster: 5 x 5 pixels, 3 bands, PT_8BUI pixel type, NODATA = 0
(2, ('01000003009A9999999999A93F9A9999999999A9BF000000E02B274A' ||
'41000000007719564100000000000000000000000000000000FFFFFFFF050005000400FDFEFDFEFEFDFEFEFDF9FAFEF' ||
'EFCF9FBFDFEFEFDFCFAFEFEFE04004E627AADD16076B4F9FE6370A9F5FE59637AB0E54F58617087040046566487A1506CA2E3FA5A6CAFFBFE4D566DA4CB3E454C5665')::raster);

The functions below are ones which a user of PostGIS Raster is likely to need. There are other raster support functions which are not of interest to a general user.

11.1. 래스터 지원 데이터형

초록

이 단원에서 래스터 기능성을 지원하기 위해 특별히 생성된 PostgreSQL 데이터 유형들을 소개합니다.

  • geomval — (도형 객체를 담고 있는) geom과 (래스터 밴드의 이중 정밀도 픽셀값을 담고 있는) val, 두 개의 필드를 가진 공간 데이터형입니다.
  • addbandarg — 새로운 밴드의 속성 및 초기값을 정의하는 ST_AddBand 함수의 입력물로 이용되는 복합 데이터형입니다.
  • rastbandarg — 래스터 및 해당 래스터의 밴드 인덱스를 표현해야 할 경우 쓰이는 복합 데이터형입니다.
  • raster — 래스터 공간 데이터형입니다.
  • reclassarg — A composite type used as input into the ST_Reclass function defining the behavior of reclassification.
  • summarystats — ST_SummaryStats 및 ST_SummaryStatsAgg 함수가 반환하는 복합 데이터형입니다.
  • unionarg — 공간 처리할 밴드들 및 UNION 연산의 습성을 정의하는 ST_Union 함수의 입력물로 쓰이는 복합 데이터형입니다.

제목

geomval — (도형 객체를 담고 있는) geom과 (래스터 밴드의 이중 정밀도 픽셀값을 담고 있는) val, 두 개의 필드를 가진 공간 데이터형입니다.

Description

geomval은 복합 데이터 유형으로, .geom 필드가 참조하는 도형 객체와 래스터 밴드 내부의 특정 기하 위치에 있는 픽셀값을 나타내는 이중 정밀도 값인 val로 구성됩니다. ST_DumpAsPolygon 및 래스터 교차 계열 함수들이 래스터 밴드를 도형 폴리곤들로 분해하기 위한 출력물 유형으로 이 데이터형을 이용합니다.


제목

addbandarg — 새로운 밴드의 속성 및 초기값을 정의하는 ST_AddBand 함수의 입력물로 이용되는 복합 데이터형입니다.

Description

새로운 밴드의 속성 및 초기값을 정의하는 ST_AddBand 함수의 입력물로 이용되는 복합 데이터형입니다.

FieldTypeDescription
indexinteger래스터의 밴드들 사이 어떤 위치에 새 밴드를 추가할지 지시하는 1-기반 값입니다. NULL일 경우, 래스터 밴드의 마지막에 새 밴드를 추가할 것입니다.
pixeltypetextPixel type of the new band. One of the pixel types described in ST_BandPixelType.
initialvaluedouble precisionInitial value that all pixels of the new band will be set to.
nodatavaldouble precision새 밴드의 NODATA 값입니다. NULL일 경우, 새 밴드에 NODATA 값을 할당하지 않을 것입니다.

참고

ST_AddBand


제목

rastbandarg — 래스터 및 해당 래스터의 밴드 인덱스를 표현해야 할 경우 쓰이는 복합 데이터형입니다.

Description

래스터 및 해당 래스터의 밴드 인덱스를 표현해야 할 경우 쓰이는 복합 데이터형입니다.

FieldTypeDescription
rastrasterThe raster in question.
nbandinteger1-based value indicating the raster band.

제목

raster — 래스터 공간 데이터형입니다.

Description

raster is a spatial data type used to represent raster data such as those imported from JPEGs, TIFFs, PNGs, digital elevation models. Each raster has 1 or more bands each having a set of pixel values. Rasters can be georeferenced.

[참고]

GDAL 지원과 함께 컴파일한 PostGIS가 필요합니다. 현재 래스터를 제약 없이 도형 유형으로 변환할 수 있지만, 이 변환 작업은 래스터의 ST_ConvexHull 을 반환합니다. 이 자동 형변환 기능은 가까운 시일 내에 제거될 수 있으므로 의존하지 않는 편이 좋습니다.

형변환 습성

이 단원에서 이런 데이터 유형에 사용할 수 있는 자동 형변환은 물론 명시적인 형변환도 소개합니다.

형변환 결과습성
도형자동적

제목

reclassarg — A composite type used as input into the ST_Reclass function defining the behavior of reclassification.

Description

A composite type used as input into the ST_Reclass function defining the behavior of reclassification.

FieldTypeDescription
nbandinteger재분류할 밴드의 밴드 개수입니다.
reclassexprtextComma-delimited range:map_range mappings that define how old band values map to new band values.
pixeltypetextOne of defined pixel types as described in ST_BandPixelType.
nodatavaldouble precisionNODATA로 취급되는 값입니다. 투명도를 지원하는 이미지 출력물의 경우, 이 값이 투명이 될 것입니다.

The reclassexpr range delimiters mean: ( greater than, ) less than, ] less than or equal, and [ greater than or equal.

  • [a-b] means a <= x <= b.

  • (a-b] means a < x <= b.

  • [a-b) means a <= x < b.

  • (a-b) means a < x < b.

Opening-parenthesis notation is optional, so a-b means the same as (a-b).

예시

Reclassify band 2 as an 8BUI where 255 is nodata value.

Code
SELECT ROW(2, '0-100:1-10, 101-500:11-150,501 - 10000: 151-254', '8BUI', 255)::reclassarg;

Reclassify band 1 as an 1BB and no nodata value defined.

Code
SELECT ROW(1, '0-100]:0, (100-255:1', '1BB', NULL)::reclassarg;

제목

summarystats — ST_SummaryStats 및 ST_SummaryStatsAgg 함수가 반환하는 복합 데이터형입니다.

Description

ST_SummaryStatsST_SummaryStatsAgg 함수가 반환하는 복합 데이터형입니다.

count integer

요약 통계를 위해 집계된 픽셀 개수입니다.

sum double precision

집계된 모든 픽셀 값의 합입니다.

mean double precision

집계된 모든 픽셀 값의 산술 평균입니다.

stddev double precision

집계된 모든 픽셀 값의 표준 편차입니다.

min double precision

집계된 픽셀 값 가운데 최소값입니다.

max double precision

집계된 픽셀 값 가운데 최대값입니다.


제목

unionarg — 공간 처리할 밴드들 및 UNION 연산의 습성을 정의하는 ST_Union 함수의 입력물로 쓰이는 복합 데이터형입니다.

Description

공간 처리할 밴드들 및 UNION 연산의 습성을 정의하는 ST_Union 함수의 입력물로 쓰이는 복합 데이터형입니다.

FieldTypeDescription
nbandinteger공간 처리할 각 입력 래스터의 밴드를 지시하는 1-기반 값입니다.
uniontypetextType of union operation. One of the types described in ST_Union.

참고

ST_Union

11.2. 래스터 관리

  • AddRasterConstraints — Adds raster constraints to a loaded raster table for a specific column that constrains spatial ref, scaling, blocksize, alignment, bands, band type and a flag to denote if raster column is regularly blocked. The table must be loaded with data for the constraints to be inferred. Returns true if the constraint setting was accomplished and issues a notice otherwise.
  • DropRasterConstraints — 래스터 테이블 열을 참조하는 PostGIS 래스터 제약조건을 삭제합니다. 데이터를 다시 로드하거나 사용자 래스터 열 데이터를 업데이트해야 할 경우 유용합니다.
  • AddOverviewConstraints — 래스터 열을 또 다른 래스터 열의 미리보기(overview)로 태그합니다.
  • DropOverviewConstraints — 또 다른 래스터 열의 미리보기(overview)로서의 래스터 열을 태그 해제합니다.
  • PostGIS_GDAL_Version — PostGIS가 이용하고 있는 GDAL 라이브러리의 버전을 반환합니다.
  • PostGIS_Raster_Lib_Build_Date — 전체 래스터 라이브러리의 빌드 날짜를 반환합니다.
  • PostGIS_Raster_Lib_Version — 전체 래스터 버전 및 설정 정보를 반환합니다.
  • ST_GDALDrivers — Returns a list of raster formats supported by PostGIS through GDAL. Only those formats with can_write=True can be used by ST_AsGDALRaster
  • UpdateRasterSRID — 사용자가 지정한 열 및 테이블에 있는 모든 래스터의 SRID를 변경합니다.
  • ST_CreateOverview — 입력 래스터 커버리지의 저해상도 버전을 생성합니다.

제목

AddRasterConstraints — Adds raster constraints to a loaded raster table for a specific column that constrains spatial ref, scaling, blocksize, alignment, bands, band type and a flag to denote if raster column is regularly blocked. The table must be loaded with data for the constraints to be inferred. Returns true if the constraint setting was accomplished and issues a notice otherwise.

요약

boolean AddRasterConstraints(name rasttable, name rastcolumn, boolean srid=true, boolean scale_x=true, boolean scale_y=true, boolean blocksize_x=true, boolean blocksize_y=true, boolean same_alignment=true, boolean regular_blocking=false, boolean num_bands=true , boolean pixel_types=true , boolean nodata_values=true , boolean out_db=true , boolean extent=true );

boolean AddRasterConstraints(name rasttable, name rastcolumn, text[] VARIADIC constraints);

boolean AddRasterConstraints(name rastschema, name rasttable, name rastcolumn, text[] VARIADIC constraints);

boolean AddRasterConstraints(name rastschema, name rasttable, name rastcolumn, boolean srid=true, boolean scale_x=true, boolean scale_y=true, boolean blocksize_x=true, boolean blocksize_y=true, boolean same_alignment=true, boolean regular_blocking=false, boolean num_bands=true, boolean pixel_types=true, boolean nodata_values=true , boolean out_db=true , boolean extent=true );

Description

raster_columns 래스터 카탈로그에 정보를 표출하는 데 쓰이는, 래스터 열에 대한 제약조건들을 생성합니다. rastschema 는 해당 테이블이 속해 있는 테이블 스키마의 명칭입니다. srid 는 SPATIAL_REF_SYS 테이블에 있는 항목을 참조하는 정수형 값이어야만 합니다.

raster2pgsql 로더는 래스터 테이블을 등록하는 데 이 함수를 이용합니다.

입력할 유효한 제약조건 명칭에 대한 자세한 내용은 10.2.1절. “래스터 열 카탈로그” 를 참조하십시오.

  • blocksize 는 X 및 Y 블록 크기를 둘 다 설정합니다.

  • blocksize_x 는 X 타일(각 타일의 너비 픽셀 개수)을 설정합니다.

  • blocksize_y 는 Y 타일(각 타일의 높이 픽셀 개수)을 설정합니다.

  • extent 는 전체 테이블의 범위를 계산하고 제약조건을 적용합니다. 모든 래스터는 해당 범위 내에 들어와야만 합니다.

  • num_bands 는 밴드의 개수입니다.

  • pixel_types 각 밴드에 대해 픽셀 유형의 배열을 읽어 들입니다. 모든 밴드 N이 동일한 픽셀 유형을 가지도록 보장합니다.

  • regular_blocking 은 공간적 유일성 제약조건(어떤 두 래스터도 공간적으로 동일할 수 없습니다) 및 커버리지 타일 제약조건(래스터는 커버리지에 맞춰 정렬됩니다)을 설정합니다.

  • same_alignment ensures they all have same alignment meaning any two tiles you compare will return true for. Refer to ST_SameAlignment.

  • srid 는 모든 타일이 동일한 SRID를 가지도록 보장합니다.

  • 기타 -- 앞의 함수들이 입력받는 제약조건은 무엇이든 추가해주십시오.

[참고]

이 함수는 테이블에 이미 존재하는 데이터에 제약조건을 적용합니다. 따라서 이 함수가 작동하려면, 먼저 래스터 열을 생성한 다음 데이터를 로드해야만 합니다.

[참고]

사용자가 제약조건을 적용한 다음 추가 데이터를 로드해야 할 경우, 사용자 데이터의 범위가 변경된다면 DropRasterConstraints 함수를 실행하는 편이 좋습니다.

2.0.0 버전부터 사용할 수 있습니다.

예시

Apply all possible constraints on column based on data.

Verify the raster table is registered correctly in the raster_columns view.

Code
CREATE TABLE myrasters(rid SERIAL primary key, rast raster);
INSERT INTO myrasters(rast)
SELECT ST_AddBand(ST_MakeEmptyRaster(1000, 1000, 0.3, -0.3, 2, 2, 0, 0, 4326), 1, '8BSI'::text, -129, NULL);

SELECT AddRasterConstraints('myrasters'::name, 'rast'::name);
SELECT srid, scale_x, scale_y, blocksize_x, blocksize_y, num_bands, pixel_types, nodata_values
    FROM raster_columns
    WHERE r_table_name = 'myrasters';
래스터 출력
srid | scale_x | scale_y | blocksize_x | blocksize_y | num_bands | pixel_types| nodata_values
------+---------+---------+-------------+-------------+-----------+-------------+---------------
 4326 |       2 |       2 |        1000 |        1000 |         1 | {8BSI}      | {0}

Apply single constraint.

Code
CREATE TABLE public.myrasters2(rid SERIAL primary key, rast raster);
INSERT INTO myrasters2(rast)
SELECT ST_AddBand(ST_MakeEmptyRaster(1000, 1000, 0.3, -0.3, 2, 2, 0, 0, 4326), 1, '8BSI'::text, -129, NULL);

SELECT AddRasterConstraints('public'::name, 'myrasters2'::name, 'rast'::name, 'regular_blocking', 'blocksize');
래스터 출력
NOTICE:  Adding regular blocking constraint
NOTICE:  Adding blocksize-X constraint
NOTICE:  Adding blocksize-Y constraint

제목

DropRasterConstraints — 래스터 테이블 열을 참조하는 PostGIS 래스터 제약조건을 삭제합니다. 데이터를 다시 로드하거나 사용자 래스터 열 데이터를 업데이트해야 할 경우 유용합니다.

요약

boolean DropRasterConstraints(name rasttable, name rastcolumn, boolean srid, boolean scale_x, boolean scale_y, boolean blocksize_x, boolean blocksize_y, boolean same_alignment, boolean regular_blocking, boolean num_bands=true, boolean pixel_types=true, boolean nodata_values=true, boolean out_db=true , boolean extent=true);

boolean DropRasterConstraints(name rastschema, name rasttable, name rastcolumn, boolean srid=true, boolean scale_x=true, boolean scale_y=true, boolean blocksize_x=true, boolean blocksize_y=true, boolean same_alignment=true, boolean regular_blocking=false, boolean num_bands=true, boolean pixel_types=true, boolean nodata_values=true, boolean out_db=true , boolean extent=true);

boolean DropRasterConstraints(name rastschema, name rasttable, name rastcolumn, text[] constraints);

Description

AddRasterConstraints 가 추가한, 래스터 테이블 열을 참조하는 PostGIS 래스터 제약조건을 삭제합니다. 데이터를 다시 로드하거나 사용자 래스터 열 데이터를 업데이트해야 할 경우 유용합니다. 래스터 테이블 또는 래스터 열을 제거하려고 이 함수를 쓸 필요는 없습니다.

To drop a raster table use standard SQL: DROP TABLE mytable.

To drop just a raster column and leave the rest of the table, use standard SQL: ALTER TABLE mytable DROP COLUMN rast.

열 또는 테이블을 삭제할 경우 raster_columns 카탈로그에서 테이블이 사라질 것입니다. 하지만 제약조건들만 삭제할 경우, 래스터 열은 계속 raster_columns 카탈로그 목록에 남아 있을 것입니다. 그러나 열 및 테이블 명칭을 제외한 정보는 남아 있지 않을 것입니다.

2.0.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT DropRasterConstraints ('myrasters', 'rast');
래스터 출력
droprasterconstraints
-----------------------
 t
(1 row)

Verify change in raster_columns.

Code
SELECT srid, scale_x, scale_y, blocksize_x, blocksize_y, num_bands, pixel_types, nodata_values
    FROM raster_columns
    WHERE r_table_name = 'myrasters';
래스터 출력
srid | scale_x | scale_y | blocksize_x | blocksize_y | num_bands | pixel_types| nodata_values
------+---------+---------+-------------+-------------+-----------+-------------+---------------
    0 |         |         |             |             |           |             |

제목

AddOverviewConstraints — 래스터 열을 또 다른 래스터 열의 미리보기(overview)로 태그합니다.

요약

boolean AddOverviewConstraints(name ovschema, name ovtable, name ovcolumn, name refschema, name reftable, name refcolumn, int ovfactor);

boolean AddOverviewConstraints(name ovtable, name ovcolumn, name reftable, name refcolumn, int ovfactor);

Description

raster_overviews 래스터 카탈로그에 정보를 표출하는 데 쓰이는 래스터 열에 제약조건을 추가합니다.

ovfactor 파라미터는 미리보기 열에 대한 축척 승수(乘數)를 나타냅니다. ovfactor 가 클수록 해상도가 낮아집니다.

ovschemarefschema 파라미터를 생략할 경우, search_path 를 스캔하면서 처음 발견한 테이블을 이용할 것입니다.

2.0.0 버전부터 사용할 수 있습니다.

예시

Verify the raster table is registered correctly in the raster_overviews view.

Code
CREATE TABLE res1 AS SELECT
ST_AddBand(ST_MakeEmptyRaster(1000, 1000, 0, 0, 2),
  1, '8BSI'::text, -129, NULL
) r1;

CREATE TABLE res2 AS SELECT
ST_AddBand(ST_MakeEmptyRaster(500, 500, 0, 0, 4),
  1, '8BSI'::text, -129, NULL
) r2;

SELECT AddOverviewConstraints('res2', 'r2', 'res1', 'r1', 2);
SELECT o_table_name ot, o_raster_column oc,
       r_table_name rt, r_raster_column rc,
       overview_factor f
FROM raster_overviews WHERE o_table_name = 'res2';
래스터 출력
ot  | oc |  rt  | rc | f
------+----+------+----+---
 res2 | r2 | res1 | r1 | 2
(1 row)

제목

DropOverviewConstraints — 또 다른 래스터 열의 미리보기(overview)로서의 래스터 열을 태그 해제합니다.

요약

boolean DropOverviewConstraints(name ovschema, name ovtable, name ovcolumn);

boolean DropOverviewConstraints(name ovtable, name ovcolumn);

Description

raster_overviews 래스터 카탈로그에 또 다른 래스터 열의 미리보기를 표출하는 데 쓰이는 래스터 열의 제약조건을 제거합니다.

ovschema 파라미터를 생략할 경우, search_path 를 스캔하면서 처음 발견한 테이블을 이용할 것입니다.

2.0.0 버전부터 사용할 수 있습니다.


제목

PostGIS_GDAL_Version — PostGIS가 이용하고 있는 GDAL 라이브러리의 버전을 반환합니다.

요약

text PostGIS_GDAL_Version();

Description

PostGIS가 이용하고 있는 GDAL 라이브러리의 버전을 반환합니다. 또 GDAL이 자체 데이터 파일을 찾을 수 있는지도 확인해서 보고할 것입니다.

예시

Code
SELECT PostGIS_GDAL_Version();
래스터 출력
GDAL 1.11dev, released 2013/04/13

제목

PostGIS_Raster_Lib_Build_Date — 전체 래스터 라이브러리의 빌드 날짜를 반환합니다.

요약

text PostGIS_Raster_Lib_Build_Date();

Description

래스터의 빌드 날짜를 보고합니다.

예시

Code
SELECT PostGIS_Raster_Lib_Build_Date();
래스터 출력
2010-04-28 21:15:10

제목

PostGIS_Raster_Lib_Version — 전체 래스터 버전 및 설정 정보를 반환합니다.

요약

text PostGIS_Raster_Lib_Version();

Description

전체 래스터 버전 및 설정 정보를 보고합니다.

예시

Code
SELECT PostGIS_Raster_Lib_Version();
래스터 출력
2.0.0

제목

ST_GDALDrivers — Returns a list of raster formats supported by PostGIS through GDAL. Only those formats with can_write=True can be used by ST_AsGDALRaster

요약

setof record ST_GDALDrivers(integer OUT idx, text OUT short_name, text OUT long_name, text OUT can_read, text OUT can_write, text OUT create_options);

Description

Returns a list of raster formats short_name,long_name and creator options of each format supported by GDAL. Use the short_name as input in the format parameter of ST_AsGDALRaster. Options vary depending on what drivers your libgdal was compiled with. create_options returns an xml formatted set of CreationOptionList/Option consisting of name and optional type, description and set of VALUE for each creator option for the specific driver.

Changed: 2.5.0 - add can_read and can_write columns.

변경 사항: 2.0.6, 2.1.3 버전 - GUC 또는 환경 변수 gdal_enabled_drivers를 설정하지 않을 경우, 기본적으로 어떤 드라이버도 활성화돼 있지 않습니다.

2.0.0 버전부터 사용할 수 있습니다. GDAL 1.6.0 이상 버전이 필요합니다.

예시

List of Drivers.

Code
SET postgis.gdal_enabled_drivers = 'ENABLE_ALL';
SELECT short_name, long_name, can_write
FROM ST_GDALDrivers()
ORDER BY short_name;
래스터 출력
short_name    |                          long_name                          | can_write
-----------------+-------------------------------------------------------------+-----------
 AAIGrid         | Arc/Info ASCII Grid                                         | t
 ACE2            | ACE2                                                        | f
 ADRG            | ARC Digitized Raster Graphics                               | f
 AIG             | Arc/Info Binary Grid                                        | f
 AirSAR          | AirSAR Polarimetric Image                                   | f
 ARG             | Azavea Raster Grid format                                   | t
 BAG             | Bathymetry Attributed Grid                                  | f
 BIGGIF          | Graphics Interchange Format (.gif)                          | f
 BLX             | Magellan topo (.blx)                                        | t
 BMP             | MS Windows Device Independent Bitmap                        | f
 BSB             | Maptech BSB Nautical Charts                                 | f
 PAux            | PCI .aux Labelled                                           | f
 PCIDSK          | PCIDSK Database File                                        | f
 PCRaster        | PCRaster Raster File                                        | f
 PDF             | Geospatial PDF                                              | f
 PDS             | NASA Planetary Data System                                  | f
 PDS4            | NASA Planetary Data System 4                                | t
 PLMOSAIC        | Planet Labs Mosaics API                                     | f
 PLSCENES        | Planet Labs Scenes API                                      | f
 PNG             | Portable Network Graphics                                   | t
 PNM             | Portable Pixmap Format (netpbm)                             | f
 PRF             | Racurs PHOTOMOD PRF                                         | f
 R               | R Object Data Store                                         | t
 Rasterlite      | Rasterlite                                                  | t
 RDA             | DigitalGlobe Raster Data Access driver                      | f
 RIK             | Swedish Grid RIK (.rik)                                     | f
 RMF             | Raster Matrix Format                                        | f
 ROI_PAC         | ROI_PAC raster                                              | f
 RPFTOC          | Raster Product Format TOC format                            | f
 RRASTER         | R Raster                                                    | f
 RS2             | RadarSat 2 XML Product                                      | f
 RST             | Idrisi Raster A.1                                           | t
 SAFE            | Sentinel-1 SAR SAFE Product                                 | f
 SAGA            | SAGA GIS Binary Grid (.sdat, .sg-grd-z)                     | t
 SAR_CEOS        | CEOS SAR Image                                              | f
 SDTS            | SDTS Raster                                                 | f
 SENTINEL2       | Sentinel 2                                                  | f
 SGI             | SGI Image File Format 1.0                                   | f
 SNODAS          | Snow Data Assimilation System                               | f
 SRP             | Standard Raster Product (ASRP/USRP)                         | f
 SRTMHGT         | SRTMHGT File Format                                         | t
 Terragen        | Terragen heightfield                                        | f
 TIL             | EarthWatch .TIL                                             | f
 TSX             | TerraSAR-X Product                                          | f
 USGSDEM         | USGS Optional ASCII DEM (and CDED)                          | t
 VICAR           | MIPL VICAR file                                             | f
 VRT             | Virtual Raster                                              | t
 WCS             | OGC Web Coverage Service                                    | f
 WMS             | OGC Web Map Service                                         | t
 WMTS            | OGC Web Map Tile Service                                    | t
 XPM             | X11 PixMap Format                                           | t
 XYZ             | ASCII Gridded XYZ                                           | t
 ZMap            | ZMap Plus Grid                                              | t

List of options for each driver.

Output the create options XML column of JPEG as a table. These creator options can be used in the ST_AsGDALRaster options argument.

Code
SELECT (xpath('@name', g.opt))[1]::text As oname,
       (xpath('@type', g.opt))[1]::text As otype,
       (xpath('@description', g.opt))[1]::text As descrip
FROM (SELECT unnest(xpath('/CreationOptionList/Option', create_options::xml)) As opt
FROM  ST_GDALDrivers()
WHERE short_name = 'JPEG') As g;
래스터 출력
oname        |  otype  |      descrip
--------------------+---------+-------------------------------------------------
 PROGRESSIVE        | boolean | whether to generate a progressive JPEG
 QUALITY            | int     | good=100, bad=0, default=75
 WORLDFILE          | boolean | whether to generate a worldfile
 INTERNAL_MASK      | boolean | whether to generate a validity mask
 COMMENT            | string  | Comment
 SOURCE_ICC_PROFILE | string  | ICC profile encoded in Base64
 EXIF_THUMBNAIL     | boolean | whether to generate an EXIF thumbnail(overview).
                                By default its max dimension will be 128
 THUMBNAIL_WIDTH    | int     | Forced thumbnail width
 THUMBNAIL_HEIGHT   | int     | Forced thumbnail height
(9 rows)

This example turns a few common GeoTIFF creator options into a compact table.

Code
WITH gtiff_options AS (
    SELECT
        option_name,
        option_type,
        default_value
    FROM ST_GDALDrivers() AS driver
    CROSS JOIN LATERAL XMLTABLE(
        '/CreationOptionList/Option'
        PASSING (driver.create_options::xml)
        COLUMNS
            option_name text PATH '@name',
            option_type text PATH '@type',
            default_value text PATH '@default'
    ) AS options
    WHERE driver.short_name = 'GTiff'
)
SELECT option_name AS name, option_type AS type, coalesce(default_value, '') AS default_value
FROM gtiff_options
WHERE option_name = ANY (ARRAY[
    'COMPRESS',
    'INTERLEAVE',
    'TILED',
    'BLOCKXSIZE',
    'BLOCKYSIZE',
    'JPEG_QUALITY'
])
ORDER BY 1;
래스터 출력
name      |     type      | default_value
---------------+---------------+---------------
 BLOCKXSIZE    | int           |
 BLOCKYSIZE    | int           |
 COMPRESS      | string-select |
 INTERLEAVE    | string-select | PIXEL
 JPEG_QUALITY  | int           | 75
 TILED         | boolean       |
(6 rows)

Use XMLTABLE to expose selected GTiff creation options as rows. The same pattern can be used without the name filter to inspect the full XML document.

Code
SET postgis.gdal_enabled_drivers = 'ENABLE_ALL';

SELECT option_name, option_type
FROM ST_GDALDrivers() AS driver
CROSS JOIN LATERAL XMLTABLE(
    '/CreationOptionList/Option'
    PASSING (driver.create_options::xml)
    COLUMNS
        option_name text PATH '@name',
        option_type text PATH '@type'
) AS options
WHERE driver.short_name = 'GTiff'
  AND option_name IN ('COMPRESS', 'TILED', 'BIGTIFF')
ORDER BY option_name;
래스터 출력
option_name |  option_type
-------------+---------------
 BIGTIFF     | string-select
 COMPRESS    | string-select
 TILED       | boolean
(3 rows)

제목

UpdateRasterSRID — 사용자가 지정한 열 및 테이블에 있는 모든 래스터의 SRID를 변경합니다.

요약

raster UpdateRasterSRID(name schema_name, name table_name, name column_name, integer new_srid);

raster UpdateRasterSRID(name table_name, name column_name, integer new_srid);

Description

사용자가 지정한 열 및 테이블에 있는 모든 래스터의 SRID를 변경합니다. 이 함수는 지정한 열의 래스터의 SRID를 변경하기 전에 적절한 모든 열 제약조건들(범위, 정렬 방향 및 SRID)을 삭제할 것입니다.

[참고]

래스터의 데이터(밴드 픽셀 값)를 건드리지는 않습니다. 래스터의 메타데이터만 변경합니다.

2.1.0 버전부터 사용할 수 있습니다.


제목

ST_CreateOverview — 입력 래스터 커버리지의 저해상도 버전을 생성합니다.

요약

regclass ST_CreateOverview(regclass tab, name col, int factor, text algo='NearestNeighbor');

Description

소스 테이블로부터 리샘플링한 타일들을 담은 미리보기 테이블을 생성합니다. 출력 타일은 입력 타일과 크기가 동일하고, 더 낮은 해상도로 동일한 공간 범위를 커버합니다(픽셀 크기는 양방향 모두 원본의 1/factor 이 될 것입니다).

raster_overviews 카탈로그에서 이 미리보기 테이블을 사용할 수 있게 되고, 래스터 제약조건도 강제될 것입니다.

알고리즘 옵션에는 'NearestNeighbor', 'Bilinear', 'Cubic', 'CubicSpline', 그리고 'Lanczos'가 있습니다. 자세한 내용은 GDAL Warp resampling methods 를 참조하십시오.

2.2.0 버전부터 사용할 수 있습니다.

예시

Output to generally better quality but slower to product format

Code
SELECT ST_CreateOverview('mydata.mytable'::regclass, 'rast', 2, 'Lanczos');

Output to faster to process default nearest neighbor

Code
SELECT ST_CreateOverview('mydata.mytable'::regclass, 'rast', 2);

11.3. 래스터 작성자(constructor)

  • ST_AddBand — 입력 인덱스 위치에 입력 초기값으로 추가된 입력 유형의 새 밴드(들)을 가진 래스터를 반환합니다. 인덱스를 설정하지 않을 경우, 마지막 위치에 밴드를 추가합니다.
  • ST_AsRaster — PostGIS 도형을 PostGIS 래스터로 변환합니다.
  • ST_AsRasterAgg — Aggregate. Renders PostGIS geometries into a new raster.
  • ST_Band — 기존 래스터의 하나 이상의 밴드를 새 래스터로 반환합니다. 기존 래스터로부터 새 래스터를 빌드하는 데 유용합니다.
  • ST_MakeEmptyCoverage — Cover georeferenced area with a grid of empty raster tiles.
  • ST_MakeEmptyRaster — 설정된 차원(너비 & 높이), 좌상단 X 및 Y, 픽셀 크기, 회전(scalex, scaley, skewx & skewy) 그리고 공간 참조 시스템(SRID)를 가진 텅 빈 (밴드가 없는) 래스터를 반환합니다. 래스터를 입력할 경우, 동일한 크기, 정렬 방향 및 SRID를 가진 새 래스터를 반환합니다. SRID를 생략할 경우, 공간 참조 시스템을 0(unknown)으로 설정합니다.
  • ST_Tile — 출력 래스터에 원하는 차원을 바탕으로 입력 래스터를 분할해서 나온 래스터들의 집합을 반환합니다.
  • ST_Retile — 임의로 타일화된 래스터 커버리지로부터, 설정된 타일들의 집합을 반환합니다.
  • ST_FromGDALRaster — 지원 GDAL 래스터 파일로부터 래스터를 반환합니다.

제목

ST_AddBand — 입력 인덱스 위치에 입력 초기값으로 추가된 입력 유형의 새 밴드(들)을 가진 래스터를 반환합니다. 인덱스를 설정하지 않을 경우, 마지막 위치에 밴드를 추가합니다.

요약

(1) raster ST_AddBand(raster rast, addbandarg[] addbandargset);

(2) raster ST_AddBand(raster rast, integer index, text pixeltype, double precision initialvalue=0, double precision nodataval=NULL);

(3) raster ST_AddBand(raster rast, text pixeltype, double precision initialvalue=0, double precision nodataval=NULL);

(4) raster ST_AddBand(raster torast, raster fromrast, integer fromband=1, integer torastindex=at_end);

(5) raster ST_AddBand(raster torast, raster[] fromrasts, integer fromband=1, integer torastindex=at_end);

(6) raster ST_AddBand(raster rast, integer index, text outdbfile, integer[] outdbindex, double precision nodataval=NULL);

(7) raster ST_AddBand(raster rast, text outdbfile, integer[] outdbindex, integer index=at_end, double precision nodataval=NULL);

Description

Returns a raster with a new band added in given position (index), of given type, of given initial value, and of given nodata value. If no index is specified, the band is added to the end. If no fromband is specified, band 1 is assumed. Pixel type is a string representation of one of the pixel types specified in ST_BandPixelType. If an existing index is specified all subsequent bands >= that index are incremented by 1. If an initial value greater than the max of the pixel type is specified, then the initial value is set to the highest value allowed by the pixel type.

addbandarg 의 배열을 입력받는 변종 1의 경우, 특정 addbandarg의 인덱스 값은 addbandarg가 묘사하는 밴드가 래스터에 추가될 당시의 해당 래스터에 상대적입니다. 다음에 나오는 복수의 새로운 밴드 예시를 참고하십시오.

래스터 배열을 입력받는 변종 5의 경우, torast 가 NULL이라면 배열 안에 있는 각 래스터의 fromband 밴드를 새 래스터에 누계(累計)합니다.

outdbfile 을 입력받는 변종 6 및 7의 경우, outdbfile 값이 래스터 파일을 가리키는 전체 경로를 포함해야만 합니다. PostgreSQL 서버 프로세스도 해당 파일에 접근할 수 있어야만 합니다.

개선 사항: 2.1.0 버전부터 addbandarg를 지원합니다.

개선 사항: 2.1.0 버전부터 새로운 DB 외부 밴드를 지원합니다.

예시

Single New Band.

This example adds another 8-bit unsigned integer band with pixels initialized to 200.

Code
UPDATE dummy_rast
    SET rast = ST_AddBand(rast, '8BUI'::text, 200)
WHERE rid = 1;
                

Create an empty raster 100x100 units, with upper left right at 0, add 2 bands (band 1 is 0/1 boolean bit switch, band2 allows values 0-15) Uses addbandargs.

Output metadata for the raster bands to verify they are correct.

Code
INSERT INTO dummy_rast(rid, rast)
    VALUES(10, ST_AddBand(ST_MakeEmptyRaster(100, 100, 0, 0, 1, -1, 0, 0, 0),
    ARRAY[
        ROW(1, '1BB'::text, 0, NULL),
        ROW(2, '4BUI'::text, 0, NULL)
            ]::addbandarg[]
     )
    );

SELECT  (bmd).*
FROM (SELECT ST_BandMetaData(rast, generate_series(1, 2)) As bmd
    FROM dummy_rast WHERE rid = 10) AS foo;
래스터 출력
pixeltype | nodatavalue | isoutdb | path
-----------+----------------+-------------+---------+------
 1BB       |             | f       |
 4BUI      |             | f       |

This example outputs metadata for the raster.

Code
SELECT  (rmd).width, (rmd).height, (rmd).numbands
FROM (SELECT ST_MetaData(rast) As rmd
    FROM dummy_rast WHERE rid = 10) AS foo;
래스터 출력
width | height | numbands
-------+--------+----------
   100 |    100 |        2

Multiple New Bands.

Code
SELECT
    *
FROM ST_BandMetaData(ST_AddBand(ST_MakeEmptyRaster(10, 10, 0, 0, 1, -1, 0, 0, 0),
        ARRAY[
            ROW(NULL, '8BUI', 255, 0),
            ROW(NULL, '16BUI', 1, 2),
            ROW(2, '32BUI', 100, 12),
            ROW(2, '32BF', 3.14, -1)
        ]::addbandarg[]
    ),
    ARRAY[]::integer[]
);
래스터 출력
bandnum | pixeltype | nodatavalue | isoutdb | path | outdbbandnum | filesize | filetimestamp
---------+-----------+-------------+---------+------+--------------+----------+---------------
       1 | 8BUI      |           0 | f       | null |         null |     null |          null
       2 | 32BF      |          -1 | f       | null |         null |     null |          null
       3 | 32BUI     |          12 | f       | null |         null |     null |          null
       4 | 16BUI     |           2 | f       | null |         null |     null |          null

Aggregate the 1st band of a table of like rasters into a single raster. With as many bands as there are test_types and as many rows (new rasters) as there are mice. Note that The ORDER BY test_type clause relies on aggregate ORDER BY support. The resulting raster will have a band for each test_type alphabetical by test_type. For mouse lovers: No mice were harmed in this exercise.

Code
SELECT
    mouse,
    ST_AddBand(NULL, array_agg(rast ORDER BY test_type), 1) As rast
FROM mice_studies
GROUP BY mouse;
                

New Out-db band.

Code
SELECT
    *
FROM ST_BandMetaData(ST_AddBand(ST_MakeEmptyRaster(10, 10, 0, 0, 1, -1, 0, 0, 0),
        '/home/raster/mytestraster.tif'::text, NULL::int[]
    ),
    ARRAY[]::integer[]
);
래스터 출력
bandnum | pixeltype | nodatavalue | isoutdb | path
---------+-----------+-------------+---------+------
       1 | 8BUI      |             | t       | /home/raster/mytestraster.tif
       2 | 8BUI      |             | t       | /home/raster/mytestraster.tif
       3 | 8BUI      |             | t       | /home/raster/mytestraster.tif

제목

ST_AsRaster — PostGIS 도형을 PostGIS 래스터로 변환합니다.

요약

raster ST_AsRaster(geometry geom, raster ref, text pixeltype, double precision value=1, double precision nodataval=0, boolean touched=false);

raster ST_AsRaster(geometry geom, raster ref, text[] pixeltype=ARRAY['8BUI'], double precision[] value=ARRAY[1], double precision[] nodataval=ARRAY[0], boolean touched=false);

raster ST_AsRaster(geometry geom, double precision scalex, double precision scaley, double precision gridx, double precision gridy, text pixeltype, double precision value=1, double precision nodataval=0, double precision skewx=0, double precision skewy=0, boolean touched=false);

raster ST_AsRaster(geometry geom, double precision scalex, double precision scaley, double precision gridx=NULL, double precision gridy=NULL, text[] pixeltype=ARRAY['8BUI'], double precision[] value=ARRAY[1], double precision[] nodataval=ARRAY[0], double precision skewx=0, double precision skewy=0, boolean touched=false);

raster ST_AsRaster(geometry geom, double precision scalex, double precision scaley, text pixeltype, double precision value=1, double precision nodataval=0, double precision upperleftx=NULL, double precision upperlefty=NULL, double precision skewx=0, double precision skewy=0, boolean touched=false);

raster ST_AsRaster(geometry geom, double precision scalex, double precision scaley, text[] pixeltype, double precision[] value=ARRAY[1], double precision[] nodataval=ARRAY[0], double precision upperleftx=NULL, double precision upperlefty=NULL, double precision skewx=0, double precision skewy=0, boolean touched=false);

raster ST_AsRaster(geometry geom, integer width, integer height, double precision gridx, double precision gridy, text pixeltype, double precision value=1, double precision nodataval=0, double precision skewx=0, double precision skewy=0, boolean touched=false);

raster ST_AsRaster(geometry geom, integer width, integer height, double precision gridx=NULL, double precision gridy=NULL, text[] pixeltype=ARRAY['8BUI'], double precision[] value=ARRAY[1], double precision[] nodataval=ARRAY[0], double precision skewx=0, double precision skewy=0, boolean touched=false);

raster ST_AsRaster(geometry geom, integer width, integer height, text pixeltype, double precision value=1, double precision nodataval=0, double precision upperleftx=NULL, double precision upperlefty=NULL, double precision skewx=0, double precision skewy=0, boolean touched=false);

raster ST_AsRaster(geometry geom, integer width, integer height, text[] pixeltype, double precision[] value=ARRAY[1], double precision[] nodataval=ARRAY[0], double precision upperleftx=NULL, double precision upperlefty=NULL, double precision skewx=0, double precision skewy=0, boolean touched=false);

Description

PostGIS 도형을 PostGIS 래스터로 변환합니다. 다양한 변종들을 통해 출력 래스터의 정렬 방향과 픽셀 크기를 크게 세 가지 방법으로 설정할 수 있습니다.

처음 두 변종으로 이루어진 첫 번째 방법은 주어진 참조 래스터와 동일한 정렬 방향(scalex, scaleygridx, gridy), 픽셀 유형, NODATA 값을 가진 래스터를 생성합니다. 일반적으로, 참조 래스터를 담고 있는 테이블과 도형을 담고 있는 테이블을 결합하는 방법으로 해당 참조 래스터를 입력합니다.

네 변종으로 이루어진 두 번째 방법은 픽셀 크기(scalex & scaleyskewx & skewy)의 파라미터를 제공, 사용자가 래스터의 차원을 설정할 수 있도록 합니다. 결과 래스터의 width & height 가 도형의 범위에 맞도록 조정될 것입니다. 대부분의 경우, 정수형 scalex & scaley 인수들을 PostgreSQL이 올바른 변종을 선택하도록 이중 정밀도 데이터형으로 형변환해야만 합니다.

네 변종으로 이루어진 세 번째 방법은 래스터의 차원(width & height)을 제공, 사용자가 래스터의 차원을 수정할 수 있도록 합니다. 결과 래스터의 픽셀 크기 파라미터(scalex & scaleyskewx & skewy)가 도형의 범위에 맞도록 조정될 것입니다.

뒤의 두 방법 가운데 각 방법의 처음 두 변종들은 사용자가 정렬 그리드의 임의의 모서리(gridx & gridy)를 설정할 수 있도록 합니다. 다른 두 변종들은 좌상단(upperleftx & upperlefty))을 입력받습니다.

각 방법의 변종은 단일 밴드 래스터 또는 복수 밴드 래스터를 생성할 수 있게 해줍니다. 복수 밴드 래스터를 생성하려면, 사용자가 픽셀 유형의 배열(pixeltype[]), 초기값의 배열(value) 그리고 NODTATA 값의 배열(nodataval)을 준비해야만 합니다. 이들을 입력하지 않으면, 기본적으로 픽셀 유형은 8BUI, 초기값은 1, NODATA 값은 0이 됩니다.

출력 래스터는 소스 도형과 동일한 공간 참조 시스템을 가지게 됩니다. 유일한 예외는 참조 래스터를 받는 변종들뿐입니다. 이런 경우 결과 래스터는 참조 래스터와 동일한 SRID를 가지게 됩니다.

선택적인 touched 파라미터의 기본값은 거짓으로 GDAL ALL_TOUCHED 래스터화 옵션에 매핑되는데, 이 옵션은 라인 또는 폴리곤에 닿은 픽셀을 없앨 것인지 말 것인지 결정합니다. 렌더링된 라인 경로 상에 있는 픽셀만이 아니라, 그 중심점이 폴리곤 내부에 있는 픽셀 또한 말이죠.

이 함수는 ST_AsPNG 및 다른 ST_AsGDALRaster 계열 함수와 결합해서 사용할 때 데이터베이스로부터 직접 가져온 도형의 JPEG 또는 PNG를 렌더링하는 데 특히 유용합니다.

2.0.0 버전부터 사용할 수 있습니다. GDAL 1.6.0 이상 버전이 필요합니다.

Curved geometry inputs are linearized before rasterization, including NURBSCurve inputs handled by PostGIS. TIN and PolyhedralSurface inputs are not supported.

예시: PNG 파일로 도형을 출력

This example outputs a black circle on a white background, occupying 150 by 150 pixels.

Code
SELECT ST_AsPNG(
    ST_AsRaster(
        ST_Buffer(ST_Point(1, 5), 10),
        150, 150,
        ARRAY['8BUI', '8BUI', '8BUI'],
        ARRAY[0, 0, 0],
        ARRAY[255, 255, 255]
    )
) AS image;
래스터 출력
image
-------------------------------
 PNG image, 150 x 150 pixels
                
Figure
Geometry figure for visual-rt-st-asraster-01

This example maps bands to RGB channels, producing the teal value (118,154,118).

Code
SELECT ST_AsPNG(
    ST_AsRaster(
        ST_Buffer('LINESTRING(50 50,150 150,150 50)'::geometry, 10, 'join=bevel'),
        200, 200,
        ARRAY['8BUI', '8BUI', '8BUI'],
        ARRAY[118, 154, 118],
        ARRAY[255, 255, 255]
    )
) AS image;
래스터 출력
image
-------------------------------
 PNG image, 200 x 200 pixels
                
Figure
Geometry figure for visual-rt-st-asraster-02

제목

ST_AsRasterAgg — Aggregate. Renders PostGIS geometries into a new raster.

요약

raster ST_AsRasterAgg(geometry geom, double precision val, raster ref, text pixeltype, double precision nodataval, text uniontype, boolean touched);

Description

Returns a single-band raster containing the rendered version of all incoming geometries, each with its associated value.

Availability: 3.6.0

예시

Code
WITH inp(g, v) AS (
    VALUES
        ( ST_Buffer(ST_MakePoint(10, 0), 10), 1 ),
        ( ST_Buffer(ST_MakePoint(20, 0), 10), 2 )
),
agg AS (
    SELECT ST_AsRasterAgg(
        g,
        v,
        ST_MakeEmptyRaster(0, 0, 0, 0, 1.0),
        '8BUI',
        99,
        'SUM',
        true
    ) r
    FROM inp
)
SELECT
    ST_Width(r) w,
    ST_Height(r) h,
    ST_Value(r, 'POINT(5 0)') v5_0,
    ST_Value(r, 'POINT(15 0)') v15_0,
    ST_Value(r, 'POINT(25 0)') v25_0
FROM agg;
래스터 출력
w  | h  | v5_0 | v15_0 | v25_0
----+----+------+-------+-------
 30 | 20 |    1 |     3 |     2
(1 row)

제목

ST_Band — 기존 래스터의 하나 이상의 밴드를 새 래스터로 반환합니다. 기존 래스터로부터 새 래스터를 빌드하는 데 유용합니다.

요약

raster ST_Band(raster rast, integer[] nbands = ARRAY[1]);

raster ST_Band(raster rast, integer nband);

raster ST_Band(raster rast, text nbands, character delimiter=,);

Description

Returns one or more bands of an existing raster as a new raster. Useful for building new rasters from existing rasters or export of only selected bands of a raster or rearranging the order of bands in a raster. If no band is specified or any of specified bands does not exist in the raster, then all bands are returned. Used as a helper function in various functions such as for deleting a band.

[주의]

이 함수의 텍스트 변종으로 nbands 의 경우, 기본 구분자가 ,'1,2,3' 과 같은 서식으로 지정할 수 있다는 뜻입니다. 다른 구분자를 쓰고 싶은 경우 ST_Band(rast, '1@2@3', '@') 와 같은 서식을 이용하면 됩니다. 복수의 밴드를 지정하는 경우, 사용자가 이 함수의 ST_Band(rast, '{1,2,3}'::int[]); 와 같은 배열 서식을 이용하도록 강력히 권고합니다. PostGIS 향후 버전에서 밴드들의 text 목록 서식이 제거될 수도 있기 때문입니다.

2.0.0 버전부터 사용할 수 있습니다.

예시

This example creates two rasters: one containing band 1 of dummy_rast, and one containing band 2 reclassified as 2BUI.

Code
SELECT ST_NumBands(rast1) As numb1, ST_BandPixelType(rast1) As pix1,
 ST_NumBands(rast2) As numb2, ST_BandPixelType(rast2) As pix2
FROM (
    SELECT ST_Band(rast) As rast1, ST_Reclass(ST_Band(rast, 3), '100-200):1, [200-254:2', '2BUI') As rast2
        FROM dummy_rast
        WHERE rid = 2) As foo;
래스터 출력
numb1 | pix1 | numb2 | pix2
-------+------+-------+------
     1 | 8BUI |     1 | 2BUI

Return bands 2 and 3 using array cast syntax.

Code
SELECT ST_NumBands(ST_Band(rast, '{2,3}'::int[])) As num_bands
FROM dummy_rast WHERE rid=2;
래스터 출력
2

Return bands 2 and 3 using array syntax.

Code
SELECT ST_NumBands(ST_Band(rast, ARRAY[2, 3])) As num_bands
    FROM dummy_rast
WHERE rid=2;
                    
래스터 출력
2

This example uses three distinct shapes as the red, green, and blue bands of a synthetic raster. It compares the original RGB raster with band 2 followed by band 1 twice, and with band 3 alone.

Code
WITH canvas AS (
    SELECT ST_AddBand(
        ST_AddBand(
            ST_AddBand(
                ST_MakeEmptyRaster(128, 128, 0, 128, 1, -1, 0, 0, 0),
                '8BUI'::text, 0::double precision, 0::double precision
            ),
            '8BUI'::text, 0::double precision, 0::double precision
        ),
        '8BUI'::text, 0::double precision, 0::double precision
    ) AS rast
), bands AS (
    SELECT ST_SetValue(
        ST_SetValue(
            ST_SetValue(rast, 1, ST_Buffer('POINT(32 96)'::geometry, 22), 220),
            2, ST_Buffer('LINESTRING(18 20,110 110)'::geometry, 6,
                         'endcap=flat join=bevel'), 210
        ),
        3, ST_Buffer('LINESTRING(10 48,118 48)'::geometry, 7,
                     'endcap=flat'), 180
    ) AS rast
    FROM canvas
)
SELECT ST_AsPNG(rast) AS "original RGB",
    ST_AsPNG(ST_Band(rast, ARRAY[2, 1, 1])) AS "bands 2,1,1",
    ST_AsPNG(ST_Band(rast, 3)) AS "band 3"
FROM bands;
                    
래스터 출력
original RGB                | bands 2,1,1                | band 3
-----------------------------+----------------------------+----------------------------
 PNG image, 128 x 128 pixels | PNG image, 128 x 128 pixels | PNG image, 128 x 128 pixels
Figure
Geometry figure for visual-rt-st-band-04

Band selection from a multi-band raster.

원본(rast 열)

dupe_band

sing_band


제목

ST_MakeEmptyCoverage — Cover georeferenced area with a grid of empty raster tiles.

요약

raster ST_MakeEmptyCoverage(integer tilewidth, integer tileheight, integer width, integer height, double precision upperleftx, double precision upperlefty, double precision scalex, double precision scaley, double precision skewx, double precision skewy, integer srid=unknown);

Description

Create a set of raster tiles with ST_MakeEmptyRaster. Grid dimension is width & height. Tile dimension is tilewidth & tileheight. The covered georeferenced area is from upper left corner (upperleftx, upperlefty) to lower right corner (upperleftx + width * scalex, upperlefty + height * scaley).

[참고]

Note that scaley is generally negative for rasters and scalex is generally positive. So lower right corner will have a lower y value and higher x value than the upper left corner.

2.2.0 버전부터 사용할 수 있습니다.

기본 예시

Create 16 tiles in a 4x4 grid to cover the WGS84 area from upper left corner (22, 77) to lower right corner (55, 33).

Code
SELECT (ST_MetaData(tile)).* FROM ST_MakeEmptyCoverage(1, 1, 4, 4, 22, 33, (55 - 22)/(4)::float, (33 - 77)/(4)::float, 0., 0., 4326) tile;
래스터 출력
upperleftx | upperlefty | width | height | scalex | scaley | skewx | skewy | srid | numbands
-------------------------------------------------------------------------------------
         22 |         33 |     1 |      1 |   8.25 |    -11 |     0 |     0 | 4326 |        0
      30.25 |         33 |     1 |      1 |   8.25 |    -11 |     0 |     0 | 4326 |        0
       38.5 |         33 |     1 |      1 |   8.25 |    -11 |     0 |     0 | 4326 |        0
      46.75 |         33 |     1 |      1 |   8.25 |    -11 |     0 |     0 | 4326 |        0
         22 |         22 |     1 |      1 |   8.25 |    -11 |     0 |     0 | 4326 |        0
      30.25 |         22 |     1 |      1 |   8.25 |    -11 |     0 |     0 | 4326 |        0
       38.5 |         22 |     1 |      1 |   8.25 |    -11 |     0 |     0 | 4326 |        0
      46.75 |         22 |     1 |      1 |   8.25 |    -11 |     0 |     0 | 4326 |        0
         22 |         11 |     1 |      1 |   8.25 |    -11 |     0 |     0 | 4326 |        0
      30.25 |         11 |     1 |      1 |   8.25 |    -11 |     0 |     0 | 4326 |        0
       38.5 |         11 |     1 |      1 |   8.25 |    -11 |     0 |     0 | 4326 |        0
      46.75 |         11 |     1 |      1 |   8.25 |    -11 |     0 |     0 | 4326 |        0
         22 |          0 |     1 |      1 |   8.25 |    -11 |     0 |     0 | 4326 |        0
      30.25 |          0 |     1 |      1 |   8.25 |    -11 |     0 |     0 | 4326 |        0
       38.5 |          0 |     1 |      1 |   8.25 |    -11 |     0 |     0 | 4326 |        0
      46.75 |          0 |     1 |      1 |   8.25 |    -11 |     0 |     0 | 4326 |        0

제목

ST_MakeEmptyRaster — 설정된 차원(너비 & 높이), 좌상단 X 및 Y, 픽셀 크기, 회전(scalex, scaley, skewx & skewy) 그리고 공간 참조 시스템(SRID)를 가진 텅 빈 (밴드가 없는) 래스터를 반환합니다. 래스터를 입력할 경우, 동일한 크기, 정렬 방향 및 SRID를 가진 새 래스터를 반환합니다. SRID를 생략할 경우, 공간 참조 시스템을 0(unknown)으로 설정합니다.

요약

raster ST_MakeEmptyRaster(raster rast);

raster ST_MakeEmptyRaster(integer width, integer height, float8 upperleftx, float8 upperlefty, float8 scalex, float8 scaley, float8 skewx, float8 skewy, integer srid=unknown);

raster ST_MakeEmptyRaster(integer width, integer height, float8 upperleftx, float8 upperlefty, float8 pixelsize);

Description

설정된 차원(너비 & 높이), 공간 (또는 월드) 좌표로 지리참조된 좌상단 X(upperleftx) 및 좌상단 Y(upperlefty), 픽셀 크기, 회전(scalex, scaley, skewx & skewy) 그리고 공간 참조 시스템(SRID)를 가진 텅 빈 (밴드가 없는) 래스터를 반환합니다.

지난 버전은 픽셀 크기(pixelsize)를 설정하기 위한 단일 파라미터만 사용했습니다. scalex는 이 인수로 설정됐고, scaley는 이 인수의 음의 값으로 설정됐습니다. skewx 및 skewy는 0으로 설정됐습니다.

기존 래스터를 입력할 경우, 동일한 메타데이터 설정을 가진 (밴드가 없는) 새 래스터를 반환합니다.

어떤 SRID도 설정하지 않을 경우 기본값은 0입니다. 텅 빈 래스터를 생성한 다음 사용자가 밴드를 추가하거나 편집하려 할 수도 있습니다. 밴드를 정의하려면 ST_AddBand 를, 기본 픽셀 값을 설정하려면 ST_SetValue 를 참조하십시오.

예시

Use an existing raster as a template and output metadata of the rasters we added.

Code
INSERT INTO dummy_rast(rid, rast)
VALUES(3, ST_MakeEmptyRaster(100, 100, 0.0005, 0.0005, 1, 1, 0, 0, 4326) );
INSERT INTO dummy_rast(rid, rast)
SELECT 4, ST_MakeEmptyRaster(rast)
FROM dummy_rast WHERE rid = 3;
SELECT
    rid,
    (md).width,
    (md).height,
    (md).scalex,
    (md).scaley,
    (md).srid
FROM (
    SELECT rid, ST_MetaData(rast) AS md
    FROM dummy_rast
    WHERE rid IN (3, 4)
) AS foo
ORDER BY rid;
래스터 출력
rid | width | height | scalex | scaley | srid
-----+-------+--------+--------+--------+------
   3 |   100 |    100 |      1 |      1 | 4326
   4 |   100 |    100 |      1 |      1 | 4326

제목

ST_Tile — 출력 래스터에 원하는 차원을 바탕으로 입력 래스터를 분할해서 나온 래스터들의 집합을 반환합니다.

요약

setof raster ST_Tile(raster rast, int[] nband, integer width, integer height, boolean padwithnodata=FALSE, double precision nodataval=NULL);

setof raster ST_Tile(raster rast, integer nband, integer width, integer height, boolean padwithnodata=FALSE, double precision nodataval=NULL);

setof raster ST_Tile(raster rast, integer width, integer height, boolean padwithnodata=FALSE, double precision nodataval=NULL);

Description

출력 래스터에 원하는 차원을 바탕으로 입력 래스터를 분할해서 나온 래스터들의 집합을 반환합니다.

padwithnodata = FALSE일 경우, 래스터 우단 및 하단의 가장자리 타일들이 나머지 타일들과 다른 차원을 가지고 있을지도 모릅니다. padwithnodata = TRUE일 경우, 모든 타일들이 동일한 차원을 가지게 되지만 가장자리 타일들이 NODATA 값으로 패딩(padding)됐을 가능성이 있습니다. 래스터 밴드(들)이 지정된 NODATA 값(들)을 가지지 않은 경우, nodataval 을 설정해서 NODATA 값을 지정할 수 있습니다.

[참고]

입력 래스터의 지정된 밴드가 DB 외부 밴드일 경우, 출력 래스터의 해당 밴드 또한 DB 외부 밴드일 것입니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

Code
WITH foo AS (
    SELECT ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 0, 0, 1, -1, 0, 0, 0), 1, '8BUI', 1, 0), 2, '8BUI', 10, 0) AS rast UNION ALL
    SELECT ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 3, 0, 1, -1, 0, 0, 0), 1, '8BUI', 2, 0), 2, '8BUI', 20, 0) AS rast UNION ALL
    SELECT ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 6, 0, 1, -1, 0, 0, 0), 1, '8BUI', 3, 0), 2, '8BUI', 30, 0) AS rast UNION ALL

    SELECT ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 0, -3, 1, -1, 0, 0, 0), 1, '8BUI', 4, 0), 2, '8BUI', 40, 0) AS rast UNION ALL
    SELECT ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 3, -3, 1, -1, 0, 0, 0), 1, '8BUI', 5, 0), 2, '8BUI', 50, 0) AS rast UNION ALL
    SELECT ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 6, -3, 1, -1, 0, 0, 0), 1, '8BUI', 6, 0), 2, '8BUI', 60, 0) AS rast UNION ALL

    SELECT ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 0, -6, 1, -1, 0, 0, 0), 1, '8BUI', 7, 0), 2, '8BUI', 70, 0) AS rast UNION ALL
    SELECT ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 3, -6, 1, -1, 0, 0, 0), 1, '8BUI', 8, 0), 2, '8BUI', 80, 0) AS rast UNION ALL
    SELECT ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 6, -6, 1, -1, 0, 0, 0), 1, '8BUI', 9, 0), 2, '8BUI', 90, 0) AS rast
), bar AS (
    SELECT ST_Union(rast) AS rast FROM foo
), baz AS (
    SELECT
        row_number() OVER (
            ORDER BY ST_UpperLeftY(rast) DESC, ST_UpperLeftX(rast)
        ) AS tile_id,
        rast
    FROM (
        SELECT ST_Tile(rast, 3, 3, TRUE) AS rast
        FROM bar
    ) AS tiled
)
SELECT
    tile_id,
    ST_UpperLeftX(rast) AS ulx,
    ST_UpperLeftY(rast) AS uly,
    ST_Value(rast, 1, 1, 1) AS band1,
    ST_Value(rast, 2, 1, 1) AS band2
FROM baz;
래스터 출력
tile_id | ulx | uly | band1 | band2
---------+-----+-----+-------+-------
       1 |   0 |   0 |     1 |    10
       2 |   3 |   0 |     2 |    20
       3 |   6 |   0 |     3 |    30
       4 |   0 |  -3 |     4 |    40
       5 |   3 |  -3 |     5 |    50
       6 |   6 |  -3 |     6 |    60
       7 |   0 |  -6 |     7 |    70
       8 |   3 |  -6 |     8 |    80
       9 |   6 |  -6 |     9 |    90
(9 rows)
Code
WITH foo AS (
    SELECT ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 0, 0, 1, -1, 0, 0, 0), 1, '8BUI', 1, 0), 2, '8BUI', 10, 0) AS rast UNION ALL
    SELECT ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 3, 0, 1, -1, 0, 0, 0), 1, '8BUI', 2, 0), 2, '8BUI', 20, 0) AS rast UNION ALL
    SELECT ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 6, 0, 1, -1, 0, 0, 0), 1, '8BUI', 3, 0), 2, '8BUI', 30, 0) AS rast UNION ALL

    SELECT ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 0, -3, 1, -1, 0, 0, 0), 1, '8BUI', 4, 0), 2, '8BUI', 40, 0) AS rast UNION ALL
    SELECT ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 3, -3, 1, -1, 0, 0, 0), 1, '8BUI', 5, 0), 2, '8BUI', 50, 0) AS rast UNION ALL
    SELECT ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 6, -3, 1, -1, 0, 0, 0), 1, '8BUI', 6, 0), 2, '8BUI', 60, 0) AS rast UNION ALL

    SELECT ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 0, -6, 1, -1, 0, 0, 0), 1, '8BUI', 7, 0), 2, '8BUI', 70, 0) AS rast UNION ALL
    SELECT ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 3, -6, 1, -1, 0, 0, 0), 1, '8BUI', 8, 0), 2, '8BUI', 80, 0) AS rast UNION ALL
    SELECT ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 6, -6, 1, -1, 0, 0, 0), 1, '8BUI', 9, 0), 2, '8BUI', 90, 0) AS rast
), bar AS (
    SELECT ST_Union(rast) AS rast FROM foo
), baz AS (
    SELECT
        row_number() OVER (
            ORDER BY ST_UpperLeftY(rast) DESC, ST_UpperLeftX(rast)
        ) AS tile_id,
        rast
    FROM (
        SELECT ST_Tile(rast, ARRAY[2], 3, 3) AS rast
        FROM bar
    ) AS tiled
)
SELECT
    tile_id,
    ST_UpperLeftX(rast) AS ulx,
    ST_UpperLeftY(rast) AS uly,
    ST_Value(rast, 1, 1, 1) AS band_value
FROM baz;
래스터 출력
tile_id | ulx | uly | band_value
---------+-----+-----+------------
       1 |   0 |   0 |         10
       2 |   3 |   0 |         20
       3 |   6 |   0 |         30
       4 |   0 |  -3 |         40
       5 |   3 |  -3 |         50
       6 |   6 |  -3 |         60
       7 |   0 |  -6 |         70
       8 |   3 |  -6 |         80
       9 |   6 |  -6 |         90
(9 rows)

제목

ST_Retile — 임의로 타일화된 래스터 커버리지로부터, 설정된 타일들의 집합을 반환합니다.

요약

SETOF raster ST_Retile(regclass tab, name col, geometry ext, float8 sfx, float8 sfy, int tw, int th, text algo='NearestNeighbor');

Description

설정한 축척(sfx, sfy)과 최대 크기(tw, th)를 가지고, 설정한 래스터 커버리지(tab, col)에서 나온 데이터로 설정한 범위(ext)를 커버하는 타일들의 집합을 반환합니다.

알고리즘 옵션에는 'NearestNeighbor', 'Bilinear', 'Cubic', 'CubicSpline', 그리고 'Lanczos'가 있습니다. 자세한 내용은 GDAL Warp resampling methods 를 참조하십시오.

2.2.0 버전부터 사용할 수 있습니다.


제목

ST_FromGDALRaster — 지원 GDAL 래스터 파일로부터 래스터를 반환합니다.

요약

raster ST_FromGDALRaster(bytea gdaldata, integer srid=NULL);

Description

지원 GDAL 래스터 파일로부터 래스터를 반환합니다. gdaldata 는 bytea 유형으로 GDAL 래스터 파일의 내용을 담고 있어야 합니다.

srid 가 NULL일 경우, 이 함수는 GDAL 래스터로부터 자동적으로 SRID를 할당하려 할 것입니다. srid 를 설정한 경우, 해당 값이 자동적으로 할당된 어떤 SRID보다 우선할 것입니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

Code
WITH foo AS (
    SELECT ST_AsPNG(ST_AddBand(ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(2, 2, 0, 0, 0.1, -0.1, 0, 0, 4326), 1, '8BUI', 1, 0), 2, '8BUI', 2, 0), 3, '8BUI', 3, 0)) AS png
),
bar AS (
    SELECT 1 AS rid, ST_FromGDALRaster(png) AS rast FROM foo
    UNION ALL
    SELECT 2 AS rid, ST_FromGDALRaster(png, 3310) AS rast FROM foo
)
SELECT
    rid,
    ST_MetaData(rast) AS metadata,
    ST_SummaryStats(rast, 1) AS stats1,
    ST_SummaryStats(rast, 2) AS stats2,
    ST_SummaryStats(rast, 3) AS stats3
FROM bar
ORDER BY rid;
래스터 출력
rid |         metadata          |    stats1     |    stats2     |     stats3
-----+---------------------------+---------------+---------------+----------------
   1 | (0,0,2,2,1,-1,0,0,0,3)    | (4,4,1,0,1,1) | (4,8,2,0,2,2) | (4,12,3,0,3,3)
   2 | (0,0,2,2,1,-1,0,0,3310,3) | (4,4,1,0,1,1) | (4,8,2,0,2,2) | (4,12,3,0,3,3)
(2 rows)

11.4. 래스터 접근자(accessor)

  • ST_GeoReference — 월드(world) 파일에서 흔히 볼 수 있는 지리참조 메타데이터를 GDAL 또는 ESRI 형식으로 반환합니다. 기본값은 GDAL입니다.
  • ST_Height — 래스터의 높이를 픽셀 개수로 반환합니다.
  • ST_IsEmpty — 래스터가 비어 있을 경우 (width = 0, height = 0) 참을 반환합니다. 그렇지 않을 경우 거짓을 반환합니다.
  • ST_MemSize — 래스터가 차지하는 공간의 용량을 (바이트 단위로) 반환합니다.
  • ST_MetaData — 래스터 객체의 픽셀 크기, 회전(skew), 좌상단, 좌하단 등과 같은 기본 메타데이터를 반환합니다.
  • ST_NumBands — 래스터 객체 내부에 있는 밴드들의 개수를 반환합니다.
  • ST_PixelHeight — 픽셀 높이를 공간 참조 시스템의 기하 단위로 반환합니다.
  • ST_PixelWidth — 픽셀 너비를 공간 참조 시스템의 기하 단위로 반환합니다.
  • ST_ScaleX — 픽셀 너비의 X 요소를 좌표 참조 시스템의 단위로 반환합니다.
  • ST_ScaleY — 픽셀 높이의 Y 요소를 좌표 참조 시스템의 단위로 반환합니다.
  • ST_RasterToWorldCoord — 주어진 열과 행에 있는 래스터의 좌상단의 기하학적 X, Y(경도, 위도)를 으로 반환합니다. 열과 행은 1부터 시작합니다.
  • ST_RasterToWorldCoordX — 열과 행에 있는 래스터의 좌상단의 기하학적 X 좌표를 반환합니다. 열과 행의 번호는 1부터 시작합니다.
  • ST_RasterToWorldCoordY — 열과 행에 있는 래스터의 좌상단의 기하학적 Y 좌표를 반환합니다. 열과 행의 번호는 1부터 시작합니다.
  • ST_Rotation — 래스터의 회전각을 라디안으로 반환합니다.
  • ST_SkewX — 지리참조 X 기울기(skew)(또는 회전각 파라미터)를 반환합니다.
  • ST_SkewY — 지리참조 Y 기울기(또는 회전각 파라미터)를 반환합니다.
  • ST_SRID — spatial_ref_sys 테이블에 정의되어 있는, 래스터의 공간 참조 식별자를 반환합니다.
  • ST_Summary — 래스터의 내용을 요약한 텍스트를 반환합니다.
  • ST_UpperLeftX — 래스터의 좌상단 X 좌표를 투영된 공간 참조 단위로 반환합니다.
  • ST_UpperLeftY — 래스터의 좌상단 Y 좌표를 투영된 공간 참조 단위로 반환합니다.
  • ST_Width — 래스터의 너비를 픽셀 개수로 반환합니다.
  • ST_WorldToRasterCoord — 주어진 기하학적 X, Y(경도, 위도)의 좌상단을 열과 행으로 또는 래스터의 공간 참조 좌표 시스템 단위로 표현된 포인트 도형으로 반환합니다.
  • ST_WorldToRasterCoordX — 포인트 도형(pt)의 래스터 안의 열 또는 래스터의 월드 공간 참조 시스템 단위로 표현된 X, Y 월드 좌표(xw, yw)를 반환합니다.
  • ST_WorldToRasterCoordY — 포인트 도형(pt)의 래스터 안의 행 또는 래스터의 월드 공간 참조 시스템 단위로 표현된 X, Y 월드 좌표(xw, yw)를 반환합니다.

제목

ST_GeoReference — 월드(world) 파일에서 흔히 볼 수 있는 지리참조 메타데이터를 GDAL 또는 ESRI 형식으로 반환합니다. 기본값은 GDAL입니다.

요약

text ST_GeoReference(raster rast, text format=GDAL);

Description

월드 파일 에서 흔히 보이는, 캐리지(carriage)를 포함한 지리참조 메타데이터를 GDAL 또는 ESRI 형식으로 반환합니다. 유형을 따로 설정하지 않을 경우 기본값은 GDAL입니다. 해당 유형값은 'GDAL' 또는 'ESRI' 문자열입니다.

형식 표현식 사이의 차이점은 다음과 같습니다:

GDAL:

래스터 출력
scalex
skewy
skewx
scaley
upperleftx
upperlefty

ESRI:

래스터 출력
scalex
skewy
skewx
scaley
upperleftx + scalex*0.5
upperlefty + scaley*0.5

예시

Code
SELECT
    format,
    replace(ST_GeoReference(rast, format), E'\n', ' | ') AS georef
FROM dummy_rast
CROSS JOIN (VALUES ('ESRI'), ('GDAL')) AS formats(format)
WHERE rid = 1;
래스터 출력
format | georef
--------+---------------------------------------------------------------------------
 ESRI   | 2.0000000000 | 0.0000000000 | 0.0000000000 | 3.0000000000 | 1.5000000000 | 2.0000000000
 GDAL   | 2.0000000000 | 0.0000000000 | 0.0000000000 | 3.0000000000 | 0.5000000000 | 0.5000000000
(2 rows)

제목

ST_Height — 래스터의 높이를 픽셀 개수로 반환합니다.

요약

integer ST_Height(raster rast);

Description

래스터의 높이를 반환합니다.

예시

Code
SELECT rid, ST_Height(rast) As rastheight
FROM dummy_rast;
래스터 출력
rid | rastheight
-----+------------
   1 |         20
   2 |          5

참고

ST_Width


제목

ST_IsEmpty — 래스터가 비어 있을 경우 (width = 0, height = 0) 참을 반환합니다. 그렇지 않을 경우 거짓을 반환합니다.

요약

boolean ST_IsEmpty(raster rast);

Description

래스터가 비어 있을 경우 (width = 0, height = 0) 참을 반환합니다. 그렇지 않을 경우 거짓을 반환합니다.

2.0.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT ST_IsEmpty(ST_MakeEmptyRaster(100, 100, 0, 0, 0, 0, 0, 0))
래스터 출력
f
Code
SELECT ST_IsEmpty(ST_MakeEmptyRaster(0, 0, 0, 0, 0, 0, 0, 0))
래스터 출력
t

제목

ST_MemSize — 래스터가 차지하는 공간의 용량을 (바이트 단위로) 반환합니다.

요약

integer ST_MemSize(raster rast);

Description

래스터가 차지하는 공간의 용량을 (바이트 단위로) 반환합니다.

이 함수는 PostgreSQL 내장 함수들인 pg_column_size, pg_size_pretty, pg_relation_size, pg_total_relation_size를 멋지게 보완합니다.

[참고]

테이블의 바이트 용량을 출력하는 pg_relation_size가 ST_MemSize보다 적은 바이트 용량을 반환할 수도 있습니다. 왜냐하면 pg_relation_size 함수는 TOAST 테이블에 저장된 대용량 도형들 및 TOAST가 적용된 테이블이 분담하는 용량을 추가하지 않기 때문입니다. pg_column_size 함수는 압축된 용량을 반환하기 때문에 더 적은 용량을 반환할 수도 있습니다.

pg_total_relation_size 함수는 테이블, TOAST가 적용된 테이블 및 인덱스를 포함합니다.

2.2.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT ST_MemSize(ST_AsRaster(ST_Buffer(ST_Point(1, 5), 10, 1000), 150, 150, '8BUI')) AS rast_mem;
래스터 출력
22568

참고


제목

ST_MetaData — 래스터 객체의 픽셀 크기, 회전(skew), 좌상단, 좌하단 등과 같은 기본 메타데이터를 반환합니다.

요약

record ST_MetaData(raster rast);

Description

래스터 객체의 픽셀 크기, 회전(skew), 좌상단, 좌하단 등과 같은 기본 메타데이터를 반환합니다. 반환되는 열들은 다음과 같습니다: upperleftx | upperlefty | width | height | scalex | scaley | skewx | skewy | srid | numbands

예시

Code
SELECT
    rid,
    format('(%s, %s)', (md).upperleftx, (md).upperlefty) AS upper_left,
    format('%sx%s', (md).width, (md).height) AS size,
    format('(%s, %s)', (md).scalex, (md).scaley) AS scale,
    format('(%s, %s)', (md).skewx, (md).skewy) AS skew,
    (md).srid AS srid,
    (md).numbands AS numbands
FROM (
    SELECT rid, ST_MetaData(rast) AS md
    FROM dummy_rast
) AS foo
ORDER BY rid;
래스터 출력
rid |        upper_left        | size  |      scale      |  skew  | srid | numbands
-----+--------------------------+-------+-----------------+--------+------+----------
   1 | (0.5, 0.5)               | 10x20 | (2, 3)          | (0, 0) |    0 |        0
   2 | (3427927.75, 5793244)    | 5x5   | (0.05, -0.05)   | (0, 0) |    0 |        3
(2 rows)

제목

ST_NumBands — 래스터 객체 내부에 있는 밴드들의 개수를 반환합니다.

요약

integer ST_NumBands(raster rast);

Description

래스터 객체 내부에 있는 밴드들의 개수를 반환합니다.

예시

Code
SELECT rid, ST_NumBands(rast) As numbands
FROM dummy_rast;
래스터 출력
rid | numbands
----+----------
  1 |        0
  2 |        3

참고

ST_Value


제목

ST_PixelHeight — 픽셀 높이를 공간 참조 시스템의 기하 단위로 반환합니다.

요약

double precision ST_PixelHeight(raster rast);

Description

픽셀 높이를 공간 참조 시스템의 기하 단위로 반환합니다. 회전하지 않은 일반적인 경우, 픽셀 높이란 단순히 기하 좌표와 래스터 픽셀의 축척 비율일 뿐입니다.

이 관계성을 그림으로 시각화한 예시를 보려면 ST_PixelWidth 를 참조하십시오.

예시

Rasters with no skew.

Code
SELECT ST_Height(rast) As rastheight, ST_PixelHeight(rast) As pixheight,
 ST_ScaleX(rast) As scalex, ST_ScaleY(rast) As scaley, ST_SkewX(rast) As skewx,
        ST_SkewY(rast) As skewy
FROM dummy_rast;
래스터 출력
rastheight | pixheight | scalex | scaley | skewx | skewy
------------+-----------+--------+--------+-------+----------
         20 |         3 |      2 |      3 |     0 |        0
          5 |      0.05 |   0.05 |  -0.05 |     0 |        0

Rasters with skew different than 0.

Code
SELECT ST_Height(rast) As rastheight, ST_PixelHeight(rast) As pixheight,
 ST_ScaleX(rast) As scalex, ST_ScaleY(rast) As scaley, ST_SkewX(rast) As skewx,
        ST_SkewY(rast) As skewy
FROM (SELECT ST_SetSkew(rast, 0.5, 0.5) As rast
        FROM dummy_rast) As skewed;
래스터 출력
rastheight |     pixheight     | scalex | scaley | skewx | skewy
-----------+-------------------+--------+--------+-------+----------
        20 |  3.04138126514911 |      2 |      3 |   0.5 |      0.5
         5 | 0.502493781056044 |   0.05 |  -0.05 |   0.5 |      0.5

제목

ST_PixelWidth — 픽셀 너비를 공간 참조 시스템의 기하 단위로 반환합니다.

요약

double precision ST_PixelWidth(raster rast);

Description

픽셀 너비를 공간 참조 시스템의 기하 단위로 반환합니다. 회전하지 않은 일반적인 경우, 픽셀 너비란 단순히 기하 좌표와 래스터 픽셀의 축척 비율일 뿐입니다.

The following executable example draws the two pixel basis vectors on the same coordinate frame as a skewed raster footprint. The i direction vector is (scaleX, skewY); the j direction vector is (skewX, scaleY).

예시

Pixel basis vectors and footprint for a raster with non-zero skew.

Code
WITH raster AS (
    SELECT ST_MakeEmptyRaster(
        3, 3, 0, 0,
        2, -3, 1, 0.5,
        0
    ) AS rast
)
SELECT
    ST_ConvexHull(rast) AS footprint,
    ST_MakeLine(
        ST_Point(0, 0),
        ST_Point(ST_ScaleX(rast), ST_SkewY(rast))
    ) AS "i direction (scaleX, skewY)",
    ST_MakeLine(
        ST_Point(0, 0),
        ST_Point(ST_SkewX(rast), ST_ScaleY(rast))
    ) AS "j direction (skewX, scaleY)"
FROM raster;
래스터 출력
POLYGON((0 0,6 1.5,9 -7.5,3 -9,0 0)) | LINESTRING(0 0,2 0.5) | LINESTRING(0 0,1 -3)
Figure
Geometry figure for visual-rt-st-pixelwidth-01

Rasters with no skew.

Code
SELECT ST_Width(rast) As rastwidth, ST_PixelWidth(rast) As pixwidth,
ST_ScaleX(rast) As scalex, ST_ScaleY(rast) As scaley, ST_SkewX(rast) As skewx,
ST_SkewY(rast) As skewy
FROM dummy_rast;
래스터 출력
rastwidth | pixwidth | scalex | scaley | skewx | skewy
-----------+----------+--------+--------+-------+----------
10 |        2 |      2 |      3 |     0 |        0
 5 |     0.05 |   0.05 |  -0.05 |     0 |        0

Rasters with skew different than 0.

Code
SELECT ST_Width(rast) As rastwidth, ST_PixelWidth(rast) As pixwidth,
ST_ScaleX(rast) As scalex, ST_ScaleY(rast) As scaley, ST_SkewX(rast) As skewx,
ST_SkewY(rast) As skewy
FROM (SELECT ST_SetSkew(rast, 0.5, 0.5) As rast
FROM dummy_rast) As skewed;
래스터 출력
rastwidth |     pixwidth      | scalex | scaley | skewx | skewy
-----------+-------------------+--------+--------+-------+----------
10 |  2.06155281280883 |      2 |      3 |   0.5 |      0.5
 5 | 0.502493781056044 |   0.05 |  -0.05 |   0.5 |      0.5

제목

ST_ScaleX — 픽셀 너비의 X 요소를 좌표 참조 시스템의 단위로 반환합니다.

요약

float8 ST_ScaleX(raster rast);

Description

픽셀 너비의 X 요소를 좌표 참조 시스템의 단위로 반환합니다. 자세한 내용은 월드 파일 을 참조하십시오.

변경 사항: 2.0.0 미만 WKTRaster 버전에서는 ST_PixelSizeX라는 명칭이었습니다.

예시

Code
SELECT rid, ST_ScaleX(rast) As rastpixwidth
FROM dummy_rast;
래스터 출력
rid | rastpixwidth
-----+--------------
   1 |            2
   2 |         0.05

참고

ST_Width


제목

ST_ScaleY — 픽셀 높이의 Y 요소를 좌표 참조 시스템의 단위로 반환합니다.

요약

float8 ST_ScaleY(raster rast);

Description

픽셀 높이의 Y 요소를 좌표 참조 시스템의 단위로 반환합니다. 음수일 수도 있습니다. 자세한 내용은 월드 파일 을 참조하십시오.

변경 사항: 2.0.0 미만 WKTRaster 버전에서는 ST_PixelSizeY라는 명칭이었습니다.

예시

Code
SELECT rid, ST_ScaleY(rast) As rastpixheight
FROM dummy_rast;
래스터 출력
rid | rastpixheight
-----+---------------
   1 |             3
   2 |         -0.05

참고

ST_Height


제목

ST_RasterToWorldCoord — 주어진 열과 행에 있는 래스터의 좌상단의 기하학적 X, Y(경도, 위도)를 으로 반환합니다. 열과 행은 1부터 시작합니다.

요약

record ST_RasterToWorldCoord(raster rast, integer xcolumn, integer yrow);

Description

주어진 열과 행에 있는 래스터의 좌상단의 기하학적 X, Y(경도, 위도)를 반환합니다. 반환된 X, Y의 좌표는 지리참조된 래스터의 기하 단위입니다. 열과 행의 번호는 1부터 시작하지만 두 파라미터 가운데 하나라도 0, 음수, 또는 래스터의 각 차원보다 큰 숫자를 입력할 경우, 래스터의 그리드가 래스터의 경계선 바깥에도 적용된다고 가정하고 래스터 외부의 좌표를 반환할 것입니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

This example uses a non-skewed raster.

Code
SELECT
    rid,
    (ST_RasterToWorldCoord(rast, 1, 1)).*,
    (ST_RasterToWorldCoord(rast, 2, 2)).*
FROM dummy_rast
래스터 출력
rid | longitude  | latitude | longitude |  latitude
-----+------------+----------+-----------+------------
   1 |        0.5 |      0.5 |       2.5 |        3.5
   2 | 3427927.75 |  5793244 | 3427927.8 | 5793243.95

This example uses a skewed raster.

Code
SELECT
    rid,
    (ST_RasterToWorldCoord(rast, 1, 1)).*,
    (ST_RasterToWorldCoord(rast, 2, 3)).*
FROM (
    SELECT
        rid,
        ST_SetSkew(rast, 100.5, 0) As rast
    FROM dummy_rast
) As foo
래스터 출력
rid | longitude  | latitude | longitude | latitude
-----+------------+----------+-----------+-----------
   1 |        0.5 |      0.5 |     203.5 |       6.5
   2 | 3427927.75 |  5793244 | 3428128.8 | 5793243.9

제목

ST_RasterToWorldCoordX — 열과 행에 있는 래스터의 좌상단의 기하학적 X 좌표를 반환합니다. 열과 행의 번호는 1부터 시작합니다.

요약

float8 ST_RasterToWorldCoordX(raster rast, integer xcolumn);

float8 ST_RasterToWorldCoordX(raster rast, integer xcolumn, integer yrow);

Description

래스터 열과 행의 좌상단 X 좌표를 지리참조된 래스터의 기하 단위로 반환합니다. 열과 행의 번호는 1부터 시작하지만 두 파라미터 가운데 하나라도 음수 또는 래스터 열의 개수보다 큰 숫자를 입력할 경우, 회전 및 픽셀 크기가 선택된 래스터와 동일하다고 가정하고 래스터 파일의 왼쪽 또는 오른쪽 바깥에 있는 좌표를 반환할 것입니다.

[참고]

회전하지 않은 래스터의 경우, X열만 입력해도 충분합니다. 회전한 래스터의 경우, 지리참조된 좌표는 ST_ScaleX, ST_SkewX, 행 및 열의 함수입니다. 회전한 래스터에 대해 X열만 입력할 경우 오류가 발생할 것입니다.

변경 사항: 2.1.0 미만 버전에서는 ST_Raster2WorldCoordX라는 명칭이었습니다.

예시

This example shows that providing a column is sufficient for a non-skewed raster.

Code
SELECT rid, ST_RasterToWorldCoordX(rast, 1) As x1coord,
    ST_RasterToWorldCoordX(rast, 2) As x2coord,
    ST_ScaleX(rast) As pixelx
FROM dummy_rast;
래스터 출력
rid |  x1coord   |  x2coord  | pixelx
-----+------------+-----------+--------
   1 |        0.5 |       2.5 |      2
   2 | 3427927.75 | 3427927.8 |   0.05

For fun let's skew it.

Code
SELECT rid, ST_RasterToWorldCoordX(rast, 1, 1) As x1coord,
    ST_RasterToWorldCoordX(rast, 2, 3) As x2coord,
    ST_ScaleX(rast) As pixelx
FROM (SELECT rid, ST_SetSkew(rast, 100.5, 0) As rast FROM dummy_rast) As foo;
래스터 출력
rid |  x1coord   |  x2coord  | pixelx
-----+------------+-----------+--------
   1 |        0.5 |     203.5 |      2
   2 | 3427927.75 | 3428128.8 |   0.05

제목

ST_RasterToWorldCoordY — 열과 행에 있는 래스터의 좌상단의 기하학적 Y 좌표를 반환합니다. 열과 행의 번호는 1부터 시작합니다.

요약

float8 ST_RasterToWorldCoordY(raster rast, integer yrow);

float8 ST_RasterToWorldCoordY(raster rast, integer xcolumn, integer yrow);

Description

래스터 열과 행의 좌상단 Y 좌표를 지리참조된 래스터의 기하 단위로 반환합니다. 열과 행의 번호는 1부터 시작하지만 두 파라미터 가운데 하나라도 음수 또는 래스터 열/행의 개수보다 큰 숫자를 입력할 경우, 회전 및 픽셀 크기가 선택된 래스터와 동일하다고 가정하고 래스터 타일의 왼쪽 또는 오른쪽 바깥에 있는 좌표를 반환할 것입니다.

[참고]

회전하지 않은 래스터의 경우, Y열만 입력해도 충분합니다. 회전한 래스터의 경우, 지리참조된 좌표는 ST_ScaleY, ST_SkewY, 행 및 열의 함수입니다. 회전한 래스터에 대해 Y행만 입력할 경우 오류가 발생할 것입니다.

변경 사항: 2.1.0 미만 버전에서는 ST_Raster2WorldCoordY라는 명칭이었습니다.

예시

Non-skewed raster providing row is sufficient.

Code
SELECT rid, ST_RasterToWorldCoordY(rast, 1) As y1coord,
    ST_RasterToWorldCoordY(rast, 3) As y2coord,
    ST_ScaleY(rast) As pixely
FROM dummy_rast;
래스터 출력
rid | y1coord |  y2coord  | pixely
-----+---------+-----------+--------
   1 |     0.5 |       6.5 |      3
   2 | 5793244 | 5793243.9 |  -0.05

For fun let's skew it.

Code
SELECT rid, ST_RasterToWorldCoordY(rast, 1, 1) As y1coord,
    ST_RasterToWorldCoordY(rast, 2, 3) As y2coord,
    ST_ScaleY(rast) As pixely
FROM (SELECT rid, ST_SetSkew(rast, 0, 100.5) As rast FROM dummy_rast) As foo;
래스터 출력
rid | y1coord |  y2coord  | pixely
-----+---------+-----------+--------
   1 |     0.5 |       107 |      3
   2 | 5793244 | 5793344.4 |  -0.05

제목

ST_Rotation — 래스터의 회전각을 라디안으로 반환합니다.

요약

float8 ST_Rotation(raster rast);

Description

래스터의 균일한 회전각을 라디안으로 반환합니다. 래스터가 균일한 회전각으로 회전하지 않은 경우, NaN을 반환합니다. 자세한 내용은 월드 파일 을 참조하십시오.

예시

Code
SELECT rid, ST_Rotation(ST_SetScale(ST_SetSkew(rast, sqrt(2)), sqrt(2))) AS rot FROM dummy_rast;
래스터 출력
rid |        rot
-----+-------------------
   1 | 0.785398163397448
   2 | 0.785398163397448

제목

ST_SkewX — 지리참조 X 기울기(skew)(또는 회전각 파라미터)를 반환합니다.

요약

float8 ST_SkewX(raster rast);

Description

지리참조 X 기울기(또는 회전각 파라미터)를 반환합니다. 자세한 내용은 월드 파일 을 참조하십시오.

예시

Code
WITH refs AS (
    SELECT
        rid,
        format('(%s, %s)', ST_SkewX(rast), ST_SkewY(rast)) AS skew,
        string_to_array(ST_GeoReference(rast), E'\n') AS georef
    FROM dummy_rast
)
SELECT
    rid,
    skew,
    term,
    georef[idx] AS value
FROM refs
CROSS JOIN (VALUES
    (1, 'scaleX'),
    (2, 'skewY'),
    (3, 'skewX'),
    (4, 'scaleY'),
    (5, 'originX'),
    (6, 'originY')
) AS parts(idx, term)
ORDER BY rid, idx;
래스터 출력
rid |  skew  |  term   |       value
-----+--------+---------+--------------------
   1 | (0, 0) | scaleX  | 2.0000000000
   1 | (0, 0) | skewY   | 0.0000000000
   1 | (0, 0) | skewX   | 0.0000000000
   1 | (0, 0) | scaleY  | 3.0000000000
   1 | (0, 0) | originX | 0.5000000000
   1 | (0, 0) | originY | 0.5000000000
   2 | (0, 0) | scaleX  | 0.0500000000
   2 | (0, 0) | skewY   | 0.0000000000
   2 | (0, 0) | skewX   | 0.0000000000
   2 | (0, 0) | scaleY  | -0.0500000000
   2 | (0, 0) | originX | 3427927.7500000000
   2 | (0, 0) | originY | 5793244.0000000000
(12 rows)

제목

ST_SkewY — 지리참조 Y 기울기(또는 회전각 파라미터)를 반환합니다.

요약

float8 ST_SkewY(raster rast);

Description

지리참조 Y 기울기(또는 회전각 파라미터)를 반환합니다. 자세한 내용은 월드 파일 을 참조하십시오.

예시

Code
WITH refs AS (
    SELECT
        rid,
        format('(%s, %s)', ST_SkewX(rast), ST_SkewY(rast)) AS skew,
        string_to_array(ST_GeoReference(rast), E'\n') AS georef
    FROM dummy_rast
)
SELECT
    rid,
    skew,
    term,
    georef[idx] AS value
FROM refs
CROSS JOIN (VALUES
    (1, 'scaleX'),
    (2, 'skewY'),
    (3, 'skewX'),
    (4, 'scaleY'),
    (5, 'originX'),
    (6, 'originY')
) AS parts(idx, term)
ORDER BY rid, idx;
래스터 출력
rid |  skew  |  term   |       value
-----+--------+---------+--------------------
   1 | (0, 0) | scaleX  | 2.0000000000
   1 | (0, 0) | skewY   | 0.0000000000
   1 | (0, 0) | skewX   | 0.0000000000
   1 | (0, 0) | scaleY  | 3.0000000000
   1 | (0, 0) | originX | 0.5000000000
   1 | (0, 0) | originY | 0.5000000000
   2 | (0, 0) | scaleX  | 0.0500000000
   2 | (0, 0) | skewY   | 0.0000000000
   2 | (0, 0) | skewX   | 0.0000000000
   2 | (0, 0) | scaleY  | -0.0500000000
   2 | (0, 0) | originX | 3427927.7500000000
   2 | (0, 0) | originY | 5793244.0000000000
(12 rows)

제목

ST_SRID — spatial_ref_sys 테이블에 정의되어 있는, 래스터의 공간 참조 식별자를 반환합니다.

요약

integer ST_SRID(raster rast);

Description

spatial_ref_sys 테이블에 정의되어 있는, 래스터 객체의 공간 참조 식별자를 반환합니다.

[참고]

Non-georeferenced rasters and geometries use SRID 0.

예시

Code
SELECT ST_SRID(rast) As srid
FROM dummy_rast WHERE rid=1;
래스터 출력
0

제목

ST_Summary — 래스터의 내용을 요약한 텍스트를 반환합니다.

요약

text ST_Summary(raster rast);

Description

래스터의 내용을 요약한 텍스트를 반환합니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT ST_Summary(ST_AddBand(ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(10, 10, 0, 0, 1, -1, 0, 0, 0),
                1, '8BUI', 1, 0
            ),
            2, '32BF', 0, -9999
        ),
        3, '16BSI', 0, NULL
    )
);
래스터 출력
Raster of 10x10 pixels has 3 bands and extent of BOX(0 -10,10 0)+
     band 1 of pixtype 8BUI is in-db with NODATA value of 0      +
     band 2 of pixtype 32BF is in-db with NODATA value of -9999  +
     band 3 of pixtype 16BSI is in-db with no NODATA value
(1 row)

제목

ST_UpperLeftX — 래스터의 좌상단 X 좌표를 투영된 공간 참조 단위로 반환합니다.

요약

float8 ST_UpperLeftX(raster rast);

Description

래스터의 좌상단 X 좌표를 투영된 공간 참조 단위로 반환합니다.

예시

Code
SELECt rid, ST_UpperLeftX(rast) As ulx
FROM dummy_rast;
래스터 출력
rid |    ulx
-----+------------
   1 |        0.5
   2 | 3427927.75

제목

ST_UpperLeftY — 래스터의 좌상단 Y 좌표를 투영된 공간 참조 단위로 반환합니다.

요약

float8 ST_UpperLeftY(raster rast);

Description

래스터의 좌상단 Y 좌표를 투영된 공간 참조 단위로 반환합니다.

예시

Code
SELECT rid, ST_UpperLeftY(rast) As uly
FROM dummy_rast;
래스터 출력
rid |   uly
-----+---------
   1 |     0.5
   2 | 5793244

제목

ST_Width — 래스터의 너비를 픽셀 개수로 반환합니다.

요약

integer ST_Width(raster rast);

Description

래스터의 너비를 픽셀 개수로 반환합니다.

예시

Code
SELECT ST_Width(rast) As rastwidth
FROM dummy_rast WHERE rid=1;
래스터 출력
10

참고

ST_Height


제목

ST_WorldToRasterCoord — 주어진 기하학적 X, Y(경도, 위도)의 좌상단을 열과 행으로 또는 래스터의 공간 참조 좌표 시스템 단위로 표현된 포인트 도형으로 반환합니다.

요약

record ST_WorldToRasterCoord(raster rast, geometry pt);

record ST_WorldToRasterCoord(raster rast, double precision longitude, double precision latitude);

Description

주어진 기하학적 X, Y(경도, 위도)의 좌상단을 열과 행으로 또는 포인트 도형으로 반환합니다. 이 함수는 기하학적 X, Y 또는 포인트 도형이 래스터 범위 외부에 있건 말건 상관없이 동작합니다. 기하학적 X, Y는 래스터의 공간 참조 좌표 시스템 단위로 표현돼야만 합니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT
    rid,
    (ST_WorldToRasterCoord(rast, 3427927.8, 20.5)).*,
    (ST_WorldToRasterCoord(rast, ST_GeomFromText('POINT(3427927.8 20.5)', ST_SRID(rast)))).*
FROM dummy_rast;
래스터 출력
rid | columnx |   rowy    | columnx |   rowy
-----+---------+-----------+---------+-----------
   1 | 1713964 |         7 | 1713964 |         7
   2 |       2 | 115864471 |       2 | 115864471

제목

ST_WorldToRasterCoordX — 포인트 도형(pt)의 래스터 안의 열 또는 래스터의 월드 공간 참조 시스템 단위로 표현된 X, Y 월드 좌표(xw, yw)를 반환합니다.

요약

integer ST_WorldToRasterCoordX(raster rast, geometry pt);

integer ST_WorldToRasterCoordX(raster rast, double precision xw);

integer ST_WorldToRasterCoordX(raster rast, double precision xw, double precision yw);

Description

포인트 도형(pt)의 래스터 안의 열 또는 X, Y 월드 좌표(xw, yw)를 반환합니다. 포인트가 필요합니다(또는 래스터가 기울어진 경우 xw 및 yw 월드 좌표가 두 개 모두 필요합니다). 래스터가 기울어지지 않은 경우 xw 좌표만으로도 충분합니다. 월드 좌표란 래스터의 공간 참조 좌표 시스템의 좌표를 말합니다.

변경 사항: 2.1.0 미만 버전에서는 ST_World2RasterCoordX라는 명칭이었습니다.

예시

Code
SELECT rid, ST_WorldToRasterCoordX(rast, 3427927.8) As xcoord,
        ST_WorldToRasterCoordX(rast, 3427927.8, 20.5) As xcoord_xwyw,
        ST_WorldToRasterCoordX(rast, ST_GeomFromText('POINT(3427927.8 20.5)', ST_SRID(rast))) As ptxcoord
FROM dummy_rast;
래스터 출력
rid | xcoord  |  xcoord_xwyw   | ptxcoord
-----+---------+---------+----------
   1 | 1713964 | 1713964 |  1713964
   2 |       1 |       1 |        1

제목

ST_WorldToRasterCoordY — 포인트 도형(pt)의 래스터 안의 행 또는 래스터의 월드 공간 참조 시스템 단위로 표현된 X, Y 월드 좌표(xw, yw)를 반환합니다.

요약

integer ST_WorldToRasterCoordY(raster rast, geometry pt);

integer ST_WorldToRasterCoordY(raster rast, double precision xw);

integer ST_WorldToRasterCoordY(raster rast, double precision xw, double precision yw);

Description

포인트 도형(pt)의 래스터 안의 행 또는 X, Y 월드 좌표(xw, yw)를 반환합니다. 포인트가 필요합니다(또는 래스터가 기울어진 경우 xw 및 yw 월드 좌표가 두 개 모두 필요합니다). 래스터가 기울어지지 않은 경우 xw 좌표만으로도 충분합니다. 월드 좌표란 래스터의 공간 참조 좌표 시스템의 좌표를 말합니다.

변경 사항: 2.1.0 미만 버전에서는 ST_World2RasterCoordY라는 명칭이었습니다.

예시

Code
SELECT rid, ST_WorldToRasterCoordY(rast, 20.5) As ycoord,
        ST_WorldToRasterCoordY(rast, 3427927.8, 20.5) As ycoord_xwyw,
        ST_WorldToRasterCoordY(rast, ST_GeomFromText('POINT(3427927.8 20.5)', ST_SRID(rast))) As ptycoord
FROM dummy_rast;
래스터 출력
rid |  ycoord   | ycoord_xwyw | ptycoord
-----+-----------+-------------+-----------
   1 |         7 |           7 |         7
   2 | 115864471 |   115864471 | 115864471

11.5. 래스터 밴드 접근자

  • ST_BandMetaData — 지정 래스터 밴드에 대한 기본 메타데이터를 반환합니다. 밴드를 지정하지 않을 경우 밴드 1번이라고 가정합니다.
  • ST_BandNoDataValue — 입력 밴드에서 NODATA를 나타내는 값을 반환합니다. 어떤 밴드도 지정하지 않을 경우 밴드 1로 가정합니다.
  • ST_BandIsNoData — 밴드가 NODATA 값만으로 채워져 있을 경우 참을 반환합니다.
  • ST_BandPath — 파일 시스템에 저장된 밴드를 가리키는 시스템 파일 경로를 반환합니다. bandnum을 설정하지 않을 경우 밴드 1로 가정합니다.
  • ST_BandFileSize — Returns the file size of a band stored in file system. If no bandnum specified, 1 is assumed.
  • ST_BandFileTimestamp — Returns the file timestamp of a band stored in file system. If no bandnum specified, 1 is assumed.
  • ST_BandPixelType — 입력 밴드의 픽셀 유형을 반환합니다. bandnum을 설정하지 않을 경우 밴드 1로 가정합니다.
  • ST_MinPossibleValue — 래스터 객체 내부에 있는 밴드들의 개수를 반환합니다.
  • ST_HasNoBand — 입력된 밴드 번호에 밴드가 없을 경우 참을 반환합니다. 밴드 번호를 설정하지 않을 경우, 밴드 1로 가정합니다.

제목

ST_BandMetaData — 지정 래스터 밴드에 대한 기본 메타데이터를 반환합니다. 밴드를 지정하지 않을 경우 밴드 1번이라고 가정합니다.

요약

(1) record ST_BandMetaData(raster rast, integer band=1);

(2) record ST_BandMetaData(raster rast, integer[] band);

Description

Returns basic meta data about a raster band. Columns returned: pixeltype, nodatavalue, isoutdb, path, outdbbandnum, filesize, filetimestamp.

[참고]

래스터가 어떤 밴드도 담고 있지 않을 경우 오류가 발생합니다.

[참고]

If band has no NODATA value, nodatavalue are NULL.

[참고]

If isoutdb is False, path, outdbbandnum, filesize and filetimestamp are NULL. If outdb access is disabled, filesize and filetimestamp will also be NULL.

Enhanced: 2.5.0 to include outdbbandnum, filesize and filetimestamp for outdb rasters.

예시

Variant 1.

Code
SELECT
    rid,
    (foo.md).*
FROM (
    SELECT
        rid,
        ST_BandMetaData(rast, 1) AS md
    FROM dummy_rast
    WHERE rid=2
) As foo;
래스터 출력
rid | pixeltype | nodatavalue | isoutdb | path | outdbbandnum
-----+-----------+-------------+---------+------+--------------
   2 | 8BUI      |           0 | f       |      |
(1 row)
                

Variant 2.

Code
WITH foo AS (
    SELECT
        ST_AddBand(NULL::raster, '/home/pele/devel/geo/postgis-git/raster/test/regress/loader/Projected.tif', NULL::int[]) AS rast
)
SELECT
    bandnum,
    pixeltype,
    isoutdb,
    regexp_replace(path, '^.*/', '') AS file,
    outdbbandnum
FROM ST_BandMetaData((SELECT rast FROM foo),
    ARRAY[1, 3, 2]::int[]
);
래스터 출력
bandnum | pixeltype | isoutdb |     file      | outdbbandnum
---------+-----------+---------+---------------+--------------
       1 | 8BUI      | t       | Projected.tif |            1
       3 | 8BUI      | t       | Projected.tif |            3
       2 | 8BUI      | t       | Projected.tif |            2

제목

ST_BandNoDataValue — 입력 밴드에서 NODATA를 나타내는 값을 반환합니다. 어떤 밴드도 지정하지 않을 경우 밴드 1로 가정합니다.

요약

double precision ST_BandNoDataValue(raster rast, integer bandnum=1);

Description

밴드에서 NODATA를 나타내는 값을 반환합니다.

예시

Code
SELECT ST_BandNoDataValue(rast, 1) As bnval1,
    ST_BandNoDataValue(rast, 2) As bnval2, ST_BandNoDataValue(rast, 3) As bnval3
FROM dummy_rast
WHERE rid = 2;
래스터 출력
bnval1 | bnval2 | bnval3
--------+--------+--------
      0 |      0 |      0

제목

ST_BandIsNoData — 밴드가 NODATA 값만으로 채워져 있을 경우 참을 반환합니다.

요약

boolean ST_BandIsNoData(raster rast, integer band, boolean forceChecking=false);

boolean ST_BandIsNoData(raster rast, boolean forceChecking=false);

Description

밴드가 NODATA 값만으로 채워져 있을 경우 참을 반환합니다. 밴드를 지정하지 않으면 밴드 1로 가정합니다. 마지막 인수가 TRUE일 경우, 밴드의 픽셀 전체를 하나하나 확인합니다. 그렇지 않을 경우, 이 함수는 밴드에 대한 isnodata 플래그의 값을 반환할 뿐입니다. 따로 설정하지 않을 경우, 해당 파라미터의 기본값은 FALSE입니다.

2.0.0 버전부터 사용할 수 있습니다.

[참고]

If the flag is dirty (this is, the result is different using TRUE as last parameter and not using it) you should update the raster to set this flag to true, by using ST_SetBandIsNoData(), or ST_SetBandNoDataValue() with TRUE as last argument. See ST_SetBandIsNoData.

예시

This example creates a dummy table with one raster column. The raster has two bands and one pixel per band. In the first band, the NODATA value and pixel value are both 3. In the second band, the NODATA value is 13 and the pixel value is 4.

Code
create table dummy_rast (rid integer, rast raster);

insert into dummy_rast values(
1,
(
'01' -- little endian (uint8 ndr)
||
'0000' -- version (uint16 0)
||
'0200' -- nBands (uint16 0)
||
'17263529ED684A3F' -- scaleX (float64 0.000805965234044584)
||
'F9253529ED684ABF' -- scaleY (float64 -0.00080596523404458)
||
'1C9F33CE69E352C0' -- ipX (float64 -75.5533328537098)
||
'718F0E9A27A44840' -- ipY (float64 49.2824585505576)
||
'ED50EB853EC32B3F' -- skewX (float64 0.000211812383858707)
||
'7550EB853EC32B3F' -- skewY (float64 0.000211812383858704)
||
'E6100000' -- SRID (int32 4326)
||
'0100' -- width (uint16 1)
||
'0100' -- height (uint16 1)
||
'6' -- hasnodatavalue and isnodata value set to true.
||
'2' -- first band type (4BUI)
||
'03' -- novalue==3
||
'03' -- pixel(0,0)==3 (same that nodata)
||
'0' -- hasnodatavalue set to false
||
'5' -- second band type (16BSI)
||
'0D00' -- novalue==13
||
'0400' -- pixel(0,0)==4
)::raster
);

select ST_BandIsNoData(rast, 1) from dummy_rast where rid = 1; -- Expected true
select ST_BandIsNoData(rast, 2) from dummy_rast where rid = 1; -- Expected false
            

제목

ST_BandPath — 파일 시스템에 저장된 밴드를 가리키는 시스템 파일 경로를 반환합니다. bandnum을 설정하지 않을 경우 밴드 1로 가정합니다.

요약

text ST_BandPath(raster rast, integer bandnum=1);

Description

밴드를 가리키는 시스템 파일 경로를 반환합니다. DB 내부 밴드와 함께 호출할 경우 오류가 발생합니다.

예시

Code
WITH foo AS (
    SELECT ST_AddBand(
        NULL::raster,
        '/home/pele/devel/geo/postgis-git/raster/test/regress/loader/Projected.tif',
        NULL::int[]
    ) AS rast
)
SELECT bandnum, ST_BandPath(rast, bandnum) AS path
FROM foo
CROSS JOIN generate_series(1, 3) AS bandnum;
래스터 출력
bandnum |                                    path
---------+----------------------------------------------------------------------------
       1 | /home/pele/devel/geo/postgis-git/raster/test/regress/loader/Projected.tif
       2 | /home/pele/devel/geo/postgis-git/raster/test/regress/loader/Projected.tif
       3 | /home/pele/devel/geo/postgis-git/raster/test/regress/loader/Projected.tif

제목

ST_BandFileSize — Returns the file size of a band stored in file system. If no bandnum specified, 1 is assumed.

요약

bigint ST_BandFileSize(raster rast, integer bandnum=1);

Description

Returns the file size of a band stored in file system. Throws an error if called with an in db band, or if outdb access is not enabled.

This function is typically used in conjunction with ST_BandPath() and ST_BandFileTimestamp() so a client can determine if the filename of a outdb raster as seen by it is the same as the one seen by the server.

Availability: 2.5.0

예시

Code
SELECT ST_BandFileSize(rast, 1) FROM dummy_rast WHERE rid = 1;
래스터 출력
240574

제목

ST_BandFileTimestamp — Returns the file timestamp of a band stored in file system. If no bandnum specified, 1 is assumed.

요약

bigint ST_BandFileTimestamp(raster rast, integer bandnum=1);

Description

Returns the file timestamp (number of seconds since Jan 1st 1970 00:00:00 UTC) of a band stored in file system. Throws an error if called with an in db band, or if outdb access is not enabled.

This function is typically used in conjunction with ST_BandPath() and ST_BandFileSize() so a client can determine if the filename of a outdb raster as seen by it is the same as the one seen by the server.

Availability: 2.5.0

예시

Code
SELECT ST_BandFileTimestamp(rast, 1) FROM dummy_rast WHERE rid = 1;
래스터 출력
1521807257

제목

ST_BandPixelType — 입력 밴드의 픽셀 유형을 반환합니다. bandnum을 설정하지 않을 경우 밴드 1로 가정합니다.

요약

text ST_BandPixelType(raster rast, integer bandnum=1);

Description

Returns name describing data type and size of values stored in each cell of given band.

11가지 픽셀 유형이 있습니다. 지원하는 픽셀 유형은 다음과 같습니다:

  • 1BB - 1비트 불 값

  • 2BUI - 부호 없는 2비트 정수형

  • 4BUI - 부호 없는 4비트 정수형

  • 8BSI - 부호 있는 8비트 정수형

  • 8BUI - 부호 없는 8비트 정수형

  • 16BSI - 부호 있는 16비트 정수형

  • 16BUI - 부호 없는 16비트 정수형

  • 32BSI - 부호 있는 32비트 정수형

  • 32BUI - 부호 없는 32비트 정수형

  • 32BF - 32비트 부동소수점 실수형

  • 64BF - 64비트 부동소수점 실수형

예시

Code
SELECT ST_BandPixelType(rast, 1) As btype1,
    ST_BandPixelType(rast, 2) As btype2, ST_BandPixelType(rast, 3) As btype3
FROM dummy_rast
WHERE rid = 2;
래스터 출력
btype1 | btype2 | btype3
--------+--------+--------
 8BUI   | 8BUI   | 8BUI

제목

ST_MinPossibleValue — 래스터 객체 내부에 있는 밴드들의 개수를 반환합니다.

요약

integer ST_MinPossibleValue(text pixeltype);

Description

래스터 객체 내부에 있는 밴드들의 개수를 반환합니다.

예시

Code
SELECT ST_MinPossibleValue('16BSI');
래스터 출력
-32768
Code
SELECT ST_MinPossibleValue('8BUI');
래스터 출력
0

제목

ST_HasNoBand — 입력된 밴드 번호에 밴드가 없을 경우 참을 반환합니다. 밴드 번호를 설정하지 않을 경우, 밴드 1로 가정합니다.

요약

boolean ST_HasNoBand(raster rast, integer bandnum=1);

Description

입력된 밴드 번호에 밴드가 없을 경우 참을 반환합니다. 밴드 번호를 설정하지 않을 경우, 밴드 1로 가정합니다.

2.0.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT rid, ST_HasNoBand(rast) As hb1, ST_HasNoBand(rast, 2) as hb2,
ST_HasNoBand(rast, 4) as hb4, ST_NumBands(rast) As numbands
FROM dummy_rast;
래스터 출력
rid | hb1 | hb2 | hb4 | numbands
-----+-----+-----+-----+----------
1 | t   | t   | t   |        0
2 | f   | f   | t   |        3

11.6. 래스터 픽셀 접근자 및 설정자(setter)

  • ST_PixelAsPolygon — 특정 행 및 열에 대한 픽셀의 경계를 이루는 폴리곤 도형을 반환합니다.
  • ST_PixelAsPolygons — 래스터 밴드의 모든 픽셀의 경계를 이루는 폴리곤 도형을 각 픽셀의 값과 X, Y 래스터 좌표와 함께 반환합니다.
  • ST_PixelAsPoint — 픽셀의 좌상단에 위치하는 포인트 도형을 반환합니다.
  • ST_PixelAsPoints — 래스터 밴드의 각 픽셀에 대한 포인트 도형을 각 픽셀의 값 및 X, Y 래스터 좌표와 함께 반환합니다. 포인트 도형의 좌표는 픽셀의 좌상단 좌표입니다.
  • ST_PixelAsCentroid — 픽셀 하나가 차지하는 면의 중심점(포인트 도형)을 반환합니다.
  • ST_PixelAsCentroids — 래스터 밴드의 각 픽셀에 대한 중심점(포인트 도형)을 각 픽셀의 값 및 X, Y 래스터 좌표와 함께 반환합니다. 포인트 도형은 픽셀이 차지하는 면의 중심점입니다.
  • ST_Value — 입력 columnx, rowy 픽셀의 입력 밴드의 값, 또는 특정 기하학적 포인트의 밴드의 값을 반환합니다. 밴드 번호는 1부터 시작하며, 따로 지정하지 않을 경우 1로 가정합니다. exclude_nodata_value 를 거짓으로 설정할 경우, nodata 픽셀을 포함한 모든 픽셀이 교차한다고 가정하고 값을 반환합니다. exclude_nodata_value 를 설정하지 않은 경우, 래스터의 메타데이터에서 값을 읽어 들입니다.
  • ST_NearestValue — columnx 및 rowy, 또는 래스터와 동일한 공간 참조 좌표 시스템 단위로 표현된 기하학적 포인트로 지정된 입력 밴드의 픽셀에 가장 가까운 NODATA 가 아닌 값을 반환합니다.
  • ST_SetZ — Returns a geometry with the same X/Y coordinates as the input geometry, and values from the raster copied into the Z dimension using the requested resample algorithm.
  • ST_SetM — Returns a geometry with the same X/Y coordinates as the input geometry, and values from the raster copied into the M dimension using the requested resample algorithm.
  • ST_Neighborhood — columnx 및 rowy, 또는 래스터와 동일한 공간 참조 좌표 시스템 단위로 표현된 기하학적 포인트로 지정된 입력 밴드의 픽셀 주위의 NODATA 가 아닌 값들의 이중 정밀도 데이터형 2차원 배열을 반환합니다.
  • ST_SetValue — 입력한 columnx, rowy 픽셀 또는 특정 도형과 교차하는 픽셀들의 위치의 밴드 값을 설정해서 나온 수정된 래스터를 반환합니다. 밴드 번호는 1부터 시작하며, 따로 설정하지 않을 경우 1로 가정합니다.
  • ST_SetValues — 지정한 밴드의 값들을 설정해서 나온 수정된 래스터를 반환합니다.
  • ST_DumpValues — 지정된 밴드의 값들을 2차원 배열로 반환합니다.
  • ST_PixelOfValue — 검색 값과 일치하는 값을 가진 픽셀의 columnx, rowy 좌표를 반환합니다.

제목

ST_PixelAsPolygon — 특정 행 및 열에 대한 픽셀의 경계를 이루는 폴리곤 도형을 반환합니다.

요약

geometry ST_PixelAsPolygon(raster rast, integer columnx, integer rowy);

Description

특정 행 및 열에 대한 픽셀의 경계를 이루는 폴리곤 도형을 반환합니다.

2.0.0 버전부터 사용할 수 있습니다.

예시

This example returns a raster pixel polygon.

Code
SELECT i, j, ST_PixelAsPolygon(foo.rast, i, j) As b1pgeom
FROM dummy_rast As foo
    CROSS JOIN generate_series(1, 2) As i
    CROSS JOIN generate_series(1, 1) As j
WHERE rid=2;
래스터 출력
i | j |                                                    b1pgeom
---+---+-----------------------------------------------------------------------------
 1 | 1 | POLYGON((3427927.75 5793244,3427927.8 5793244,3427927.8 5793243.95,...
 2 | 1 | POLYGON((3427927.8 5793244,3427927.85 5793244,3427927.85 5793243.95, ..

제목

ST_PixelAsPolygons — 래스터 밴드의 모든 픽셀의 경계를 이루는 폴리곤 도형을 각 픽셀의 값과 X, Y 래스터 좌표와 함께 반환합니다.

요약

setof record ST_PixelAsPolygons(raster rast, integer band=1, boolean exclude_nodata_value=TRUE);

Description

래스터 밴드의 모든 픽셀의 경계를 이루는 폴리곤 도형을 각 픽셀의 값(이중 정밀도 데이터형)과 X, Y 래스터 좌표(정수형)와 함께 반환합니다.

Return record format: geom geometry, val double precision, x integer, y integers.

[참고]

When exclude_nodata_value is TRUE, only pixels whose values are not NODATA are returned. Unlike ST_DumpAsPolygons, this function returns one polygon per pixel rather than merging adjacent pixels with the same value.

2.0.0 버전부터 사용할 수 있습니다.

개선 사항: 2.1.0 버전부터 선택적인 exclude_nodata_value 인수를 추가했습니다.

변경 사항: 2.1.1 버전에서 exclude_nodata_value의 습성을 변경했습니다.

예시

This example returns a raster pixel polygon.

Code
WITH raster AS (
    SELECT ST_SetValue(
        ST_SetValue(
            ST_AddBand(
                ST_MakeEmptyRaster(
                    2, 2, 0, 0, 0.001, -0.001, 0.001, 0.001, 4269
                ),
                1, '8BUI', 1, 0
            ),
            2, 2, 10
        ),
        1, 1, NULL
    ) AS rast
), pixels AS (
    SELECT (ST_PixelAsPolygons(rast)).*
    FROM raster
)
SELECT x, y, val, geom AS geom
FROM pixels
ORDER BY x, y;
래스터 출력
x | y | val |                geom
---+---+-----------------------------------------------------------------------------
 1 | 2 |   1 | POLYGON((0.001 -0.001,0.002 0,0.003 -0.001,0.002 -0.002,0.001 -0.001))
 2 | 1 |   1 | POLYGON((0.001 0.001,0.002 0.002,0.003 0.001,0.002 0,0.001 0.001))
 2 | 2 |  10 | POLYGON((0.002 0,0.003 0.001,0.004 0,0.003 -0.001,0.002 0))
Figure
Geometry figure for visual-rt-st-pixelaspolygons-01

제목

ST_PixelAsPoint — 픽셀의 좌상단에 위치하는 포인트 도형을 반환합니다.

요약

geometry ST_PixelAsPoint(raster rast, integer columnx, integer rowy);

Description

픽셀의 좌상단에 위치하는 포인트 도형을 반환합니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT ST_PixelAsPoint(rast, 1, 1) FROM dummy_rast WHERE rid = 1;
래스터 출력
POINT(0.5 0.5)
Figure
Geometry figure for visual-rt-st-pixelaspoint-01

제목

ST_PixelAsPoints — 래스터 밴드의 각 픽셀에 대한 포인트 도형을 각 픽셀의 값 및 X, Y 래스터 좌표와 함께 반환합니다. 포인트 도형의 좌표는 픽셀의 좌상단 좌표입니다.

요약

setof record ST_PixelAsPoints(raster rast, integer band=1, boolean exclude_nodata_value=TRUE);

Description

래스터 밴드의 각 픽셀에 대한 포인트 도형을 각 픽셀의 값 및 X, Y 래스터 좌표와 함께 반환합니다. 포인트 도형의 좌표는 픽셀의 좌상단 좌표입니다.

Return record format: geom geometry, val double precision, x integer, y integers.

[참고]

When exclude_nodata_value = TRUE, only those pixels whose values are not NODATA are returned as points.

2.1.0 버전부터 사용할 수 있습니다.

변경 사항: 2.1.1 버전에서 exclude_nodata_value의 습성을 변경했습니다.

예시

This example returns point features together with a derived marker size that a client can use for value-scaled point rendering.

Code
SELECT
    x,
    y,
    val,
    round((val / 32.0)::numeric, 2) AS marker_scale,geom AS geom
FROM (
    SELECT (ST_PixelAsPoints(rast, 1)).*
    FROM dummy_rast
    WHERE rid = 2
) AS foo
ORDER BY y, x;
래스터 출력
x | y | val | marker_scale |          geom
---+---+-----+--------------+------------------------------
 1 | 1 | 253 |         7.91 | POINT(3427927.75 5793244)
 2 | 1 | 254 |         7.94 | POINT(3427927.8 5793244)
 3 | 1 | 253 |         7.91 | POINT(3427927.85 5793244)
 4 | 1 | 254 |         7.94 | POINT(3427927.9 5793244)
 5 | 1 | 254 |         7.94 | POINT(3427927.95 5793244)
 1 | 2 | 253 |         7.91 | POINT(3427927.75 5793243.95)
 2 | 2 | 254 |         7.94 | POINT(3427927.8 5793243.95)
 3 | 2 | 254 |         7.94 | POINT(3427927.85 5793243.95)
 4 | 2 | 253 |         7.91 | POINT(3427927.9 5793243.95)
 5 | 2 | 249 |         7.78 | POINT(3427927.95 5793243.95)
 1 | 3 | 250 |         7.81 | POINT(3427927.75 5793243.9)
 2 | 3 | 254 |         7.94 | POINT(3427927.8 5793243.9)
 3 | 3 | 254 |         7.94 | POINT(3427927.85 5793243.9)
 4 | 3 | 252 |         7.88 | POINT(3427927.9 5793243.9)
 5 | 3 | 249 |         7.78 | POINT(3427927.95 5793243.9)
 1 | 4 | 251 |         7.84 | POINT(3427927.75 5793243.85)
 2 | 4 | 253 |         7.91 | POINT(3427927.8 5793243.85)
 3 | 4 | 254 |         7.94 | POINT(3427927.85 5793243.85)
 4 | 4 | 254 |         7.94 | POINT(3427927.9 5793243.85)
 5 | 4 | 253 |         7.91 | POINT(3427927.95 5793243.85)
 1 | 5 | 252 |         7.88 | POINT(3427927.75 5793243.8)
 2 | 5 | 250 |         7.81 | POINT(3427927.8 5793243.8)
 3 | 5 | 254 |         7.94 | POINT(3427927.85 5793243.8)
 4 | 5 | 254 |         7.94 | POINT(3427927.9 5793243.8)
 5 | 5 | 254 |         7.94 | POINT(3427927.95 5793243.8)
Figure
Geometry figure for visual-rt-st-pixelaspoints-01

제목

ST_PixelAsCentroid — 픽셀 하나가 차지하는 면의 중심점(포인트 도형)을 반환합니다.

요약

geometry ST_PixelAsCentroid(raster rast, integer x, integer y);

Description

픽셀 하나가 차지하는 면의 중심점(포인트 도형)을 반환합니다.

개선 사항: 2.1.0 버전에서 C 언어로 다시 쓰였습니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT ST_PixelAsCentroid(rast, 1, 1) FROM dummy_rast WHERE rid = 1;
래스터 출력
POINT(1.5 2)
Figure
Geometry figure for visual-rt-st-pixelascentroid-01

제목

ST_PixelAsCentroids — 래스터 밴드의 각 픽셀에 대한 중심점(포인트 도형)을 각 픽셀의 값 및 X, Y 래스터 좌표와 함께 반환합니다. 포인트 도형은 픽셀이 차지하는 면의 중심점입니다.

요약

setof record ST_PixelAsCentroids(raster rast, integer band=1, boolean exclude_nodata_value=TRUE);

Description

래스터 밴드의 각 픽셀에 대한 중심점(포인트 도형)을 각 픽셀의 값 및 X, Y 래스터 좌표와 함께 반환합니다. 포인트 도형은 픽셀이 차지하는 면의 중심점입니다.

Return record format: geom geometry, val double precision, x integer, y integers.

[참고]

When exclude_nodata_value = TRUE, only those pixels whose values are not NODATA are returned as points.

개선 사항: 2.1.0 버전에서 C 언어로 다시 쓰였습니다.

변경 사항: 2.1.1 버전에서 exclude_nodata_value의 습성을 변경했습니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

This example uses LATERAL syntax.

Code
SELECT x, y, val,geom
    FROM (SELECT dp.* FROM dummy_rast, LATERAL ST_PixelAsCentroids(rast, 1) AS dp WHERE rid = 2) foo;
래스터 출력
x | y | val |           st_astext
---+---+-----+--------------------------------
 1 | 1 | 253 | POINT(3427927.775 5793243.975)
 2 | 1 | 254 | POINT(3427927.825 5793243.975)
 3 | 1 | 253 | POINT(3427927.875 5793243.975)
 4 | 1 | 254 | POINT(3427927.925 5793243.975)
 5 | 1 | 254 | POINT(3427927.975 5793243.975)
 1 | 2 | 253 | POINT(3427927.775 5793243.925)
 2 | 2 | 254 | POINT(3427927.825 5793243.925)
 3 | 2 | 254 | POINT(3427927.875 5793243.925)
 4 | 2 | 253 | POINT(3427927.925 5793243.925)
 5 | 2 | 249 | POINT(3427927.975 5793243.925)
 1 | 3 | 250 | POINT(3427927.775 5793243.875)
 2 | 3 | 254 | POINT(3427927.825 5793243.875)
 3 | 3 | 254 | POINT(3427927.875 5793243.875)
 4 | 3 | 252 | POINT(3427927.925 5793243.875)
 5 | 3 | 249 | POINT(3427927.975 5793243.875)
 1 | 4 | 251 | POINT(3427927.775 5793243.825)
 2 | 4 | 253 | POINT(3427927.825 5793243.825)
 3 | 4 | 254 | POINT(3427927.875 5793243.825)
 4 | 4 | 254 | POINT(3427927.925 5793243.825)
 5 | 4 | 253 | POINT(3427927.975 5793243.825)
 1 | 5 | 252 | POINT(3427927.775 5793243.775)
 2 | 5 | 250 | POINT(3427927.825 5793243.775)
 3 | 5 | 254 | POINT(3427927.875 5793243.775)
 4 | 5 | 254 | POINT(3427927.925 5793243.775)
 5 | 5 | 254 | POINT(3427927.975 5793243.775)
Figure
Geometry figure for visual-rt-st-pixelascentroids-01

제목

ST_Value — 입력 columnx, rowy 픽셀의 입력 밴드의 값, 또는 특정 기하학적 포인트의 밴드의 값을 반환합니다. 밴드 번호는 1부터 시작하며, 따로 지정하지 않을 경우 1로 가정합니다. exclude_nodata_value 를 거짓으로 설정할 경우, nodata 픽셀을 포함한 모든 픽셀이 교차한다고 가정하고 값을 반환합니다. exclude_nodata_value 를 설정하지 않은 경우, 래스터의 메타데이터에서 값을 읽어 들입니다.

요약

double precision ST_Value(raster rast, geometry pt, boolean exclude_nodata_value=true);

double precision ST_Value(raster rast, integer band, geometry pt, boolean exclude_nodata_value=true, text resample='nearest');

double precision ST_Value(raster rast, integer x, integer y, boolean exclude_nodata_value=true);

double precision ST_Value(raster rast, integer band, integer x, integer y, boolean exclude_nodata_value=true);

Description

입력한 columnx, rowy 픽셀 또는 특정 도형과 교차하는 픽셀들의 위치의 밴드 값을 설정해서 나온 수정된 래스터를 반환합니다. 밴드 번호는 1부터 시작하며, 따로 설정하지 않을 경우 1로 가정합니다.

exclude_nodata_value 를 참으로 설정할 경우, 래스터의 nodata 값이 아닌 픽셀의 개수만 반환할 것입니다. 모든 픽셀의 개수를 구하려면 exclude_nodata_value 를 거짓으로 설정하십시오.

The allowed values of the resample parameter are "nearest" which performs the default nearest-neighbor resampling, "bilinear" which performs a bilinear interpolation to estimate the value between pixel centers, and the nearest-neighbor boundary options "nearest-UL", "nearest-UR", "nearest-LL", and "nearest-LR". Boundary options choose which pixel is returned when the point lies on a horizontal or vertical pixel boundary, including corner intersections.

Enhanced: 3.7.0 resample accepts nearest-neighbor boundary options "nearest-UL", "nearest-UR", "nearest-LL", and "nearest-LR".

개선 사항: 2.1.0 버전부터 선택적인 exclude_nodata_value 인수를 추가했습니다.

개선 사항: 2.0.0 버전부터 선택적인 exclude_nodata_value 인수를 추가했습니다.

예시

Get raster values at particular postgis geometry points. The srid of your geometry should be same as for your raster.

Code
SELECT rid, ST_Value(rast, foo.pt_geom) As b1pval, ST_Value(rast, 2, foo.pt_geom) As b2pval
FROM dummy_rast CROSS JOIN (SELECT ST_SetSRID(ST_Point(3427927.77, 5793243.76), 0) As pt_geom) As foo
WHERE rid=2;
래스터 출력
rid | b1pval | b2pval
-----+--------+--------
   2 |    252 |     79

General fictitious example using a real table.

Code
SELECT rid, ST_Value(rast, 3, sometable.geom) As b3pval
FROM sometable
WHERE ST_Intersects(rast, sometable.geom);
Code
SELECT rid, ST_Value(rast, 1, 1, 1) As b1pval,
    ST_Value(rast, 2, 1, 1) As b2pval, ST_Value(rast, 3, 1, 1) As b3pval
FROM dummy_rast
WHERE rid=2;
래스터 출력
rid | b1pval | b2pval | b3pval
-----+--------+--------+--------
   2 |    253 |     78 |     70

Get all values in bands 1,2,3 of each pixel.

Code

SELECT x, y, ST_Value(rast, 1, x, y) As b1val,
    ST_Value(rast, 2, x, y) As b2val, ST_Value(rast, 3, x, y) As b3val
FROM dummy_rast CROSS JOIN
generate_series(1, 1000) As x CROSS JOIN generate_series(1, 1000) As y
WHERE rid =  2 AND x <= ST_Width(rast) AND y <= ST_Height(rast);
래스터 출력
 x | y | b1val | b2val | b3val
---+---+-------+-------+-------
 1 | 1 |   253 |    78 |    70
 1 | 2 |   253 |    96 |    80
 1 | 3 |   250 |    99 |    90
 1 | 4 |   251 |    89 |    77
 1 | 5 |   252 |    79 |    62
 2 | 1 |   254 |    98 |    86
 2 | 2 |   254 |   118 |   108
 :
 :

Get all values in bands 1,2,3 of each pixel same as above but returning the upper left point point of each pixel.

Code

SELECT ST_SetSRID(ST_Point(ST_UpperLeftX(rast) + ST_ScaleX(rast)*x,
        ST_UpperLeftY(rast) + ST_ScaleY(rast)*y),
        ST_SRID(rast)) As uplpt,
    ST_Value(rast, 1, x, y) As b1val,
    ST_Value(rast, 2, x, y) As b2val, ST_Value(rast, 3, x, y) As b3val
FROM dummy_rast CROSS JOIN
generate_series(1,1000) As x CROSS JOIN generate_series(1,1000) As y
WHERE rid =  2 AND x <= ST_Width(rast) AND y <= ST_Height(rast);
래스터 출력
            uplpt            | b1val | b2val | b3val
-----------------------------+-------+-------+-------
 POINT(3427929.25 5793245.5) |   253 |    78 |    70
 POINT(3427929.25 5793247)   |   253 |    96 |    80
 POINT(3427929.25 5793248.5) |   250 |    99 |    90
:

Get a polygon formed by union of all pixels that fall in a particular value range and intersect a particular polygon.

Code

SELECT ST_Union(pixpolyg) As shadow
FROM (SELECT ST_Translate(ST_MakeEnvelope(ST_UpperLeftX(rast), ST_UpperLeftY(rast),
            ST_UpperLeftX(rast) + ST_ScaleX(rast),
            ST_UpperLeftY(rast) + ST_ScaleY(rast), 0
            ), ST_ScaleX(rast)*x, ST_ScaleY(rast)*y
        ) As pixpolyg, ST_Value(rast, 2, x, y) As b2val
    FROM dummy_rast CROSS JOIN
generate_series(1,1000) As x CROSS JOIN generate_series(1,1000) As y
WHERE rid =  2
    AND x <= ST_Width(rast) AND y <= ST_Height(rast)) As foo
WHERE
    ST_Intersects(
        pixpolyg,
        ST_GeomFromText('POLYGON((3427928 5793244,3427927.75 5793243.75,3427928 5793243.75,3427928 5793244))',0)
        ) AND b2val != 254;
래스터 출력
        shadow
------------------------------------------------------------------------------------
 MULTIPOLYGON(((3427928 5793243.9,3427928 5793243.85,3427927.95 5793243.85,3427927.95 5793243.9,
 3427927.95 5793243.95,3427928 5793243.95,3427928.05 5793243.95,3427928.05 5793243.9,3427928 5793243.9)),((3427927.95 5793243.9,3427927.95 579324
3.85,3427927.9 5793243.85,3427927.85 5793243.85,3427927.85 5793243.9,3427927.9 5793243.9,3427927.9 5793243.95,
3427927.95 5793243.95,3427927.95 5793243.9)),((3427927.85 5793243.75,3427927.85 5793243.7,3427927.8 5793243.7,3427927.8 5793243.75,
3427927.8 5793243.8,3427927.8 5793243.85,3427927.85 5793243.85,3427927.85 5793243.8,3427927.85 5793243.75)),
((3427928.05 5793243.75,3427928.05 5793243.7,3427928 5793243.7,3427927.95 5793243.7,3427927.95 5793243.75,3427927.95 5793243.8,3427
927.95 5793243.85,3427928 5793243.85,3427928 5793243.8,3427928.05 5793243.8,
3427928.05 5793243.75)),((3427927.95 5793243.75,3427927.95 5793243.7,3427927.9 5793243.7,3427927.85 5793243.7,
3427927.85 5793243.75,3427927.85 5793243.8,3427927.85 5793243.85,3427927.9 5793243.85,
3427927.95 5793243.85,3427927.95 5793243.8,3427927.95 5793243.75)))

Checking all the pixels of a large raster tile can take a long time. You can dramatically improve speed at some lose of precision by orders of magnitude. By sampling pixels using the step optional parameter of generate_series. This next example does the same as previous but by checking 1 for every 4 (2x2) pixels and putting in the last checked. Putting in the checked pixel as the value for subsequent 4.

Code


SELECT ST_Union(pixpolyg) As shadow
FROM (SELECT ST_Translate(ST_MakeEnvelope(ST_UpperLeftX(rast), ST_UpperLeftY(rast),
            ST_UpperLeftX(rast) + ST_ScaleX(rast)*2,
            ST_UpperLeftY(rast) + ST_ScaleY(rast)*2, 0
            ), ST_ScaleX(rast)*x, ST_ScaleY(rast)*y
        ) As pixpolyg, ST_Value(rast, 2, x, y) As b2val
    FROM dummy_rast CROSS JOIN
generate_series(1,1000,2) As x CROSS JOIN generate_series(1,1000,2) As y
WHERE rid =  2
    AND x <= ST_Width(rast)  AND y <= ST_Height(rast)  ) As foo
WHERE
    ST_Intersects(
        pixpolyg,
        ST_GeomFromText('POLYGON((3427928 5793244,3427927.75 5793243.75,3427928 5793243.75,3427928 5793244))',0)
        ) AND b2val != 254;
래스터 출력
        shadow
------------------------------------------------------------------------------------
 MULTIPOLYGON(((3427927.9 5793243.85,3427927.8 5793243.85,3427927.8 5793243.95,
 3427927.9 5793243.95,3427928 5793243.95,3427928.1 5793243.95,3427928.1 5793243.85,3427928 5793243.85,3427927.9 5793243.85)),
 ((3427927.9 5793243.65,3427927.8 5793243.65,3427927.8 5793243.75,3427927.8 5793243.85,3427927.9 5793243.85,
 3427928 5793243.85,3427928 5793243.75,3427928.1 5793243.75,3427928.1 5793243.65,3427928 5793243.65,3427927.9 5793243.65)))


제목

ST_NearestValue — columnx 및 rowy, 또는 래스터와 동일한 공간 참조 좌표 시스템 단위로 표현된 기하학적 포인트로 지정된 입력 밴드의 픽셀에 가장 가까운 NODATA 가 아닌 값을 반환합니다.

요약

double precision ST_NearestValue(raster rast, integer bandnum, geometry pt, boolean exclude_nodata_value=true);

double precision ST_NearestValue(raster rast, geometry pt, boolean exclude_nodata_value=true);

double precision ST_NearestValue(raster rast, integer bandnum, integer columnx, integer rowy, boolean exclude_nodata_value=true);

double precision ST_NearestValue(raster rast, integer columnx, integer rowy, boolean exclude_nodata_value=true);

Description

입력한 columnx, rowy 픽셀, 또는 특정 기하학적 포인트 위치에 있는 입력 밴드에 가장 가까운 NODATA 가 아닌 값을 반환합니다. columnx, rowy 픽셀 또는 특정 기하학적 포인트 위치의 픽셀이 NODATA 일 경우, 이 함수는 columnx, rowy 픽셀 또는 특정 기하학적 포인트 위치에 가장 가까우며 NODATA 가 아닌 픽셀을 찾을 것입니다.

밴드 번호는 1부터 시작하며, 따로 지정하지 않을 경우 bandnum 을 1로 가정합니다. exclude_nodata_value 를 거짓으로 설정할 경우, nodata 픽셀을 포함한 모든 픽셀이 교차한다고 가정하고 값을 반환합니다. exclude_nodata_value 를 설정하지 않은 경우, 래스터의 메타데이터에서 값을 읽어 들입니다.

2.1.0 버전부터 사용할 수 있습니다.

[참고]

ST_NearestValue 함수는 즉석에서 ST_Value를 대체할 수 있습니다.

예시

This example reads a value from pixel 2x2.

Code
WITH source AS (
    SELECT ST_SetValues(
        ST_AddBand(
            ST_MakeEmptyRaster(5, 5, -2, 2, 1, -1, 0, 0, 0),
            1, '8BUI', 1, 0
        ),
        1, 1, 1,
        ARRAY[
            [0, 1, 1, 1, 1],
            [1, 1, 1, 0, 1],
            [1, 0, 1, 1, 1],
            [1, 1, 1, 1, 0],
            [1, 1, 0, 1, 1]
        ]::double precision[][]
    ) AS rast
)
SELECT
    ST_Value(rast, 2, 2) AS value,
    ST_NearestValue(rast, 2, 2) AS nearestvalue
FROM source
래스터 출력
value | nearestvalue
-------+--------------
     1 |            1

This example reads a NODATA value from pixel 2x3.

Code
WITH source AS (
    SELECT ST_SetValues(
        ST_AddBand(
            ST_MakeEmptyRaster(5, 5, -2, 2, 1, -1, 0, 0, 0),
            1, '8BUI', 1, 0
        ),
        1, 1, 1,
        ARRAY[
            [0, 1, 1, 1, 1],
            [1, 1, 1, 0, 1],
            [1, 0, 1, 1, 1],
            [1, 1, 1, 1, 0],
            [1, 1, 0, 1, 1]
        ]::double precision[][]
    ) AS rast
)
SELECT
    ST_Value(rast, 2, 3) AS value,
    ST_NearestValue(rast, 2, 3) AS nearestvalue
FROM source
래스터 출력
value | nearestvalue
-------+--------------
       |            1

제목

ST_SetZ — Returns a geometry with the same X/Y coordinates as the input geometry, and values from the raster copied into the Z dimension using the requested resample algorithm.

요약

geometry ST_SetZ(raster rast, geometry geom, text resample=nearest, integer band=1);

Description

Returns a geometry with the same X/Y coordinates as the input geometry, and values from the raster copied into the Z dimensions using the requested resample algorithm.

The resample parameter can be set to "nearest" to copy the values from the cell each vertex falls within, or "bilinear" to use bilinear interpolation to calculate a value that takes neighboring cells into account also.

Availability: 3.2.0

예시

2x2 test raster with values. 10 50. 40 20.

Code
WITH test_raster AS (
SELECT
ST_SetValues(
ST_AddBand(
ST_MakeEmptyRaster(
      width => 2,
      height => 2,
      upperleftx => 0,
      upperlefty => 2,
      scalex => 1.0,
      scaley => -1.0,
      skewx => 0,
      skewy => 0,
      srid => 4326),
    index => 1,
    pixeltype => '16BSI',
    initialvalue => 0,
    nodataval => -999
),
  1,
  1,
  1,
  newvalueset => ARRAY[ARRAY[10.0::float8, 50.0::float8], ARRAY[40.0::float8, 20.0::float8]]) AS rast
)
SELECT
ST_SetZ(
    rast,
    band => 1,
    geom => 'SRID=4326;LINESTRING(1.0 1.9,1.0 0.2)'::geometry,
    resample => 'bilinear'
)
FROM test_raster
래스터 출력
LINESTRING Z (1 1.9 38,1 0.2 27)
Figure
Geometry figure for visual-rt-st-setz-01

제목

ST_SetM — Returns a geometry with the same X/Y coordinates as the input geometry, and values from the raster copied into the M dimension using the requested resample algorithm.

요약

geometry ST_SetM(raster rast, geometry geom, text resample=nearest, integer band=1);

Description

Returns a geometry with the same X/Y coordinates as the input geometry, and values from the raster copied into the M dimensions using the requested resample algorithm.

The resample parameter can be set to "nearest" to copy the values from the cell each vertex falls within, or "bilinear" to use bilinear interpolation to calculate a value that takes neighboring cells into account also.

Availability: 3.2.0

예시

2x2 test raster with values. 10 50. 40 20.

Code
WITH test_raster AS (
SELECT
ST_SetValues(
ST_AddBand(
ST_MakeEmptyRaster(
      width => 2,
      height => 2,
      upperleftx => 0,
      upperlefty => 2,
      scalex => 1.0,
      scaley => -1.0,
      skewx => 0,
      skewy => 0,
      srid => 4326),
    index => 1,
    pixeltype => '16BSI',
    initialvalue => 0,
    nodataval => -999
),
  1,
  1,
  1,
  newvalueset => ARRAY[ARRAY[10.0::float8, 50.0::float8], ARRAY[40.0::float8, 20.0::float8]]) AS rast
)
SELECT
ST_SetM(
    rast,
    band => 1,
    geom => 'SRID=4326;LINESTRING(1.0 1.9,1.0 0.2)'::geometry,
    resample => 'bilinear'
)
FROM test_raster
래스터 출력
LINESTRING M (1 1.9 38,1 0.2 27)
Figure
Geometry figure for visual-rt-st-setm-01

제목

ST_Neighborhood — columnx 및 rowy, 또는 래스터와 동일한 공간 참조 좌표 시스템 단위로 표현된 기하학적 포인트로 지정된 입력 밴드의 픽셀 주위의 NODATA 가 아닌 값들의 이중 정밀도 데이터형 2차원 배열을 반환합니다.

요약

double precision[][] ST_Neighborhood(raster rast, integer bandnum, integer columnX, integer rowY, integer distanceX, integer distanceY, boolean exclude_nodata_value=true);

double precision[][] ST_Neighborhood(raster rast, integer columnX, integer rowY, integer distanceX, integer distanceY, boolean exclude_nodata_value=true);

double precision[][] ST_Neighborhood(raster rast, integer bandnum, geometry pt, integer distanceX, integer distanceY, boolean exclude_nodata_value=true);

double precision[][] ST_Neighborhood(raster rast, geometry pt, integer distanceX, integer distanceY, boolean exclude_nodata_value=true);

Description

columnx 및 rowy, 또는 래스터와 동일한 공간 참조 좌표 시스템 단위로 표현된 기하학적 포인트로 지정된 입력 밴드의 픽셀 주위의 NODATA 가 아닌 값들의 이중 정밀도 데이터형 2차원 배열을 반환합니다. distanceXdistanceY 파라미터가 지정한 픽셀 주위의 픽셀 개수를 X 및 Y축으로 정의합니다. 예를 들어, 사용자 설정 픽셀 주위로 X축을 따라 3픽셀 거리 안 그리고 Y축을 따라 2픽셀 거리 안의 모든 값을 원하는 경우 말입니다. 2차원 배열의 중심값은 columnx 및 rowy 또는 기하학적 포인트로 지정된 픽셀의 값이 될 것입니다.

밴드 번호는 1부터 시작하며, 따로 지정하지 않을 경우 bandnum 을 1로 가정합니다. exclude_nodata_value 를 거짓으로 설정할 경우, nodata 픽셀을 포함한 모든 픽셀이 교차한다고 가정하고 값을 반환합니다. exclude_nodata_value 를 설정하지 않은 경우, 래스터의 메타데이터에서 값을 읽어 들입니다.

[참고]

반환되는 2차원 배열의 각 축의 구성 요소 개수는 2 * (distanceX|distanceY) + 1입니다. 따라서 distanceXdistanceY 가 각각 1인 경우, 반환되는 배열은 3x3이 될 것입니다.

[참고]

ST_Min4ma, ST_Sum4ma, ST_Mean4ma 같은 어떤 래스터 공간 처리 내장 함수도 이 2차원 배열 출력물을 입력받을 수 있습니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

This example reads a value from pixel 2x2.

Code
SELECT
    ST_Neighborhood(rast, 2, 2, 1, 1)
FROM (
    SELECT
        ST_SetValues(ST_AddBand(ST_MakeEmptyRaster(5, 5, -2, 2, 1, -1, 0, 0, 0),
                '8BUI'::text, 1, 0
            ),
            1, 1, 1, ARRAY[
                [0, 1, 1, 1, 1],
                [1, 1, 1, 0, 1],
                [1, 0, 1, 1, 1],
                [1, 1, 1, 1, 0],
                [1, 1, 0, 1, 1]
            ]::double precision[],
            1
        ) AS rast
) AS foo
래스터 출력
{{NULL,1,1},{1,1,1},{1,NULL,1}}

This example reads a NODATA value from pixel 2x3.

Code
SELECT
    ST_Neighborhood(rast, 2, 3, 1, 1)
FROM (
    SELECT
        ST_SetValues(ST_AddBand(ST_MakeEmptyRaster(5, 5, -2, 2, 1, -1, 0, 0, 0),
                '8BUI'::text, 1, 0
            ),
            1, 1, 1, ARRAY[
                [0, 1, 1, 1, 1],
                [1, 1, 1, 0, 1],
                [1, 0, 1, 1, 1],
                [1, 1, 1, 1, 0],
                [1, 1, 0, 1, 1]
            ]::double precision[],
            1
        ) AS rast
) AS foo
래스터 출력
{{1,1,1},{1,NULL,1},{1,1,1}}

Pixel 3x3 has value. Exclude_nodata_value = FALSE.

Code
SELECT
    ST_Neighborhood(rast, 3, 3, 1, 1, false)
FROM ST_SetValues(ST_AddBand(ST_MakeEmptyRaster(5, 5, -2, 2, 1, -1, 0, 0, 0),
                '8BUI'::text, 1, 0
            ),
            1, 1, 1, ARRAY[
                [0, 1, 1, 1, 1],
                [1, 1, 1, 0, 1],
                [1, 0, 1, 1, 1],
                [1, 1, 1, 1, 0],
                [1, 1, 0, 1, 1]
            ]::double precision[],
            1
        ) AS rast
래스터 출력
{{1,1,0},{0,1,1},{1,1,1}}

제목

ST_SetValue — 입력한 columnx, rowy 픽셀 또는 특정 도형과 교차하는 픽셀들의 위치의 밴드 값을 설정해서 나온 수정된 래스터를 반환합니다. 밴드 번호는 1부터 시작하며, 따로 설정하지 않을 경우 1로 가정합니다.

요약

raster ST_SetValue(raster rast, integer bandnum, geometry geom, double precision newvalue);

raster ST_SetValue(raster rast, geometry geom, double precision newvalue);

raster ST_SetValue(raster rast, integer bandnum, integer columnx, integer rowy, double precision newvalue);

raster ST_SetValue(raster rast, integer columnx, integer rowy, double precision newvalue);

Description

Returns modified raster resulting from setting the specified pixels' values to new value for the designated band given the raster's row and column or a geometry. If no band is specified, then band 1 is assumed.

개선 사항: 2.1.0 버전부터 ST_SetValue() 함수의 도형 변종이 포인트뿐만이 아니라 모든 도형 유형을 지원합니다. 이 도형 변종은 ST_SetValues()의 geomval[] 변종을 감싸는 래퍼(wrapper)입니다.

예시

This example uses geometry input.

Code

                SELECT (foo.geomval).val, ST_Union((foo.geomval).geom)
FROM (SELECT ST_DumpAsPolygons(ST_SetValue(
            rast,
            1,
            ST_Point(3427927.75, 5793243.95),
            50)
            ) As geomval
FROM dummy_rast
where rid = 2) As foo
WHERE (foo.geomval).val < 250
GROUP BY (foo.geomval).val;
래스터 출력
 val |                                                     st_astext
-----+-------------------------------------------------------------------
  50 | POLYGON((3427927.75 5793244,3427927.75 5793243.95,3427927.8 579324 ...
 249 | POLYGON((3427927.95 5793243.95,3427927.95 5793243.85,3427928 57932 ...

This example stores the changed raster.

Code
UPDATE dummy_rast SET rast = ST_SetValue(rast, 1, ST_Point(3427927.75, 5793243.95), 100)
    WHERE rid = 2   ;

                

제목

ST_SetValues — 지정한 밴드의 값들을 설정해서 나온 수정된 래스터를 반환합니다.

요약

raster ST_SetValues(raster rast, integer nband, integer columnx, integer rowy, double precision[][] newvalueset, boolean[][] noset=NULL, boolean keepnodata=FALSE);

raster ST_SetValues(raster rast, integer nband, integer columnx, integer rowy, double precision[][] newvalueset, double precision nosetvalue, boolean keepnodata=FALSE);

raster ST_SetValues(raster rast, integer nband, integer columnx, integer rowy, integer width, integer height, double precision newvalue, boolean keepnodata=FALSE);

raster ST_SetValues(raster rast, integer columnx, integer rowy, integer width, integer height, double precision newvalue, boolean keepnodata=FALSE);

raster ST_SetValues(raster rast, integer nband, geomval[] geomvalset, boolean keepnodata=FALSE);

Description

지정한 밴드에 대해, 설정한 픽셀들을 새로운 값(들)로 설정해서 나온 수정된 래스터를 반환합니다.

keepnodata 가 TRUE일 경우, NODATA 값인 픽셀들을 newvalueset 에 있는 상응하는 값으로 설정하지 않을 것입니다.

변종 1의 경우, columnx, rowy 픽셀 좌표 및 newvalueset 배열의 차원이 설정 대상 픽셀들을 결정합니다. 이미 newvalueset 에 있는 값들을 가진 픽셀을 중복 설정하는 것을 막기 위해 noset 을 이용할 수 있습니다(PostgreSQL이 이가 빠진 배열을 허용하지 않기 때문입니다). 변종 1 예시를 참조하십시오.

변종 2는 변종 1과 비슷하지만, 불 값인 noset 배열 대신 단순한 이중 정밀도 데이터형인 nosetvalue 를 입력받습니다. newvalueset 가운데 nosetvalue 값을 가진 구성 요소를 무시할 것입니다. 변종 2 예시를 참조하십시오.

변종 3의 경우, columnx, rowy 픽셀 좌표, widthheight 가 설정 대상 픽셀들을 결정합니다. 변종 3 예시를 참조하십시오.

변종 4는 rast 의 첫 번째 밴드의 픽셀들이 설정될 것이라고 가정하는 점만 제외하면 변종 3과 동일합니다.

변종 5의 경우, 설정 대상 픽셀들을 결정하는 데 geomval 의 배열을 이용합니다. 배열 안의 도형들이 모두 POINT 또는 MULTIPOINT일 경우, 이 함수는 각 포인트의 경도와 위도를 써서 직접 픽셀을 설정하는 지름길을 이용합니다. 그렇지 않을 경우, 도형을 래스터로 변환한 다음 동일한 방식으로 반복합니다. 변종 5 예시를 참조하십시오.

2.1.0 버전부터 사용할 수 있습니다.

예시

Variant 1.

These examples pass FALSE for exclude_nodata_value so that every raster cell remains visible. NODATA cells display the band's NODATA value, which is 0 here.

Set the lower-right 2 by 2 block of a 3 by 3 raster to 9.

Code
SELECT
    (poly).x,
    (poly).y,
    (poly).val
FROM (
SELECT
    ST_PixelAsPolygons(ST_SetValues(ST_AddBand(ST_MakeEmptyRaster(3, 3, 0, 0, 1, -1, 0, 0, 0),
                1, '8BUI', 1, 0
            ),
            1, 2, 2, ARRAY[[9, 9], [9, 9]]::double precision[][]
        ),
        1, FALSE
    ) AS poly
) foo
ORDER BY 1, 2;
래스터 출력
 x | y | val
---+---+-----
 1 | 1 |   1
 1 | 2 |   1
 1 | 3 |   1
 2 | 1 |   1
 2 | 2 |   9
 2 | 3 |   9
 3 | 1 |   1
 3 | 2 |   9
 3 | 3 |   9

Replace the complete raster from an array; the central NULL becomes NODATA.

Code
SELECT
    (poly).x,
    (poly).y,
    (poly).val
FROM (
SELECT
    ST_PixelAsPolygons(ST_SetValues(ST_AddBand(ST_MakeEmptyRaster(3, 3, 0, 0, 1, -1, 0, 0, 0),
                1, '8BUI', 1, 0
            ),
            1, 1, 1, ARRAY[[9, 9, 9], [9, NULL, 9], [9, 9, 9]]::double precision[][]
        ),
        1, FALSE
    ) AS poly
) foo
ORDER BY 1, 2;
래스터 출력
 x | y | val
---+---+-----
 1 | 1 |   9
 1 | 2 |   9
 1 | 3 |   9
 2 | 1 |   9
 2 | 2 |   0
 2 | 3 |   9
 3 | 1 |   9
 3 | 2 |   9
 3 | 3 |   9

Use the noset mask to retain the left-middle source pixel while replacing the other cells.

Code
SELECT
    (poly).x,
    (poly).y,
    (poly).val
FROM (
SELECT
    ST_PixelAsPolygons(ST_SetValues(ST_AddBand(ST_MakeEmptyRaster(3, 3, 0, 0, 1, -1, 0, 0, 0),
                1, '8BUI', 1, 0
            ),
            1, 1, 1,
                ARRAY[[9, 9, 9], [9, NULL, 9], [9, 9, 9]]::double precision[][],
                ARRAY[[false], [true]]::boolean[][]
        ),
        1, FALSE
    ) AS poly
) foo
ORDER BY 1, 2;
래스터 출력
x | y | val
---+---+-----
 1 | 1 |   9
 1 | 2 |   1
 1 | 3 |   9
 2 | 1 |   9
 2 | 2 |   0
 2 | 3 |   9
 3 | 1 |   9
 3 | 2 |   9
 3 | 3 |   9

With keepnodata enabled, an existing NODATA pixel is not overwritten.

Code
SELECT
    (poly).x,
    (poly).y,
    (poly).val
FROM (
SELECT
    ST_PixelAsPolygons(ST_SetValues(ST_SetValue(ST_AddBand(ST_MakeEmptyRaster(3, 3, 0, 0, 1, -1, 0, 0, 0),
                    1, '8BUI', 1, 0
                ),
                1, 1, 1, NULL
            ),
            1, 1, 1,
                ARRAY[[9, 9, 9], [9, NULL, 9], [9, 9, 9]]::double precision[][],
                ARRAY[[false], [true]]::boolean[][],
                TRUE
        ),
        1, FALSE
    ) AS poly
) foo
ORDER BY 1, 2;
래스터 출력
x | y | val
---+---+-----
 1 | 1 |   0
 1 | 2 |   1
 1 | 3 |   9
 2 | 1 |   9
 2 | 2 |   0
 2 | 3 |   9
 3 | 1 |   9
 3 | 2 |   9
 3 | 3 |   9

Variant 2.

Use -1 as the value that should not be written; only the lower-right 2 by 2 block changes.

Code
SELECT
    (poly).x,
    (poly).y,
    (poly).val
FROM (
SELECT
    ST_PixelAsPolygons(ST_SetValues(ST_AddBand(ST_MakeEmptyRaster(3, 3, 0, 0, 1, -1, 0, 0, 0),
                1, '8BUI', 1, 0
            ),
            1, 1, 1, ARRAY[[-1, -1, -1], [-1, 9, 9], [-1, 9, 9]]::double precision[][], -1
        ),
        1, FALSE
    ) AS poly
) foo
ORDER BY 1, 2;
래스터 출력
x | y | val
---+---+-----
 1 | 1 |   1
 1 | 2 |   1
 1 | 3 |   1
 2 | 1 |   1
 2 | 2 |   9
 2 | 3 |   9
 3 | 1 |   1
 3 | 2 |   9
 3 | 3 |   9

The same update can use NULL as the value that should not be written.

Code
SELECT
    (poly).x,
    (poly).y,
    (poly).val
FROM (
SELECT
    ST_PixelAsPolygons(ST_SetValues(ST_AddBand(ST_MakeEmptyRaster(3, 3, 0, 0, 1, -1, 0, 0, 0),
                1, '8BUI', 1, 0
            ),
            1, 1, 1, ARRAY[[NULL, NULL, NULL], [NULL, 9, 9], [NULL, 9, 9]]::double precision[][], NULL::double precision
        ),
        1, FALSE
    ) AS poly
) foo
ORDER BY 1, 2;
래스터 출력
x | y | val
---+---+-----
 1 | 1 |   1
 1 | 2 |   1
 1 | 3 |   1
 2 | 1 |   1
 2 | 2 |   9
 2 | 3 |   9
 3 | 1 |   1
 3 | 2 |   9
 3 | 3 |   9

Variant 3.

Set a 2 by 2 rectangle starting at column 2, row 2.

Code
SELECT
    (poly).x,
    (poly).y,
    (poly).val
FROM (
SELECT
    ST_PixelAsPolygons(ST_SetValues(ST_AddBand(ST_MakeEmptyRaster(3, 3, 0, 0, 1, -1, 0, 0, 0),
                1, '8BUI', 1, 0
            ),
            1, 2, 2, 2, 2, 9
        ),
        1, FALSE
    ) AS poly
) foo
ORDER BY 1, 2;
래스터 출력
x | y | val
---+---+-----
 1 | 1 |   1
 1 | 2 |   1
 1 | 3 |   1
 2 | 1 |   1
 2 | 2 |   9
 2 | 3 |   9
 3 | 1 |   1
 3 | 2 |   9
 3 | 3 |   9

When keepnodata is true, the NODATA cell inside the rectangle remains unchanged.

Code
SELECT
    (poly).x,
    (poly).y,
    (poly).val
FROM (
SELECT
    ST_PixelAsPolygons(ST_SetValues(ST_SetValue(ST_AddBand(ST_MakeEmptyRaster(3, 3, 0, 0, 1, -1, 0, 0, 0),
                    1, '8BUI', 1, 0
                ),
                1, 2, 2, NULL
            ),
            1, 2, 2, 2, 2, 9, TRUE
        ),
        1, FALSE
    ) AS poly
) foo
ORDER BY 1, 2;
래스터 출력
x | y | val
---+---+-----
 1 | 1 |   1
 1 | 2 |   1
 1 | 3 |   1
 2 | 1 |   1
 2 | 2 |   0
 2 | 3 |   9
 3 | 1 |   1
 3 | 2 |   9
 3 | 3 |   9

Variant 5.

Code
WITH foo AS (
    SELECT 1 AS rid, ST_AddBand(ST_MakeEmptyRaster(5, 5, 0, 0, 1, -1, 0, 0, 0), 1, '8BUI', 0, 0) AS rast
), bar AS (
    SELECT 1 AS gid, 'SRID=0;POINT(2.5 -2.5)'::geometry geom UNION ALL
    SELECT 2 AS gid, 'SRID=0;POLYGON((1 -1,4 -1,4 -4,1 -4,1 -1))'::geometry geom UNION ALL
    SELECT 3 AS gid, 'SRID=0;POLYGON((0 0,5 0,5 -1,1 -1,1 -4,0 -4,0 0))'::geometry geom UNION ALL
    SELECT 4 AS gid, 'SRID=0;MULTIPOINT(0 0,4 4,4 -4)'::geometry
), changed AS (
    SELECT rid, gid, ST_SetValue(rast, 1, geom, gid) AS rast
    FROM foo
    CROSS JOIN bar
)
SELECT
    rid,
    gid,
    y,
    array_agg(ST_Value(rast, 1, x, y) ORDER BY x) AS values
FROM changed
CROSS JOIN generate_series(1, 5) AS x
CROSS JOIN generate_series(1, 5) AS y
GROUP BY rid, gid, y
ORDER BY rid, gid, y;
래스터 출력
rid | gid | y |           values
-----+-----+---+----------------------------
   1 |   1 | 1 | {NULL,NULL,NULL,NULL,NULL}
   1 |   1 | 2 | {NULL,NULL,NULL,NULL,NULL}
   1 |   1 | 3 | {NULL,NULL,1,NULL,NULL}
   1 |   1 | 4 | {NULL,NULL,NULL,NULL,NULL}
   1 |   1 | 5 | {NULL,NULL,NULL,NULL,NULL}
   1 |   2 | 1 | {NULL,NULL,NULL,NULL,NULL}
   1 |   2 | 2 | {NULL,2,2,2,NULL}
   1 |   2 | 3 | {NULL,2,2,2,NULL}
   1 |   2 | 4 | {NULL,2,2,2,NULL}
   1 |   2 | 5 | {NULL,NULL,NULL,NULL,NULL}
   1 |   3 | 1 | {3,3,3,3,3}
   1 |   3 | 2 | {3,NULL,NULL,NULL,NULL}
   1 |   3 | 3 | {3,NULL,NULL,NULL,NULL}
   1 |   3 | 4 | {3,NULL,NULL,NULL,NULL}
   1 |   3 | 5 | {NULL,NULL,NULL,NULL,NULL}
   1 |   4 | 1 | {4,NULL,NULL,NULL,NULL}
   1 |   4 | 2 | {NULL,NULL,NULL,NULL,NULL}
   1 |   4 | 3 | {NULL,NULL,NULL,NULL,NULL}
   1 |   4 | 4 | {NULL,NULL,NULL,NULL,NULL}
   1 |   4 | 5 | {NULL,NULL,NULL,NULL,4}
(20 rows)

다음은 배열 후반에 있는 geomvals가 전반의 geomvals를 덮어 쓸 수 있다는 사실을 보여주는 예시입니다.

Code
WITH foo AS (
    SELECT 1 AS rid, ST_AddBand(ST_MakeEmptyRaster(5, 5, 0, 0, 1, -1, 0, 0, 0), 1, '8BUI', 0, 0) AS rast
), bar AS (
    SELECT 1 AS gid, 'SRID=0;POINT(2.5 -2.5)'::geometry geom UNION ALL
    SELECT 2 AS gid, 'SRID=0;POLYGON((1 -1,4 -1,4 -4,1 -4,1 -1))'::geometry geom UNION ALL
    SELECT 3 AS gid, 'SRID=0;POLYGON((0 0,5 0,5 -1,1 -1,1 -4,0 -4,0 0))'::geometry geom UNION ALL
    SELECT 4 AS gid, 'SRID=0;MULTIPOINT(0 0,4 4,4 -4)'::geometry
), changed AS (
    SELECT ST_SetValues(
        rast,
        1,
        ARRAY[
            ROW((SELECT geom FROM bar WHERE gid = 1), 1),
            ROW((SELECT geom FROM bar WHERE gid = 2), 2)
        ]::geomval[]
    ) AS rast
    FROM foo
)
SELECT
    y,
    array_agg(ST_Value(rast, 1, x, y) ORDER BY x) AS values
FROM changed
CROSS JOIN generate_series(1, 5) AS x
CROSS JOIN generate_series(1, 5) AS y
GROUP BY y
ORDER BY y;
래스터 출력
y |           values
---+----------------------------
 1 | {NULL,NULL,NULL,NULL,NULL}
 2 | {NULL,2,2,2,NULL}
 3 | {NULL,2,2,2,NULL}
 4 | {NULL,2,2,2,NULL}
 5 | {NULL,NULL,NULL,NULL,NULL}
(5 rows)

이전 예시와 반대되는 상황을 보여주는 예시입니다.

Code
WITH foo AS (
    SELECT 1 AS rid, ST_AddBand(ST_MakeEmptyRaster(5, 5, 0, 0, 1, -1, 0, 0, 0), 1, '8BUI', 0, 0) AS rast
), bar AS (
    SELECT 1 AS gid, 'SRID=0;POINT(2.5 -2.5)'::geometry geom UNION ALL
    SELECT 2 AS gid, 'SRID=0;POLYGON((1 -1,4 -1,4 -4,1 -4,1 -1))'::geometry geom UNION ALL
    SELECT 3 AS gid, 'SRID=0;POLYGON((0 0,5 0,5 -1,1 -1,1 -4,0 -4,0 0))'::geometry geom UNION ALL
    SELECT 4 AS gid, 'SRID=0;MULTIPOINT(0 0,4 4,4 -4)'::geometry
), changed AS (
    SELECT ST_SetValues(
        rast,
        1,
        ARRAY[
            ROW((SELECT geom FROM bar WHERE gid = 2), 2),
            ROW((SELECT geom FROM bar WHERE gid = 1), 1)
        ]::geomval[]
    ) AS rast
    FROM foo
)
SELECT
    y,
    array_agg(ST_Value(rast, 1, x, y) ORDER BY x) AS values
FROM changed
CROSS JOIN generate_series(1, 5) AS x
CROSS JOIN generate_series(1, 5) AS y
GROUP BY y
ORDER BY y;
래스터 출력
y |           values
---+----------------------------
 1 | {NULL,NULL,NULL,NULL,NULL}
 2 | {NULL,2,2,2,NULL}
 3 | {NULL,2,1,2,NULL}
 4 | {NULL,2,2,2,NULL}
 5 | {NULL,NULL,NULL,NULL,NULL}
(5 rows)

제목

ST_DumpValues — 지정된 밴드의 값들을 2차원 배열로 반환합니다.

요약

setof record ST_DumpValues( raster rast , integer[] nband=NULL , boolean exclude_nodata_value=true );

double precision[][] ST_DumpValues( raster rast , integer nband , boolean exclude_nodata_value=true );

Description

지정된 밴드의 값들을 2차원 배열로 반환합니다(첫 번째 인덱스가 행, 두 번째 인덱스가 열입니다). nband 가 NULL이거나 설정되지 않은 경우, 래스터의 모든 밴드를 처리합니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

Code
WITH foo AS (
    SELECT ST_AddBand(ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 0, 0, 1, -1, 0, 0, 0), 1, '8BUI'::text, 1, 0), 2, '32BF'::text, 3, -9999), 3, '16BSI', 0, 0) AS rast
)
SELECT
    (ST_DumpValues(rast)).*
FROM foo;
래스터 출력
nband |                       valarray
-------+------------------------------------------------------
     1 | {{1,1,1},{1,1,1},{1,1,1}}
     2 | {{3,3,3},{3,3,3},{3,3,3}}
     3 | {{NULL,NULL,NULL},{NULL,NULL,NULL},{NULL,NULL,NULL}}
(3 rows)
Code
WITH foo AS (
    SELECT ST_AddBand(ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(3, 3, 0, 0, 1, -1, 0, 0, 0), 1, '8BUI'::text, 1, 0), 2, '32BF'::text, 3, -9999), 3, '16BSI', 0, 0) AS rast
)
SELECT
    (ST_DumpValues(rast, ARRAY[3, 1])).*
FROM foo;
래스터 출력
nband |                       valarray
-------+------------------------------------------------------
     3 | {{NULL,NULL,NULL},{NULL,NULL,NULL},{NULL,NULL,NULL}}
     1 | {{1,1,1},{1,1,1},{1,1,1}}
(2 rows)
Code
WITH foo AS (
    SELECT ST_SetValue(ST_AddBand(ST_MakeEmptyRaster(3, 3, 0, 0, 1, -1, 0, 0, 0), 1, '8BUI', 1, 0), 1, 2, 5) AS rast
)
SELECT
    (ST_DumpValues(rast, 1))[2][1]
FROM foo;
래스터 출력
5

제목

ST_PixelOfValue — 검색 값과 일치하는 값을 가진 픽셀의 columnx, rowy 좌표를 반환합니다.

요약

setof record ST_PixelOfValue( raster rast , integer nband , double precision[] search , boolean exclude_nodata_value=true );

setof record ST_PixelOfValue( raster rast , double precision[] search , boolean exclude_nodata_value=true );

setof record ST_PixelOfValue( raster rast , integer nband , double precision search , boolean exclude_nodata_value=true );

setof record ST_PixelOfValue( raster rast , double precision search , boolean exclude_nodata_value=true );

Description

검색 값과 일치하는 값을 가진 픽셀의 columnx, rowy 좌표를 반환합니다. 밴드를 따로 설정하지 않을 경우, 밴드 1로 가정합니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

Code
WITH source AS (
    SELECT ST_SetValues(
        ST_AddBand(
            ST_MakeEmptyRaster(5, 5, -2, 2, 1, -1, 0, 0, 0),
            1, '8BUI', 1, 0
        ),
        1, 1, 1,
        ARRAY[
            [0, 1, 1, 1, 1],
            [1, 1, 1, 0, 1],
            [1, 0, 1, 1, 1],
            [1, 1, 1, 1, 255],
            [1, 1, 0, 1, 1]
        ]::double precision[][]
    ) AS rast
)
SELECT (ST_PixelOfValue(rast, 1, ARRAY[1, 255])).*
FROM source
래스터 출력
val | x | y
-----+---+---
   1 | 1 | 2
   1 | 1 | 3
   1 | 1 | 4
   1 | 1 | 5
   1 | 2 | 1
   1 | 2 | 2
   1 | 2 | 4
   1 | 2 | 5
   1 | 3 | 1
   1 | 3 | 2
   1 | 3 | 3
   1 | 3 | 4
   1 | 4 | 1
   1 | 4 | 3
   1 | 4 | 4
   1 | 4 | 5
   1 | 5 | 1
   1 | 5 | 2
   1 | 5 | 3
 255 | 5 | 4
   1 | 5 | 5

11.7. 래스터 편집자

  • ST_SetGeoReference — 단일 호출로 지리참조 파라미터 6개를 설정합니다. 숫자를 공백으로 구분해야 합니다. GDAL 또는 ESRI 서식의 입력물을 받아들입니다. 기본값은 GDAL입니다.
  • ST_SetRotation — 래스터의 회전각을 라디안으로 설정합니다.
  • ST_SetScale — X 및 Y 픽셀 크기를 좌표 참조 시스템의 단위로 설정합니다. 단위/픽셀 너비/픽셀 높이 순서입니다.
  • ST_SetSkew — 지리참조 X 및 Y 기울기(skew)(또는 회전각 파라미터)를 설정합니다. 값 하나만 입력할 경우, X와 Y를 동일한 값으로 설정합니다.
  • ST_SetSRID — 래스터의 SRID를 spatial_ref_sys 테이블에 정의된 특정 SRID의 정수값으로 설정합니다.
  • ST_SetUpperLeft — Sets the value of the upper left corner of the pixel of the raster to projected X and Y coordinates.
  • ST_Resample — 특정 리샘플링 알고리즘, 새로운 차원, 임의의 그리드 모서리, 그리고 또 다른 래스터에서 정의되거나 빌려온 래스터 지리참조 속성들의 집합을 이용해서 래스터를 리샘플링합니다.
  • ST_Rescale — Resample a raster by adjusting only its scale (or pixel size). New pixel values are computed using the NearestNeighbor (english or american spelling), Bilinear, Cubic, CubicSpline, Lanczos, Max or Min resampling algorithm. Default is NearestNeighbor.
  • ST_Reskew — 기울기(또는 회전각 파라미터)만 조정해서 래스터를 리샘플링합니다. NearestNeighbor(영국 또는 미국 철자), Bilinear, Cubic, CubicSpline 또는 Lanczos 리샘플링 알고리즘을 이용해서 새 픽셀 값을 계산합니다. 기본값은 NearestNeighbor입니다.
  • ST_SnapToGrid — 그리드에 래스터를 스냅시켜서 래스터를 리샘플링합니다. NearestNeighbor(영국 또는 미국 철자), Bilinear, Cubic, CubicSpline 또는 Lanczos 리샘플링 알고리즘을 이용해서 새 픽셀 값을 계산합니다. 기본값은 NearestNeighbor입니다.
  • ST_Resize — 래스터의 크기를 새 너비/높이로 조정합니다.
  • ST_Transform — 알려진 공간 참조 시스템의 래스터를 지정한 리샘플링 알고리즘을 통해 또 다른 알려진 공간 참조 시스템으로 재투영합니다. NearestNeighbor, Bilinear, Cubic, CubicSpline, Lanczos 알고리즘을 이용할 수 있습니다. 기본값은 NearestNeighbor입니다.

제목

ST_SetGeoReference — 단일 호출로 지리참조 파라미터 6개를 설정합니다. 숫자를 공백으로 구분해야 합니다. GDAL 또는 ESRI 서식의 입력물을 받아들입니다. 기본값은 GDAL입니다.

요약

raster ST_SetGeoReference(raster rast, text georefcoords, text format=GDAL);

raster ST_SetGeoReference(raster rast, double precision upperleftx, double precision upperlefty, double precision scalex, double precision scaley, double precision skewx, double precision skewy);

Description

단일 호출로 지리참조 파라미터 6개를 설정합니다. 'GDAL' 또는 'ESRI' 서식의 입력물을 받아들입니다. 기본값은 GDAL입니다. 6개의 좌표를 입력하지 않을 경우 NULL을 반환할 것입니다.

형식 표현식 사이의 차이점은 다음과 같습니다:

GDAL uses the value order shown below.

Code
scalex skewy skewx scaley upperleftx upperlefty

ESRI uses the value order shown below.

Code
scalex skewy skewx scaley upperleftx + scalex*0.5 upperlefty + scaley*0.5
[참고]

래스터가 DB 외부 밴드를 가지고 있을 경우, 지리참조 파라미터를 변경하면 밴드의 외부 저장 데이터에 접근하는 데 오류가 발생할 수도 있습니다.

개선 사항: 2.1.0버전에서 ST_SetGeoReference(raster, double precision, ...) 변종이 추가됐습니다.

예시

Code
WITH source AS (
    SELECT ST_MakeEmptyRaster(5, 5, 0, 0, 1, -1, 0, 0, 0) AS rast
), variants AS (
    SELECT 0 AS rid, rast FROM source
    UNION ALL
    SELECT 1, ST_SetGeoReference(rast, '10 0 0 -10 0.1 0.1', 'GDAL')
    FROM source
    UNION ALL
    SELECT 2, ST_SetGeoReference(rast, '10 0 0 -10 5.1 -4.9', 'ESRI')
    FROM source
    UNION ALL
    SELECT 3, ST_SetGeoReference(rast, 1, 1, 10, -10, 0.001, 0.001)
    FROM source
)
SELECT
    rid,
    round(ST_UpperLeftX(rast)::numeric, 3) AS upperleftx,
    round(ST_UpperLeftY(rast)::numeric, 3) AS upperlefty,
    ST_ScaleX(rast) AS scalex,
    ST_ScaleY(rast) AS scaley,
    ST_SkewX(rast) AS skewx,
    ST_SkewY(rast) AS skewy
FROM variants
ORDER BY rid;
래스터 출력
rid | upperleftx | upperlefty | scalex | scaley | skewx | skewy
-----+------------+------------+--------+--------+-------+-------
   0 |      0.000 |      0.000 |      1 |     -1 |     0 |     0
   1 |      0.100 |      0.100 |     10 |    -10 |     0 |     0
   2 |      0.100 |      0.100 |     10 |    -10 |     0 |     0
   3 |      1.000 |      1.000 |     10 |    -10 | 0.001 | 0.001
(4 rows)

제목

ST_SetRotation — 래스터의 회전각을 라디안으로 설정합니다.

요약

raster ST_SetRotation(raster rast, float8 rotation);

Description

래스터를 균일하게 회전시킵니다. 회전각은 라디안 단위입니다. 자세한 내용은 월드 파일 을 참조하십시오.

예시

Code
WITH variants AS (
    SELECT rid, 'rotated' AS kind, ST_SetRotation(rast, 15) AS rast
    FROM dummy_rast
    UNION ALL
    SELECT rid, 'original', rast
    FROM dummy_rast
)
SELECT
    rid,
    kind,
    round(ST_ScaleX(rast)::numeric, 4) AS scale_x,
    round(ST_ScaleY(rast)::numeric, 4) AS scale_y,
    round(ST_SkewX(rast)::numeric, 4) AS skew_x,
    round(ST_SkewY(rast)::numeric, 4) AS skew_y
FROM variants
ORDER BY rid, kind;
래스터 출력
rid |   kind   | scale_x | scale_y | skew_x | skew_y
-----+----------+---------+---------+--------+--------
   1 | original |  2.0000 |  3.0000 | 0.0000 | 0.0000
   1 | rotated  | -1.5194 | -2.2791 | 1.9509 | 1.3006
   2 | original |  0.0500 | -0.0500 | 0.0000 | 0.0000
   2 | rotated  | -0.0380 | -0.0380 | 0.0325 | 0.0325
(4 rows)

제목

ST_SetScale — X 및 Y 픽셀 크기를 좌표 참조 시스템의 단위로 설정합니다. 단위/픽셀 너비/픽셀 높이 순서입니다.

요약

raster ST_SetScale(raster rast, float8 xy);

raster ST_SetScale(raster rast, float8 x, float8 y);

Description

X 및 Y 픽셀 크기를 좌표 참조 시스템의 단위로 설정합니다. 단위/픽셀 너비/픽셀 높이 순서로 숫자를 입력합니다. 단위 한 개만 입력될 경우, X와 Y가 동일한 숫자라고 가정합니다.

[참고]

ST_SetScale은 래스터 범위에 매칭시키기 위해 래스터를 리샘플링하지 않는다는 점에서 ST_Rescale 과는 다릅니다. 원본에서 잘못 설정된 축척을 교정하기 위해 래스터의 메타데이터(또는 지리참조)를 변경할 뿐입니다. ST_Rescale 함수는 입력 데이터의 지리적 범위에 맞추기 위해 너비와 높이를 수정한 래스터를 출력합니다. ST_SetScale 함수는 래스터의 너비는 물론 높이도 수정하지 않습니다.

변경 사항: 2.0.0 미만 WKTRaster 버전에서는 ST_SetPixelSize라는 명칭이었습니다. 2.0.0 버전에서 현재 명칭으로 변경됐습니다.

예시

Code
UPDATE dummy_rast
    SET rast = ST_SetScale(rast, 1.5)
WHERE rid = 2;

SELECT ST_ScaleX(rast) As pixx, ST_ScaleY(rast) As pixy, Box3D(rast) As newbox
FROM dummy_rast
WHERE rid = 2;
래스터 출력
pixx | pixy |                    newbox
------+------+----------------------------------------------
  1.5 |  1.5 | BOX(3427927.75 5793244 0, 3427935.25 5793251.5 0)
Code
UPDATE dummy_rast
    SET rast = ST_SetScale(rast, 1.5, 0.55)
WHERE rid = 2;

SELECT ST_ScaleX(rast) As pixx, ST_ScaleY(rast) As pixy, Box3D(rast) As newbox
FROM dummy_rast
WHERE rid = 2;
래스터 출력
pixx | pixy |                   newbox
------+------+--------------------------------------------
  1.5 | 0.55 | BOX(3427927.75 5793244 0,3427935.25 5793247 0)

제목

ST_SetSkew — 지리참조 X 및 Y 기울기(skew)(또는 회전각 파라미터)를 설정합니다. 값 하나만 입력할 경우, X와 Y를 동일한 값으로 설정합니다.

요약

raster ST_SetSkew(raster rast, float8 skewxy);

raster ST_SetSkew(raster rast, float8 skewx, float8 skewy);

Description

지리참조 X 및 Y 기울기(또는 회전각 파라미터)를 설정합니다. 값 하나만 입력할 경우, X와 Y를 동일한 값으로 설정합니다. 자세한 내용은 월드 파일 을 참조하십시오.

예시

This is the first example.

Code
UPDATE dummy_rast SET rast = ST_SetSkew(rast, 1, 2) WHERE rid = 1;
SELECT
    rid,
    format('(%s, %s)', skewx, skewy) AS skew,
    term,
    georef[idx] AS value
FROM (
    SELECT
        rid,
        ST_SkewX(rast) AS skewx,
        ST_SkewY(rast) AS skewy,
        string_to_array(ST_GeoReference(rast), E'\n') AS georef
    FROM dummy_rast
    WHERE rid = 1
) AS refs
CROSS JOIN (VALUES
    (1, 'scaleX'),
    (2, 'skewY'),
    (3, 'skewX'),
    (4, 'scaleY'),
    (5, 'originX'),
    (6, 'originY')
) AS parts(idx, term)
ORDER BY idx;
래스터 출력
rid |  skew  |  term   |    value
-----+--------+---------+--------------
   1 | (1, 2) | scaleX  | 2.0000000000
   1 | (1, 2) | skewY   | 2.0000000000
   1 | (1, 2) | skewX   | 1.0000000000
   1 | (1, 2) | scaleY  | 3.0000000000
   1 | (1, 2) | originX | 0.5000000000
   1 | (1, 2) | originY | 0.5000000000
(6 rows)

This second example sets both values to the same number.

Code
UPDATE dummy_rast SET rast = ST_SetSkew(rast, 0) WHERE rid = 1;
SELECT
    rid,
    format('(%s, %s)', skewx, skewy) AS skew,
    term,
    georef[idx] AS value
FROM (
    SELECT
        rid,
        ST_SkewX(rast) AS skewx,
        ST_SkewY(rast) AS skewy,
        string_to_array(ST_GeoReference(rast), E'\n') AS georef
    FROM dummy_rast
    WHERE rid = 1
) AS refs
CROSS JOIN (VALUES
    (1, 'scaleX'),
    (2, 'skewY'),
    (3, 'skewX'),
    (4, 'scaleY'),
    (5, 'originX'),
    (6, 'originY')
) AS parts(idx, term)
ORDER BY idx;
래스터 출력
rid |  skew  |  term   |    value
-----+--------+---------+--------------
   1 | (0, 0) | scaleX  | 2.0000000000
   1 | (0, 0) | skewY   | 0.0000000000
   1 | (0, 0) | skewX   | 0.0000000000
   1 | (0, 0) | scaleY  | 3.0000000000
   1 | (0, 0) | originX | 0.5000000000
   1 | (0, 0) | originY | 0.5000000000
(6 rows)

제목

ST_SetSRID — 래스터의 SRID를 spatial_ref_sys 테이블에 정의된 특정 SRID의 정수값으로 설정합니다.

요약

raster ST_SetSRID(raster rast, integer srid);

Description

래스터의 SRID를 특정 정수값으로 설정합니다.

[참고]

이 함수는 래스터를 어떤 식으로든 변환하지 않습니다. 현재 좌표 참조 시스템의 공간 참조를 정의하는 메타데이터를 설정할 뿐입니다. 향후 변환 작업을 준비하는 데 유용합니다.


제목

ST_SetUpperLeft — Sets the value of the upper left corner of the pixel of the raster to projected X and Y coordinates.

요약

raster ST_SetUpperLeft(raster rast, double precision x, double precision y);

Description

Set the value of the upper left corner of raster to the projected X and Y coordinates

예시

Code
SELECT ST_SetUpperLeft(rast, -71.01, 42.37)
FROM dummy_rast
WHERE rid = 2;
                    

제목

ST_Resample — 특정 리샘플링 알고리즘, 새로운 차원, 임의의 그리드 모서리, 그리고 또 다른 래스터에서 정의되거나 빌려온 래스터 지리참조 속성들의 집합을 이용해서 래스터를 리샘플링합니다.

요약

raster ST_Resample(raster rast, integer width, integer height, double precision gridx=NULL, double precision gridy=NULL, double precision skewx=0, double precision skewy=0, text algorithm=NearestNeighbor, double precision maxerr=0.125);

raster ST_Resample(raster rast, double precision scalex=0, double precision scaley=0, double precision gridx=NULL, double precision gridy=NULL, double precision skewx=0, double precision skewy=0, text algorithm=NearestNeighbor, double precision maxerr=0.125);

raster ST_Resample(raster rast, raster ref, text algorithm=NearestNeighbor, double precision maxerr=0.125, boolean usescale=true);

raster ST_Resample(raster rast, raster ref, boolean usescale, text algorithm=NearestNeighbor, double precision maxerr=0.125);

Description

특정 리샘플링 알고리즘, 새로운 차원(width & height), 그리드 모서리(gridx & gridy), 그리고 또 다른 래스터에서 정의되거나 빌려온 래스터 지리참조 속성들(scalex, scaley, skewx & skewy)의 집합을 이용해서 래스터를 리샘플링합니다. 참조 래스터를 이용할 경우, 두 래스터는 동일한 SRID를 지고 있어야만 합니다.

New pixel values are computed using one of the following resampling algorithms:

  • NearestNeighbor (english or american spelling)

  • Bilinear

  • Cubic

  • CubicSpline

  • Lanczos

  • Max

  • Min

The default is NearestNeighbor which is the fastest but results in the worst interpolation.

maxerr 를 설정하지 않을 경우 최대 오류 백분율 0.125를 사용합니다.

[참고]

자세한 내용은 GDAL Warp resampling methods 를 참조하십시오.

2.0.0 버전부터 사용할 수 있습니다. GDAL 1.6.1 이상 버전이 필요합니다.

Enhanced: 3.4.0 max and min resampling options added

예시

Code
SELECT
    ST_Width(orig) AS orig_width,
    ST_Width(reduce_100) AS new_width
FROM (
    SELECT
        rast AS orig,
        ST_Resample(rast, 100, 100) AS reduce_100
    FROM aerials.boston
    WHERE ST_Intersects(
        rast,
        ST_Transform(ST_MakeEnvelope(-71.128, 42.2392, -71.1277, 42.2397, 4326),
            26986)
    )
    LIMIT 1
) AS foo;
래스터 출력
orig_width | new_width
------------+-------------
        200 |         100

제목

ST_Rescale — Resample a raster by adjusting only its scale (or pixel size). New pixel values are computed using the NearestNeighbor (english or american spelling), Bilinear, Cubic, CubicSpline, Lanczos, Max or Min resampling algorithm. Default is NearestNeighbor.

요약

raster ST_Rescale(raster rast, double precision scalexy, text algorithm=NearestNeighbor, double precision maxerr=0.125);

raster ST_Rescale(raster rast, double precision scalex, double precision scaley, text algorithm=NearestNeighbor, double precision maxerr=0.125);

Description

Resample a raster by adjusting only its scale (or pixel size). New pixel values are computed using one of the following resampling algorithms:

  • NearestNeighbor (english or american spelling)

  • Bilinear

  • Cubic

  • CubicSpline

  • Lanczos

  • Max

  • Min

The default is NearestNeighbor which is the fastest but results in the worst interpolation.

scalex and scaley define the new pixel size. scaley must often be negative to get well oriented raster.

새 scalex 또는 scaley가 래스터 너비 또는 높이의 나눗수가 아닌 경우, 결과 래스터의 범위가 입력 래스터의 범위를 포괄하도록 확장됩니다. 입력 범위를 정확히 유지하고자 할 경우, ST_Resize 를 참조하십시오.

maxerr is the threshold for transformation approximation by the resampling algorithm (in pixel units). A default of 0.125 is used if no maxerr is specified, which is the same value used in GDAL gdalwarp utility. If set to zero, no approximation takes place.

[참고]

자세한 내용은 GDAL Warp resampling methods 를 참조하십시오.

[참고]

ST_Rescale은 래스터 범위에 매칭시키기 위해 래스터를 리샘플링한다는 점에서 ST_SetScale 과는 다릅니다. ST_SetScale은 원본에서 잘못 설정된 축척을 교정하기 위해 래스터의 메타데이터(또는 지리참조)를 변경할 뿐입니다. ST_Rescale 함수는 입력 데이터의 지리적 범위에 맞추기 위해 너비와 높이를 수정한 래스터를 출력합니다. ST_SetScale 함수는 래스터의 너비는 물론 높이도 수정하지 않습니다.

2.0.0 버전부터 사용할 수 있습니다. GDAL 1.6.1 이상 버전이 필요합니다.

Enhanced: 3.4.0 max and min resampling options added

변경 사항: 2.1.0 버전부터 SRID가 없는 래스터도 입력받습니다.

예시

픽셀 크기 0.001도에서 픽셀 크기 0.0015도로 래스터를 재축척하는 단순한 예시입니다.

This example returns the original raster pixel size.

Code
SELECT ST_PixelWidth(ST_AddBand(ST_MakeEmptyRaster(100, 100, 0, 0, 0.001, -0.001, 0, 0, 4269), '8BUI'::text, 1, 0)) width
래스터 출력
0.001

This example returns the pixel size of the rescaled raster.

Code
SELECT ST_PixelWidth(ST_Rescale(ST_AddBand(ST_MakeEmptyRaster(100, 100, 0, 0, 0.001, -0.001, 0, 0, 4269), '8BUI'::text, 1, 0), 0.0015)) width
래스터 출력
0.0015

제목

ST_Reskew — 기울기(또는 회전각 파라미터)만 조정해서 래스터를 리샘플링합니다. NearestNeighbor(영국 또는 미국 철자), Bilinear, Cubic, CubicSpline 또는 Lanczos 리샘플링 알고리즘을 이용해서 새 픽셀 값을 계산합니다. 기본값은 NearestNeighbor입니다.

요약

raster ST_Reskew(raster rast, double precision skewxy, text algorithm=NearestNeighbor, double precision maxerr=0.125);

raster ST_Reskew(raster rast, double precision skewx, double precision skewy, text algorithm=NearestNeighbor, double precision maxerr=0.125);

Description

기울기(또는 회전각 파라미터)만 조정해서 래스터를 리샘플링합니다. NearestNeighbor(영국 또는 미국 철자), Bilinear, Cubic, CubicSpline 또는 Lanczos 리샘플링 알고리즘을 이용해서 새 픽셀 값을 계산합니다. 기본값은 가장 빠르지만 보간의 질은 가장 낮은 NearestNeighbor입니다.

skewxskewy 가 새 기울기를 정의합니다.

새 래스터의 범위가 입력 래스터의 범위를 포괄할 것입니다.

maxerr 를 설정하지 않을 경우 최대 오류 백분율 0.125를 사용합니다.

[참고]

자세한 내용은 GDAL Warp resampling methods 를 참조하십시오.

[참고]

ST_Reskew는 래스터 범위에 매칭시키기 위해 래스터를 리샘플링한다는 점에서 ST_SetSkew 와는 다릅니다. ST_SetSkew는 원본에서 잘못 설정된 기울기를 교정하기 위해 래스터의 메타데이터(또는 지리참조)를 변경할 뿐입니다. ST_Reskew 함수는 입력 데이터의 지리적 범위에 맞추기 위해 너비와 높이를 수정한 래스터를 출력합니다. ST_SetSkew 함수는 래스터의 너비는 물론 높이도 수정하지 않습니다.

2.0.0 버전부터 사용할 수 있습니다. GDAL 1.6.1 이상 버전이 필요합니다.

변경 사항: 2.1.0 버전부터 SRID가 없는 래스터도 입력받습니다.

예시

기울기 0.0에서 기울기 0.0015로 래스터를 다시 기울이는 단순한 예시입니다.

This example uses the original non-rotated raster.

Code
SELECT ST_Rotation(ST_AddBand(ST_MakeEmptyRaster(100, 100, 0, 0, 0.001, -0.001, 0, 0, 4269), '8BUI'::text, 1, 0));
래스터 출력
st_rotation
-------------
           0
(1 row)

The reskewed raster rotation.

Code
SELECT ST_Rotation(ST_Reskew(ST_AddBand(ST_MakeEmptyRaster(100, 100, 0, 0, 0.001, -0.001, 0, 0, 4269), '8BUI'::text, 1, 0), 0.0015));
래스터 출력
st_rotation
------------------
 -0.982793723247329
(1 row)

제목

ST_SnapToGrid — 그리드에 래스터를 스냅시켜서 래스터를 리샘플링합니다. NearestNeighbor(영국 또는 미국 철자), Bilinear, Cubic, CubicSpline 또는 Lanczos 리샘플링 알고리즘을 이용해서 새 픽셀 값을 계산합니다. 기본값은 NearestNeighbor입니다.

요약

raster ST_SnapToGrid(raster rast, double precision gridx, double precision gridy, text algorithm=NearestNeighbor, double precision maxerr=0.125, double precision scalex=DEFAULT 0, double precision scaley=DEFAULT 0);

raster ST_SnapToGrid(raster rast, double precision gridx, double precision gridy, double precision scalex, double precision scaley, text algorithm=NearestNeighbor, double precision maxerr=0.125);

raster ST_SnapToGrid(raster rast, double precision gridx, double precision gridy, double precision scalexy, text algorithm=NearestNeighbor, double precision maxerr=0.125);

Description

임의의 픽셀 모서리(gridx & gridy)와 선택적인 픽셀 크기(scalex & scaley)로 정의되는 그리드에 래스터를 스냅시켜서 래스터를 리샘플링합니다. NearestNeighbor(영국 또는 미국 철자), Bilinear, Cubic, CubicSpline 또는 Lanczos 리샘플링 알고리즘을 이용해서 새 픽셀 값을 계산합니다. 기본값은 가장 빠르지만 보간의 질은 가장 낮은 NearestNeighbor입니다.

gridxgridy 가 새 그리드의 어떤 임의의 픽셀 모서리라도 정의합니다. 이 픽셀 모서리가 새 래스터의 좌상단일 필요도 없고, 새 래스터 범위의 경계선 또는 내부에 있어야 하지도 않습니다.

You can optionally define the pixel size of the new grid with scalex and scaley.

새 래스터의 범위가 입력 래스터의 범위를 포괄할 것입니다.

maxerr 를 설정하지 않을 경우 최대 오류 백분율 0.125를 사용합니다.

[참고]

자세한 내용은 GDAL Warp resampling methods 를 참조하십시오.

[참고]

그리드 파라미터를 더 세밀하게 조정해야 할 경우 ST_Resample 함수를 이용하십시오.

2.0.0 버전부터 사용할 수 있습니다. GDAL 1.6.1 이상 버전이 필요합니다.

변경 사항: 2.1.0 버전부터 SRID가 없는 래스터도 입력받습니다.

예시

래스터를 약간 다른 그리드에 스냅시키는 단순한 예시입니다.

This example returns the upper-left X coordinate of the original raster.

Code
SELECT ST_UpperLeftX(ST_AddBand(ST_MakeEmptyRaster(10, 10, 0, 0, 0.001, -0.001, 0, 0, 4269), '8BUI'::text, 1, 0));
래스터 출력
st_upperleftx
---------------
             0
(1 row)

The upper left of raster after snapping.

Code
SELECT ST_UpperLeftX(ST_SnapToGrid(ST_AddBand(ST_MakeEmptyRaster(10, 10, 0, 0, 0.001, -0.001, 0, 0, 4269), '8BUI'::text, 1, 0), 0.0002, 0.0002));
래스터 출력
st_upperleftx
---------------
       -0.0008
(1 row)

제목

ST_Resize — 래스터의 크기를 새 너비/높이로 조정합니다.

요약

raster ST_Resize(raster rast, integer width, integer height, text algorithm=NearestNeighbor, double precision maxerr=0.125);

raster ST_Resize(raster rast, double precision percentwidth, double precision percentheight, text algorithm=NearestNeighbor, double precision maxerr=0.125);

raster ST_Resize(raster rast, text width, text height, text algorithm=NearestNeighbor, double precision maxerr=0.125);

Description

래스터의 크기를 새 너비/높이로 조정합니다. 픽셀의 정확한 개수 또는 입력 래스터의 너비/높이의 백분율로 새 너비/높이를 설정할 수 있습니다. 새 래스터의 범위가 입력 래스터의 범위와 동일할 것입니다.

NearestNeighbor(영국 또는 미국 철자), Bilinear, Cubic, CubicSpline 또는 Lanczos 리샘플링 알고리즘을 이용해서 새 픽셀 값을 계산합니다. 기본값은 가장 빠르지만 보간의 질은 가장 낮은 NearestNeighbor입니다.

변종 1은 출력 레이어의 실제 너비/높이를 입력받습니다.

변종 2는 입력 래스터의 너비/높이의 백분율을 나타내는 0과 1 사이의 소수값을 입력받습니다.

변종 3은 출력 래스터의 실제 너비/높이 또는 입력 래스터의 너비/높이의 백분율을 나타내는 문자열("20%")을 입력받습니다.

2.1.0 버전부터 사용할 수 있습니다. GDAL 1.6.1 이상 버전이 필요합니다.

예시

Code
WITH foo AS(
SELECT
    1 AS rid,
    ST_Resize(ST_AddBand(ST_MakeEmptyRaster(1000, 1000, 0, 0, 1, -1, 0, 0, 0),
            1, '8BUI', 255, 0
        ),
    '50%', '500') AS rast
UNION ALL
SELECT
    2 AS rid,
    ST_Resize(ST_AddBand(ST_MakeEmptyRaster(1000, 1000, 0, 0, 1, -1, 0, 0, 0),
            1, '8BUI', 255, 0
        ),
    500, 100) AS rast
UNION ALL
SELECT
    3 AS rid,
    ST_Resize(ST_AddBand(ST_MakeEmptyRaster(1000, 1000, 0, 0, 1, -1, 0, 0, 0),
            1, '8BUI', 255, 0
        ),
    0.25, 0.9) AS rast
)
SELECT
    rid,
    ST_Width(rast) AS width,
    ST_Height(rast) AS height,
    ST_ScaleX(rast) AS scale_x,
    round(ST_ScaleY(rast)::numeric, 4) AS scale_y
FROM foo
ORDER BY rid
래스터 출력
rid | width | height | scale_x | scale_y
-----+-------+--------+---------+---------
   1 |   500 |    500 |       2 | -2.0000
   2 |   500 |    100 |       2 | -10.0000
   3 |   250 |    900 |       4 | -1.1111
(3 rows)

제목

ST_Transform — 알려진 공간 참조 시스템의 래스터를 지정한 리샘플링 알고리즘을 통해 또 다른 알려진 공간 참조 시스템으로 재투영합니다. NearestNeighbor, Bilinear, Cubic, CubicSpline, Lanczos 알고리즘을 이용할 수 있습니다. 기본값은 NearestNeighbor입니다.

요약

raster ST_Transform(raster rast, integer srid, text algorithm=NearestNeighbor, double precision maxerr=0.125, double precision scalex, double precision scaley);

raster ST_Transform(raster rast, integer srid, double precision scalex, double precision scaley, text algorithm=NearestNeighbor, double precision maxerr=0.125);

raster ST_Transform(raster rast, raster alignto, text algorithm=NearestNeighbor, double precision maxerr=0.125);

Description

알려진 공간 참조 시스템의 래스터를 지정한 픽셀 왜곡(pixel warp) 알고리즘을 통해 또 다른 알려진 공간 참조 시스템으로 재투영합니다. 따로 알고리즘을 설정하지 않을 경우 기본값은 NearestNeighbor이며, maxerror를 설정하지 않을 경우 기본값은 백분율 0.125입니다.

알고리즘 옵션에는 'NearestNeighbor', 'Bilinear', 'Cubic', 'CubicSpline', 그리고 'Lanczos'가 있습니다. 자세한 내용은 GDAL Warp resampling methods 를 참조하십시오.

ST_Transform 함수는 종종 ST_SetSRID()와 착각당합니다. ST_Transform이 실제로 래스터의 좌표를 한 공간 참조 시스템에서 또다른 공간 참조 시스템으로 변환시키는 (그리고 픽셀 값을 리샘플링하는) 반면, ST_SetSRID()는 래스터의 SRID 식별자를 변경할 뿐입니다.

다른 변종과 달리, 변종 3은 alignto 파라미터에 참조 래스터를 요구합니다. 결과 래스터는 참조 래스터의 공간 참조 시스템(SRID)으로 변환될 것이며, (ST_SameAlignment = TRUE일 경우) 참조 래스터와 동일하게 정렬될 것입니다.

[참고]

If you find your transformation support is not working right, you may need to set the environment variable PROJSO to the projection library your PostGIS build is using. This just needs to have the name of the file. So for example on windows, you would in Control Panel -> System -> Environment Variables add a system variable called PROJSO and set it to libproj.dll. You'll have to restart your PostgreSQL service/daemon after this change.

[주의]

When transforming a coverage of tiles, you almost always want to use a reference raster to insure same alignment and no gaps in your tiles as demonstrated in example: Variant 3.

2.0.0 버전부터 사용할 수 있습니다. GDAL 1.6.1 이상 버전이 필요합니다.

개선 사항: 2.1.0버전에서 ST_Transform(rast, alignto) 변종이 추가됐습니다.

예시

Compare a source raster with nearest-neighbor and bilinear reprojections. The diagonal bands make the resampling behavior visible: nearest-neighbor keeps hard pixel steps, while bilinear smooths values between pixels. All three figures are generated from this query at manual build time.

Code
WITH rows AS (
    SELECT
        y,
        array_agg(
            ((
                    x * 3 + y * 5
                    + CASE WHEN (x + y) % 8 < 4 THEN 80 ELSE 0 END
                ) % 255)::double precision
            ORDER BY x
        ) AS row_values
    FROM generate_series(1, 80) AS y
    CROSS JOIN generate_series(1, 80) AS x
    GROUP BY y
), source AS (
    SELECT ST_SetValues(
        ST_AddBand(
            ST_MakeEmptyRaster(
                80, 80,
                -500000, 600000,
                2500, -2500,
                0, 0,
                2163
            ),
            1, '8BUI', 0, NULL
        ),
        1, 1, 1,
        array_agg(row_values ORDER BY y)::double precision[][]
    ) AS rast
    FROM rows
), transformed AS (
    SELECT
        rast,
        ST_Transform(rast, 4326, 'NearestNeighbor') AS nearest,
        ST_Transform(rast, 4326, 'Bilinear') AS bilinear
    FROM source
)
SELECT
    ST_AsPNG(rast) AS "source (EPSG:2163)",
    ST_AsPNG(nearest) AS "nearest (EPSG:4326)",
    ST_AsPNG(bilinear) AS "bilinear (EPSG:4326)"
FROM transformed;
래스터 출력
PNG image, 80 x 80 pixels | PNG image, 98 x 64 pixels | PNG image, 98 x 64 pixels
Figure
Geometry figure for visual-rt-st-transform-01

Raster reprojection and resampling.

Massachusetts State Plane source

WGS 84 nearest-neighbor

WGS 84 bilinear

Variant 3.

다음은 ST_Transform(raster, srid)과 ST_Transform(raster, alignto)의 차이점을 보여주는 예시입니다.

Code
WITH foo AS (
    SELECT 0 AS rid, ST_AddBand(ST_MakeEmptyRaster(2, 2, -500000, 600000, 100, -100, 0, 0, 2163), 1, '16BUI', 1, 0) AS rast UNION ALL
    SELECT 1, ST_AddBand(ST_MakeEmptyRaster(2, 2, -499800, 600000, 100, -100, 0, 0, 2163), 1, '16BUI', 2, 0) AS rast UNION ALL
    SELECT 2, ST_AddBand(ST_MakeEmptyRaster(2, 2, -499600, 600000, 100, -100, 0, 0, 2163), 1, '16BUI', 3, 0) AS rast UNION ALL

    SELECT 3, ST_AddBand(ST_MakeEmptyRaster(2, 2, -500000, 599800, 100, -100, 0, 0, 2163), 1, '16BUI', 10, 0) AS rast UNION ALL
    SELECT 4, ST_AddBand(ST_MakeEmptyRaster(2, 2, -499800, 599800, 100, -100, 0, 0, 2163), 1, '16BUI', 20, 0) AS rast UNION ALL
    SELECT 5, ST_AddBand(ST_MakeEmptyRaster(2, 2, -499600, 599800, 100, -100, 0, 0, 2163), 1, '16BUI', 30, 0) AS rast UNION ALL

    SELECT 6, ST_AddBand(ST_MakeEmptyRaster(2, 2, -500000, 599600, 100, -100, 0, 0, 2163), 1, '16BUI', 100, 0) AS rast UNION ALL
    SELECT 7, ST_AddBand(ST_MakeEmptyRaster(2, 2, -499800, 599600, 100, -100, 0, 0, 2163), 1, '16BUI', 200, 0) AS rast UNION ALL
    SELECT 8, ST_AddBand(ST_MakeEmptyRaster(2, 2, -499600, 599600, 100, -100, 0, 0, 2163), 1, '16BUI', 300, 0) AS rast
), bar AS (
    SELECT
        ST_Transform(rast, 4269) AS alignto
    FROM foo
    LIMIT 1
), baz AS (
    SELECT
        rid,
        rast,
        ST_Transform(rast, 4269) AS not_aligned,
        ST_Transform(rast, alignto) AS aligned
    FROM foo
    CROSS JOIN bar
)
SELECT
    ST_Collect(ST_ConvexHull(not_aligned) ORDER BY rid) AS not_aligned,
    ST_Collect(ST_ConvexHull(aligned) ORDER BY rid) AS aligned
FROM baz
래스터 출력
MULTIPOLYGON(((-107.007 50.2,-107.005 50.2,-107.005 50.198,-107.007 50.198,-107.007 50.2)),((-107.004 50.201,-107.002 50.201,-107.002 50.198,-107.004 50.198,-107.004 50.201)),((-107.001 50.201,-106.999 50.201,-106.999 50.198,-107.001 50.198,-107.001 50.201)),((-107.007 50.199,-107.004 50.199,-107.004 50.196,-107.007 50.196,-107.007 50.199)),((-107.004 50.199,-107.001 50.199,-107.001 50.196,-107.004 50.196,-107.004 50.199)),((-107.001 50.199,-106.999 50.199,-106.999 50.196,-107.001 50.196,-107.001 50.199)),((-107.006 50.197,-107.004 50.197,-107.004 50.194,-107.006 50.194,-107.006 50.197)),((-107.004 50.197,-107.001 50.197,-107.001 50.194,-107.004 50.194,-107.004 50.197)),((-107.001 50.197,-106.998 50.197,-106.998 50.195,-107.001 50.195,-107.001 50.197))) | MULTIPOLYGON(((-107.007 50.2,-107.005 50.2,-107.005 50.198,-107.007 50.198,-107.007 50.2)),((-107.005 50.202,-107.001 50.202,-107.001 50.198,-107.005 50.198,-107.005 50.202)),((-107.002 50.202,-106.998 50.202,-106.998 50.198,-107.002 50.198,-107.002 50.202)),((-107.007 50.199,-107.003 50.199,-107.003 50.195,-107.007 50.195,-107.007 50.199)),((-107.005 50.199,-107.001 50.199,-107.001 50.195,-107.005 50.195,-107.005 50.199)),((-107.002 50.199,-106.998 50.199,-106.998 50.195,-107.002 50.195,-107.002 50.199)),((-107.007 50.198,-107.003 50.198,-107.003 50.194,-107.007 50.194,-107.007 50.198)),((-107.005 50.198,-107.001 50.198,-107.001 50.194,-107.005 50.194,-107.005 50.198)),((-107.002 50.198,-106.998 50.198,-106.998 50.194,-107.002 50.194,-107.002 50.198)))
Figure
Geometry figure for visual-rt-st-transform-02

11.8. 래스터 밴드 편집자

  • ST_SetBandNoDataValue — NODATA를 나타내는 입력 밴드의 값을 설정합니다. 밴드를 따로 설정하지 않을 경우 밴드 1로 가정합니다. 밴드에 NODATA가 없다고 표시하려면, nodata value = NULL이라고 설정하십시오.
  • ST_SetBandIsNoData — 밴드의 isnodata 플래그를 참으로 설정합니다.
  • ST_SetBandPath — Update the external path and band number of an out-db band
  • ST_SetBandIndex — Update the external band number of an out-db band

제목

ST_SetBandNoDataValue — NODATA를 나타내는 입력 밴드의 값을 설정합니다. 밴드를 따로 설정하지 않을 경우 밴드 1로 가정합니다. 밴드에 NODATA가 없다고 표시하려면, nodata value = NULL이라고 설정하십시오.

요약

raster ST_SetBandNoDataValue(raster rast, double precision nodatavalue);

raster ST_SetBandNoDataValue(raster rast, integer band, double precision nodatavalue, boolean forcechecking=false);

Description

밴드에서 NODATA를 나타내는 값을 설정합니다. 밴드를 따로 설정하지 않을 경우 밴드 1로 가정합니다. 이 함수는 ST_Polygon, ST_DumpAsPolygons, 그리고 ST_PixelAs...() 함수의 결과물에 영향을 미칩니다.

예시

This example changes only the first band NODATA value.

Code
UPDATE dummy_rast
    SET rast = ST_SetBandNoDataValue(rast, 1, 254)
WHERE rid = 2;

This example changes the NODATA value for bands 1, 2, and 3.

Code
UPDATE dummy_rast
    SET rast =
        ST_SetBandNoDataValue(ST_SetBandNoDataValue(ST_SetBandNoDataValue(rast, 1, 254),
                2, 99),
                3, 108)
        WHERE rid = 2;

This example removes the NODATA value so that all pixels are considered by processing functions.

Code
UPDATE dummy_rast
    SET rast = ST_SetBandNoDataValue(rast, 1, NULL)
WHERE rid = 2;
                    

제목

ST_SetBandIsNoData — 밴드의 isnodata 플래그를 참으로 설정합니다.

요약

raster ST_SetBandIsNoData(raster rast, integer band=1);

Description

밴드의 isnodata 플래그를 참으로 설정합니다. 밴드를 따로 설정하지 않을 경우 밴드 1로 가정합니다. 플래그가 지저분하다고 여겨지는 경우에만 이 함수를 호출해야 합니다. 즉, 마지막 인수에 참을 설정한 경우와 설정하지 않을 경우 ST_BandIsNoData 함수를 호출해서 나온 결과물이 달라질 때 말입니다.

2.0.0 버전부터 사용할 수 있습니다.

예시

This example creates a dummy table with one raster column. The raster has two bands and one pixel per band. In the first band, the NODATA value and pixel value are both 3. In the second band, the NODATA value is 13 and the pixel value is 4.

Code
create table dummy_rast (rid integer, rast raster);

insert into dummy_rast values(
1,
(
'01' -- little endian (uint8 ndr)
||
'0000' -- version (uint16 0)
||
'0200' -- nBands (uint16 0)
||
'17263529ED684A3F' -- scaleX (float64 0.000805965234044584)
||
'F9253529ED684ABF' -- scaleY (float64 -0.00080596523404458)
||
'1C9F33CE69E352C0' -- ipX (float64 -75.5533328537098)
||
'718F0E9A27A44840' -- ipY (float64 49.2824585505576)
||
'ED50EB853EC32B3F' -- skewX (float64 0.000211812383858707)
||
'7550EB853EC32B3F' -- skewY (float64 0.000211812383858704)
||
'E6100000' -- SRID (int32 4326)
||
'0100' -- width (uint16 1)
||
'0100' -- height (uint16 1)
||
'4' -- hasnodatavalue set to true, isnodata value set to false (when it should be true)
||
'2' -- first band type (4BUI)
||
'03' -- novalue==3
||
'03' -- pixel(0,0)==3 (same that nodata)
||
'0' -- hasnodatavalue set to false
||
'5' -- second band type (16BSI)
||
'0D00' -- novalue==13
||
'0400' -- pixel(0,0)==4
)::raster
);

select ST_BandIsNoData(rast, 1) from dummy_rast where rid = 1; -- Expected false
select ST_BandIsNoData(rast, 1, TRUE) from dummy_rast where rid = 1; -- Expected true
                    

The isnodata flag is dirty, so set it to true.

Code
update dummy_rast set rast = ST_SetBandIsNoData(rast, 1) where rid = 1;


select ST_BandIsNoData(rast, 1) from dummy_rast where rid = 1; -- Expected true

                    

제목

ST_SetBandPath — Update the external path and band number of an out-db band

요약

raster ST_SetBandPath(raster rast, integer band, text outdbpath, integer outdbindex, boolean force=false);

Description

Updates an out-db band's external raster file path and external band number.

[참고]

If force is set to true, no tests are done to ensure compatibility (e.g. alignment, pixel support) between the external raster file and the PostGIS raster. This mode is intended for file system changes where the external raster resides.

Availability: 2.5.0

예시

Code
WITH foo AS (
    SELECT ST_AddBand(
        NULL::raster,
        '/home/pele/devel/geo/postgis-git/raster/test/regress/loader/Projected.tif',
        NULL::int[]
    ) AS rast
)
SELECT
    1 AS query,
    bandnum,
    regexp_replace(path, '^.*/', '') AS path,
    outdbbandnum
FROM ST_BandMetaData(
    (SELECT rast FROM foo),
    ARRAY[1, 3, 2]::int[]
) AS metadata
UNION ALL
SELECT
    2, bandnum,
    regexp_replace(path, '^.*/', ''),
    outdbbandnum
FROM ST_BandMetaData((
        SELECT
            ST_SetBandPath(rast,
                2,
                '/home/pele/devel/geo/postgis-git/raster/test/regress/loader/Projected2.tif',
                1
            ) AS rast
        FROM foo
    ),
    ARRAY[1, 3, 2]::int[]
) AS metadata
ORDER BY 1, 2;

In the second result set, band 2 now points at Projected2.tif and uses out-db band 1.

래스터 출력
query | bandnum | path           | outdbbandnum
-------+---------+----------------+--------------
     1 |       1 | Projected.tif  |            1
     1 |       2 | Projected.tif  |            2
     1 |       3 | Projected.tif  |            3
     2 |       1 | Projected.tif  |            1
     2 |       2 | Projected2.tif |            1
     2 |       3 | Projected.tif  |            3

제목

ST_SetBandIndex — Update the external band number of an out-db band

요약

raster ST_SetBandIndex(raster rast, integer band, integer outdbindex, boolean force=false);

Description

Updates an out-db band's external band number. This does not touch the external raster file associated with the out-db band

[참고]

If force is set to true, no tests are done to ensure compatibility (e.g. alignment, pixel support) between the external raster file and the PostGIS raster. This mode is intended for where bands are moved around in the external raster file.

[참고]

Internally, this method replaces the PostGIS raster's band at index band with a new band instead of updating the existing path information.

Availability: 2.5.0

예시

Code
WITH foo AS (
    SELECT ST_AddBand(
        NULL::raster,
        '/home/pele/devel/geo/postgis-git/raster/test/regress/loader/Projected.tif',
        NULL::int[]
    ) AS rast
)
SELECT
    1 AS query,
    bandnum,
    regexp_replace(path, '^.*/', '') AS path,
    outdbbandnum
FROM ST_BandMetaData(
    (SELECT rast FROM foo),
    ARRAY[1, 3, 2]::int[]
) AS metadata
UNION ALL
SELECT
    2, bandnum,
    regexp_replace(path, '^.*/', ''),
    outdbbandnum
FROM ST_BandMetaData((
        SELECT
            ST_SetBandIndex(rast,
                2,
                1
            ) AS rast
        FROM foo
    ),
    ARRAY[1, 3, 2]::int[]
) AS metadata
ORDER BY 1, 2;

In the second result set, band 2 still points at the same file but now reads external band 1.

래스터 출력
query | bandnum | path          | outdbbandnum
-------+---------+---------------+--------------
     1 |       1 | Projected.tif |            1
     1 |       2 | Projected.tif |            2
     1 |       3 | Projected.tif |            3
     2 |       1 | Projected.tif |            1
     2 |       2 | Projected.tif |            1
     2 |       3 | Projected.tif |            3

11.9. 래스터 밴드 통계 및 분석

  • ST_Count — 래스터 또는 래스터 커버리지의 입력 밴드에 있는 픽셀 개수를 반환합니다. 밴드를 따로 설정하지 않을 경우 기본값은 밴드 1입니다. exclude_nodata_value를 참으로 설정할 경우, NODATA 값이 아닌 픽셀의 개수만 반환할 것입니다.
  • ST_CountAgg — 종합 함수입니다. 래스터 집합의 입력 밴드에 있는 픽셀 개수를 반환합니다. 밴드를 따로 설정하지 않을 경우 기본값은 밴드 1입니다. exclude_nodata_value를 참으로 설정할 경우, NODATA 값이 아닌 픽셀의 개수만 반환할 것입니다.
  • ST_Histogram — 빈(bin; 히스토그램 표시에서 수직 막대로 나타나는 단위) 범위로 구분된 래스터 또는 래스터 커버리지의 데이터 분포를 요약하는 레코드 집합을 반환합니다. 따로 설정하지 않을 경우 빈의 개수를 자동으로 계산합니다.
  • ST_Quantile — 샘플링 또는 채우기(population)라는 맥락에서 래스터 또는 래스터 테이블 커버리지의 사분위(quantile)를 계산합니다. 따라서, 래스터의 25%, 50%, 75% 백분위(percentile) 단계로 값을 확인할 수 있습니다.
  • ST_SummaryStats — Returns summarystats consisting of count, sum, mean, stddev, min, max for a given raster band of a raster or raster coverage. Band 1 is assumed if no band is specified.
  • ST_SummaryStatsAgg — Aggregate. Returns summarystats consisting of count, sum, mean, stddev, min, max for a given raster band of a set of raster. Band 1 is assumed if no band is specified.
  • ST_ValueCount — 설정한 값들의 집합을 가진 래스터(또는 래스터 커버리지)의 입력 밴드에 있는 픽셀 밴드 값 및 픽셀 개수의 집계를 담고 있는 레코드 집합을 반환합니다. 밴드를 따로 설정하지 않을 경우 기본값은 밴드 1입니다. 기본적으로 NODATA 값은 집계되지 않습니다. 픽셀의 다른 모든 값들을 출력하는데, 픽셀 밴드 값은 가장 가까운 정수로 반올림됩니다.

제목

ST_Count — 래스터 또는 래스터 커버리지의 입력 밴드에 있는 픽셀 개수를 반환합니다. 밴드를 따로 설정하지 않을 경우 기본값은 밴드 1입니다. exclude_nodata_value를 참으로 설정할 경우, NODATA 값이 아닌 픽셀의 개수만 반환할 것입니다.

요약

bigint ST_Count(raster rast, integer nband=1, boolean exclude_nodata_value=true);

bigint ST_Count(raster rast, boolean exclude_nodata_value);

Description

래스터 또는 래스터 커버리지의 입력 밴드에 있는 픽셀 개수를 반환합니다. 밴드를 따로 설정하지 않을 경우 nband 의 기본값은 1입니다.

[참고]

exclude_nodata_value 를 참으로 설정할 경우, 래스터의 nodata 값이 아닌 픽셀의 개수만 반환할 것입니다. 모든 픽셀의 개수를 구하려면 exclude_nodata_value 를 거짓으로 설정하십시오.

2.2.0 버전부터 더 이상 ST_Count(rastertable, rastercolumn, ...) 변종 함수를 지원하지 않습니다. 대신 ST_CountAgg 함수를 이용하십시오.

2.0.0 버전부터 사용할 수 있습니다.

예시

Example will count all pixels not 249 and one will count all pixels.

Code
SELECT rid, ST_Count(ST_SetBandNoDataValue(rast, 249)) As exclude_nodata,
        ST_Count(ST_SetBandNoDataValue(rast, 249), false) As include_nodata
    FROM dummy_rast WHERE rid=2;
래스터 출력
rid | exclude_nodata | include_nodata
-----+----------------+----------------
   2 |             23 |             25

제목

ST_CountAgg — 종합 함수입니다. 래스터 집합의 입력 밴드에 있는 픽셀 개수를 반환합니다. 밴드를 따로 설정하지 않을 경우 기본값은 밴드 1입니다. exclude_nodata_value를 참으로 설정할 경우, NODATA 값이 아닌 픽셀의 개수만 반환할 것입니다.

요약

bigint ST_CountAgg(raster rast, integer nband, boolean exclude_nodata_value, double precision sample_percent);

bigint ST_CountAgg(raster rast, integer nband, boolean exclude_nodata_value);

bigint ST_CountAgg(raster rast, boolean exclude_nodata_value);

Description

래스터 집합의 입력 밴드에 있는 픽셀 개수를 반환합니다. 밴드를 따로 설정하지 않을 경우 nband 의 기본값은 1입니다.

exclude_nodata_value 를 참으로 설정할 경우, 래스터의 nodata 값이 아닌 픽셀의 개수만 반환할 것입니다. 모든 픽셀의 개수를 구하려면 exclude_nodata_value 를 거짓으로 설정하십시오.

기본적으로 모든 픽셀을 샘플링할 것입니다. 더 빠른 속도를 원한다면, sample_percent 를 0과 1 사이의 값으로 설정하십시오.

2.2.0 버전부터 사용할 수 있습니다.

예시

Code
WITH foo AS (
    SELECT
        rast.rast
    FROM (
        SELECT ST_SetValue(ST_SetValue(ST_SetValue(ST_AddBand(ST_MakeEmptyRaster(10, 10, 10, 10, 2, 2, 0, 0, 0),
                        1, '64BF', 0, 0
                    ),
                    1, 1, 1, -10
                ),
                1, 5, 4, 0
            ),
            1, 5, 5, 3.14159
        ) AS rast
    ) AS rast
    FULL JOIN (
        SELECT generate_series(1, 10) AS id
    ) AS id
        ON 1 = 1
)
SELECT
    ST_CountAgg(rast, 1, TRUE) AS non_nodata_pixels
FROM foo;
래스터 출력
non_nodata_pixels
-------------------
                20
(1 row)

제목

ST_Histogram — 빈(bin; 히스토그램 표시에서 수직 막대로 나타나는 단위) 범위로 구분된 래스터 또는 래스터 커버리지의 데이터 분포를 요약하는 레코드 집합을 반환합니다. 따로 설정하지 않을 경우 빈의 개수를 자동으로 계산합니다.

요약

SETOF record ST_Histogram(raster rast, integer nband=1, boolean exclude_nodata_value=true, integer bins=autocomputed, double precision[] width=NULL, boolean right=false);

SETOF record ST_Histogram(raster rast, integer nband, integer bins, double precision[] width=NULL, boolean right=false);

SETOF record ST_Histogram(raster rast, integer nband, boolean exclude_nodata_value, integer bins, boolean right);

SETOF record ST_Histogram(raster rast, integer nband, integer bins, boolean right);

Description

각 빈에 대해 입력 래스터 밴드의 min, max, count, percent로 이루어진 레코드 집합을 반환합니다. 밴드를 따로 설정하지 않을 경우 nband 의 기본값은 1입니다.

[참고]

기본적으로 nodata 값이 아닌 픽셀 값만 처리합니다. 모든 픽셀의 개수를 구하려면 exclude_nodata_value 를 거짓으로 설정하십시오.

width

width: 각 카테고리/빈의 너비를 나타내는 배열입니다. 빈 개수가 width 개수보다 큰 경우, width를 반복합니다.

예시: 빈 9개, width [a, b, c]는 [a, b, c, a, b, c, a, b, c]로 출력될 것입니다.

bins

분류 단계(breakout)의 개수: 따로 설정할 경우 함수가 반환하는 레코드의 개수입니다. 따로 설정하지 않을 경우 분류 단계의 개수를 자동으로 계산합니다.

right

히스토그램을 왼쪽부터보다는 오른쪽부터(기본값) 계산합니다. X값을 평가하는 기준을 [a, b) 에서 (a, b] 로 변경합니다.

Changed: 3.1.0 Removed ST_Histogram(table_name, column_name) variant.

2.0.0 버전부터 사용할 수 있습니다.

예시

Single raster tile - compute histograms for bands 1, 2, 3 and autocompute bins.

Code
SELECT band, (stats).*
FROM (SELECT rid, band, ST_Histogram(rast, band) As stats
    FROM dummy_rast CROSS JOIN generate_series(1, 3) As band
     WHERE rid=2) As foo;
래스터 출력
band |  min  |  max  | count | percent
------+-------+-------+-------+---------
    1 |   249 |   250 |     2 |    0.08
    1 |   250 |   251 |     2 |    0.08
    1 |   251 |   252 |     1 |    0.04
    1 |   252 |   253 |     2 |    0.08
    1 |   253 |   254 |    18 |    0.72
    2 |    78 | 113.2 |    11 |    0.44
    2 | 113.2 | 148.4 |     4 |    0.16
    2 | 148.4 | 183.6 |     4 |    0.16
    2 | 183.6 | 218.8 |     1 |    0.04
    2 | 218.8 |   254 |     5 |     0.2
    3 |    62 | 100.4 |    11 |    0.44
    3 | 100.4 | 138.8 |     5 |     0.2
    3 | 138.8 | 177.2 |     4 |    0.16
    3 | 177.2 | 215.6 |     1 |    0.04
    3 | 215.6 |   254 |     4 |    0.16

Just band 2 but for 6 bins.

Code
SELECT (stats).*
FROM (SELECT rid, ST_Histogram(rast, 2, 6) As stats
    FROM dummy_rast
     WHERE rid=2) As foo;
래스터 출력
min     |    max     | count | percent
------------+------------+-------+---------
         78 | 107.333333 |     9 |    0.36
 107.333333 | 136.666667 |     6 |    0.24
 136.666667 |        166 |     0 |       0
        166 | 195.333333 |     4 |    0.16
 195.333333 | 224.666667 |     1 |    0.04
 224.666667 |        254 |     5 |     0.2
(6 rows)

Same as previous but we explicitly control the pixel value range of each bin.

Code
SELECT (stats).*
FROM (SELECT rid, ST_Histogram(rast, 2, 6, ARRAY[0.5, 1, 4, 100, 5]) As stats
    FROM dummy_rast
     WHERE rid=2) As foo;
래스터 출력
min  |  max  | count | percent
-------+-------+-------+----------
    78 |  78.5 |     1 |     0.08
  78.5 |  79.5 |     1 |     0.04
  79.5 |  83.5 |     0 |        0
  83.5 | 183.5 |    17 |   0.0068
 183.5 | 188.5 |     0 |        0
 188.5 |   254 |     6 | 0.003664
(6 rows)

제목

ST_Quantile — 샘플링 또는 채우기(population)라는 맥락에서 래스터 또는 래스터 테이블 커버리지의 사분위(quantile)를 계산합니다. 따라서, 래스터의 25%, 50%, 75% 백분위(percentile) 단계로 값을 확인할 수 있습니다.

요약

SETOF record ST_Quantile(raster rast, integer nband=1, boolean exclude_nodata_value=true, double precision[] quantiles=NULL);

SETOF record ST_Quantile(raster rast, double precision[] quantiles);

SETOF record ST_Quantile(raster rast, integer nband, double precision[] quantiles);

double precision ST_Quantile(raster rast, double precision quantile);

double precision ST_Quantile(raster rast, boolean exclude_nodata_value, double precision quantile=NULL);

double precision ST_Quantile(raster rast, integer nband, double precision quantile);

double precision ST_Quantile(raster rast, integer nband, boolean exclude_nodata_value, double precision quantile);

double precision ST_Quantile(raster rast, integer nband, double precision quantile);

Description

샘플링 또는 채우기(population)라는 맥락에서 래스터 또는 래스터 테이블 커버리지의 사분위(quantile)를 계산합니다. 따라서, 래스터의 25%, 50%, 75% 백분위(percentile) 단계로 값을 확인할 수 있습니다.

[참고]

exclude_nodata_value 를 거짓으로 설정하면, NODATA 값의 픽셀도 집계할 것입니다.

Changed: 3.1.0 Removed ST_Quantile(table_name, column_name) variant.

2.0.0 버전부터 사용할 수 있습니다.

예시

Example will consider only pixels of band 1 that are not 249 and in named quantiles.

Code
UPDATE dummy_rast SET rast = ST_SetBandNoDataValue(rast, 249) WHERE rid=2;

SELECT (pvq).*
FROM (SELECT ST_Quantile(rast, ARRAY[0.25, 0.75]) As pvq
    FROM dummy_rast WHERE rid=2) As foo
    ORDER BY (pvq).quantile;
래스터 출력
quantile | value
----------+-------
     0.25 |   253
     0.75 |   254
Code
SELECT ST_Quantile(rast, 0.75) As value
FROM dummy_rast WHERE rid=2;
래스터 출력
254

Real live example. Quantile of all pixels in band 2 intersecting a geometry.

Code
SELECT rid, (ST_Quantile(rast, 2)).* As pvc
    FROM o_4_boston
        WHERE ST_Intersects(
            rast,
            ST_GeomFromText('POLYGON((224486 892151,224486 892200,224706 892200,224706 892151,224486 892151))', 26986)
            )
ORDER BY value, quantile, rid
;
래스터 출력
rid | quantile | value
-----+----------+-------
   1 |        0 |     0
   2 |        0 |     0
  14 |        0 |     1
  15 |        0 |     2
  14 |     0.25 |    37
   1 |     0.25 |    42
  15 |     0.25 |    47
   2 |     0.25 |    50
  14 |      0.5 |    56
   1 |      0.5 |    64
  15 |      0.5 |    66
   2 |      0.5 |    77
  14 |     0.75 |    81
  15 |     0.75 |    87
   1 |     0.75 |    94
   2 |     0.75 |   106
  14 |        1 |   199
   1 |        1 |   244
   2 |        1 |   255
  15 |        1 |   255

제목

ST_SummaryStats — Returns summarystats consisting of count, sum, mean, stddev, min, max for a given raster band of a raster or raster coverage. Band 1 is assumed if no band is specified.

요약

summarystats ST_SummaryStats(raster rast, boolean exclude_nodata_value);

summarystats ST_SummaryStats(raster rast, integer nband, boolean exclude_nodata_value);

Description

입력한 래스터 밴드 또는 래스터 또는 래스터 커버리지의 count, sum, mean, stddev, min, max로 이루어진 summarystats 을 반환합니다. 밴드를 따로 설정하지 않을 경우 nband 의 기본값은 1입니다.

[참고]

기본적으로 nodata 값이 아닌 픽셀 값만 처리합니다. 모든 픽셀의 개수를 구하려면 exclude_nodata_value 를 거짓으로 설정하십시오.

[참고]

기본적으로 모든 픽셀을 샘플링할 것입니다. 더 빠른 속도를 원한다면, sample_percent 를 1보다 작은 값으로 설정하십시오.

2.2.0 버전부터 더 이상 ST_SummaryStats(rastertable, rastercolumn, ...) 변종 함수를 지원하지 않습니다. 대신 ST_SummaryStatsAgg 함수를 이용하십시오.

2.0.0 버전부터 사용할 수 있습니다.

예시

Single raster tile.

Code
SELECT rid, band, (stats).*
FROM (SELECT rid, band, ST_SummaryStats(rast, band) As stats
    FROM dummy_rast CROSS JOIN generate_series(1, 3) As band
     WHERE rid=2) As foo;
래스터 출력
rid | band | count | sum  |    mean    |  stddev   | min | max
-----+------+-------+------+------------+-----------+-----+-----
   2 |    1 |    23 | 5821 | 253.086957 |  1.248061 | 250 | 254
   2 |    2 |    25 | 3682 |     147.28 | 59.862188 |  78 | 254
   2 |    3 |    25 | 3290 |      131.6 | 61.647384 |  62 | 254

Summarize pixels that intersect buildings of interest.

This example selects the target buildings, clips band 2 of the raster tiles to each building boundary, computes statistics for each clipped region, and then summarizes those statistics by building. It took 574ms on PostGIS Windows 64-bit with all of Boston Buildings and aerial Tiles (tiles each 150x150 pixels ~ 134,000 tiles), ~102,000 building records.

Code
WITH
-- our features of interest
feat AS (
    SELECT gid AS building_id, geom_26986 AS geom
    FROM buildings AS b
    WHERE gid IN (100, 103, 150)
),
-- clip band 2 of raster tiles to boundaries of builds
-- then get stats for these clipped regions
b_stats AS (
    SELECT building_id, (stats).*
    FROM (
        SELECT
            building_id,
            ST_SummaryStats(ST_Clip(rast, 2, geom)) AS stats
        FROM aerials.boston
        INNER JOIN feat
            ON ST_Intersects(feat.geom, rast)
    ) AS foo
)
-- finally summarize stats
SELECT
    building_id,
    SUM(count) AS num_pixels,
    MIN(min) AS min_pval,
    MAX(max) AS max_pval,
    SUM(mean * count) / SUM(count) AS avg_pval
FROM b_stats
WHERE count 
> 0
GROUP BY building_id
ORDER BY building_id;
래스터 출력
building_id | num_pixels | min_pval | max_pval |     avg_pval
-------------+------------+----------+----------+------------------
        100 |       1090 |        1 |      255 | 61.0697247706422
        103 |        655 |        7 |      182 | 70.5038167938931
        150 |        895 |        2 |      252 | 185.642458100559

Raster coverage.

This example returns statistics for each band.

Code
SELECT band, (stats).*
FROM (SELECT band, ST_SummaryStats('o_4_boston', 'rast', band) As stats
    FROM generate_series(1, 3) As band) As foo;
래스터 출력
band |  count  |  sum   |       mean       |      stddev      | min | max
------+---------+--------+------------------+------------------+-----+-----
    1 | 8450000 | 725799 | 82.7064349112426 | 45.6800222638537 |   0 | 255
    2 | 8450000 | 700487 | 81.4197705325444 | 44.2161184161765 |   0 | 255
    3 | 8450000 | 575943 |  74.682739408284 | 44.2143885481407 |   0 | 255

For a table, sampling less than 100% can improve speed. Here the sampling is set to 25%.

Code
SELECT band, (stats).*
FROM (SELECT band, ST_SummaryStats('o_4_boston', 'rast', band, true, 0.25) As stats
    FROM generate_series(1, 3) As band) As foo;
래스터 출력
band |  count  |  sum   |       mean       |      stddev      | min | max
------+---------+--------+------------------+------------------+-----+-----
    1 | 2112500 | 180686 | 82.6890480473373 | 45.6961043857248 |   0 | 255
    2 | 2112500 | 174571 |  81.448503668639 | 44.2252623171821 |   0 | 255
    3 | 2112500 | 144364 | 74.6765884023669 | 44.2014869384578 |   0 | 255
                

제목

ST_SummaryStatsAgg — Aggregate. Returns summarystats consisting of count, sum, mean, stddev, min, max for a given raster band of a set of raster. Band 1 is assumed if no band is specified.

요약

summarystats ST_SummaryStatsAgg(raster rast, integer nband, boolean exclude_nodata_value, double precision sample_percent);

summarystats ST_SummaryStatsAgg(raster rast, boolean exclude_nodata_value, double precision sample_percent);

summarystats ST_SummaryStatsAgg(raster rast, integer nband, boolean exclude_nodata_value);

Description

입력한 래스터 밴드 또는 래스터 또는 래스터 커버리지의 count, sum, mean, stddev, min, max로 이루어진 summarystats 을 반환합니다. 밴드를 따로 설정하지 않을 경우 nband 의 기본값은 1입니다.

[참고]

기본적으로 nodata 값이 아닌 픽셀 값만 처리합니다. 모든 픽셀의 개수를 구하려면 exclude_nodata_value 를 거짓으로 설정하십시오.

[참고]

기본적으로 모든 픽셀을 샘플링할 것입니다. 더 빠른 속도를 원한다면, sample_percent 를 0과 1 사이의 값으로 설정하십시오.

2.2.0 버전부터 사용할 수 있습니다.

예시

Code
WITH foo AS (
    SELECT
        rast.rast
    FROM (
        SELECT ST_SetValue(ST_SetValue(ST_SetValue(ST_AddBand(ST_MakeEmptyRaster(10, 10, 10, 10, 2, 2, 0, 0, 0),
                        1, '64BF', 0, 0
                    ),
                    1, 1, 1, -10
                ),
                1, 5, 4, 0
            ),
            1, 5, 5, 3.14159
        ) AS rast
    ) AS rast
    FULL JOIN (
        SELECT generate_series(1, 10) AS id
    ) AS id
        ON 1 = 1
)
SELECT
    (stats).count AS count,
    round((stats).sum::numeric, 3) AS sum,
    round((stats).mean::numeric, 3) AS mean,
    round((stats).stddev::numeric, 3) AS stddev,
    round((stats).min::numeric, 3) AS min,
    round((stats).max::numeric, 3) AS max
FROM (
    SELECT
        ST_SummaryStatsAgg(rast, 1, TRUE, 1) AS stats
    FROM foo
) bar;
래스터 출력
count |   sum   |  mean  | stddev |   min   |  max
-------+---------+--------+--------+---------+-------
    20 | -68.584 | -3.429 |  6.571 | -10.000 | 3.142
(1 row)

제목

ST_ValueCount — 설정한 값들의 집합을 가진 래스터(또는 래스터 커버리지)의 입력 밴드에 있는 픽셀 밴드 값 및 픽셀 개수의 집계를 담고 있는 레코드 집합을 반환합니다. 밴드를 따로 설정하지 않을 경우 기본값은 밴드 1입니다. 기본적으로 NODATA 값은 집계되지 않습니다. 픽셀의 다른 모든 값들을 출력하는데, 픽셀 밴드 값은 가장 가까운 정수로 반올림됩니다.

요약

SETOF record ST_ValueCount(raster rast, integer nband=1, boolean exclude_nodata_value=true, double precision[] searchvalues=NULL, double precision roundto=0, double precision OUT value, integer OUT count);

SETOF record ST_ValueCount(raster rast, integer nband, double precision[] searchvalues, double precision roundto=0, double precision OUT value, integer OUT count);

SETOF record ST_ValueCount(raster rast, double precision[] searchvalues, double precision roundto=0, double precision OUT value, integer OUT count);

bigint ST_ValueCount(raster rast, double precision searchvalue, double precision roundto=0);

bigint ST_ValueCount(raster rast, integer nband, boolean exclude_nodata_value, double precision searchvalue, double precision roundto=0);

bigint ST_ValueCount(raster rast, integer nband, double precision searchvalue, double precision roundto=0);

SETOF record ST_ValueCount(text rastertable, text rastercolumn, integer nband=1, boolean exclude_nodata_value=true, double precision[] searchvalues=NULL, double precision roundto=0, double precision OUT value, integer OUT count);

SETOF record ST_ValueCount(text rastertable, text rastercolumn, double precision[] searchvalues, double precision roundto=0, double precision OUT value, integer OUT count);

SETOF record ST_ValueCount(text rastertable, text rastercolumn, integer nband, double precision[] searchvalues, double precision roundto=0, double precision OUT value, integer OUT count);

bigintST_ValueCount(text rastertable, text rastercolumn, integer nband, boolean exclude_nodata_value, double precision searchvalue, double precision roundto=0);

bigint ST_ValueCount(text rastertable, text rastercolumn, double precision searchvalue, double precision roundto=0);

bigint ST_ValueCount(text rastertable, text rastercolumn, integer nband, double precision searchvalue, double precision roundto=0);

Description

선택한 밴드의 래스터 타일 또는 래스터 커버리지에 있는 픽셀의 밴드 값 및 개수를 담고 있는 value, count 열을 가진 레코드 집합을 반환합니다.

밴드를 따로 설정하지 않을 경우 nband 의 기본값은 1입니다. searchvalues 를 설정하지 않을 경우, 래스터 또는 래스터 커버리지에서 발견된 모든 픽셀 값을 반환할 것입니다. searchvalues 를 하나만 설정하면, 레코드 대신 해당 픽셀 밴드 값을 가진 픽셀의 개수를 나타내는 정수를 반환할 것입니다.

[참고]

exclude_nodata_value 를 거짓으로 설정하면, NODATA 값의 픽셀도 집계할 것입니다.

2.0.0 버전부터 사용할 수 있습니다.

예시

Example will count only pixels of band 1 that are not 249.

Code
UPDATE dummy_rast SET rast = ST_SetBandNoDataValue(rast, 249) WHERE rid=2;

SELECT (pvc).*
FROM (SELECT ST_ValueCount(rast) As pvc
    FROM dummy_rast WHERE rid=2) As foo
    ORDER BY (pvc).value;
래스터 출력
value | count
-------+-------
   250 |     2
   251 |     1
   252 |     2
   253 |     6
   254 |    12

Example will coount all pixels of band 1 including 249.

Code
SELECT (pvc).*
FROM (SELECT ST_ValueCount(rast, 1, false) As pvc
    FROM dummy_rast WHERE rid=2) As foo
    ORDER BY (pvc).value;
래스터 출력
value | count
-------+-------
   249 |     2
   250 |     2
   251 |     1
   252 |     2
   253 |     6
   254 |    12

Example will count only non-nodata value pixels of band 2.

Code
SELECT (pvc).*
FROM (SELECT ST_ValueCount(rast, 2) As pvc
    FROM dummy_rast WHERE rid=2) As foo
    ORDER BY (pvc).value;
래스터 출력
value | count
-------+-------
    78 |     1
    79 |     1
    88 |     1
    89 |     1
    96 |     1
    97 |     1
    98 |     1
    99 |     2
   112 |     2
:

                

Real live example. Count all the pixels in an aerial raster tile band 2 intersecting a geometry. And return only the pixel band values that have a count > 500.

Code
SELECT (pvc).value, SUM((pvc).count) As total
FROM (SELECT ST_ValueCount(rast, 2) As pvc
    FROM o_4_boston
        WHERE ST_Intersects(
            rast,
            ST_GeomFromText('POLYGON((224486 892151,224486 892200,224706 892200,224706 892151,224486 892151))', 26986)
             )
        ) As foo
    GROUP BY (pvc).value
    HAVING SUM((pvc).count) > 500
    ORDER BY (pvc).value;
래스터 출력
value | total
-------+-----
    51 | 502
    54 | 521

Just return count of pixels in each raster tile that have value of 100 of tiles that intersect a specific geometry.

Code
SELECT rid, ST_ValueCount(rast, 2, 100) As count
    FROM o_4_boston
        WHERE ST_Intersects(
            rast,
            ST_GeomFromText('POLYGON((224486 892151,224486 892200,224706 892200,224706 892151,224486 892151))', 26986)
             ) ;
래스터 출력
rid | count
-----+-------
   1 |    56
   2 |    95
  14 |    37
  15 |    64

11.10. Raster Inputs

  • ST_RastFromWKB — Return a raster value from a Well-Known Binary (WKB) raster.
  • ST_RastFromHexWKB — Return a raster value from a Hex representation of Well-Known Binary (WKB) raster.

제목

ST_RastFromWKB — Return a raster value from a Well-Known Binary (WKB) raster.

요약

raster ST_RastFromWKB(bytea wkb);

Description

Given a Well-Known Binary (WKB) raster, return a raster.

Availability: 2.5.0

예시

Code
SELECT (ST_MetaData(ST_RastFromWKB('\001\000\000\000\000\000\000\000\000\000\000\000@\000\000\000\000\000\000\010@\000\000\000\000\000\000\340?\000\000\000\000\000\000\340?\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\012\000\000\000\012\000\024\000'::bytea
    )
)).* AS metadata;
래스터 출력
upperleftx | upperlefty | width | height | scalex | scaley | skewx | skewy | srid | numbands
------------+------------+-------+--------+--------+--------+-------+-------+------+----------
        0.5 |        0.5 |    10 |     20 |      2 |      3 |     0 |     0 |   10 |        0

제목

ST_RastFromHexWKB — Return a raster value from a Hex representation of Well-Known Binary (WKB) raster.

요약

raster ST_RastFromHexWKB(text wkb);

Description

Given a Well-Known Binary (WKB) raster in Hex representation, return a raster.

Availability: 2.5.0

예시

Code
SELECT (ST_MetaData(ST_RastFromHexWKB('010000000000000000000000400000000000000840000000000000E03F000000000000E03F000000000000000000000000000000000A0000000A001400'
    )
)).* AS metadata;
래스터 출력
upperleftx | upperlefty | width | height | scalex | scaley | skewx | skewy | srid | numbands
------------+------------+-------+--------+--------+--------+-------+-------+------+----------
        0.5 |        0.5 |    10 |     20 |      2 |      3 |     0 |     0 |   10 |        0

11.11. 래스터 출력

  • ST_AsBinary/ST_AsWKB — Return the Well-Known Binary (WKB) representation of the raster.
  • ST_AsHexWKB — Return the Well-Known Binary (WKB) in Hex representation of the raster.
  • ST_AsGDALRaster — Return the raster tile in the designated GDAL Raster format. Raster formats are one of those supported by your compiled library. Use ST_GDALDrivers() to get a list of formats supported by your library.
  • ST_AsJPEG — 래스터 타일에서 선택한 밴드들을 단일 JPEG(Joint Photographic Exports Group) 이미지(바이트 배열)로 반환합니다. 밴드를 따로 설정하지 않거나, 밴드가 1개거나 또는 3개를 초과할 경우 첫 번째 밴드를 씁니다. 밴드가 3개뿐일 경우 밴드 3개를 모두 써서 RGB에 매핑시킵니다.
  • ST_AsPNG — 래스터 타일에서 선택한 밴드들을 단일 PNG(Portable Network Graphics) 이미지(바이트 배열)로 반환합니다. 래스터의 밴드가 1개, 3개, 또는 4개이거나 따로 설정하지 않을 경우 모든 밴드를 씁니다. 밴드가 2개 또는 4개를 초과하며 따로 설정하지 않을 경우, 밴드 1만 씁니다. 밴드를 RGB 또는 RGBA 스페이스에 매핑합니다.
  • ST_AsTIFF — Return the raster selected bands as a single TIFF image (byte array). If no band is specified or any of specified bands does not exist in the raster, then will try to use all bands.

제목

ST_AsBinary/ST_AsWKB — Return the Well-Known Binary (WKB) representation of the raster.

요약

bytea ST_AsBinary(raster rast, boolean outasin=FALSE);

bytea ST_AsWKB(raster rast, boolean outasin=FALSE);

Description

Returns the Binary representation of the raster. If outasin is TRUE, out-db bands are treated as in-db. Refer to raster/doc/RFC2-WellKnownBinaryFormat located in the PostGIS source folder for details of the representation.

이 함수는 데이터베이스로부터 데이터를 문자열 표현식으로 변환하지 않고 추출하는 바이너리 커서에 유용합니다.

[참고]

기본적으로, WKB 출력물은 DB 외부 밴드를 가리키는 외부 파일 경로를 담고 있습니다. 클라이언트가 DB 외부 밴드의 기저 래스터 파일에 접근하지 못 하는 경우, outasin 을 참으로 설정하십시오.

개선 사항: 2.1.0버전에서 outasin 이 추가됐습니다.

Enhanced: 2.5.0 Addition of ST_AsWKB

예시

Code
SELECT ST_AsBinary(rast) AS rastbin FROM dummy_rast WHERE rid=1;
래스터 출력
\001\000\000\000\000\000\000\000\000\000\000\000@\000\000\000\000\000\000\010@\000\000\000\000\000\000\340?\000\000\000\000\000\000\340?\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\012\000\000\000\012\000\024\000

제목

ST_AsHexWKB — Return the Well-Known Binary (WKB) in Hex representation of the raster.

요약

bytea ST_AsHexWKB(raster rast, boolean outasin=FALSE);

Description

Returns the Binary representation in Hex representation of the raster. If outasin is TRUE, out-db bands are treated as in-db. Refer to raster/doc/RFC2-WellKnownBinaryFormat located in the PostGIS source folder for details of the representation.

[참고]

By default, Hex WKB output contains the external file path for out-db bands. If the client does not have access to the raster file underlying an out-db band, set outasin to TRUE.

Availability: 2.5.0

예시

Code
SELECT ST_AsHexWKB(rast) AS rastbin FROM dummy_rast WHERE rid=1;
래스터 출력
010000000000000000000000400000000000000840000000000000E03F000000000000E03F000000000000000000000000000000000A0000000A001400

제목

ST_AsGDALRaster — Return the raster tile in the designated GDAL Raster format. Raster formats are one of those supported by your compiled library. Use ST_GDALDrivers() to get a list of formats supported by your library.

요약

bytea ST_AsGDALRaster(raster rast, text format, text[] options=NULL, integer srid=sameassource);

Description

래스터 타일을 지정한 형식으로 반환합니다. 인수들은 다음과 같습니다:

  • format - 출력할 형식입니다. 사용자의 LibGDAL 라이브러리에 컴파일된 드라이버에 따라 달라질 수 있습니다. 일반적으로 사용할 수 있는 형식은 'JPEG', 'GTiff', 'PNG'입니다. 사용자 라이브러리가 지원하는 형식들의 목록을 보려면 ST_GDALDrivers 함수를 이용하십시오.

  • options - GDAL 옵션들의 텍스트 배열입니다. 형식에 따라 유효한 옵션들이 달라집니다. 자세한 내용은 GDAL 래스터 형식 옵션 을 참조하십시오.

  • srid the spatial reference identifier to embed in the output raster

2.0.0 버전부터 사용할 수 있습니다. GDAL 1.6.0 이상 버전이 필요합니다.

예시

Export multiple raster tiles as a single JPEG image with 50 percent quality.

Code
SELECT ST_AsGDALRaster(ST_Union(rast), 'JPEG', ARRAY['QUALITY=50']) As rastjpg
FROM dummy_rast
WHERE rast && ST_MakeEnvelope(10, 10, 11, 11);

One way to export raster into another format is using PostgreSQL large object export functions. The following repeats the JPEG example and exports the result. Note that this requires superuser access because it uses server-side large object functions. It will also export to path on server network. If you need export locally, use the psql equivalent lo_ functions which export to the local file system instead of the server file system.

Code
DROP TABLE IF EXISTS tmp_out ;

CREATE TABLE tmp_out AS
SELECT lo_from_bytea(
       0,
       ST_AsGDALRaster(ST_Union(rast), 'JPEG', ARRAY['QUALITY=50'])
        ) AS loid
  FROM dummy_rast
WHERE rast && ST_MakeEnvelope(10, 10, 11, 11);

SELECT lo_export(loid, '/tmp/dummy.jpg')
   FROM tmp_out;

SELECT lo_unlink(loid)
  FROM tmp_out;

Export a raster as a GeoTIFF using the default creation options.

Code
SELECT ST_AsGDALRaster(rast, 'GTiff') AS rasttiff
FROM dummy_rast WHERE rid = 2;

Export a GeoTIFF using JPEG compression at 90 percent quality and embed SRID 4269.

Code
SELECT ST_AsGDALRaster(
  rast,
  'GTiff',
  ARRAY['COMPRESS=JPEG', 'JPEG_QUALITY=90'],
  4269) AS rasttiff
FROM dummy_rast WHERE rid = 2;
                

제목

ST_AsJPEG — 래스터 타일에서 선택한 밴드들을 단일 JPEG(Joint Photographic Exports Group) 이미지(바이트 배열)로 반환합니다. 밴드를 따로 설정하지 않거나, 밴드가 1개거나 또는 3개를 초과할 경우 첫 번째 밴드를 씁니다. 밴드가 3개뿐일 경우 밴드 3개를 모두 써서 RGB에 매핑시킵니다.

요약

bytea ST_AsJPEG(raster rast, text[] options=NULL);

bytea ST_AsJPEG(raster rast, integer nband, integer quality);

bytea ST_AsJPEG(raster rast, integer nband, text[] options=NULL);

bytea ST_AsJPEG(raster rast, integer[] nbands, text[] options=NULL);

bytea ST_AsJPEG(raster rast, integer[] nbands, integer quality);

Description

래스터에서 선택한 밴드들을 단일 JPEG(Joint Photographic Exports Group) 이미지로 반환합니다. 덜 흔한 래스터 유형으로 내보내야 할 경우 ST_AsGDALRaster 함수를 이용하십시오. 밴드를 따로 설정하지 않거나, 밴드가 1개거나 또는 3개를 초과할 경우 첫 번째 밴드만 씁니다. 밴드가 3개일 경우 밴드 3개를 모두 씁니다. 이 함수에는 다음과 같은 많은 옵션을 가진 많은 변종이 있습니다.

  • nband - 단일 밴드 내보내기를 위한 옵션입니다.

  • nbands - 내보낼 밴드들의 배열입니다(JPEG의 경우 3이 최대값입니다). 밴드의 순서는 RGB입니다. 예를 들어 ARRAY[3,2,1]은 밴드 3을 빨간색, 밴드 2를 초록색, 밴드 1을 파란색에 매핑한다는 뜻입니다.

  • quality - 1부터 100까지의 숫자입니다. 숫자가 높을수록 이미지가 선명해집니다.

  • options - JPEG에 대해 정의된 GDAL 옵션들의 텍스트 배열입니다(ST_GDALDrivers에서 JPEG에 대한 create_options를 살펴보십시오). JPEG의 경우, 유효한 옵션은 PROGRESSIVE ON/OFF 및 기본값이 75이고 0부터 100까지의 범위에서 설정할 수 있는 QUALITY 입니다. 자세한 내용은 GDAL 래스터 형식 옵션 을 참조하십시오.

2.0.0 버전부터 사용할 수 있습니다. GDAL 1.6.0 이상 버전이 필요합니다.

예시: 출력

Output the first three bands at 75 percent quality.

Code
SELECT ST_AsJPEG(rast) As rastjpg
FROM dummy_rast WHERE rid=2;

Output only the first band at 90 percent quality.

Code
SELECT ST_AsJPEG(rast, 1, 90) As rastjpg
FROM dummy_rast WHERE rid=2;

Output the first three bands, mapping band 2 to red, band 1 to green, and band 3 to blue, using progressive encoding at 90 percent quality.

Code
SELECT ST_AsJPEG(rast, ARRAY[2, 1, 3], ARRAY['QUALITY=90', 'PROGRESSIVE=ON']) As rastjpg
FROM dummy_rast WHERE rid=2;

제목

ST_AsPNG — 래스터 타일에서 선택한 밴드들을 단일 PNG(Portable Network Graphics) 이미지(바이트 배열)로 반환합니다. 래스터의 밴드가 1개, 3개, 또는 4개이거나 따로 설정하지 않을 경우 모든 밴드를 씁니다. 밴드가 2개 또는 4개를 초과하며 따로 설정하지 않을 경우, 밴드 1만 씁니다. 밴드를 RGB 또는 RGBA 스페이스에 매핑합니다.

요약

bytea ST_AsPNG(raster rast, text[] options=NULL);

bytea ST_AsPNG(raster rast, integer nband, integer compression);

bytea ST_AsPNG(raster rast, integer nband, text[] options=NULL);

bytea ST_AsPNG(raster rast, integer[] nbands, integer compression);

bytea ST_AsPNG(raster rast, integer[] nbands, text[] options=NULL);

Description

래스터에서 선택한 밴드들을 단일 PNG(Portable Network Graphics) 이미지로 반환합니다. 덜 흔한 래스터 유형으로 내보내야 할 경우 ST_AsGDALRaster 함수를 이용하십시오. 밴드를 따로 설정하지 않을 경우, 처음 3개의 밴드를 내보냅니다. srid 를 따로 설정하지 않으면 래스터의 SRID를 사용합니다. 이 함수에는 다음과 같은 많은 옵션을 가진 많은 변종이 있습니다:

  • nband - 단일 밴드 내보내기를 위한 옵션입니다.

  • nbands - 내보낼 밴드들의 배열입니다(PNG의 경우 4가 최대값입니다). 밴드의 순서는 RGBA입니다. 예를 들어 ARRAY[3,2,1]은 밴드 3을 빨간색, 밴드 2를 초록색, 밴드 1을 파란색에 매핑한다는 뜻입니다.

  • compression - 1부터 9까지의 숫자입니다. 숫자가 높을수록 압축률도 높아집니다.

  • options - PNG에 대해 정의된 GDAL 옵션들의 텍스트 배열입니다(ST_GDALDrivers에서 PNG에 대한 create_options를 살펴보십시오). PNG의 경우, 유효한 옵션은 ZLEVEL(압축에 소비할 시간 - 기본값은 6)뿐으로, 예를 들어 ARRAY['ZLEVEL=9']처럼 쓰입니다. 이 함수는 출력물 2개를 출력해야 하기 때문에 월드 파일을 사용할 수는 없습니다. 자세한 내용은 GDAL 래스터 형식 옵션 을 참조하십시오.

2.0.0 버전부터 사용할 수 있습니다. GDAL 1.6.0 이상 버전이 필요합니다.

예시

Export the first 3 bands and map band 3 to red, band 1 to green, and band 2 to blue.

Code
SELECT ST_AsPNG(rast) As rastpng
FROM dummy_rast WHERE rid=2;
SELECT ST_AsPNG(rast, ARRAY[3, 1, 2]) As rastpng
FROM dummy_rast WHERE rid=2;
                

제목

ST_AsTIFF — Return the raster selected bands as a single TIFF image (byte array). If no band is specified or any of specified bands does not exist in the raster, then will try to use all bands.

요약

bytea ST_AsTIFF(raster rast, text[] options='', integer srid=sameassource);

bytea ST_AsTIFF(raster rast, text compression='', integer srid=sameassource);

bytea ST_AsTIFF(raster rast, integer[] nbands, text compression='', integer srid=sameassource);

bytea ST_AsTIFF(raster rast, integer[] nbands, text[] options, integer srid=sameassource);

Description

래스터에서 선택한 밴드들을 단일 TIFF(Tagged Image File Format) 이미지로 반환합니다. 밴드를 따로 설정하지 않을 경우, 모든 밴드를 쓰려 할 것입니다. 이 함수는 ST_AsGDALRaster 를 둘러싼 래퍼입니다. 덜 흔한 래스터 유형으로 내보내야 할 경우 ST_AsGDALRaster 함수를 이용하십시오. 어떤 공간 참조 SRS 텍스트도 없을 경우, 래스터의 공간 참조를 사용합니다. 이 함수에는 다음과 같은 많은 옵션을 가진 많은 변종이 있습니다:

  • nbands - 내보낼 밴드들의 배열입니다(PNG의 경우 3이 최대값입니다). 밴드의 순서는 RGB입니다. 예를 들어 ARRAY[3,2,1]은 밴드 3을 빨간색, 밴드 2를 초록색, 밴드 1을 파란색에 매핑한다는 뜻입니다.

  • compression - 압축 표현식: JPEG90(또는 다른 퍼센트), LZW, JPEG, DEFLATE9

  • options - GTiff에 대해 정의된 GDAL 생성 옵션들의 텍스트 배열입니다(ST_GDALDrivers에서 GTiff에 대한 create_options를 살펴보십시오). 자세한 내용은 GDAL 래스터 형식 옵션 을 참조하십시오.

  • srid - 래스터의 spatial_ref_sys의 SRID입니다. 이 옵션은 지리참조 정보를 채우는 데 쓰입니다.

2.0.0 버전부터 사용할 수 있습니다. GDAL 1.6.0 이상 버전이 필요합니다.

예시: JPEG 압축 90%

Code
SELECT ST_AsTIFF(rast, 'JPEG90') As rasttiff
FROM dummy_rast WHERE rid=2;
                

11.12. 래스터 공간 처리

  • ST_Clip — Returns the raster clipped by the input geometry. If band number is not specified, all bands are processed. If crop is not specified or TRUE, the output raster is cropped. If touched is set to TRUE, then touched pixels are included, otherwise only if the center of the pixel is in the geometry it is included.
  • ST_ColorMap — 소스 래스터 및 설정한 밴드로부터 8BUI 밴드(grayscale, RGB, RGBA)를 4개까지 가지는 새 래스터를 생성합니다. 밴드를 따로 설정하지 않으면 밴드 1로 가정합니다.
  • ST_Grayscale — Creates a new one-8BUI band raster from the source raster and specified bands representing Red, Green and Blue
  • ST_Intersection — 두 래스터의 공유 부분을 표현하는, 또는 벡터화된 래스터와 도형의 기하학적 교차를 표현하는 래스터 또는 도형-픽셀값 쌍의 집합을 반환합니다.
  • ST_MapAlgebra (callback function version) — 콜백 함수 버전 - 래스터 1개 이상, 밴드 인덱스, 그리고 사용자 지정 콜백 함수 1개를 입력받아 밴드 1개를 가진 래스터를 반환합니다.
  • ST_MapAlgebra (expression version) — 표현식 버전 - 입력 래스터 1개 또는 2개, 밴드 인덱스, 그리고 사용자 지정 SQL 표현식 1개 이상을 입력받아 밴드 1개를 가진 래스터를 반환합니다.
  • ST_MapAlgebraExpr — 래스터 밴드 1개 버전: 입력 래스터에 대해 유효한 PostgreSQL 대수 연산을 적용해서 형성되고, 설정한 픽셀 유형을 가진, 밴드 1개를 가진 새 래스터를 생성합니다. 따로 밴드를 설정하지 않을 경우, 밴드 1로 가정합니다.
  • ST_MapAlgebraExpr — 래스터 밴드 2개 버전: 입력 래스터 2개에 대해 유효한 PostgreSQL 대수 연산을 적용해서 형성되고, 설정한 픽셀 유형을 가진, 밴드 1개를 가진 새 래스터를 생성합니다. 따로 밴드를 설정하지 않을 경우, 각 래스터의 밴드 1로 가정합니다. 출력 래스터는 첫 번째 래스터가 정의하는 그리드 상에 (축척, 기울기 및 픽셀 모서리가) 정렬될 것입니다. extenttype 파라미터가 출력 래스터의 범위를 정의할 것입니다. extenttype 의 값은 INTERSECTION, UNION, FIRST, SECOND가 될 수 있습니다.
  • ST_MapAlgebraFct — 래스터 밴드 1개 버전: 입력 래스터에 대해 유효한 PostgreSQL 대수 연산을 적용해서 형성되고, 설정한 픽셀 유형을 가진, 밴드 1개를 가진 새 래스터를 생성합니다. 따로 밴드를 설정하지 않을 경우, 밴드 1로 가정합니다.
  • ST_MapAlgebraFct — 래스터 밴드 2개 버전: 입력 래스터 2개에 대해 유효한 PostgreSQL 함수를 적용해서 형성되고, 설정한 픽셀 유형을 가진, 밴드 1개를 가진 새 래스터를 생성합니다. 따로 밴드를 설정하지 않을 경우, 밴드 1로 가정합니다. 범위 유형을 따로 설정하지 않을 경우 기본값은 INTERSECTION입니다.
  • ST_MapAlgebraFctNgb — 래스터 밴드 1개 버전: 사용자 지정 PostgreSQL 함수를 이용하는 맵 대수 최근접 이웃(Map Algebra Nearest Neighbor)입니다. 입력 래스터 밴드의 값의 이웃(neighborhood)이 관련된 PostgreSQL 사용자 함수가 출력하는 값을 가진 래스터를 반환합니다.
  • ST_Reclass — 원본으로부터 재분류된 밴드 유형으로 이루어진 새 래스터를 생성합니다. nband 는 변경할 밴드를 가리킵니다. nband 를 따로 설정하지 않을 경우 밴드 1로 가정합니다. 다른 모든 밴드들은 변경 없이 반환됩니다. 실제 사례: 보기 좋은 형식으로 더 간단하게 렌더링하기 위해 16BUI 밴드를 8BUI 등등으로 변환하십시오.
  • ST_ReclassExact — Creates a new raster composed of bands reclassified from original, using a 1:1 mapping from values in the original band to new values in the destination band.
  • ST_Union — 래스터 타일 집합을 1개 이상의 밴드로 이루어진 단일 래스터로 통합합니다.

제목

ST_Clip — Returns the raster clipped by the input geometry. If band number is not specified, all bands are processed. If crop is not specified or TRUE, the output raster is cropped. If touched is set to TRUE, then touched pixels are included, otherwise only if the center of the pixel is in the geometry it is included.

요약

raster ST_Clip(raster rast, integer[] nband, geometry geom, double precision[] nodataval=NULL, boolean crop=TRUE, boolean touched=FALSE);

raster ST_Clip(raster rast, integer nband, geometry geom, double precision nodataval, boolean crop=TRUE, boolean touched=FALSE);

raster ST_Clip(raster rast, integer nband, geometry geom, boolean crop, boolean touched=FALSE);

raster ST_Clip(raster rast, geometry geom, double precision[] nodataval=NULL, boolean crop=TRUE, boolean touched=FALSE);

raster ST_Clip(raster rast, geometry geom, double precision nodataval, boolean crop=TRUE, boolean touched=FALSE);

raster ST_Clip(raster rast, geometry geom, boolean crop, boolean touched=FALSE);

Description

입력 도형 geom 으로 잘라낸 래스터를 반환합니다. 밴드 인덱스를 지정하지 않을 경우, 모든 밴드를 처리합니다.

ST_Clip이 출력한 래스터는 각 밴드에 대해 잘라낸 면에 할당된 NODATA 값을 가지고 있어야 합니다. NODATA 값을 설정하지 않고 입력 래스터에 정의된 NODATA 값이 없을 경우, 출력 래스터의 NODATA 값을 ST_MinPossibleValue(ST_BandPixelType(rast, band))로 설정합니다. 배열 내부의 NODATA 값의 개수가 밴드 개수보다 작을 경우, 배열 안의 마지막 NODATA 값을 남은 밴드의 NODATA 값으로 씁니다. NODATA 값의 개수가 밴드 개수보다 클 경우, 남는 NODATA 값을 무시합니다. NODATA 값의 배열을 입력받는 모든 변종 함수는 각 밴드에 할당될 단일 값도 입력받습니다.

If crop is not specified, true is assumed meaning the output raster is cropped to the intersection of the geomand rast extents. If crop is set to false, the new raster gets the same extent as rast. If touched is set to true, then all pixels in the rast that intersect the geometry are selected.

[참고]

The default behavior is touched=false, which will only select pixels where the center of the pixel is covered by the geometry.

Enhanced: 3.5.0 - touched argument added.

2.0.0 버전부터 사용할 수 있습니다.

개선 사항: 2.1.0 버전에서 C 언어로 다시 쓰였습니다.

Examples here use Massachusetts aerial data available on MassGIS site MassGIS Aerial Orthos.

예시

Comparing selecting all touched vs. not all touched.

Code
WITH source AS (
    SELECT rast, geom
    FROM ST_AsRaster(ST_Letters('R'), scalex =
> 1.0, scaley =
> -1.0) AS r(rast)
    INNER JOIN ST_GeomFromText('LINESTRING(0 1,5 6,10 10)') AS g(geom)
        ON ST_Intersects(r.rast, g.geom)
), clipped AS (
    SELECT rast,
        ST_Clip(rast, geom, touched =
> true) AS rast_touched,
        ST_Clip(rast, geom, touched =
> false) AS rast_not_touched
    FROM source
), variants AS (
    SELECT 'original' AS title, ST_Count(rast) AS pixel_count, rast AS rendered
    FROM clipped
    UNION ALL
    SELECT 'all touched', ST_Count(rast_touched), rast_touched
    FROM clipped
    UNION ALL
    SELECT 'default clip', ST_Count(rast_not_touched), rast_not_touched
    FROM clipped
)
SELECT title, pixel_count, ST_AsPNG(rendered) AS image
FROM variants
ORDER BY CASE title
    WHEN 'original' THEN 1
    WHEN 'all touched' THEN 2
    ELSE 3
END;
래스터 출력
title        | pixel_count | image
--------------+-------------+----------------------------
 original     |        2605 | PNG image, 48 x 74 pixels
 all touched  |          16 | PNG image, 11 x 11 pixels
 default clip |          10 | PNG image, 11 x 11 pixels
(3 rows)
Figure
Geometry figure for visual-rt-st-clip-01

The following self-contained example uses three simple shapes as RGB bands. It compares cropping band 1, clipping band 1 without cropping and then restoring bands 2 and 3, and clipping every band without cropping.

Code
WITH canvas AS (
    SELECT ST_AddBand(
        ST_AddBand(
            ST_AddBand(
                ST_MakeEmptyRaster(128, 128, 0, 128, 1, -1, 0, 0, 0),
                '8BUI'::text, 0::double precision, 0::double precision
            ),
            '8BUI'::text, 0::double precision, 0::double precision
        ),
        '8BUI'::text, 0::double precision, 0::double precision
    ) AS rast
), source AS (
    SELECT ST_SetValue(
        ST_SetValue(
            ST_SetValue(rast, 1, ST_Buffer('POINT(32 96)'::geometry, 22), 220),
            2, ST_Buffer('LINESTRING(18 20,110 110)'::geometry, 6,
                         'endcap=flat join=bevel'), 210
        ),
        3, ST_Buffer('LINESTRING(10 48,118 48)'::geometry, 7,
                     'endcap=flat'), 180
    ) AS rast,
    ST_Buffer('POINT(64 64)'::geometry, 34) AS clipper
    FROM canvas
), variants AS (
    SELECT 'original RGB' AS title, rast AS rendered FROM source
    UNION ALL
    SELECT 'band 1 cropped', ST_Clip(rast, 1, clipper, true) FROM source
    UNION ALL
    SELECT
        'band 1 only',
        ST_AddBand(
            ST_Clip(rast, 1, clipper, false),
            ARRAY[ST_Band(rast, 2), ST_Band(rast, 3)]
        )
    FROM source
    UNION ALL
    SELECT 'all bands clipped', ST_Clip(rast, clipper, false) FROM source
)
SELECT title, ST_AsPNG(rendered) AS image
FROM variants
ORDER BY CASE title
    WHEN 'original RGB' THEN 1
    WHEN 'band 1 cropped' THEN 2
    WHEN 'band 1 only' THEN 3
    ELSE 4
END;
래스터 출력
title             | image
-------------------+-----------------------------
 original RGB      | PNG image, 128 x 128 pixels
 band 1 cropped    | PNG image, 68 x 68 pixels
 band 1 only       | PNG image, 128 x 128 pixels
 all bands clipped | PNG image, 128 x 128 pixels
(4 rows)
Figure
Geometry figure for visual-rt-st-clip-02

Crop, single-band clipping, and all-band clipping.

Source tile

Cropped

One-band source

One-band clip

All-band source

All-band clip


제목

ST_ColorMap — 소스 래스터 및 설정한 밴드로부터 8BUI 밴드(grayscale, RGB, RGBA)를 4개까지 가지는 새 래스터를 생성합니다. 밴드를 따로 설정하지 않으면 밴드 1로 가정합니다.

요약

raster ST_ColorMap(raster rast, integer nband=1, text colormap=grayscale, text method=INTERPOLATE);

raster ST_ColorMap(raster rast, text colormap, text method=INTERPOLATE);

Description

rastnband 위치의 밴드에 colormap 을 적용해서 8BUI 밴드 4개까지로 구성된 새 래스터를 출력합니다. colormap 안에 정의된 색상 구성 요소의 개수가 새 래스터의 8BUI 밴드 개수를 결정합니다.

nband 를 설정하지 않을 경우, 밴드 1로 가정합니다.

미리 정의된 컬러맵의 키워드, 또는 값 및 색상 구성 요소를 정의하는 라인 집합이 colormap 이 될 수 있습니다.

유효한 미리 정의된 colormap 키워드:

  • grayscale 또는 greyscale - 8BUI 밴드 래스터의 회색조(shades of gray)를 설정

  • pseudocolor - 8BUI(RGBA) 밴드 4개의 래스터에 대해 파랑에서 녹색으로, 녹색에서 빨강으로 변하는 색상을 설정

  • fire - 8BUI(RGBA) 밴드 4개의 래스터에 대해 검정에서 빨강으로, 빨강에서 연한 노랑으로 변하는 색상을 설정

  • bluered - 8BUI(RGBA) 밴드 4개의 래스터에 대해 파랑에서 연한 하양으로, 연한 하양에서 빨강으로 변하는 색상을 설정

사용자 지정 컬러맵을 설정하려면 사용자가 colormap 에 (한 줄에 하나씩 작성한) 항목들의 집합을 입력할 수 있습니다. 각 항목은 일반적으로 다음 5개의 값으로 구성됩니다. 픽셀 값과 해당 픽셀의 빨강, 녹색, 파랑, 알파 구성 요소(RGBA)입니다(색상 구성 요소는 0부터 255 사이의 값입니다). 픽셀 값 대신 해당 래스터 밴드의 최소/최대값이 0/100%인 백분율 값을 쓸 수도 있습니다. 각 값을 쉼표, 탭, 쌍점, 그리고/또는 공백으로 구분할 수 있습니다. 픽셀 값이 NODATA 값일 경우, nv, null 또는 nodata 로 설정할 수 있습니다. 다음은 그 예시입니다.

Code
5 0 0 0 255
4 100:50 55 255
1 150, 100 150 255
0% 255 255 255 255
nv 0 0 0 0
                    

colormap 의 문법은 GDAL의 색상 강조(color-relief) 모드 gdaldem 의 문법과 유사합니다.

유효한 method 키워드:

  • INTERPOLATE - 입력한 픽셀 값들 사이의 색상을 부드럽게 섞여들게 하기 위해 선형 보간법을 이용합니다.

  • EXACT - 컬러맵에 존재하는 픽셀 값과만 엄격히 매칭시킵니다. 컬러맵 항목과 일치하지 않는 값을 가진 픽셀은 0 0 0 0(RGBA)으로 설정할 것입니다.

  • NEAREST - 픽셀 값과 가장 가까운 값을 가진 컬러맵 항목을 이용합니다.

[참고]

컬러맵에 대해서는 ColorBrewer 를 참조하면 좋습니다.

[주의]

그 결과 새 래스터의 밴드들은 NODATA 값을 가지지 않을 것입니다. NODATA 값이 필요하다면 ST_SetBandNoDataValue 를 이용해서 NODATA 값을 설정하십시오.

2.1.0 버전부터 사용할 수 있습니다.

예시

This example builds a raster from rotated buffered lines and compares the original values with predefined and custom color maps.

Code
WITH ref AS (
    SELECT ST_MakeEmptyRaster(200, 200, 0, 200, 1, -1, 0, 0) AS rast
), source AS (
    SELECT ST_Union(rast) AS rast
    FROM (
    SELECT
        ST_AsRaster(ST_Rotate(ST_Buffer('LINESTRING(0 2,50 50,150 150,125 50)'::geometry,
                    i*2
                ),
                pi() * i * 0.125, ST_Point(50, 50)
            ),
            ref.rast, '8BUI'::text, i * 5
        ) AS rast
    FROM ref
    CROSS JOIN generate_series(1, 10, 3) AS i
) AS shapes
)
SELECT title, ST_AsPNG(rendered) AS image
FROM source
CROSS JOIN LATERAL (VALUES
    ('original', rast),
    ('grayscale', ST_ColorMap(rast, 1, 'greyscale')),
    ('pseudocolor', ST_ColorMap(rast, 1, 'pseudocolor')),
    ('fire', ST_ColorMap(rast, 1, 'fire')),
    ('blue-red', ST_ColorMap(rast, 1, 'bluered')),
    ('custom red', ST_ColorMap(
        rast,
        1,
        E'100% 255 0 0 255\n80% 160 0 0 255\n50% 130 0 0 255\n' ||
        E'30% 30 0 0 255\n20% 60 0 0 255\n0% 0 0 0 255\n' ||
        E'nv 255 255 255 0'
    ))
) AS variants(title, rendered);
래스터 출력
title      | image
------------+--------------------------------
 original   | PNG image, 224 x 295 pixels
 grayscale | PNG image, 224 x 295 pixels
 pseudocolor| PNG image, 224 x 295 pixels
 fire       | PNG image, 224 x 295 pixels
 blue-red   | PNG image, 224 x 295 pixels
 custom red | PNG image, 224 x 295 pixels
                    
Figure
Geometry figure for visual-rt-st-colormap-01

제목

ST_Grayscale — Creates a new one-8BUI band raster from the source raster and specified bands representing Red, Green and Blue

요약

(1) raster ST_Grayscale(raster rast, integer redband=1, integer greenband=2, integer blueband=3, text extenttype=INTERSECTION);

(2) raster ST_Grayscale(rastbandarg[] rastbandargset, text extenttype=INTERSECTION);

Description

Create a raster with one 8BUI band given three input bands (from one or more rasters). Any input band whose pixel type is not 8BUI will be reclassified using ST_Reclass.

[참고]

This function is not like ST_ColorMap with the grayscale keyword as ST_ColorMap operates on only one band while this function expects three bands for RGB. This function applies the following equation for converting RGB to Grayscale: 0.2989 * RED + 0.5870 * GREEN + 0.1140 * BLUE

Availability: 2.5.0

예시

This self-contained example paints an apple with gradients and highlights into three raster bands. It compares the original RGB raster with the equivalent grayscale results produced by both function variants.

Code
WITH pixels AS (
    SELECT
        col,
        row,
        x,
        y,
        (((x - 48.0)^2 / (25.0^2) + (y - 54.0)^2 / (29.0^2) < 1)
         OR ((x - 72.0)^2 / (25.0^2) + (y - 54.0)^2 / (29.0^2) < 1))
         AND NOT ((x - 60.0)^2 / (8.0^2) + (y - 26.0)^2 / (5.0^2) < 1) AS fruit,
        ((x - 82.0) * 0.84 + (y - 28.0) * 0.54)^2 / (22.0^2)
          + (-(x - 82.0) * 0.54 + (y - 28.0) * 0.84)^2 / (8.0^2) < 1 AS leaf,
        abs((x - 62.0) * 0.96 - (y - 29.0) * 0.28) < 3
          AND x BETWEEN 60 AND 69 AND y BETWEEN 21 AND 45 AS stem
    FROM (
        SELECT
            col,
            row,
            col / 2.0 AS x,
            row / 2.0 AS y
        FROM generate_series(1, 180) AS row
        CROSS JOIN generate_series(1, 240) AS col
    ) AS source_pixels
), shaded AS (
    SELECT
        col,
        row,
        x,
        y,
        CASE
            WHEN stem THEN 95 + y * 0.7 + (x % 3) * 8
            WHEN leaf THEN 28 + (90 - x) * 0.5
            WHEN fruit THEN LEAST(255, GREATEST(0,
                150
                + (85 - sqrt((x - 39.0)^2 + (y - 37.0)^2)) * 1.1
                + CASE
                    WHEN (x - 43.0)^2 / (10.0^2) + (y - 43.0)^2 / (7.0^2) < 1
                    THEN 35
                    ELSE 0
                END
                - CASE
                    WHEN (x - 77.0)^2 / (20.0^2) + (y - 67.0)^2 / (13.0^2) < 1
                    THEN 35
                    ELSE 0
                END
                + ((x * 13 + y * 7) % 19 - 9)
            ))
            ELSE 245
        END AS red,
        CASE
            WHEN stem THEN 50 + y * 0.35
            WHEN leaf THEN LEAST(190, GREATEST(40,
                105 + (95 - x) * 1.2 + (y - 20) * 1.5
                + CASE
                    WHEN (x - 76.0)^2 / (12.0^2) + (y - 24.0)^2 / (4.0^2) < 1
                    THEN 45
                    ELSE 0
                END
            ))
            WHEN fruit THEN LEAST(95, GREATEST(15,
                24 + (68 - y) * 0.35
                + CASE
                    WHEN (x - 43.0)^2 / (10.0^2) + (y - 43.0)^2 / (7.0^2) < 1
                    THEN 30
                    ELSE 0
                END
                + ((x * 5 + y * 11) % 13 - 6)
            ))
            ELSE 245
        END AS green,
        CASE
            WHEN stem THEN 22 + (x % 4) * 3
            WHEN leaf THEN 42 + (100 - x) * 0.4
            WHEN fruit THEN LEAST(75, GREATEST(10,
                18
                + CASE
                    WHEN (x - 43.0)^2 / (10.0^2) + (y - 43.0)^2 / (7.0^2) < 1
                    THEN 25
                    ELSE 0
                END
                + ((x * 3 + y * 5) % 11 - 5)
            ))
            ELSE 245
        END AS blue
    FROM pixels
), rows AS (
    SELECT
        row,
        array_agg(red::double precision ORDER BY col) AS red_values,
        array_agg(green::double precision ORDER BY col) AS green_values,
        array_agg(blue::double precision ORDER BY col) AS blue_values
    FROM shaded
    GROUP BY row
), source AS (
    SELECT ST_SetValues(ST_SetValues(ST_SetValues(
        ST_AddBand(ST_AddBand(ST_AddBand(
            ST_MakeEmptyRaster(240, 180, 0, 180, 1, -1, 0, 0, 0),
            '8BUI'::text, 245::double precision, 0::double precision),
            '8BUI'::text, 245::double precision, 0::double precision),
            '8BUI'::text, 245::double precision, 0::double precision),
        1, 1, 1, array_agg(red_values ORDER BY row)::double precision[][]),
        2, 1, 1, array_agg(green_values ORDER BY row)::double precision[][]),
        3, 1, 1, array_agg(blue_values ORDER BY row)::double precision[][]) AS rast
    FROM rows
)
SELECT ST_AsPNG(rast) AS "original RGB",
    ST_AsPNG(ST_Grayscale(rast)) AS "grayscale (variant 1)",
    ST_AsPNG(ST_Grayscale(ARRAY[
        ROW(rast, 1)::rastbandarg,
        ROW(rast, 2)::rastbandarg,
        ROW(rast, 3)::rastbandarg
    ]::rastbandarg[])) AS "grayscale (variant 2)"
FROM source;
래스터 출력
original RGB                | grayscale (variant 1)      | grayscale (variant 2)
-----------------------------+----------------------------+----------------------------
 PNG image, 240 x 180 pixels | PNG image, 240 x 180 pixels | PNG image, 240 x 180 pixels
(1 row)
Figure
Geometry figure for visual-rt-st-grayscale-01

Original photographic illustration:

original apple

grayscale apple


제목

ST_Intersection — 두 래스터의 공유 부분을 표현하는, 또는 벡터화된 래스터와 도형의 기하학적 교차를 표현하는 래스터 또는 도형-픽셀값 쌍의 집합을 반환합니다.

요약

setof geomval ST_Intersection(geometry geom, raster rast, integer band_num=1);

setof geomval ST_Intersection(raster rast, geometry geom);

setof geomval ST_Intersection(raster rast, integer band, geometry geomin);

raster ST_Intersection(raster rast1, raster rast2, double precision[] nodataval);

raster ST_Intersection(raster rast1, raster rast2, text returnband, double precision[] nodataval);

raster ST_Intersection(raster rast1, integer band1, raster rast2, integer band2, double precision[] nodataval);

raster ST_Intersection(raster rast1, integer band1, raster rast2, integer band2, text returnband, double precision[] nodataval);

Description

두 래스터의 공유 부분을 표현하는, 또는 벡터화된 래스터와 도형의 기하학적 교차를 표현하는 래스터 또는 도형-픽셀값 쌍의 집합을 반환합니다.

geomval 집합을 반환하는 처음 세 변종 함수는 벡터 스페이스에서 작동합니다. 먼저 (ST_DumpAsPolygon을 통해) 래스터를 geomval 행의 집합으로 벡터화한 다음, 해당 행을 ST_Intersection(geometry, geometry) PostGIS 함수를 이용해서 도형과 교차시킵니다. 도형이 래스터의 NODATA 값 부분과만 교차할 경우, 텅 빈 도형을 반환합니다. WHERE 절에 ST_Intersect 함수를 적절히 사용하면, 일반적으로 결과에서 이런 경우들을 제외시킬 수 있습니다.

출력되는 geomval 집합 앞뒤에 괄호를 치고 표현식 끝에 '.geom' 또는 '.val'을 붙이면 도형 및 값 부분에 접근할 수 있습니다. 예: (ST_Intersection(rast, geom)).geom

래스터를 반환하는 다른 변종들은 래스터 스페이스에서 작동합니다. 이 변종들은 교차를 수행하기 위해 ST_MapAlgebraExpr 함수의 래스터 2개를 입력받는 버전을 이용합니다.

출력 래스터의 범위는 두 래스터 범위의 기하학적 교차 부분과 일치합니다. 출력 래스터는 returnband 파라미터가 어떻게 설정됐는지에 따라 'BAND1', 'BAND2' 또는 'BOTH' 밴드를 포함합니다. 어느 한 밴드에서 NODATA 값을 가진 부분은 출력물의 모든 밴드에서 NODATA 값을 가지게 됩니다. 즉, NODATA 값을 가진 픽셀과 교차하는 픽셀을 모두 NODATA 값을 가진 픽셀로 출력합니다.

ST_Intersection 함수가 출력하는 래스터는 교차하지 않는 부분에 할당된 NODATA 값을 가지고 있어야 합니다. 사용자가 'BAND1', 'BAND2' 또는 'BOTH' 밴드 가운데 어떤 것을 요청하느냐에 따라 1개 또는 2개의 NODATA 값을 가진 nodataval[] 배열을 입력해서 어떤 출력 밴드에 대해서도 NODATA 값을 정의하거나 대체할 수 있습니다. 배열의 첫 번째 값은 첫 번째 밴드의 NODATA 값을 대체하고, 두 번째 값은 두 번째 밴드의 NODATA 값을 대체합니다. 만약 입력 밴드 가운데 하나에 정의된 NODATA 값이 없고 입력된 NODATA 값 배열도 없을 경우, ST_MinPossibleValue 함수를 통해 NODATA 값을 선택합니다. NODATA 값의 배열을 입력받는 모든 변종 함수는 요청된 각 밴드에 할당될 단일 값도 입력받습니다.

모든 변종 함수에서, 밴드 번호를 따로 지정하지 않을 경우 밴드 1로 가정합니다. 래스터와 도형 사이의 교차 부분을 래스터로 반환받아야 할 경우, ST_Clip 을 참조하십시오.

[참고]

For more control over the result extent or NODATA handling, use the two-raster variant of ST_MapAlgebraExpr. To compute a raster-space intersection with a geometry, use ST_Clip.

Use this function together with ST_Intersects and an index on the raster or geometry column when filtering table data.

개선 사항: 2.0.0부터 래스터 스페이스에서 교차 부분을 구할 수 있습니다. 2.0.0 미만 버전에서는, 벡터 스페이스에서만 교차 작업을 수행할 수 있었습니다.

예시: 도형, 래스터 -- 도형-값 쌍으로 출력

Code
SELECT
    foo.rid,
    foo.gid,
    GeometryType((foo.geomval).geom) AS geom_type,
    (foo.geomval).val AS value
FROM (
    SELECT
        A.rid,
        g.gid,
        ST_Intersection(A.rast, g.geom) As geomval
    FROM dummy_rast AS A
    CROSS JOIN (
        VALUES
            (1, ST_Point(3427928, 5793243.85) ),
            (2, 'LINESTRING(3427927.85 5793243.75,3427927.8 5793243.75,3427927.8 5793243.8)'::geometry),
            (3, 'LINESTRING(1 2,3 4)'::geometry)
    ) As g(gid, geom)
    WHERE A.rid = 2
) AS foo;
래스터 출력
rid | gid |      geom_type       | value
-----+-----+----------------------+-------
   2 |   1 | POINT                |   249
   2 |   1 | POINT                |   253
   2 |   2 | POINT                |   254
   2 |   2 | POINT                |   251
   2 |   2 | POINT                |   253
   2 |   2 | LINESTRING           |   252
   2 |   2 | MULTILINESTRING      |   250
   2 |   3 | GEOMETRYCOLLECTION   |

The same line example rendered in a common coordinate frame. The raster footprint and complete input line remain visible behind the returned intersection pieces.

Code
WITH source AS (
    SELECT
        rast,
        ST_GeomFromText(
            'LINESTRING(3427927.85 5793243.75,'
            '3427927.8 5793243.75,3427927.8 5793243.8)'
        ) AS input_geometry
    FROM dummy_rast
    WHERE rid = 2
), intersection AS (
SELECT
    rast,
    input_geometry,
    ST_Collect(gv.geom) AS result_geometry
FROM source
CROSS JOIN LATERAL ST_Intersection(rast, input_geometry) AS gv
GROUP BY rast, input_geometry
), layers AS (
    SELECT
        'raster' AS title,
        ST_Translate(ST_Envelope(rast), -3427927.75, -5793243.75) AS geom
    FROM intersection
    UNION ALL
    SELECT
        'input',
        ST_Translate(input_geometry, -3427927.75, -5793243.75)
    FROM intersection
    UNION ALL
    SELECT
        'intersection',
        ST_Translate(result_geometry, -3427927.75, -5793243.75)
    FROM intersection
)
SELECT title, geom AS geom
FROM layers
ORDER BY CASE title
    WHEN 'raster' THEN 1
    WHEN 'input' THEN 2
    ELSE 3
END;
래스터 출력
title        | geom
--------------+-------------------------------------------------------------
 raster       | POLYGON((0 0,0 0.25,0.25 0.25,0.25 0,0 0))
 input        | LINESTRING(0.1 0,0.05 0,0.05 0.05)
 intersection | GEOMETRYCOLLECTION
Figure
Geometry figure for visual-rt-st-intersection-02

제목

ST_MapAlgebra (callback function version) — 콜백 함수 버전 - 래스터 1개 이상, 밴드 인덱스, 그리고 사용자 지정 콜백 함수 1개를 입력받아 밴드 1개를 가진 래스터를 반환합니다.

요약

raster ST_MapAlgebra(rastbandarg[] rastbandargset, regprocedure callbackfunc, text pixeltype=NULL, text extenttype=INTERSECTION, raster customextent=NULL, integer distancex=0, integer distancey=0, text[] VARIADIC userargs=NULL);

raster ST_MapAlgebra(raster rast, integer[] nband, regprocedure callbackfunc, text pixeltype=NULL, text extenttype=FIRST, raster customextent=NULL, integer distancex=0, integer distancey=0, text[] VARIADIC userargs=NULL);

raster ST_MapAlgebra(raster rast, integer nband, regprocedure callbackfunc, text pixeltype=NULL, text extenttype=FIRST, raster customextent=NULL, integer distancex=0, integer distancey=0, text[] VARIADIC userargs=NULL);

raster ST_MapAlgebra(raster rast1, integer nband1, raster rast2, integer nband2, regprocedure callbackfunc, text pixeltype=NULL, text extenttype=INTERSECTION, raster customextent=NULL, integer distancex=0, integer distancey=0, text[] VARIADIC userargs=NULL);

raster ST_MapAlgebra(raster rast, integer nband, regprocedure callbackfunc, float8[] mask, boolean weighted, text pixeltype=NULL, text extenttype=INTERSECTION, raster customextent=NULL, text[] VARIADIC userargs=NULL);

Description

래스터 1개 이상, 밴드 인덱스, 그리고 사용자 지정 콜백 함수 1개를 입력받아 밴드 1개를 가진 래스터를 반환합니다.

rast,rast1,rast2, rastbandargset

맵 대수(代數) 처리를 평가하는 데 쓰이는 래스터

rastbandargset 은 많은 래스터 그리고/또는 많은 밴드에 대해 맵 대수 연산을 이용할 수 있도록 해줍니다. 변종 1 예시를 참조하십시오.

nband, nband1, nband2

평가할 래스터의 밴드 개수입니다. nband는 밴드를 나타내는 정수 또는 정수 배열이 될 수 있습니다. nband1은 rast1에 있는 밴드이며 nband2는 래스터 2개/밴드 2개일 경우 rast2에 있는 밴드입니다.

callbackfunc

The callbackfunc parameter must be the name and signature of an SQL or PL/pgSQL function, cast to a regprocedure. An example PL/pgSQL function example is:

Code
CREATE OR REPLACE FUNCTION sample_callbackfunc(value double precision[][][], pos integer[][], VARIADIC userargs text[])
    RETURNS double precision
    AS $$
    BEGIN
        RETURN 0;
    END;
    $$ LANGUAGE 'plpgsql' IMMUTABLE;
                                    

The callbackfunc must have two or three arguments: a 3-dimension double precision array, a 2-dimension integer array and, optionally, a variadic 1-dimension text array. The first argument value is the set of values (as double precision) from all input rasters. The three dimensions (where indexes are 1-based) are: raster #, row y, column x. The second argument position is the set of pixel positions from the output raster and input rasters. The outer dimension (where indexes are 0-based) is the raster #. The position at outer dimension index 0 is the output raster's pixel position. For each outer dimension, there are two elements in the inner dimension for X and Y. The optional third argument userargs is for passing through any user-specified arguments.

The callback return value is used as the value of the output pixel. If the callback returns NULL, the output pixel is set to NODATA when the output band has a NODATA value. If the output band has no NODATA value, a NULL callback result raises an error.

Passing a regprocedure argument to a SQL function requires the full function signature to be passed, then cast to a regprocedure type. To pass the above example PL/pgSQL function as an argument, the SQL for the argument is:

Code
'sample_callbackfunc(double precision[], integer[], text[])'::regprocedure

Note that PostgreSQL array types do not encode dimensions in function signatures, so multidimensional callback arguments are written as double precision[] and integer[] in the regprocedure signature.

mask

An n-dimensional array (matrix) of numbers used to filter what cells get passed to map algebra call-back function. 0 means a neighbor cell value should be treated as no-data and 1 means value should be treated as data. If weight is set to true, then the values, are used as multipliers to multiple the pixel value of that value in the neighborhood position.

weighted

mask 값에 가중치를 적용해야 할지(원래 값으로 곱해야 할지) 말지(mask를 입력받는 최초 버전에만 적용할지)를 표시하는 불 값(참/거짓)입니다.

pixeltype

pixeltype 을 설정할 경우, 새 래스터의 밴드 하나가 해당 픽셀 유형이 될 것입니다. pixeltype 이 NULL이거나 생략된 경우, 새 래스터 밴드가 첫 번째 래스터의 지정된 밴드와(범위 유형의 경우: INTERSECTION, UNION, FIRST, CUSTOM), 또는 적절한 래스터의 지정된 밴드와(범위 유형의 경우: SECOND, LAST) 동일한 픽셀 유형을 가지게 될 것입니다. 어떤 유형인지 확신하지 못 한다면, 언제나 pixeltype 을 설정하십시오.

출력 래스터의 픽셀 유형은 ST_BandPixelType 목록에 존재하는 유형 가운데 하나이거나, 생략되거나, NULL로 설정돼야만 합니다.

extenttype

사용할 수 있는 값은 INTERSECTION(기본값), UNION, FIRST(래스터 1개를 입력받는 변종들의 기본값), SECOND, LAST, CUSTOM입니다.

customextent

extentype 이 CUSTOM일 경우, 래스터가 customextent 를 입력받아야만 합니다. 변종 1의 4번째 예시를 참조하십시오.

distancex

The distance in pixels from the reference cell in x direction. So width of resulting matrix would be 2*distancex + 1.If not specified only the reference cell is considered (neighborhood of 0).

distancey

참조 셀에서 나온 Y 방향의 픽셀 단위 거리입니다. 결과 매트릭스의 높이는 2*distancey + 1 일 것입니다. 따로 설정하지 않으면 참조 셀만 (이웃 셀의 개수가 0) 고려합니다.

userargs

If the callbackfunc declares a third argument, that argument is a variadic text array. All trailing text arguments are passed through to the specified callbackfunc, and are contained in the userargs argument.

[참고]

(다양한 개수의 인수를 입력받는) VARIADIC 키워드에 대한 더 자세한 정보를 알고 싶다면, PostgreSQL 문서 가운데 Query Language (SQL) Functions 의 "SQL Functions with Variable Numbers of Arguments" 단원을 참조하십시오.

변종 1은 많은 래스터 그리고/또는 많은 밴드에 대해 맵 대수 연산을 이용할 수 있도록 해주는 rastbandarg 배열을 입력받습니다. 변종 1 예시를 참조하십시오.

변종 2 및 3은 한 래스터의 1개 이상의 밴드에 대해 연산합니다. 변종 2및 3의 예시를 참조하십시오.

변종 4는 각 래스터가 밴드 1개씩 가지고 있는 래스터 2개에 대해 연산합니다. 변종 4 예시를 참조하십시오.

2.2.0 버전부터 mask를 추가할 수 있습니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

Compare an unmasked mean with neighbor-only and weighted-neighbor masks. The weighted mask multiplies neighboring values by 2 before computing the result.

Code
WITH foo AS (
    SELECT ST_SetBandNoDataValue(
        ST_SetValue(
            ST_SetValue(
                ST_AsRaster(
                    ST_Buffer('LINESTRING(50 50,100 90,100 50)'::geometry, 5, 'join=bevel'),
                    200, 200, ARRAY['8BUI'], ARRAY[100], ARRAY[0]
                ),
                ST_Buffer('POINT(70 70)'::geometry, 10, 'quad_segs=1'),
                50
            ),
            'LINESTRING(20 20,100 100,150 98)'::geometry,
            1
        ),
        0
    ) AS rast
), variants AS (
    SELECT 'original' AS title, rast
    FROM foo
    UNION ALL
    SELECT 'unmasked mean' AS title,
        ST_MapAlgebra(rast, 1, 'ST_Mean4ma(double precision[], int[], text[])'::regprocedure) AS rast
    FROM foo
    UNION ALL
    SELECT 'neighbor-only mean' AS title,
        ST_MapAlgebra(
            rast,
            1,
            'ST_Mean4ma(double precision[], int[], text[])'::regprocedure,
            '{{1,1,1}, {1,0,1}, {1,1,1}}'::double precision[],
            false
        ) AS rast
    FROM foo
    UNION ALL
    SELECT 'weighted neighbor mean' AS title,
        ST_MapAlgebra(
            rast,
            1,
            'ST_Mean4ma(double precision[], int[], text[])'::regprocedure,
            '{{2,2,2}, {2,0,2}, {2,2,2}}'::double precision[],
            true
        ) AS rast
    FROM foo
)
SELECT title, ST_AsPNG(rast) AS image
FROM variants;
래스터 출력
title                  | image
------------------------+--------------------------------
 original               | PNG image, 200 x 200 pixels
 unmasked mean          | PNG image, 200 x 200 pixels
 neighbor-only mean     | PNG image, 200 x 200 pixels
 weighted neighbor mean | PNG image, 200 x 200 pixels
                    
Figure
Geometry figure for visual-rt-st-mapalgebra-01

Variant 1.

래스터 1개, 밴드 1개

Code
WITH foo AS (
    SELECT 1 AS rid, ST_AddBand(ST_MakeEmptyRaster(2, 2, 0, 0, 1, -1, 0, 0, 0), 1, '16BUI', 1, 0) AS rast
)
SELECT
    ST_MapAlgebra(ARRAY[ROW(rast, 1)]::rastbandarg[],
        'sample_callbackfunc(double precision[], int[], text[])'::regprocedure
    ) AS rast
FROM foo
                    

래스터 1개, 밴드 몇 개

Code
WITH foo AS (
    SELECT 1 AS rid, ST_AddBand(ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(2, 2, 0, 0, 1, -1, 0, 0, 0), 1, '16BUI', 1, 0), 2, '8BUI', 10, 0), 3, '32BUI', 100, 0) AS rast
)
SELECT
    ST_MapAlgebra(ARRAY[ROW(rast, 3), ROW(rast, 1), ROW(rast, 3), ROW(rast, 2)]::rastbandarg[],
        'sample_callbackfunc(double precision[], int[], text[])'::regprocedure
    ) AS rast
FROM foo
                    

래스터 몇 개, 밴드 몇 개

Code
WITH foo AS (
    SELECT 1 AS rid, ST_AddBand(ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(2, 2, 0, 0, 1, -1, 0, 0, 0), 1, '16BUI', 1, 0), 2, '8BUI', 10, 0), 3, '32BUI', 100, 0) AS rast UNION ALL
    SELECT 2 AS rid, ST_AddBand(ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(2, 2, 0, 1, 1, -1, 0, 0, 0), 1, '16BUI', 2, 0), 2, '8BUI', 20, 0), 3, '32BUI', 300, 0) AS rast
)
SELECT
    ST_MapAlgebra(ARRAY[ROW(t1.rast, 3), ROW(t2.rast, 1), ROW(t2.rast, 3), ROW(t1.rast, 2)]::rastbandarg[],
        'sample_callbackfunc(double precision[], int[], text[])'::regprocedure
    ) AS rast
FROM foo t1
CROSS JOIN foo t2
WHERE t1.rid = 1
    AND t2.rid = 2
                    

Complete example of tiles of a coverage with neighborhood.

Code
WITH foo AS (
    SELECT 0 AS rid, ST_AddBand(ST_MakeEmptyRaster(2, 2, 0, 0, 1, -1, 0, 0, 0), 1, '16BUI', 1, 0) AS rast UNION ALL
    SELECT 1, ST_AddBand(ST_MakeEmptyRaster(2, 2, 2, 0, 1, -1, 0, 0, 0), 1, '16BUI', 2, 0) AS rast UNION ALL
    SELECT 2, ST_AddBand(ST_MakeEmptyRaster(2, 2, 4, 0, 1, -1, 0, 0, 0), 1, '16BUI', 3, 0) AS rast UNION ALL

    SELECT 3, ST_AddBand(ST_MakeEmptyRaster(2, 2, 0, -2, 1, -1, 0, 0, 0), 1, '16BUI', 10, 0) AS rast UNION ALL
    SELECT 4, ST_AddBand(ST_MakeEmptyRaster(2, 2, 2, -2, 1, -1, 0, 0, 0), 1, '16BUI', 20, 0) AS rast UNION ALL
    SELECT 5, ST_AddBand(ST_MakeEmptyRaster(2, 2, 4, -2, 1, -1, 0, 0, 0), 1, '16BUI', 30, 0) AS rast UNION ALL

    SELECT 6, ST_AddBand(ST_MakeEmptyRaster(2, 2, 0, -4, 1, -1, 0, 0, 0), 1, '16BUI', 100, 0) AS rast UNION ALL
    SELECT 7, ST_AddBand(ST_MakeEmptyRaster(2, 2, 2, -4, 1, -1, 0, 0, 0), 1, '16BUI', 200, 0) AS rast UNION ALL
    SELECT 8, ST_AddBand(ST_MakeEmptyRaster(2, 2, 4, -4, 1, -1, 0, 0, 0), 1, '16BUI', 300, 0) AS rast
)
SELECT
    t1.rid,
    ST_MapAlgebra(ARRAY[ROW(ST_Union(t2.rast), 1)]::rastbandarg[],
        'sample_callbackfunc(double precision[], int[], text[])'::regprocedure,
        '32BUI',
        'CUSTOM', t1.rast,
        1, 1
    ) AS rast
FROM foo t1
CROSS JOIN foo t2
WHERE t1.rid = 4
    AND t2.rid BETWEEN 0 AND 8
    AND ST_Intersects(t1.rast, t2.rast)
GROUP BY t1.rid, t1.rast
                    

Example like the prior one for tiles of a coverage with neighborhood but using only basic SQL features.

Code
WITH src AS (
    SELECT 0 AS rid, ST_AddBand(ST_MakeEmptyRaster(2, 2, 0, 0, 1, -1, 0, 0, 0), 1, '16BUI', 1, 0) AS rast UNION ALL
    SELECT 1, ST_AddBand(ST_MakeEmptyRaster(2, 2, 2, 0, 1, -1, 0, 0, 0), 1, '16BUI', 2, 0) AS rast UNION ALL
    SELECT 2, ST_AddBand(ST_MakeEmptyRaster(2, 2, 4, 0, 1, -1, 0, 0, 0), 1, '16BUI', 3, 0) AS rast UNION ALL

    SELECT 3, ST_AddBand(ST_MakeEmptyRaster(2, 2, 0, -2, 1, -1, 0, 0, 0), 1, '16BUI', 10, 0) AS rast UNION ALL
    SELECT 4, ST_AddBand(ST_MakeEmptyRaster(2, 2, 2, -2, 1, -1, 0, 0, 0), 1, '16BUI', 20, 0) AS rast UNION ALL
    SELECT 5, ST_AddBand(ST_MakeEmptyRaster(2, 2, 4, -2, 1, -1, 0, 0, 0), 1, '16BUI', 30, 0) AS rast UNION ALL

    SELECT 6, ST_AddBand(ST_MakeEmptyRaster(2, 2, 0, -4, 1, -1, 0, 0, 0), 1, '16BUI', 100, 0) AS rast UNION ALL
    SELECT 7, ST_AddBand(ST_MakeEmptyRaster(2, 2, 2, -4, 1, -1, 0, 0, 0), 1, '16BUI', 200, 0) AS rast UNION ALL
    SELECT 8, ST_AddBand(ST_MakeEmptyRaster(2, 2, 4, -4, 1, -1, 0, 0, 0), 1, '16BUI', 300, 0) AS rast
), foo AS (
    SELECT
        t1.rid,
        ST_Union(t2.rast) AS rast
    FROM src t1
    JOIN src t2
        ON ST_Intersects(t1.rast, t2.rast)
        AND t2.rid BETWEEN 0 AND 8
    WHERE t1.rid = 4
    GROUP BY t1.rid
), bar AS (
    SELECT
        t1.rid,
        ST_MapAlgebra(
            ARRAY[ROW(t2.rast, 1)]::rastbandarg[],
            'sample_callbackfunc(double precision[], int[], text[])'::regprocedure,
            '32BUI',
            'CUSTOM', t1.rast,
            1, 1
        ) AS rast
    FROM src t1
    JOIN foo t2
        ON t1.rid = t2.rid
)
SELECT
    rid,
    (ST_MetaData(rast)),
    (ST_BandMetaData(rast, 1)),
    ST_Value(rast, 1, 1, 1)
FROM bar;
                    

Variants 2 and 3.

래스터 1개, 밴드 몇 개

Code
WITH foo AS (
    SELECT 1 AS rid, ST_AddBand(ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(2, 2, 0, 0, 1, -1, 0, 0, 0), 1, '16BUI', 1, 0), 2, '8BUI', 10, 0), 3, '32BUI', 100, 0) AS rast
)
SELECT
    ST_MapAlgebra(
        rast,
        ARRAY[3, 1, 3, 2]::integer[],
        'sample_callbackfunc(double precision[], int[], text[])'::regprocedure
    ) AS rast
FROM foo
                    

래스터 1개, 밴드 1개

Code
WITH foo AS (
    SELECT 1 AS rid, ST_AddBand(ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(2, 2, 0, 0, 1, -1, 0, 0, 0), 1, '16BUI', 1, 0), 2, '8BUI', 10, 0), 3, '32BUI', 100, 0) AS rast
)
SELECT
    ST_MapAlgebra(
        rast,
        2,
        'sample_callbackfunc(double precision[], int[], text[])'::regprocedure
    ) AS rast
FROM foo
                    

Variant 4.

래스터 2개, 밴드 2개

Code
WITH foo AS (
    SELECT 1 AS rid, ST_AddBand(ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(2, 2, 0, 0, 1, -1, 0, 0, 0), 1, '16BUI', 1, 0), 2, '8BUI', 10, 0), 3, '32BUI', 100, 0) AS rast UNION ALL
    SELECT 2 AS rid, ST_AddBand(ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(2, 2, 0, 1, 1, -1, 0, 0, 0), 1, '16BUI', 2, 0), 2, '8BUI', 20, 0), 3, '32BUI', 300, 0) AS rast
)
SELECT
    ST_MapAlgebra(
        t1.rast,
        2,
        t2.rast,
        1,
        'sample_callbackfunc(double precision[], int[], text[])'::regprocedure
    ) AS rast
FROM foo t1
CROSS JOIN foo t2
WHERE t1.rid = 1
    AND t2.rid = 2
                    

제목

ST_MapAlgebra (expression version) — 표현식 버전 - 입력 래스터 1개 또는 2개, 밴드 인덱스, 그리고 사용자 지정 SQL 표현식 1개 이상을 입력받아 밴드 1개를 가진 래스터를 반환합니다.

요약

raster ST_MapAlgebra(raster rast, integer nband, text pixeltype, text expression, double precision nodataval=NULL);

raster ST_MapAlgebra(raster rast, text pixeltype, text expression, double precision nodataval=NULL);

raster ST_MapAlgebra(raster rast1, integer nband1, raster rast2, integer nband2, text expression, text pixeltype=NULL, text extenttype=INTERSECTION, text nodata1expr=NULL, text nodata2expr=NULL, double precision nodatanodataval=NULL);

raster ST_MapAlgebra(raster rast1, raster rast2, text expression, text pixeltype=NULL, text extenttype=INTERSECTION, text nodata1expr=NULL, text nodata2expr=NULL, double precision nodatanodataval=NULL);

Description

표현식 버전 - 입력 래스터 1개 또는 2개, 밴드 인덱스, 그리고 사용자 지정 SQL 표현식 1개 이상을 입력받아 밴드 1개를 가진 래스터를 반환합니다.

2.1.0 버전부터 사용할 수 있습니다.

설명: 변종 1, 2 (래스터 1개)

입력 래스터(rast)에 대해 expression 이 정의하는 유효한 PostgreSQL 대수 연산을 적용해서 형성된, 밴드 1개를 가진 새 래스터를 생성합니다. nband 를 설정하지 않을 경우, 밴드 1로 가정합니다. 이 새 래스터는 원본 래스터와 동일한 지리참조, 너비 및 높이이지만, 밴드는 1개만 가질 것입니다.

pixeltype 을 설정할 경우, 새 래스터의 밴드가 해당 픽셀 유형이 될 것입니다. pixeltype 이 NULL일 경우, 새 래스터의 밴드는 입력 rast 의 밴드와 동일한 픽셀 유형이 될 것입니다.

  • expression 에 키워드를 쓸 수 있습니다.

    1. [rast] - 관심 픽셀의 픽셀 값

    2. [rast.val] - 관심 픽셀의 픽셀 값

    3. [rast.x] - 관심 픽셀의 1-기반 픽셀 열

    4. [rast.y] - 관심 픽셀의 1-기반 픽셀 행

설명: 변종 3, 4 (래스터 2개)

입력 래스터 밴드 rast1, (rast2)에 대한 expression 이 정의하는 밴드 2개에 대해, 유효한 PostgreSQL 대수 연산을 적용해서 형성된, 밴드 1개를 가진 새 래스터를 생성합니다. band1, band2 를 설정하지 않을 경우, 밴드 1로 가정합니다. 출력 래스터는 첫 번째 래스터가 정의하는 그리드 상에 (축척, 기울기 및 픽셀 모서리가) 정렬될 것입니다. extenttype 파라미터가 출력 래스터의 범위를 정의할 것입니다.

expression

래스터 2개가 관련된 PostgreSQL 대수 표현식 및 픽셀들이 교차할 경우 픽셀 값을 정의할 PostgreSQL 정의 함수/연산자입니다. 예: (([rast1] + [rast2])/2.0)::integer

pixeltype

출력 래스터의 픽셀 유형입니다. 이 유형은 ST_BandPixelType 목록에 존재하는 유형 가운데 하나이거나, 생략되거나, NULL로 설정돼야만 합니다. 따로 설정하지 않거나 NULL로 설정하지 않으면, 첫 번째 래스터의 픽셀 유형을 기본값으로 삼을 것입니다.

extenttype

출력 래스터의 범위 제어

  1. INTERSECTION - 새 래스터의 범위는 두 래스터의 교차 부분입니다. 기본값입니다.

  2. UNION - 새 래스터의 범위는 두 래스터를 통합한 범위입니다.

  3. FIRST - 새 래스터의 범위는 첫 번째 래스터의 범위와 동일합니다.

  4. SECOND - 새 래스터의 범위는 두 번째 래스터의 범위와 동일합니다.

nodata1expr

rast1 의 픽셀들이 NODATA 값이고 공간적으로 상응하는 rast2 의 픽셀들이 값을 가지고 있을 때 어떤 것을 반환할지 정의하는 상수만, 또는 rast2 와만 관련된 대수 표현식입니다.

nodata2expr

rast2 의 픽셀들이 NODATA 값이고 공간적으로 상응하는 rast1 의 픽셀들이 값을 가지고 있을 때 어떤 것을 반환할지 정의하는 상수만, 또는 rast1 과만 관련된 대수 표현식입니다.

nodatanodataval

공간적으로 상응하는 rast1rast2 의 픽셀들이 모두 NODATA 값일 경우 반환하는 숫자 상수입니다.

  • expression, nodata1exprnodata2expr 에 키워드를 쓸 수 있습니다.

    1. [rast1] - rast1 에 있는 관심 픽셀의 픽셀 값

    2. [rast1.val] - rast1 에 있는 관심 픽셀의 픽셀 값

    3. [rast1.x] - rast1 에 있는 관심 픽셀의 1-기반 픽셀 열

    4. [rast1.y] - rast1 에 있는 관심 픽셀의 1-기반 픽셀 행

    5. [rast2] - rast2 에 있는 관심 픽셀의 픽셀 값

    6. [rast2.val] - rast2 에 있는 관심 픽셀의 픽셀 값

    7. [rast2.x] - rast2 에 있는 관심 픽셀의 1-기반 픽셀 열

    8. [rast2.y] - rast2 에 있는 관심 픽셀의 1-기반 픽셀 행

예시

Variants 1 and 2.

Code
WITH foo AS (
    SELECT ST_AddBand(ST_MakeEmptyRaster(10, 10, 0, 0, 1, 1, 0, 0, 0), '32BF'::text, 1, -1) AS rast
)
SELECT
    ST_MapAlgebra(rast, 1, NULL, 'ceil([rast]*[rast.x]/[rast.y]+[rast.val])')
FROM foo;
                    

Variant 3 and 4.

Code
WITH foo AS (
    SELECT 1 AS rid, ST_AddBand(ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(2, 2, 0, 0, 1, -1, 0, 0, 0), 1, '16BUI', 1, 0), 2, '8BUI', 10, 0), 3, '32BUI'::text, 100, 0) AS rast UNION ALL
    SELECT 2 AS rid, ST_AddBand(ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(2, 2, 0, 1, 1, -1, 0, 0, 0), 1, '16BUI', 2, 0), 2, '8BUI', 20, 0), 3, '32BUI'::text, 300, 0) AS rast
)
SELECT
    ST_MapAlgebra(
        t1.rast,
        2,
        t2.rast,
        1,
        '([rast2] + [rast1.val]) / 2'
    ) AS rast
FROM foo t1
CROSS JOIN foo t2
WHERE t1.rid = 1
    AND t2.rid = 2;
                    

제목

ST_MapAlgebraExpr — 래스터 밴드 1개 버전: 입력 래스터에 대해 유효한 PostgreSQL 대수 연산을 적용해서 형성되고, 설정한 픽셀 유형을 가진, 밴드 1개를 가진 새 래스터를 생성합니다. 따로 밴드를 설정하지 않을 경우, 밴드 1로 가정합니다.

요약

raster ST_MapAlgebraExpr(raster rast, integer band, text pixeltype, text expression, double precision nodataval=NULL);

raster ST_MapAlgebraExpr(raster rast, text pixeltype, text expression, double precision nodataval=NULL);

Description

[주의]

ST_MapAlgebraExpr 2.1.0 버전부터 더 이상 이 함수를 지원하지 않습니다. 대신 ST_MapAlgebra (expression version) 함수를 이용하십시오.

입력 래스터(rast)에 대해 expression 이 정의하는 유효한 PostgreSQL 대수 연산을 적용해서 형성된, 밴드 1개를 가진 새 래스터를 생성합니다. nband 를 설정하지 않을 경우, 밴드 1로 가정합니다. 이 새 래스터는 원본 래스터와 동일한 지리참조, 너비 및 높이이지만, 밴드는 1개만 가질 것입니다.

pixeltype 을 설정할 경우, 새 래스터의 밴드가 해당 픽셀 유형이 될 것입니다. pixeltype 이 NULL일 경우, 새 래스터의 밴드는 입력 rast 의 밴드와 동일한 픽셀 유형이 될 것입니다.

표현식에서 원본 밴드의 픽셀 값을 참조하는 데 [rast], 1-기반 픽셀 열 인덱스를 참조하는 데 [rast.x], 1-기반 픽셀 행 인덱스를 참조하는 데 [rast.y] 용어를 사용할 수 있습니다.

2.0.0 버전부터 사용할 수 있습니다.

예시

원본 래스터 2개를 입력받는 모듈로(modulo) 함수인 원본으로부터 밴드 1개를 가진 새 래스터를 생성합니다.

Code
ALTER TABLE dummy_rast ADD COLUMN map_rast raster;
UPDATE dummy_rast SET map_rast = ST_MapAlgebraExpr(rast, NULL, 'mod([rast]::numeric,2)') WHERE rid = 2;

SELECT
    ST_Value(rast, 1, i, j) As origval,
    ST_Value(map_rast, 1, i, j) As mapval
FROM dummy_rast
CROSS JOIN generate_series(1, 3) AS i
CROSS JOIN generate_series(1, 3) AS j
WHERE rid = 2;
래스터 출력
origval | mapval
---------+--------
     253 |      1
     254 |      0
     253 |      1
     253 |      1
     254 |      0
     254 |      0
     250 |      0
     254 |      0
     254 |      0

재분류를 거치고 NODATA 값을 0으로 설정한 원본으로부터 픽셀 유형이 2BUI인, 밴드 1개를 가진 새 래스터를 생성합니다.

Code
ALTER TABLE dummy_rast ADD COLUMN map_rast2 raster;
UPDATE dummy_rast SET
    map_rast2 = ST_MapAlgebraExpr(rast, '2BUI'::text, 'CASE WHEN [rast] BETWEEN 100 and 250 THEN 1 WHEN [rast] = 252 THEN 2 WHEN [rast] BETWEEN 253 and 254 THEN 3 ELSE 0 END'::text, '0')
WHERE rid = 2;

SELECT DISTINCT
    ST_Value(rast, 1, i, j) As origval,
    ST_Value(map_rast2, 1, i, j) As mapval
FROM dummy_rast
CROSS JOIN generate_series(1, 5) AS i
CROSS JOIN generate_series(1, 5) AS j
WHERE rid = 2;
래스터 출력
origval | mapval
---------+--------
     249 |      1
     250 |      1
     251 |
     252 |      2
     253 |      3
     254 |      3
Code
SELECT
    ST_BandPixelType(map_rast2) As b1pixtyp
FROM dummy_rast
WHERE rid = 2;
래스터 출력
2BUI

A self-contained source raster and the raster produced by classifying its values into four display levels.

Code
WITH source AS (
    SELECT ST_SetValues(
        ST_AddBand(
            ST_MakeEmptyRaster(8, 8, 0, 8, 1, -1, 0, 0, 0),
            1, '8BUI', 0, 0
        ),
        1, 1, 1,
        ARRAY[
            [0, 1, 2, 3, 4, 5, 6, 7],
            [8, 9, 10, 11, 12, 13, 14, 15],
            [16, 17, 18, 19, 20, 21, 22, 23],
            [24, 25, 26, 27, 28, 29, 30, 31],
            [32, 33, 34, 35, 36, 37, 38, 39],
            [40, 41, 42, 43, 44, 45, 46, 47],
            [48, 49, 50, 51, 52, 53, 54, 55],
            [56, 57, 58, 59, 60, 61, 62, 63]
        ]::double precision[][]
    ) AS rast
), variants AS (
    SELECT 'source' AS title, rast AS rendered
    FROM source
    UNION ALL
    SELECT
        'classified',
        ST_MapAlgebraExpr(rast, '8BUI', 'floor([rast] / 16) * 85')
    FROM source
)
SELECT title, ST_AsPNG(rendered) AS image
FROM variants
ORDER BY title DESC;
래스터 출력
title      | image
------------+-------------------------
 source     | PNG image, 8 x 8 pixels
 classified | PNG image, 8 x 8 pixels
Figure
Geometry figure for visual-rt-st-mapalgebraexpr-04

Map algebra altering the first band of a three-band raster.

original (column rast_view)

rast_view_ma

밴드 3개를 가진 원본 래스터에서 맵 대수로 첫 번째 밴드를 조정하고 나머지 두 밴드는 그대로 둔 상태로, 동일한 픽셀 유형인 밴드 3개를 가진 새 래스터를 생성합니다.

Code
SELECT
    ST_AddBand(ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(rast_view),
                ST_MapAlgebraExpr(rast_view, 1, NULL, 'tan([rast])*[rast]')
            ),
            ST_Band(rast_view, 2)
        ),
        ST_Band(rast_view, 3)
    )  As rast_view_ma
FROM wind
WHERE rid=167;
                    

제목

ST_MapAlgebraExpr — 래스터 밴드 2개 버전: 입력 래스터 2개에 대해 유효한 PostgreSQL 대수 연산을 적용해서 형성되고, 설정한 픽셀 유형을 가진, 밴드 1개를 가진 새 래스터를 생성합니다. 따로 밴드를 설정하지 않을 경우, 각 래스터의 밴드 1로 가정합니다. 출력 래스터는 첫 번째 래스터가 정의하는 그리드 상에 (축척, 기울기 및 픽셀 모서리가) 정렬될 것입니다. extenttype 파라미터가 출력 래스터의 범위를 정의할 것입니다. extenttype 의 값은 INTERSECTION, UNION, FIRST, SECOND가 될 수 있습니다.

요약

raster ST_MapAlgebraExpr(raster rast1, raster rast2, text expression, text pixeltype=same_as_rast1_band, text extenttype=INTERSECTION, text nodata1expr=NULL, text nodata2expr=NULL, double precision nodatanodataval=NULL);

raster ST_MapAlgebraExpr(raster rast1, integer band1, raster rast2, integer band2, text expression, text pixeltype=same_as_rast1_band, text extenttype=INTERSECTION, text nodata1expr=NULL, text nodata2expr=NULL, double precision nodatanodataval=NULL);

Description

[주의]

ST_MapAlgebraExpr 2.1.0 버전부터 더 이상 이 함수를 지원하지 않습니다. 대신 ST_MapAlgebra (expression version) 함수를 이용하십시오.

입력 래스터 밴드 rast1, (rast2)에 대한 expression 이 정의하는 밴드 2개에 대해, 유효한 PostgreSQL 대수 연산을 적용해서 형성된, 밴드 1개를 가진 새 래스터를 생성합니다. band1, band2 를 설정하지 않을 경우, 밴드 1로 가정합니다. 출력 래스터는 첫 번째 래스터가 정의하는 그리드 상에 (축척, 기울기 및 픽셀 모서리가) 정렬될 것입니다. extenttype 파라미터가 출력 래스터의 범위를 정의할 것입니다.

expression

래스터 2개가 관련된 PostgreSQL 대수 표현식 및 픽셀들이 교차할 경우 픽셀 값을 정의할 PostgreSQL 정의 함수/연산자입니다. 예: (([rast1] + [rast2])/2.0)::integer

pixeltype

출력 래스터의 픽셀 유형입니다. 이 유형은 ST_BandPixelType 목록에 존재하는 유형 가운데 하나이거나, 생략되거나, NULL로 설정돼야만 합니다. 따로 설정하지 않거나 NULL로 설정하지 않으면, 첫 번째 래스터의 픽셀 유형을 기본값으로 삼을 것입니다.

extenttype

출력 래스터의 범위 제어

  1. INTERSECTION - 새 래스터의 범위는 두 래스터의 교차 부분입니다. 기본값입니다.

  2. UNION - 새 래스터의 범위는 두 래스터를 통합한 범위입니다.

  3. FIRST - 새 래스터의 범위는 첫 번째 래스터의 범위와 동일합니다.

  4. SECOND - 새 래스터의 범위는 두 번째 래스터의 범위와 동일합니다.

nodata1expr

rast1 의 픽셀들이 NODATA 값이고 공간적으로 상응하는 rast2 의 픽셀들이 값을 가지고 있을 때 어떤 것을 반환할지 정의하는 상수만, 또는 rast2 와만 관련된 대수 표현식입니다.

nodata2expr

rast2 의 픽셀들이 NODATA 값이고 공간적으로 상응하는 rast1 의 픽셀들이 값을 가지고 있을 때 어떤 것을 반환할지 정의하는 상수만, 또는 rast1 과만 관련된 대수 표현식입니다.

nodatanodataval

공간적으로 상응하는 rast1rast2 의 픽셀들이 모두 NODATA 값일 경우 반환하는 숫자 상수입니다.

pixeltype 을 설정할 경우, 새 래스터의 밴드가 해당 픽셀 유형이 될 것입니다. pixeltype 이 NULL이거나 따로 설정하지 않을 경우, 새 래스터의 밴드는 입력 rast1 의 밴드와 동일한 픽셀 유형이 될 것입니다.

원본 밴드의 픽셀 값을 참조하는 데 [rast1.val], [rast2.val], 픽셀의 열/행 위치를 참조하는 데 [rast1.x], [rast1.y] 등의 용어를 사용하십시오.

2.0.0 버전부터 사용할 수 있습니다.

예시

2 Band Intersection and Union.

원본 래스터 2개를 입력받는 모듈로(modulo) 함수인 원본으로부터 밴드 1개를 가진 새 래스터를 생성합니다.

Create a cool set of rasters.

Insert some cool shapes around Boston in Massachusetts state plane meters, then map their intersection and union.

Code
DROP TABLE IF EXISTS fun_shapes;
CREATE TABLE fun_shapes(rid serial PRIMARY KEY, fun_name text, rast raster);

INSERT INTO fun_shapes(fun_name, rast)
VALUES ('ref', ST_AsRaster(ST_MakeEnvelope(235229, 899970, 237229, 901930, 26986), 200, 200, '8BUI', 0, 0));

INSERT INTO fun_shapes(fun_name, rast)
WITH ref(rast) AS (SELECT rast FROM fun_shapes WHERE fun_name = 'ref' )
SELECT 'area' AS fun_name, ST_AsRaster(ST_Buffer(ST_SetSRID(ST_Point(236229, 900930), 26986), 1000),
            ref.rast, '8BUI', 10, 0) As rast
FROM ref
UNION ALL
SELECT 'rand bubbles',
       ST_AsRaster(
           (
               SELECT ST_Collect(geom)
               FROM (
                   SELECT ST_Buffer(
                       ST_SetSRID(ST_Point(236229 + i*random()*100, 900930 + j*random()*100), 26986),
                       random()*20
                   ) AS geom
                   FROM generate_series(1, 10) AS i,
                        generate_series(1, 10) AS j
               ) AS foo
           ),
           ref.rast, '8BUI', 200, 0
       )
FROM ref;

SELECT  ST_MapAlgebraExpr(area.rast, bub.rast, '[rast2.val]', '8BUI', 'INTERSECTION', '[rast2.val]', '[rast1.val]') As interrast,
        ST_MapAlgebraExpr(area.rast, bub.rast, '[rast2.val]', '8BUI', 'UNION', '[rast2.val]', '[rast1.val]') As unionrast
FROM
  (SELECT rast FROM fun_shapes WHERE fun_name = 'area') As area
CROSS JOIN
  (SELECT rast FROM fun_shapes WHERE fun_name = 'rand bubbles') As bub
                    

The same intersection and union operations using two deterministic, self-contained rasters.

Code
WITH canvas AS (
    SELECT ST_AddBand(
        ST_MakeEmptyRaster(80, 80, 0, 80, 1, -1, 0, 0, 0),
        1, '8BUI', 40, 0
    ) AS rast
), inputs AS (
    SELECT
        rast AS raster_1,
        ST_AsRaster(
            ST_Buffer(ST_Point(40, 40), 28),
            rast,
            '8BUI', 220, 0
        ) AS raster_2
    FROM canvas
), variants AS (
    SELECT 'raster 1' AS title, raster_1 AS rendered FROM inputs
    UNION ALL
    SELECT 'raster 2', raster_2 FROM inputs
    UNION ALL
    SELECT 'intersection', ST_MapAlgebraExpr(
        raster_1, raster_2,
        '[rast2.val]', '8BUI', 'INTERSECTION',
        '[rast2.val]', '[rast1.val]'
    ) FROM inputs
    UNION ALL
    SELECT 'union', ST_MapAlgebraExpr(
        raster_1, raster_2,
        '[rast2.val]', '8BUI', 'UNION',
        '[rast2.val]', '[rast1.val]'
    ) FROM inputs
)
SELECT title, ST_AsPNG(rendered) AS image
FROM variants
ORDER BY CASE title
    WHEN 'raster 1' THEN 1
    WHEN 'raster 2' THEN 2
    WHEN 'intersection' THEN 3
    ELSE 4
END;
래스터 출력
title        | image
--------------+---------------------------
 raster 1     | PNG image, 80 x 80 pixels
 raster 2     | PNG image, 56 x 56 pixels
 intersection | PNG image, 56 x 56 pixels
 union        | PNG image, 80 x 80 pixels
Figure
Geometry figure for visual-rt-st-mapalgebraexpr2-01

Overlaying rasters on a one-unit-per-pixel canvas as separate bands. We use ST_AsPNG to render the image so all single band ones look grey.

Code
WITH mygeoms AS (
    SELECT 2 AS bnum, ST_Buffer(ST_Point(1, 5), 10) AS geom
    UNION ALL
    SELECT 3,
        ST_Buffer(
            ST_GeomFromText('LINESTRING(50 50,150 150,150 50)'),
            10,
            'join=bevel'
        )
    UNION ALL
    SELECT 1,
        ST_Buffer(
            ST_GeomFromText('LINESTRING(60 50,150 150,150 50)'),
            5,
            'join=bevel'
        )
), canvas AS (
    SELECT ST_AddBand(
        ST_MakeEmptyRaster(
            200,
            200,
            ST_XMin(e)::integer,
            ST_YMax(e)::integer,
            1, -1, 0, 0),
        '8BUI'::text,
        0
    ) AS rast
    FROM (
      SELECT ST_Extent(geom) AS e
      FROM mygeoms
    ) AS bounds
), rbands AS (
    SELECT ARRAY(
        SELECT ST_MapAlgebraExpr(
            canvas.rast,
            ST_AsRaster(m.geom, canvas.rast, '8BUI', 100),
            '[rast2.val]', '8BUI', 'FIRST',
            '[rast2.val]', '[rast1.val]'
        )
        FROM mygeoms AS m
        CROSS JOIN canvas
        ORDER BY m.bnum
    ) AS rasts
)
SELECT title, ST_AsPNG(rendered) AS image
FROM rbands
CROSS JOIN LATERAL (VALUES
    ('band 1', rasts[1]),
    ('band 2', rasts[2]),
    ('band 3', rasts[3]),
    ('RGB', ST_AddBand(ST_AddBand(rasts[1], rasts[2]), rasts[3]))
) AS variants(title, rendered);
래스터 출력
title  | image
--------+-----------------------------
 band 1 | PNG image, 200 x 200 pixels
 band 2 | PNG image, 200 x 200 pixels
 band 3 | PNG image, 200 x 200 pixels
 RGB    | PNG image, 200 x 200 pixels
Figure
Geometry figure for visual-rt-st-mapalgebraexpr2-02

Overlay a two-meter boundary of selected parcels over aerial imagery. The query first unions the parcel geometries, clips the source raster shards to the region, unions those smaller shards, and finally adds the first two bands plus a third-band map algebra overlay.

Create a new three-band raster composed of the first two clipped bands and the third band overlaid with the geometry. This query took 3.6 seconds on a 64-bit PostGIS Windows installation.

Code
WITH pr AS (
    SELECT ST_Clip(rast, ST_Expand(geom, 50)) AS rast, g.geom
    FROM aerials.o_2_boston AS r
    INNER JOIN (
        SELECT ST_Union(ST_Transform(geom, 26986)) AS geom
        FROM landparcels
        WHERE pid IN ('0303890000', '0303900000')
    ) AS g
        ON ST_Intersects(rast::geometry, ST_Expand(g.geom, 50))
), prunion AS (
    SELECT ST_AddBand(
        NULL,
        ARRAY[
            ST_Union(rast, 1),
            ST_Union(rast, 2),
            ST_Union(rast, 3)
        ]
    ) AS clipped,
    geom
    FROM pr
    GROUP BY geom
)
SELECT ST_AddBand(
    ST_Band(clipped, ARRAY[1, 2]),
    ST_MapAlgebraExpr(
     ST_Band(clipped, 3),
     ST_AsRaster(ST_Buffer(ST_Boundary(geom), 2), clipped, '8BUI', 250),
     '[rast2.val]',
     '8BUI',
     'FIRST',
     '[rast2.val]',
     '[rast1.val]') ) As rast
FROM prunion;
                    

Parcel-boundary overlay.

The blue lines are the boundaries of selected parcels

The generated four-panel canvas example above shows the same band-overlay technique without requiring an external aerial-imagery or parcel table.


제목

ST_MapAlgebraFct — 래스터 밴드 1개 버전: 입력 래스터에 대해 유효한 PostgreSQL 대수 연산을 적용해서 형성되고, 설정한 픽셀 유형을 가진, 밴드 1개를 가진 새 래스터를 생성합니다. 따로 밴드를 설정하지 않을 경우, 밴드 1로 가정합니다.

요약

raster ST_MapAlgebraFct(raster rast, regprocedure onerasteruserfunc);

raster ST_MapAlgebraFct(raster rast, regprocedure onerasteruserfunc, text[] VARIADIC args);

raster ST_MapAlgebraFct(raster rast, text pixeltype, regprocedure onerasteruserfunc);

raster ST_MapAlgebraFct(raster rast, text pixeltype, regprocedure onerasteruserfunc, text[] VARIADIC args);

raster ST_MapAlgebraFct(raster rast, integer band, regprocedure onerasteruserfunc);

raster ST_MapAlgebraFct(raster rast, integer band, regprocedure onerasteruserfunc, text[] VARIADIC args);

raster ST_MapAlgebraFct(raster rast, integer band, text pixeltype, regprocedure onerasteruserfunc);

raster ST_MapAlgebraFct(raster rast, integer band, text pixeltype, regprocedure onerasteruserfunc, text[] VARIADIC args);

Description

[주의]

ST_MapAlgebraFct 2.1.0 버전부터 더 이상 이 함수를 지원하지 않습니다. 대신 ST_MapAlgebra (callback function version) 함수를 이용하십시오.

입력 래스터(rast)에 대해 onerasteruserfunc 가 정의하는 유효한 PostgreSQL 함수를 적용해서 형성된, 밴드 1개를 가진 새 래스터를 생성합니다. band 를 설정하지 않을 경우, 밴드 1로 가정합니다. 이 새 래스터는 원본 래스터와 동일한 지리참조, 너비 및 높이이지만, 밴드는 1개만 가질 것입니다.

pixeltype 을 설정할 경우, 새 래스터의 밴드가 해당 픽셀 유형이 될 것입니다. pixeltype 이 NULL일 경우, 새 래스터의 밴드는 입력 rast 의 밴드와 동일한 픽셀 유형이 될 것입니다.

The onerasteruserfunc parameter must be the name and signature of a SQL or PL/pgSQL function, cast to a regprocedure. A very simple and quite useless PL/pgSQL function example is:

Code
CREATE OR REPLACE FUNCTION simple_function(pixel FLOAT, pos INTEGER[], VARIADIC args TEXT[])
RETURNS FLOAT
AS $$ BEGIN
    RETURN 0.0;
END; $$
LANGUAGE 'plpgsql' IMMUTABLE;

The userfunction may accept two or three arguments: a float value, an optional integer array, and a variadic text array. The first argument is the value of an individual raster cell (regardless of the raster datatype). The second argument is the position of the current processing cell in the form '{x,y}'. The third argument indicates that all remaining parameters to ST_MapAlgebraFct shall be passed through to the userfunction.

Passing a regprodedure argument to a SQL function requires the full function signature to be passed, then cast to a regprocedure type. To pass the above example PL/pgSQL function as an argument, the SQL for the argument is:

Code
'simple_function(float,integer[],text[])'::regprocedure

Note that the argument contains the name of the function, the types of the function arguments, quotes around the name and argument types, and a cast to a regprocedure.

userfunction 에 들어가는 세 번째 인수는 variadic text 배열입니다. 어떤 ST_MapAlgebraFct 함수 호출에도 입력되는 길고 긴 텍스트 인수들이 모두 지정된 userfunction 에 넘겨지며, args 인수에 담겨집니다.

[참고]

(다양한 개수의 인수를 입력받는) VARIADIC 키워드에 대한 더 자세한 정보를 알고 싶다면, PostgreSQL 문서 가운데 Query Language (SQL) Functions 의 "SQL Functions with Variable Numbers of Arguments" 단원을 참조하십시오.

[참고]

공간 처리를 위해 사용자 함수에 어떤 인수를 넘겨주기로 하고 말고에 상관없이, userfunction 에 들어가는 text[] 인수는 필요합니다.

2.0.0 버전부터 사용할 수 있습니다.

예시

원본 래스터 2개를 입력받는 모듈로(modulo) 함수인 원본으로부터 밴드 1개를 가진 새 래스터를 생성합니다.

Code
ALTER TABLE dummy_rast ADD COLUMN map_rast raster;
CREATE FUNCTION mod_fct(pixel float, pos integer[], variadic args text[])
RETURNS float
AS $$
BEGIN
    RETURN pixel::integer % 2;
END;
$$
LANGUAGE 'plpgsql' IMMUTABLE;

UPDATE dummy_rast SET map_rast = ST_MapAlgebraFct(rast, NULL, 'mod_fct(float,integer[],text[])'::regprocedure) WHERE rid = 2;

SELECT ST_Value(rast, 1, i, j) As origval, ST_Value(map_rast, 1, i, j) As mapval
FROM dummy_rast CROSS JOIN generate_series(1, 3) AS i CROSS JOIN generate_series(1, 3) AS j
WHERE rid = 2;
래스터 출력
origval | mapval
---------+--------
     253 |      1
     254 |      0
     253 |      1
     253 |      1
     254 |      0
     254 |      0
     250 |      0
     254 |      0
     254 |      0

재분류를 거치고 NODATA 값을 사용자 함수(0)으로 넘겨진 파라미터로 설정한 원본으로부터 픽셀 유형이 2BUI인, 밴드 1개를 가진 새 래스터를 생성합니다.

Code
ALTER TABLE dummy_rast ADD COLUMN map_rast2 raster;
CREATE FUNCTION classify_fct(pixel float, pos integer[], variadic args text[])
RETURNS float
AS
$$
DECLARE
    nodata float := 0;
BEGIN
    IF NOT args[1] IS NULL THEN
        nodata := args[1];
    END IF;
    IF pixel < 251 THEN
        RETURN 1;
    ELSIF pixel = 252 THEN
        RETURN 2;
    ELSIF pixel 
> 252 THEN
        RETURN 3;
    ELSE
        RETURN nodata;
    END IF;
END;
$$
LANGUAGE 'plpgsql';
UPDATE dummy_rast SET map_rast2 = ST_MapAlgebraFct(rast,'2BUI','classify_fct(float,integer[],text[])'::regprocedure, '0') WHERE rid = 2;

SELECT DISTINCT ST_Value(rast,1,i,j) As origval, ST_Value(map_rast2, 1, i, j) As mapval
FROM dummy_rast CROSS JOIN generate_series(1, 5) AS i CROSS JOIN generate_series(1,5) AS j
WHERE rid = 2;
래스터 출력
 origval | mapval
---------+--------
     249 |      1
     250 |      1
     251 |
     252 |      2
     253 |      3
     254 |      3
Code
SELECT ST_BandPixelType(map_rast2) As b1pixtyp
FROM dummy_rast WHERE rid = 2;
래스터 출력
 b1pixtyp
----------
 2BUI

밴드 3개를 가진 원본 래스터에서 맵 대수로 첫 번째 밴드를 조정하고 나머지 두 밴드는 그대로 둔 상태로, 동일한 픽셀 유형인 밴드 3개를 가진 새 래스터를 생성합니다.

Code
CREATE FUNCTION rast_plus_tan(pixel float, pos integer[], variadic args text[])
RETURNS float
AS
$$
BEGIN
    RETURN tan(pixel) * pixel;
END;
$$
LANGUAGE 'plpgsql';

SELECT ST_AddBand(ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(rast_view),
            ST_MapAlgebraFct(rast_view, 1, NULL, 'rast_plus_tan(float,integer[],text[])'::regprocedure)
        ),
        ST_Band(rast_view, 2)
    ),
    ST_Band(rast_view, 3) As rast_view_ma
)
FROM wind
WHERE rid=167;
                    

The deprecated callback form above is equivalent to a modern ST_MapAlgebra (callback function version) expression for simple per-pixel transforms. This build-time example renders the original raster and a modulo-2 classification.

Code
WITH pixels AS (
    SELECT x, y, (x + y * 2)::double precision AS value
    FROM generate_series(1, 48) AS x
    CROSS JOIN generate_series(1, 48) AS y
), rows AS (
    SELECT y, array_agg(value ORDER BY x) AS values
    FROM pixels
    GROUP BY y
), source AS (
    SELECT ST_SetValues(
        ST_AddBand(
            ST_MakeEmptyRaster(48, 48, 0, 48, 1, -1, 0, 0, 0),
            1, '8BUI', 0, 0
        ),
        1, 1, 1, array_agg(values ORDER BY y)::double precision[][]
    ) AS rast
    FROM rows
), variants AS (
    SELECT 'source' AS title, rast AS rendered FROM source
    UNION ALL
    SELECT 'modulo 2', ST_MapAlgebra(
        rast, 1,
        '8BUI',
        'mod([rast]::integer,2) * 255'
    )
    FROM source
)
SELECT title, ST_AsPNG(rendered) AS image
FROM variants
ORDER BY title DESC;
래스터 출력
title   | image
----------+-------------------------
 source   | PNG image, 48 x 48 pixels
 modulo 2 | PNG image, 48 x 48 pixels
Figure
Geometry figure for visual-rt-st-mapalgebrafct-04

제목

ST_MapAlgebraFct — 래스터 밴드 2개 버전: 입력 래스터 2개에 대해 유효한 PostgreSQL 함수를 적용해서 형성되고, 설정한 픽셀 유형을 가진, 밴드 1개를 가진 새 래스터를 생성합니다. 따로 밴드를 설정하지 않을 경우, 밴드 1로 가정합니다. 범위 유형을 따로 설정하지 않을 경우 기본값은 INTERSECTION입니다.

요약

raster ST_MapAlgebraFct(raster rast1, raster rast2, regprocedure tworastuserfunc, text pixeltype=same_as_rast1, text extenttype=INTERSECTION, text[] VARIADIC userargs);

raster ST_MapAlgebraFct(raster rast1, integer band1, raster rast2, integer band2, regprocedure tworastuserfunc, text pixeltype=same_as_rast1, text extenttype=INTERSECTION, text[] VARIADIC userargs);

Description

[주의]

ST_MapAlgebraFct 2.1.0 버전부터 더 이상 이 함수를 지원하지 않습니다. 대신 ST_MapAlgebra (callback function version) 함수를 이용하십시오.

입력 래스터 rast1, rast2 에 대해 tworastuserfunc 가 정의하는 PostgreSQL 함수를 적용해서 형성된, 밴드 1개를 가진 새 래스터를 생성합니다. band1 또는 band2 를 설정하지 않을 경우, 밴드 1로 가정합니다. 이 새 래스터는 원본 래스터와 동일한 지리참조, 너비 및 높이이지만, 밴드는 1개만 가질 것입니다.

pixeltype 을 설정할 경우, 새 래스터의 밴드가 해당 픽셀 유형이 될 것입니다. pixeltype 이 NULL이거나 따로 설정하지 않을 경우, 새 래스터의 밴드는 입력 rast1 의 밴드와 동일한 픽셀 유형이 될 것입니다.

The tworastuserfunc parameter must be the name and signature of an SQL or PL/pgSQL function, cast to a regprocedure. An example PL/pgSQL function example is:

Code
CREATE OR REPLACE FUNCTION simple_function_for_two_rasters(pixel1 FLOAT, pixel2 FLOAT, pos INTEGER[], VARIADIC args TEXT[])
RETURNS FLOAT
AS $$ BEGIN
    RETURN 0.0;
END; $$
LANGUAGE 'plpgsql' IMMUTABLE;

The tworastuserfunc may accept three or four arguments: a double precision value, a double precision value, an optional integer array, and a variadic text array. The first argument is the value of an individual raster cell in rast1 (regardless of the raster datatype). The second argument is an individual raster cell value in rast2. The third argument is the position of the current processing cell in the form '{x,y}'. The fourth argument indicates that all remaining parameters to ST_MapAlgebraFct shall be passed through to the tworastuserfunc.

Passing a regprodedure argument to a SQL function requires the full function signature to be passed, then cast to a regprocedure type. To pass the above example PL/pgSQL function as an argument, the SQL for the argument is:

Code
'simple_function(double precision, double precision, integer[], text[])'::regprocedure

Note that the argument contains the name of the function, the types of the function arguments, quotes around the name and argument types, and a cast to a regprocedure.

The fourth argument to the tworastuserfunc is a variadic text array. All trailing text arguments to any ST_MapAlgebraFct call are passed through to the specified tworastuserfunc, and are contained in the userargs argument.

[참고]

(다양한 개수의 인수를 입력받는) VARIADIC 키워드에 대한 더 자세한 정보를 알고 싶다면, PostgreSQL 문서 가운데 Query Language (SQL) Functions 의 "SQL Functions with Variable Numbers of Arguments" 단원을 참조하십시오.

[참고]

공간 처리를 위해 사용자 함수에 어떤 인수를 넘겨주기로 하고 말고에 상관없이, tworastuserfunc 에 들어가는 text[] 인수는 필요합니다.

2.0.0 버전부터 사용할 수 있습니다.

예시: 캔버스 상에 래스터들을 개별 밴드로서 오버레이

The deprecated two-raster callback form can often be expressed with the modern two-raster ST_MapAlgebra (callback function version) expression variant. This build-time example renders two input rasters and their averaged overlap.

Code
WITH canvas AS (
    SELECT ST_AddBand(
        ST_MakeEmptyRaster(80, 80, 0, 80, 1, -1, 0, 0, 0),
        1, '8BUI', 0, 0
    ) AS rast
), inputs AS (
    SELECT
        ST_AsRaster(ST_Buffer(ST_Point(30, 40), 25), rast, '8BUI', 80, 0)
            AS raster_1,
        ST_AsRaster(ST_Buffer(ST_Point(50, 40), 25), rast, '8BUI', 220, 0)
            AS raster_2
    FROM canvas
), variants AS (
    SELECT 'raster 1' AS title, raster_1 AS rendered FROM inputs
    UNION ALL
    SELECT 'raster 2', raster_2 FROM inputs
    UNION ALL
    SELECT 'averaged', ST_MapAlgebra(
        raster_1, 1,
        raster_2, 1,
        '([rast1] + [rast2]) / 2',
        '8BUI',
        'UNION'
    ) FROM inputs
)
SELECT title, ST_AsPNG(rendered) AS image
FROM variants
ORDER BY title DESC;
래스터 출력
title   | image
----------+-------------------------
 raster 2 | PNG image, 50 x 50 pixels
 raster 1 | PNG image, 50 x 50 pixels
 averaged | PNG image, 70 x 50 pixels
Figure
Geometry figure for visual-rt-st-mapalgebrafct2-01

Define our user defined function.

Code

CREATE OR REPLACE FUNCTION raster_mapalgebra_union(
    rast1 double precision,
    rast2 double precision,
    pos integer[],
    VARIADIC userargs text[]
)
    RETURNS double precision
    AS $$
    DECLARE
    BEGIN
        CASE
            WHEN rast1 IS NOT NULL AND rast2 IS NOT NULL THEN
                RETURN ((rast1 + rast2)/2.);
            WHEN rast1 IS NULL AND rast2 IS NULL THEN
                RETURN NULL;
            WHEN rast1 IS NULL THEN
                RETURN rast2;
            ELSE
                RETURN rast1;
        END CASE;

        RETURN NULL;
    END;
    $$ LANGUAGE 'plpgsql' IMMUTABLE COST 1000;

Prepare a test table of rasters.

Code
DROP TABLE IF EXISTS map_shapes;
CREATE TABLE map_shapes(rid serial PRIMARY KEY, rast raster, bnum integer, descrip text);
INSERT INTO map_shapes(rast,bnum, descrip)
WITH mygeoms
    AS ( SELECT 2 As bnum, ST_Buffer(ST_Point(90,90),30) As geom, 'circle' As descrip
            UNION ALL
            SELECT 3 AS bnum,
                ST_Buffer(ST_GeomFromText('LINESTRING(50 50,150 150,150 50)'), 15) As geom, 'big road' As descrip
            UNION ALL
            SELECT 1 As bnum,
                ST_Translate(ST_Buffer(ST_GeomFromText('LINESTRING(60 50,150 150,150 50)'), 8,'join=bevel'), 10,-6) As geom, 'small road' As descrip
            ),
   -- define our canvas to be 1 to 1 pixel to geometry
   canvas
    AS ( SELECT ST_AddBand(
        ST_MakeEmptyRaster(
            250,
            250,
            ST_XMin(e)::integer,
            ST_YMax(e)::integer,
            1, -1, 0, 0),
        '8BUI'::text,
        0) As rast
        FROM (SELECT ST_Extent(geom) As e,
                    Max(ST_SRID(geom)) As srid
                    from mygeoms
                    ) As foo
            )
-- return our rasters aligned with our canvas
SELECT ST_AsRaster(m.geom, canvas.rast, '8BUI', 240) As rast, bnum, descrip
                FROM mygeoms AS m CROSS JOIN canvas
UNION ALL
SELECT canvas.rast, 4, 'canvas'
FROM canvas;

Map algebra on single-band rasters and then collect the result with ST_AddBand.

Code
INSERT INTO map_shapes(rast,bnum,descrip)
SELECT ST_AddBand(ST_AddBand(rasts[1], rasts[2]),rasts[3]), 4, 'map bands overlay fct union (canvas)'
    FROM (SELECT ARRAY(SELECT ST_MapAlgebraFct(
            m1.rast,
            m2.rast,
            'raster_mapalgebra_union(double precision, double precision, integer[], text[])'::regprocedure,
            '8BUI',
            'FIRST')
                FROM map_shapes As m1 CROSS JOIN map_shapes As m2
    WHERE m1.descrip = 'canvas' AND m2.descrip <
> 'canvas' ORDER BY m2.bnum) As rasts) As foo;

A compact, executable callback example. The source rasters and their averaged overlap are rendered at build time.

Code
CREATE OR REPLACE FUNCTION pg_temp.raster_average(
    value_1 double precision,
    value_2 double precision,
    position integer[],
    VARIADIC userargs text[]
) RETURNS double precision
LANGUAGE SQL IMMUTABLE
AS 'SELECT COALESCE(($1 + $2) / 2.0, $1, $2)';

WITH canvas AS (
    SELECT ST_AddBand(
        ST_MakeEmptyRaster(80, 80, 0, 80, 1, -1, 0, 0, 0),
        1, '8BUI', 0, 0
    ) AS rast
), inputs AS (
    SELECT
        ST_AsRaster(ST_Buffer(ST_Point(30, 40), 25), rast, '8BUI', 80, 0)
            AS raster_1,
        ST_AsRaster(ST_Buffer(ST_Point(50, 40), 25), rast, '8BUI', 220, 0)
            AS raster_2
    FROM canvas
), variants AS (
    SELECT 'raster 1' AS title, raster_1 AS rendered FROM inputs
    UNION ALL
    SELECT 'raster 2', raster_2 FROM inputs
    UNION ALL
    SELECT 'averaged', ST_MapAlgebraFct(
        raster_1,
        raster_2,
        'pg_temp.raster_average(double precision,double precision,integer[],text[])'::regprocedure,
        '8BUI',
        'UNION'
    ) FROM inputs
)
SELECT title, ST_AsPNG(rendered) AS image
FROM variants
ORDER BY title DESC;
래스터 출력
title    | image
----------+---------------------------
 raster 2 | PNG image, 50 x 50 pixels
 raster 1 | PNG image, 50 x 50 pixels
 averaged | PNG image, 70 x 50 pixels

추가 인수를 입력받는 사용자 지정 함수

Code
CREATE OR REPLACE FUNCTION raster_mapalgebra_userargs(
    rast1 double precision,
    rast2 double precision,
    pos integer[],
    VARIADIC userargs text[]
)
    RETURNS double precision
    AS $$
    DECLARE
    BEGIN
        CASE
            WHEN rast1 IS NOT NULL AND rast2 IS NOT NULL THEN
                RETURN least(userargs[1]::integer,(rast1 + rast2)/2.);
            WHEN rast1 IS NULL AND rast2 IS NULL THEN
                RETURN userargs[2]::integer;
            WHEN rast1 IS NULL THEN
                RETURN greatest(rast2, random()*userargs[3]::integer)::integer;
            ELSE
                RETURN greatest(rast1, random()*userargs[4]::integer)::integer;
        END CASE;

        RETURN NULL;
    END;
    $$ LANGUAGE 'plpgsql' VOLATILE COST 1000;

SELECT ST_MapAlgebraFct(
    m1.rast,
    1,
    m1.rast,
    3,
    'raster_mapalgebra_userargs(double precision, double precision, integer[], text[])'::regprocedure,
    '8BUI',
    'INTERSECT',
    '100', '200', '200', '0')
                FROM map_shapes As m1
    WHERE m1.descrip = 'map bands overlay fct union (canvas)';
                    

The generated callback figure above demonstrates the raster alignment and overlap used by this variant; the exact callback result remains available as text.


제목

ST_MapAlgebraFctNgb — 래스터 밴드 1개 버전: 사용자 지정 PostgreSQL 함수를 이용하는 맵 대수 최근접 이웃(Map Algebra Nearest Neighbor)입니다. 입력 래스터 밴드의 값의 이웃(neighborhood)이 관련된 PostgreSQL 사용자 함수가 출력하는 값을 가진 래스터를 반환합니다.

요약

raster ST_MapAlgebraFctNgb(raster rast, integer band, text pixeltype, integer ngbwidth, integer ngbheight, regprocedure onerastngbuserfunc, text nodatamode, text[] VARIADIC args);

Description

[주의]

ST_MapAlgebraFctNgb 2.1.0 버전부터 더 이상 이 함수를 지원하지 않습니다. 대신 ST_MapAlgebra (callback function version) 함수를 이용하십시오.

래스터 1개 버전: 입력 래스터 밴드 값의 이웃(neighborhood)이 관련된 PostgreSQL 사용자 함수가 출력하는 값을 가진 래스터를 반환합니다. 사용자 함수가 픽셀의 이웃 값을 숫자의 배열로 입력받아, 각 픽셀에 대해 사용자 함수의 결과값을 반환해서, 현재 처리중인 픽셀의 픽셀 값을 함수 결과값으로 대체합니다.

rast

사용자 함수를 평가하는 데 쓰이는 래스터

band

평가할 래스터 밴드 번호(기본값은 1)

pixeltype

출력 래스터의 픽셀 유형입니다. 이 유형은 ST_BandPixelType 목록에 존재하는 유형 가운데 하나이거나, 생략되거나, NULL로 설정돼야만 합니다. 따로 설정하지 않거나 NULL로 설정하지 않으면, rast의 픽셀 유형을 기본값으로 삼을 것입니다. 결과값이 픽셀 유형의 허용치보다 클 경우 결과값의 길이를 허용치에 맞춰 줄입니다.

ngbwidth

이웃(neighborhood)의 셀 단위 너비

ngbheight

이웃(neighborhood)의 셀 단위 높이

onerastngbuserfunc

래스터의 단일 밴드의 근접 픽셀에 적용할 PL/pgSQL 또는 psql 사용자 함수입니다. 첫 번째 요소가 사각형 픽셀 이웃을 표현하는 2차원 숫자 배열입니다.

nodatamode

NODATA 또는 NULL인 이웃 픽셀의 경우 함수에 어떤 값을 넘겨줄지 정의합니다.

'ignore': 이웃에서 맞닥뜨린 어떤 NODATA 값도 계산을 통해 무시합니다. 사용자 콜백 함수에 이 플래그를 전송해야만 하며, 사용자 함수는 NODATA 값을 어떻게 무시할 것인지 결정합니다.

'NULL': 이웃에서 맞닥뜨린 모든 NODATA 값이 출력 픽셀을 NULL로 만들 것입니다. 이 경우 사용자 콜백 함수를 건너뜁니다.

'value': 이웃에서 맞닥뜨린 어떤 NODATA 값도 참조 픽셀(이웃의 한가운데 있는 픽셀)로 대체합니다. 이 값이 NODATA일 경우, (영향을 받는 이웃에 대해) 'NULL'과 동일한 습성을 보인다는 점에 주의하십시오.

args

사용자 함수로 넘겨줄 인수들

2.0.0 버전부터 사용할 수 있습니다.

예시

다음 예시는 https://gdal.org/user/drivers/raster/postgisraster.html 에서 설명하는 대로 단일 타일로 불러온 다음 ST_Rescale 예시 대로 준비한 카트리나 래스터를 활용합니다.

A simple 'callback' user function that averages up all the values in a neighborhood.

Code
CREATE OR REPLACE FUNCTION rast_avg(matrix float[][], nodatamode text, variadic args text[])
    RETURNS float AS
    $$
    DECLARE
        _matrix float[][];
        x1 integer;
        x2 integer;
        y1 integer;
        y2 integer;
        sum float;
    BEGIN
        _matrix := matrix;
        sum := 0;
        FOR x in array_lower(matrix, 1)..array_upper(matrix, 1) LOOP
            FOR y in array_lower(matrix, 2)..array_upper(matrix, 2) LOOP
                sum := sum + _matrix[x][y];
            END LOOP;
        END LOOP;
        RETURN (sum*1.0/(array_upper(matrix,1)*array_upper(matrix,2) ))::integer ;
    END;
    $$
LANGUAGE 'plpgsql' IMMUTABLE COST 1000;
                    

Apply the raster averaging callback within two pixels of each input pixel in the X and Y directions.

Code
SELECT ST_MapAlgebraFctNgb(
        rast,
        1,
        '8BUI',
        4,
        4,
        'rast_avg(float[][], text, text[])'::regprocedure,
        'NULL',
        NULL) As nn_with_border
    FROM katrinas_rescaled
    limit 1;
                    

A self-contained neighborhood average. The source raster has a sharp central square, while the result spreads those values across neighboring pixels. The source uses a non-NODATA background so nodatamode ignore averages background values with the square values, instead of treating the background as absent.

Code
WITH source AS (
    SELECT ST_SetValues(
        ST_AddBand(
            ST_MakeEmptyRaster(16, 16, 0, 16, 1, -1, 0, 0, 0),
            1, '8BUI', 25, NULL
        ),
        1, 6, 6,
        ARRAY[
            [240, 240, 240, 240, 240, 240],
            [240, 240, 240, 240, 240, 240],
            [240, 240, 240, 240, 240, 240],
            [240, 240, 240, 240, 240, 240],
            [240, 240, 240, 240, 240, 240],
            [240, 240, 240, 240, 240, 240]
        ]::double precision[][]
    ) AS rast
), variants AS (
    SELECT 'source' AS title, rast AS rendered FROM source
    UNION ALL
    SELECT 'averaged', ST_SetBandNoDataValue(ST_MapAlgebraFctNgb(
        rast,
        1,
        '8BUI',
        2,
        2,
        'ST_Mean4ma(float[][],text,text[])'::regprocedure,
        'ignore',
        NULL
    ), NULL) FROM source
)
SELECT title, ST_AsPNG(rendered) AS image
FROM variants
ORDER BY title DESC;
래스터 출력
title    | image
----------+-------------------------
 source   | PNG image, 16 x 16 pixels
 averaged | PNG image, 16 x 16 pixels
Figure
Geometry figure for visual-rt-st-mapalgebrafctngb-01

Neighborhood averaging.

래스터의 첫 번째 밴드

Averaged result


제목

ST_Reclass — 원본으로부터 재분류된 밴드 유형으로 이루어진 새 래스터를 생성합니다. nband 는 변경할 밴드를 가리킵니다. nband 를 따로 설정하지 않을 경우 밴드 1로 가정합니다. 다른 모든 밴드들은 변경 없이 반환됩니다. 실제 사례: 보기 좋은 형식으로 더 간단하게 렌더링하기 위해 16BUI 밴드를 8BUI 등등으로 변환하십시오.

요약

raster ST_Reclass(raster rast, integer nband, text reclassexpr, text pixeltype, double precision nodataval=NULL);

raster ST_Reclass(raster rast, reclassarg[] VARIADIC reclassargset);

raster ST_Reclass(raster rast, text reclassexpr, text pixeltype);

Description

Creates a new raster formed by applying a reclassification operation defined by the reclassexpr on the input raster (rast). Refer to reclassarg for the description of reclassification expressions. If no band is specified band 1 is assumed.

The new raster will have the same georeference, width, and height as the original raster. The bands of the new raster have pixel type of pixeltype. If reclassargset is specified then each reclassarg defines the type of the target band. Bands not designated are returned unchanged.

2.0.0 버전부터 사용할 수 있습니다.

예시

Basic.

원본의 밴드 2를 8BUI에서 4BUI로 변환하고 101에서 254까지의 모든 값을 NODATA 값으로 설정한 새 래스터를 생성합니다.

Code
ALTER TABLE dummy_rast ADD COLUMN reclass_rast raster;
UPDATE dummy_rast SET reclass_rast = ST_Reclass(rast, 2, '0-87:1-10, 88-100:11-15, 101-254:0-0', '4BUI', 0) WHERE rid = 2;

SELECT i as col, j as row, ST_Value(rast, 2, i, j) As origval,
    ST_Value(reclass_rast, 2, i, j) As reclassval,
    ST_Value(reclass_rast, 2, i, j, false) As reclassval_include_nodata
FROM dummy_rast CROSS JOIN generate_series(1, 3) AS i CROSS JOIN generate_series(1, 3) AS j
WHERE rid = 2;
래스터 출력
col | row | origval | reclassval | reclassval_include_nodata
-----+-----+---------+------------+---------------------------
   1 |   1 |      78 |          9 |                         9
   2 |   1 |      98 |         14 |                        14
   3 |   1 |     122 |            |                         0
   1 |   2 |      96 |         14 |                        14
   2 |   2 |     118 |            |                         0
   3 |   2 |     180 |            |                         0
   1 |   3 |      99 |         15 |                        15
   2 |   3 |     112 |            |                         0
   3 |   3 |     169 |            |                         0

Advanced using multiple reclassargs.

원본 래스터의 밴드 1, 2, 3을 각각 1BB, 4BUI, 4BUI로 변환하고 재분류한 새 래스터를 생성합니다. 이 예시가 (이론적으로 사용자가 가진 밴드의 개수만큼) 무한한 개수의 재분류 인수를 입력받을 수 있는, 다양한 개수의 인수를 입력받는 reclassarg 인수를 이용한다는 점에 주의하십시오.

Code
UPDATE dummy_rast SET reclass_rast =
    ST_Reclass(
        rast,
        ROW(2, '0-87]:1-10, (87-100]:11-15, (101-254]:0-0', '4BUI', NULL)::reclassarg,
        ROW(1, '0-253]:1, 254:0', '1BB', NULL)::reclassarg,
        ROW(3, '0-70]:1, (70-86:2, [86-150):3, [150-255:4', '4BUI', NULL)::reclassarg
        ) WHERE rid = 2;

SELECT i as col, j as row, ST_Value(rast, 1, i, j) As ov1, ST_Value(reclass_rast, 1, i, j) As rv1,
    ST_Value(rast, 2, i, j) As ov2, ST_Value(reclass_rast, 2, i, j) As rv2,
    ST_Value(rast, 3, i, j) As ov3, ST_Value(reclass_rast, 3, i, j) As rv3
FROM dummy_rast CROSS JOIN generate_series(1, 3) AS i CROSS JOIN generate_series(1, 3) AS j
WHERE rid = 2;
래스터 출력
col | row | ov1 | rv1 | ov2 | rv2 | ov3 | rv3
----+-----+-----+-----+-----+-----+-----+-----
  1 |   1 | 253 |   1 |  78 |   9 |  70 |   1
  2 |   1 | 254 |   0 |  98 |  14 |  86 |   3
  3 |   1 | 253 |   1 | 122 |   0 | 100 |   3
  1 |   2 | 253 |   1 |  96 |  14 |  80 |   2
  2 |   2 | 254 |   0 | 118 |   0 | 108 |   3
  3 |   2 | 254 |   0 | 180 |   0 | 162 |   4
  1 |   3 | 250 |   1 |  99 |  15 |  90 |   3
  2 |   3 | 254 |   0 | 112 |   0 | 108 |   3
  3 |   3 | 254 |   0 | 169 |   0 | 175 |   4

Advanced Map a single band 32BF raster to multiple viewable bands.

32BF 밴드 하나만 가진 래스터로부터 새로운 밴드 3개((8BUI,8BUI,8BUI)를 가진 보기 좋은 새 래스터를 생성합니다.

Code
ALTER TABLE wind ADD COLUMN rast_view raster;
UPDATE wind
    set rast_view = ST_AddBand(
        NULL,
        ARRAY[
    ST_Reclass(rast, 1, '0.1-10]:1-10,9-10]:11,(11-33:0'::text, '8BUI'::text, 0),
    ST_Reclass(rast, 1, '11-33):0-255,[0-32:0,(34-1000:0'::text, '8BUI'::text, 0),
    ST_Reclass(rast, 1, '0-32]:0,(32-100:100-255'::text, '8BUI'::text, 0)
    ]
    );
                    

제목

ST_ReclassExact — Creates a new raster composed of bands reclassified from original, using a 1:1 mapping from values in the original band to new values in the destination band.

요약

raster ST_ReclassExact(raster rast, double precision[] inputvalues, double precision[] outputvalues, integer bandnumber=1, text pixeltype=32BF, double precision nodatavalue=NULL);

Description

Creates a new raster formed by applying a reclassification operation defined by the inputvalues and outputvalues arrays. Pixel values found in the input array are mapped to the corresponding value in the output array. All other pixel values are mapped to the nodatavalue.

The output pixel type defaults to float, but can be specified using the pixeltype parameter. If no bandnumber is specified band 1 is assumed.

The new raster will have the same georeference, width, and height as the original raster. Bands not designated are returned unchanged.

Availability: 3.6.0

Example: Basic

Create a small raster and map its pixels to new values.

Create a raster with four pixels: first row 1 2, second row 3 4.

Code
CREATE TABLE reclassexact (
    id integer,
    rast raster
);
INSERT INTO reclassexact (id, rast)
SELECT 1, ST_SetValues(ST_AddBand(ST_MakeEmptyRaster(2, -- width in pixels
        2, -- height in pixels
        0, -- upper-left x-coordinate
        0, -- upper-left y-coordinate
        1, -- pixel size in x-direction
        -1, -- pixel size in y-direction (negative for north-up)
        0, -- skew in x-direction
        0, -- skew in y-direction
        4326  -- SRID (e.g., WGS 84)
      ),
      '32BUI'::text, -- pixel type (e.g., '32BF' for float, '8BUI' for unsigned 8-bit int)
      0.0, -- initial value for the band (e.g., 0.0 or a no-data value)
      -99            -- nodatavalue
    ),
    1, -- band number (usually 1 for single-band rasters)
    1, -- x origin for setting values (usually 1)
    1, -- y origin for setting values (usually 1)
    ARRAY[
      ARRAY[1, 2],
      ARRAY[3, 4]
    ]::double precision[][] -- 2D array of values
  );
                    

Reclass the values to new values and dump the values of the new raster for display.

Code
WITH rc AS (
  SELECT ST_ReclassExact(rast, -- input raster
    ARRAY[4, 3, 2, 1], -- input map
    ARRAY[14, 13, 12, 11], -- output map
    1, -- band number to remap
    '32BUI'              -- output raster pixel type
    ) AS rast
  FROM reclassexact
  WHERE id = 1
  )
SELECT 'rce-1', (ST_DumpValues(rc.rast)).*
FROM rc;
                    

제목

ST_Union — 래스터 타일 집합을 1개 이상의 밴드로 이루어진 단일 래스터로 통합합니다.

요약

raster ST_Union(setof raster rast);

raster ST_Union(setof raster rast, unionarg[] unionargset);

raster ST_Union(setof raster rast, integer nband);

raster ST_Union(setof raster rast, text uniontype);

raster ST_Union(setof raster rast, integer nband, text uniontype);

Description

래스터 타일 집합을 최소한 밴드 1개로 이루어진 단일 래스터로 통합합니다. 출력 래스터의 범위는 전체 집합의 범위입니다. 교차 부분의 경우, uniontype 이 결과 값을 정의합니다. uniontype 의 값은 LAST(기본값), FIRST, MIN, MAX, COUNT, SUM, MEAN, RANGE 가운데 하나입니다.

[참고]

In order for rasters to be unioned, they must all have the same alignment. Use ST_SameAlignment and ST_NotSameAlignmentReason for more details and help. One way to fix alignment issues is to use ST_Resample and use the same reference raster for alignment.

2.0.0 버전부터 사용할 수 있습니다.

개선 사항: 2.1.0 버전부터 속도가 향상됐습니다(완전히 C언어 기반으로 변경했습니다).

2.1.0 버전부터 ST_Union(rast, unionarg) 변종을 사용할 수 있습니다.

개선 사항: 2.1.0 버전부터 ST_Union(rast) 변종 1 함수가 모든 입력 래스터의 모든 밴드를 통합합니다. PostGIS 이전 버전에서는 첫 번째 밴드로 가정했습니다.

개선 사항: 2.1.0 버전부터 ST_Union(rast, uniontype) 변종 4 함수가 모든 입력 래스터의 모든 밴드를 통합합니다.

예시

Reconstitute a single band chunked raster tile.

This creates a single band from first band of raster tiles. That form the original file system tile.

Code
SELECT filename, ST_Union(rast, 1) As file_rast
FROM sometable WHERE filename IN('dem01', 'dem02') GROUP BY filename;
                    

Return a multi-band raster that is the union of tiles intersecting geometry.

This creates a multi band raster collecting all the tiles that intersect a line. Note that In 2.0, this would have just returned a single band raster. , new union works on all bands by default. This is equivalent to unionarg: ARRAY[ROW(1, 'LAST'), ROW(2, 'LAST'), ROW(3, 'LAST')]::unionarg[].

Code
SELECT ST_Union(rast)
FROM aerials.boston
WHERE ST_Intersects(rast, ST_GeomFromText('LINESTRING(230486 887771,230500 88772)', 26986) );
                    

Select and reorder bands while unioning tiles that intersect a geometry.

다음은 밴드들의 하위 집합만을 원하거나, 또는 밴드들의 순서를 변경하고자 하는 경우 더 긴 문법을 사용하는 예시입니다.

This creates a multi band raster collecting all the tiles that intersect a line.

Code
SELECT ST_Union(rast, ARRAY[ROW(2, 'LAST'), ROW(1, 'LAST'), ROW(3, 'LAST')]::unionarg[])
FROM aerials.boston
WHERE ST_Intersects(rast, ST_GeomFromText('LINESTRING(230486 887771,230500 88772)', 26986) );
                    

11.13. 내장 맵 대수 콜백 함수

  • ST_Distinct4ma — 이웃에서 유일한 픽셀 값들의 개수를 계산하는 래스터 공간 처리 함수입니다.
  • ST_InvDistWeight4ma — 픽셀의 이웃으로부터 픽셀 값을 보간하는 래스터 공간 처리 함수입니다.
  • ST_Max4ma — 이웃에서 최대 픽셀 값을 계산하는 래스터 공간 처리 함수입니다.
  • ST_Mean4ma — 이웃에서 평균 픽셀 값을 계산하는 래스터 공간 처리 함수입니다.
  • ST_Min4ma — 이웃에서 최소 픽셀 값을 계산하는 래스터 공간 처리 함수입니다.
  • ST_MinDist4ma — 관심 픽셀과 값을 가지고 있는 이웃 픽셀 사이의 최소 거리를 (픽셀 개수로) 반환하는 래스터 공간 처리 함수입니다.
  • ST_Range4ma — 이웃에 있는 픽셀값들의 범위를 계산하는 래스터 공간 처리 함수입니다.
  • ST_StdDev4ma — 이웃에 있는 픽셀값들의 표준 편차를 계산하는 래스터 공간 처리 함수입니다.
  • ST_Sum4ma — 이웃에 있는 모든 픽셀값들의 합계를 계산하는 래스터 공간 처리 함수입니다.

제목

ST_Distinct4ma — 이웃에서 유일한 픽셀 값들의 개수를 계산하는 래스터 공간 처리 함수입니다.

요약

float8 ST_Distinct4ma(float8[][] matrix, text nodatamode, text[] VARIADIC args);

double precision ST_Distinct4ma(double precision[][][] value, integer[][] pos, text[] VARIADIC userargs);

Description

픽셀의 이웃에 있는 유일한 픽셀 값들의 개수를 계산합니다.

[참고]

변종 1은 ST_MapAlgebraFctNgb 의 콜백 파라미터로 쓰이는 특화된 콜백 함수입니다.

[참고]

변종 2는 ST_MapAlgebra (callback function version) 의 콜백 파라미터로 쓰이는 특화된 콜백 함수입니다.

[주의]

2.1.0 버전부터 ST_MapAlgebraFctNgb 를 지원하지 않기 때문에 변종 1 함수를 쓰지 않는 편이 좋습니다.

2.0.0 버전부터 사용할 수 있습니다.

개선 사항: 2.1.0 버전에서 변종 2가 추가됐습니다.

예시

Code
SELECT
    rid,
    ST_Value(ST_MapAlgebraFctNgb(rast, 1, NULL, 1, 1, 'ST_Distinct4ma(float[][],text,text[])'::regprocedure, 'ignore', NULL), 2, 2
    )
FROM dummy_rast
WHERE rid = 2;
래스터 출력
rid | st_value
-----+----------
   2 |        3
(1 row)

제목

ST_InvDistWeight4ma — 픽셀의 이웃으로부터 픽셀 값을 보간하는 래스터 공간 처리 함수입니다.

요약

double precision ST_InvDistWeight4ma(double precision[][][] value, integer[][] pos, text[] VARIADIC userargs);

Description

거리 역산 가중법(Inverse Distance Weighted method)을 이용해서 픽셀에 대한 보간값을 계산합니다.

userargs 를 통해 넘길 수 있는 선택적인 파라미터가 2개 있습니다. 첫 번째 파라미터는 거리 역산 가중법 방정식에 쓰이는 0과 1 사이의 역률(力率)입니다(다음 방정식의 k 변수). 따로 설정하지 않을 경우, 기본값은 1입니다. 두 번째 파라미터는 관심 픽셀의 값이 이웃에서 나온 보간값에 포함될 경우에만 적용되는 가중치 백분율입니다. 관심 픽셀이 값을 가지고 있고 따로 설정하지 않을 경우, 해당 값을 반환합니다.

The basic inverse-distance weighted estimate is:

z = (Σᵢ zᵢ / dᵢᵏ) / (Σᵢ 1 / dᵢᵏ)

Here zᵢ is a neighboring pixel value, dᵢ is its distance from the pixel being estimated, and k is a real-valued power factor between 0 and 1.

[참고]

이 함수는 ST_MapAlgebra (callback function version) 의 콜백 파라미터로 쓰이는 특화된 콜백 함수입니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

Code
WITH foo AS (
    SELECT ST_SetValues(ST_AddBand(ST_MakeEmptyRaster(3, 3, 0, 0, 1, -1, 0, 0, 0), 1, '32BF', NULL::double precision, -9999),
        1, 1, 1, ARRAY[
            [10, 10, 10],
            [10, NULL, 20],
            [20, 20, 20]
        ]::double precision[][]
    ) AS rast
)
SELECT ST_Value(
    ST_MapAlgebra(
        rast,
        1,
        'ST_InvDistWeight4ma(double precision[][][],integer[][],text[])'::regprocedure,
        '32BF',
        'FIRST',
        NULL,
        1,
        1
    ),
    2, 2
) AS interpolated_value
FROM foo;
래스터 출력
15

제목

ST_Max4ma — 이웃에서 최대 픽셀 값을 계산하는 래스터 공간 처리 함수입니다.

요약

float8 ST_Max4ma(float8[][] matrix, text nodatamode, text[] VARIADIC args);

double precision ST_Max4ma(double precision[][][] value, integer[][] pos, text[] VARIADIC userargs);

Description

픽셀의 이웃에 있는 최대 픽셀 값을 계산합니다.

변종 2의 경우, 해당 값을 userargs 에 넘겨서 NODATA 픽셀의 대체값을 지정할 수 있습니다.

[참고]

변종 1은 ST_MapAlgebraFctNgb 의 콜백 파라미터로 쓰이는 특화된 콜백 함수입니다.

[참고]

변종 2는 ST_MapAlgebra (callback function version) 의 콜백 파라미터로 쓰이는 특화된 콜백 함수입니다.

[주의]

2.1.0 버전부터 ST_MapAlgebraFctNgb 를 지원하지 않기 때문에 변종 1 함수를 쓰지 않는 편이 좋습니다.

2.0.0 버전부터 사용할 수 있습니다.

개선 사항: 2.1.0 버전에서 변종 2가 추가됐습니다.

예시

Code
SELECT
    rid,
    ST_Value(ST_MapAlgebraFctNgb(rast, 1, NULL, 1, 1, 'ST_Max4ma(float[][],text,text[])'::regprocedure, 'ignore', NULL), 2, 2
    )
FROM dummy_rast
WHERE rid = 2;
래스터 출력
rid | st_value
-----+----------
   2 |      254
(1 row)

제목

ST_Mean4ma — 이웃에서 평균 픽셀 값을 계산하는 래스터 공간 처리 함수입니다.

요약

float8 ST_Mean4ma(float8[][] matrix, text nodatamode, text[] VARIADIC args);

double precision ST_Mean4ma(double precision[][][] value, integer[][] pos, text[] VARIADIC userargs);

Description

픽셀의 이웃에 있는 평균 픽셀 값을 계산합니다.

변종 2의 경우, 해당 값을 userargs 에 넘겨서 NODATA 픽셀의 대체값을 지정할 수 있습니다.

[참고]

변종 1은 ST_MapAlgebraFctNgb 의 콜백 파라미터로 쓰이는 특화된 콜백 함수입니다.

[참고]

변종 2는 ST_MapAlgebra (callback function version) 의 콜백 파라미터로 쓰이는 특화된 콜백 함수입니다.

[주의]

2.1.0 버전부터 ST_MapAlgebraFctNgb 를 지원하지 않기 때문에 변종 1 함수를 쓰지 않는 편이 좋습니다.

2.0.0 버전부터 사용할 수 있습니다.

개선 사항: 2.1.0 버전에서 변종 2가 추가됐습니다.

예시

Variant 1.

Code
SELECT
    rid,
    ST_Value(ST_MapAlgebraFctNgb(rast, 1, '32BF', 1, 1, 'ST_Mean4ma(float[][],text,text[])'::regprocedure, 'ignore', NULL), 2, 2
    )
FROM dummy_rast
WHERE rid = 2;
래스터 출력
rid |     st_value
-----+------------------
   2 | 253.222229003906
(1 row)

Variant 2.

Code
SELECT
  rid,
  ST_Value(
      ST_MapAlgebra(rast, 1, 'ST_Mean4ma(double precision[][][], integer[][], text[])'::regprocedure, '32BF', 'FIRST', NULL, 1, 1),
      2,
      2)
FROM dummy_rast
 WHERE rid = 2;
래스터 출력
rid |     st_value
-----+------------------
   2 | 253.222229003906
(1 row)

제목

ST_Min4ma — 이웃에서 최소 픽셀 값을 계산하는 래스터 공간 처리 함수입니다.

요약

float8 ST_Min4ma(float8[][] matrix, text nodatamode, text[] VARIADIC args);

double precision ST_Min4ma(double precision[][][] value, integer[][] pos, text[] VARIADIC userargs);

Description

픽셀의 이웃에 있는 최소 픽셀 값을 계산합니다.

변종 2의 경우, 해당 값을 userargs 에 넘겨서 NODATA 픽셀의 대체값을 지정할 수 있습니다.

[참고]

변종 1은 ST_MapAlgebraFctNgb 의 콜백 파라미터로 쓰이는 특화된 콜백 함수입니다.

[참고]

변종 2는 ST_MapAlgebra (callback function version) 의 콜백 파라미터로 쓰이는 특화된 콜백 함수입니다.

[주의]

2.1.0 버전부터 ST_MapAlgebraFctNgb 를 지원하지 않기 때문에 변종 1 함수를 쓰지 않는 편이 좋습니다.

2.0.0 버전부터 사용할 수 있습니다.

개선 사항: 2.1.0 버전에서 변종 2가 추가됐습니다.

예시

Code
SELECT
    rid,
    ST_Value(ST_MapAlgebraFctNgb(rast, 1, NULL, 1, 1, 'ST_Min4ma(float[][],text,text[])'::regprocedure, 'ignore', NULL), 2, 2
    )
FROM dummy_rast
WHERE rid = 2;
래스터 출력
rid | st_value
-----+----------
   2 |      250
(1 row)

제목

ST_MinDist4ma — 관심 픽셀과 값을 가지고 있는 이웃 픽셀 사이의 최소 거리를 (픽셀 개수로) 반환하는 래스터 공간 처리 함수입니다.

요약

double precision ST_MinDist4ma(double precision[][][] value, integer[][] pos, text[] VARIADIC userargs);

Description

관심 픽셀과 이웃에서 값을 가지고 있는 가장 가까운 픽셀 사이의 최단 거리를 (픽셀 개수로) 반환합니다.

[참고]

이 함수의 목적은 ST_InvDistWeight4ma 함수가 반환하는 관심 픽셀의 보간값의 유용성을 추론하는 것을 도와주는 유익한 데이터 포인트를 제공하는 것입니다. 이웃의 밀도가 희박한 경우 이 함수가 특히 유용합니다.

[참고]

이 함수는 ST_MapAlgebra (callback function version) 의 콜백 파라미터로 쓰이는 특화된 콜백 함수입니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

Code
WITH foo AS (
    SELECT ST_SetValues(ST_AddBand(ST_MakeEmptyRaster(3, 3, 0, 0, 1, -1, 0, 0, 0), 1, '32BF', NULL::double precision, -9999),
        1, 1, 1, ARRAY[
            [10, 10, 10],
            [10, NULL, 20],
            [20, 20, 20]
        ]::double precision[][]
    ) AS rast
)
SELECT ST_Value(
    ST_MapAlgebra(
        rast,
        1,
        'ST_MinDist4ma(double precision[][][],integer[][],text[])'::regprocedure,
        '32BF',
        'FIRST',
        NULL,
        1,
        1
    ),
    2, 2
) AS min_distance
FROM foo;
래스터 출력
1

제목

ST_Range4ma — 이웃에 있는 픽셀값들의 범위를 계산하는 래스터 공간 처리 함수입니다.

요약

float8 ST_Range4ma(float8[][] matrix, text nodatamode, text[] VARIADIC args);

double precision ST_Range4ma(double precision[][][] value, integer[][] pos, text[] VARIADIC userargs);

Description

픽셀의 이웃에 있는 픽셀 값들의 범위를 계산합니다.

변종 2의 경우, 해당 값을 userargs 에 넘겨서 NODATA 픽셀의 대체값을 지정할 수 있습니다.

[참고]

변종 1은 ST_MapAlgebraFctNgb 의 콜백 파라미터로 쓰이는 특화된 콜백 함수입니다.

[참고]

변종 2는 ST_MapAlgebra (callback function version) 의 콜백 파라미터로 쓰이는 특화된 콜백 함수입니다.

[주의]

2.1.0 버전부터 ST_MapAlgebraFctNgb 를 지원하지 않기 때문에 변종 1 함수를 쓰지 않는 편이 좋습니다.

2.0.0 버전부터 사용할 수 있습니다.

개선 사항: 2.1.0 버전에서 변종 2가 추가됐습니다.

예시

Code
SELECT
    rid,
    ST_Value(ST_MapAlgebraFctNgb(rast, 1, NULL, 1, 1, 'ST_Range4ma(float[][],text,text[])'::regprocedure, 'ignore', NULL), 2, 2
    )
FROM dummy_rast
WHERE rid = 2;
래스터 출력
rid | st_value
-----+----------
   2 |        4
(1 row)

제목

ST_StdDev4ma — 이웃에 있는 픽셀값들의 표준 편차를 계산하는 래스터 공간 처리 함수입니다.

요약

float8 ST_StdDev4ma(float8[][] matrix, text nodatamode, text[] VARIADIC args);

double precision ST_StdDev4ma(double precision[][][] value, integer[][] pos, text[] VARIADIC userargs);

Description

픽셀의 이웃에 있는 픽셀 값들의 표준 편차를 계산합니다.

[참고]

변종 1은 ST_MapAlgebraFctNgb 의 콜백 파라미터로 쓰이는 특화된 콜백 함수입니다.

[참고]

변종 2는 ST_MapAlgebra (callback function version) 의 콜백 파라미터로 쓰이는 특화된 콜백 함수입니다.

[주의]

2.1.0 버전부터 ST_MapAlgebraFctNgb 를 지원하지 않기 때문에 변종 1 함수를 쓰지 않는 편이 좋습니다.

2.0.0 버전부터 사용할 수 있습니다.

개선 사항: 2.1.0 버전에서 변종 2가 추가됐습니다.

예시

Code
SELECT
    rid,
    ST_Value(ST_MapAlgebraFctNgb(rast, 1, '32BF', 1, 1, 'ST_StdDev4ma(float[][],text,text[])'::regprocedure, 'ignore', NULL), 2, 2
    )
FROM dummy_rast
WHERE rid = 2;
래스터 출력
rid |     st_value
-----+------------------
   2 | 1.30170822143555
(1 row)

제목

ST_Sum4ma — 이웃에 있는 모든 픽셀값들의 합계를 계산하는 래스터 공간 처리 함수입니다.

요약

float8 ST_Sum4ma(float8[][] matrix, text nodatamode, text[] VARIADIC args);

double precision ST_Sum4ma(double precision[][][] value, integer[][] pos, text[] VARIADIC userargs);

Description

픽셀의 이웃에 있는 모든 픽셀 값들의 합계를 계산합니다.

변종 2의 경우, 해당 값을 userargs 에 넘겨서 NODATA 픽셀의 대체값을 지정할 수 있습니다.

[참고]

변종 1은 ST_MapAlgebraFctNgb 의 콜백 파라미터로 쓰이는 특화된 콜백 함수입니다.

[참고]

변종 2는 ST_MapAlgebra (callback function version) 의 콜백 파라미터로 쓰이는 특화된 콜백 함수입니다.

[주의]

2.1.0 버전부터 ST_MapAlgebraFctNgb 를 지원하지 않기 때문에 변종 1 함수를 쓰지 않는 편이 좋습니다.

2.0.0 버전부터 사용할 수 있습니다.

개선 사항: 2.1.0 버전에서 변종 2가 추가됐습니다.

예시

Code
SELECT
    rid,
    ST_Value(ST_MapAlgebraFctNgb(rast, 1, '32BF', 1, 1, 'ST_Sum4ma(float[][],text,text[])'::regprocedure, 'ignore', NULL), 2, 2
    )
FROM dummy_rast
WHERE rid = 2;
래스터 출력
rid | st_value
-----+----------
   2 |     2279
(1 row)

11.14. 래스터 공간 처리

  • ST_Aspect — 표고 래스터 밴드의 향(기본 단위는 도)을 반환합니다. 지형을 분석하는 데 유용합니다.
  • ST_HillShade — 입력한 방위각, 고도각, 밝기 및 축척을 이용해서 표고 래스터 밴드의 가상적인 음영기복을 반환합니다.
  • ST_Roughness — DEM의 계산된 "거칠기(roughness)"와 함께 래스터를 반환합니다.
  • ST_Slope — 표고 래스터 밴드의 경사(기본 단위는 도)를 반환합니다. 지형을 분석하는 데 유용합니다.
  • ST_TPI — 계산된 지형위치지수(Topographic Position Index)와 함께 래스터를 반환합니다.
  • ST_TRI — 계산된 지형험준도지수(Terrain Ruggedness Index)와 함께 래스터를 반환합니다.
  • ST_InterpolateRaster — Interpolates a gridded surface based on an input set of 3-d points, using the X- and Y-values to position the points on the grid and the Z-value of the points as the surface elevation.
  • ST_Contour — Generates a set of vector contours from the provided raster band, using the GDAL contouring algorithm.

제목

ST_Aspect — 표고 래스터 밴드의 향(기본 단위는 도)을 반환합니다. 지형을 분석하는 데 유용합니다.

요약

raster ST_Aspect(raster rast, integer band=1, text pixeltype=32BF, text units=DEGREES, boolean interpolate_nodata=FALSE);

raster ST_Aspect(raster rast, integer band, raster customextent, text pixeltype=32BF, text units=DEGREES, boolean interpolate_nodata=FALSE);

Description

표고 래스터 밴드의 향(기본 단위는 도)을 반환합니다. 맵 대수를 활용해서 이웃 픽셀들에 향 방정식을 적용합니다.

units 는 향의 단위를 의미합니다. RADIANS, DEGREES(기본값)를 쓸 수 있습니다.

units = RADIANS일 경우, 북쪽에서 시계방향으로 측정한 0과 2π 라디안 사이의 값입니다.

units = DEGREES일 경우, 북쪽에서 시계방향으로 측정한 0도와 360도 사이의 값입니다.

픽셀의 경사가 0일 경우, 픽셀의 향은 -1입니다.

[참고]

경사(slope), 향(aspect), 음영기복(hillshade)에 대한 자세한 내용을 알고 싶다면, ESRI - How hillshade worksERDAS Field Guide - Aspect Images 를 참조하십시오.

2.0.0 버전부터 사용할 수 있습니다.

개선 사항: 2.1.0 버전부터 ST_MapAlgebra()를 이용하며, 선택적인 interpolate_nodata 함수 파라미터가 추가됐습니다.

변경 사항: 2.1.0 미만 버전에서는 반환되는 값이 라디안 단위였습니다. 2.1.0 버전부터 반환되는 값의 기본 단위가 도로 바뀌었습니다.

예시

Variant 1.

This symmetric peak highlights the expected compass directions at the corners and the -1 aspect at the summit. The generated PNG shows the full aspect surface without relying on a manual illustration. The generated source raster is large enough for the PNG to show the directional field around the summit.

Code
WITH pixels AS (
    SELECT
        x,
        y,
        (20 - greatest(abs(x - 9), abs(y - 9)))::double precision AS value
    FROM generate_series(1, 17) AS y
    CROSS JOIN generate_series(1, 17) AS x
), rows AS (
    SELECT
        y,
        array_agg(value ORDER BY x) AS row_values
    FROM pixels
    GROUP BY y
), source AS (
    SELECT ST_SetValues(
        ST_AddBand(
            ST_MakeEmptyRaster(17, 17, 0, 0, 1, -1, 0, 0, 0),
            1, '32BF', 0, -9999
        ),
        1, 1, 1,
        array_agg(row_values ORDER BY y)::double precision[][]
    ) AS rast
    FROM rows
), aspect AS (
    SELECT ST_Aspect(rast, 1, '32BF') AS rast
    FROM source
)
SELECT
    round(ST_Value(rast, 1, 1, 1)::numeric, 3) AS northwest_degrees,
    round(ST_Value(rast, 1, 9, 9)::numeric, 3) AS summit_degrees,
    round(ST_Value(rast, 1, 17, 17)::numeric, 3) AS southeast_degrees,
    ST_AsPNG(ST_ColorMap(rast, 1, 'bluered')) AS image
FROM aspect;
래스터 출력
northwest_degrees | summit_degrees | southeast_degrees | image
-------------------+----------------+-------------------+------------------------
           315.000 |         -1.000 |           135.000 | PNG image, 17 x 17 pixels
Figure
Geometry figure for visual-rt-st-aspect-01

Variant 2.

Complete example of tiles of a coverage.

Code
WITH foo AS (
    SELECT ST_Tile(ST_SetValues(ST_AddBand(ST_MakeEmptyRaster(6, 6, 0, 0, 1, -1, 0, 0, 0),
                1, '32BF', 0, -9999
            ),
            1, 1, 1, ARRAY[
                [1, 1, 1, 1, 1, 1],
                [1, 1, 1, 1, 2, 1],
                [1, 2, 2, 3, 3, 1],
                [1, 1, 3, 2, 1, 1],
                [1, 2, 2, 1, 2, 1],
                [1, 1, 1, 1, 1, 1]
            ]::double precision[]
        ),
        2, 2
    ) AS rast
)
SELECT
    t1.rast,
    ST_Aspect(ST_Union(t2.rast), 1, t1.rast)
FROM foo t1
CROSS JOIN foo t2
WHERE ST_Intersects(t1.rast, t2.rast)
GROUP BY t1.rast;
                    

제목

ST_HillShade — 입력한 방위각, 고도각, 밝기 및 축척을 이용해서 표고 래스터 밴드의 가상적인 음영기복을 반환합니다.

요약

raster ST_HillShade(raster rast, integer band=1, text pixeltype=32BF, double precision azimuth=315, double precision altitude=45, double precision max_bright=255, double precision scale=1.0, boolean interpolate_nodata=FALSE);

raster ST_HillShade(raster rast, integer band, raster customextent, text pixeltype=32BF, double precision azimuth=315, double precision altitude=45, double precision max_bright=255, double precision scale=1.0, boolean interpolate_nodata=FALSE);

Description

입력한 방위각, 고도각, 밝기 및 축척을 이용해서 표고 래스터 밴드의 가상적인 음영기복을 반환합니다. 맵 대수를 활용해서 이웃 픽셀들에 음영기복 방정식을 적용합니다. 반환되는 픽셀 값은 0과 255 사이입니다.

azimuth 는 북쪽에서 시계방향으로 측정한 0도와 360도 사이의 값입니다.

altitude 는 0도가 지평선, 90도가 천정(天頂)인 0도와 90도 사이의 값입니다.

max_bright 는 0이 밝기가 없고, 255가 최대 밝기인 0과 255 사이의 값입니다.

scale 은 수평 단위에 대한 수직 단위의 비율입니다. 피트:경위도의 경우 scale=370400, 미터:경위도의 경우 scale=111120을 사용하십시오.

interpolate_nodata 가 참일 경우, 음영기복을 계산하기 전에 ST_InvDistWeight4ma 함수를 통해 입력 래스터에서 나온 NODATA 픽셀들의 값을 보간할 것입니다.

[참고]

음영기복에 대해 더 자세히 알고 싶다면, How hillshade works 를 참조하십시오.

2.0.0 버전부터 사용할 수 있습니다.

개선 사항: 2.1.0 버전부터 ST_MapAlgebra()를 이용하며, 선택적인 interpolate_nodata 함수 파라미터가 추가됐습니다.

변경 사항: 2.1.0 미만 버전에서는 방위각 및 고도각이 라디안 단위였습니다. 2.1.0 버전부터 방위각과 고도각이 도 단위로 바뀌었습니다.

예시

Variant 1.

Code
WITH foo AS (
    SELECT ST_SetValues(ST_AddBand(ST_MakeEmptyRaster(5, 5, 0, 0, 1, -1, 0, 0, 0), 1, '32BF', 0, -9999),
        1, 1, 1, ARRAY[
            [1, 1, 1, 1, 1],
            [1, 2, 2, 2, 1],
            [1, 2, 3, 2, 1],
            [1, 2, 2, 2, 1],
            [1, 1, 1, 1, 1]
        ]::double precision[][]
    ) AS rast
)
SELECT
    ST_DumpValues(ST_HillShade(rast, 1, '32BF'))
FROM foo

                                                                                                                       st_dumpvalues
래스터 출력
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------
 (1,"{{NULL,NULL,NULL,NULL,NULL},{NULL,251.32763671875,220.749786376953,147.224319458008,NULL},{NULL,220.749786376953,180.312225341797,67.7497863769531,NULL},{NULL,147.224319458008,
67.7497863769531,43.1210060119629,NULL},{NULL,NULL,NULL,NULL,NULL}}")
(1 row)

Variant 2.

Complete example of tiles of a coverage.

Code
WITH foo AS (
    SELECT ST_Tile(ST_SetValues(ST_AddBand(ST_MakeEmptyRaster(6, 6, 0, 0, 1, -1, 0, 0, 0),
                1, '32BF', 0, -9999
            ),
            1, 1, 1, ARRAY[
                [1, 1, 1, 1, 1, 1],
                [1, 1, 1, 1, 2, 1],
                [1, 2, 2, 3, 3, 1],
                [1, 1, 3, 2, 1, 1],
                [1, 2, 2, 1, 2, 1],
                [1, 1, 1, 1, 1, 1]
            ]::double precision[]
        ),
        2, 2
    ) AS rast
)
SELECT
    t1.rast,
    ST_HillShade(ST_Union(t2.rast), 1, t1.rast)
FROM foo t1
CROSS JOIN foo t2
WHERE ST_Intersects(t1.rast, t2.rast)
GROUP BY t1.rast;
                    

제목

ST_Roughness — DEM의 계산된 "거칠기(roughness)"와 함께 래스터를 반환합니다.

요약

raster ST_Roughness(raster rast, integer nband, raster customextent, text pixeltype="32BF" , boolean interpolate_nodata=FALSE );

Description

관심 지역에 대해 최소값에서 최대값을 뺀 DEM의 "거칠기"를 계산합니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

Code
WITH foo AS (
    SELECT ST_SetValues(ST_AddBand(ST_MakeEmptyRaster(5, 5, 0, 0, 1, -1, 0, 0, 0), 1, '32BF', 0, -9999),
        1, 1, 1, ARRAY[
            [1, 1, 2, 3, 3],
            [1, 2, 4, 15, 3],
            [2, 4, 10, 7, 5],
            [3, 5, 7, 6, 4],
            [3, 3, 5, 4, 4]
        ]::double precision[][]
    ) AS rast
)
SELECT ST_Value(ST_Roughness(rast, 1, '32BF'), 3, 3) AS roughness
FROM foo;
래스터 출력
13

제목

ST_Slope — 표고 래스터 밴드의 경사(기본 단위는 도)를 반환합니다. 지형을 분석하는 데 유용합니다.

요약

raster ST_Slope(raster rast, integer nband=1, text pixeltype=32BF, text units=DEGREES, double precision scale=1.0, boolean interpolate_nodata=FALSE);

raster ST_Slope(raster rast, integer nband, raster customextent, text pixeltype=32BF, text units=DEGREES, double precision scale=1.0, boolean interpolate_nodata=FALSE);

Description

표고 래스터 밴드의 경사(기본 단위는 도)를 반환합니다. 맵 대수를 활용해서 이웃 픽셀들에 경사 방정식을 적용합니다.

units 는 경사의 단위를 의미합니다. RADIANS, DEGREES(기본값), PERCENT를 쓸 수 있습니다.

scale 은 수평 단위에 대한 수직 단위의 비율입니다. 피트:경위도의 경우 scale=370400, 미터:경위도의 경우 scale=111120을 사용하십시오.

interpolate_nodata 가 참일 경우, 지표면 경사를 계산하기 전에 ST_InvDistWeight4ma 함수를 통해 입력 래스터에서 나온 NODATA 픽셀들의 값을 보간할 것입니다.

[참고]

경사(slope), 향(aspect), 음영기복(hillshade)에 대한 자세한 내용을 알고 싶다면, ESRI - How hillshade worksERDAS Field Guide - Slope Images 를 참조하십시오.

2.0.0 버전부터 사용할 수 있습니다.

개선 사항: 2.1.0 버전부터 ST_MapAlgebra()를 이용하며, 선택적인 units, scale, interpolate_nodata 함수 파라미터가 추가됐습니다.

변경 사항: 2.1.0 미만 버전에서는 반환되는 값이 라디안 단위였습니다. 2.1.0 버전부터 반환되는 값의 기본 단위가 도로 바뀌었습니다.

예시

Variant 1.

Code
WITH foo AS (
    SELECT ST_SetValues(ST_AddBand(ST_MakeEmptyRaster(5, 5, 0, 0, 1, -1, 0, 0, 0), 1, '32BF', 0, -9999),
        1, 1, 1, ARRAY[
            [1, 1, 1, 1, 1],
            [1, 2, 2, 2, 1],
            [1, 2, 3, 2, 1],
            [1, 2, 2, 2, 1],
            [1, 1, 1, 1, 1]
        ]::double precision[][]
    ) AS rast
)
SELECT
    ST_DumpValues(ST_Slope(rast, 1, '32BF'))
FROM foo

                            st_dumpvalues
래스터 출력
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------
 (1,"{{10.0249881744385,21.5681285858154,26.5650520324707,21.5681285858154,10.0249881744385},{21.5681285858154,35.2643890380859,36.8698959350586,35.2643890380859,21.5681285858154},
{26.5650520324707,36.8698959350586,0,36.8698959350586,26.5650520324707},{21.5681285858154,35.2643890380859,36.8698959350586,35.2643890380859,21.5681285858154},{10.0249881744385,21.
5681285858154,26.5650520324707,21.5681285858154,10.0249881744385}}")
(1 row)

Variant 2.

Complete example of tiles of a coverage.

Code
WITH foo AS (
    SELECT ST_Tile(ST_SetValues(ST_AddBand(ST_MakeEmptyRaster(6, 6, 0, 0, 1, -1, 0, 0, 0),
                1, '32BF', 0, -9999
            ),
            1, 1, 1, ARRAY[
                [1, 1, 1, 1, 1, 1],
                [1, 1, 1, 1, 2, 1],
                [1, 2, 2, 3, 3, 1],
                [1, 1, 3, 2, 1, 1],
                [1, 2, 2, 1, 2, 1],
                [1, 1, 1, 1, 1, 1]
            ]::double precision[]
        ),
        2, 2
    ) AS rast
)
SELECT
    t1.rast,
    ST_Slope(ST_Union(t2.rast), 1, t1.rast)
FROM foo t1
CROSS JOIN foo t2
WHERE ST_Intersects(t1.rast, t2.rast)
GROUP BY t1.rast;
                    

제목

ST_TPI — 계산된 지형위치지수(Topographic Position Index)와 함께 래스터를 반환합니다.

요약

raster ST_TPI(raster rast, integer nband, raster customextent, text pixeltype="32BF" , boolean interpolate_nodata=FALSE );

Description

Calculates the Topographic Position Index, which is defined as the focal mean with radius of one minus the center cell.

[참고]

이 함수는 1 반경 중심 평균(focalmean radius of one)만을 지원합니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

Code
WITH foo AS (
    SELECT ST_SetValues(ST_AddBand(ST_MakeEmptyRaster(5, 5, 0, 0, 1, -1, 0, 0, 0), 1, '32BF', 0, -9999),
        1, 1, 1, ARRAY[
            [1, 1, 2, 3, 3],
            [1, 2, 4, 15, 3],
            [2, 4, 10, 7, 5],
            [3, 5, 7, 6, 4],
            [3, 3, 5, 4, 4]
        ]::double precision[][]
    ) AS rast
)
SELECT ST_Value(ST_TPI(rast, 1, '32BF'), 3, 3) AS tpi
FROM foo;
래스터 출력
3.75

제목

ST_TRI — 계산된 지형험준도지수(Terrain Ruggedness Index)와 함께 래스터를 반환합니다.

요약

raster ST_TRI(raster rast, integer nband, raster customextent, text pixeltype="32BF" , boolean interpolate_nodata=FALSE );

Description

중심 픽셀과 그 이웃을 비교해서 그 차의 절대값의 평균으로 지형험준도지수(Terrain Ruggedness Index)를 계산합니다.

[참고]

이 함수는 1 반경 중심 평균(focalmean radius of one)만을 지원합니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

Code
WITH foo AS (
    SELECT ST_SetValues(ST_AddBand(ST_MakeEmptyRaster(5, 5, 0, 0, 1, -1, 0, 0, 0), 1, '32BF', 0, -9999),
        1, 1, 1, ARRAY[
            [1, 1, 2, 3, 3],
            [1, 2, 4, 15, 3],
            [2, 4, 10, 7, 5],
            [3, 5, 7, 6, 4],
            [3, 3, 5, 4, 4]
        ]::double precision[][]
    ) AS rast
)
SELECT ST_Value(ST_TRI(rast, 1, '32BF'), 3, 3) AS tri
FROM foo;
래스터 출력
5

제목

ST_InterpolateRaster — Interpolates a gridded surface based on an input set of 3-d points, using the X- and Y-values to position the points on the grid and the Z-value of the points as the surface elevation.

요약

raster ST_InterpolateRaster(geometry input_points, text algorithm_options, raster template, integer template_band_num=1);

Description

Interpolates a gridded surface based on an input set of 3-d points, using the X- and Y-values to position the points on the grid and the Z-value of the points as the surface elevation. There are five interpolation algorithms available: inverse distance, inverse distance nearest-neighbor, moving average, nearest neighbor, and linear interpolation. See the gdal_grid documentation for more details on the algorithms and their parameters. For more information on how interpolations are calculated, see the GDAL grid tutorial.

Input parameters are:

input_points

The points to drive the interpolation. Any geometry with Z-values is acceptable, all points in the input will be used.

algorithm_options

A string defining the algorithm and algorithm options, in the format used by gdal_grid. For example, for an inverse-distance interpolation with a smoothing of 2, you would use "invdist:smoothing=2.0"

template

A raster template to drive the geometry of the output raster. The width, height, pixel size, spatial extent and pixel type will be read from this template.

template_band_num

By default the first band in the template raster is used to drive the output raster, but that can be adjusted with this parameter.

Availability: 3.2.0

예시

Code
SELECT ST_InterpolateRaster('MULTIPOINT(10.5 9.5 1000,11.5 8.5 1000,10.5 8.5 500,11.5 9.5 500)'::geometry,
    'invdist:smoothing:2.0',
    ST_AddBand(ST_MakeEmptyRaster(200, 400, 10, 10, 0.01, -0.005, 0, 0), '16BSI')
)

참고

ST_Contour


제목

ST_Contour — Generates a set of vector contours from the provided raster band, using the GDAL contouring algorithm.

요약

setof record ST_Contour(raster rast, integer bandnumber=1, double precision level_interval=100.0, double precision level_base=0.0, double precision[] fixed_levels=ARRAY[], boolean polygonize=false);

Description

Generates a set of vector contours from the provided raster band, using the GDAL contouring algorithm.

When the fixed_levels parameter is a non-empty array, the level_interval and level_base parameters are ignored.

Input parameters are:

rast

The raster to generate the contour of

bandnumber

The band to generate the contour of

level_interval

The elevation interval between contours generated

level_base

The "base" relative to which contour intervals are applied, this is normally zero, but could be different. To generate 10m contours at 5, 15, 25, ... the LEVEL_BASE would be 5.

fixed_levels

The elevation interval between contours generated

polygonize

If true, contour polygons will be created, rather than polygon lines.

Return values are a set of records with the following attributes:

geom

The geometry of the contour line.

id

A unique identifier given to the contour line by GDAL.

value

The raster value the line represents. For an elevation DEM input, this would be the elevation of the output contour.

Availability: 3.2.0

예시

Code
WITH c AS (
SELECT (ST_Contour(rast, 1, fixed_levels => ARRAY[100.0, 200.0, 300.0])).*
FROM dem_grid WHERE rid = 1
)
SELECT geom, id, value
FROM c;

11.15. 래스터를 도형으로

  • Box3D — 래스터를 둘러싼 상자의 BOX3D 표현식을 반환합니다.
  • ST_ConvexHull — BandNoDataValue와 일치하는 픽셀 값을 포함한, 래스터의 볼록 껍질 도형을 반환합니다. 정규 형상 및 기울어지지 않은 래스터의 경우, ST_Envelope와 동일한 결과물을 출력하므로 비정규 형상 또는 기울어진 래스터에 대해서만 쓸모가 있습니다.
  • ST_DumpAsPolygons — 입력 래스터 밴드로부터 geomval(geom, val) 행들의 집합을 반환합니다. 밴드 번호를 설정하지 않을 경우 기본적으로 밴드 1로 가정합니다.
  • ST_Envelope — 래스터 범위의 폴리곤 표현식을 반환합니다.
  • ST_MinConvexHull — 래스터의 NODATA 픽셀을 제외한 볼록 껍질 도형을 반환합니다.
  • ST_Polygon — NODATA 값이 아닌 픽셀 값을 가진 픽셀들을 통합해서 형성된 멀티폴리곤 도형을 반환합니다.
  • ST_IntersectionFractions — Calculates the fraction of each raster cell that is covered by a given geometry.

제목

Box3D — 래스터를 둘러싼 상자의 BOX3D 표현식을 반환합니다.

요약

box3d Box3D(raster rast);

Description

래스터의 범위를 표현하는 상자를 반환합니다.

경계 상자의 꼭짓점 포인트들((MINX, MINY), (MAXX, MAXY))이 폴리곤을 정의합니다.

변경 사항: 2.0.0 미만 버전에서는 BOX3D 대신 BOX2D를 이용했습니다. BOX2D가 지원이 끝난 유형이기 때문에, 2.0.0 버전에서 BOX3D로 바뀌었습니다.

예시

Code
SELECT
    rid,
    Box3D(rast) AS rastbox
FROM dummy_rast;
래스터 출력
rid |        rastbox
----+-------------------------------------------------
1   | BOX3D(0.5 0.5 0,20.5 60.5 0)
2   | BOX3D(3427927.75 5793243.5 0,3427928 5793244 0)

참고

ST_Envelope


제목

ST_ConvexHull — BandNoDataValue와 일치하는 픽셀 값을 포함한, 래스터의 볼록 껍질 도형을 반환합니다. 정규 형상 및 기울어지지 않은 래스터의 경우, ST_Envelope와 동일한 결과물을 출력하므로 비정규 형상 또는 기울어진 래스터에 대해서만 쓸모가 있습니다.

요약

geometry ST_ConvexHull(raster rast);

Description

NoDataBandValue 밴드 픽셀을 포함한, 래스터의 볼록 껍질 도형을 반환합니다. 정규 형상 및 기울어지지 않은 래스터의 경우, ST_Envelope와 거의 동일한 결과물을 출력하므로 비정규 형상 또는 기울어진 래스터에 대해서만 쓸모가 있습니다.

[참고]

ST_Envelope 함수는 좌표를 버림(floor)하기 때문에 래스터 주위에 버퍼를 약간 주게 됩니다. 따라서 버림을 하지 않는 ST_ConvexHull 함수와는 약간 다른 결과를 냅니다.

예시

See doc/development/internals/raster-affine.md for the scale, skew, and rotation terms that make the convex hull and envelope differ for skewed rasters.

For regular non-skewed rasters, the envelope and convex hull are more or less the same.

Code
SELECT ST_ConvexHull(rast) As convhull, ST_Envelope(rast) As env
FROM dummy_rast WHERE rid=1;
래스터 출력
convhull                        |                env
--------------------------------------------------------+------------------------------------
 POLYGON((0.5 0.5,20.5 0.5,20.5 60.5,0.5 60.5,0.5 0.5)) | POLYGON((0 0,20 0,20 60,0 60,0 0))

Now we skew the raster. Note how the convex hull and envelope are now different.

Code
SELECT ST_ConvexHull(rast) As convhull, ST_Envelope(rast) As env
FROM (SELECT ST_SetRotation(rast, 0.1, 0.1) As rast
    FROM dummy_rast WHERE rid=1) As foo;
래스터 출력
convhull                        |                env
--------------------------------------------------------+------------------------------------
 POLYGON((0.5 0.5,20.5 1.5,22.5 61.5,2.5 60.5,0.5 0.5)) | POLYGON((0 0,22 0,22 61,0 61,0 0))

제목

ST_DumpAsPolygons — 입력 래스터 밴드로부터 geomval(geom, val) 행들의 집합을 반환합니다. 밴드 번호를 설정하지 않을 경우 기본적으로 밴드 1로 가정합니다.

요약

setof geomval ST_DumpAsPolygons(raster rast, integer band_num=1, boolean exclude_nodata_value=TRUE);

Description

이 함수는 집합 반환 함수(SRF; Set-Returning Function)입니다. 도형(geom)과 픽셀 밴드 값(val)으로 이루어진 geomval 행들의 집합을 반환합니다. 각 폴리곤은 해당 밴드에서 val이 표시하는 값과 동일한 픽셀 값을 가진 모든 픽셀들을 통합한 것입니다.

ST_DumpAsPolygon은 래스터를 폴리곤화하는 데 유용합니다. 새 행들을 생성한다는 점에서 GROUP BY의 역함수라고 할 수 있습니다. 예를 들어 단일 래스터를 복수의 폴리곤/멀티폴리곤으로 확장하는 데 이 함수를 쓸 수 있습니다.

Changed 3.3.0, validation and fixing is disabled to improve performance. May result invalid geometries.

Changed 3.7.0, the polygonization honours PostgreSQL interrupts so cancellations and statement timeouts halt processing promptly.

GDAL 1.7 이상 버전이 필요합니다.

[참고]

If there is a no data value set for a band, pixels with that value will not be returned except in the case of exclude_nodata_value=false.

[참고]

래스터 안에 있는 해당 값을 가진 픽셀들의 개수에만 관심이 있다면, ST_ValueCount 함수가 더 빠릅니다.

[참고]

이 함수는 픽셀 값과 상관없이 각 픽셀에 대해 도형 하나를 반환하는 ST_PixelAsPolygons 함수와 다릅니다.

예시

This syntax uses a LATERAL join.

Code
SELECT val,geom As geomwkt
FROM (
SELECT dp.*
FROM dummy_rast, LATERAL ST_DumpAsPolygons(rast) AS dp
WHERE rid = 2
) As foo
WHERE val BETWEEN 249 and 251
ORDER BY val;
래스터 출력
val |                                                       geomwkt
-----+--------------------------------------------------------------------------
 249 | POLYGON((3427927.95 5793243.95,3427927.95 5793243.85,3427928 5793243.85,
        3427928 5793243.95,3427927.95 5793243.95))
 250 | POLYGON((3427927.75 5793243.9,3427927.75 5793243.85,3427927.8 5793243.85,
        3427927.8 5793243.9,3427927.75 5793243.9))
 250 | POLYGON((3427927.8 5793243.8,3427927.8 5793243.75,3427927.85 5793243.75,
        3427927.85 5793243.8, 3427927.8 5793243.8))
 251 | POLYGON((3427927.75 5793243.85,3427927.75 5793243.8,3427927.8 5793243.8,
        3427927.8 5793243.85,3427927.75 5793243.85))

제목

ST_Envelope — 래스터 범위의 폴리곤 표현식을 반환합니다.

요약

geometry ST_Envelope(raster rast);

Description

래스터 범위의 폴리곤 표현식을 SRID가 정의하는 공간 좌표 단위로 반환합니다. 여기에서 폴리곤 표현식이란 폴리곤으로 표현된 float8 형 최소치 경계 상자입니다.

해당 폴리곤은 경계 상자의 꼭짓점 포인트들로 정의됩니다((MINX, MINY), (MINX, MAXY), (MAXX, MAXY), (MAXX, MINY), (MINX, MINY)).

예시

Code
SELECT rid, ST_Envelope(rast) As envgeomwkt
FROM dummy_rast;
래스터 출력
rid |                                         envgeomwkt
-----+--------------------------------------------------------------------
   1 | POLYGON((0 0,20 0,20 60,0 60,0 0))
   2 | POLYGON((3427927 5793243,3427928 5793243,
        3427928 5793244,3427927 5793244, 3427927 5793243))

제목

ST_MinConvexHull — 래스터의 NODATA 픽셀을 제외한 볼록 껍질 도형을 반환합니다.

요약

geometry ST_MinConvexHull(raster rast, integer nband=NULL);

Description

래스터의 NODATA 픽셀을 제외한 볼록 껍질 도형을 반환합니다. nband 가 NULL일 경우, 래스터의 모든 밴드를 처리합니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

Code
WITH foo AS (
    SELECT
        ST_SetValues(ST_SetValues(ST_AddBand(ST_AddBand(ST_MakeEmptyRaster(9, 9, 0, 0, 1, -1, 0, 0, 0), 1, '8BUI', 0, 0), 2, '8BUI', 1, 0),
                1, 1, 1,
                ARRAY[
                    [0, 0, 0, 0, 0, 0, 0, 0, 0],
                    [0, 0, 0, 0, 0, 0, 0, 0, 0],
                    [0, 0, 0, 0, 0, 0, 0, 0, 0],
                    [0, 0, 0, 1, 0, 0, 0, 0, 1],
                    [0, 0, 0, 1, 1, 0, 0, 0, 0],
                    [0, 0, 0, 1, 0, 0, 0, 0, 0],
                    [0, 0, 0, 0, 0, 0, 0, 0, 0],
                    [0, 0, 0, 0, 0, 0, 0, 0, 0],
                    [0, 0, 0, 0, 0, 0, 0, 0, 0]
                ]::double precision[][]
            ),
            2, 1, 1,
            ARRAY[
                [0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0],
                [1, 0, 0, 0, 0, 1, 0, 0, 0],
                [0, 0, 0, 0, 1, 1, 0, 0, 0],
                [0, 0, 0, 0, 0, 1, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 1, 0, 0, 0, 0, 0, 0]
            ]::double precision[][]
        ) AS rast
)
SELECT title, geom AS geom
FROM foo
CROSS JOIN LATERAL (VALUES
    ('raster hull', ST_ConvexHull(rast)),
    ('all bands', ST_MinConvexHull(rast)),
    ('band 1', ST_MinConvexHull(rast, 1)),
    ('band 2', ST_MinConvexHull(rast, 2))
) AS variants(title, geom);
래스터 출력
title    |                 geom
-------------+---------------------------------------
 raster hull | POLYGON((0 0,9 0,9 -9,0 -9,0 0))
 all bands   | POLYGON((0 -3,9 -3,9 -9,0 -9,0 -3))
 band 1      | POLYGON((3 -3,9 -3,9 -6,3 -6,3 -3))
 band 2      | POLYGON((0 -3,6 -3,6 -9,0 -9,0 -3))
Figure
Geometry figure for visual-rt-st-minconvexhull-01

제목

ST_Polygon — NODATA 값이 아닌 픽셀 값을 가진 픽셀들을 통합해서 형성된 멀티폴리곤 도형을 반환합니다.

요약

geometry ST_Polygon(raster rast, integer band_num=1);

Description

Changed 3.3.0, validation and fixing is disabled to improve performance. May result invalid geometries.

0.1.6 버전부터 사용할 수 있습니다. GDAL 1.7 이상 버전이 필요합니다.

개선 사항: 2.1.0 버전부터 속도가 향상됐습니다(완전히 C언어 기반으로 변경했습니다). 반환되는 멀티폴리곤이 유효한 도형인지 확인합니다.

변경 사항: 2.1.0 미만 버전에서 종종 폴리곤을 반환하곤 했던 것을, 언제나 멀티폴리곤을 반환하도록 바꿨습니다.

예시

Compare polygonization of every pixel with polygonization after zero is assigned as the NODATA value. The latter preserves the gap formed by zero-valued cells.

Code
WITH source AS (
    SELECT ST_SetValues(
        ST_AddBand(
            ST_MakeEmptyRaster(4, 4, 0, 4, 1, -1, 0, 0, 0),
            1, '8BUI', 1, NULL
        ),
        1, 1, 1,
        ARRAY[
            [1, 1, 1, 1],
            [1, 0, 0, 1],
            [1, 1, 0, 1],
            [1, 1, 1, 1]
        ]::double precision[][]
    ) AS rast
), variants AS (
    SELECT 'all pixels' AS title, ST_Polygon(rast) AS geom
    FROM source
    UNION ALL
    SELECT
        'zero excluded',
        ST_Polygon(ST_SetBandNoDataValue(rast, 1, 0))
    FROM source
)
SELECT title, geom AS geom
FROM variants
ORDER BY CASE title
    WHEN 'all pixels' THEN 1
    ELSE 2
END;
래스터 출력
title         | geom
---------------+----------------------------------------------------------------------
 all pixels    | MULTIPOLYGON(((0 4,4 4,4 0,0 0,0 4)))
 zero excluded | MULTIPOLYGON(((0 4,0 0,4 0,4 4,0 4),(1 3,3 3,3 1,2 1,2 2,1 2,1 3)))
(2 rows)
Figure
Geometry figure for visual-rt-st-polygon-01

제목

ST_IntersectionFractions — Calculates the fraction of each raster cell that is covered by a given geometry.

요약

raster ST_IntersectionFractions(raster rast, geometry geom);

Description

Calculates the fraction of each raster cell that is covered by a given geometry. The first argument is a raster, which defines the grid geometry to use for the calculation. The extent and cell size are read from the raster parameter. The second argument is a geometry, which is overlaid with the grid, and each grid populated based on overlaying the geometry on the grid. For polygons, the value returned for each cell is the proportion of its area that is covered by the geometry. For linestrings, the value returned for each cell is the length contained in the cell.

Availability: 3.6.0 Requires GEOS 3.14 or higher.

예시

This rotated square polygon covers half of each cell in the raster.

Code
CREATE TABLE raster_proportions_rast (
    name text,
    rast raster
);

INSERT INTO raster_proportions_rast (name, rast) VALUES (
  '2x2 raster covering 0,0 to 10,10',
  ST_MakeEmptyRaster(2, 2, -- raster width/height in pixels
    0, 10, -- upper-left corner x/y coordinates
    5, -5, -- pixel width/height in ground units
    0, 0, -- skew x/y
    0        -- SRID
  ));

SELECT name, ST_DumpValues(
    ST_IntersectionFractions(
        rast,
        'POLYGON((5 0,0 5,5 10,10 5,5 0))'::geometry),
    1)
FROM raster_proportions_rast;
래스터 출력
2x2 raster covering 0,0 to 10,10
---------------------------------
 {{0.5,0.5},{0.5,0.5}}

11.16. 래스터 연산자

  • && — A의 경계 상자와 B의 경계 상자가 교차하는 경우 TRUE 를 반환합니다.
  • &< — A의 경계 상자가 B의 경계 상자 왼쪽에 있을 경우 TRUE 를 반환합니다.
  • &> — A의 경계 상자가 B의 경계 상자 오른쪽에 있을 경우 TRUE 를 반환합니다.
  • = — A의 경계 상자와 B의 경계 상자가 동일할 경우 TRUE 를 반환합니다. 이중 정밀도 경계 상자를 이용합니다.
  • @ — B의 경계 상자가 A의 경계 상자를 담고 있을 경우 TRUE 를 반환합니다. 이중 정밀도 경계 상자를 이용합니다.
  • ~= — A의 경계 상자와 B의 경계 상자가 동일할 경우 TRUE 를 반환합니다.
  • ~ — A의 경계 상자가 B의 경계 상자를 담고 있을 경우 TRUE 를 반환합니다. 이중 정밀도 경계 상자를 이용합니다.

제목

&& — A의 경계 상자와 B의 경계 상자가 교차하는 경우 TRUE 를 반환합니다.

요약

boolean &&( raster A , raster B );

boolean &&( raster A , geometry B );

boolean &&( geometry B , raster A );

Description

&& 연산자는 래스터/도형 A의 경계 상자와 래스터/도형 B의 경계 상자가 교차하는 경우 TRUE 를 반환합니다.

[참고]

이 피연산자(operand)는 래스터에서 이용할 수도 있는 모든 인덱스를 활용할 것입니다.

2.0.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT A.rid As a_rid, B.rid As b_rid, A.rast && B.rast As intersect
FROM dummy_rast AS A CROSS JOIN dummy_rast AS B LIMIT 3;
래스터 출력
a_rid | b_rid | intersect
-------+-------+---------
     2 |     2 | t
     2 |     3 | f
     2 |     1 | f

제목

&< — A의 경계 상자가 B의 경계 상자 왼쪽에 있을 경우 TRUE 를 반환합니다.

요약

boolean &<( raster A , raster B );

Description

&< 연산자는 래스터 A의 경계 상자가 래스터 B의 경계 상자와 겹치거나 그 왼쪽에 있을 경우, 또는 더 정확히 말하자면 래스터 B의 경계 상자와 겹치거나 그 오른쪽에 있지 않을 경우, TRUE 를 반환합니다.

[참고]

이 피연산자(operand)는 래스터에서 이용할 수도 있는 모든 인덱스를 활용할 것입니다.

예시

Code
SELECT A.rid As a_rid, B.rid As b_rid, A.rast &< B.rast As overleft
 FROM dummy_rast AS A CROSS JOIN dummy_rast AS B;
래스터 출력
a_rid | b_rid | overleft
------+-------+----------
    2 |     2 | t
    2 |     3 | f
    2 |     1 | f
    3 |     2 | t
    3 |     3 | t
    3 |     1 | f
    1 |     2 | t
    1 |     3 | t
    1 |     1 | t

제목

&> — A의 경계 상자가 B의 경계 상자 오른쪽에 있을 경우 TRUE 를 반환합니다.

요약

boolean &>( raster A , raster B );

Description

&> 연산자는 래스터 A의 경계 상자가 래스터 B의 경계 상자와 겹치거나 그 오른쪽에 있을 경우, 또는 더 정확히 말하자면 래스터 B의 경계 상자와 겹치거나 그 왼쪽에 있지 않을 경우, TRUE 를 반환합니다.

[참고]

이 피연산자(operand)는 도형에서 이용할 수도 있는 모든 인덱스를 활용할 것입니다.

예시

Code
SELECT A.rid As a_rid, B.rid As b_rid, A.rast &
> B.rast As overright
 FROM dummy_rast AS A CROSS JOIN dummy_rast AS B;
래스터 출력
 a_rid | b_rid | overright
-------+-------+----------
     2 |     2 | t
     2 |     3 | t
     2 |     1 | t
     3 |     2 | f
     3 |     3 | t
     3 |     1 | f
     1 |     2 | f
     1 |     3 | t
     1 |     1 | t

제목

= — A의 경계 상자와 B의 경계 상자가 동일할 경우 TRUE 를 반환합니다. 이중 정밀도 경계 상자를 이용합니다.

요약

boolean =( raster A , raster B );

Description

= 연산자는 래스터 A의 경계 상자와 래스터 B의 경계 상자가 동일할 경우 TRUE 를 반환합니다. PostgreSQL은 래스터를 내부 정렬하고 비교하기 위해 도형에 대해 정의된 =, <, 및 > 연산자를 이용합니다(예: GROUP BY 또는 ORDER BY 절에서).

[경고]

이 피연산자(operand)는 래스터에 대해 이용할 수 있을지도 모르는 어떤 인덱스도 활용하지 않을 것입니다. 대신 ~= 함수를 이용하십시오. 이 연산자의 목적은 대부분 래스터 열로 그룹화(group by)하는 것입니다.

2.1.0 버전부터 사용할 수 있습니다.

참고

~=


제목

@ — B의 경계 상자가 A의 경계 상자를 담고 있을 경우 TRUE 를 반환합니다. 이중 정밀도 경계 상자를 이용합니다.

요약

boolean @( raster A , raster B );

boolean @( geometry A , raster B );

boolean @( raster B , geometry A );

Description

@ 연산자는 래스터/도형 B의 경계 상자가 래스터/도형 A의 경계 상자를 담고 있을 경우 TRUE 를 반환합니다.

[참고]

이 피연산자(operand)는 래스터에 있는 공간 인덱스를 활용할 것입니다.

2.0.0 버전부터 raster @ raster, raster @ geometry 를 사용할 수 있습니다.

2.0.5 버전부터 geometry @ raster 를 지원합니다.

참고

~


제목

~= — A의 경계 상자와 B의 경계 상자가 동일할 경우 TRUE 를 반환합니다.

요약

boolean ~=( raster A , raster B );

Description

~= 연산자는 래스터 A의 경계 상자와 래스터 B의 경계 상자가 동일할 경우 TRUE 를 반환합니다.

[참고]

이 피연산자(operand)는 래스터에서 이용할 수도 있는 모든 인덱스를 활용할 것입니다.

2.0.0 버전부터 사용할 수 있습니다.

예시

동일한 뭉치이지만 서로 다른 주제를 표현하는 단일 밴드 래스터의 집합 2개를 입력받아 다중 밴드 래스터를 생성하는 데 매우 유용합니다.

Code
SELECT ST_AddBand(prec.rast, alt.rast) As new_rast
FROM prec INNER JOIN alt ON (prec.rast ~= alt.rast);
        

참고

ST_AddBand, =


제목

~ — A의 경계 상자가 B의 경계 상자를 담고 있을 경우 TRUE 를 반환합니다. 이중 정밀도 경계 상자를 이용합니다.

요약

boolean ~( raster A , raster B );

boolean ~( geometry A , raster B );

boolean ~( raster B , geometry A );

Description

~ 연산자는 래스터/도형 A의 경계 상자가 래스터/도형 B의 경계 상자를 담고 있을 경우 TRUE 를 반환합니다.

[참고]

이 피연산자(operand)는 래스터에 있는 공간 인덱스를 활용할 것입니다.

2.0.0 버전부터 사용할 수 있습니다.

참고

@

11.17. 래스터 및 래스터 밴드의 공간 관계성

  • ST_Contains — 래스터 rastA 외부에 놓인 래스터 rastB의 포인트가 하나도 없고, 적어도 rastB 내부의 포인트 하나가 rastA의 내부에 있는 경우 참을 반환합니다.
  • ST_ContainsProperly — rastB가 rastA의 내부와 교차하지만 rastA의 경계선 또는 외부와 교차하지는 않을 경우 참을 반환합니다.
  • ST_Covers — 래스터 rastB의 어떤 포인트도 래스터 rastA 외부에 없을 경우 참을 반환합니다.
  • ST_CoveredBy — 래스터 rastA의 어떤 포인트도 래스터 rastB 외부에 없을 경우 참을 반환합니다.
  • ST_Disjoint — 래스터 rastA와 래스터 rastB가 공간적으로 교차하지 않을 경우 참을 반환합니다.
  • ST_Intersects — 래스터 rastA와 래스터 rastB가 공간적으로 교차할 경우 참을 반환합니다.
  • ST_Overlaps — 래스터 rastA와 래스터 rastB가 교차하지만 어느 한 쪽이 다른 한 쪽을 완전히 담고 있지는 않을 경우 참을 반환합니다.
  • ST_Touches — 래스터 rastA와 래스터 rastB가 최소한 포인트 한 개를 공유하지만, 내부가 교차하지는 않을 경우 TRUE 를 반환합니다.
  • ST_SameAlignment — 래스터들이 동일한 기울기, 축척, 공간 참조 시스템, 그리고 오프셋을 가지고 있을 경우 (픽셀이 다른 픽셀을 침범하지 않고 동일한 그리드에 놓일 수 있을 경우) 참을 반환하고, 그렇지 않을 경우 문제점을 설명하는 안내문과 함께 거짓을 반환합니다.
  • ST_NotSameAlignmentReason — 래스터들이 정렬돼 있는지 아닌지, 그리고 정렬되지 않았다면 그 이유를 설명하는 텍스트를 반환합니다.
  • ST_Within — 래스터 rastB 외부에 놓인 래스터 rastA의 포인트가 하나도 없고, 적어도 rastA 내부의 포인트 하나가 rastB의 내부에 있는 경우 참을 반환합니다.
  • ST_DWithin — 래스터 rastA와 래스터 rastB가 서로 설정된 거리 안에 있을 경우 참을 반환합니다.
  • ST_DFullyWithin — 래스터 rastA와 래스터 rastB가 완전히 서로 설정된 거리 안에 있을 경우 참을 반환합니다.

제목

ST_Contains — 래스터 rastA 외부에 놓인 래스터 rastB의 포인트가 하나도 없고, 적어도 rastB 내부의 포인트 하나가 rastA의 내부에 있는 경우 참을 반환합니다.

요약

boolean ST_Contains( raster rastA , integer nbandA , raster rastB , integer nbandB );

boolean ST_Contains( raster rastA , raster rastB );

Description

래스터 rastA 외부에 놓인 래스터 rastB의 포인트가 하나도 없고, 적어도 rastB 내부의 포인트 하나가 rastA의 내부에 있을 경우에만 rastA가 rastB를 담고 있다고 합니다. 밴드 번호를 설정하지 않거나 또는 NULL로 설정할 경우, 확인 작업중 래스터의 볼록 껍질만 고려합니다. 밴드 번호를 설정할 경우, 확인 작업중 값을 가진 (NODATA가 아닌) 픽셀들만 고려합니다.

[참고]

이 함수는 래스터에서 이용할 수도 있는 모든 인덱스를 활용할 것입니다.

[참고]

래스터와 도형의 공간 관계성을 확인하려면, ST_Contains(ST_Polygon(raster), geometry) 또는 ST_Contains(geometry, ST_Polygon(raster))처럼 래스터에 ST_Polygon 함수를 이용하십시오.

[참고]

ST_Contains()는 ST_Within()의 역함수입니다. 따라서, ST_Contains(rastA, rastB)의 결과와 ST_Within(rastB, rastA)의 결과는 동일할 것입니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

Specified band numbers.

Code
SELECT r1.rid, r2.rid, ST_Contains(r1.rast, 1, r2.rast, 1) FROM dummy_rast r1 CROSS JOIN dummy_rast r2 WHERE r1.rid = 1;
래스터 출력
NOTICE:  The first raster provided has no bands
 rid | rid | st_contains
-----+-----+-------------
   1 |   1 |
   1 |   2 | f

No band numbers specified.

Code
SELECT r1.rid, r2.rid, ST_Contains(r1.rast, r2.rast) FROM dummy_rast r1 CROSS JOIN dummy_rast r2 WHERE r1.rid = 1;
래스터 출력
rid | rid | st_contains
-----+-----+-------------
   1 |   1 | t
   1 |   2 | f

제목

ST_ContainsProperly — rastB가 rastA의 내부와 교차하지만 rastA의 경계선 또는 외부와 교차하지는 않을 경우 참을 반환합니다.

요약

boolean ST_ContainsProperly( raster rastA , integer nbandA , raster rastB , integer nbandB );

boolean ST_ContainsProperly( raster rastA , raster rastB );

Description

래스터 rastB가 래스터 rastA의 내부와 교차하지만 rastA의 경계선 또는 외부와 교차하지는 않을 경우 rastA가 rastB를 제대로 담고 있다고 합니다. 밴드 번호를 설정하지 않거나 또는 NULL로 설정할 경우, 확인 작업중 래스터의 볼록 껍질만 고려합니다. 밴드 번호를 설정할 경우, 확인 작업중 값을 가진 (NODATA가 아닌) 픽셀들만 고려합니다.

래스터 rastA는 자기 자신을 제대로 담고 있지는 않지만, 자기 자신을 담고 있긴 합니다.

[참고]

이 함수는 래스터에서 이용할 수도 있는 모든 인덱스를 활용할 것입니다.

[참고]

래스터와 도형의 공간 관계성을 확인하려면, ST_ContainsProperly(ST_Polygon(raster), geometry) 또는 ST_ContainsProperly(geometry, ST_Polygon(raster))처럼 래스터에 ST_Polygon 함수를 이용하십시오.

2.1.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT r1.rid, r2.rid, ST_ContainsProperly(r1.rast, 1, r2.rast, 1) FROM dummy_rast r1 CROSS JOIN dummy_rast r2 WHERE r1.rid = 2;
래스터 출력
rid | rid | st_containsproperly
-----+-----+---------------------
   2 |   1 | f
   2 |   2 | f

제목

ST_Covers — 래스터 rastB의 어떤 포인트도 래스터 rastA 외부에 없을 경우 참을 반환합니다.

요약

boolean ST_Covers( raster rastA , integer nbandA , raster rastB , integer nbandB );

boolean ST_Covers( raster rastA , raster rastB );

Description

래스터 rastB의 어떤 포인트도 래스터 rastA 외부에 없을 경우 rastA가 rastB를 커버한다고 합니다. 밴드 번호를 설정하지 않거나 또는 NULL로 설정할 경우, 확인 작업중 래스터의 볼록 껍질만 고려합니다. 밴드 번호를 설정할 경우, 확인 작업중 값을 가진 (NODATA가 아닌) 픽셀들만 고려합니다.

[참고]

이 함수는 래스터에서 이용할 수도 있는 모든 인덱스를 활용할 것입니다.

[참고]

래스터와 도형의 공간 관계성을 확인하려면, ST_Covers(ST_Polygon(raster), geometry) 또는 ST_Covers(geometry, ST_Polygon(raster))처럼 래스터에 ST_Polygon 함수를 이용하십시오.

2.1.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT r1.rid, r2.rid, ST_Covers(r1.rast, 1, r2.rast, 1) FROM dummy_rast r1 CROSS JOIN dummy_rast r2 WHERE r1.rid = 2;
래스터 출력
rid | rid | st_covers
-----+-----+-----------
   2 |   1 | f
   2 |   2 | t

제목

ST_CoveredBy — 래스터 rastA의 어떤 포인트도 래스터 rastB 외부에 없을 경우 참을 반환합니다.

요약

boolean ST_CoveredBy( raster rastA , integer nbandA , raster rastB , integer nbandB );

boolean ST_CoveredBy( raster rastA , raster rastB );

Description

래스터 rastA의 어떤 포인트도 래스터 rastB 외부에 없을 경우 rastA가 rastB에 의해 커버된다고 합니다. 밴드 번호를 설정하지 않거나 또는 NULL로 설정할 경우, 확인 작업중 래스터의 볼록 껍질만 고려합니다. 밴드 번호를 설정할 경우, 확인 작업중 값을 가진 (NODATA가 아닌) 픽셀들만 고려합니다.

[참고]

이 함수는 래스터에서 이용할 수도 있는 모든 인덱스를 활용할 것입니다.

[참고]

래스터와 도형의 공간 관계성을 확인하려면, ST_CoveredBy(ST_Polygon(raster), geometry) 또는 ST_CoveredBy(geometry, ST_Polygon(raster))처럼 래스터에 ST_Polygon 함수를 이용하십시오.

2.1.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT r1.rid, r2.rid, ST_CoveredBy(r1.rast, 1, r2.rast, 1) FROM dummy_rast r1 CROSS JOIN dummy_rast r2 WHERE r1.rid = 2;
래스터 출력
rid | rid | st_coveredby
-----+-----+--------------
   2 |   1 | f
   2 |   2 | t

제목

ST_Disjoint — 래스터 rastA와 래스터 rastB가 공간적으로 교차하지 않을 경우 참을 반환합니다.

요약

boolean ST_Disjoint( raster rastA , integer nbandA , raster rastB , integer nbandB );

boolean ST_Disjoint( raster rastA , raster rastB );

Description

래스터 rastA와 래스터 rastB가 어떤 공간도 함께 공유하지 않을 경우 rastA와 rastB가 분리됐다고 합니다. 밴드 번호를 설정하지 않거나 또는 NULL로 설정할 경우, 확인 작업중 래스터의 볼록 껍질만 고려합니다. 밴드 번호를 설정할 경우, 확인 작업중 값을 가진 (NODATA가 아닌) 픽셀들만 고려합니다.

[참고]

이 함수는 어떤 인덱스도 활용하지 않습니다.

[참고]

래스터와 도형의 공간 관계성을 확인하려면, ST_Disjoint(ST_Polygon(raster), geometry)처럼 래스터에 ST_Polygon 함수를 이용하십시오.

2.1.0 버전부터 사용할 수 있습니다.

예시

Rid = 1 has no bands, hence the NOTICE and the NULL value for st_disjoint.

Code
SELECT r1.rid, r2.rid, ST_Disjoint(r1.rast, 1, r2.rast, 1) FROM dummy_rast r1 CROSS JOIN dummy_rast r2 WHERE r1.rid = 2;
래스터 출력
NOTICE:  The second raster provided has no bands
 rid | rid | st_disjoint
-----+-----+-------------
   2 |   1 |
   2 |   2 | f

This time, without specifying band numbers.

Code
SELECT r1.rid, r2.rid, ST_Disjoint(r1.rast, r2.rast) FROM dummy_rast r1 CROSS JOIN dummy_rast r2 WHERE r1.rid = 2;
래스터 출력
rid | rid | st_disjoint
-----+-----+-------------
   2 |   1 | t
   2 |   2 | f

제목

ST_Intersects — 래스터 rastA와 래스터 rastB가 공간적으로 교차할 경우 참을 반환합니다.

요약

boolean ST_Intersects( raster rastA , integer nbandA , raster rastB , integer nbandB );

boolean ST_Intersects( raster rastA , raster rastB );

boolean ST_Intersects( raster rast , integer nband , geometry geommin );

boolean ST_Intersects( raster rast , geometry geommin , integer nband=NULL );

boolean ST_Intersects( geometry geommin , raster rast , integer nband=NULL );

Description

래스터 rastA와 래스터 rastB가 공간적으로 교차할 경우 참을 반환합니다. 밴드 번호를 설정하지 않거나 또는 NULL로 설정할 경우, 확인 작업중 래스터의 볼록 껍질만 고려합니다. 밴드 번호를 설정할 경우, 확인 작업중 값을 가진 (NODATA가 아닌) 픽셀들만 고려합니다.

[참고]

이 함수는 래스터에서 이용할 수도 있는 모든 인덱스를 활용할 것입니다.

개선 사항: 2.0.0 버전부터 래스터/래스터 교차를 지원합니다.

[주의]

변경 사항: 2.1.0 버전부터 ST_Intersects(geometry, raster)의 습성과 일치시키기 위해 ST_Intersects(raster, geometry) 변종의 습성을 바꿨습니다.

예시

Different bands of same raster.

Code
SELECT ST_Intersects(rast, 2, rast, 3) FROM dummy_rast WHERE rid = 2;
래스터 출력
t

제목

ST_Overlaps — 래스터 rastA와 래스터 rastB가 교차하지만 어느 한 쪽이 다른 한 쪽을 완전히 담고 있지는 않을 경우 참을 반환합니다.

요약

boolean ST_Overlaps( raster rastA , integer nbandA , raster rastB , integer nbandB );

boolean ST_Overlaps( raster rastA , raster rastB );

Description

래스터 rastA와 래스터 rastB가 공간적으로 중첩할 경우 참을 반환합니다. 다시 말해 rastA와 rastB가 교차하지만 어느 한 쪽이 다른 한 쪽을 완전히 담고 있지는 않다는 뜻입니다. 밴드 번호를 설정하지 않거나 또는 NULL로 설정할 경우, 확인 작업중 래스터의 볼록 껍질만 고려합니다. 밴드 번호를 설정할 경우, 확인 작업중 값을 가진 (NODATA가 아닌) 픽셀들만 고려합니다.

[참고]

이 함수는 래스터에서 이용할 수도 있는 모든 인덱스를 활용할 것입니다.

[참고]

래스터와 도형의 공간 관계성을 확인하려면, ST_Overlaps(ST_Polygon(raster), geometry)처럼 래스터에 ST_Polygon 함수를 이용하십시오.

2.1.0 버전부터 사용할 수 있습니다.

예시

Comparing different bands of same raster.

Code
SELECT ST_Overlaps(rast, 1, rast, 2) FROM dummy_rast WHERE rid = 2;
래스터 출력
f

제목

ST_Touches — 래스터 rastA와 래스터 rastB가 최소한 포인트 한 개를 공유하지만, 내부가 교차하지는 않을 경우 TRUE 를 반환합니다.

요약

boolean ST_Touches( raster rastA , integer nbandA , raster rastB , integer nbandB );

boolean ST_Touches( raster rastA , raster rastB );

Description

래스터 rastA와 래스터 rastB가 공간적으로 접촉할 경우 참을 반환합니다. 다시 말해 rastA와 래스터 rastB가 최소한 포인트 한 개를 공유하지만, 내부가 교차하지는 않는다는 뜻입니다. 밴드 번호를 설정하지 않거나 또는 NULL로 설정할 경우, 확인 작업중 래스터의 볼록 껍질만 고려합니다. 밴드 번호를 설정할 경우, 확인 작업중 값을 가진 (NODATA가 아닌) 픽셀들만 고려합니다.

[참고]

이 함수는 래스터에서 이용할 수도 있는 모든 인덱스를 활용할 것입니다.

[참고]

래스터와 도형의 공간 관계성을 확인하려면, ST_Touches(ST_Polygon(raster), geometry)처럼 래스터에 ST_Polygon 함수를 이용하십시오.

2.1.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT r1.rid, r2.rid, ST_Touches(r1.rast, 1, r2.rast, 1) FROM dummy_rast r1 CROSS JOIN dummy_rast r2 WHERE r1.rid = 2;
래스터 출력
rid | rid | st_touches
-----+-----+------------
   2 |   1 | f
   2 |   2 | f

제목

ST_SameAlignment — 래스터들이 동일한 기울기, 축척, 공간 참조 시스템, 그리고 오프셋을 가지고 있을 경우 (픽셀이 다른 픽셀을 침범하지 않고 동일한 그리드에 놓일 수 있을 경우) 참을 반환하고, 그렇지 않을 경우 문제점을 설명하는 안내문과 함께 거짓을 반환합니다.

요약

boolean ST_SameAlignment( raster rastA , raster rastB );

boolean ST_SameAlignment( double precision ulx1 , double precision uly1 , double precision scalex1 , double precision scaley1 , double precision skewx1 , double precision skewy1 , double precision ulx2 , double precision uly2 , double precision scalex2 , double precision scaley2 , double precision skewx2 , double precision skewy2 );

boolean ST_SameAlignment( raster set rastfield );

Description

종합 함수가 아닌 버전(변종 1, 2): (직접 입력하거나 또는 좌상단, 축척, 기울기, SRID 값을 이용해서) 두 래스터가 동일한 축척, 기울기, SRID를 가지며 한 래스터의 어떤 픽셀의 꼭짓점 4개 가운데 적어도 어느 한 꼭짓점이 다른 래스터의 그리드의 어느 모서리에 놓일 경우 참을 반환합니다. 그렇지 않을 경우 정렬 문제를 설명하는 안내문(NOTICE)과 함께 거짓을 반환합니다.

종합 함수 버전(변종 3): 래스터 집합에서, 집합 내부의 모든 래스터가 정렬돼 있을 경우 참을 반환합니다. ST_SameAlignment() 함수는 PostgreSQL 전문 용어로 "종합(aggregate)" 함수입니다. 즉 SUM() 및 AVG() 함수와 마찬가지로 데이터 행들을 대상으로 연산한다는 뜻입니다.

2.0.0 버전부터 사용할 수 있습니다.

개선 사항: 2.1.0 버전에서 종합 함수 변종이 추가됐습니다.

예시: 래스터

Code
SELECT ST_SameAlignment(ST_MakeEmptyRaster(1, 1, 0, 0, 1, 1, 0, 0),
    ST_MakeEmptyRaster(1, 1, 0, 0, 1, 1, 0, 0)
) as sm;
래스터 출력
t
Code
SELECT ST_SameAlignment(A.rast, b.rast)
FROM dummy_rast AS A CROSS JOIN dummy_rast AS B;
래스터 출력
NOTICE:  The two rasters provided have different SRIDs
NOTICE:  The two rasters provided have different SRIDs
 t
 f
 f
 f

제목

ST_NotSameAlignmentReason — 래스터들이 정렬돼 있는지 아닌지, 그리고 정렬되지 않았다면 그 이유를 설명하는 텍스트를 반환합니다.

요약

text ST_NotSameAlignmentReason(raster rastA, raster rastB);

Description

래스터들이 정렬돼 있는지 아닌지, 그리고 정렬되지 않았다면 그 이유를 설명하는 텍스트를 반환합니다.

[참고]

래스터들이 정렬되지 않은 이유가 여러 개 있을 경우, 한 가지 이유(실패한 첫 번째 확인 작업)만 반환할 것입니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT
    ST_SameAlignment(ST_MakeEmptyRaster(1, 1, 0, 0, 1, 1, 0, 0),
        ST_MakeEmptyRaster(1, 1, 0, 0, 1.1, 1.1, 0, 0)
    ),
    ST_NotSameAlignmentReason(ST_MakeEmptyRaster(1, 1, 0, 0, 1, 1, 0, 0),
        ST_MakeEmptyRaster(1, 1, 0, 0, 1.1, 1.1, 0, 0)
    )
;
래스터 출력
st_samealignment |            st_notsamealignmentreason
------------------+-------------------------------------------------
 f                | The rasters have different scales on the X axis
(1 row)

제목

ST_Within — 래스터 rastB 외부에 놓인 래스터 rastA의 포인트가 하나도 없고, 적어도 rastA 내부의 포인트 하나가 rastB의 내부에 있는 경우 참을 반환합니다.

요약

boolean ST_Within( raster rastA , integer nbandA , raster rastB , integer nbandB );

boolean ST_Within( raster rastA , raster rastB );

Description

래스터 rastB 외부에 놓인 래스터 rastA의 포인트가 하나도 없고, 적어도 rastA 내부의 포인트 하나가 rastB의 내부에 있을 경우에만 rastA가 rastB 내부에 있다고 합니다. 밴드 번호를 설정하지 않거나 또는 NULL로 설정할 경우, 확인 작업중 래스터의 볼록 껍질만 고려합니다. 밴드 번호를 설정할 경우, 확인 작업중 값을 가진 (NODATA가 아닌) 픽셀들만 고려합니다.

[참고]

이 피연산자(operand)는 래스터에서 이용할 수도 있는 모든 인덱스를 활용할 것입니다.

[참고]

래스터와 도형의 공간 관계성을 확인하려면, ST_Within(ST_Polygon(raster), geometry) 또는 ST_Within(geometry, ST_Polygon(raster))처럼 래스터에 ST_Polygon 함수를 이용하십시오.

[참고]

ST_Within()는 ST_Contains()의 역함수입니다. 따라서, ST_Within(rastA, rastB)의 결과와 ST_Contains(rastB, rastA)의 결과는 동일할 것입니다.

2.1.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT r1.rid, r2.rid, ST_Within(r1.rast, 1, r2.rast, 1) FROM dummy_rast r1 CROSS JOIN dummy_rast r2 WHERE r1.rid = 2;
래스터 출력
rid | rid | st_within
-----+-----+-----------
   2 |   1 | f
   2 |   2 | t

제목

ST_DWithin — 래스터 rastA와 래스터 rastB가 서로 설정된 거리 안에 있을 경우 참을 반환합니다.

요약

boolean ST_DWithin( raster rastA , integer nbandA , raster rastB , integer nbandB , double precision distance_of_srid );

boolean ST_DWithin( raster rastA , raster rastB , double precision distance_of_srid );

Description

래스터 rastA와 래스터 rastB가 서로 설정된 거리 안에 있을 경우 참을 반환합니다. 밴드 번호를 설정하지 않거나 또는 NULL로 설정할 경우, 확인 작업중 래스터의 볼록 껍질만 고려합니다. 밴드 번호를 설정할 경우, 확인 작업중 값을 가진 (NODATA가 아닌) 픽셀들만 고려합니다.

거리는 래스터들의 공간 참조 시스템이 정의한 단위로 설정됩니다. 이 함수가 제대로 동작하려면, 소스 래스터들이 둘 다 동일한 SRID를 가진, 동일한 좌표 투영체여야 합니다.

[참고]

이 피연산자(operand)는 래스터에서 이용할 수도 있는 모든 인덱스를 활용할 것입니다.

[참고]

래스터와 도형의 공간 관계성을 확인하려면, ST_DWithin(ST_Polygon(raster), geometry)처럼 래스터에 ST_Polygon 함수를 이용하십시오.

2.1.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT r1.rid, r2.rid, ST_DWithin(r1.rast, 1, r2.rast, 1, 3.14) FROM dummy_rast r1 CROSS JOIN dummy_rast r2 WHERE r1.rid = 2;
래스터 출력
rid | rid | st_dwithin
-----+-----+------------
   2 |   1 | f
   2 |   2 | t

제목

ST_DFullyWithin — 래스터 rastA와 래스터 rastB가 완전히 서로 설정된 거리 안에 있을 경우 참을 반환합니다.

요약

boolean ST_DFullyWithin( raster rastA , integer nbandA , raster rastB , integer nbandB , double precision distance_of_srid );

boolean ST_DFullyWithin( raster rastA , raster rastB , double precision distance_of_srid );

Description

래스터 rastA와 래스터 rastB가 완전히 서로 설정된 거리 안에 있을 경우 참을 반환합니다. 밴드 번호를 설정하지 않거나 또는 NULL로 설정할 경우, 확인 작업중 래스터의 볼록 껍질만 고려합니다. 밴드 번호를 설정할 경우, 확인 작업중 값을 가진 (NODATA가 아닌) 픽셀들만 고려합니다.

거리는 래스터들의 공간 참조 시스템이 정의한 단위로 설정됩니다. 이 함수가 제대로 동작하려면, 소스 래스터들이 둘 다 동일한 SRID를 가진, 동일한 좌표 투영체여야 합니다.

[참고]

이 피연산자(operand)는 래스터에서 이용할 수도 있는 모든 인덱스를 활용할 것입니다.

[참고]

래스터와 도형의 공간 관계성을 확인하려면, ST_DFullyWithin(ST_Polygon(raster), geometry)처럼 래스터에 ST_Polygon 함수를 이용하십시오.

2.1.0 버전부터 사용할 수 있습니다.

예시

Code
SELECT r1.rid, r2.rid, ST_DFullyWithin(r1.rast, 1, r2.rast, 1, 3.14) FROM dummy_rast r1 CROSS JOIN dummy_rast r2 WHERE r1.rid = 2;
래스터 출력
rid | rid | st_dfullywithin
-----+-----+-----------------
   2 |   1 | f
   2 |   2 | t

11.18. Raster Tips

초록

This section documents various gotchas and tips related to PostGIS Raster.

11.18.1. Out-DB Rasters

11.18.1.1. Directory containing many files

When GDAL opens a file, GDAL eagerly scans the directory of that file to build a catalog of other files. If this directory contains many files (e.g. thousands, millions), opening that file becomes extremely slow (especially if that file happens to be on a network drive such as NFS).

To control this behavior, GDAL provides the following environment variable: GDAL_DISABLE_READDIR_ON_OPEN. Set GDAL_DISABLE_READDIR_ON_OPEN to TRUE to disable directory scanning.

In Ubuntu (and assuming you are using PostgreSQL's packages for Ubuntu), GDAL_DISABLE_READDIR_ON_OPEN can be set in /etc/postgresql/POSTGRESQL_VERSION/CLUSTER_NAME/environment (where POSTGRESQL_VERSION is the version of PostgreSQL, e.g. 9.6 and CLUSTER_NAME is the name of the cluster, e.g. maindb). You can also set PostGIS environment variables here as well.

Code
# environment variables for postmaster process
# This file has the same syntax as postgresql.conf:
#  VARIABLE = simple_value
#  VARIABLE2 = 'any value!'
# I. e. you need to enclose any value which does not only consist of letters,
# numbers, and '-', '_', '.' in single quotes. Shell commands are not
# evaluated.
POSTGIS_GDAL_ENABLED_DRIVERS = 'ENABLE_ALL'

POSTGIS_ENABLE_OUTDB_RASTERS = 1

GDAL_DISABLE_READDIR_ON_OPEN = 'TRUE'
                    

11.18.1.2. Maximum Number of Open Files

The maximum number of open files permitted by Linux and PostgreSQL are typically conservative (typically 1024 open files per process) given the assumption that the system is consumed by human users. For Out-DB Rasters, a single valid query can easily exceed this limit (e.g. a dataset of 10 year's worth of rasters with one raster for each day containing minimum and maximum temperatures and we want to know the absolute min and max value for a pixel in that dataset).

The easiest change to make is the following PostgreSQL setting: max_files_per_process. The default is set to 1000, which is far too low for Out-DB Rasters. A safe starting value could be 65536 but this really depends on your datasets and the queries run against those datasets. This setting can only be made on server start and probably only in the PostgreSQL configuration file (e.g. /etc/postgresql/POSTGRESQL_VERSION/CLUSTER_NAME/postgresql.conf in Ubuntu environments).

Code
...
# - Kernel Resource Usage -

max_files_per_process = 65536           # min 25
                                        # (change requires restart)
...
                    

The major change to make is the Linux kernel's open files limits. There are two parts to this:

  • Maximum number of open files for the entire system

  • Maximum number of open files per process

11.18.1.2.1. Maximum number of open files for the entire system

You can inspect the current maximum number of open files for the entire system with the following example:

Code
$ sysctl -a | grep fs.file-max
fs.file-max = 131072
                    

If the value returned is not large enough, add a file to /etc/sysctl.d/ as per the following example:

Code
$ echo "fs.file-max = 6145324" >> /etc/sysctl.d/fs.conf

$ cat /etc/sysctl.d/fs.conf
fs.file-max = 6145324

$ sysctl -p --system
* Applying /etc/sysctl.d/fs.conf ...
fs.file-max = 2097152
* Applying /etc/sysctl.conf ...

$ sysctl -a | grep fs.file-max
fs.file-max = 6145324
                    
11.18.1.2.2. Maximum number of open files per process

We need to increase the maximum number of open files per process for the PostgreSQL server processes.

To see what the current PostgreSQL service processes are using for maximum number of open files, do as per the following example (make sure to have PostgreSQL running):

Code
$ ps aux | grep postgres
래스터 출력
postgres 31713  0.0  0.4 179012 17564 pts/0    S    Dec26   0:03 /home/dustymugs/devel/postgresql/sandbox/10/usr/local/bin/postgres -D /home/dustymugs/devel/postgresql/sandbox/10/pgdata
postgres 31716  0.0  0.8 179776 33632 ?        Ss   Dec26   0:01 postgres: checkpointer process
postgres 31717  0.0  0.2 179144  9416 ?        Ss   Dec26   0:05 postgres: writer process
postgres 31718  0.0  0.2 179012  8708 ?        Ss   Dec26   0:06 postgres: wal writer process
postgres 31719  0.0  0.1 179568  7252 ?        Ss   Dec26   0:03 postgres: autovacuum launcher process
postgres 31720  0.0  0.1  34228  4124 ?        Ss   Dec26   0:09 postgres: stats collector process
postgres 31721  0.0  0.1 179308  6052 ?        Ss   Dec26   0:00 postgres: bgworker: logical replication launcher
Code
$ cat /proc/31718/limits
래스터 출력
Limit                     Soft Limit           Hard Limit           Units
Max cpu time              unlimited            unlimited            seconds
Max file size             unlimited            unlimited            bytes
Max data size             unlimited            unlimited            bytes
Max stack size            8388608              unlimited            bytes
Max core file size        0                    unlimited            bytes
Max resident set          unlimited            unlimited            bytes
Max processes             15738                15738                processes
Max open files            1024                 4096                 files
Max locked memory         65536                65536                bytes
Max address space         unlimited            unlimited            bytes
Max file locks            unlimited            unlimited            locks
Max pending signals       15738                15738                signals
Max msgqueue size         819200               819200               bytes
Max nice priority         0                    0
Max realtime priority     0                    0
Max realtime timeout      unlimited            unlimited            us
                    

In the example above, we inspected the open files limit for Process 31718. It doesn't matter which PostgreSQL process, any of them will do. The response we are interested in is Max open files.

We want to increase Soft Limit and Hard Limit of Max open files to be greater than the value we specified for the PostgreSQL setting max_files_per_process. In our example, we set max_files_per_process to 65536.

In Ubuntu (and assuming you are using PostgreSQL's packages for Ubuntu), the easiest way to change the Soft Limit and Hard Limit is to edit /etc/init.d/postgresql (SysV) or /lib/systemd/system/postgresql*.service (systemd).

Let's first address the SysV Ubuntu case where we add ulimit -H -n 262144 and ulimit -n 131072 to /etc/init.d/postgresql.

Code
...
case "$1" in
    start|stop|restart|reload)
        if [ "$1" = "start" ]; then
            create_socket_directory
        fi
    if [ -z "`pg_lsclusters -h`" ]; then
        log_warning_msg 'No PostgreSQL clusters exist; see "man pg_createcluster"'
        exit 0
    fi

    ulimit -H -n 262144
    ulimit -n 131072

    for v in $versions; do
        $1 $v || EXIT=$?
    done
    exit ${EXIT:-0}
        ;;
    status)
...

Now to address the systemd Ubuntu case. We will add LimitNOFILE=131072 to every /lib/systemd/system/postgresql*.service file in the [Service] section.

Code
...
[Service]

LimitNOFILE=131072

...

[Install]
WantedBy=multi-user.target
...

After making the necessary systemd changes, make sure to reload the daemon

Code
systemctl daemon-reload

12장. PostGIS Extras

This chapter documents features found in the extras folder of the PostGIS source tarballs and source repository. These are not always packaged with PostGIS binary releases, but are usually PL/pgSQL based or standard shell scripts that can be run as is.

13장. PostGIS Special Functions Index

13.1. PostGIS Aggregate Functions

The functions below are spatial aggregate functions that are used in the same way as SQL aggregate function such as sum and average.

  • CG_3DUnion - Perform 3D union using postgis_sfcgal.
  • ST_3DExtent - Aggregate function that returns the 3D bounding box of geometries.
  • ST_AsFlatGeobuf - Return a FlatGeobuf representation of a set of rows.
  • ST_AsGeobuf - Return a Geobuf representation of a set of rows.
  • ST_AsMVT - Aggregate function returning a MVT representation of a set of rows.
  • ST_ClusterDBSCAN - Window function that returns a cluster id for each input geometry using the DBSCAN algorithm.
  • ST_ClusterIntersecting - Aggregate function that clusters input geometries into connected sets.
  • ST_ClusterIntersectingWin - Window function that returns a cluster id for each input geometry, clustering input geometries into connected sets.
  • ST_ClusterKMeans - Window function that returns a cluster id for each input geometry using the K-means algorithm.
  • ST_ClusterRelateWin - Window function that returns a cluster id for each input geometry, clustering input geometries into connected sets using the relate pattern to determine whether the geometries are connected.
  • ST_ClusterWithin - Aggregate function that clusters geometries by separation distance.
  • ST_ClusterWithinWin - Window function that returns a cluster id for each input geometry, clustering using separation distance.
  • ST_Collect - Creates a GeometryCollection or Multi* geometry from a set of geometries.
  • ST_CoverageClean - Computes a clean (edge matched, non-overlapping, gap-cleared) polygonal coverage, given a non-clean input.
  • ST_CoverageInvalidEdges - Window function that finds locations where polygons fail to form a valid coverage.
  • ST_CoverageSimplify - Window function that simplifies the edges of a polygonal coverage.
  • ST_CoverageUnion - Computes the union of a set of polygons forming a coverage by removing shared edges.
  • ST_Extent - Aggregate function that returns the bounding box of geometries.
  • ST_MakeLine - 포인트, 멀티포인트 또는 라인 도형으로부터 라인스트링을 생성합니다.
  • ST_MemUnion - Aggregate function which unions geometries in a memory-efficent but slower way
  • ST_MinimumSpanningTree - Window function that returns a tree id for each input geometry, clustering input geometries into connected trees using the Minimum Spanning Tree algorithm.
  • ST_Polygonize - Computes a collection of polygons formed from the linework of a set of geometries.
  • ST_SameAlignment - 래스터들이 동일한 기울기, 축척, 공간 참조 시스템, 그리고 오프셋을 가지고 있을 경우 (픽셀이 다른 픽셀을 침범하지 않고 동일한 그리드에 놓일 수 있을 경우) 참을 반환하고, 그렇지 않을 경우 문제점을 설명하는 안내문과 함께 거짓을 반환합니다.
  • ST_Union - Computes a geometry representing the point-set union of the input geometries.
  • ST_Union - 래스터 타일 집합을 1개 이상의 밴드로 이루어진 단일 래스터로 통합합니다.
  • TopoElementArray_Agg - Returns a topoelementarray for a set of element_id, type arrays (topoelements).

13.2. PostGIS Window Functions

The functions below are spatial window functions that are used in the same way as SQL window functions such as row_number(), lead(), and lag(). They must be followed by an OVER() clause.

  • ST_ClusterDBSCAN - Window function that returns a cluster id for each input geometry using the DBSCAN algorithm.
  • ST_ClusterIntersectingWin - Window function that returns a cluster id for each input geometry, clustering input geometries into connected sets.
  • ST_ClusterKMeans - Window function that returns a cluster id for each input geometry using the K-means algorithm.
  • ST_ClusterRelateWin - Window function that returns a cluster id for each input geometry, clustering input geometries into connected sets using the relate pattern to determine whether the geometries are connected.
  • ST_ClusterWithinWin - Window function that returns a cluster id for each input geometry, clustering using separation distance.
  • ST_CoverageClean - Computes a clean (edge matched, non-overlapping, gap-cleared) polygonal coverage, given a non-clean input.
  • ST_CoverageInvalidEdges - Window function that finds locations where polygons fail to form a valid coverage.
  • ST_CoverageSimplify - Window function that simplifies the edges of a polygonal coverage.
  • ST_MinimumSpanningTree - Window function that returns a tree id for each input geometry, clustering input geometries into connected trees using the Minimum Spanning Tree algorithm.

13.3. PostGIS SQL-MM Compliant Functions

The functions given below are PostGIS functions that conform to the SQL/MM 3 standard

  • CG_3DArea - 3차원 표면 도형의 면적을 계산합니다. 입체일 경우 0을 반환할 것입니다.
  • CG_3DDifference - 3차원 차이를 수행합니다.
  • CG_3DIntersection - 3차원 교차를 수행합니다.
  • CG_3DUnion - Perform 3D union using postgis_sfcgal.
  • CG_Volume - Computes the volume of a 3D geometry. Closed surfaces can have non-zero volume.
  • ST_3DDWithin - Tests if two 3D geometries are within a given 3D distance
  • ST_3DDistance - 도형 유형에 대해, 두 도형 사이의 (SRS에 기반한) 3차원 데카르트 최단 거리를 투영 단위로 반환합니다.
  • ST_3DIntersects - Tests if two geometries spatially intersect in 3D - only for points, linestrings, polygons, polyhedral surface (area)
  • ST_3DLength - 도형의 기하학적 중심을 반환합니다.
  • ST_3DPerimeter - 도형의 기하학적 중심을 반환합니다.
  • ST_AddEdgeModFace - 새 경계선을 추가하고, 그 과정에서 경계선이 표면을 분할할 경우, 원본 표면을 수정하고 새 표면을 추가합니다.
  • ST_AddEdgeNewFaces - 새 경계선을 추가하고, 그 과정에서 경계선이 표면을 분할할 경우, 원본 표면을 삭제하고 새 표면 2개로 교체합니다.
  • ST_AddIsoEdge - 지형에 두 개의 고립된 기존 노드 anode 와 anothernode 를 연결하는 alinestring 도형이 정의하는 고립된 경계선을 추가하고 새 경계선의 ID를 반환합니다.
  • ST_AddIsoNode - 지형 안의 표면에 고립된(isolated) 노드를 추가하고 새 노드의 ID를 반환합니다. 표면이 NULL일 경우, 그래도 노드를 생성합니다.
  • ST_Area - 도형의 기하학적 중심을 반환합니다.
  • ST_AsBinary - Return the OGC/ISO Well-Known Binary (WKB) representation of the geometry/geography without SRID meta data.
  • ST_AsGML - 도형을 GML 2 또는 GML 3 버전 요소로 반환합니다.
  • ST_AsText - 도형/지리형의 WKT(Well-Known Text) 표현식을 SRID 메타데이터 없이 반환합니다.
  • ST_Boundary - 해당 도형의 결합된 범위의 닫힘 여부를 반환합니다.
  • ST_Buffer - Computes a geometry covering all points within a given distance from a geometry.
  • ST_Centroid - 도형의 기하학적 중심을 반환합니다.
  • ST_ChangeEdgeGeom - 지형 구조를 건드리는 일 없이 경계선의 형상을 변경합니다.
  • ST_Contains - Tests if every point of B lies in A, and their interiors have a point in common
  • ST_ConvexHull - Computes the convex hull of a geometry.
  • ST_CoordDim - ST_Geometry 값의 좌표 차원을 반환합니다.
  • ST_CreateTopoGeo - 텅 빈 입력 지형에 도형들의 집합을 추가한 다음 작업 성공 여부를 상세하게 설명하는 메시지를 반환합니다.
  • ST_Crosses - Tests if two geometries have some, but not all, interior points in common
  • ST_CurveN - Returns the Nth component curve geometry of a CompoundCurve.
  • ST_CurveToLine - Converts a geometry containing curves to a linear geometry.
  • ST_Difference - Computes a geometry representing the part of geometry A that does not intersect geometry B.
  • ST_Dimension - ST_Geometry 값의 좌표 차원을 반환합니다.
  • ST_Disjoint - Tests if two geometries have no points in common
  • ST_Distance - 두 도형 사이의 3차원 최장(longest) 라인을 반환합니다.
  • ST_EndPoint - Returns the last point of a LineString, CircularLineString, or NURBSCurve.
  • ST_Envelope - 주어진 도형의 이중 정밀도(double precision; float8) 경계 상자를 표현하는 도형을 반환합니다.
  • ST_Equals - Tests if two geometries include the same set of points
  • ST_ExteriorRing - 폴리곤 도형의 내곽 고리의 개수를 반환합니다.
  • ST_GMLToSQL - Returns a geometry from GML. Alias for ST_GeomFromGML.
  • ST_GeomCollFromText - Makes a collection Geometry from collection WKT with the given SRID. If SRID is not given, it defaults to 0.
  • ST_GeomFromText - WKT 표현식으로부터 지정된 ST_Geometry 값을 반환합니다.
  • ST_GeomFromWKB - WKB(Well-Known Binary) 도형 표현식과 선택적인 SRID로부터 도형 인스턴스를 생성합니다.
  • ST_GeometryFromText - Returns a geometry from Well-Known Text (WKT). Alias for ST_GeomFromText.
  • ST_GeometryN - ST_Geometry 값의 도형 유형을 반환합니다.
  • ST_GeometryType - ST_Geometry 값의 도형 유형을 반환합니다.
  • ST_GetFaceEdges - aface 의 경계를 이루는 정렬된 경계선들의 집합을 반환합니다.
  • ST_GetFaceGeometry - 입력 지형으로부터 설정된 표면 ID를 가진 폴리곤을 반환합니다.
  • ST_InitTopoGeo - Creates a new topology schema and registers it in the topology.topology table.
  • ST_InteriorRingN - 폴리곤 도형의 내곽 고리의 개수를 반환합니다.
  • ST_Intersection - Computes a geometry representing the shared portion of geometries A and B.
  • ST_Intersects - Tests if two geometries intersect (they have at least one point in common)
  • ST_IsClosed - LINESTRING 의 시작점과 종단점이 일치하는 경우 TRUE 를 반환합니다. 다면체 표면이 닫혀 (부피를 가지고) 있는 경우 TRUE 를 반환합니다.
  • ST_IsEmpty - Tests if a geometry is empty.
  • ST_IsRing - Tests if a LineString is closed and simple.
  • ST_IsSimple - 해당 도형이 자체 교차하거나 자체 접촉하는 이례적인 도형 포인트를 가지고 있지 않을 경우 TRUE 를 반환합니다.
  • ST_IsValid - Tests if a geometry is well-formed in 2D.
  • ST_Length - 도형의 기하학적 중심을 반환합니다.
  • ST_LineFromText - 주어진 SRID와 함께 WKT 표현식으로부터 도형을 만듭니다. SRID가 주어지지 않은 경우, 기본값인 0을 씁니다.
  • ST_LineFromWKB - Creates a LINESTRING from a WKB representation, optionally using a given SRID.
  • ST_LinestringFromWKB - Creates a LINESTRING from a WKB representation, optionally using a given SRID.
  • ST_LocateAlong - Returns the point(s) on a geometry that match a measure value.
  • ST_LocateBetween - Returns the portions of a geometry that match a measure range.
  • ST_M - Returns the M coordinate of a Point.
  • ST_MLineFromText - WKT 표현식으로부터 지정된 ST_MultiLineString 값을 반환합니다.
  • ST_MPointFromText - Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.
  • ST_MPolyFromText - Makes a MultiPolygon Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.
  • ST_ModEdgeHeal - Heals two edges by deleting the node connecting them, modifying the first edge and deleting the second edge. Returns the id of the deleted node.
  • ST_ModEdgeSplit - 기존 경계선을 따라 새 노드를 추가한 다음, 원본 경계선을 수정하고 새 경계선을 추가해서 경계선을 분할합니다.
  • ST_MoveIsoNode - Moves an isolated node in a topology from one point to another. If new apoint geometry exists as a node an error is thrown. Returns description of move.
  • ST_NewEdgeHeal - Heals two edges by deleting the node connecting them, deleting both edges, and replacing them with an edge whose direction is the same as the first edge provided.
  • ST_NewEdgesSplit - 기존 경계선을 따라 새 노드를 추가한 다음, 원본 경계선을 삭제하고 새 경계선 2개로 교체해서 경계선을 분할합니다. 새 경계선들을 결합하는 새로 생성된 노드의 ID를 반환합니다.
  • ST_NumCurves - Return the number of component curves in a CompoundCurve.
  • ST_NumGeometries - 도형이 가지고 있는 포인트의 개수를 반환합니다. 모든 도형을 입력받을 수 있습니다.
  • ST_NumInteriorRings - 폴리곤 도형의 내곽 고리의 개수를 반환합니다.
  • ST_NumPatches - Returns the number of faces in a PolyhedralSurface or TIN.
  • ST_NumPoints - ST_LineString 또는 ST_CircularString 값에 있는 포인트의 개수를 반환합니다.
  • ST_OrderingEquals - Tests if two geometries represent the same geometry and have points in the same directional order
  • ST_Overlaps - Tests if two geometries have the same dimension and intersect, but each has at least one point not in the other
  • ST_PatchN - Returns the Nth face of a PolyhedralSurface or TIN.
  • ST_Perimeter - Returns the length of the boundary of a polygonal geometry or geography.
  • ST_Point - Creates a Point with X, Y and SRID values.
  • ST_PointFromText - 주어진 SRID와 함께 WKT 표현식으로부터 포인트 도형을 만듭니다. SRID가 주어지지 않은 경우, 기본값인 0을 씁니다.
  • ST_PointFromWKB - 주어진 SRID와 함께 WKB로부터 도형을 만듭니다.
  • ST_PointN - ST_LineString 또는 ST_CircularString 값에 있는 포인트의 개수를 반환합니다.
  • ST_PointOnSurface - Computes a point guaranteed to lie in a polygon, or on a geometry.
  • ST_Polygon - Creates a Polygon from a LineString with a specified SRID.
  • ST_PolygonFromText - Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.
  • ST_Relate - Tests if two geometries have a topological relationship matching an Intersection Matrix pattern, or computes their Intersection Matrix
  • ST_RemEdgeModFace - Removes an edge, and if the edge separates two faces deletes one face and modifies the other face to cover the space of both.
  • ST_RemEdgeNewFace - 경계선을 제거하고, 제거한 경계선이 두 표면을 분할하고 있을 경우, 원본 표면들을 삭제하고 새 표면 하나로 대체합니다.
  • ST_RemoveIsoEdge - Removes an isolated edge and returns description of action. If the edge is not isolated, then an exception is thrown.
  • ST_RemoveIsoNode - 고립된 노드를 제거하고 작업 내용을 설명하는 메시지를 반환합니다. 노드가 고립되지 않은 (경계선의 시작점이나 종단점인) 경우, 예외가 발생합니다.
  • ST_SRID - Returns the spatial reference identifier for a geometry.
  • ST_StartPoint - Returns the first point of a LineString, CircularLineString, or NURBSCurve.
  • ST_SymDifference - Computes a geometry representing the portions of geometries A and B that do not intersect.
  • ST_Touches - Tests if two geometries have at least one point in common, but their interiors do not intersect
  • ST_Transform - Return a new geometry with coordinates transformed to a different spatial reference system.
  • ST_Union - Computes a geometry representing the point-set union of the input geometries.
  • ST_WKBToSQL - Returns a geometry from Well-Known Binary (WKB). SQL/MM alias for ST_GeomFromWKB without an SRID argument.
  • ST_WKTToSQL - Returns a geometry from Well-Known Text (WKT). SQL/MM alias for ST_GeomFromText.
  • ST_Within - Tests if every point of A lies in B, and their interiors have a point in common
  • ST_X - Returns the X coordinate of a Point.
  • ST_Y - Returns the Y coordinate of a Point.
  • ST_Z - Returns the Z coordinate of a Point.

13.4. PostGIS Geography Support Functions

The functions and operators given below are PostGIS functions/operators that take as input or return as output a geography data type object.

[참고]

Functions with a (T) are not native geodetic functions, and use a ST_Transform call to and from geometry to do the operation. As a result, they may not behave as expected when going over dateline, poles, and for large geometries or geometry pairs that cover more than one UTM zone. Basic transform - (favoring UTM, Lambert Azimuthal (North/South), and falling back on mercator in worst case scenario)

  • ST_Area - 도형의 기하학적 중심을 반환합니다.
  • ST_AsBinary - Return the OGC/ISO Well-Known Binary (WKB) representation of the geometry/geography without SRID meta data.
  • ST_AsEWKT - 도형의 WKT(Well-Known Text) 표현식을 SRID 메타데이터와 함께 반환합니다.
  • ST_AsGML - 도형을 GML 2 또는 GML 3 버전 요소로 반환합니다.
  • ST_AsGeoJSON - Return a geometry or feature in GeoJSON format.
  • ST_AsKML - 도형을 GML 2 또는 GML 3 버전 요소로 반환합니다.
  • ST_AsSVG - Returns SVG path data for a geometry.
  • ST_AsText - 도형/지리형의 WKT(Well-Known Text) 표현식을 SRID 메타데이터 없이 반환합니다.
  • ST_Azimuth - 두 도형 사이의 2차원 최단 라인을 반환합니다.
  • ST_Buffer - Computes a geometry covering all points within a given distance from a geometry.
  • ST_Centroid - 도형의 기하학적 중심을 반환합니다.
  • ST_ClosestPoint - Returns the 2D point on g1 that is closest to g2. This is the first point of the shortest line from one geometry to the other.
  • ST_CoveredBy - Tests if every point of A lies in B
  • ST_Covers - Tests if every point of B lies in A
  • ST_DWithin - Tests if two geometries are within a given distance
  • ST_Distance - 두 도형 사이의 3차원 최장(longest) 라인을 반환합니다.
  • ST_GeogFromText - WKT (확장) 표현식으로부터 지정된 지리형 값을 반환합니다.
  • ST_GeogFromWKB - WKB 도형 표현식 또는 EWKB(확장 WKB)로부터 지리형 인스턴스를 생성합니다.
  • ST_GeographyFromText - WKT (확장) 표현식으로부터 지정된 지리형 값을 반환합니다.
  • = - Returns TRUE if the coordinates and coordinate order geometry/geography A are the same as the coordinates and coordinate order of geometry/geography B.
  • ST_Intersection - Computes a geometry representing the shared portion of geometries A and B.
  • ST_Intersects - Tests if two geometries intersect (they have at least one point in common)
  • ST_Length - 도형의 기하학적 중심을 반환합니다.
  • ST_LineInterpolatePoint - Returns a point interpolated along a line at a fractional location.
  • ST_LineInterpolatePoints - Returns points interpolated along a line at a fractional interval.
  • ST_LineLocatePoint - Returns the fractional location of the closest point on a line to a point.
  • ST_LineSubstring - Returns the part of a line between two fractional locations.
  • ST_Perimeter - Returns the length of the boundary of a polygonal geometry or geography.
  • ST_Project - Returns a point projected from a start point by a distance and bearing (azimuth).
  • ST_Segmentize - Returns a modified geometry/geography having no segment longer than a given distance.
  • ST_ShortestLine - 두 도형 사이의 2차원 최단 라인을 반환합니다.
  • ST_Summary - 도형의 내용을 요약한 텍스트를 반환합니다.
  • <-> - A와 B 사이의 2차원 거리를 반환합니다.
  • && - A의 2D 경계 상자와 B의 2D 경계 상자가 교차하는 경우 TRUE 를 반환합니다.

13.5. PostGIS Raster Support Functions

The functions and operators given below are PostGIS functions/operators that take as input or return as output a raster data type object. Listed in alphabetical order.

  • Box3D - 래스터를 둘러싼 상자의 BOX3D 표현식을 반환합니다.
  • @ - B의 경계 상자가 A의 경계 상자를 담고 있을 경우 TRUE 를 반환합니다. 이중 정밀도 경계 상자를 이용합니다.
  • ~ - A의 경계 상자가 B의 경계 상자를 담고 있을 경우 TRUE 를 반환합니다. 이중 정밀도 경계 상자를 이용합니다.
  • = - A의 경계 상자와 B의 경계 상자가 동일할 경우 TRUE 를 반환합니다. 이중 정밀도 경계 상자를 이용합니다.
  • && - A의 경계 상자와 B의 경계 상자가 교차하는 경우 TRUE 를 반환합니다.
  • &< - A의 경계 상자가 B의 경계 상자 왼쪽에 있을 경우 TRUE 를 반환합니다.
  • &> - A의 경계 상자가 B의 경계 상자 오른쪽에 있을 경우 TRUE 를 반환합니다.
  • ~= - A의 경계 상자와 B의 경계 상자가 동일할 경우 TRUE 를 반환합니다.
  • ST_Retile - 임의로 타일화된 래스터 커버리지로부터, 설정된 타일들의 집합을 반환합니다.
  • ST_AddBand - 입력 인덱스 위치에 입력 초기값으로 추가된 입력 유형의 새 밴드(들)을 가진 래스터를 반환합니다. 인덱스를 설정하지 않을 경우, 마지막 위치에 밴드를 추가합니다.
  • ST_AsBinary/ST_AsWKB - Return the Well-Known Binary (WKB) representation of the raster.
  • ST_AsGDALRaster - Return the raster tile in the designated GDAL Raster format. Raster formats are one of those supported by your compiled library. Use ST_GDALDrivers() to get a list of formats supported by your library.
  • ST_AsHexWKB - Return the Well-Known Binary (WKB) in Hex representation of the raster.
  • ST_AsJPEG - 래스터 타일에서 선택한 밴드들을 단일 JPEG(Joint Photographic Exports Group) 이미지(바이트 배열)로 반환합니다. 밴드를 따로 설정하지 않거나, 밴드가 1개거나 또는 3개를 초과할 경우 첫 번째 밴드를 씁니다. 밴드가 3개뿐일 경우 밴드 3개를 모두 써서 RGB에 매핑시킵니다.
  • ST_AsPNG - 래스터 타일에서 선택한 밴드들을 단일 PNG(Portable Network Graphics) 이미지(바이트 배열)로 반환합니다. 래스터의 밴드가 1개, 3개, 또는 4개이거나 따로 설정하지 않을 경우 모든 밴드를 씁니다. 밴드가 2개 또는 4개를 초과하며 따로 설정하지 않을 경우, 밴드 1만 씁니다. 밴드를 RGB 또는 RGBA 스페이스에 매핑합니다.
  • ST_AsRaster - PostGIS 도형을 PostGIS 래스터로 변환합니다.
  • ST_AsRasterAgg - Aggregate. Renders PostGIS geometries into a new raster.
  • ST_AsTIFF - Return the raster selected bands as a single TIFF image (byte array). If no band is specified or any of specified bands does not exist in the raster, then will try to use all bands.
  • ST_Aspect - 표고 래스터 밴드의 향(기본 단위는 도)을 반환합니다. 지형을 분석하는 데 유용합니다.
  • ST_Band - 기존 래스터의 하나 이상의 밴드를 새 래스터로 반환합니다. 기존 래스터로부터 새 래스터를 빌드하는 데 유용합니다.
  • ST_BandFileSize - Returns the file size of a band stored in file system. If no bandnum specified, 1 is assumed.
  • ST_BandFileTimestamp - Returns the file timestamp of a band stored in file system. If no bandnum specified, 1 is assumed.
  • ST_BandIsNoData - 밴드가 NODATA 값만으로 채워져 있을 경우 참을 반환합니다.
  • ST_BandMetaData - 지정 래스터 밴드에 대한 기본 메타데이터를 반환합니다. 밴드를 지정하지 않을 경우 밴드 1번이라고 가정합니다.
  • ST_BandNoDataValue - 입력 밴드에서 NODATA를 나타내는 값을 반환합니다. 어떤 밴드도 지정하지 않을 경우 밴드 1로 가정합니다.
  • ST_BandPath - 파일 시스템에 저장된 밴드를 가리키는 시스템 파일 경로를 반환합니다. bandnum을 설정하지 않을 경우 밴드 1로 가정합니다.
  • ST_BandPixelType - 입력 밴드의 픽셀 유형을 반환합니다. bandnum을 설정하지 않을 경우 밴드 1로 가정합니다.
  • ST_Clip - Returns the raster clipped by the input geometry. If band number is not specified, all bands are processed. If crop is not specified or TRUE, the output raster is cropped. If touched is set to TRUE, then touched pixels are included, otherwise only if the center of the pixel is in the geometry it is included.
  • ST_ColorMap - 소스 래스터 및 설정한 밴드로부터 8BUI 밴드(grayscale, RGB, RGBA)를 4개까지 가지는 새 래스터를 생성합니다. 밴드를 따로 설정하지 않으면 밴드 1로 가정합니다.
  • ST_Contains - 래스터 rastA 외부에 놓인 래스터 rastB의 포인트가 하나도 없고, 적어도 rastB 내부의 포인트 하나가 rastA의 내부에 있는 경우 참을 반환합니다.
  • ST_ContainsProperly - rastB가 rastA의 내부와 교차하지만 rastA의 경계선 또는 외부와 교차하지는 않을 경우 참을 반환합니다.
  • ST_Contour - Generates a set of vector contours from the provided raster band, using the GDAL contouring algorithm.
  • ST_ConvexHull - BandNoDataValue와 일치하는 픽셀 값을 포함한, 래스터의 볼록 껍질 도형을 반환합니다. 정규 형상 및 기울어지지 않은 래스터의 경우, ST_Envelope와 동일한 결과물을 출력하므로 비정규 형상 또는 기울어진 래스터에 대해서만 쓸모가 있습니다.
  • ST_Count - 래스터 또는 래스터 커버리지의 입력 밴드에 있는 픽셀 개수를 반환합니다. 밴드를 따로 설정하지 않을 경우 기본값은 밴드 1입니다. exclude_nodata_value를 참으로 설정할 경우, NODATA 값이 아닌 픽셀의 개수만 반환할 것입니다.
  • ST_CountAgg - 종합 함수입니다. 래스터 집합의 입력 밴드에 있는 픽셀 개수를 반환합니다. 밴드를 따로 설정하지 않을 경우 기본값은 밴드 1입니다. exclude_nodata_value를 참으로 설정할 경우, NODATA 값이 아닌 픽셀의 개수만 반환할 것입니다.
  • ST_CoveredBy - 래스터 rastA의 어떤 포인트도 래스터 rastB 외부에 없을 경우 참을 반환합니다.
  • ST_Covers - 래스터 rastB의 어떤 포인트도 래스터 rastA 외부에 없을 경우 참을 반환합니다.
  • ST_DFullyWithin - 래스터 rastA와 래스터 rastB가 완전히 서로 설정된 거리 안에 있을 경우 참을 반환합니다.
  • ST_DWithin - 래스터 rastA와 래스터 rastB가 서로 설정된 거리 안에 있을 경우 참을 반환합니다.
  • ST_Disjoint - 래스터 rastA와 래스터 rastB가 공간적으로 교차하지 않을 경우 참을 반환합니다.
  • ST_DumpAsPolygons - 입력 래스터 밴드로부터 geomval(geom, val) 행들의 집합을 반환합니다. 밴드 번호를 설정하지 않을 경우 기본적으로 밴드 1로 가정합니다.
  • ST_DumpValues - 지정된 밴드의 값들을 2차원 배열로 반환합니다.
  • ST_Envelope - 래스터 범위의 폴리곤 표현식을 반환합니다.
  • ST_FromGDALRaster - 지원 GDAL 래스터 파일로부터 래스터를 반환합니다.
  • ST_GeoReference - 월드(world) 파일에서 흔히 볼 수 있는 지리참조 메타데이터를 GDAL 또는 ESRI 형식으로 반환합니다. 기본값은 GDAL입니다.
  • ST_Grayscale - Creates a new one-8BUI band raster from the source raster and specified bands representing Red, Green and Blue
  • ST_HasNoBand - 입력된 밴드 번호에 밴드가 없을 경우 참을 반환합니다. 밴드 번호를 설정하지 않을 경우, 밴드 1로 가정합니다.
  • ST_Height - 래스터의 높이를 픽셀 개수로 반환합니다.
  • ST_HillShade - 입력한 방위각, 고도각, 밝기 및 축척을 이용해서 표고 래스터 밴드의 가상적인 음영기복을 반환합니다.
  • ST_Histogram - 빈(bin; 히스토그램 표시에서 수직 막대로 나타나는 단위) 범위로 구분된 래스터 또는 래스터 커버리지의 데이터 분포를 요약하는 레코드 집합을 반환합니다. 따로 설정하지 않을 경우 빈의 개수를 자동으로 계산합니다.
  • ST_InterpolateRaster - Interpolates a gridded surface based on an input set of 3-d points, using the X- and Y-values to position the points on the grid and the Z-value of the points as the surface elevation.
  • ST_Intersection - 두 래스터의 공유 부분을 표현하는, 또는 벡터화된 래스터와 도형의 기하학적 교차를 표현하는 래스터 또는 도형-픽셀값 쌍의 집합을 반환합니다.
  • ST_IntersectionFractions - Calculates the fraction of each raster cell that is covered by a given geometry.
  • ST_Intersects - 래스터 rastA와 래스터 rastB가 공간적으로 교차할 경우 참을 반환합니다.
  • ST_IsEmpty - 래스터가 비어 있을 경우 (width = 0, height = 0) 참을 반환합니다. 그렇지 않을 경우 거짓을 반환합니다.
  • ST_MakeEmptyCoverage - Cover georeferenced area with a grid of empty raster tiles.
  • ST_MakeEmptyRaster - 설정된 차원(너비 & 높이), 좌상단 X 및 Y, 픽셀 크기, 회전(scalex, scaley, skewx & skewy) 그리고 공간 참조 시스템(SRID)를 가진 텅 빈 (밴드가 없는) 래스터를 반환합니다. 래스터를 입력할 경우, 동일한 크기, 정렬 방향 및 SRID를 가진 새 래스터를 반환합니다. SRID를 생략할 경우, 공간 참조 시스템을 0(unknown)으로 설정합니다.
  • ST_MapAlgebra (callback function version) - 콜백 함수 버전 - 래스터 1개 이상, 밴드 인덱스, 그리고 사용자 지정 콜백 함수 1개를 입력받아 밴드 1개를 가진 래스터를 반환합니다.
  • ST_MapAlgebraExpr - 래스터 밴드 1개 버전: 입력 래스터에 대해 유효한 PostgreSQL 대수 연산을 적용해서 형성되고, 설정한 픽셀 유형을 가진, 밴드 1개를 가진 새 래스터를 생성합니다. 따로 밴드를 설정하지 않을 경우, 밴드 1로 가정합니다.
  • ST_MapAlgebraExpr - 래스터 밴드 2개 버전: 입력 래스터 2개에 대해 유효한 PostgreSQL 대수 연산을 적용해서 형성되고, 설정한 픽셀 유형을 가진, 밴드 1개를 가진 새 래스터를 생성합니다. 따로 밴드를 설정하지 않을 경우, 각 래스터의 밴드 1로 가정합니다. 출력 래스터는 첫 번째 래스터가 정의하는 그리드 상에 (축척, 기울기 및 픽셀 모서리가) 정렬될 것입니다. extenttype 파라미터가 출력 래스터의 범위를 정의할 것입니다. extenttype 의 값은 INTERSECTION, UNION, FIRST, SECOND가 될 수 있습니다.
  • ST_MapAlgebraFct - 래스터 밴드 1개 버전: 입력 래스터에 대해 유효한 PostgreSQL 대수 연산을 적용해서 형성되고, 설정한 픽셀 유형을 가진, 밴드 1개를 가진 새 래스터를 생성합니다. 따로 밴드를 설정하지 않을 경우, 밴드 1로 가정합니다.
  • ST_MapAlgebraFct - 래스터 밴드 2개 버전: 입력 래스터 2개에 대해 유효한 PostgreSQL 함수를 적용해서 형성되고, 설정한 픽셀 유형을 가진, 밴드 1개를 가진 새 래스터를 생성합니다. 따로 밴드를 설정하지 않을 경우, 밴드 1로 가정합니다. 범위 유형을 따로 설정하지 않을 경우 기본값은 INTERSECTION입니다.
  • ST_MapAlgebraFctNgb - 래스터 밴드 1개 버전: 사용자 지정 PostgreSQL 함수를 이용하는 맵 대수 최근접 이웃(Map Algebra Nearest Neighbor)입니다. 입력 래스터 밴드의 값의 이웃(neighborhood)이 관련된 PostgreSQL 사용자 함수가 출력하는 값을 가진 래스터를 반환합니다.
  • ST_MapAlgebra (expression version) - 표현식 버전 - 입력 래스터 1개 또는 2개, 밴드 인덱스, 그리고 사용자 지정 SQL 표현식 1개 이상을 입력받아 밴드 1개를 가진 래스터를 반환합니다.
  • ST_MemSize - 래스터가 차지하는 공간의 용량을 (바이트 단위로) 반환합니다.
  • ST_MetaData - 래스터 객체의 픽셀 크기, 회전(skew), 좌상단, 좌하단 등과 같은 기본 메타데이터를 반환합니다.
  • ST_MinConvexHull - 래스터의 NODATA 픽셀을 제외한 볼록 껍질 도형을 반환합니다.
  • ST_NearestValue - columnx 및 rowy, 또는 래스터와 동일한 공간 참조 좌표 시스템 단위로 표현된 기하학적 포인트로 지정된 입력 밴드의 픽셀에 가장 가까운 NODATA 가 아닌 값을 반환합니다.
  • ST_Neighborhood - columnx 및 rowy, 또는 래스터와 동일한 공간 참조 좌표 시스템 단위로 표현된 기하학적 포인트로 지정된 입력 밴드의 픽셀 주위의 NODATA 가 아닌 값들의 이중 정밀도 데이터형 2차원 배열을 반환합니다.
  • ST_NotSameAlignmentReason - 래스터들이 정렬돼 있는지 아닌지, 그리고 정렬되지 않았다면 그 이유를 설명하는 텍스트를 반환합니다.
  • ST_NumBands - 래스터 객체 내부에 있는 밴드들의 개수를 반환합니다.
  • ST_Overlaps - 래스터 rastA와 래스터 rastB가 교차하지만 어느 한 쪽이 다른 한 쪽을 완전히 담고 있지는 않을 경우 참을 반환합니다.
  • ST_PixelAsCentroid - 픽셀 하나가 차지하는 면의 중심점(포인트 도형)을 반환합니다.
  • ST_PixelAsCentroids - 래스터 밴드의 각 픽셀에 대한 중심점(포인트 도형)을 각 픽셀의 값 및 X, Y 래스터 좌표와 함께 반환합니다. 포인트 도형은 픽셀이 차지하는 면의 중심점입니다.
  • ST_PixelAsPoint - 픽셀의 좌상단에 위치하는 포인트 도형을 반환합니다.
  • ST_PixelAsPoints - 래스터 밴드의 각 픽셀에 대한 포인트 도형을 각 픽셀의 값 및 X, Y 래스터 좌표와 함께 반환합니다. 포인트 도형의 좌표는 픽셀의 좌상단 좌표입니다.
  • ST_PixelAsPolygon - 특정 행 및 열에 대한 픽셀의 경계를 이루는 폴리곤 도형을 반환합니다.
  • ST_PixelAsPolygons - 래스터 밴드의 모든 픽셀의 경계를 이루는 폴리곤 도형을 각 픽셀의 값과 X, Y 래스터 좌표와 함께 반환합니다.
  • ST_PixelHeight - 픽셀 높이를 공간 참조 시스템의 기하 단위로 반환합니다.
  • ST_PixelOfValue - 검색 값과 일치하는 값을 가진 픽셀의 columnx, rowy 좌표를 반환합니다.
  • ST_PixelWidth - 픽셀 너비를 공간 참조 시스템의 기하 단위로 반환합니다.
  • ST_Polygon - NODATA 값이 아닌 픽셀 값을 가진 픽셀들을 통합해서 형성된 멀티폴리곤 도형을 반환합니다.
  • ST_Quantile - 샘플링 또는 채우기(population)라는 맥락에서 래스터 또는 래스터 테이블 커버리지의 사분위(quantile)를 계산합니다. 따라서, 래스터의 25%, 50%, 75% 백분위(percentile) 단계로 값을 확인할 수 있습니다.
  • ST_RastFromHexWKB - Return a raster value from a Hex representation of Well-Known Binary (WKB) raster.
  • ST_RastFromWKB - Return a raster value from a Well-Known Binary (WKB) raster.
  • ST_RasterToWorldCoord - 주어진 열과 행에 있는 래스터의 좌상단의 기하학적 X, Y(경도, 위도)를 으로 반환합니다. 열과 행은 1부터 시작합니다.
  • ST_RasterToWorldCoordX - 열과 행에 있는 래스터의 좌상단의 기하학적 X 좌표를 반환합니다. 열과 행의 번호는 1부터 시작합니다.
  • ST_RasterToWorldCoordY - 열과 행에 있는 래스터의 좌상단의 기하학적 Y 좌표를 반환합니다. 열과 행의 번호는 1부터 시작합니다.
  • ST_Reclass - 원본으로부터 재분류된 밴드 유형으로 이루어진 새 래스터를 생성합니다. nband 는 변경할 밴드를 가리킵니다. nband 를 따로 설정하지 않을 경우 밴드 1로 가정합니다. 다른 모든 밴드들은 변경 없이 반환됩니다. 실제 사례: 보기 좋은 형식으로 더 간단하게 렌더링하기 위해 16BUI 밴드를 8BUI 등등으로 변환하십시오.
  • ST_ReclassExact - Creates a new raster composed of bands reclassified from original, using a 1:1 mapping from values in the original band to new values in the destination band.
  • ST_Resample - 특정 리샘플링 알고리즘, 새로운 차원, 임의의 그리드 모서리, 그리고 또 다른 래스터에서 정의되거나 빌려온 래스터 지리참조 속성들의 집합을 이용해서 래스터를 리샘플링합니다.
  • ST_Rescale - Resample a raster by adjusting only its scale (or pixel size). New pixel values are computed using the NearestNeighbor (english or american spelling), Bilinear, Cubic, CubicSpline, Lanczos, Max or Min resampling algorithm. Default is NearestNeighbor.
  • ST_Resize - 래스터의 크기를 새 너비/높이로 조정합니다.
  • ST_Reskew - 기울기(또는 회전각 파라미터)만 조정해서 래스터를 리샘플링합니다. NearestNeighbor(영국 또는 미국 철자), Bilinear, Cubic, CubicSpline 또는 Lanczos 리샘플링 알고리즘을 이용해서 새 픽셀 값을 계산합니다. 기본값은 NearestNeighbor입니다.
  • ST_Rotation - 래스터의 회전각을 라디안으로 반환합니다.
  • ST_Roughness - DEM의 계산된 "거칠기(roughness)"와 함께 래스터를 반환합니다.
  • ST_SRID - spatial_ref_sys 테이블에 정의되어 있는, 래스터의 공간 참조 식별자를 반환합니다.
  • ST_SameAlignment - 래스터들이 동일한 기울기, 축척, 공간 참조 시스템, 그리고 오프셋을 가지고 있을 경우 (픽셀이 다른 픽셀을 침범하지 않고 동일한 그리드에 놓일 수 있을 경우) 참을 반환하고, 그렇지 않을 경우 문제점을 설명하는 안내문과 함께 거짓을 반환합니다.
  • ST_ScaleX - 픽셀 너비의 X 요소를 좌표 참조 시스템의 단위로 반환합니다.
  • ST_ScaleY - 픽셀 높이의 Y 요소를 좌표 참조 시스템의 단위로 반환합니다.
  • ST_SetBandIndex - Update the external band number of an out-db band
  • ST_SetBandIsNoData - 밴드의 isnodata 플래그를 참으로 설정합니다.
  • ST_SetBandNoDataValue - NODATA를 나타내는 입력 밴드의 값을 설정합니다. 밴드를 따로 설정하지 않을 경우 밴드 1로 가정합니다. 밴드에 NODATA가 없다고 표시하려면, nodata value = NULL이라고 설정하십시오.
  • ST_SetBandPath - Update the external path and band number of an out-db band
  • ST_SetGeoReference - 단일 호출로 지리참조 파라미터 6개를 설정합니다. 숫자를 공백으로 구분해야 합니다. GDAL 또는 ESRI 서식의 입력물을 받아들입니다. 기본값은 GDAL입니다.
  • ST_SetM - Returns a geometry with the same X/Y coordinates as the input geometry, and values from the raster copied into the M dimension using the requested resample algorithm.
  • ST_SetRotation - 래스터의 회전각을 라디안으로 설정합니다.
  • ST_SetSRID - 래스터의 SRID를 spatial_ref_sys 테이블에 정의된 특정 SRID의 정수값으로 설정합니다.
  • ST_SetScale - X 및 Y 픽셀 크기를 좌표 참조 시스템의 단위로 설정합니다. 단위/픽셀 너비/픽셀 높이 순서입니다.
  • ST_SetSkew - 지리참조 X 및 Y 기울기(skew)(또는 회전각 파라미터)를 설정합니다. 값 하나만 입력할 경우, X와 Y를 동일한 값으로 설정합니다.
  • ST_SetUpperLeft - Sets the value of the upper left corner of the pixel of the raster to projected X and Y coordinates.
  • ST_SetValue - 입력한 columnx, rowy 픽셀 또는 특정 도형과 교차하는 픽셀들의 위치의 밴드 값을 설정해서 나온 수정된 래스터를 반환합니다. 밴드 번호는 1부터 시작하며, 따로 설정하지 않을 경우 1로 가정합니다.
  • ST_SetValues - 지정한 밴드의 값들을 설정해서 나온 수정된 래스터를 반환합니다.
  • ST_SetZ - Returns a geometry with the same X/Y coordinates as the input geometry, and values from the raster copied into the Z dimension using the requested resample algorithm.
  • ST_SkewX - 지리참조 X 기울기(skew)(또는 회전각 파라미터)를 반환합니다.
  • ST_SkewY - 지리참조 Y 기울기(또는 회전각 파라미터)를 반환합니다.
  • ST_Slope - 표고 래스터 밴드의 경사(기본 단위는 도)를 반환합니다. 지형을 분석하는 데 유용합니다.
  • ST_SnapToGrid - 그리드에 래스터를 스냅시켜서 래스터를 리샘플링합니다. NearestNeighbor(영국 또는 미국 철자), Bilinear, Cubic, CubicSpline 또는 Lanczos 리샘플링 알고리즘을 이용해서 새 픽셀 값을 계산합니다. 기본값은 NearestNeighbor입니다.
  • ST_Summary - 래스터의 내용을 요약한 텍스트를 반환합니다.
  • ST_SummaryStats - Returns summarystats consisting of count, sum, mean, stddev, min, max for a given raster band of a raster or raster coverage. Band 1 is assumed if no band is specified.
  • ST_SummaryStatsAgg - Aggregate. Returns summarystats consisting of count, sum, mean, stddev, min, max for a given raster band of a set of raster. Band 1 is assumed if no band is specified.
  • ST_TPI - 계산된 지형위치지수(Topographic Position Index)와 함께 래스터를 반환합니다.
  • ST_TRI - 계산된 지형험준도지수(Terrain Ruggedness Index)와 함께 래스터를 반환합니다.
  • ST_Tile - 출력 래스터에 원하는 차원을 바탕으로 입력 래스터를 분할해서 나온 래스터들의 집합을 반환합니다.
  • ST_Touches - 래스터 rastA와 래스터 rastB가 최소한 포인트 한 개를 공유하지만, 내부가 교차하지는 않을 경우 TRUE 를 반환합니다.
  • ST_Transform - 알려진 공간 참조 시스템의 래스터를 지정한 리샘플링 알고리즘을 통해 또 다른 알려진 공간 참조 시스템으로 재투영합니다. NearestNeighbor, Bilinear, Cubic, CubicSpline, Lanczos 알고리즘을 이용할 수 있습니다. 기본값은 NearestNeighbor입니다.
  • ST_Union - 래스터 타일 집합을 1개 이상의 밴드로 이루어진 단일 래스터로 통합합니다.
  • ST_UpperLeftX - 래스터의 좌상단 X 좌표를 투영된 공간 참조 단위로 반환합니다.
  • ST_UpperLeftY - 래스터의 좌상단 Y 좌표를 투영된 공간 참조 단위로 반환합니다.
  • ST_Value - 입력 columnx, rowy 픽셀의 입력 밴드의 값, 또는 특정 기하학적 포인트의 밴드의 값을 반환합니다. 밴드 번호는 1부터 시작하며, 따로 지정하지 않을 경우 1로 가정합니다. exclude_nodata_value 를 거짓으로 설정할 경우, nodata 픽셀을 포함한 모든 픽셀이 교차한다고 가정하고 값을 반환합니다. exclude_nodata_value 를 설정하지 않은 경우, 래스터의 메타데이터에서 값을 읽어 들입니다.
  • ST_ValueCount - 설정한 값들의 집합을 가진 래스터(또는 래스터 커버리지)의 입력 밴드에 있는 픽셀 밴드 값 및 픽셀 개수의 집계를 담고 있는 레코드 집합을 반환합니다. 밴드를 따로 설정하지 않을 경우 기본값은 밴드 1입니다. 기본적으로 NODATA 값은 집계되지 않습니다. 픽셀의 다른 모든 값들을 출력하는데, 픽셀 밴드 값은 가장 가까운 정수로 반올림됩니다.
  • ST_Width - 래스터의 너비를 픽셀 개수로 반환합니다.
  • ST_Within - 래스터 rastB 외부에 놓인 래스터 rastA의 포인트가 하나도 없고, 적어도 rastA 내부의 포인트 하나가 rastB의 내부에 있는 경우 참을 반환합니다.
  • ST_WorldToRasterCoord - 주어진 기하학적 X, Y(경도, 위도)의 좌상단을 열과 행으로 또는 래스터의 공간 참조 좌표 시스템 단위로 표현된 포인트 도형으로 반환합니다.
  • ST_WorldToRasterCoordX - 포인트 도형(pt)의 래스터 안의 열 또는 래스터의 월드 공간 참조 시스템 단위로 표현된 X, Y 월드 좌표(xw, yw)를 반환합니다.
  • ST_WorldToRasterCoordY - 포인트 도형(pt)의 래스터 안의 행 또는 래스터의 월드 공간 참조 시스템 단위로 표현된 X, Y 월드 좌표(xw, yw)를 반환합니다.
  • UpdateRasterSRID - 사용자가 지정한 열 및 테이블에 있는 모든 래스터의 SRID를 변경합니다.

13.6. PostGIS Geometry / Geography / Raster Dump Functions

The functions given below are PostGIS functions that take as input or return as output a set of or single geometry_dump or geomval data type object.

  • ST_DumpAsPolygons - 입력 래스터 밴드로부터 geomval(geom, val) 행들의 집합을 반환합니다. 밴드 번호를 설정하지 않을 경우 기본적으로 밴드 1로 가정합니다.
  • ST_Intersection - 두 래스터의 공유 부분을 표현하는, 또는 벡터화된 래스터와 도형의 기하학적 교차를 표현하는 래스터 또는 도형-픽셀값 쌍의 집합을 반환합니다.
  • ST_Dump - Returns a set of geometry_dump rows for the components of a geometry.
  • ST_DumpPoints - 도형의 내용을 요약한 텍스트를 반환합니다.
  • ST_DumpRings - Returns a set of geometry_dump rows for the exterior and interior rings of a Polygon.
  • ST_DumpSegments - 도형의 내용을 요약한 텍스트를 반환합니다.

13.7. PostGIS Box Functions

The functions given below are PostGIS functions that take as input or return as output the box* family of PostGIS spatial types. The box family of types consists of box2d, and box3d

  • Box2D - Returns a BOX2D representing the 2D extent of a geometry.
  • Box3D - Returns a BOX3D representing the 3D extent of a geometry.
  • MakeTopologyPrecise - Snap topology vertices to precision grid.
  • Box3D - 래스터를 둘러싼 상자의 BOX3D 표현식을 반환합니다.
  • ST_3DExtent - Aggregate function that returns the 3D bounding box of geometries.
  • ST_3DMakeBox - Creates a BOX3D defined by two 3D point geometries.
  • ST_AsMVTGeom - Transforms a geometry into the coordinate space of a MVT tile.
  • ST_AsTWKB - 도형을 TWKB(Tiny Well-Known Binary)로 반환합니다.
  • ST_Box2dFromGeoHash - GeoHash 스트링으로부터 BOX2D를 반환합니다.
  • ST_ClipByBox2D - Computes the portion of a geometry falling within a rectangle.
  • ST_EstimatedExtent - Returns the estimated extent of a spatial table.
  • ST_Expand - Returns a bounding box expanded from another bounding box or a geometry.
  • ST_Extent - Aggregate function that returns the bounding box of geometries.
  • ST_MakeBox2D - Creates a BOX2D defined by two 2D point geometries.
  • ST_RemoveIrrelevantPointsForView - Removes points that are irrelevant for rendering a specific rectangular view of a geometry.
  • ST_XMax - Returns the X maxima of a 2D or 3D bounding box or a geometry.
  • ST_XMin - Returns the X minima of a 2D or 3D bounding box or a geometry.
  • ST_XSize - Returns the X size of a 2D or 3D bounding box or a geometry.
  • ST_YMax - Returns the Y maxima of a 2D or 3D bounding box or a geometry.
  • ST_YMin - Returns the Y minima of a 2D or 3D bounding box or a geometry.
  • ST_YSize - Returns the Y size of a 2D or 3D bounding box or a geometry.
  • ST_ZMax - Returns the Z maxima of a 2D or 3D bounding box or a geometry.
  • ST_ZMin - Returns the Z minima of a 2D or 3D bounding box or a geometry.
  • ST_ZSize - Returns the Z size of a 2D or 3D bounding box or a geometry.
  • RemoveUnusedPrimitives - Removes topology primitives which not needed to define existing TopoGeometry objects.
  • ValidateTopology - Returns a set of validatetopology_returntype objects detailing issues with topology.
  • ValidateTopologyPrecision - Returns non-precise vertices in the topology.
  • ~(box2df,box2df) - Returns TRUE if a 2D float precision bounding box (BOX2DF) contains another 2D float precision bounding box (BOX2DF).
  • ~(box2df,geometry) - Returns TRUE if a 2D float precision bounding box (BOX2DF) contains a geometry's 2D bonding box.
  • ~(geometry,box2df) - Returns TRUE if a geometry's 2D bonding box contains a 2D float precision bounding box (GIDX).
  • @(box2df,box2df) - Returns TRUE if a 2D float precision bounding box (BOX2DF) is contained into another 2D float precision bounding box.
  • @(box2df,geometry) - Returns TRUE if a 2D float precision bounding box (BOX2DF) is contained into a geometry's 2D bounding box.
  • @(geometry,box2df) - Returns TRUE if a geometry's 2D bounding box is contained into a 2D float precision bounding box (BOX2DF).
  • &&(box2df,box2df) - Returns TRUE if two 2D float precision bounding boxes (BOX2DF) intersect each other.
  • &&(box2df,geometry) - Returns TRUE if a 2D float precision bounding box (BOX2DF) intersects a geometry's (cached) 2D bounding box.
  • &&(geometry,box2df) - Returns TRUE if a geometry's (cached) 2D bounding box intersects a 2D float precision bounding box (BOX2DF).

13.8. PostGIS Functions that support 3D

The functions given below are PostGIS functions that do not throw away the Z-Index.

  • AddGeometryColumn - 공간 테이블에서 지오메트리 컬럼을 제거합니다.
  • Box3D - Returns a BOX3D representing the 3D extent of a geometry.
  • CG_3DAlphaWrapping - Computes a 3D Alpha-wrapping strictly enclosing a geometry.
  • CG_3DArea - 3차원 표면 도형의 면적을 계산합니다. 입체일 경우 0을 반환할 것입니다.
  • CG_3DConvexHull - 면 도형의 근사 중심축을 계산합니다.
  • CG_3DDifference - 3차원 차이를 수행합니다.
  • CG_3DIntersection - 3차원 교차를 수행합니다.
  • CG_3DRotate - Rotates a geometry in 3D space around an axis vector.
  • CG_3DScale - Scales a geometry by separate factors along X, Y, and Z axes.
  • CG_3DScaleAroundCenter - Scales a geometry in 3D space around a specified center point.
  • CG_3DTranslate - Translates (moves) a geometry by given offsets in 3D space.
  • CG_3DUnion - Perform 3D union using postgis_sfcgal.
  • CG_ConstrainedDelaunayTriangles - Return a constrained Delaunay triangulation around the given input geometry.
  • CG_Extrude - 표면을 관련 입체로 돌출시킵니다.
  • CG_ForceLHR - LHR(Left Hand Reverse; 시계 방향) 방향을 강제합니다.
  • CG_IsPlanar - 표면이 평면인지 아닌지 확인합니다.
  • CG_IsSolid - 도형이 입체인지 테스트합니다. 어떤 유효성 검사도 수행하지 않습니다.
  • CG_MakeSolid - 도형을 입체로 지정합니다. 어떤 확인 작업도 수행하지 않습니다. 유효한 입체를 얻으려면, 입력 도형이 닫힌 다면체 표면 또는 닫힌 TIN이어야만 합니다.
  • CG_NurbsCurveApproximate - Creates an approximating NURBS curve fitting data points within a tolerance
  • CG_NurbsCurveDerivative - Computes the derivative (tangent, curvature) of a NURBS curve at a given parameter
  • CG_NurbsCurveInterpolate - Creates an interpolating NURBS curve passing through all given data points
  • CG_Orientation - 표면의 방향(orientation)을 결정합니다.
  • CG_RotateX - Rotates a geometry around the X-axis by a given angle.
  • CG_RotateY - Rotates a geometry around the Y-axis by a given angle.
  • CG_RotateZ - Rotates a geometry around the Z-axis by a given angle.
  • CG_Simplify - Reduces the complexity of a geometry while preserving essential features and Z/M values.
  • CG_StraightSkeleton - 도형으로부터 직선 골격(straight skeleton)을 계산합니다.
  • CG_Tesselate - 폴리곤 또는 다면체 표면의 표면 다듬기(tessellation) 작업을 수행한 다음 TIN 또는 TIN 집합으로 반환합니다.
  • CG_Visibility - Compute a visibility polygon from a point or a segment in a polygon geometry
  • CG_Volume - Computes the volume of a 3D geometry. Closed surfaces can have non-zero volume.
  • DropGeometryColumn - 공간 테이블에서 지오메트리 컬럼을 제거합니다.
  • GeometryType - ST_Geometry 값의 도형 유형을 반환합니다.
  • ST_3DClosestPoint - g2에 가장 가까운 g1 상에 있는 3차원 포인트를 반환합니다. 해당 포인트는 3D 최단 라인의 첫 번째 포인트입니다.
  • ST_3DDFullyWithin - Tests if two 3D geometries are entirely within a given 3D distance
  • ST_3DDWithin - Tests if two 3D geometries are within a given 3D distance
  • ST_3DDistance - 도형 유형에 대해, 두 도형 사이의 (SRS에 기반한) 3차원 데카르트 최단 거리를 투영 단위로 반환합니다.
  • ST_3DExtent - Aggregate function that returns the 3D bounding box of geometries.
  • ST_3DInterpolatePoint - Returns the interpolated measure of a geometry closest to a point in 3D.
  • ST_3DIntersects - Tests if two geometries spatially intersect in 3D - only for points, linestrings, polygons, polyhedral surface (area)
  • ST_3DLength - 도형의 기하학적 중심을 반환합니다.
  • ST_3DLineInterpolatePoint - Returns a point interpolated along a 3D line at a fractional location.
  • ST_3DLongestLine - 두 도형 사이의 3차원 최장(longest) 라인을 반환합니다.
  • ST_3DMaxDistance - 도형 유형에 대해, 두 도형 사이의 (SRS에 기반한) 3차원 데카르트 최장 거리를 투영 단위로 반환합니다.
  • ST_3DPerimeter - 도형의 기하학적 중심을 반환합니다.
  • ST_3DShortestLine - 두 도형 사이의 3차원 최단(shortest) 라인을 반환합니다.
  • ST_AddMeasure - Interpolates measures along a linear geometry.
  • ST_AddPoint - 라인스트링에 포인트를 추가합니다.
  • ST_Affine - Apply a 3D affine transformation to a geometry.
  • ST_AsBinary - Return the OGC/ISO Well-Known Binary (WKB) representation of the geometry/geography without SRID meta data.
  • ST_AsEWKB - Return the Extended Well-Known Binary (EWKB) representation of the geometry with SRID meta data.
  • ST_AsEWKT - 도형의 WKT(Well-Known Text) 표현식을 SRID 메타데이터와 함께 반환합니다.
  • ST_AsGML - 도형을 GML 2 또는 GML 3 버전 요소로 반환합니다.
  • ST_AsGeoJSON - Return a geometry or feature in GeoJSON format.
  • ST_AsHEXEWKB - 도형을 소 엔디안(NDR) 또는 대 엔디안(XDR) 인코딩을 통해 HEXEWKB (텍스트) 형식으로 반환합니다.
  • ST_AsKML - 도형을 GML 2 또는 GML 3 버전 요소로 반환합니다.
  • ST_AsX3D - 도형을 X3D XML 노드 요소 형식: ISO-IEC-19776-1.2-X3DEncodings-XML로 반환합니다.
  • ST_Boundary - 해당 도형의 결합된 범위의 닫힘 여부를 반환합니다.
  • ST_BoundingDiagonal - 주어진 도형의 경계 상자의 대각선을 반환합니다.
  • ST_CPAWithin - Tests if the closest point of approach of two trajectories is within the specified distance.
  • ST_CatmullRomSmoothing - Returns a smoothed version of a geometry, using the Catmull-Rom spline algorithm
  • ST_ChaikinSmoothing - Returns a smoothed version of a geometry, using the Chaikin algorithm
  • ST_ClosestPointOfApproach - Returns a measure at the closest point of approach of two trajectories.
  • ST_Collect - Creates a GeometryCollection or Multi* geometry from a set of geometries.
  • ST_ConvexHull - Computes the convex hull of a geometry.
  • ST_CoordDim - ST_Geometry 값의 좌표 차원을 반환합니다.
  • ST_CurveN - Returns the Nth component curve geometry of a CompoundCurve.
  • ST_CurveToLine - Converts a geometry containing curves to a linear geometry.
  • ST_DelaunayTriangles - Returns the Delaunay triangulation of the vertices of a geometry.
  • ST_Difference - Computes a geometry representing the part of geometry A that does not intersect geometry B.
  • ST_DistanceCPA - Returns the distance between the closest point of approach of two trajectories.
  • ST_Dump - Returns a set of geometry_dump rows for the components of a geometry.
  • ST_DumpPoints - 도형의 내용을 요약한 텍스트를 반환합니다.
  • ST_DumpRings - Returns a set of geometry_dump rows for the exterior and interior rings of a Polygon.
  • ST_DumpSegments - 도형의 내용을 요약한 텍스트를 반환합니다.
  • ST_EndPoint - Returns the last point of a LineString, CircularLineString, or NURBSCurve.
  • ST_ExteriorRing - 폴리곤 도형의 내곽 고리의 개수를 반환합니다.
  • ST_FlipCoordinates - Returns a version of a geometry with X and Y axis flipped.
  • ST_Force2D - 도형을 "2차원 모드"로 강제합니다.
  • ST_ForceCurve - 적용이 가능한 경우, 도형을 해당 도형의 만곡 유형으로 상위 형변환(upcast)합니다.
  • ST_ForcePolygonCCW - Orients all exterior rings counter-clockwise and all interior rings clockwise.
  • ST_ForcePolygonCW - Orients all exterior rings clockwise and all interior rings counter-clockwise.
  • ST_ForceRHR - 폴리곤 안에 있는 꼭짓점들의 방향(orientation)이 오른손 법칙(Right-Hand Rule)을 따르도록 강제합니다.
  • ST_ForceSFS - Force geometries to use SFS 1.1 or 1.2 geometry types.
  • ST_Force3D - 도형을 XYZ 모드로 강제합니다. ST_Force3DZ라고도 합니다.
  • ST_Force3DZ - 도형을 XYZ 모드로 강제합니다.
  • ST_Force4D - 도형을 XYZM 모드로 강제합니다.
  • ST_ForceCollection - 도형을 도형 집합으로 변환합니다.
  • ST_GeomFromEWKB - EWKB(Extended Well-Known Binary)로부터 지정된 ST_Geometry 값을 반환합니다.
  • ST_GeomFromEWKT - EWKT(Extended Well-Known Text)로부터 지정된 ST_Geometry 값을 반환합니다.
  • ST_GeomFromGML - 도형의 GML 표현식을 입력받아 PostGIS 도형 객체를 출력합니다.
  • ST_GeomFromGeoJSON - GeoJSON 표현식을 입력받아 PostGIS 도형 객체를 출력합니다.
  • ST_GeomFromKML - 도형의 KML 표현식을 입력받아 PostGIS 도형 객체를 출력합니다.
  • ST_GeometricMedian - 멀티 포인트의 기하학적 중심값(median)을 반환합니다.
  • ST_GeometryN - ST_Geometry 값의 도형 유형을 반환합니다.
  • ST_GeometryType - ST_Geometry 값의 도형 유형을 반환합니다.
  • ST_HasArc - Tests if a geometry contains a circular arc
  • ST_HasM - Checks if a geometry has an M (measure) dimension.
  • ST_HasZ - Checks if a geometry has a Z dimension.
  • ST_InteriorRingN - 폴리곤 도형의 내곽 고리의 개수를 반환합니다.
  • ST_InterpolatePoint - 입력 포인트에 가까운 포인트에서 도형의 척도 차원(M 차원)의 값을 반환합니다.
  • ST_Intersection - Computes a geometry representing the shared portion of geometries A and B.
  • ST_IsClosed - LINESTRING 의 시작점과 종단점이 일치하는 경우 TRUE 를 반환합니다. 다면체 표면이 닫혀 (부피를 가지고) 있는 경우 TRUE 를 반환합니다.
  • ST_IsCollection - 해당 도형이 텅 빈 도형 집합, 폴리곤, 포인트 등인 경우 TRUE 를 반환합니다.
  • ST_IsPolygonCCW - Tests if Polygons have exterior rings oriented counter-clockwise and interior rings oriented clockwise.
  • ST_IsPolygonCW - Tests if Polygons have exterior rings oriented clockwise and interior rings oriented counter-clockwise.
  • ST_IsSimple - 해당 도형이 자체 교차하거나 자체 접촉하는 이례적인 도형 포인트를 가지고 있지 않을 경우 TRUE 를 반환합니다.
  • ST_IsValidTrajectory - Tests if the geometry is a valid trajectory.
  • ST_LengthSpheroid - 도형의 기하학적 중심을 반환합니다.
  • ST_LineFromMultiPoint - 멀티포인트 도형으로부터 라인스트링을 생성합니다.
  • ST_LineInterpolatePoint - Returns a point interpolated along a line at a fractional location.
  • ST_LineInterpolatePoints - Returns points interpolated along a line at a fractional interval.
  • ST_LineSubstring - Returns the part of a line between two fractional locations.
  • ST_LineToCurve - Converts a linear geometry to a curved geometry.
  • ST_LocateBetweenElevations - Returns the portions of a geometry that lie in an elevation (Z) range.
  • ST_M - Returns the M coordinate of a Point.
  • ST_MMax - Returns the M maxima of a geometry.
  • ST_MMin - Returns the M minima of a geometry.
  • ST_MSize - Returns the M size of a geometry.
  • ST_MakeLine - 포인트, 멀티포인트 또는 라인 도형으로부터 라인스트링을 생성합니다.
  • ST_MakePoint - Creates a 2D, 3DZ or 4D Point.
  • ST_MakePolygon - Creates a Polygon or CurvePolygon from a shell and optional list of holes.
  • ST_MakeValid - Attempts to make an invalid geometry valid without losing vertices.
  • ST_MemSize - ST_Geometry 값의 도형 유형을 반환합니다.
  • ST_MemUnion - Aggregate function which unions geometries in a memory-efficent but slower way
  • ST_NDims - ST_Geometry 값의 좌표 차원을 반환합니다.
  • ST_NPoints - 도형이 가지고 있는 포인트(꼭짓점)의 개수를 반환합니다.
  • ST_NRings - 폴리곤 도형의 내곽 고리의 개수를 반환합니다.
  • ST_Node - Nodes a collection of lines.
  • ST_NumCurves - Return the number of component curves in a CompoundCurve.
  • ST_NumGeometries - 도형이 가지고 있는 포인트의 개수를 반환합니다. 모든 도형을 입력받을 수 있습니다.
  • ST_NumPatches - Returns the number of faces in a PolyhedralSurface or TIN.
  • ST_PatchN - Returns the Nth face of a PolyhedralSurface or TIN.
  • ST_PointFromWKB - 주어진 SRID와 함께 WKB로부터 도형을 만듭니다.
  • ST_PointN - ST_LineString 또는 ST_CircularString 값에 있는 포인트의 개수를 반환합니다.
  • ST_PointOnSurface - Computes a point guaranteed to lie in a polygon, or on a geometry.
  • ST_Points - 도형의 모든 좌표들을 담고 있는 멀티포인트를 반환합니다.
  • ST_Polygon - Creates a Polygon from a LineString with a specified SRID.
  • ST_RemovePoint - Remove a point from a linestring.
  • ST_RemoveRepeatedPoints - Returns a version of a geometry with duplicate points removed.
  • ST_Reverse - 꼭짓점들의 순서가 반대인 도형을 반환합니다.
  • ST_Rotate - Rotates a geometry about an origin point.
  • ST_RotateX - Rotates a geometry about the X axis.
  • ST_RotateY - Rotates a geometry about the Y axis.
  • ST_RotateZ - Rotates a geometry about the Z axis.
  • ST_Scale - Scales a geometry by given factors.
  • ST_Scroll - Change start point of a closed LineString.
  • ST_SetPoint - 라인스트링의 포인트를 주어진 포인트로 대체합니다.
  • ST_ShiftLongitude - Shifts the longitude coordinates of a geometry between -180..180 and 0..360.
  • ST_SnapToGrid - 입력 도형의 모든 포인트를 정규 그리드로 스냅(snap)시킵니다.
  • ST_StartPoint - Returns the first point of a LineString, CircularLineString, or NURBSCurve.
  • ST_SwapOrdinates - 입력 도형을 좌표값을 뒤바꾼 상태로 반환합니다.
  • ST_SymDifference - Computes a geometry representing the portions of geometries A and B that do not intersect.
  • ST_TransScale - Translates and scales a geometry by given offsets and factors.
  • ST_Translate - Translates a geometry by given offsets.
  • ST_UnaryUnion - Computes the union of the components of a single geometry.
  • ST_Union - Computes a geometry representing the point-set union of the input geometries.
  • ST_WrapX - X값 근처에서 도형을 래핑합니다.
  • ST_X - Returns the X coordinate of a Point.
  • ST_XMax - Returns the X maxima of a 2D or 3D bounding box or a geometry.
  • ST_XMin - Returns the X minima of a 2D or 3D bounding box or a geometry.
  • ST_XSize - Returns the X size of a 2D or 3D bounding box or a geometry.
  • ST_Y - Returns the Y coordinate of a Point.
  • ST_YMax - Returns the Y maxima of a 2D or 3D bounding box or a geometry.
  • ST_YMin - Returns the Y minima of a 2D or 3D bounding box or a geometry.
  • ST_YSize - Returns the Y size of a 2D or 3D bounding box or a geometry.
  • ST_Z - Returns the Z coordinate of a Point.
  • ST_ZMFlag - ST_Geometry 값의 좌표 차원을 반환합니다.
  • ST_ZMax - Returns the Z maxima of a 2D or 3D bounding box or a geometry.
  • ST_ZMin - Returns the Z minima of a 2D or 3D bounding box or a geometry.
  • ST_ZSize - Returns the Z size of a 2D or 3D bounding box or a geometry.
  • Equals - 두 TopoGeometry가 동일한 지형 원시형으로 이루어졌을 경우 참을 반환합니다.
  • Intersects - 두 TopoGeometry에서 나온 원시형의 쌍 가운데 하나라도 교차할 경우 참을 반환합니다.
  • UpdateGeometrySRID - Updates the SRID of all features in a geometry column, and the table metadata.
  • &&& - A의 n차원 경계 상자와 B의 n차원 경계 상자가 교차하는 경우 TRUE 를 반환합니다.
  • &&&(geometry,gidx) - Returns TRUE if a geometry's (cached) n-D bounding box intersects a n-D float precision bounding box (GIDX).
  • &&&(gidx,geometry) - Returns TRUE if a n-D float precision bounding box (GIDX) intersects a geometry's (cached) n-D bounding box.
  • &&&(gidx,gidx) - Returns TRUE if two n-D float precision bounding boxes (GIDX) intersect each other.

13.9. PostGIS Curved Geometry Support Functions

The functions given below are PostGIS functions that can use CIRCULARSTRING, CURVEPOLYGON, and other curved geometry types

  • AddGeometryColumn - 공간 테이블에서 지오메트리 컬럼을 제거합니다.
  • Box2D - Returns a BOX2D representing the 2D extent of a geometry.
  • Box3D - Returns a BOX3D representing the 3D extent of a geometry.
  • DropGeometryColumn - 공간 테이블에서 지오메트리 컬럼을 제거합니다.
  • GeometryType - ST_Geometry 값의 도형 유형을 반환합니다.
  • PostGIS_AddBBox - 도형에 경계 상자를 추가합니다.
  • PostGIS_DropBBox - 도형으로부터 경계 상자 캐시를 삭제합니다.
  • PostGIS_HasBBox - 해당 도형의 경계 상자가 캐시화된 경우 참을 반환하고, 그렇지 않을 경우 거짓을 반환합니다.
  • ST_3DExtent - Aggregate function that returns the 3D bounding box of geometries.
  • ST_Affine - Apply a 3D affine transformation to a geometry.
  • ST_AsBinary - Return the OGC/ISO Well-Known Binary (WKB) representation of the geometry/geography without SRID meta data.
  • ST_AsEWKB - Return the Extended Well-Known Binary (EWKB) representation of the geometry with SRID meta data.
  • ST_AsEWKT - 도형의 WKT(Well-Known Text) 표현식을 SRID 메타데이터와 함께 반환합니다.
  • ST_AsHEXEWKB - 도형을 소 엔디안(NDR) 또는 대 엔디안(XDR) 인코딩을 통해 HEXEWKB (텍스트) 형식으로 반환합니다.
  • ST_AsSVG - Returns SVG path data for a geometry.
  • ST_AsText - 도형/지리형의 WKT(Well-Known Text) 표현식을 SRID 메타데이터 없이 반환합니다.
  • ST_ClusterDBSCAN - Window function that returns a cluster id for each input geometry using the DBSCAN algorithm.
  • ST_ClusterWithin - Aggregate function that clusters geometries by separation distance.
  • ST_ClusterWithinWin - Window function that returns a cluster id for each input geometry, clustering using separation distance.
  • ST_Collect - Creates a GeometryCollection or Multi* geometry from a set of geometries.
  • ST_CoordDim - ST_Geometry 값의 좌표 차원을 반환합니다.
  • ST_CurveToLine - Converts a geometry containing curves to a linear geometry.
  • ST_Distance - 두 도형 사이의 3차원 최장(longest) 라인을 반환합니다.
  • ST_Dump - Returns a set of geometry_dump rows for the components of a geometry.
  • ST_DumpPoints - 도형의 내용을 요약한 텍스트를 반환합니다.
  • ST_EndM - Returns the M coordinate of the last point of a LineString, CircularLineString, or NURBSCurve.
  • ST_EndPoint - Returns the last point of a LineString, CircularLineString, or NURBSCurve.
  • ST_EstimatedExtent - Returns the estimated extent of a spatial table.
  • ST_FlipCoordinates - Returns a version of a geometry with X and Y axis flipped.
  • ST_Force2D - 도형을 "2차원 모드"로 강제합니다.
  • ST_ForceCurve - 적용이 가능한 경우, 도형을 해당 도형의 만곡 유형으로 상위 형변환(upcast)합니다.
  • ST_ForceSFS - Force geometries to use SFS 1.1 or 1.2 geometry types.
  • ST_Force3D - 도형을 XYZ 모드로 강제합니다. ST_Force3DZ라고도 합니다.
  • ST_Force3DM - 도형을 XYM 모드로 강제합니다.
  • ST_Force3DZ - 도형을 XYZ 모드로 강제합니다.
  • ST_Force4D - 도형을 XYZM 모드로 강제합니다.
  • ST_ForceCollection - 도형을 도형 집합으로 변환합니다.
  • ST_GeoHash - 도형의 GeoHash 표현식을 반환합니다.
  • ST_GeogFromWKB - WKB 도형 표현식 또는 EWKB(확장 WKB)로부터 지리형 인스턴스를 생성합니다.
  • ST_GeomFromEWKB - EWKB(Extended Well-Known Binary)로부터 지정된 ST_Geometry 값을 반환합니다.
  • ST_GeomFromEWKT - EWKT(Extended Well-Known Text)로부터 지정된 ST_Geometry 값을 반환합니다.
  • ST_GeomFromText - WKT 표현식으로부터 지정된 ST_Geometry 값을 반환합니다.
  • ST_GeomFromWKB - WKB(Well-Known Binary) 도형 표현식과 선택적인 SRID로부터 도형 인스턴스를 생성합니다.
  • ST_GeometryN - ST_Geometry 값의 도형 유형을 반환합니다.
  • = - Returns TRUE if the coordinates and coordinate order geometry/geography A are the same as the coordinates and coordinate order of geometry/geography B.
  • &<| - A의 경계 상자가 B의 경계 상자와 겹치거나 그 아래에 있을 경우 TRUE 를 반환합니다.
  • ST_HasArc - Tests if a geometry contains a circular arc
  • ST_Intersects - Tests if two geometries intersect (they have at least one point in common)
  • ST_IsClosed - LINESTRING 의 시작점과 종단점이 일치하는 경우 TRUE 를 반환합니다. 다면체 표면이 닫혀 (부피를 가지고) 있는 경우 TRUE 를 반환합니다.
  • ST_IsCollection - 해당 도형이 텅 빈 도형 집합, 폴리곤, 포인트 등인 경우 TRUE 를 반환합니다.
  • ST_IsEmpty - Tests if a geometry is empty.
  • ST_LineToCurve - Converts a linear geometry to a curved geometry.
  • ST_MMax - Returns the M maxima of a geometry.
  • ST_MMin - Returns the M minima of a geometry.
  • ST_MSize - Returns the M size of a geometry.
  • ST_MemSize - ST_Geometry 값의 도형 유형을 반환합니다.
  • ST_NPoints - 도형이 가지고 있는 포인트(꼭짓점)의 개수를 반환합니다.
  • ST_NRings - 폴리곤 도형의 내곽 고리의 개수를 반환합니다.
  • ST_PointFromWKB - 주어진 SRID와 함께 WKB로부터 도형을 만듭니다.
  • ST_PointN - ST_LineString 또는 ST_CircularString 값에 있는 포인트의 개수를 반환합니다.
  • ST_Points - 도형의 모든 좌표들을 담고 있는 멀티포인트를 반환합니다.
  • ST_Rotate - Rotates a geometry about an origin point.
  • ST_RotateZ - Rotates a geometry about the Z axis.
  • ST_SRID - Returns the spatial reference identifier for a geometry.
  • ST_Scale - Scales a geometry by given factors.
  • ST_SetEndM - Sets the M coordinate of the last point of a LineString, CircularLineString, or NURBSCurve.
  • ST_SetSRID - Set the SRID on a geometry.
  • ST_SetStartM - Sets the M coordinate of the first point of a LineString, CircularLineString, or NURBSCurve.
  • ST_StartM - Returns the M coordinate of the first point of a LineString, CircularLineString, or NURBSCurve.
  • ST_StartPoint - Returns the first point of a LineString, CircularLineString, or NURBSCurve.
  • ST_Summary - 도형의 내용을 요약한 텍스트를 반환합니다.
  • ST_SwapOrdinates - 입력 도형을 좌표값을 뒤바꾼 상태로 반환합니다.
  • ST_TransScale - Translates and scales a geometry by given offsets and factors.
  • ST_Transform - Return a new geometry with coordinates transformed to a different spatial reference system.
  • ST_Translate - Translates a geometry by given offsets.
  • ST_XMax - Returns the X maxima of a 2D or 3D bounding box or a geometry.
  • ST_XMin - Returns the X minima of a 2D or 3D bounding box or a geometry.
  • ST_XSize - Returns the X size of a 2D or 3D bounding box or a geometry.
  • ST_YMax - Returns the Y maxima of a 2D or 3D bounding box or a geometry.
  • ST_YMin - Returns the Y minima of a 2D or 3D bounding box or a geometry.
  • ST_YSize - Returns the Y size of a 2D or 3D bounding box or a geometry.
  • ST_ZMFlag - ST_Geometry 값의 좌표 차원을 반환합니다.
  • ST_ZMax - Returns the Z maxima of a 2D or 3D bounding box or a geometry.
  • ST_ZMin - Returns the Z minima of a 2D or 3D bounding box or a geometry.
  • ST_ZSize - Returns the Z size of a 2D or 3D bounding box or a geometry.
  • UpdateGeometrySRID - Updates the SRID of all features in a geometry column, and the table metadata.
  • ~(box2df,box2df) - Returns TRUE if a 2D float precision bounding box (BOX2DF) contains another 2D float precision bounding box (BOX2DF).
  • ~(box2df,geometry) - Returns TRUE if a 2D float precision bounding box (BOX2DF) contains a geometry's 2D bonding box.
  • ~(geometry,box2df) - Returns TRUE if a geometry's 2D bonding box contains a 2D float precision bounding box (GIDX).
  • && - A의 2D 경계 상자와 B의 2D 경계 상자가 교차하는 경우 TRUE 를 반환합니다.
  • &&& - A의 n차원 경계 상자와 B의 n차원 경계 상자가 교차하는 경우 TRUE 를 반환합니다.
  • @(box2df,box2df) - Returns TRUE if a 2D float precision bounding box (BOX2DF) is contained into another 2D float precision bounding box.
  • @(box2df,geometry) - Returns TRUE if a 2D float precision bounding box (BOX2DF) is contained into a geometry's 2D bounding box.
  • @(geometry,box2df) - Returns TRUE if a geometry's 2D bounding box is contained into a 2D float precision bounding box (BOX2DF).
  • &&(box2df,box2df) - Returns TRUE if two 2D float precision bounding boxes (BOX2DF) intersect each other.
  • &&(box2df,geometry) - Returns TRUE if a 2D float precision bounding box (BOX2DF) intersects a geometry's (cached) 2D bounding box.
  • &&(geometry,box2df) - Returns TRUE if a geometry's (cached) 2D bounding box intersects a 2D float precision bounding box (BOX2DF).
  • &&&(geometry,gidx) - Returns TRUE if a geometry's (cached) n-D bounding box intersects a n-D float precision bounding box (GIDX).
  • &&&(gidx,geometry) - Returns TRUE if a n-D float precision bounding box (GIDX) intersects a geometry's (cached) n-D bounding box.
  • &&&(gidx,gidx) - Returns TRUE if two n-D float precision bounding boxes (GIDX) intersect each other.

13.10. PostGIS Polyhedral Surface Support Functions

The functions given below are PostGIS functions that can use POLYHEDRALSURFACE, POLYHEDRALSURFACEM geometries

  • Box2D - Returns a BOX2D representing the 2D extent of a geometry.
  • Box3D - Returns a BOX3D representing the 3D extent of a geometry.
  • CG_3DArea - 3차원 표면 도형의 면적을 계산합니다. 입체일 경우 0을 반환할 것입니다.
  • CG_3DConvexHull - 면 도형의 근사 중심축을 계산합니다.
  • CG_3DDifference - 3차원 차이를 수행합니다.
  • CG_3DIntersection - 3차원 교차를 수행합니다.
  • CG_3DUnion - Perform 3D union using postgis_sfcgal.
  • CG_ApproximateMedialAxis - 면 도형의 근사 중심축을 계산합니다.
  • CG_Extrude - 표면을 관련 입체로 돌출시킵니다.
  • CG_ForceLHR - LHR(Left Hand Reverse; 시계 방향) 방향을 강제합니다.
  • CG_GenerateFlatRoof - Generate a flat (box) roof from a footprint polygon.
  • CG_GenerateGableRoof - Generate a gable roof from a footprint polygon.
  • CG_GenerateHippedRoof - Generate a hipped roof from a footprint polygon.
  • CG_GenerateRoof - Generate a roof of the requested type from a footprint polygon.
  • CG_GenerateSkillionRoof - Generate a skillion (single-slope) roof from a footprint polygon.
  • CG_IsPlanar - 표면이 평면인지 아닌지 확인합니다.
  • CG_IsSolid - 도형이 입체인지 테스트합니다. 어떤 유효성 검사도 수행하지 않습니다.
  • CG_MakeSolid - 도형을 입체로 지정합니다. 어떤 확인 작업도 수행하지 않습니다. 유효한 입체를 얻으려면, 입력 도형이 닫힌 다면체 표면 또는 닫힌 TIN이어야만 합니다.
  • CG_PolygonRepair - Repair an invalid polygon or multipolygon.
  • CG_StraightSkeleton - 도형으로부터 직선 골격(straight skeleton)을 계산합니다.
  • CG_Tesselate - 폴리곤 또는 다면체 표면의 표면 다듬기(tessellation) 작업을 수행한 다음 TIN 또는 TIN 집합으로 반환합니다.
  • CG_Visibility - Compute a visibility polygon from a point or a segment in a polygon geometry
  • CG_Volume - Computes the volume of a 3D geometry. Closed surfaces can have non-zero volume.
  • GeometryType - ST_Geometry 값의 도형 유형을 반환합니다.
  • ST_3DClosestPoint - g2에 가장 가까운 g1 상에 있는 3차원 포인트를 반환합니다. 해당 포인트는 3D 최단 라인의 첫 번째 포인트입니다.
  • ST_3DDFullyWithin - Tests if two 3D geometries are entirely within a given 3D distance
  • ST_3DDWithin - Tests if two 3D geometries are within a given 3D distance
  • ST_3DDistance - 도형 유형에 대해, 두 도형 사이의 (SRS에 기반한) 3차원 데카르트 최단 거리를 투영 단위로 반환합니다.
  • ST_3DExtent - Aggregate function that returns the 3D bounding box of geometries.
  • ST_3DIntersects - Tests if two geometries spatially intersect in 3D - only for points, linestrings, polygons, polyhedral surface (area)
  • ST_3DLongestLine - 두 도형 사이의 3차원 최장(longest) 라인을 반환합니다.
  • ST_3DMaxDistance - 도형 유형에 대해, 두 도형 사이의 (SRS에 기반한) 3차원 데카르트 최장 거리를 투영 단위로 반환합니다.
  • ST_3DShortestLine - 두 도형 사이의 3차원 최단(shortest) 라인을 반환합니다.
  • ST_Affine - Apply a 3D affine transformation to a geometry.
  • ST_Area - 도형의 기하학적 중심을 반환합니다.
  • ST_AsBinary - Return the OGC/ISO Well-Known Binary (WKB) representation of the geometry/geography without SRID meta data.
  • ST_AsEWKB - Return the Extended Well-Known Binary (EWKB) representation of the geometry with SRID meta data.
  • ST_AsEWKT - 도형의 WKT(Well-Known Text) 표현식을 SRID 메타데이터와 함께 반환합니다.
  • ST_AsGML - 도형을 GML 2 또는 GML 3 버전 요소로 반환합니다.
  • ST_AsX3D - 도형을 X3D XML 노드 요소 형식: ISO-IEC-19776-1.2-X3DEncodings-XML로 반환합니다.
  • ST_CoordDim - ST_Geometry 값의 좌표 차원을 반환합니다.
  • ST_Dimension - ST_Geometry 값의 좌표 차원을 반환합니다.
  • ST_Dump - Returns a set of geometry_dump rows for the components of a geometry.
  • ST_DumpPoints - 도형의 내용을 요약한 텍스트를 반환합니다.
  • ST_Expand - Returns a bounding box expanded from another bounding box or a geometry.
  • ST_Extent - Aggregate function that returns the bounding box of geometries.
  • ST_FlipCoordinates - Returns a version of a geometry with X and Y axis flipped.
  • ST_Force2D - 도형을 "2차원 모드"로 강제합니다.
  • ST_ForceRHR - 폴리곤 안에 있는 꼭짓점들의 방향(orientation)이 오른손 법칙(Right-Hand Rule)을 따르도록 강제합니다.
  • ST_ForceSFS - Force geometries to use SFS 1.1 or 1.2 geometry types.
  • ST_Force3D - 도형을 XYZ 모드로 강제합니다. ST_Force3DZ라고도 합니다.
  • ST_Force3DZ - 도형을 XYZ 모드로 강제합니다.
  • ST_ForceCollection - 도형을 도형 집합으로 변환합니다.
  • ST_GeomFromEWKB - EWKB(Extended Well-Known Binary)로부터 지정된 ST_Geometry 값을 반환합니다.
  • ST_GeomFromEWKT - EWKT(Extended Well-Known Text)로부터 지정된 ST_Geometry 값을 반환합니다.
  • ST_GeomFromGML - 도형의 GML 표현식을 입력받아 PostGIS 도형 객체를 출력합니다.
  • ST_GeometryN - ST_Geometry 값의 도형 유형을 반환합니다.
  • ST_GeometryType - ST_Geometry 값의 도형 유형을 반환합니다.
  • = - Returns TRUE if the coordinates and coordinate order geometry/geography A are the same as the coordinates and coordinate order of geometry/geography B.
  • &<| - A의 경계 상자가 B의 경계 상자와 겹치거나 그 아래에 있을 경우 TRUE 를 반환합니다.
  • ~= - A의 경계 상자와 B의 경계 상자가 동일할 경우 TRUE 를 반환합니다.
  • ST_IsClosed - LINESTRING 의 시작점과 종단점이 일치하는 경우 TRUE 를 반환합니다. 다면체 표면이 닫혀 (부피를 가지고) 있는 경우 TRUE 를 반환합니다.
  • ST_MemSize - ST_Geometry 값의 도형 유형을 반환합니다.
  • ST_NPoints - 도형이 가지고 있는 포인트(꼭짓점)의 개수를 반환합니다.
  • ST_NumGeometries - 도형이 가지고 있는 포인트의 개수를 반환합니다. 모든 도형을 입력받을 수 있습니다.
  • ST_NumPatches - Returns the number of faces in a PolyhedralSurface or TIN.
  • ST_PatchN - Returns the Nth face of a PolyhedralSurface or TIN.
  • ST_RemoveRepeatedPoints - Returns a version of a geometry with duplicate points removed.
  • ST_Reverse - 꼭짓점들의 순서가 반대인 도형을 반환합니다.
  • ST_Rotate - Rotates a geometry about an origin point.
  • ST_RotateX - Rotates a geometry about the X axis.
  • ST_RotateY - Rotates a geometry about the Y axis.
  • ST_RotateZ - Rotates a geometry about the Z axis.
  • ST_Scale - Scales a geometry by given factors.
  • ST_ShiftLongitude - Shifts the longitude coordinates of a geometry between -180..180 and 0..360.
  • ST_Summary - 도형의 내용을 요약한 텍스트를 반환합니다.
  • ST_SwapOrdinates - 입력 도형을 좌표값을 뒤바꾼 상태로 반환합니다.
  • ST_Transform - Return a new geometry with coordinates transformed to a different spatial reference system.
  • ~(box2df,box2df) - Returns TRUE if a 2D float precision bounding box (BOX2DF) contains another 2D float precision bounding box (BOX2DF).
  • ~(box2df,geometry) - Returns TRUE if a 2D float precision bounding box (BOX2DF) contains a geometry's 2D bonding box.
  • ~(geometry,box2df) - Returns TRUE if a geometry's 2D bonding box contains a 2D float precision bounding box (GIDX).
  • && - A의 2D 경계 상자와 B의 2D 경계 상자가 교차하는 경우 TRUE 를 반환합니다.
  • &&& - A의 n차원 경계 상자와 B의 n차원 경계 상자가 교차하는 경우 TRUE 를 반환합니다.
  • @(box2df,box2df) - Returns TRUE if a 2D float precision bounding box (BOX2DF) is contained into another 2D float precision bounding box.
  • @(box2df,geometry) - Returns TRUE if a 2D float precision bounding box (BOX2DF) is contained into a geometry's 2D bounding box.
  • @(geometry,box2df) - Returns TRUE if a geometry's 2D bounding box is contained into a 2D float precision bounding box (BOX2DF).
  • &&(box2df,box2df) - Returns TRUE if two 2D float precision bounding boxes (BOX2DF) intersect each other.
  • &&(box2df,geometry) - Returns TRUE if a 2D float precision bounding box (BOX2DF) intersects a geometry's (cached) 2D bounding box.
  • &&(geometry,box2df) - Returns TRUE if a geometry's (cached) 2D bounding box intersects a 2D float precision bounding box (BOX2DF).
  • &&&(geometry,gidx) - Returns TRUE if a geometry's (cached) n-D bounding box intersects a n-D float precision bounding box (GIDX).
  • &&&(gidx,geometry) - Returns TRUE if a n-D float precision bounding box (GIDX) intersects a geometry's (cached) n-D bounding box.
  • &&&(gidx,gidx) - Returns TRUE if two n-D float precision bounding boxes (GIDX) intersect each other.

13.11. PostGIS Function Support Matrix

Below is an alphabetical listing of spatial specific functions in PostGIS and the kinds of spatial types they work with or OGC/SQL compliance they try to conform to.

  • A means the function works with the type or subtype natively.
  • A means it works but with a transform cast built-in using cast to geometry, transform to a "best srid" spatial ref and then cast back. Results may not be as expected for large areas or areas at poles and may accumulate floating point junk.
  • A means the function works with the type because of a auto-cast to another such as to box3d rather than direct type support.
  • A means the function only available if PostGIS compiled with SFCGAL support.
  • geom - Basic 2D geometry support (x,y).
  • geog - Basic 2D geography support (x,y).
  • 2.5D - basic 2D geometries in 3 D/4D space (has Z or M coord).
  • PS - Polyhedral surfaces
  • T - Triangles and Triangulated Irregular Network surfaces (TIN)

Functiongeomgeog2.5DCurvesSQL MMPST
ST_Collect      
ST_LineFromMultiPoint       
ST_MakeEnvelope       
ST_MakeLine       
ST_MakePoint       
ST_MakePointM       
ST_MakePolygon       
ST_Point       
ST_PointZ       
ST_PointM       
ST_PointZM       
ST_Polygon       
ST_TileEnvelope       
ST_HexagonGrid       
ST_Hexagon       
ST_SquareGrid       
ST_Square       
ST_Letters       
ST_MakeNurbsCurve       
GeometryType    
ST_Boundary       
ST_BoundingDiagonal       
ST_CoordDim  
ST_Dimension    
ST_Dump    
ST_DumpPoints    
ST_DumpSegments      
ST_DumpRings       
ST_EndPoint     
ST_Envelope       
ST_ExteriorRing       
ST_GeometryN  
ST_GeometryType      
ST_HasArc      
ST_InteriorRingN       
ST_NumCurves       
ST_CurveN       
ST_IsClosed    
ST_IsCollection      
ST_IsEmpty      
ST_IsPolygonCCW       
ST_IsPolygonCW       
ST_IsRing       
ST_IsSimple       
ST_M       
ST_MemSize    
ST_NDims       
ST_NPoints      
ST_NRings      
ST_NumGeometries    
ST_NumInteriorRings       
ST_NumInteriorRing       
ST_NumPatches      
ST_NumPoints       
ST_PatchN    
ST_PointN     
ST_Points      
ST_StartPoint     
ST_StartM       
ST_EndM       
ST_SetStartM       
ST_SetEndM       
ST_Summary    
ST_X       
ST_Y       
ST_Z       
ST_ZMFlag      
ST_HasZ       
ST_HasM       
ST_ControlPoints       
ST_Degree       
ST_Weights       
ST_Knots       
ST_NumControlPoints       
ST_NurbsCurveIsRational       
ST_IsNurbsCurve       
ST_Evaluate       
ST_NurbsToLineString       
ST_AddPoint       
ST_CollectionExtract       
ST_CollectionHomogenize       
ST_CurveToLine     
ST_Scroll       
ST_FlipCoordinates    
ST_Force2D      
ST_Force3D      
ST_Force3DZ      
ST_Force3DM       
ST_Force4D      
ST_ForceCollection      
ST_ForceCurve      
ST_ForcePolygonCCW       
ST_ForcePolygonCW       
ST_ForceSFS    
ST_ForceRHR       
ST_LineExtend       
ST_LineToCurve      
ST_Multi       
ST_Normalize       
ST_Project      
ST_QuantizeCoordinates       
ST_RemovePoint       
ST_RemoveRepeatedPoints       
ST_RemoveIrrelevantPointsForView       
ST_RemoveSmallParts       
ST_Reverse       
ST_Segmentize      
ST_SetPoint       
ST_ShiftLongitude     
ST_WrapX       
ST_SnapToGrid       
ST_Snap       
ST_SwapOrdinates    
ST_IsValid       
ST_IsValidDetail       
ST_IsValidReason       
ST_MakeValid       
ST_InverseTransformPipeline       
ST_SetSRID       
ST_SRID      
ST_Transform     
ST_TransformPipeline       
postgis_srs_codes        
postgis_srs        
postgis_srs_all        
postgis_srs_search       
ST_BdPolyFromText       
ST_BdMPolyFromText       
ST_GeogFromText        
ST_GeographyFromText        
ST_GeomCollFromText       
ST_GeomFromEWKT    
ST_GeomFromMARC21       
ST_GeometryFromText       
ST_GeomFromText      
ST_LineFromText       
ST_MLineFromText       
ST_MPointFromText       
ST_MPolyFromText       
ST_PointFromText       
ST_PolygonFromText       
ST_WKTToSQL       
ST_GeogFromWKB        
ST_GeomFromEWKB    
ST_GeomFromWKB      
ST_LineFromWKB       
ST_LinestringFromWKB       
ST_PointFromWKB     
ST_WKBToSQL       
ST_Box2dFromGeoHash       
ST_GeomFromGeoHash       
ST_GeomFromGML     
ST_GeomFromGeoJSON       
ST_GeomFromKML       
ST_GeomFromTWKB       
ST_GMLToSQL       
ST_LineFromEncodedPolyline       
ST_PointFromGeoHash        
ST_FromFlatGeobufToTable        
ST_FromFlatGeobuf        
ST_AsEWKT  
ST_AsText     
ST_AsBinary
ST_AsEWKB    
ST_AsHEXEWKB      
ST_AsEncodedPolyline       
ST_AsFlatGeobuf       
ST_AsGeobuf       
ST_AsGeoJSON     
ST_AsGML  
ST_AsKML     
ST_AsLatLonText       
ST_AsMARC21       
ST_AsMVTGeom       
ST_AsMVT       
ST_AsSVG      
ST_AsTWKB       
ST_AsX3D     
ST_GeoHash       
&&      
&&(geometry,box2df)       
&&(box2df,geometry)       
&&(box2df,box2df)       
&&&    
&&&(geometry,gidx)    
&&&(gidx,geometry)    
&&&(gidx,gidx)     
&<       
&<|       
&>       
<<       
<<|       
=      
>>       
@       
@(geometry,box2df)       
@(box2df,geometry)       
@(box2df,box2df)       
|&>       
|>>       
~       
~(geometry,box2df)       
~(box2df,geometry)       
~(box2df,box2df)       
~=       
<->      
|=|       
<#>       
<<->>       
ST_3DIntersects    
ST_Contains       
ST_ContainsProperly       
ST_CoveredBy      
ST_Covers      
ST_Crosses       
ST_Disjoint       
ST_Equals       
ST_Intersects    
ST_LineCrossingDirection       
ST_OrderingEquals       
ST_Overlaps       
ST_Relate       
ST_RelateMatch        
ST_Touches       
ST_Within       
ST_3DDWithin      
ST_3DDFullyWithin       
ST_DFullyWithin       
ST_DWithin      
ST_PointInsideCircle       
ST_Area     
ST_Azimuth      
ST_Angle       
ST_ClosestPoint      
ST_3DClosestPoint       
ST_Distance     
ST_3DDistance      
ST_DistanceSphere       
ST_DistanceSpheroid       
ST_FrechetDistance       
ST_HausdorffDistance       
ST_Length      
ST_Length2D       
ST_3DLength       
ST_LengthSpheroid       
ST_LongestLine       
ST_3DLongestLine       
ST_MaxDistance       
ST_3DMaxDistance       
ST_MinimumClearance       
ST_MinimumClearanceLine       
ST_Perimeter      
ST_Perimeter2D       
ST_3DPerimeter       
ST_ShortestLine      
ST_3DShortestLine       
ST_ClipByBox2D       
ST_Difference       
ST_Intersection     
ST_MemUnion       
ST_Node       
ST_Split       
ST_Subdivide       
ST_SymDifference       
ST_UnaryUnion       
ST_Union       
ST_Buffer      
ST_BuildArea       
ST_Centroid      
ST_ChaikinSmoothing       
ST_CatmullRomSmoothing       
ST_ConcaveHull       
ST_ConvexHull       
ST_DelaunayTriangles      
ST_FilterByM       
ST_GeneratePoints       
ST_GeometricMedian       
ST_LineMerge       
ST_MaximumInscribedCircle       
ST_LargestEmptyCircle       
ST_MinimumBoundingCircle       
ST_MinimumBoundingRadius       
ST_OrientedEnvelope       
ST_OffsetCurve       
ST_PointOnSurface       
ST_Polygonize       
ST_ReducePrecision       
ST_SharedPaths       
ST_Simplify       
ST_SimplifyPreserveTopology       
ST_SimplifyPolygonHull       
ST_SimplifyVW       
ST_SetEffectiveArea       
ST_TriangulatePolygon       
ST_VoronoiLines       
ST_VoronoiPolygons       
ST_CoverageInvalidEdges       
ST_CoverageClean       
ST_CoverageSimplify       
ST_CoverageEdges       
ST_CoverageUnion       
ST_Affine    
ST_Rotate    
ST_RotateX     
ST_RotateY     
ST_RotateZ    
ST_Scale    
ST_Translate      
ST_TransScale      
ST_ClusterDBSCAN       
ST_ClusterIntersecting       
ST_ClusterIntersectingWin       
ST_ClusterRelateWin       
ST_MinimumSpanningTree       
ST_ClusterKMeans       
ST_ClusterWithin       
ST_ClusterWithinWin       
Box2D     
Box3D    
ST_EstimatedExtent       
ST_Expand     
ST_Extent     
ST_3DExtent    
ST_MakeBox2D       
ST_3DMakeBox       
ST_XMax      
ST_XMin      
ST_YMax      
ST_YMin      
ST_ZMax      
ST_ZMin      
ST_XSize      
ST_YSize      
ST_ZSize      
ST_MMin      
ST_MMax      
ST_MSize      
ST_LineInterpolatePoint     
ST_3DLineInterpolatePoint       
ST_LineInterpolatePoints     
ST_LineLocatePoint      
ST_LineSubstring     
ST_LocateAlong       
ST_LocateBetween       
ST_LocateBetweenElevations       
ST_InterpolatePoint       
ST_3DInterpolatePoint       
ST_AddMeasure       
ST_IsValidTrajectory       
ST_ClosestPointOfApproach       
ST_DistanceCPA       
ST_CPAWithin       
postgis.gdal_datapath        
postgis.gdal_enabled_drivers        
postgis.enable_outdb_rasters        
postgis.gdal_vsi_options        
postgis.gdal_cpl_debug        
PostGIS_AddBBox       
PostGIS_DropBBox       
PostGIS_HasBBox       
postgis_sfcgal_version        
postgis_sfcgal_full_version        
CG_ForceLHR     
CG_IsPlanar     
CG_IsSolid     
CG_MakeSolid     
CG_Orientation       
CG_Area       
CG_3DArea    
CG_Volume    
CG_Intersection       
CG_Intersects      
CG_3DIntersects      
CG_Difference      
CG_3DDifference    
CG_Distance      
CG_3DDistance      
CG_3DConvexHull     
CG_3DIntersection    
CG_Union       
CG_3DUnion    
CG_AlphaShape       
CG_ApproxConvexPartition       
CG_ApproximateMedialAxis     
CG_GenerateFlatRoof       
CG_GenerateHippedRoof       
CG_GenerateGableRoof       
CG_GenerateSkillionRoof       
CG_GenerateRoof       
CG_PolygonRepair       
CG_ConstrainedDelaunayTriangles       
CG_Extrude     
CG_ExtrudeStraightSkeleton       
CG_GreeneApproxConvexPartition       
CG_MinkowskiSum       
CG_OptimalAlphaShape       
CG_OptimalConvexPartition       
CG_StraightSkeleton     
CG_Tesselate     
CG_Triangulate       
CG_Visibility     
CG_YMonotonePartition       
CG_StraightSkeletonPartition       
CG_3DBuffer       
CG_Rotate       
CG_2DRotate       
CG_3DRotate       
CG_RotateX       
CG_RotateY       
CG_RotateZ       
CG_Scale       
CG_3DScale       
CG_3DScaleAroundCenter       
CG_Translate       
CG_3DTranslate       
CG_Simplify       
CG_3DAlphaWrapping       
CG_NurbsCurveInterpolate       
CG_NurbsCurveApproximate       
CG_NurbsCurveDerivative       
getfaceedges_returntype        
TopoGeometry        
validatetopology_returntype        
TopoElement        
TopoElementArray        
AddTopoGeometryColumn        
RenameTopoGeometryColumn        
DropTopology        
RenameTopology        
DropTopoGeometryColumn        
FixCorruptTopoGeometryColumn        
Populate_Topology_Layer        
TopologySummary        
ValidateTopology       
ValidateTopologyRelation        
ValidateTopologyPrecision       
MakeTopologyPrecise       
FindTopology       
FindLayer       
TotalTopologySize        
UpgradeTopology        
CreateTopology        
CopyTopology        
ST_InitTopoGeo        
ST_CreateTopoGeo       
TopoGeo_AddPoint       
TopoGeo_AddLineString       
TopoGeo_AddPolygon       
TopoGeo_LoadGeometry       
ST_AddIsoNode       
ST_AddIsoEdge       
ST_AddEdgeNewFaces       
ST_AddEdgeModFace       
ST_RemEdgeNewFace        
ST_RemEdgeModFace        
ST_ChangeEdgeGeom       
ST_ModEdgeSplit       
ST_ModEdgeHeal        
ST_NewEdgeHeal        
ST_MoveIsoNode       
ST_NewEdgesSplit       
ST_RemoveIsoNode        
ST_RemoveIsoEdge        
GetEdgeByPoint       
GetFaceByPoint       
GetFaceContainingPoint       
GetNodeByPoint       
GetTopologyID        
GetTopologySRID        
GetTopologyName        
ST_GetFaceEdges        
ST_GetFaceGeometry       
GetRingEdges        
GetNodeEdges        
FindVertexSegmentPairsBelowDistance        
Polygonize        
AddNode       
AddEdge       
AddFace       
ST_Simplify       
RemoveUnusedPrimitives       
CreateTopoGeom       
toTopoGeom       
TopoElementArray_Agg        
TopoElement       
clearTopoGeom       
TopoGeom_addElement       
TopoGeom_remElement       
TopoGeom_addTopoGeom       
toTopoGeom        
GetTopoGeomElementArray        
GetTopoGeomElements        
ST_SRID       
AsGML       
AsTopoJSON       
Equals       
Intersects       
geomval        
addbandarg        
rastbandarg        
raster        
reclassarg        
summarystats        
unionarg        
AddRasterConstraints        
DropRasterConstraints        
AddOverviewConstraints        
DropOverviewConstraints        
PostGIS_GDAL_Version        
PostGIS_Raster_Lib_Build_Date        
PostGIS_Raster_Lib_Version        
ST_GDALDrivers        
UpdateRasterSRID        
ST_CreateOverview        
ST_AddBand        
ST_AsRaster       
ST_AsRasterAgg       
ST_Band        
ST_MakeEmptyCoverage        
ST_MakeEmptyRaster        
ST_Tile        
ST_Retile       
ST_FromGDALRaster        
ST_GeoReference        
ST_Height        
ST_IsEmpty        
ST_MemSize        
ST_MetaData        
ST_NumBands        
ST_PixelHeight        
ST_PixelWidth        
ST_ScaleX        
ST_ScaleY        
ST_RasterToWorldCoord        
ST_RasterToWorldCoordX        
ST_RasterToWorldCoordY        
ST_Rotation        
ST_SkewX        
ST_SkewY        
ST_SRID        
ST_Summary        
ST_UpperLeftX        
ST_UpperLeftY        
ST_Width        
ST_WorldToRasterCoord       
ST_WorldToRasterCoordX       
ST_WorldToRasterCoordY       
ST_BandMetaData        
ST_BandNoDataValue        
ST_BandIsNoData        
ST_BandPath        
ST_BandFileSize        
ST_BandFileTimestamp        
ST_BandPixelType        
ST_MinPossibleValue        
ST_HasNoBand        
ST_PixelAsPolygon       
ST_PixelAsPolygons        
ST_PixelAsPoint       
ST_PixelAsPoints        
ST_PixelAsCentroid       
ST_PixelAsCentroids        
ST_Value       
ST_NearestValue       
ST_SetZ       
ST_SetM       
ST_Neighborhood       
ST_SetValue       
ST_SetValues        
ST_DumpValues        
ST_PixelOfValue        
ST_SetGeoReference        
ST_SetRotation        
ST_SetScale        
ST_SetSkew        
ST_SetSRID        
ST_SetUpperLeft        
ST_Resample        
ST_Rescale        
ST_Reskew        
ST_SnapToGrid        
ST_Resize        
ST_Transform        
ST_SetBandNoDataValue        
ST_SetBandIsNoData        
ST_SetBandPath        
ST_SetBandIndex        
ST_Count        
ST_CountAgg        
ST_Histogram        
ST_Quantile        
ST_SummaryStats        
ST_SummaryStatsAgg        
ST_ValueCount        
ST_RastFromWKB        
ST_RastFromHexWKB        
ST_AsBinary/ST_AsWKB        
ST_AsHexWKB        
ST_AsGDALRaster        
ST_AsJPEG        
ST_AsPNG        
ST_AsTIFF        
ST_Clip       
ST_ColorMap        
ST_Grayscale        
ST_Intersection       
ST_MapAlgebra (callback function version)        
ST_MapAlgebra (expression version)        
ST_MapAlgebraExpr        
ST_MapAlgebraExpr        
ST_MapAlgebraFct        
ST_MapAlgebraFct        
ST_MapAlgebraFctNgb        
ST_Reclass        
ST_ReclassExact        
ST_Union        
ST_Distinct4ma        
ST_InvDistWeight4ma        
ST_Max4ma        
ST_Mean4ma        
ST_Min4ma        
ST_MinDist4ma        
ST_Range4ma        
ST_StdDev4ma        
ST_Sum4ma        
ST_Aspect        
ST_HillShade        
ST_Roughness        
ST_Slope        
ST_TPI        
ST_TRI        
ST_InterpolateRaster       
ST_Contour        
Box3D       
ST_ConvexHull       
ST_DumpAsPolygons        
ST_Envelope       
ST_MinConvexHull       
ST_Polygon       
ST_IntersectionFractions       
&&       
&<        
&>        
=        
@       
~=        
~       
ST_Contains        
ST_ContainsProperly        
ST_Covers        
ST_CoveredBy        
ST_Disjoint        
ST_Intersects       
ST_Overlaps        
ST_Touches        
ST_SameAlignment        
ST_NotSameAlignmentReason        
ST_Within        
ST_DWithin        
ST_DFullyWithin        

13.12. New, Enhanced or changed PostGIS Functions

13.12.1. PostGIS Functions new or enhanced in 3.7

The functions given below are PostGIS functions that were added or enhanced.

Functions new in PostGIS 3.7

  • CG_ApproximateMedialAxis - Availability: 3.7.0 - projected parameter. Requires SFCGAL >= 2.3.0 for projected result; falls back to non-projected with a notice on older versions. 면 도형의 근사 중심축을 계산합니다.
  • CG_GenerateFlatRoof - Availability: 3.7.0 - requires SFCGAL >= 2.3.0. Generate a flat (box) roof from a footprint polygon.
  • CG_GenerateGableRoof - Availability: 3.7.0 - requires SFCGAL >= 2.3.0. Generate a gable roof from a footprint polygon.
  • CG_GenerateHippedRoof - Availability: 3.7.0 - requires SFCGAL >= 2.3.0. Generate a hipped roof from a footprint polygon.
  • CG_GenerateRoof - Availability: 3.7.0 - requires SFCGAL >= 2.3.0. Generate a roof of the requested type from a footprint polygon.
  • CG_GenerateSkillionRoof - Availability: 3.7.0 - requires SFCGAL >= 2.3.0. Generate a skillion (single-slope) roof from a footprint polygon.
  • CG_NurbsCurveApproximate - Availability: 3.7.0 - requires SFCGAL >= 2.3.0. Creates an approximating NURBS curve fitting data points within a tolerance
  • CG_NurbsCurveDerivative - Availability: 3.7.0 - requires SFCGAL >= 2.3.0. Computes the derivative (tangent, curvature) of a NURBS curve at a given parameter
  • CG_NurbsCurveInterpolate - Availability: 3.7.0 - requires SFCGAL >= 2.3.0. Creates an interpolating NURBS curve passing through all given data points
  • CG_PolygonRepair - Availability: 3.7.0 - requires SFCGAL >= 2.3.0 and CGAL >= 6.0. Repair an invalid polygon or multipolygon.
  • FindVertexSegmentPairsBelowDistance - Availability: 3.7 Find pairs of topology vertex/segment that are closer than tolerated distance
  • ST_3DInterpolatePoint - Availability: 3.7.0 Returns the interpolated measure of a geometry closest to a point in 3D.
  • ST_ClusterRelateWin - Availability: 3.7.0 Window function that returns a cluster id for each input geometry, clustering input geometries into connected sets using the relate pattern to determine whether the geometries are connected.
  • ST_ControlPoints - Availability: 3.7.0 Returns the control points of a NURBS curve as a MULTIPOINT geometry.
  • ST_CoverageEdges - Availability: 3.7.0 Computes the unique edges of a polygonal coverage.
  • ST_Degree - Availability: 3.7.0 Returns the polynomial degree of a NURBS curve.
  • ST_Evaluate - Availability: 3.7.0 Evaluates a NURBS curve at a specific parameter value and returns the resulting point.
  • ST_IsNurbsCurve - Availability: 3.7.0 Checks if a geometry is a NURBS curve.
  • ST_Knots - Availability: 3.7.0 Returns the knot vector of a NURBS curve.
  • ST_MSize - Availability: 3.7.0 Returns the M size of a geometry.
  • ST_MakeLine - Availability: 3.7.0 - Support for MultiLineString input elements was introduced 포인트, 멀티포인트 또는 라인 도형으로부터 라인스트링을 생성합니다.
  • ST_MakeNurbsCurve - Availability: 3.7.0 Creates a NURBS (Non-Uniform Rational B-Spline) curve from control points, optional weights, and optional knot vector.
  • ST_MinimumSpanningTree - Availability: 3.7.0 Window function that returns a tree id for each input geometry, clustering input geometries into connected trees using the Minimum Spanning Tree algorithm.
  • ST_NumControlPoints - Availability: 3.7.0 Returns the number of control points in a NURBS curve.
  • ST_NurbsCurveIsRational - Availability: 3.7.0 Checks if a NURBS curve is rational (has weights).
  • ST_NurbsToLineString - Availability: 3.7.0 Converts a NURBS curve to a LINESTRING by uniform sampling.
  • ST_Weights - Availability: 3.7.0 Returns the weight array of a rational NURBS curve.
  • ST_XSize - Availability: 3.7.0 Returns the X size of a 2D or 3D bounding box or a geometry.
  • ST_YSize - Availability: 3.7.0 Returns the Y size of a 2D or 3D bounding box or a geometry.
  • ST_ZSize - Availability: 3.7.0 Returns the Z size of a 2D or 3D bounding box or a geometry.

Functions enhanced in PostGIS 3.7

  • ST_GMLToSQL - Enhanced: 3.7.0 support for GML ArcString, curved Ring, and CurvePolygon geometries was introduced. Returns a geometry from GML. Alias for ST_GeomFromGML.
  • ST_GeomFromGML - Enhanced: 3.7.0 support for GML ArcString, curved Ring, and CurvePolygon geometries was introduced. 도형의 GML 표현식을 입력받아 PostGIS 도형 객체를 출력합니다.
  • ST_LongestLine - Enhanced: 3.7.0 - support for a single geometry input. 두 도형 사이의 3차원 최장(longest) 라인을 반환합니다.
  • ST_MakePolygon - Enhanced: 3.7.0 - Support for curved input rings was introduced. Creates a Polygon or CurvePolygon from a shell and optional list of holes.
  • ST_MaxDistance - Enhanced: 3.7.0 - support for a single geometry input. 두 도형 사이의 2차원 최장 거리를 투영 단위로 반환합니다.
  • ST_Value - Enhanced: 3.7.0 resample accepts nearest-neighbor boundary options "nearest-UL", "nearest-UR", "nearest-LL", and "nearest-LR". 입력 columnx, rowy 픽셀의 입력 밴드의 값, 또는 특정 기하학적 포인트의 밴드의 값을 반환합니다. 밴드 번호는 1부터 시작하며, 따로 지정하지 않을 경우 1로 가정합니다. exclude_nodata_value 를 거짓으로 설정할 경우, nodata 픽셀을 포함한 모든 픽셀이 교차한다고 가정하고 값을 반환합니다. exclude_nodata_value 를 설정하지 않은 경우, 래스터의 메타데이터에서 값을 읽어 들입니다.
  • TopoGeo_AddLineString - Enhanced: 3.7.0 added support for limiting the number of new edges created in the topology. Adds a linestring to an existing topology using a tolerance and possibly splitting existing edges/faces.

Functions changed in PostGIS 3.7

  • ST_AsGeoJSON - Changed: 3.7.0 added warning about duplicate keys Return a geometry or feature in GeoJSON format.
  • toTopoGeom - Changed: 3.7.0 changes meaning of tolerance 0 to really mean 0 and -1 (new default) to request using the topology precision. Converts a simple Geometry into a topo geometry.

13.12.2. PostGIS Functions new or enhanced in 3.6

The functions given below are PostGIS functions that were added or enhanced.

Functions new in PostGIS 3.6

  • CG_2DRotate - Availability: 3.6.0 - requires SFCGAL >= 2.0.0 Rotates a geometry by a given angle around a specified point in 2D.
  • CG_3DAlphaWrapping - Availability: 3.6.0 - requires SFCGAL >= 2.1.0 Computes a 3D Alpha-wrapping strictly enclosing a geometry.
  • CG_3DBuffer - Availability: 3.6.0 - requires SFCGAL >= 2.0.0 Computes a 3D buffer around a geometry.
  • CG_3DRotate - Availability: 3.6.0 - requires SFCGAL >= 2.0.0 Rotates a geometry in 3D space around an axis vector.
  • CG_3DScale - Availability: 3.6.0 - requires SFCGAL >= 2.0.0 Scales a geometry by separate factors along X, Y, and Z axes.
  • CG_3DScaleAroundCenter - Availability: 3.6.0 - requires SFCGAL >= 2.0.0 Scales a geometry in 3D space around a specified center point.
  • CG_3DTranslate - Availability: 3.6.0 - requires SFCGAL >= 2.0.0 Translates (moves) a geometry by given offsets in 3D space.
  • CG_Rotate - Availability: 3.6.0 - requires SFCGAL >= 2.0.0 Rotates a geometry by a given angle around the origin (0,0).
  • CG_RotateX - Availability: 3.6.0 - requires SFCGAL >= 2.0.0 Rotates a geometry around the X-axis by a given angle.
  • CG_RotateY - Availability: 3.6.0 - requires SFCGAL >= 2.0.0 Rotates a geometry around the Y-axis by a given angle.
  • CG_RotateZ - Availability: 3.6.0 - requires SFCGAL >= 2.0.0 Rotates a geometry around the Z-axis by a given angle.
  • CG_Scale - Availability: 3.6.0 - requires SFCGAL >= 2.0.0 Scales a geometry uniformly in all dimensions by a given factor.
  • CG_Simplify - Availability: 3.6.0 - requires SFCGAL >= 2.1.0 Reduces the complexity of a geometry while preserving essential features and Z/M values.
  • CG_StraightSkeletonPartition - Availability: 3.6.0 - requires SFCGAL >= 2.0.0. Computes the straight skeleton partition of a polygon.
  • CG_Translate - Availability: 3.6.0 - requires SFCGAL >= 2.0.0 Translates (moves) a geometry by given offsets in 2D space.
  • FixCorruptTopoGeometryColumn - Availability: 3.6.1 Fixes topogeometry corruption caused by upgrade to postgis_topology 3.6.0 and higher
  • MakeTopologyPrecise - Availability: 3.6.0 Snap topology vertices to precision grid.
  • ST_AsRasterAgg - Availability: 3.6.0 Aggregate. Renders PostGIS geometries into a new raster.
  • ST_CatmullRomSmoothing - Availability: 3.6.0 Returns a smoothed version of a geometry, using the Catmull-Rom spline algorithm
  • ST_CoverageClean - Availability: 3.6.0 - requires GEOS >= 3.14.0 Computes a clean (edge matched, non-overlapping, gap-cleared) polygonal coverage, given a non-clean input.
  • ST_IntersectionFractions - Availability: 3.6.0 Requires GEOS 3.14 or higher. Calculates the fraction of each raster cell that is covered by a given geometry.
  • ST_ReclassExact - Availability: 3.6.0 Creates a new raster composed of bands reclassified from original, using a 1:1 mapping from values in the original band to new values in the destination band.
  • TotalTopologySize - Availability: 3.6.0 Total disk space used by the specified topology, including all indexes and TOAST data.
  • UpgradeTopology - Availability: 3.6.0 Upgrades the specified topology to support large ids (int8) for topology and primitive ids.
  • ValidateTopologyPrecision - Availability: 3.6.0 Returns non-precise vertices in the topology.
  • postgis.gdal_cpl_debug - Availability: 3.6.0 A boolean configuration to turn logging of GDAL debug messages on and off.

Functions enhanced in PostGIS 3.6

  • CreateTopology - Enhanced: 3.6.0 added topoid and usesLargeIDs parameters. Creates a new topology schema and registers it in the topology.topology table.

Functions changed in PostGIS 3.6

  • ST_GeometryN - Changed: 3.6.0 TIN and PolyhedralSurface are treated as unitary geometries and are not decomposed into patches; use ST_PatchN to access faces. ST_Geometry 값의 도형 유형을 반환합니다.
  • ST_NumGeometries - Changed: 3.6.0 TIN and PolyhedralSurface are treated as unitary geometries and return 1; use ST_NumPatches to count faces. 도형이 가지고 있는 포인트의 개수를 반환합니다. 모든 도형을 입력받을 수 있습니다.

13.12.3. PostGIS Functions new or enhanced in 3.5

The functions given below are PostGIS functions that were added or enhanced.

Functions new in PostGIS 3.5

  • CG_3DArea - Availability: 3.5.0 3차원 표면 도형의 면적을 계산합니다. 입체일 경우 0을 반환할 것입니다.
  • CG_3DConvexHull - Availability: 3.5.0 면 도형의 근사 중심축을 계산합니다.
  • CG_3DDifference - Availability: 3.5.0 3차원 차이를 수행합니다.
  • CG_3DDistance - Availability: 3.5.0 Computes the minimum 3D distance between two geometries
  • CG_3DIntersection - Availability: 3.5.0 3차원 교차를 수행합니다.
  • CG_3DIntersects - Availability: 3.5.0 Tests if two 3D geometries intersect
  • CG_3DUnion - Availability: 3.5.0 Perform 3D union using postgis_sfcgal.
  • CG_AlphaShape - Availability: 3.5.0 - requires SFCGAL >= 1.4.1. Computes an Alpha-shape enclosing a geometry
  • CG_ApproxConvexPartition - Availability: 3.5.0 - requires SFCGAL >= 1.5.0. Computes approximal convex partition of the polygon geometry
  • CG_ApproximateMedialAxis - Availability: 3.5.0 면 도형의 근사 중심축을 계산합니다.
  • CG_Area - Availability: 3.5.0 Calculates the area of a geometry
  • CG_Difference - Availability: 3.5.0 Computes the geometric difference between two geometries
  • CG_Distance - Availability: 3.5.0 Computes the minimum distance between two geometries
  • CG_Extrude - Availability: 3.5.0 표면을 관련 입체로 돌출시킵니다.
  • CG_ExtrudeStraightSkeleton - Availability: 3.5.0 - requires SFCGAL >= 1.5.0. Straight Skeleton Extrusion
  • CG_ForceLHR - Availability: 3.5.0 LHR(Left Hand Reverse; 시계 방향) 방향을 강제합니다.
  • CG_GreeneApproxConvexPartition - Availability: 3.5.0 - requires SFCGAL >= 1.5.0. Computes approximal convex partition of the polygon geometry
  • CG_Intersection - Availability: 3.5.0 Computes the intersection of two geometries
  • CG_Intersects - Availability: 3.5.0 Tests if two geometries intersect (they have at least one point in common)
  • CG_IsPlanar - Availability: 3.5.0 표면이 평면인지 아닌지 확인합니다.
  • CG_IsSolid - Availability: 3.5.0 도형이 입체인지 테스트합니다. 어떤 유효성 검사도 수행하지 않습니다.
  • CG_MakeSolid - Availability: 3.5.0 도형을 입체로 지정합니다. 어떤 확인 작업도 수행하지 않습니다. 유효한 입체를 얻으려면, 입력 도형이 닫힌 다면체 표면 또는 닫힌 TIN이어야만 합니다.
  • CG_MinkowskiSum - Availability: 3.5.0 민코프스키 합계를 수행합니다.
  • CG_OptimalAlphaShape - Availability: 3.5.0 - requires SFCGAL >= 1.4.1. Computes an Alpha-shape enclosing a geometry using an "optimal" alpha value.
  • CG_OptimalConvexPartition - Availability: 3.5.0 - requires SFCGAL >= 1.5.0. Computes an optimal convex partition of the polygon geometry
  • CG_Orientation - Availability: 3.5.0 표면의 방향(orientation)을 결정합니다.
  • CG_StraightSkeleton - Availability: 3.5.0 도형으로부터 직선 골격(straight skeleton)을 계산합니다.
  • CG_Tesselate - Availability: 3.5.0 폴리곤 또는 다면체 표면의 표면 다듬기(tessellation) 작업을 수행한 다음 TIN 또는 TIN 집합으로 반환합니다.
  • CG_Triangulate - Availability: 3.5.0 Triangulates a polygonal geometry
  • CG_Union - Availability: 3.5.0 Computes the union of two geometries
  • CG_Visibility - Availability: 3.5.0 - requires SFCGAL >= 1.5.0. Compute a visibility polygon from a point or a segment in a polygon geometry
  • CG_Volume - Availability: 3.5.0 Computes the volume of a 3D geometry. Closed surfaces can have non-zero volume.
  • CG_YMonotonePartition - Availability: 3.5.0 - requires SFCGAL >= 1.5.0. Computes y-monotone partition of the polygon geometry
  • ST_HasM - Availability: 3.5.0 Checks if a geometry has an M (measure) dimension.
  • ST_HasZ - Availability: 3.5.0 Checks if a geometry has a Z dimension.
  • ST_RemoveIrrelevantPointsForView - Availability: 3.5.0 Removes points that are irrelevant for rendering a specific rectangular view of a geometry.
  • ST_RemoveSmallParts - Availability: 3.5.0 Removes small parts (polygon rings or linestrings) of a geometry.
  • TopoGeo_LoadGeometry - Availability: 3.5.0 Load a geometry into an existing topology, snapping and splitting as needed.

Functions enhanced in PostGIS 3.5

  • ST_Clip - Enhanced: 3.5.0 - touched argument added. Returns the raster clipped by the input geometry. If band number is not specified, all bands are processed. If crop is not specified or TRUE, the output raster is cropped. If touched is set to TRUE, then touched pixels are included, otherwise only if the center of the pixel is in the geometry it is included.

Functions changed in PostGIS 3.5

  • ST_AsGeoJSON - Changed: 3.5.0 allow specifying the column containing the feature id Return a geometry or feature in GeoJSON format.
  • ST_DFullyWithin - Changed: 3.5.0 : the logic behind the function now uses a test of containment within a buffer, rather than the ST_MaxDistance algorithm. Results will differ from prior versions, but should be closer to user expectations. Tests if a geometry is entirely inside a distance of another

13.12.4. PostGIS Functions new or enhanced in 3.4

The functions given below are PostGIS functions that were added or enhanced.

Functions new in PostGIS 3.4

  • PostGIS_GEOS_Compiled_Version - Availability: 3.4.0 Returns the version number of the GEOS library against which PostGIS was built.
  • PostGIS_PROJ_Compiled_Version - Availability: 3.5.0 Returns the version number of the PROJ library against which PostGIS was built.
  • RenameTopoGeometryColumn - Availability: 3.4.0 Renames a topogeometry column
  • RenameTopology - Availability: 3.4.0 Renames a topology
  • ST_ClusterIntersectingWin - Availability: 3.4.0 Window function that returns a cluster id for each input geometry, clustering input geometries into connected sets.
  • ST_ClusterWithinWin - Availability: 3.4.0 Window function that returns a cluster id for each input geometry, clustering using separation distance.
  • ST_CoverageInvalidEdges - Availability: 3.4.0 Window function that finds locations where polygons fail to form a valid coverage.
  • ST_CoverageSimplify - Availability: 3.4.0 Window function that simplifies the edges of a polygonal coverage.
  • ST_CoverageUnion - Availability: 3.4.0 - requires GEOS >= 3.8.0 Computes the union of a set of polygons forming a coverage by removing shared edges.
  • ST_InverseTransformPipeline - Availability: 3.4.0 Return a new geometry with coordinates transformed to a different spatial reference system using the inverse of a defined coordinate transformation pipeline.
  • ST_LargestEmptyCircle - Availability: 3.4.0. Computes the largest circle not overlapping a geometry.
  • ST_LineExtend - Availability: 3.4.0 Returns a line extended forwards and backwards by specified distances.
  • ST_TransformPipeline - Availability: 3.4.0 Return a new geometry with coordinates transformed to a different spatial reference system using a defined coordinate transformation pipeline.
  • TopoElement - Availability: 3.4.0 Converts a topogeometry to a topoelement.
  • postgis_srs - Availability: 3.4.0 Return a metadata record for the requested authority and srid.
  • postgis_srs_all - Availability: 3.4.0 Return metadata records for every spatial reference system in the underlying Proj database.
  • postgis_srs_codes - Availability: 3.4.0 Return the list of SRS codes associated with the given authority.
  • postgis_srs_search - Availability: 3.4.0 Return metadata records for projected coordinate systems that have areas of usage that fully contain the bounds parameter.

Functions enhanced in PostGIS 3.4

  • PostGIS_Full_Version - Enhanced: 3.4.0 now includes extra PROJ configurations NETWORK_ENABLED, URL_ENDPOINT and DATABASE_PATH of proj.db location Reports full PostGIS version and build configuration infos.
  • PostGIS_PROJ_Version - Enhanced: 3.4.0 now includes NETWORK_ENABLED, URL_ENDPOINT and DATABASE_PATH of proj.db location Returns the version number of the PROJ4 library.
  • ST_AsSVG - Enhanced: 3.4.0 to support all curve types Returns SVG path data for a geometry.
  • ST_ClosestPoint - Enhanced: 3.4.0 - Support for geography. Returns the 2D point on g1 that is closest to g2. This is the first point of the shortest line from one geometry to the other.
  • ST_LineSubstring - Enhanced: 3.4.0 - Support for geography was introduced. Returns the part of a line between two fractional locations.
  • ST_Project - Enhanced: 3.4.0 Allow geometry arguments and two-point form omitting azimuth. Returns a point projected from a start point by a distance and bearing (azimuth).
  • ST_Resample - Enhanced: 3.4.0 max and min resampling options added 특정 리샘플링 알고리즘, 새로운 차원, 임의의 그리드 모서리, 그리고 또 다른 래스터에서 정의되거나 빌려온 래스터 지리참조 속성들의 집합을 이용해서 래스터를 리샘플링합니다.
  • ST_Rescale - Enhanced: 3.4.0 max and min resampling options added Resample a raster by adjusting only its scale (or pixel size). New pixel values are computed using the NearestNeighbor (english or american spelling), Bilinear, Cubic, CubicSpline, Lanczos, Max or Min resampling algorithm. Default is NearestNeighbor.
  • ST_ShortestLine - Enhanced: 3.4.0 - support for geography. 두 도형 사이의 2차원 최단 라인을 반환합니다.

Functions changed in PostGIS 3.4

  • PostGIS_Extensions_Upgrade - Changed: 3.4.0 to add target_version argument. Packages and upgrades PostGIS extensions (e.g. postgis_raster, postgis_topology, postgis_sfcgal) to given or latest version.

13.12.5. PostGIS Functions new or enhanced in 3.3

The functions given below are PostGIS functions that were added or enhanced.

Functions new in PostGIS 3.3

  • RemoveUnusedPrimitives - Availability: 3.3.0 Removes topology primitives which not needed to define existing TopoGeometry objects.
  • ST_AsMARC21 - Availability: 3.3.0 Returns geometry as a MARC21/XML record with a geographic datafield (034).
  • ST_GeomFromMARC21 - Availability: 3.3.0, requires libxml2 2.6+ Takes MARC21/XML geographic data as input and returns a PostGIS geometry object.
  • ST_Letters - Availability: 3.3.0 Returns the input letters rendered as geometry with a default start position at the origin and default text height of 100.
  • ST_SimplifyPolygonHull - Availability: 3.3.0. Computes a simplified topology-preserving outer or inner hull of a polygonal geometry.
  • ST_TriangulatePolygon - Availability: 3.3.0. Computes the constrained Delaunay triangulation of polygons
  • postgis_sfcgal_full_version - Availability: 3.3.0 Returns the full version of SFCGAL in use including CGAL and Boost versions

Functions enhanced in PostGIS 3.3

  • ST_ConcaveHull - Enhanced: 3.3.0, GEOS native implementation enabled for GEOS 3.11+ Computes a possibly concave geometry that contains all input geometry vertices
  • ST_LineMerge - Enhanced: 3.3.0 accept a directed parameter. Return the lines formed by sewing together a MultiLineString.

Functions changed in PostGIS 3.3

  • PostGIS_Extensions_Upgrade - Changed: 3.3.0 support for upgrades from any PostGIS version. Does not work on all systems. Packages and upgrades PostGIS extensions (e.g. postgis_raster, postgis_topology, postgis_sfcgal) to given or latest version.

13.12.6. PostGIS Functions new or enhanced in 3.2

The functions given below are PostGIS functions that were added or enhanced.

Functions new in PostGIS 3.2

  • FindLayer - Availability: 3.2.0 Returns a topology.layer record by different means.
  • FindTopology - Availability: 3.2.0 Returns a topology record by different means.
  • GetFaceContainingPoint - Availability: 3.2.0 Finds the face containing a point.
  • ST_AsFlatGeobuf - Availability: 3.2.0 Return a FlatGeobuf representation of a set of rows.
  • ST_Contour - Availability: 3.2.0 Generates a set of vector contours from the provided raster band, using the GDAL contouring algorithm.
  • ST_DumpSegments - Availability: 3.2.0 도형의 내용을 요약한 텍스트를 반환합니다.
  • ST_FromFlatGeobuf - Availability: 3.2.0 Reads FlatGeobuf data.
  • ST_FromFlatGeobufToTable - Availability: 3.2.0 Creates a table based on the structure of FlatGeobuf data.
  • ST_InterpolateRaster - Availability: 3.2.0 Interpolates a gridded surface based on an input set of 3-d points, using the X- and Y-values to position the points on the grid and the Z-value of the points as the surface elevation.
  • ST_SRID - Availability: 3.2.0 Returns the spatial reference identifier for a topogeometry.
  • ST_Scroll - Availability: 3.2.0 Change start point of a closed LineString.
  • ST_SetM - Availability: 3.2.0 Returns a geometry with the same X/Y coordinates as the input geometry, and values from the raster copied into the M dimension using the requested resample algorithm.
  • ST_SetZ - Availability: 3.2.0 Returns a geometry with the same X/Y coordinates as the input geometry, and values from the raster copied into the Z dimension using the requested resample algorithm.
  • TopoGeom_addTopoGeom - Availability: 3.2 Adds element of a TopoGeometry to the definition of another TopoGeometry.
  • ValidateTopologyRelation - Availability: 3.2.0 Returns info about invalid topology relation records
  • postgis.gdal_vsi_options - Availability: 3.2.0 DB 외부 래스터 밴드에 접근할 수 있게 해주는 불 설정 옵션입니다.

Functions enhanced in PostGIS 3.2

  • GetFaceByPoint - Enhanced: 3.2.0 more efficient implementation and clearer contract, stops working with invalid topologies. Finds face intersecting a given point.
  • ST_ClusterKMeans - Enhanced: 3.2.0 Support for max_radius Window function that returns a cluster id for each input geometry using the K-means algorithm.
  • ST_MakeValid - Enhanced: 3.2.0, added algorithm options, 'linework' and 'structure' which requires GEOS >= 3.10.0. Attempts to make an invalid geometry valid without losing vertices.
  • ST_PixelAsCentroid - 개선 사항: 2.1.0 버전에서 C 언어로 다시 쓰였습니다. 픽셀 하나가 차지하는 면의 중심점(포인트 도형)을 반환합니다.
  • ST_PixelAsCentroids - 개선 사항: 2.1.0 버전에서 C 언어로 다시 쓰였습니다. 래스터 밴드의 각 픽셀에 대한 중심점(포인트 도형)을 각 픽셀의 값 및 X, Y 래스터 좌표와 함께 반환합니다. 포인트 도형은 픽셀이 차지하는 면의 중심점입니다.
  • ST_Point - Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID to mark the srid on the geometry. Creates a Point with X, Y and SRID values.
  • ST_PointM - Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID to mark the srid on the geometry. Creates a Point with X, Y, M and SRID values.
  • ST_PointZ - Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID to mark the srid on the geometry. Creates a Point with X, Y, Z and SRID values.
  • ST_PointZM - Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID to mark the srid on the geometry. Creates a Point with X, Y, Z, M and SRID values.
  • ST_RemovePoint - Enhanced: 3.2.0 Remove a point from a linestring.
  • ST_RemoveRepeatedPoints - Enhanced: 3.2.0 Returns a version of a geometry with duplicate points removed.
  • ST_StartPoint - Enhanced: 3.2.0 returns a point for all geometries. Prior behavior returns NULLs if input was not a LineString. Returns the first point of a LineString, CircularLineString, or NURBSCurve.
  • ST_Value - 개선 사항: 2.1.0 버전부터 선택적인 exclude_nodata_value 인수를 추가했습니다. 입력 columnx, rowy 픽셀의 입력 밴드의 값, 또는 특정 기하학적 포인트의 밴드의 값을 반환합니다. 밴드 번호는 1부터 시작하며, 따로 지정하지 않을 경우 1로 가정합니다. exclude_nodata_value 를 거짓으로 설정할 경우, nodata 픽셀을 포함한 모든 픽셀이 교차한다고 가정하고 값을 반환합니다. exclude_nodata_value 를 설정하지 않은 경우, 래스터의 메타데이터에서 값을 읽어 들입니다.
  • TopoGeo_AddLineString - Enhanced: 3.2.0 added support for returning signed identifier. Adds a linestring to an existing topology using a tolerance and possibly splitting existing edges/faces.

Functions changed in PostGIS 3.2

  • ST_Boundary - Changed: 3.2.0 support for TIN, does not use geos, does not linearize curves 해당 도형의 결합된 범위의 닫힘 여부를 반환합니다.
  • ValidateTopology - Changed: 3.2.0 added optional bbox parameter, perform face labeling and edge linking checks. Returns a set of validatetopology_returntype objects detailing issues with topology.

13.12.7. PostGIS Functions new or enhanced in 3.1

The functions given below are PostGIS functions that were added or enhanced.

Functions new in PostGIS 3.1

  • ST_Hexagon - 2.1.0 버전부터 사용할 수 있습니다. Returns a single hexagon, using the provided edge size and cell coordinate within the hexagon grid space.
  • ST_HexagonGrid - 2.1.0 버전부터 사용할 수 있습니다. Returns a set of hexagons and cell indices that completely cover the bounds of the geometry argument.
  • ST_MaximumInscribedCircle - Availability: 3.1.0. 도형의 기하학적 중심을 반환합니다.
  • ST_ReducePrecision - Availability: 3.1.0. Returns a valid geometry with points rounded to a grid tolerance.
  • ST_Square - 2.1.0 버전부터 사용할 수 있습니다. Returns a single square, using the provided edge size and cell coordinate within the square grid space.
  • ST_SquareGrid - 2.1.0 버전부터 사용할 수 있습니다. Returns a set of grid squares and cell indices that completely cover the bounds of the geometry argument.

Functions enhanced in PostGIS 3.1

  • ST_AsEWKT - Enhanced: 3.1.0 support for optional precision parameter. 도형의 WKT(Well-Known Text) 표현식을 SRID 메타데이터와 함께 반환합니다.
  • ST_ClusterKMeans - Enhanced: 3.1.0 Support for 3D geometries and weights Window function that returns a cluster id for each input geometry using the K-means algorithm.
  • ST_Difference - Enhanced: 3.1.0 accept a gridSize parameter. Computes a geometry representing the part of geometry A that does not intersect geometry B.
  • ST_Intersection - Enhanced: 3.1.0 accept a gridSize parameter Computes a geometry representing the shared portion of geometries A and B.
  • ST_MakeValid - Enhanced: 3.1.0, added removal of Coordinates with NaN values. Attempts to make an invalid geometry valid without losing vertices.
  • ST_Subdivide - Enhanced: 3.1.0 accept a gridSize parameter. Computes a rectilinear subdivision of a geometry.
  • ST_SymDifference - Enhanced: 3.1.0 accept a gridSize parameter. Computes a geometry representing the portions of geometries A and B that do not intersect.
  • ST_TileEnvelope - 개선 사항: 2.0.0 버전에서 선택적인 기본 SRID 파라미터가 추가됐습니다. Creates a rectangular Polygon in Web Mercator (SRID:3857) using the XYZ tile system.
  • ST_UnaryUnion - Enhanced: 3.1.0 accept a gridSize parameter. Computes the union of the components of a single geometry.
  • ST_Union - Enhanced: 3.1.0 accept a gridSize parameter. Computes a geometry representing the point-set union of the input geometries.

Functions changed in PostGIS 3.1

  • ST_Count - 2.2.0 버전부터 더 이상 ST_Count(rastertable, rastercolumn, ...) 변종 함수를 지원하지 않습니다. 대신 함수를 이용하십시오. 래스터 또는 래스터 커버리지의 입력 밴드에 있는 픽셀 개수를 반환합니다. 밴드를 따로 설정하지 않을 경우 기본값은 밴드 1입니다. exclude_nodata_value를 참으로 설정할 경우, NODATA 값이 아닌 픽셀의 개수만 반환할 것입니다.
  • ST_Force3D - Changed: 3.1.0. Added support for supplying a non-zero Z value. 도형을 XYZ 모드로 강제합니다. ST_Force3DZ라고도 합니다.
  • ST_Force3DM - Changed: 3.1.0. Added support for supplying a non-zero M value. 도형을 XYM 모드로 강제합니다.
  • ST_Force3DZ - Changed: 3.1.0. Added support for supplying a non-zero Z value. 도형을 XYZ 모드로 강제합니다.
  • ST_Force4D - Changed: 3.1.0. Added support for supplying non-zero Z and M values. 도형을 XYZM 모드로 강제합니다.
  • ST_Histogram - Changed: 3.1.0 Removed ST_Histogram(table_name, column_name) variant. 빈(bin; 히스토그램 표시에서 수직 막대로 나타나는 단위) 범위로 구분된 래스터 또는 래스터 커버리지의 데이터 분포를 요약하는 레코드 집합을 반환합니다. 따로 설정하지 않을 경우 빈의 개수를 자동으로 계산합니다.
  • ST_Quantile - Changed: 3.1.0 Removed ST_Quantile(table_name, column_name) variant. 샘플링 또는 채우기(population)라는 맥락에서 래스터 또는 래스터 테이블 커버리지의 사분위(quantile)를 계산합니다. 따라서, 래스터의 25%, 50%, 75% 백분위(percentile) 단계로 값을 확인할 수 있습니다.
  • ST_SummaryStats - 2.2.0 버전부터 더 이상 ST_SummaryStats(rastertable, rastercolumn, ...) 변종 함수를 지원하지 않습니다. 대신 함수를 이용하십시오. Returns summarystats consisting of count, sum, mean, stddev, min, max for a given raster band of a raster or raster coverage. Band 1 is assumed if no band is specified.

13.12.8. PostGIS Functions new or enhanced in 3.0

The functions given below are PostGIS functions that were added or enhanced.

Functions new in PostGIS 3.0

  • CG_ConstrainedDelaunayTriangles - 2.1.0 버전부터 사용할 수 있습니다. Return a constrained Delaunay triangulation around the given input geometry.
  • ST_3DLineInterpolatePoint - 2.1.0 버전부터 사용할 수 있습니다. Returns a point interpolated along a 3D line at a fractional location.
  • ST_TileEnvelope - 2.1.0 버전부터 사용할 수 있습니다. Creates a rectangular Polygon in Web Mercator (SRID:3857) using the XYZ tile system.

Functions enhanced in PostGIS 3.0

  • ST_AsMVT - Enhanced: 3.0 - added support for Feature ID. Aggregate function returning a MVT representation of a set of rows.
  • ST_Contains - Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION Tests if every point of B lies in A, and their interiors have a point in common
  • ST_ContainsProperly - Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION Tests if every point of B lies in the interior of A
  • ST_CoveredBy - Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION Tests if every point of A lies in B
  • ST_Covers - Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION Tests if every point of B lies in A
  • ST_Crosses - Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION Tests if two geometries have some, but not all, interior points in common
  • ST_CurveToLine - Enhanced: 3.0.0 implemented a minimum number of segments per linearized arc to prevent topological collapse. Converts a geometry containing curves to a linear geometry.
  • ST_Disjoint - Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION Tests if two geometries have no points in common
  • ST_Equals - Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION Tests if two geometries include the same set of points
  • ST_GeneratePoints - Enhanced: 3.0.0, added seed parameter Generates a multipoint of random points contained in a Polygon or MultiPolygon.
  • ST_GeomFromGeoJSON - Enhanced: 3.0.0 parsed geometry defaults to SRID=4326 if not specified otherwise. GeoJSON 표현식을 입력받아 PostGIS 도형 객체를 출력합니다.
  • ST_LocateBetween - Enhanced: 3.0.0 - added support for POLYGON, TIN, TRIANGLE. Returns the portions of a geometry that match a measure range.
  • ST_LocateBetweenElevations - Enhanced: 3.0.0 - added support for POLYGON, TIN, TRIANGLE. Returns the portions of a geometry that lie in an elevation (Z) range.
  • ST_Overlaps - Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION Tests if two geometries have the same dimension and intersect, but each has at least one point not in the other
  • ST_Relate - Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION Tests if two geometries have a topological relationship matching an Intersection Matrix pattern, or computes their Intersection Matrix
  • ST_Segmentize - Enhanced: 3.0.0 Segmentize geometry now produces equal-length subsegments Returns a modified geometry/geography having no segment longer than a given distance.
  • ST_Touches - Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION Tests if two geometries have at least one point in common, but their interiors do not intersect
  • ST_Within - Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION Tests if every point of A lies in B, and their interiors have a point in common

Functions changed in PostGIS 3.0

  • PostGIS_Extensions_Upgrade - Changed: 3.0.0 to repackage loose extensions and support postgis_raster. Packages and upgrades PostGIS extensions (e.g. postgis_raster, postgis_topology, postgis_sfcgal) to given or latest version.
  • ST_3DDistance - Changed: 3.0.0 - SFCGAL version removed 도형 유형에 대해, 두 도형 사이의 (SRS에 기반한) 3차원 데카르트 최단 거리를 투영 단위로 반환합니다.
  • ST_3DIntersects - Changed: 3.0.0 SFCGAL backend removed, GEOS backend supports TINs. Tests if two geometries spatially intersect in 3D - only for points, linestrings, polygons, polyhedral surface (area)
  • ST_Area - Changed: 3.0.0 - does not depend on SFCGAL anymore. 도형의 기하학적 중심을 반환합니다.
  • ST_AsGeoJSON - Changed: 3.0.0 support records as input Return a geometry or feature in GeoJSON format.
  • ST_AsGeoJSON - Changed: 3.0.0 output SRID if not EPSG:4326. Return a geometry or feature in GeoJSON format.
  • ST_AsKML - Changed: 3.0.0 - Removed the "versioned" variant signature 도형을 GML 2 또는 GML 3 버전 요소로 반환합니다.
  • ST_Distance - Changed: 3.0.0 - does not depend on SFCGAL anymore. 두 도형 사이의 3차원 최장(longest) 라인을 반환합니다.
  • ST_Intersection - Changed: 3.0.0 does not depend on SFCGAL. Computes a geometry representing the shared portion of geometries A and B.
  • ST_Intersects - Changed: 3.0.0 SFCGAL version removed and native support for 2D TINS added. Tests if two geometries intersect (they have at least one point in common)
  • ST_Union - Changed: 3.0.0 does not depend on SFCGAL. Computes a geometry representing the point-set union of the input geometries.

13.12.9. PostGIS Functions new or enhanced in 2.5

The functions given below are PostGIS functions that were added or enhanced.

Functions new in PostGIS 2.5

  • PostGIS_Extensions_Upgrade - Availability: 2.5.0 Packages and upgrades PostGIS extensions (e.g. postgis_raster, postgis_topology, postgis_sfcgal) to given or latest version.
  • ST_Angle - Availability: 2.5.0 두 도형 사이의 3차원 최장(longest) 라인을 반환합니다.
  • ST_AsHexWKB - Availability: 2.5.0 Return the Well-Known Binary (WKB) in Hex representation of the raster.
  • ST_BandFileSize - Availability: 2.5.0 Returns the file size of a band stored in file system. If no bandnum specified, 1 is assumed.
  • ST_BandFileTimestamp - Availability: 2.5.0 Returns the file timestamp of a band stored in file system. If no bandnum specified, 1 is assumed.
  • ST_ChaikinSmoothing - Availability: 2.5.0 Returns a smoothed version of a geometry, using the Chaikin algorithm
  • ST_FilterByM - Availability: 2.5.0 Removes vertices based on their M value
  • ST_Grayscale - Availability: 2.5.0 Creates a new one-8BUI band raster from the source raster and specified bands representing Red, Green and Blue
  • ST_LineInterpolatePoints - Availability: 2.5.0 Returns points interpolated along a line at a fractional interval.
  • ST_OrientedEnvelope - Availability: 2.5.0. Returns a minimum-area rectangle containing a geometry.
  • ST_QuantizeCoordinates - Availability: 2.5.0 Sets least significant bits of coordinates to zero
  • ST_RastFromHexWKB - Availability: 2.5.0 Return a raster value from a Hex representation of Well-Known Binary (WKB) raster.
  • ST_RastFromWKB - Availability: 2.5.0 Return a raster value from a Well-Known Binary (WKB) raster.
  • ST_SetBandIndex - Availability: 2.5.0 Update the external band number of an out-db band
  • ST_SetBandPath - Availability: 2.5.0 Update the external path and band number of an out-db band

Functions enhanced in PostGIS 2.5

  • ST_AsBinary/ST_AsWKB - Enhanced: 2.5.0 Addition of ST_AsWKB Return the Well-Known Binary (WKB) representation of the raster.
  • ST_AsMVT - Enhanced: 2.5.0 - added support parallel query. Aggregate function returning a MVT representation of a set of rows.
  • ST_AsText - Enhanced: 2.5 - optional parameter precision introduced. 도형/지리형의 WKT(Well-Known Text) 표현식을 SRID 메타데이터 없이 반환합니다.
  • ST_BandMetaData - Enhanced: 2.5.0 to include outdbbandnum, filesize and filetimestamp for outdb rasters. 지정 래스터 밴드에 대한 기본 메타데이터를 반환합니다. 밴드를 지정하지 않을 경우 밴드 1번이라고 가정합니다.
  • ST_Buffer - Enhanced: 2.5.0 - ST_Buffer geometry support was enhanced to allow for side buffering specification side=both|left|right. Computes a geometry covering all points within a given distance from a geometry.
  • ST_GeomFromGeoJSON - Enhanced: 2.5.0 can now accept json and jsonb as inputs. GeoJSON 표현식을 입력받아 PostGIS 도형 객체를 출력합니다.
  • ST_GeometricMedian - Enhanced: 2.5.0 Added support for M as weight of points. 멀티 포인트의 기하학적 중심값(median)을 반환합니다.
  • ST_Intersects - Enhanced: 2.5.0 Supports GEOMETRYCOLLECTION. Tests if two geometries intersect (they have at least one point in common)
  • ST_OffsetCurve - Enhanced: 2.5 - added support for GEOMETRYCOLLECTION and MULTILINESTRING Returns an offset line at a given distance and side from an input line.
  • ST_Scale - Enhanced: 2.5.0 support for scaling relative to a local origin (origin parameter) was introduced. Scales a geometry by given factors.
  • ST_Split - Enhanced: 2.5.0 support for splitting a polygon by a multiline was introduced. Returns a collection of geometries created by splitting a geometry by another geometry.
  • ST_Subdivide - Enhanced: 2.5.0 reuses existing points on polygon split, vertex count is lowered from 8 to 5. Computes a rectilinear subdivision of a geometry.

Functions changed in PostGIS 2.5

  • ST_GDALDrivers - Changed: 2.5.0 - add can_read and can_write columns. Returns a list of raster formats supported by PostGIS through GDAL. Only those formats with can_write=True can be used by ST_AsGDALRaster

13.12.10. PostGIS Functions new or enhanced in 2.4

The functions given below are PostGIS functions that were added or enhanced.

Functions new in PostGIS 2.4

  • ST_AsGeobuf - 2.2.0 버전부터 사용할 수 있습니다. Return a Geobuf representation of a set of rows.
  • ST_AsMVT - 2.2.0 버전부터 사용할 수 있습니다. Aggregate function returning a MVT representation of a set of rows.
  • ST_AsMVTGeom - 2.2.0 버전부터 사용할 수 있습니다. Transforms a geometry into the coordinate space of a MVT tile.
  • ST_Centroid - Availability: 2.4.0 support for geography was introduced. 도형의 기하학적 중심을 반환합니다.
  • ST_ForcePolygonCCW - 2.2.0 버전부터 사용할 수 있습니다. Orients all exterior rings counter-clockwise and all interior rings clockwise.
  • ST_ForcePolygonCW - 2.2.0 버전부터 사용할 수 있습니다. Orients all exterior rings clockwise and all interior rings counter-clockwise.
  • ST_FrechetDistance - Availability: 2.4.0 - requires GEOS >= 3.7.0 두 도형 사이의 3차원 최단(shortest) 라인을 반환합니다.
  • ST_IsPolygonCCW - 2.2.0 버전부터 사용할 수 있습니다. Tests if Polygons have exterior rings oriented counter-clockwise and interior rings oriented clockwise.
  • ST_IsPolygonCW - 2.2.0 버전부터 사용할 수 있습니다. Tests if Polygons have exterior rings oriented clockwise and interior rings oriented counter-clockwise.
  • ST_MakeEmptyCoverage - 2.2.0 버전부터 사용할 수 있습니다. Cover georeferenced area with a grid of empty raster tiles.

Functions enhanced in PostGIS 2.4

  • ST_AsTWKB - Enhanced: 2.4.0 memory and speed improvements. 도형을 TWKB(Tiny Well-Known Binary)로 반환합니다.
  • ST_Covers - Enhanced: 2.4.0 Support for polygon in polygon and line in polygon added for geography type Tests if every point of B lies in A
  • ST_CurveToLine - Enhanced: 2.4.0 added support for max-deviation and max-angle tolerance, and for symmetric output. Converts a geometry containing curves to a linear geometry.
  • ST_Project - Enhanced: 2.4.0 Allow negative distance and non-normalized azimuth. Returns a point projected from a start point by a distance and bearing (azimuth).
  • ST_Reverse - Enhanced: 2.4.0 support for curves was introduced. 꼭짓점들의 순서가 반대인 도형을 반환합니다.

Functions changed in PostGIS 2.4

  • = - Changed: 2.4.0, in prior versions this was bounding box equality not a geometric equality. If you need bounding box equality, use instead. Returns TRUE if the coordinates and coordinate order geometry/geography A are the same as the coordinates and coordinate order of geometry/geography B.
  • ST_Node - Changed: 2.4.0 this function uses GEOSNode internally instead of GEOSUnaryUnion. This may cause the resulting linestrings to have a different order and direction compared to PostGIS < 2.4. Nodes a collection of lines.

13.12.11. PostGIS Functions new or enhanced in 2.3

The functions given below are PostGIS functions that were added or enhanced.

Functions new in PostGIS 2.3

  • &&&(geometry,gidx) - Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Returns TRUE if a geometry's (cached) n-D bounding box intersects a n-D float precision bounding box (GIDX).
  • &&&(gidx,geometry) - Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Returns TRUE if a n-D float precision bounding box (GIDX) intersects a geometry's (cached) n-D bounding box.
  • &&&(gidx,gidx) - Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Returns TRUE if two n-D float precision bounding boxes (GIDX) intersect each other.
  • &&(box2df,box2df) - Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Returns TRUE if two 2D float precision bounding boxes (BOX2DF) intersect each other.
  • &&(box2df,geometry) - Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Returns TRUE if a 2D float precision bounding box (BOX2DF) intersects a geometry's (cached) 2D bounding box.
  • &&(geometry,box2df) - Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Returns TRUE if a geometry's (cached) 2D bounding box intersects a 2D float precision bounding box (BOX2DF).
  • @(box2df,box2df) - Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Returns TRUE if a 2D float precision bounding box (BOX2DF) is contained into another 2D float precision bounding box.
  • @(box2df,geometry) - Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Returns TRUE if a 2D float precision bounding box (BOX2DF) is contained into a geometry's 2D bounding box.
  • @(geometry,box2df) - Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Returns TRUE if a geometry's 2D bounding box is contained into a 2D float precision bounding box (BOX2DF).
  • Populate_Topology_Layer - 2.3.0 버전부터 사용할 수 있습니다. Adds missing entries to topology.layer table by reading metadata from topo tables.
  • ST_ClusterDBSCAN - 2.3.0 버전부터 사용할 수 있습니다. Window function that returns a cluster id for each input geometry using the DBSCAN algorithm.
  • ST_ClusterKMeans - 2.3.0 버전부터 사용할 수 있습니다. Window function that returns a cluster id for each input geometry using the K-means algorithm.
  • ST_GeneratePoints - 2.3.0 버전부터 사용할 수 있습니다. Generates a multipoint of random points contained in a Polygon or MultiPolygon.
  • ST_GeometricMedian - 2.3.0 버전부터 사용할 수 있습니다. 멀티 포인트의 기하학적 중심값(median)을 반환합니다.
  • ST_MakeLine - 2.0.0 버전부터 라인스트링 구성 요소 입력을 지원하기 시작했습니다. 포인트, 멀티포인트 또는 라인 도형으로부터 라인스트링을 생성합니다.
  • ST_MinimumBoundingRadius - 2.3.0 버전부터 사용할 수 있습니다. Returns the center point and radius of the smallest circle that contains a geometry.
  • ST_MinimumClearance - 2.3.0 버전부터 사용할 수 있습니다. 도형의 튼튼함(robustness)의 척도인 도형의 최소 여유(clearance)를 반환합니다.
  • ST_MinimumClearanceLine - 2.3.0 버전부터 사용할 수 있습니다. GEOS 3.6.0 이상 버전이 필요합니다. 포인트 2개로 이루어진, 도형의 최소 여유를 나타내는 라인스트링을 반환합니다.
  • ST_Normalize - 2.3.0 버전부터 사용할 수 있습니다. 도형을 해당 도형의 기본형으로 반환합니다.
  • ST_Points - 2.3.0 버전부터 사용할 수 있습니다. 도형의 모든 좌표들을 담고 있는 멀티포인트를 반환합니다.
  • ST_VoronoiLines - 2.3.0 버전부터 사용할 수 있습니다. Returns the boundaries of the Voronoi diagram of the vertices of a geometry.
  • ST_VoronoiPolygons - 2.3.0 버전부터 사용할 수 있습니다. Returns the cells of the Voronoi diagram of the vertices of a geometry.
  • ST_WrapX - Availability: 2.3.0 requires GEOS X값 근처에서 도형을 래핑합니다.
  • TopoGeom_addElement - 2.3 버전부터 사용할 수 있습니다. Adds an element to the definition of a TopoGeometry.
  • TopoGeom_remElement - 2.3 버전부터 사용할 수 있습니다. Removes an element from the definition of a TopoGeometry.
  • ~(box2df,box2df) - Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Returns TRUE if a 2D float precision bounding box (BOX2DF) contains another 2D float precision bounding box (BOX2DF).
  • ~(box2df,geometry) - Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Returns TRUE if a 2D float precision bounding box (BOX2DF) contains a geometry's 2D bonding box.
  • ~(geometry,box2df) - Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Returns TRUE if a geometry's 2D bonding box contains a 2D float precision bounding box (GIDX).

Functions enhanced in PostGIS 2.3

  • ST_Contains - Enhanced: 2.3.0 Enhancement to PIP short-circuit extended to support MultiPoints with few points. Prior versions only supported point in polygon. Tests if every point of B lies in A, and their interiors have a point in common
  • ST_Covers - Enhanced: 2.3.0 Enhancement to PIP short-circuit for geometry extended to support MultiPoints with few points. Prior versions only supported point in polygon. Tests if every point of B lies in A
  • ST_Expand - Enhanced: 2.3.0 support was added to expand a box by different amounts in different dimensions. Returns a bounding box expanded from another bounding box or a geometry.
  • ST_Intersects - Enhanced: 2.3.0 Enhancement to PIP short-circuit extended to support MultiPoints with few points. Prior versions only supported point in polygon. Tests if two geometries intersect (they have at least one point in common)
  • ST_Segmentize - Enhanced: 2.3.0 Segmentize geography now produces equal-length subsegments Returns a modified geometry/geography having no segment longer than a given distance.
  • ST_Transform - Enhanced: 2.3.0 support for direct PROJ.4 text was introduced. Return a new geometry with coordinates transformed to a different spatial reference system.
  • ST_Within - Enhanced: 2.3.0 Enhancement to PIP short-circuit for geometry extended to support MultiPoints with few points. Prior versions only supported point in polygon. Tests if every point of A lies in B, and their interiors have a point in common

Functions changed in PostGIS 2.3

  • ST_PointN - 변경 사항: 2.3.0 버전부터 음수 인덱스(-1이 마지막 포인트)를 이용할 수 있습니다. ST_LineString 또는 ST_CircularString 값에 있는 포인트의 개수를 반환합니다.

13.12.12. PostGIS Functions new or enhanced in 2.2

The functions given below are PostGIS functions that were added or enhanced.

Functions new in PostGIS 2.2

  • <<->> - Availability: 2.2.0. Returns the n-D distance between the A and B geometries or bounding boxes
  • ST_AsEncodedPolyline - 2.2.0 버전부터 사용할 수 있습니다. 라인스트링 도형으로부터 인코딩된 폴리라인을 반환합니다.
  • ST_AsTWKB - 2.2.0 버전부터 사용할 수 있습니다. 도형을 TWKB(Tiny Well-Known Binary)로 반환합니다.
  • ST_BoundingDiagonal - 2.2.0 버전부터 사용할 수 있습니다. 주어진 도형의 경계 상자의 대각선을 반환합니다.
  • ST_CPAWithin - 2.2.0 버전부터 사용할 수 있습니다. Tests if the closest point of approach of two trajectories is within the specified distance.
  • ST_ClipByBox2D - 2.2.0 버전부터 사용할 수 있습니다. Computes the portion of a geometry falling within a rectangle.
  • ST_ClosestPointOfApproach - 2.2.0 버전부터 사용할 수 있습니다. Returns a measure at the closest point of approach of two trajectories.
  • ST_ClusterIntersecting - 2.2.0 버전부터 사용할 수 있습니다. Aggregate function that clusters input geometries into connected sets.
  • ST_ClusterWithin - 2.2.0 버전부터 사용할 수 있습니다. Aggregate function that clusters geometries by separation distance.
  • ST_CountAgg - 2.2.0 버전부터 사용할 수 있습니다. 종합 함수입니다. 래스터 집합의 입력 밴드에 있는 픽셀 개수를 반환합니다. 밴드를 따로 설정하지 않을 경우 기본값은 밴드 1입니다. exclude_nodata_value를 참으로 설정할 경우, NODATA 값이 아닌 픽셀의 개수만 반환할 것입니다.
  • ST_CreateOverview - 2.2.0 버전부터 사용할 수 있습니다. 입력 래스터 커버리지의 저해상도 버전을 생성합니다.
  • ST_DistanceCPA - 2.2.0 버전부터 사용할 수 있습니다. Returns the distance between the closest point of approach of two trajectories.
  • ST_ForceCurve - 2.2.0 버전부터 사용할 수 있습니다. 적용이 가능한 경우, 도형을 해당 도형의 만곡 유형으로 상위 형변환(upcast)합니다.
  • ST_IsValidTrajectory - 2.2.0 버전부터 사용할 수 있습니다. Tests if the geometry is a valid trajectory.
  • ST_LineFromEncodedPolyline - 2.2.0 버전부터 사용할 수 있습니다. 인코딩된 폴리라인(polyline)으로부터 라인스트링을 생성합니다.
  • ST_MapAlgebra (callback function version) - 2.2.0 버전부터 mask를 추가할 수 있습니다. 콜백 함수 버전 - 래스터 1개 이상, 밴드 인덱스, 그리고 사용자 지정 콜백 함수 1개를 입력받아 밴드 1개를 가진 래스터를 반환합니다.
  • ST_MemSize - 2.2.0 버전부터 사용할 수 있습니다. 래스터가 차지하는 공간의 용량을 (바이트 단위로) 반환합니다.
  • ST_RemoveRepeatedPoints - 2.2.0 버전부터 사용할 수 있습니다. Returns a version of a geometry with duplicate points removed.
  • ST_Retile - 2.2.0 버전부터 사용할 수 있습니다. 임의로 타일화된 래스터 커버리지로부터, 설정된 타일들의 집합을 반환합니다.
  • ST_SetEffectiveArea - 2.2.0 버전부터 사용할 수 있습니다. Sets the effective area for each vertex, using the Visvalingam-Whyatt algorithm.
  • ST_SimplifyVW - 2.2.0 버전부터 사용할 수 있습니다. Returns a simplified representation of a geometry, using the Visvalingam-Whyatt algorithm
  • ST_Subdivide - 2.2.0 버전부터 사용할 수 있습니다. Computes a rectilinear subdivision of a geometry.
  • ST_SummaryStatsAgg - 2.2.0 버전부터 사용할 수 있습니다. Aggregate. Returns summarystats consisting of count, sum, mean, stddev, min, max for a given raster band of a set of raster. Band 1 is assumed if no band is specified.
  • ST_SwapOrdinates - 2.2.0 버전부터 사용할 수 있습니다. 입력 도형을 좌표값을 뒤바꾼 상태로 반환합니다.
  • postgis.enable_outdb_rasters - 2.2.0 버전부터 사용할 수 있습니다. DB 외부 래스터 밴드에 접근할 수 있게 해주는 불 설정 옵션입니다.
  • postgis.gdal_datapath - 2.2.0 버전부터 사용할 수 있습니다. GDAL의 GDAL_DATA 옵션의 값을 할당하는 설정 옵션입니다. 설정하지 않을 경우, 환경적으로 설정된 GDAL_DATA 변수를 사용합니다.
  • postgis.gdal_enabled_drivers - 2.2.0 버전부터 사용할 수 있습니다. PostGIS 환경에서 사용할 수 있는 GDAL 드라이버를 설정하는 설정 옵션입니다. GDAL 설정 변수 GDAL_SKIP에 영향을 미칩니다.
  • |=| - Availability: 2.2.0. A와 B 사이의 최근접점(closest point of approach)을 잇는 궤도(trajectory)의 거리를 반환합니다.

Functions enhanced in PostGIS 2.2

  • <-> - Enhanced: 2.2.0 -- True KNN ("K nearest neighbor") behavior for geometry and geography. Note for geography KNN is based on sphere rather than spheroid. A와 B 사이의 2차원 거리를 반환합니다.
  • AsTopoJSON - 개선 사항: 2.2.1 버전부터 점형(puntal) 입력을 지원하기 시작했습니다. TopoGeometry의 TopoJSON 표현식을 반환합니다.
  • ST_Area - 개선 사항: 2.2.0 버전부터 회전타원체 측정시 정확도와 강력함을 향상시키기 위해 GeographicLib을 이용합니다. 이 새 기능의 장점을 취하려면 Proj 4.9.0 이상 버전이 필요합니다. 도형의 기하학적 중심을 반환합니다.
  • ST_AsX3D - 개선 사항: 2.2.0 버전부터 지리좌표 및 축(x/y, 경도/위도) 뒤집기를 지원합니다. 자세한 내용은 옵션을 살펴보십시오. 도형을 X3D XML 노드 요소 형식: ISO-IEC-19776-1.2-X3DEncodings-XML로 반환합니다.
  • ST_Azimuth - 개선 사항: 2.2.0 버전부터 회전타원체 측정시 정확도와 강력함을 향상시키기 위해 GeographicLib을 이용합니다. 이 새 기능의 장점을 취하려면 Proj 4.9.0 이상 버전이 필요합니다. 두 도형 사이의 2차원 최단 라인을 반환합니다.
  • ST_Distance - 개선 사항: 2.2.0 버전부터 회전타원체 측정시 정확도와 강력함을 향상시키기 위해 GeographicLib을 이용합니다. 이 새 기능의 장점을 취하려면 Proj 4.9.0 이상 버전이 필요합니다. 두 도형 사이의 3차원 최장(longest) 라인을 반환합니다.
  • ST_Scale - Enhanced: 2.2.0 support for scaling all dimension (factor parameter) was introduced. Scales a geometry by given factors.
  • ST_Split - Enhanced: 2.2.0 support for splitting a line by a multiline, a multipoint or (multi)polygon boundary was introduced. Returns a collection of geometries created by splitting a geometry by another geometry.
  • ST_Summary - 개선 사항: 2.2.0 버전부터 TIN 및 만곡 도형(curve)을 지원하기 시작했습니다. 도형의 내용을 요약한 텍스트를 반환합니다.

Functions changed in PostGIS 2.2

  • <-> - Changed: 2.2.0 -- Old hybrid-syntax workarounds may be slower once true KNN is available. See examples below. A와 B 사이의 2차원 거리를 반환합니다.
  • ST_3DClosestPoint - 변경 사항: 2.2.0 버전부터 2D 도형 두 개를 입력할 경우, (존재하지 않는 Z을 0으로 가정하는 예전 습성 대신) 2D 포인트를 반환합니다. 2D 및 3D의 경우, 더 이상 Z가 없을 때 Z를 0으로 가정하지 않습니다. g2에 가장 가까운 g1 상에 있는 3차원 포인트를 반환합니다. 해당 포인트는 3D 최단 라인의 첫 번째 포인트입니다.
  • ST_3DDistance - 변경 사항: 2.2.0 버전부터, 2D 및 3D의 경우 더 이상 Z가 없을 때 Z를 0으로 가정하지 않습니다. 도형 유형에 대해, 두 도형 사이의 (SRS에 기반한) 3차원 데카르트 최단 거리를 투영 단위로 반환합니다.
  • ST_3DLongestLine - 변경 사항: 2.2.0 버전부터 2D 도형 두 개를 입력할 경우, (존재하지 않는 Z을 0으로 가정하는 예전 습성 대신) 2D 포인트를 반환합니다. 2D 및 3D의 경우, 더 이상 Z가 없을 때 Z를 0으로 가정하지 않습니다. 두 도형 사이의 3차원 최장(longest) 라인을 반환합니다.
  • ST_3DMaxDistance - 변경 사항: 2.2.0 버전부터, 2D 및 3D의 경우 더 이상 Z가 없을 때 Z를 0으로 가정하지 않습니다. 도형 유형에 대해, 두 도형 사이의 (SRS에 기반한) 3차원 데카르트 최장 거리를 투영 단위로 반환합니다.
  • ST_3DShortestLine - 변경 사항: 2.2.0 버전부터 2D 도형 두 개를 입력할 경우, (존재하지 않는 Z을 0으로 가정하는 예전 습성 대신) 2D 포인트를 반환합니다. 2D 및 3D의 경우, 더 이상 Z가 없을 때 Z를 0으로 가정하지 않습니다. 두 도형 사이의 3차원 최단(shortest) 라인을 반환합니다.
  • ST_DistanceSphere - 변경 사항: 2.2.0 미만 버전에서는 ST_Distance_Sphere라는 명칭이었습니다. 특정 회전타원체가 주어진 두 경위도 도형 사이의 최단 거리를 반환합니다. PostGIS 1.5 미만 버전은 포인트만 지원했습니다.
  • ST_DistanceSpheroid - 변경 사항: 2.2.0 미만 버전에서는 ST_Distance_Spheroid라는 명칭이었습니다. 특정 회전타원체가 주어진 두 경위도 도형 사이의 최단 거리를 반환합니다. PostGIS 1.5 미만 버전은 포인트만 지원했습니다.
  • ST_Equals - Changed: 2.2.0 Returns true even for invalid geometries if they are binary equal Tests if two geometries include the same set of points
  • ST_LengthSpheroid - 변경 사항: 2.2.0 미만 버전에서는 ST_Length_Spheroid라는 명칭이었으며, ST_3DLength_Spheroid라는 동일 함수가 있었습니다. 도형의 기하학적 중심을 반환합니다.
  • ST_MemSize - Changed: 2.2.0 name changed to ST_MemSize to follow naming convention. ST_Geometry 값의 도형 유형을 반환합니다.
  • ST_PointInsideCircle - Changed: 2.2.0 In prior versions this was called ST_Point_Inside_Circle Tests if a point geometry is inside a circle defined by a center and radius
  • ValidateTopology - 변경 사항: 2.2.0 버전에서 'edge crosses node'를 오류 설명문과 일치시키기 위해 id1과 id2의 값을 서로 바꿨습니다. Returns a set of validatetopology_returntype objects detailing issues with topology.

13.12.13. PostGIS Functions new or enhanced in 2.1

The functions given below are PostGIS functions that were added or enhanced.

Functions new in PostGIS 2.1

  • = - 2.1.0 버전부터 사용할 수 있습니다. A의 경계 상자와 B의 경계 상자가 동일할 경우 TRUE 를 반환합니다. 이중 정밀도 경계 상자를 이용합니다.
  • AsTopoJSON - 2.1.0 버전부터 사용할 수 있습니다. TopoGeometry의 TopoJSON 표현식을 반환합니다.
  • ST_Box2dFromGeoHash - 2.1.0 버전부터 사용할 수 있습니다. GeoHash 스트링으로부터 BOX2D를 반환합니다.
  • ST_ColorMap - 2.1.0 버전부터 사용할 수 있습니다. 소스 래스터 및 설정한 밴드로부터 8BUI 밴드(grayscale, RGB, RGBA)를 4개까지 가지는 새 래스터를 생성합니다. 밴드를 따로 설정하지 않으면 밴드 1로 가정합니다.
  • ST_Contains - 2.1.0 버전부터 사용할 수 있습니다. 래스터 rastA 외부에 놓인 래스터 rastB의 포인트가 하나도 없고, 적어도 rastB 내부의 포인트 하나가 rastA의 내부에 있는 경우 참을 반환합니다.
  • ST_ContainsProperly - 2.1.0 버전부터 사용할 수 있습니다. rastB가 rastA의 내부와 교차하지만 rastA의 경계선 또는 외부와 교차하지는 않을 경우 참을 반환합니다.
  • ST_CoveredBy - 2.1.0 버전부터 사용할 수 있습니다. 래스터 rastA의 어떤 포인트도 래스터 rastB 외부에 없을 경우 참을 반환합니다.
  • ST_Covers - 2.1.0 버전부터 사용할 수 있습니다. 래스터 rastB의 어떤 포인트도 래스터 rastA 외부에 없을 경우 참을 반환합니다.
  • ST_DFullyWithin - 2.1.0 버전부터 사용할 수 있습니다. 래스터 rastA와 래스터 rastB가 완전히 서로 설정된 거리 안에 있을 경우 참을 반환합니다.
  • ST_DWithin - 2.1.0 버전부터 사용할 수 있습니다. 래스터 rastA와 래스터 rastB가 서로 설정된 거리 안에 있을 경우 참을 반환합니다.
  • ST_DelaunayTriangles - 2.1.0 버전부터 사용할 수 있습니다. Returns the Delaunay triangulation of the vertices of a geometry.
  • ST_Disjoint - 2.1.0 버전부터 사용할 수 있습니다. 래스터 rastA와 래스터 rastB가 공간적으로 교차하지 않을 경우 참을 반환합니다.
  • ST_DumpValues - 2.1.0 버전부터 사용할 수 있습니다. 지정된 밴드의 값들을 2차원 배열로 반환합니다.
  • ST_ForceSFS - 2.1.0 버전부터 사용할 수 있습니다. Force geometries to use SFS 1.1 or 1.2 geometry types.
  • ST_FromGDALRaster - 2.1.0 버전부터 사용할 수 있습니다. 지원 GDAL 래스터 파일로부터 래스터를 반환합니다.
  • ST_GeomFromGeoHash - 2.1.0 버전부터 사용할 수 있습니다. GeoHash 스트링으로부터 도형을 반환합니다.
  • ST_InvDistWeight4ma - 2.1.0 버전부터 사용할 수 있습니다. 픽셀의 이웃으로부터 픽셀 값을 보간하는 래스터 공간 처리 함수입니다.
  • ST_MapAlgebra (callback function version) - 2.1.0 버전부터 사용할 수 있습니다. 콜백 함수 버전 - 래스터 1개 이상, 밴드 인덱스, 그리고 사용자 지정 콜백 함수 1개를 입력받아 밴드 1개를 가진 래스터를 반환합니다.
  • ST_MapAlgebra (expression version) - 2.1.0 버전부터 사용할 수 있습니다. 표현식 버전 - 입력 래스터 1개 또는 2개, 밴드 인덱스, 그리고 사용자 지정 SQL 표현식 1개 이상을 입력받아 밴드 1개를 가진 래스터를 반환합니다.
  • ST_MinConvexHull - 2.1.0 버전부터 사용할 수 있습니다. 래스터의 NODATA 픽셀을 제외한 볼록 껍질 도형을 반환합니다.
  • ST_MinDist4ma - 2.1.0 버전부터 사용할 수 있습니다. 관심 픽셀과 값을 가지고 있는 이웃 픽셀 사이의 최소 거리를 (픽셀 개수로) 반환하는 래스터 공간 처리 함수입니다.
  • ST_NearestValue - 2.1.0 버전부터 사용할 수 있습니다. columnx 및 rowy, 또는 래스터와 동일한 공간 참조 좌표 시스템 단위로 표현된 기하학적 포인트로 지정된 입력 밴드의 픽셀에 가장 가까운 NODATA 가 아닌 값을 반환합니다.
  • ST_Neighborhood - 2.1.0 버전부터 사용할 수 있습니다. columnx 및 rowy, 또는 래스터와 동일한 공간 참조 좌표 시스템 단위로 표현된 기하학적 포인트로 지정된 입력 밴드의 픽셀 주위의 NODATA 가 아닌 값들의 이중 정밀도 데이터형 2차원 배열을 반환합니다.
  • ST_NotSameAlignmentReason - 2.1.0 버전부터 사용할 수 있습니다. 래스터들이 정렬돼 있는지 아닌지, 그리고 정렬되지 않았다면 그 이유를 설명하는 텍스트를 반환합니다.
  • ST_Overlaps - 2.1.0 버전부터 사용할 수 있습니다. 래스터 rastA와 래스터 rastB가 교차하지만 어느 한 쪽이 다른 한 쪽을 완전히 담고 있지는 않을 경우 참을 반환합니다.
  • ST_PixelAsCentroid - 2.1.0 버전부터 사용할 수 있습니다. 픽셀 하나가 차지하는 면의 중심점(포인트 도형)을 반환합니다.
  • ST_PixelAsCentroids - 2.1.0 버전부터 사용할 수 있습니다. 래스터 밴드의 각 픽셀에 대한 중심점(포인트 도형)을 각 픽셀의 값 및 X, Y 래스터 좌표와 함께 반환합니다. 포인트 도형은 픽셀이 차지하는 면의 중심점입니다.
  • ST_PixelAsPoint - 2.1.0 버전부터 사용할 수 있습니다. 픽셀의 좌상단에 위치하는 포인트 도형을 반환합니다.
  • ST_PixelAsPoints - 2.1.0 버전부터 사용할 수 있습니다. 래스터 밴드의 각 픽셀에 대한 포인트 도형을 각 픽셀의 값 및 X, Y 래스터 좌표와 함께 반환합니다. 포인트 도형의 좌표는 픽셀의 좌상단 좌표입니다.
  • ST_PixelOfValue - 2.1.0 버전부터 사용할 수 있습니다. 검색 값과 일치하는 값을 가진 픽셀의 columnx, rowy 좌표를 반환합니다.
  • ST_PointFromGeoHash - 2.1.0 버전부터 사용할 수 있습니다. GeoHash 스트링으로부터 포인트를 반환합니다.
  • ST_RasterToWorldCoord - 2.1.0 버전부터 사용할 수 있습니다. 주어진 열과 행에 있는 래스터의 좌상단의 기하학적 X, Y(경도, 위도)를 으로 반환합니다. 열과 행은 1부터 시작합니다.
  • ST_Resize - 2.1.0 버전부터 사용할 수 있습니다. GDAL 1.6.1 이상 버전이 필요합니다. 래스터의 크기를 새 너비/높이로 조정합니다.
  • ST_Roughness - 2.1.0 버전부터 사용할 수 있습니다. DEM의 계산된 "거칠기(roughness)"와 함께 래스터를 반환합니다.
  • ST_SetValues - 2.1.0 버전부터 사용할 수 있습니다. 지정한 밴드의 값들을 설정해서 나온 수정된 래스터를 반환합니다.
  • ST_Simplify - 2.1.0 버전부터 사용할 수 있습니다. 더글러스-패커(Douglas-Peucker) 알고리즘을 통해 입력 TopoGeometry 의 "단순화된" 도형 버전을 반환합니다.
  • ST_Summary - 2.1.0 버전부터 사용할 수 있습니다. 래스터의 내용을 요약한 텍스트를 반환합니다.
  • ST_TPI - 2.1.0 버전부터 사용할 수 있습니다. 계산된 지형위치지수(Topographic Position Index)와 함께 래스터를 반환합니다.
  • ST_TRI - 2.1.0 버전부터 사용할 수 있습니다. 계산된 지형험준도지수(Terrain Ruggedness Index)와 함께 래스터를 반환합니다.
  • ST_Tile - 2.1.0 버전부터 사용할 수 있습니다. 출력 래스터에 원하는 차원을 바탕으로 입력 래스터를 분할해서 나온 래스터들의 집합을 반환합니다.
  • ST_Touches - 2.1.0 버전부터 사용할 수 있습니다. 래스터 rastA와 래스터 rastB가 최소한 포인트 한 개를 공유하지만, 내부가 교차하지는 않을 경우 TRUE 를 반환합니다.
  • ST_Union - 2.1.0 버전부터 ST_Union(rast, unionarg) 변종을 사용할 수 있습니다. 래스터 타일 집합을 1개 이상의 밴드로 이루어진 단일 래스터로 통합합니다.
  • ST_Within - 2.1.0 버전부터 사용할 수 있습니다. 래스터 rastB 외부에 놓인 래스터 rastA의 포인트가 하나도 없고, 적어도 rastA 내부의 포인트 하나가 rastB의 내부에 있는 경우 참을 반환합니다.
  • ST_WorldToRasterCoord - 2.1.0 버전부터 사용할 수 있습니다. 주어진 기하학적 X, Y(경도, 위도)의 좌상단을 열과 행으로 또는 래스터의 공간 참조 좌표 시스템 단위로 표현된 포인트 도형으로 반환합니다.
  • UpdateRasterSRID - 2.1.0 버전부터 사용할 수 있습니다. 사용자가 지정한 열 및 테이블에 있는 모든 래스터의 SRID를 변경합니다.
  • clearTopoGeom - 2.1 버전부터 사용할 수 있습니다. Clears the content of a topo geometry.
  • postgis_sfcgal_version - 2.1.0 버전부터 사용할 수 있습니다. 실행중인 SFCGAL의 버전을 반환합니다.

Functions enhanced in PostGIS 2.1

  • ST_AddBand - 개선 사항: 2.1.0 버전부터 addbandarg를 지원합니다. 입력 인덱스 위치에 입력 초기값으로 추가된 입력 유형의 새 밴드(들)을 가진 래스터를 반환합니다. 인덱스를 설정하지 않을 경우, 마지막 위치에 밴드를 추가합니다.
  • ST_AddBand - 개선 사항: 2.1.0 버전부터 새로운 DB 외부 밴드를 지원합니다. 입력 인덱스 위치에 입력 초기값으로 추가된 입력 유형의 새 밴드(들)을 가진 래스터를 반환합니다. 인덱스를 설정하지 않을 경우, 마지막 위치에 밴드를 추가합니다.
  • ST_AsBinary/ST_AsWKB - 개선 사항: 2.1.0버전에서 outasin 이 추가됐습니다. Return the Well-Known Binary (WKB) representation of the raster.
  • ST_AsGML - 개선 사항: 2.1.0 버전부터 GML 3를 위해 ID를 지원하기 시작했습니다. 도형을 GML 2 또는 GML 3 버전 요소로 반환합니다.
  • ST_Aspect - 개선 사항: 2.1.0 버전부터 ST_MapAlgebra()를 이용하며, 선택적인 interpolate_nodata 함수 파라미터가 추가됐습니다. 표고 래스터 밴드의 향(기본 단위는 도)을 반환합니다. 지형을 분석하는 데 유용합니다.
  • ST_Boundary - 개선 사항: 2.1.0 버전부터 삼각형을 지원하기 시작했습니다. 해당 도형의 결합된 범위의 닫힘 여부를 반환합니다.
  • ST_Clip - 개선 사항: 2.1.0 버전에서 C 언어로 다시 쓰였습니다. Returns the raster clipped by the input geometry. If band number is not specified, all bands are processed. If crop is not specified or TRUE, the output raster is cropped. If touched is set to TRUE, then touched pixels are included, otherwise only if the center of the pixel is in the geometry it is included.
  • ST_DWithin - Enhanced: 2.1.0 improved speed for geography. See Making Geography faster for details. Tests if two geometries are within a given distance
  • ST_DWithin - Enhanced: 2.1.0 support for curved geometries was introduced. Tests if two geometries are within a given distance
  • ST_Distance - Enhanced: 2.1.0 improved speed for geography. See Making Geography faster for details. 두 도형 사이의 3차원 최장(longest) 라인을 반환합니다.
  • ST_Distance - 개선 사항: 2.1.0 버전부터 만곡 도형을 지원하기 시작했습니다. 두 도형 사이의 3차원 최장(longest) 라인을 반환합니다.
  • ST_Distinct4ma - 개선 사항: 2.1.0 버전에서 변종 2가 추가됐습니다. 이웃에서 유일한 픽셀 값들의 개수를 계산하는 래스터 공간 처리 함수입니다.
  • ST_DumpPoints - Enhanced: 2.1.0 Faster speed. Reimplemented as native-C. 도형의 내용을 요약한 텍스트를 반환합니다.
  • ST_HillShade - 개선 사항: 2.1.0 버전부터 ST_MapAlgebra()를 이용하며, 선택적인 interpolate_nodata 함수 파라미터가 추가됐습니다. 입력한 방위각, 고도각, 밝기 및 축척을 이용해서 표고 래스터 밴드의 가상적인 음영기복을 반환합니다.
  • ST_MakeValid - Enhanced: 2.1.0, added support for GEOMETRYCOLLECTION and MULTIPOINT. Attempts to make an invalid geometry valid without losing vertices.
  • ST_Max4ma - 개선 사항: 2.1.0 버전에서 변종 2가 추가됐습니다. 이웃에서 최대 픽셀 값을 계산하는 래스터 공간 처리 함수입니다.
  • ST_Mean4ma - 개선 사항: 2.1.0 버전에서 변종 2가 추가됐습니다. 이웃에서 평균 픽셀 값을 계산하는 래스터 공간 처리 함수입니다.
  • ST_Min4ma - 개선 사항: 2.1.0 버전에서 변종 2가 추가됐습니다. 이웃에서 최소 픽셀 값을 계산하는 래스터 공간 처리 함수입니다.
  • ST_PixelAsPolygons - 개선 사항: 2.1.0 버전부터 선택적인 exclude_nodata_value 인수를 추가했습니다. 래스터 밴드의 모든 픽셀의 경계를 이루는 폴리곤 도형을 각 픽셀의 값과 X, Y 래스터 좌표와 함께 반환합니다.
  • ST_Polygon - 개선 사항: 2.1.0 버전부터 속도가 향상됐습니다(완전히 C언어 기반으로 변경했습니다). 반환되는 멀티폴리곤이 유효한 도형인지 확인합니다. NODATA 값이 아닌 픽셀 값을 가진 픽셀들을 통합해서 형성된 멀티폴리곤 도형을 반환합니다.
  • ST_Range4ma - 개선 사항: 2.1.0 버전에서 변종 2가 추가됐습니다. 이웃에 있는 픽셀값들의 범위를 계산하는 래스터 공간 처리 함수입니다.
  • ST_SameAlignment - 개선 사항: 2.1.0 버전에서 종합 함수 변종이 추가됐습니다. 래스터들이 동일한 기울기, 축척, 공간 참조 시스템, 그리고 오프셋을 가지고 있을 경우 (픽셀이 다른 픽셀을 침범하지 않고 동일한 그리드에 놓일 수 있을 경우) 참을 반환하고, 그렇지 않을 경우 문제점을 설명하는 안내문과 함께 거짓을 반환합니다.
  • ST_Segmentize - 개선 사항: 2.1.0 버전부터 지리형을 지원하기 시작했습니다. Returns a modified geometry/geography having no segment longer than a given distance.
  • ST_SetGeoReference - 개선 사항: 2.1.0버전에서 ST_SetGeoReference(raster, double precision, ...) 변종이 추가됐습니다. 단일 호출로 지리참조 파라미터 6개를 설정합니다. 숫자를 공백으로 구분해야 합니다. GDAL 또는 ESRI 서식의 입력물을 받아들입니다. 기본값은 GDAL입니다.
  • ST_SetValue - 개선 사항: 2.1.0 버전부터 ST_SetValue() 함수의 도형 변종이 포인트뿐만이 아니라 모든 도형 유형을 지원합니다. 이 도형 변종은 ST_SetValues()의 geomval[] 변종을 감싸는 래퍼(wrapper)입니다. 입력한 columnx, rowy 픽셀 또는 특정 도형과 교차하는 픽셀들의 위치의 밴드 값을 설정해서 나온 수정된 래스터를 반환합니다. 밴드 번호는 1부터 시작하며, 따로 설정하지 않을 경우 1로 가정합니다.
  • ST_Slope - 개선 사항: 2.1.0 버전부터 ST_MapAlgebra()를 이용하며, 선택적인 units, scale, interpolate_nodata 함수 파라미터가 추가됐습니다. 표고 래스터 밴드의 경사(기본 단위는 도)를 반환합니다. 지형을 분석하는 데 유용합니다.
  • ST_StdDev4ma - 개선 사항: 2.1.0 버전에서 변종 2가 추가됐습니다. 이웃에 있는 픽셀값들의 표준 편차를 계산하는 래스터 공간 처리 함수입니다.
  • ST_Sum4ma - 개선 사항: 2.1.0 버전에서 변종 2가 추가됐습니다. 이웃에 있는 모든 픽셀값들의 합계를 계산하는 래스터 공간 처리 함수입니다.
  • ST_Summary - 개선 사항: 2.1.0 버전. 알려진 공간 참조 시스템을 가진 경우를 나타내는 S 플래그가 추가됐습니다. 도형의 내용을 요약한 텍스트를 반환합니다.
  • ST_Transform - 개선 사항: 2.1.0버전에서 ST_Transform(rast, alignto) 변종이 추가됐습니다. 알려진 공간 참조 시스템의 래스터를 지정한 리샘플링 알고리즘을 통해 또 다른 알려진 공간 참조 시스템으로 재투영합니다. NearestNeighbor, Bilinear, Cubic, CubicSpline, Lanczos 알고리즘을 이용할 수 있습니다. 기본값은 NearestNeighbor입니다.
  • ST_Union - 개선 사항: 2.1.0 버전부터 속도가 향상됐습니다(완전히 C언어 기반으로 변경했습니다). 래스터 타일 집합을 1개 이상의 밴드로 이루어진 단일 래스터로 통합합니다.
  • ST_Union - 개선 사항: 2.1.0 버전부터 ST_Union(rast) 변종 1 함수가 모든 입력 래스터의 모든 밴드를 통합합니다. PostGIS 이전 버전에서는 첫 번째 밴드로 가정했습니다. 래스터 타일 집합을 1개 이상의 밴드로 이루어진 단일 래스터로 통합합니다.
  • ST_Union - 개선 사항: 2.1.0 버전부터 ST_Union(rast, uniontype) 변종 4 함수가 모든 입력 래스터의 모든 밴드를 통합합니다. 래스터 타일 집합을 1개 이상의 밴드로 이루어진 단일 래스터로 통합합니다.
  • toTopoGeom - 개선 사항: 2.1.0 버전에서 기존 TopoGeometry를 입력받는 버전을 추가했습니다. Converts a simple Geometry into a topo geometry.

Functions changed in PostGIS 2.1

  • ST_Aspect - 변경 사항: 2.1.0 미만 버전에서는 반환되는 값이 라디안 단위였습니다. 2.1.0 버전부터 반환되는 값의 기본 단위가 도로 바뀌었습니다. 표고 래스터 밴드의 향(기본 단위는 도)을 반환합니다. 지형을 분석하는 데 유용합니다.
  • ST_EstimatedExtent - Changed: 2.1.0. Up to 2.0.x this was called ST_Estimated_Extent. Returns the estimated extent of a spatial table.
  • ST_Force2D - 변경 사항: 2.1.0 미만 버전, 즉 2.0.x 버전까지 이 함수의 명칭은 ST_Force_2D였습니다. 도형을 "2차원 모드"로 강제합니다.
  • ST_Force3D - 변경 사항: 2.1.0 미만 버전, 즉 2.0.x 버전까지 이 함수의 명칭은 ST_Force_3D였습니다. 도형을 XYZ 모드로 강제합니다. ST_Force3DZ라고도 합니다.
  • ST_Force3DM - 변경 사항: 2.1.0 미만 버전, 즉 2.0.x 버전까지 이 함수의 명칭은 ST_Force_3DM이었습니다. 도형을 XYM 모드로 강제합니다.
  • ST_Force3DZ - 변경 사항: 2.1.0 미만 버전, 즉 2.0.x 버전까지 이 함수의 명칭은 ST_Force_3DZ였습니다. 도형을 XYZ 모드로 강제합니다.
  • ST_Force4D - 변경 사항: 2.1.0 미만 버전, 즉 2.0.x 버전까지 이 함수의 명칭은 ST_Force_4D였습니다. 도형을 XYZM 모드로 강제합니다.
  • ST_ForceCollection - 변경 사항: 2.1.0 미만 버전, 즉 2.0.x 버전까지 이 함수의 명칭은 ST_Force_Collection이었습니다. 도형을 도형 집합으로 변환합니다.
  • ST_HillShade - 변경 사항: 2.1.0 미만 버전에서는 방위각 및 고도각이 라디안 단위였습니다. 2.1.0 버전부터 방위각과 고도각이 도 단위로 바뀌었습니다. 입력한 방위각, 고도각, 밝기 및 축척을 이용해서 표고 래스터 밴드의 가상적인 음영기복을 반환합니다.
  • ST_LineInterpolatePoint - 변경 사항: 2.1.0 미만 버전, 즉 2.0.x 버전까지 이 함수의 명칭은 ST_Line_Interpolate_Point였습니다. Returns a point interpolated along a line at a fractional location.
  • ST_LineLocatePoint - 변경 사항: 2.1.0 미만 버전, 즉 2.0.x 버전까지 이 함수의 명칭은 ST_Line_Locate_Point였습니다. Returns the fractional location of the closest point on a line to a point.
  • ST_LineSubstring - 변경 사항: 2.1.0 미만 버전, 즉 2.0.x 버전까지 이 함수의 명칭은 ST_Line_Substring이었습니다. Returns the part of a line between two fractional locations.
  • ST_PixelAsCentroids - 변경 사항: 2.1.1 버전에서 exclude_nodata_value의 습성을 변경했습니다. 래스터 밴드의 각 픽셀에 대한 중심점(포인트 도형)을 각 픽셀의 값 및 X, Y 래스터 좌표와 함께 반환합니다. 포인트 도형은 픽셀이 차지하는 면의 중심점입니다.
  • ST_PixelAsPoints - 변경 사항: 2.1.1 버전에서 exclude_nodata_value의 습성을 변경했습니다. 래스터 밴드의 각 픽셀에 대한 포인트 도형을 각 픽셀의 값 및 X, Y 래스터 좌표와 함께 반환합니다. 포인트 도형의 좌표는 픽셀의 좌상단 좌표입니다.
  • ST_PixelAsPolygons - 변경 사항: 2.1.1 버전에서 exclude_nodata_value의 습성을 변경했습니다. 래스터 밴드의 모든 픽셀의 경계를 이루는 폴리곤 도형을 각 픽셀의 값과 X, Y 래스터 좌표와 함께 반환합니다.
  • ST_Polygon - 변경 사항: 2.1.0 미만 버전에서 종종 폴리곤을 반환하곤 했던 것을, 언제나 멀티폴리곤을 반환하도록 바꿨습니다. NODATA 값이 아닌 픽셀 값을 가진 픽셀들을 통합해서 형성된 멀티폴리곤 도형을 반환합니다.
  • ST_RasterToWorldCoordX - 변경 사항: 2.1.0 미만 버전에서는 ST_Raster2WorldCoordX라는 명칭이었습니다. 열과 행에 있는 래스터의 좌상단의 기하학적 X 좌표를 반환합니다. 열과 행의 번호는 1부터 시작합니다.
  • ST_RasterToWorldCoordY - 변경 사항: 2.1.0 미만 버전에서는 ST_Raster2WorldCoordY라는 명칭이었습니다. 열과 행에 있는 래스터의 좌상단의 기하학적 Y 좌표를 반환합니다. 열과 행의 번호는 1부터 시작합니다.
  • ST_Rescale - 변경 사항: 2.1.0 버전부터 SRID가 없는 래스터도 입력받습니다. Resample a raster by adjusting only its scale (or pixel size). New pixel values are computed using the NearestNeighbor (english or american spelling), Bilinear, Cubic, CubicSpline, Lanczos, Max or Min resampling algorithm. Default is NearestNeighbor.
  • ST_Reskew - 변경 사항: 2.1.0 버전부터 SRID가 없는 래스터도 입력받습니다. 기울기(또는 회전각 파라미터)만 조정해서 래스터를 리샘플링합니다. NearestNeighbor(영국 또는 미국 철자), Bilinear, Cubic, CubicSpline 또는 Lanczos 리샘플링 알고리즘을 이용해서 새 픽셀 값을 계산합니다. 기본값은 NearestNeighbor입니다.
  • ST_Segmentize - Changed: 2.1.0 As a result of the introduction of geography support, the usage ST_Segmentize('LINESTRING(1 2, 3 4)', 0.5) causes an ambiguous function error. The input needs to be properly typed as a geometry or geography. Use ST_GeomFromText, ST_GeogFromText or a cast to the required type (e.g. ST_Segmentize('LINESTRING(1 2, 3 4)'::geometry, 0.5) ) Returns a modified geometry/geography having no segment longer than a given distance.
  • ST_Slope - 변경 사항: 2.1.0 미만 버전에서는 반환되는 값이 라디안 단위였습니다. 2.1.0 버전부터 반환되는 값의 기본 단위가 도로 바뀌었습니다. 표고 래스터 밴드의 경사(기본 단위는 도)를 반환합니다. 지형을 분석하는 데 유용합니다.
  • ST_SnapToGrid - 변경 사항: 2.1.0 버전부터 SRID가 없는 래스터도 입력받습니다. 그리드에 래스터를 스냅시켜서 래스터를 리샘플링합니다. NearestNeighbor(영국 또는 미국 철자), Bilinear, Cubic, CubicSpline 또는 Lanczos 리샘플링 알고리즘을 이용해서 새 픽셀 값을 계산합니다. 기본값은 NearestNeighbor입니다.
  • ST_WorldToRasterCoordX - 변경 사항: 2.1.0 미만 버전에서는 ST_World2RasterCoordX라는 명칭이었습니다. 포인트 도형(pt)의 래스터 안의 열 또는 래스터의 월드 공간 참조 시스템 단위로 표현된 X, Y 월드 좌표(xw, yw)를 반환합니다.
  • ST_WorldToRasterCoordY - 변경 사항: 2.1.0 미만 버전에서는 ST_World2RasterCoordY라는 명칭이었습니다. 포인트 도형(pt)의 래스터 안의 행 또는 래스터의 월드 공간 참조 시스템 단위로 표현된 X, Y 월드 좌표(xw, yw)를 반환합니다.

13.12.14. PostGIS Functions new or enhanced in 2.0

The functions given below are PostGIS functions that were added or enhanced.

Functions new in PostGIS 2.0

  • && - 2.0.0 버전부터 사용할 수 있습니다. A의 경계 상자와 B의 경계 상자가 교차하는 경우 TRUE 를 반환합니다.
  • &&& - 2.0.0 버전부터 사용할 수 있습니다. A의 n차원 경계 상자와 B의 n차원 경계 상자가 교차하는 경우 TRUE 를 반환합니다.
  • <#> - Availability: 2.0.0. A와 B의 경계 상자 사이의 2차원 거리를 반환합니다.
  • <-> - Availability: 2.0.0 -- Weak KNN provides nearest neighbors based on geometry centroid distances instead of true distances. Exact results for points, inexact for all other types. A와 B 사이의 2차원 거리를 반환합니다.
  • @ - 2.0.0 버전부터 raster @ raster, raster @ geometry 를 사용할 수 있습니다. B의 경계 상자가 A의 경계 상자를 담고 있을 경우 TRUE 를 반환합니다. 이중 정밀도 경계 상자를 이용합니다.
  • @ - 2.0.5 버전부터 geometry @ raster 를 지원합니다. B의 경계 상자가 A의 경계 상자를 담고 있을 경우 TRUE 를 반환합니다. 이중 정밀도 경계 상자를 이용합니다.
  • AddEdge - 2.0.0 버전부터 사용할 수 있습니다. 설정한 지형 스키마의 경계선 테이블에 라인스트링 경계선을 추가하고, 설정한 라인스트링 도형을 이용해서 포인트 노드 테이블에 경계선의 시작점 및 종단점을 추가한 다음 새 (또는 기존) 경계선의 경계선 ID(edgeid)를 반환합니다.
  • AddFace - 2.0.0 버전부터 사용할 수 있습니다. 지형에 표면 원시형(face primitive)을 등록하고 그 식별자를 반환합니다.
  • AddNode - 2.0.0 버전부터 사용할 수 있습니다. 설정한 지형 스키마의 노드 테이블에 포인트 노드를 추가하고 새 노드의 노드 ID(nodeid)를 반환합니다. 새 포인트 위치에 이미 노드가 존재할 경우, 기존 노드 ID를 반환합니다.
  • AddOverviewConstraints - 2.0.0 버전부터 사용할 수 있습니다. 래스터 열을 또 다른 래스터 열의 미리보기(overview)로 태그합니다.
  • AddRasterConstraints - 2.0.0 버전부터 사용할 수 있습니다. Adds raster constraints to a loaded raster table for a specific column that constrains spatial ref, scaling, blocksize, alignment, bands, band type and a flag to denote if raster column is regularly blocked. The table must be loaded with data for the constraints to be inferred. Returns true if the constraint setting was accomplished and issues a notice otherwise.
  • AsGML - 2.0.0 버전부터 사용할 수 있습니다. TopoGeometry의 GML 표현식을 반환합니다.
  • CopyTopology - 2.0.0 버전부터 사용할 수 있습니다. Makes a copy of a topology (nodes, edges, faces, layers and TopoGeometries) into a new schema
  • DropOverviewConstraints - 2.0.0 버전부터 사용할 수 있습니다. 또 다른 래스터 열의 미리보기(overview)로서의 래스터 열을 태그 해제합니다.
  • DropRasterConstraints - 2.0.0 버전부터 사용할 수 있습니다. 래스터 테이블 열을 참조하는 PostGIS 래스터 제약조건을 삭제합니다. 데이터를 다시 로드하거나 사용자 래스터 열 데이터를 업데이트해야 할 경우 유용합니다.
  • GetEdgeByPoint - 2.0.0 버전부터 사용할 수 있습니다. Finds the edge-id of an edge that intersects a given point.
  • GetFaceByPoint - 2.0.0 버전부터 사용할 수 있습니다. Finds face intersecting a given point.
  • GetNodeByPoint - 2.0.0 버전부터 사용할 수 있습니다. Finds the node-id of a node at a point location.
  • GetNodeEdges - 2.0 버전부터 사용할 수 있습니다. 입력 노드를 따르는 경계선들의 정렬된 집합을 반환합니다.
  • GetRingEdges - 2.0.0 버전부터 사용할 수 있습니다. 입력 경계선 쪽을 따라 탐색한 부호가 있는 경계선 식별자들의 정렬된 집합을 반환합니다.
  • GetTopoGeomElements - 2.0.0 버전부터 사용할 수 있습니다. Returns a set of topoelement objects containing the topological element_id,element_type of the given TopoGeometry (primitive elements).
  • GetTopologySRID - 2.0.0 버전부터 사용할 수 있습니다. 지형의 명칭을 입력받아 topology.topology 테이블에 있는 지형의 SRID를 반환합니다.
  • Polygonize - 2.0.0 버전부터 사용할 수 있습니다. Finds and registers all faces defined by topology edges.
  • ST_3DClosestPoint - 2.0.0 버전부터 사용할 수 있습니다. g2에 가장 가까운 g1 상에 있는 3차원 포인트를 반환합니다. 해당 포인트는 3D 최단 라인의 첫 번째 포인트입니다.
  • ST_3DDFullyWithin - 2.0.0 버전부터 사용할 수 있습니다. Tests if two 3D geometries are entirely within a given 3D distance
  • ST_3DDWithin - 2.0.0 버전부터 사용할 수 있습니다. Tests if two 3D geometries are within a given 3D distance
  • ST_3DDistance - 2.0.0 버전부터 사용할 수 있습니다. 도형 유형에 대해, 두 도형 사이의 (SRS에 기반한) 3차원 데카르트 최단 거리를 투영 단위로 반환합니다.
  • ST_3DIntersects - 2.0.0 버전부터 사용할 수 있습니다. Tests if two geometries spatially intersect in 3D - only for points, linestrings, polygons, polyhedral surface (area)
  • ST_3DLongestLine - 2.0.0 버전부터 사용할 수 있습니다. 두 도형 사이의 3차원 최장(longest) 라인을 반환합니다.
  • ST_3DMaxDistance - 2.0.0 버전부터 사용할 수 있습니다. 도형 유형에 대해, 두 도형 사이의 (SRS에 기반한) 3차원 데카르트 최장 거리를 투영 단위로 반환합니다.
  • ST_3DShortestLine - 2.0.0 버전부터 사용할 수 있습니다. 두 도형 사이의 3차원 최단(shortest) 라인을 반환합니다.
  • ST_AddEdgeModFace - 2.0 버전부터 사용할 수 있습니다. 새 경계선을 추가하고, 그 과정에서 경계선이 표면을 분할할 경우, 원본 표면을 수정하고 새 표면을 추가합니다.
  • ST_AddEdgeNewFaces - 2.0 버전부터 사용할 수 있습니다. 새 경계선을 추가하고, 그 과정에서 경계선이 표면을 분할할 경우, 원본 표면을 삭제하고 새 표면 2개로 교체합니다.
  • ST_AsGDALRaster - 2.0.0 버전부터 사용할 수 있습니다. GDAL 1.6.0 이상 버전이 필요합니다. Return the raster tile in the designated GDAL Raster format. Raster formats are one of those supported by your compiled library. Use ST_GDALDrivers() to get a list of formats supported by your library.
  • ST_AsJPEG - 2.0.0 버전부터 사용할 수 있습니다. GDAL 1.6.0 이상 버전이 필요합니다. 래스터 타일에서 선택한 밴드들을 단일 JPEG(Joint Photographic Exports Group) 이미지(바이트 배열)로 반환합니다. 밴드를 따로 설정하지 않거나, 밴드가 1개거나 또는 3개를 초과할 경우 첫 번째 밴드를 씁니다. 밴드가 3개뿐일 경우 밴드 3개를 모두 써서 RGB에 매핑시킵니다.
  • ST_AsLatLonText - 2.0 버전부터 사용할 수 있습니다. 주어진 포인트의 도, 분, 초 표현식을 반환합니다.
  • ST_AsPNG - 2.0.0 버전부터 사용할 수 있습니다. GDAL 1.6.0 이상 버전이 필요합니다. 래스터 타일에서 선택한 밴드들을 단일 PNG(Portable Network Graphics) 이미지(바이트 배열)로 반환합니다. 래스터의 밴드가 1개, 3개, 또는 4개이거나 따로 설정하지 않을 경우 모든 밴드를 씁니다. 밴드가 2개 또는 4개를 초과하며 따로 설정하지 않을 경우, 밴드 1만 씁니다. 밴드를 RGB 또는 RGBA 스페이스에 매핑합니다.
  • ST_AsRaster - 2.0.0 버전부터 사용할 수 있습니다. GDAL 1.6.0 이상 버전이 필요합니다. PostGIS 도형을 PostGIS 래스터로 변환합니다.
  • ST_AsTIFF - 2.0.0 버전부터 사용할 수 있습니다. GDAL 1.6.0 이상 버전이 필요합니다. Return the raster selected bands as a single TIFF image (byte array). If no band is specified or any of specified bands does not exist in the raster, then will try to use all bands.
  • ST_AsX3D - 2.0.0 버전부터 ISO-IEC-19776-1.2-X3DEncodings-XML을 이용할 수 있습니다. 도형을 X3D XML 노드 요소 형식: ISO-IEC-19776-1.2-X3DEncodings-XML로 반환합니다.
  • ST_Aspect - 2.0.0 버전부터 사용할 수 있습니다. 표고 래스터 밴드의 향(기본 단위는 도)을 반환합니다. 지형을 분석하는 데 유용합니다.
  • ST_Band - 2.0.0 버전부터 사용할 수 있습니다. 기존 래스터의 하나 이상의 밴드를 새 래스터로 반환합니다. 기존 래스터로부터 새 래스터를 빌드하는 데 유용합니다.
  • ST_BandIsNoData - 2.0.0 버전부터 사용할 수 있습니다. 밴드가 NODATA 값만으로 채워져 있을 경우 참을 반환합니다.
  • ST_Clip - 2.0.0 버전부터 사용할 수 있습니다. Returns the raster clipped by the input geometry. If band number is not specified, all bands are processed. If crop is not specified or TRUE, the output raster is cropped. If touched is set to TRUE, then touched pixels are included, otherwise only if the center of the pixel is in the geometry it is included.
  • ST_CollectionHomogenize - 2.0.0 버전부터 사용할 수 있습니다. Returns the simplest representation of a geometry collection.
  • ST_ConcaveHull - 2.0.0 버전부터 사용할 수 있습니다. Computes a possibly concave geometry that contains all input geometry vertices
  • ST_Count - 2.0.0 버전부터 사용할 수 있습니다. 래스터 또는 래스터 커버리지의 입력 밴드에 있는 픽셀 개수를 반환합니다. 밴드를 따로 설정하지 않을 경우 기본값은 밴드 1입니다. exclude_nodata_value를 참으로 설정할 경우, NODATA 값이 아닌 픽셀의 개수만 반환할 것입니다.
  • ST_CreateTopoGeo - 2.0 버전부터 사용할 수 있습니다. 텅 빈 입력 지형에 도형들의 집합을 추가한 다음 작업 성공 여부를 상세하게 설명하는 메시지를 반환합니다.
  • ST_Distinct4ma - 2.0.0 버전부터 사용할 수 있습니다. 이웃에서 유일한 픽셀 값들의 개수를 계산하는 래스터 공간 처리 함수입니다.
  • ST_FlipCoordinates - 2.0.0 버전부터 사용할 수 있습니다. Returns a version of a geometry with X and Y axis flipped.
  • ST_GDALDrivers - 2.0.0 버전부터 사용할 수 있습니다. GDAL 1.6.0 이상 버전이 필요합니다. Returns a list of raster formats supported by PostGIS through GDAL. Only those formats with can_write=True can be used by ST_AsGDALRaster
  • ST_GeomFromGeoJSON - 2.0.0 버전부터 사용할 수 있습니다. JSON-C 0.9 이상 버전이 필요합니다. GeoJSON 표현식을 입력받아 PostGIS 도형 객체를 출력합니다.
  • ST_GetFaceEdges - 2.0 버전부터 사용할 수 있습니다. aface 의 경계를 이루는 정렬된 경계선들의 집합을 반환합니다.
  • ST_HasNoBand - 2.0.0 버전부터 사용할 수 있습니다. 입력된 밴드 번호에 밴드가 없을 경우 참을 반환합니다. 밴드 번호를 설정하지 않을 경우, 밴드 1로 가정합니다.
  • ST_HillShade - 2.0.0 버전부터 사용할 수 있습니다. 입력한 방위각, 고도각, 밝기 및 축척을 이용해서 표고 래스터 밴드의 가상적인 음영기복을 반환합니다.
  • ST_Histogram - 2.0.0 버전부터 사용할 수 있습니다. 빈(bin; 히스토그램 표시에서 수직 막대로 나타나는 단위) 범위로 구분된 래스터 또는 래스터 커버리지의 데이터 분포를 요약하는 레코드 집합을 반환합니다. 따로 설정하지 않을 경우 빈의 개수를 자동으로 계산합니다.
  • ST_InterpolatePoint - 2.0.0 버전부터 사용할 수 있습니다. 입력 포인트에 가까운 포인트에서 도형의 척도 차원(M 차원)의 값을 반환합니다.
  • ST_IsEmpty - 2.0.0 버전부터 사용할 수 있습니다. 래스터가 비어 있을 경우 (width = 0, height = 0) 참을 반환합니다. 그렇지 않을 경우 거짓을 반환합니다.
  • ST_IsValidDetail - 2.0.0 버전부터 사용할 수 있습니다. Returns a valid_detail row stating if a geometry is valid or if not a reason and a location.
  • ST_IsValidReason - Availability: 2.0 version taking flags. Returns text stating if a geometry is valid, or a reason for invalidity.
  • ST_MakeLine - 2.0.0 버전부터 라인스트링 구성 요소 입력을 지원하기 시작했습니다. 포인트, 멀티포인트 또는 라인 도형으로부터 라인스트링을 생성합니다.
  • ST_MakeValid - 2.0.0 버전부터 사용할 수 있습니다. Attempts to make an invalid geometry valid without losing vertices.
  • ST_MapAlgebraExpr - 2.0.0 버전부터 사용할 수 있습니다. 래스터 밴드 1개 버전: 입력 래스터에 대해 유효한 PostgreSQL 대수 연산을 적용해서 형성되고, 설정한 픽셀 유형을 가진, 밴드 1개를 가진 새 래스터를 생성합니다. 따로 밴드를 설정하지 않을 경우, 밴드 1로 가정합니다.
  • ST_MapAlgebraExpr - 2.0.0 버전부터 사용할 수 있습니다. 래스터 밴드 2개 버전: 입력 래스터 2개에 대해 유효한 PostgreSQL 대수 연산을 적용해서 형성되고, 설정한 픽셀 유형을 가진, 밴드 1개를 가진 새 래스터를 생성합니다. 따로 밴드를 설정하지 않을 경우, 각 래스터의 밴드 1로 가정합니다. 출력 래스터는 첫 번째 래스터가 정의하는 그리드 상에 (축척, 기울기 및 픽셀 모서리가) 정렬될 것입니다. extenttype 파라미터가 출력 래스터의 범위를 정의할 것입니다. extenttype 의 값은 INTERSECTION, UNION, FIRST, SECOND가 될 수 있습니다.
  • ST_MapAlgebraFct - 2.0.0 버전부터 사용할 수 있습니다. 래스터 밴드 1개 버전: 입력 래스터에 대해 유효한 PostgreSQL 대수 연산을 적용해서 형성되고, 설정한 픽셀 유형을 가진, 밴드 1개를 가진 새 래스터를 생성합니다. 따로 밴드를 설정하지 않을 경우, 밴드 1로 가정합니다.
  • ST_MapAlgebraFct - 2.0.0 버전부터 사용할 수 있습니다. 래스터 밴드 2개 버전: 입력 래스터 2개에 대해 유효한 PostgreSQL 함수를 적용해서 형성되고, 설정한 픽셀 유형을 가진, 밴드 1개를 가진 새 래스터를 생성합니다. 따로 밴드를 설정하지 않을 경우, 밴드 1로 가정합니다. 범위 유형을 따로 설정하지 않을 경우 기본값은 INTERSECTION입니다.
  • ST_MapAlgebraFctNgb - 2.0.0 버전부터 사용할 수 있습니다. 래스터 밴드 1개 버전: 사용자 지정 PostgreSQL 함수를 이용하는 맵 대수 최근접 이웃(Map Algebra Nearest Neighbor)입니다. 입력 래스터 밴드의 값의 이웃(neighborhood)이 관련된 PostgreSQL 사용자 함수가 출력하는 값을 가진 래스터를 반환합니다.
  • ST_Max4ma - 2.0.0 버전부터 사용할 수 있습니다. 이웃에서 최대 픽셀 값을 계산하는 래스터 공간 처리 함수입니다.
  • ST_Mean4ma - 2.0.0 버전부터 사용할 수 있습니다. 이웃에서 평균 픽셀 값을 계산하는 래스터 공간 처리 함수입니다.
  • ST_Min4ma - 2.0.0 버전부터 사용할 수 있습니다. 이웃에서 최소 픽셀 값을 계산하는 래스터 공간 처리 함수입니다.
  • ST_ModEdgeHeal - 2.0 버전부터 사용할 수 있습니다. Heals two edges by deleting the node connecting them, modifying the first edge and deleting the second edge. Returns the id of the deleted node.
  • ST_MoveIsoNode - 2.0.0 버전부터 사용할 수 있습니다. Moves an isolated node in a topology from one point to another. If new apoint geometry exists as a node an error is thrown. Returns description of move.
  • ST_NewEdgeHeal - 2.0 버전부터 사용할 수 있습니다. Heals two edges by deleting the node connecting them, deleting both edges, and replacing them with an edge whose direction is the same as the first edge provided.
  • ST_Node - 2.0.0 버전부터 사용할 수 있습니다. Nodes a collection of lines.
  • ST_NumPatches - 2.0.0 버전부터 사용할 수 있습니다. Returns the number of faces in a PolyhedralSurface or TIN.
  • ST_OffsetCurve - 2.0 버전부터 사용할 수 있습니다. Returns an offset line at a given distance and side from an input line.
  • ST_PatchN - 2.0.0 버전부터 사용할 수 있습니다. Returns the Nth face of a PolyhedralSurface or TIN.
  • ST_Perimeter - 개선 사항: 2.0.0 버전부터 지리형을 지원합니다. Returns the length of the boundary of a polygonal geometry or geography.
  • ST_PixelAsPolygon - 2.0.0 버전부터 사용할 수 있습니다. 특정 행 및 열에 대한 픽셀의 경계를 이루는 폴리곤 도형을 반환합니다.
  • ST_PixelAsPolygons - 2.0.0 버전부터 사용할 수 있습니다. 래스터 밴드의 모든 픽셀의 경계를 이루는 폴리곤 도형을 각 픽셀의 값과 X, Y 래스터 좌표와 함께 반환합니다.
  • ST_Project - 2.0.0 버전부터 사용할 수 있습니다. Returns a point projected from a start point by a distance and bearing (azimuth).
  • ST_Quantile - 2.0.0 버전부터 사용할 수 있습니다. 샘플링 또는 채우기(population)라는 맥락에서 래스터 또는 래스터 테이블 커버리지의 사분위(quantile)를 계산합니다. 따라서, 래스터의 25%, 50%, 75% 백분위(percentile) 단계로 값을 확인할 수 있습니다.
  • ST_Range4ma - 2.0.0 버전부터 사용할 수 있습니다. 이웃에 있는 픽셀값들의 범위를 계산하는 래스터 공간 처리 함수입니다.
  • ST_Reclass - 2.0.0 버전부터 사용할 수 있습니다. 원본으로부터 재분류된 밴드 유형으로 이루어진 새 래스터를 생성합니다. nband 는 변경할 밴드를 가리킵니다. nband 를 따로 설정하지 않을 경우 밴드 1로 가정합니다. 다른 모든 밴드들은 변경 없이 반환됩니다. 실제 사례: 보기 좋은 형식으로 더 간단하게 렌더링하기 위해 16BUI 밴드를 8BUI 등등으로 변환하십시오.
  • ST_RelateMatch - 2.0.0 버전부터 사용할 수 있습니다. Tests if a DE-9IM Intersection Matrix matches an Intersection Matrix pattern
  • ST_RemEdgeModFace - 2.0 버전부터 사용할 수 있습니다. Removes an edge, and if the edge separates two faces deletes one face and modifies the other face to cover the space of both.
  • ST_RemEdgeNewFace - 2.0 버전부터 사용할 수 있습니다. 경계선을 제거하고, 제거한 경계선이 두 표면을 분할하고 있을 경우, 원본 표면들을 삭제하고 새 표면 하나로 대체합니다.
  • ST_Resample - 2.0.0 버전부터 사용할 수 있습니다. GDAL 1.6.1 이상 버전이 필요합니다. 특정 리샘플링 알고리즘, 새로운 차원, 임의의 그리드 모서리, 그리고 또 다른 래스터에서 정의되거나 빌려온 래스터 지리참조 속성들의 집합을 이용해서 래스터를 리샘플링합니다.
  • ST_Rescale - 2.0.0 버전부터 사용할 수 있습니다. GDAL 1.6.1 이상 버전이 필요합니다. Resample a raster by adjusting only its scale (or pixel size). New pixel values are computed using the NearestNeighbor (english or american spelling), Bilinear, Cubic, CubicSpline, Lanczos, Max or Min resampling algorithm. Default is NearestNeighbor.
  • ST_Reskew - 2.0.0 버전부터 사용할 수 있습니다. GDAL 1.6.1 이상 버전이 필요합니다. 기울기(또는 회전각 파라미터)만 조정해서 래스터를 리샘플링합니다. NearestNeighbor(영국 또는 미국 철자), Bilinear, Cubic, CubicSpline 또는 Lanczos 리샘플링 알고리즘을 이용해서 새 픽셀 값을 계산합니다. 기본값은 NearestNeighbor입니다.
  • ST_SameAlignment - 2.0.0 버전부터 사용할 수 있습니다. 래스터들이 동일한 기울기, 축척, 공간 참조 시스템, 그리고 오프셋을 가지고 있을 경우 (픽셀이 다른 픽셀을 침범하지 않고 동일한 그리드에 놓일 수 있을 경우) 참을 반환하고, 그렇지 않을 경우 문제점을 설명하는 안내문과 함께 거짓을 반환합니다.
  • ST_SetBandIsNoData - 2.0.0 버전부터 사용할 수 있습니다. 밴드의 isnodata 플래그를 참으로 설정합니다.
  • ST_SharedPaths - 2.0.0 버전부터 사용할 수 있습니다. 두 입력 라인스트링/멀티라인스트링이 공유하는 경로를 담고 있는 집합을 반환합니다.
  • ST_Slope - 2.0.0 버전부터 사용할 수 있습니다. 표고 래스터 밴드의 경사(기본 단위는 도)를 반환합니다. 지형을 분석하는 데 유용합니다.
  • ST_Snap - 2.0.0 버전부터 사용할 수 있습니다. 입력 도형의 분절 구간과 꼭짓점을 참조 도형의 꼭짓점으로 스냅시킵니다.
  • ST_SnapToGrid - 2.0.0 버전부터 사용할 수 있습니다. GDAL 1.6.1 이상 버전이 필요합니다. 그리드에 래스터를 스냅시켜서 래스터를 리샘플링합니다. NearestNeighbor(영국 또는 미국 철자), Bilinear, Cubic, CubicSpline 또는 Lanczos 리샘플링 알고리즘을 이용해서 새 픽셀 값을 계산합니다. 기본값은 NearestNeighbor입니다.
  • ST_Split - Availability: 2.0.0 requires GEOS Returns a collection of geometries created by splitting a geometry by another geometry.
  • ST_StdDev4ma - 2.0.0 버전부터 사용할 수 있습니다. 이웃에 있는 픽셀값들의 표준 편차를 계산하는 래스터 공간 처리 함수입니다.
  • ST_Sum4ma - 2.0.0 버전부터 사용할 수 있습니다. 이웃에 있는 모든 픽셀값들의 합계를 계산하는 래스터 공간 처리 함수입니다.
  • ST_SummaryStats - 2.0.0 버전부터 사용할 수 있습니다. Returns summarystats consisting of count, sum, mean, stddev, min, max for a given raster band of a raster or raster coverage. Band 1 is assumed if no band is specified.
  • ST_Transform - 2.0.0 버전부터 사용할 수 있습니다. GDAL 1.6.1 이상 버전이 필요합니다. 알려진 공간 참조 시스템의 래스터를 지정한 리샘플링 알고리즘을 통해 또 다른 알려진 공간 참조 시스템으로 재투영합니다. NearestNeighbor, Bilinear, Cubic, CubicSpline, Lanczos 알고리즘을 이용할 수 있습니다. 기본값은 NearestNeighbor입니다.
  • ST_UnaryUnion - 2.0.0 버전부터 사용할 수 있습니다. Computes the union of the components of a single geometry.
  • ST_Union - 2.0.0 버전부터 사용할 수 있습니다. 래스터 타일 집합을 1개 이상의 밴드로 이루어진 단일 래스터로 통합합니다.
  • ST_ValueCount - 2.0.0 버전부터 사용할 수 있습니다. 설정한 값들의 집합을 가진 래스터(또는 래스터 커버리지)의 입력 밴드에 있는 픽셀 밴드 값 및 픽셀 개수의 집계를 담고 있는 레코드 집합을 반환합니다. 밴드를 따로 설정하지 않을 경우 기본값은 밴드 1입니다. 기본적으로 NODATA 값은 집계되지 않습니다. 픽셀의 다른 모든 값들을 출력하는데, 픽셀 밴드 값은 가장 가까운 정수로 반올림됩니다.
  • TopoElementArray_Agg - 2.0.0 버전부터 사용할 수 있습니다. Returns a topoelementarray for a set of element_id, type arrays (topoelements).
  • TopoGeo_AddLineString - 2.0.0 버전부터 사용할 수 있습니다. Adds a linestring to an existing topology using a tolerance and possibly splitting existing edges/faces.
  • TopoGeo_AddPoint - 2.0.0 버전부터 사용할 수 있습니다. 허용 오차를 이용해서 그리고 기존 경계선을 분할(split)하기도 해서 기존 지형에 포인트를 추가합니다.
  • TopoGeo_AddPolygon - 2.0.0 버전부터 사용할 수 있습니다. Adds a polygon to an existing topology using a tolerance and possibly splitting existing edges/faces. Returns face identifiers.
  • TopologySummary - 2.0.0 버전부터 사용할 수 있습니다. Takes a topology name and provides summary totals of types of objects in topology.
  • toTopoGeom - 2.0 버전부터 사용할 수 있습니다. Converts a simple Geometry into a topo geometry.
  • ~ - 2.0.0 버전부터 사용할 수 있습니다. A의 경계 상자가 B의 경계 상자를 담고 있을 경우 TRUE 를 반환합니다. 이중 정밀도 경계 상자를 이용합니다.
  • ~= - 2.0.0 버전부터 사용할 수 있습니다. A의 경계 상자와 B의 경계 상자가 동일할 경우 TRUE 를 반환합니다.

Functions enhanced in PostGIS 2.0

  • && - 개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다. A의 2D 경계 상자와 B의 2D 경계 상자가 교차하는 경우 TRUE 를 반환합니다.
  • AddGeometryColumn - 개선 사항: 2.0.0 버전. use_typmod 인자가 추가됐습니다. 제약조건 기반 도형 열 대신 기본적으로 typmod 도형 열을 생성합니다. 공간 테이블에서 지오메트리 컬럼을 제거합니다.
  • Box2D - 개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다. Returns a BOX2D representing the 2D extent of a geometry.
  • Box3D - 개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다. Returns a BOX3D representing the 3D extent of a geometry.
  • CreateTopology - Enhanced: 2.0 added support for hasZ. Creates a new topology schema and registers it in the topology.topology table.
  • GeometryType - 개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다. ST_Geometry 값의 도형 유형을 반환합니다.
  • Populate_Geometry_Columns - 개선 사항: 2.0.0 버전. 열 생성시 유형 변경자와 함께, 또는 확인 제약조건과 함께 생성할지 통제할 수 있는 use_typmod 의 선택적 인자가 추가됐습니다. Ensures geometry columns are defined with type modifiers or have appropriate spatial constraints.
  • ST_3DExtent - 개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다. Aggregate function that returns the 3D bounding box of geometries.
  • ST_Affine - 개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다. Apply a 3D affine transformation to a geometry.
  • ST_Area - 개선 사항: 2.0.0 버전부터 2차원 다면체 표면(polyhedral surface)을 지원합니다. 도형의 기하학적 중심을 반환합니다.
  • ST_AsBinary - 개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다. Return the OGC/ISO Well-Known Binary (WKB) representation of the geometry/geography without SRID meta data.
  • ST_AsBinary - 개선 사항: 2.0.0 버전부터 더 높은 좌표 차원을 지원합니다. Return the OGC/ISO Well-Known Binary (WKB) representation of the geometry/geography without SRID meta data.
  • ST_AsBinary - 개선 사항: 2.0.0 버전부터 지리형과 함께 엔디안을 설정하는 방식을 지원합니다. Return the OGC/ISO Well-Known Binary (WKB) representation of the geometry/geography without SRID meta data.
  • ST_AsEWKB - 개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다. Return the Extended Well-Known Binary (EWKB) representation of the geometry with SRID meta data.
  • ST_AsEWKT - 개선 사항: 2.0.0 버전부터 지리형, 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다. 도형의 WKT(Well-Known Text) 표현식을 SRID 메타데이터와 함께 반환합니다.
  • ST_AsGML - 개선 사항: 2.0.0 버전부터 접두사를 지원합니다. 라인에 대해 커브 대신 라인스트링 태그를 이용할 수 있도록 GML 3용 옵션 '4'가 등장했습니다. GML 3가 다면체 표면 및 TIN을 지원하기 시작했습니다. 상자를 출력하는 옵션 '32'도 새롭게 등장했습니다. 도형을 GML 2 또는 GML 3 버전 요소로 반환합니다.
  • ST_AsKML - 개선 사항: 2.0.0 버전부터 네임스페이스에 접두사를 추가할 수 있습니다. 기본값은 접두사를 쓰지 않는 것입니다. 도형을 GML 2 또는 GML 3 버전 요소로 반환합니다.
  • ST_Azimuth - 개선 사항: 2.0.0 버전부터 지리형을 지원합니다. 두 도형 사이의 2차원 최단 라인을 반환합니다.
  • ST_Dimension - 개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface) 및 TIN을 지원합니다. 빈 도형이 주어져도 더 이상 예외가 발생하지 않습니다. ST_Geometry 값의 좌표 차원을 반환합니다.
  • ST_Dump - 개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다. Returns a set of geometry_dump rows for the components of a geometry.
  • ST_DumpPoints - 개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다. 도형의 내용을 요약한 텍스트를 반환합니다.
  • ST_Expand - 개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다. Returns a bounding box expanded from another bounding box or a geometry.
  • ST_Extent - 개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다. Aggregate function that returns the bounding box of geometries.
  • ST_Force2D - 개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다. 도형을 "2차원 모드"로 강제합니다.
  • ST_Force3D - 개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다. 도형을 XYZ 모드로 강제합니다. ST_Force3DZ라고도 합니다.
  • ST_Force3DZ - 개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다. 도형을 XYZ 모드로 강제합니다.
  • ST_ForceCollection - 개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다. 도형을 도형 집합으로 변환합니다.
  • ST_ForceRHR - 개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다. 폴리곤 안에 있는 꼭짓점들의 방향(orientation)이 오른손 법칙(Right-Hand Rule)을 따르도록 강제합니다.
  • ST_GMLToSQL - 개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface) 및 TIN을 지원합니다. Returns a geometry from GML. Alias for ST_GeomFromGML.
  • ST_GMLToSQL - 개선 사항: 2.0.0 버전에서 선택적인 기본 SRID 파라미터가 추가됐습니다. Returns a geometry from GML. Alias for ST_GeomFromGML.
  • ST_GeomFromEWKB - 개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface) 및 TIN을 지원합니다. EWKB(Extended Well-Known Binary)로부터 지정된 ST_Geometry 값을 반환합니다.
  • ST_GeomFromEWKT - 개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface) 및 TIN을 지원합니다. EWKT(Extended Well-Known Text)로부터 지정된 ST_Geometry 값을 반환합니다.
  • ST_GeomFromGML - 개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface) 및 TIN을 지원합니다. 도형의 GML 표현식을 입력받아 PostGIS 도형 객체를 출력합니다.
  • ST_GeomFromGML - 개선 사항: 2.0.0 버전에서 선택적인 기본 SRID 파라미터가 추가됐습니다. 도형의 GML 표현식을 입력받아 PostGIS 도형 객체를 출력합니다.
  • ST_GeometryN - 개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다. ST_Geometry 값의 도형 유형을 반환합니다.
  • ST_GeometryType - 개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다. ST_Geometry 값의 도형 유형을 반환합니다.
  • ST_IsClosed - 개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다. LINESTRING 의 시작점과 종단점이 일치하는 경우 TRUE 를 반환합니다. 다면체 표면이 닫혀 (부피를 가지고) 있는 경우 TRUE 를 반환합니다.
  • ST_MakeEnvelope - 개선 사항: 2.0 버전부터 SRID를 지정하지 않고도 직사각형(envelope)을 설정할 수 있는 기능이 추가됐습니다. 주어진 최소값과 최대값으로 형성된 직사각형 폴리곤을 생성합니다. 입력값이 SRID로 지정된 SRS를 가지고 있어야 합니다.
  • ST_MakeValid - Enhanced: 2.0.1, speed improvements Attempts to make an invalid geometry valid without losing vertices.
  • ST_NPoints - 개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다. 도형이 가지고 있는 포인트(꼭짓점)의 개수를 반환합니다.
  • ST_NumGeometries - 개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다. 도형이 가지고 있는 포인트의 개수를 반환합니다. 모든 도형을 입력받을 수 있습니다.
  • ST_Relate - Enhanced: 2.0.0 - added support for specifying boundary node rule. Tests if two geometries have a topological relationship matching an Intersection Matrix pattern, or computes their Intersection Matrix
  • ST_Rotate - 개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다. Rotates a geometry about an origin point.
  • ST_Rotate - Enhanced: 2.0.0 additional parameters for specifying the origin of rotation were added. Rotates a geometry about an origin point.
  • ST_RotateX - 개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다. Rotates a geometry about the X axis.
  • ST_RotateY - 개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다. Rotates a geometry about the Y axis.
  • ST_RotateZ - 개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다. Rotates a geometry about the Z axis.
  • ST_Scale - 개선 사항: 2.0.0 버전부터 다면체 표면, 삼각형 및 TIN을 지원하기 시작했습니다. Scales a geometry by given factors.
  • ST_ShiftLongitude - 개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface) 및 TIN을 지원합니다. Shifts the longitude coordinates of a geometry between -180..180 and 0..360.
  • ST_Summary - 개선 사항: 2.0.0 버전부터 지리형을 지원하기 시작했습니다. 도형의 내용을 요약한 텍스트를 반환합니다.
  • ST_Transform - 개선 사항: 2.0.0 버전부터 다면체 표면(polyhedral surface)을 지원합니다. Return a new geometry with coordinates transformed to a different spatial reference system.
  • ST_Value - 개선 사항: 2.0.0 버전부터 선택적인 exclude_nodata_value 인수를 추가했습니다. 입력 columnx, rowy 픽셀의 입력 밴드의 값, 또는 특정 기하학적 포인트의 밴드의 값을 반환합니다. 밴드 번호는 1부터 시작하며, 따로 지정하지 않을 경우 1로 가정합니다. exclude_nodata_value 를 거짓으로 설정할 경우, nodata 픽셀을 포함한 모든 픽셀이 교차한다고 가정하고 값을 반환합니다. exclude_nodata_value 를 설정하지 않은 경우, 래스터의 메타데이터에서 값을 읽어 들입니다.
  • ValidateTopology - 개선 사항: 2.0.0 버전에서 경계선 가로지르기 탐지를 더 효율적으로 개선하고, 이전 버전에 존재했던 긍정 오류(false positive)를 해결했습니다. Returns a set of validatetopology_returntype objects detailing issues with topology.

Functions changed in PostGIS 2.0

  • AddGeometryColumn - 변경사항: 2.0.0 이 함수는 geometry_columns이 시스템 카테고리에서 읽히는 뷰인 동안 더 이상 geometry_columns을 업데이트 하지 않습니다. 이것은 기본적으로 컨스트레인트를 만들지 않지만, 대신에 PostgreSQL의 내장된 타입 변경 동작이 대신합니다. 그래서 예를 들어 WGS84 POINT 컬럼을 이 함수로 만든다면 이 함수는 다음과 동등합니다: ALTER TABLE some_table ADD COLUMN geom geometry(Point,4326); 공간 테이블에서 지오메트리 컬럼을 제거합니다.
  • AddGeometryColumn - 변경 사항: 2.0.0 버전. 제약조건의 구식 습성이 필요할 경우, 기본값인 use_typmod 를 이용하되, 거짓으로 설정하십시오. 공간 테이블에서 지오메트리 컬럼을 제거합니다.
  • AddGeometryColumn - 변경 사항: 2.0.0 버전. 더 이상 뷰를 직접 geometry_columns에 등록시킬 수는 없지만, 도형 typmod 테이블 도형을 기반으로 빌드된 , 그리고 래퍼 함수 없이 사용되는 뷰는 자신의 페어런트 테이블 열의 typmod 습성을 상속하기 때문에 스스로를 정확히 등록시킵니다. 이런 뷰 도형 열을 geometry_columns에 정확히 등록시키려면, 다른 도형을 출력하는 도형 함수를 이용하는 뷰를 typmod 도형으로 형변환시켜야 할 것입니다. 을 참조하십시오. 공간 테이블에서 지오메트리 컬럼을 제거합니다.
  • Box3D - 변경 사항: 2.0.0 미만 버전에서는 BOX3D 대신 BOX2D를 이용했습니다. BOX2D가 지원이 끝난 유형이기 때문에, 2.0.0 버전에서 BOX3D로 바뀌었습니다. 래스터를 둘러싼 상자의 BOX3D 표현식을 반환합니다.
  • DropGeometryColumn - Changed: 2.0.0. Retained for backward compatibility after geometry_columns became a view of the system catalogs. 공간 테이블에서 지오메트리 컬럼을 제거합니다.
  • DropGeometryTable - Changed: 2.0.0. Retained for backward compatibility after geometry_columns became a view of the system catalogs. 테이블 및 geometry_columns의 모든 참조를 삭제합니다.
  • Populate_Geometry_Columns - 변경 사항: 2.0.0 버전. 이제 도형 유형을 제한하기 위해 확인 제약조건 대신 유형 변경자를 이용합니다. 새 use_typmod 를 거짓으로 설정하면, 확인 제약조건 습성을 계속 쓸 수 있습니다. Ensures geometry columns are defined with type modifiers or have appropriate spatial constraints.
  • ST_3DExtent - Changed: 2.0.0 In prior versions this used to be called ST_Extent3D Aggregate function that returns the 3D bounding box of geometries.
  • ST_3DLength - 변경 사항: 2.0.0 미만 버전에서는 ST_Length3D라는 명칭이었습니다. 도형의 기하학적 중심을 반환합니다.
  • ST_3DMakeBox - Changed: 2.0.0 In prior versions this used to be called ST_MakeBox3D Creates a BOX3D defined by two 3D point geometries.
  • ST_3DPerimeter - 변경 사항: 2.0.0 미만 버전에서는 ST_Perimeter3D라는 명칭이었습니다. 도형의 기하학적 중심을 반환합니다.
  • ST_AsBinary - Changed: 2.0.0 Inputs to this function can not be unknown -- must be geometry. Constructs such as ST_AsBinary('POINT(1 2)') are no longer valid and you will get an n ST_AsBinary(unknown) is not unique error. Code like that needs to be changed to ST_AsBinary('POINT(1 2)'::geometry);. If that is not possible, then install legacy.sql. Return the OGC/ISO Well-Known Binary (WKB) representation of the geometry/geography without SRID meta data.
  • ST_AsGML - 변경 사항: 2.0.0 버전부터 명명된 독립변수(named arg)를 기본값으로 씁니다. 도형을 GML 2 또는 GML 3 버전 요소로 반환합니다.
  • ST_AsGeoJSON - 변경 사항: 2.0.0 버전부터 기본 독립 변수(default arg) 및 명명된 독립 변수(named arg)를 지원합니다. Return a geometry or feature in GeoJSON format.
  • ST_AsSVG - 변경 사항: 2.0.0 버전부터 기본 독립 변수(default arg)를 사용하고 명명된 독립 변수(named arg)를 지원합니다. Returns SVG path data for a geometry.
  • ST_EndPoint - 변경 사항: 2.0.0 버전부터 단일 도형 멀티라인스트링을 지원하지 않습니다. PostGIS 예전 버전이라면 단일 라인 멀티라인스트링을 입력받는 경우 시작점을 반환했을 겁니다. 2.0.0 버전은 다른 모든 멀티라인스트링처럼 NULL을 반환할 뿐입니다. 구식 습성은 문서화되지 않은 기능이지만, 사용자 데이터를 라인스트링으로 저장했다고 가정한 사용자의 경우 현재 2.0 버전에서 NULL이 반환될 수도 있습니다. Returns the last point of a LineString, CircularLineString, or NURBSCurve.
  • ST_GDALDrivers - 변경 사항: 2.0.6, 2.1.3 버전 - GUC 또는 환경 변수 gdal_enabled_drivers를 설정하지 않을 경우, 기본적으로 어떤 드라이버도 활성화돼 있지 않습니다. Returns a list of raster formats supported by PostGIS through GDAL. Only those formats with can_write=True can be used by ST_AsGDALRaster
  • ST_GeomFromText - 변경 사항: PostGIS 2.0.0 미만 버전에서는 ST_GeomFromText('GEOMETRYCOLLECTION(EMPTY)') 를 사용할 수 있었습니다. PostGIS 2.0.0 버전부터, SQL/MM 표준을 더 잘 준수하기 위해 이런 사용법은 금지됐습니다. 이제는 ST_GeomFromText('GEOMETRYCOLLECTION EMPTY') 라고 작성해야 합니다. WKT 표현식으로부터 지정된 ST_Geometry 값을 반환합니다.
  • ST_GeometryN - 변경 사항: 2.0.0 미만 버전은 단일 도형에 대해 NULL을 반환했을 겁니다. 2.0.0 버전부터 ST_GeometryN(..,1) 경우에 대한 도형을 반환하도록 변경됐습니다. ST_Geometry 값의 도형 유형을 반환합니다.
  • ST_IsEmpty - 변경 사항: PostGIS 2.0.0 미만 버전에서는 ST_GeomFromText('GEOMETRYCOLLECTION(EMPTY)') 를 사용할 수 있었습니다. PostGIS 2.0.0 버전부터, SQL/MM 표준을 더 잘 준수하기 위해 이런 사용법은 금지됐습니다. Tests if a geometry is empty.
  • ST_Length - 변경 사항: 2.0.0 버전에서 중요한 변경이 이루어졌습니다. 2.0.0 이전 버전에서 이 함수에 폴리곤/멀티폴리곤 유형의 지리형을 입력하면 폴리곤/멀티폴리곤의 둘레를 반환했을 겁니다. 2.0.0 버전부터 도형 습성과 맞추기 위해 0을 반환하도록 변경됐습니다. 폴리곤의 둘레를 원한다면 ST_Perimeter 함수를 이용하십시오. 도형의 기하학적 중심을 반환합니다.
  • ST_LocateAlong - 변경 사항: 2.0.0 미만 버전에서는 ST_Locate_Along_Measure라는 명칭이었습니다. 예전 명칭은 더 지원되지 않고 곧 삭제될 예정이지만, 아직은 사용할 수 있습니다. Returns the point(s) on a geometry that match a measure value.
  • ST_LocateBetween - 변경 사항: 2.0.0 미만 버전에서는 ST_Locate_Along_Measure라는 명칭이었습니다. 예전 명칭은 더 지원되지 않고 곧 삭제될 예정이지만, 아직은 사용할 수 있습니다. Returns the portions of a geometry that match a measure range.
  • ST_ModEdgeSplit - 변경 사항: 2.0 미만 버전에서, 이 함수는 ST_ModEdgesSplit이라는 잘못된 명칭이었습니다. 기존 경계선을 따라 새 노드를 추가한 다음, 원본 경계선을 수정하고 새 경계선을 추가해서 경계선을 분할합니다.
  • ST_NumGeometries - 변경 사항: 2.0.0 미만 버전에서 도형이 집합이나 멀티 유형이 아닐 경우 NULL을 반환했습니다. 2.0.0 버전부터 폴리곤, 라인스트링, 포인트 같은 단일 도형에 대해 1을 반환합니다. 도형이 가지고 있는 포인트의 개수를 반환합니다. 모든 도형을 입력받을 수 있습니다.
  • ST_NumInteriorRings - 변경 사항: 2.0.0 미만 버전에서는 멀티폴리곤을 입력하면 첫 번째 폴리곤의 내곽 고리의 개수를 반환받을 수 있었습니다. 폴리곤 도형의 내곽 고리의 개수를 반환합니다.
  • ST_PointN - 변경 사항: 2.0.0 버전부터 단일 도형 멀티라인스트링을 지원하지 않습니다. PostGIS 예전 버전이라면 단일 라인 멀티라인스트링을 입력받는 경우 시작점을 반환했을 겁니다. 2.0.0 버전은 다른 모든 멀티라인스트링처럼 NULL을 반환할 뿐입니다. ST_LineString 또는 ST_CircularString 값에 있는 포인트의 개수를 반환합니다.
  • ST_ScaleX - 변경 사항: 2.0.0 미만 WKTRaster 버전에서는 ST_PixelSizeX라는 명칭이었습니다. 픽셀 너비의 X 요소를 좌표 참조 시스템의 단위로 반환합니다.
  • ST_ScaleY - 변경 사항: 2.0.0 미만 WKTRaster 버전에서는 ST_PixelSizeY라는 명칭이었습니다. 픽셀 높이의 Y 요소를 좌표 참조 시스템의 단위로 반환합니다.
  • ST_SetScale - 변경 사항: 2.0.0 미만 WKTRaster 버전에서는 ST_SetPixelSize라는 명칭이었습니다. 2.0.0 버전에서 현재 명칭으로 변경됐습니다. X 및 Y 픽셀 크기를 좌표 참조 시스템의 단위로 설정합니다. 단위/픽셀 너비/픽셀 높이 순서입니다.
  • ST_StartPoint - 변경 사항: 2.0.0 버전부터 단일 도형 멀티라인스트링을 지원하지 않습니다. PostGIS 예전 버전이라면 단일 라인 멀티라인스트링을 입력받는 경우 시작점을 반환했을 겁니다. 2.0.0 버전은 다른 모든 멀티라인스트링처럼 NULL을 반환할 뿐입니다. 구식 습성은 문서화되지 않은 기능이지만, 사용자 데이터를 라인스트링으로 저장했다고 가정한 사용자의 경우 현재 2.0 버전에서 NULL이 반환될 수도 있습니다. Returns the first point of a LineString, CircularLineString, or NURBSCurve.

13.12.15. PostGIS Functions new or enhanced in 1.5

The functions given below are PostGIS functions that were added or enhanced.

Functions new in PostGIS 1.5

  • && - 1.5.0 버전부터 지리형을 지원합니다. A의 2D 경계 상자와 B의 2D 경계 상자가 교차하는 경우 TRUE 를 반환합니다.
  • PostGIS_LibXML_Version - 1.5 버전부터 사용할 수 있습니다. Returns the version number of the libxml2 library.
  • ST_AddMeasure - 1.5.0 버전부터 사용할 수 있습니다. Interpolates measures along a linear geometry.
  • ST_AsBinary - 1.5.0 버전부터 지리형을 지원합니다. Return the OGC/ISO Well-Known Binary (WKB) representation of the geometry/geography without SRID meta data.
  • ST_AsGML - 1.5.0 버전부터 지리형을 지원합니다. 도형을 GML 2 또는 GML 3 버전 요소로 반환합니다.
  • ST_AsGeoJSON - 1.5.0 버전부터 지리형을 지원합니다. Return a geometry or feature in GeoJSON format.
  • ST_AsText - 1.5.0 버전부터 지리형을 지원합니다. 도형/지리형의 WKT(Well-Known Text) 표현식을 SRID 메타데이터 없이 반환합니다.
  • ST_Buffer - Availability: 1.5 - ST_Buffer was enhanced to support different endcaps and join types. These are useful for example to convert road linestrings into polygon roads with flat or square edges instead of rounded edges. Thin wrapper for geography was added. Computes a geometry covering all points within a given distance from a geometry.
  • ST_ClosestPoint - 1.5.0 버전부터 사용할 수 있습니다. Returns the 2D point on g1 that is closest to g2. This is the first point of the shortest line from one geometry to the other.
  • ST_CollectionExtract - 1.5.0 버전부터 사용할 수 있습니다. Given a geometry collection, returns a multi-geometry containing only elements of a specified type.
  • ST_Covers - 1.5.0 버전부터 지리형을 지원합니다. Tests if every point of B lies in A
  • ST_DFullyWithin - 1.5.0 버전부터 사용할 수 있습니다. Tests if a geometry is entirely inside a distance of another
  • ST_DWithin - Availability: 1.5.0 support for geography was introduced Tests if two geometries are within a given distance
  • ST_Distance - 1.5.0 버전부터 지리형을 지원합니다. 대용량 또는 수많은 꼭짓점을 가진 도형을 더 잘 처리하기 위해 평면에 대한 속도를 향상시켰습니다. 두 도형 사이의 3차원 최장(longest) 라인을 반환합니다.
  • ST_DistanceSphere - 1.5 버전부터 포인트가 아닌 다른 도형 유형을 지원하기 시작했습니다. 1.5 미만 버전에서는 포인트에 대해서만 구현돼 있었습니다. 특정 회전타원체가 주어진 두 경위도 도형 사이의 최단 거리를 반환합니다. PostGIS 1.5 미만 버전은 포인트만 지원했습니다.
  • ST_DistanceSpheroid - 1.5 버전부터 포인트가 아닌 다른 도형 유형을 지원하기 시작했습니다. 1.5 미만 버전에서는 포인트에 대해서만 구현돼 있었습니다. 특정 회전타원체가 주어진 두 경위도 도형 사이의 최단 거리를 반환합니다. PostGIS 1.5 미만 버전은 포인트만 지원했습니다.
  • ST_DumpPoints - 1.5.0 버전부터 사용할 수 있습니다. 도형의 내용을 요약한 텍스트를 반환합니다.
  • ST_Envelope - 1.5.0 버전부터 사용할 수 있으며, float4 형 대신 이중 정밀도 형으로 출력하도록 변경되었습니다. 주어진 도형의 이중 정밀도(double precision; float8) 경계 상자를 표현하는 도형을 반환합니다.
  • ST_Expand - Availability: 1.5.0 behavior changed to output double precision instead of float4 coordinates. Returns a bounding box expanded from another bounding box or a geometry.
  • ST_GMLToSQL - 1.5 버전부터 사용할 수 있습니다. LibXML2 1.6 이상 버전이 필요합니다. Returns a geometry from GML. Alias for ST_GeomFromGML.
  • ST_GeomFromGML - 1.5 버전부터 사용할 수 있습니다. LibXML2 1.6 이상 버전이 필요합니다. 도형의 GML 표현식을 입력받아 PostGIS 도형 객체를 출력합니다.
  • ST_GeomFromKML - Availability: 1.5, requires libxml2 2.6+ 도형의 KML 표현식을 입력받아 PostGIS 도형 객체를 출력합니다.
  • ST_HausdorffDistance - 1.5.0 버전부터 사용할 수 있습니다. 두 도형 사이의 3차원 최단(shortest) 라인을 반환합니다.
  • ST_Intersection - Availability: 1.5 support for geography data type was introduced. Computes a geometry representing the shared portion of geometries A and B.
  • ST_Intersects - Availability: 1.5 support for geography was introduced. Tests if two geometries intersect (they have at least one point in common)
  • ST_Length - 1.5.0 버전부터 지리형을 지원합니다. 도형의 기하학적 중심을 반환합니다.
  • ST_LongestLine - 1.5.0 버전부터 사용할 수 있습니다. 두 도형 사이의 3차원 최장(longest) 라인을 반환합니다.
  • ST_MakeEnvelope - 1.5 버전부터 사용할 수 있습니다. 주어진 최소값과 최대값으로 형성된 직사각형 폴리곤을 생성합니다. 입력값이 SRID로 지정된 SRS를 가지고 있어야 합니다.
  • ST_MaxDistance - 1.5.0 버전부터 사용할 수 있습니다. 두 도형 사이의 2차원 최장 거리를 투영 단위로 반환합니다.
  • ST_ShortestLine - 1.5.0 버전부터 사용할 수 있습니다. 두 도형 사이의 2차원 최단 라인을 반환합니다.
  • ~= - 1.5.0 버전에서 습성이 변경됐습니다. A의 경계 상자와 B의 경계 상자가 동일할 경우 TRUE 를 반환합니다.

13.12.16. PostGIS Functions new or enhanced in 1.4

The functions given below are PostGIS functions that were added or enhanced.

Functions new in PostGIS 1.4

  • Populate_Geometry_Columns - 1.4.0 버전부터 사용할 수 있습니다. Ensures geometry columns are defined with type modifiers or have appropriate spatial constraints.
  • ST_Collect - 1.4.0 버전부터 사용할 수 있습니다. 이 버전부터 ST_MakeLine가 도형 배열을 입력받을 수 있습니다. 더 많은 포인트를 더 빨리 처리하기 위해 ST_MakeLine 합산 함수를 개선했습니다. Creates a GeometryCollection or Multi* geometry from a set of geometries.
  • ST_ContainsProperly - 1.4.0 버전부터 사용할 수 있습니다. Tests if every point of B lies in the interior of A
  • ST_GeoHash - 1.4.0 버전부터 사용할 수 있습니다. 도형의 GeoHash 표현식을 반환합니다.
  • ST_IsValidReason - Availability: 1.4 Returns text stating if a geometry is valid, or a reason for invalidity.
  • ST_LineCrossingDirection - Availability: 1.4 Returns a number indicating the crossing behavior of two LineStrings
  • ST_LocateBetweenElevations - 1.4.0 버전부터 사용할 수 있습니다. Returns the portions of a geometry that lie in an elevation (Z) range.
  • ST_MakeLine - 1.4.0 버전부터 사용할 수 있습니다. 이 버전부터 ST_MakeLine가 도형 배열을 입력받을 수 있습니다. 더 많은 포인트를 더 빨리 처리하기 위해 ST_MakeLine 합산 함수를 개선했습니다. 포인트, 멀티포인트 또는 라인 도형으로부터 라인스트링을 생성합니다.
  • ST_MinimumBoundingCircle - 1.4.0 버전부터 사용할 수 있습니다. Returns the smallest circle polygon that contains a geometry.
  • ST_Union - Availability: 1.4.0 - ST_Union was enhanced. ST_Union(geomarray) was introduced and also faster aggregate collection in PostgreSQL. Computes a geometry representing the point-set union of the input geometries.

13.12.17. PostGIS Functions new or enhanced in 1.3

The functions given below are PostGIS functions that were added or enhanced.

Functions new in PostGIS 1.3

  • ST_AsGML - 1.3.2 버전부터 사용할 수 있습니다. 도형을 GML 2 또는 GML 3 버전 요소로 반환합니다.
  • ST_AsGeoJSON - 1.3.4 버전부터 사용할 수 있습니다. Return a geometry or feature in GeoJSON format.
  • ST_CurveToLine - Availability: 1.3.0 Converts a geometry containing curves to a linear geometry.
  • ST_LineToCurve - Availability: 1.3.0 Converts a linear geometry to a curved geometry.
  • ST_SimplifyPreserveTopology - 1.3.3 버전부터 사용할 수 있습니다. Returns a simplified and valid representation of a geometry, using the Douglas-Peucker algorithm.

14장. Reporting Problems

14.1. Reporting Software Bugs

Reporting bugs effectively is a fundamental way to help PostGIS development. The most effective bug report is that enabling PostGIS developers to reproduce it, so it would ideally contain a script triggering it and every information regarding the environment in which it was detected. Good enough info can be extracted running SELECT postgis_full_version() [for PostGIS] and SELECT version() [for postgresql].

If you aren't using the latest release, it's worth taking a look at its release changelog first, to find out if your bug has already been fixed.

Using the PostGIS bug tracker will ensure your reports are not discarded, and will keep you informed on its handling process. Before reporting a new bug please query the database to see if it is a known one, and if it is please add any new information you have about it.

You might want to read Simon Tatham's paper about How to Report Bugs Effectively before filing a new report.

14.2. Reporting Documentation Issues

The documentation should accurately reflect the features and behavior of the software. If it doesn't, it could be because of a software bug or because the documentation is in error or deficient.

Documentation issues can also be reported to the PostGIS bug tracker.

If your revision is trivial, just describe it in a new bug tracker issue, being specific about its location in the documentation.

If your changes are more extensive, a patch is definitely preferred. This is a four step process on Unix (assuming you already have git installed):

Before editing or building the manual, read the repository's documentation development guide. It covers the executable example, generated figure, validation, HTML, and PDF workflows used by the manual.

  1. Clone the PostGIS' git repository. On Unix, type:

    git clone https://git.osgeo.org/gitea/postgis/postgis.git

    This will be stored in the directory postgis

  2. Make your changes to the documentation with your favorite text editor. On Unix, type (for example):

    vim doc/postgis.xml

    Note that the documentation is written in DocBook XML rather than HTML, so if you are not familiar with it please follow the example of the rest of the documentation.

  3. Make a patch file containing the differences from the master copy of the documentation. On Unix, type:

    git diff doc/postgis.xml > doc.patch

  4. Attach the patch to a new issue in bug tracker.

15장. Credits and Acknowledgments

PostGIS is built and sustained by a worldwide community. This chapter records the people, organizations, funders, and upstream projects that have contributed code, documentation, infrastructure, testing, support, and funding.

15.1. Project Steering Committee

The PostGIS Project Steering Committee (PSC) coordinates the general direction, release cycles, documentation, and outreach efforts for the PostGIS project. In addition the PSC provides general user support, accepts and approves patches from the general PostGIS community and votes on miscellaneous issues involving PostGIS such as developer commit access, new PSC members or significant API changes.

Regina Obe

CI and website maintenance, Windows production and experimental builds, documentation, alignment of PostGIS with PostgreSQL releases, X3D support, management functions.

Darafei Praliaskouski

Index improvements, bug fixing and geometry/geography function improvements, SFCGAL, raster, GitHub curation, and ci maintenance.

Paul Ramsey (Chair)

Co-founder of PostGIS project. General bug fixing, geography support, geography and geometry index support (2D, 3D, nD index and anything spatial index), underlying geometry internal structures, GEOS functionality integration and alignment with GEOS releases, alignment of PostGIS with PostgreSQL releases, loader/dumper, and Shapefile GUI loader.

Sandro Santilli

Bug fixes and maintenance, ci maintenance, git mirror management, management functions, integration of new GEOS functionality and alignment with GEOS releases, topology support, and raster framework and low level API functions.

15.2. Core Contributors Present

Nicklas Avén

Distance function enhancements (including 3D distance and relationship functions) and additions, Tiny WKB (TWKB) output format and general user support

Loïc Bartoletti

SFCGAL enhancements and maintenance and ci support

Dan Baston

Geometry clustering function additions, other geometry algorithm enhancements, GEOS enhancements and general user support

Martin Davis

GEOS enhancements and documentation

Björn Harrtell

MapBox Vector Tile, GeoBuf, and Flatgeobuf functions. Gitea testing and GitLab experimentation.

Aliaksandr Kalenik

Geometry Processing, PostgreSQL gist, general bug fixing

Laurențiu Nicola

Bug fixes, maintenance, stability, and performance

15.3. Core Contributors Past

Raúl Marín Rodríguez

Prior PSC Member, MVT support, Bug fixing, Performance and stability improvements, GitHub curation, alignment of PostGIS with PostgreSQL releases

Bborie Park

Prior PSC Member. Raster development, integration with GDAL, raster loader, user support, general bug fixing, testing on various OS (Slackware, Mac, Windows, and more)

Mark Cave-Ayland

Prior PSC Member. Coordinated bug fixing and maintenance effort, spatial index selectivity and binding, loader/dumper, and Shapefile GUI Loader, integration of new and new function enhancements.

Jorge Arévalo

Raster development, GDAL driver support, loader

Olivier Courtin

(Emeritus) Input/output XML (KML,GML)/GeoJSON functions, 3D support and bug fixes.

Chris Hodgson

Prior PSC Member. General development, site and buildbot maintenance, OSGeo incubation management

Mateusz Loskot

CMake support for PostGIS, built original raster loader in python and low level raster API functions

Kevin Neufeld

Prior PSC Member. Documentation and documentation support tools, buildbot maintenance, advanced user support on PostGIS newsgroup, and PostGIS maintenance function enhancements.

Dave Blasby

The original developer/Co-founder of PostGIS. Dave wrote the server side objects, index bindings, and many of the server side analytical functions.

Jeff Lounsbury

Original development of the Shapefile loader/dumper.

Mark Leslie

Ongoing maintenance and development of core functions. Enhanced curve support. Shapefile GUI loader.

Pierre Racine

Architect of PostGIS raster implementation. Raster overall architecture, prototyping, programming support

David Zwarg

Raster development (mostly map algebra analytic functions)

15.4. Other Contributors

Individual Contributors

@amwps290 (GitHub user)Fabrice FontaineMarkus Wanner
@kannes (GitHub user: Hannes)Florentin DrogeanuMatt Amos
@sunhm89 (GitHub user)Florian WeimerMatt Bretl
@wewindy (GitHub user: Chen)François BonzonMatthias Bay
Adrien BerchetFrank WarmerdamMaxim Kochetkov
Alex BodnaruGeorge SilvaMaxime Guillaud
Alex MayrhoferGerald FenoyMaxime van Noppen
Andrea PeriGino LucreziMaxime Schoemans
Andreas Forø TollefsenGiovanni ZezzaMegan Ma
Andreas NeumannGrant HutchinsMichael Fuhr
Andreas SchildGreg TroxelMichal Páleník
Andrew GierthGuillaume LelargeMike Toews
Andrew HarveyGiuseppe BroccoloMitchell Henke
Anne GhislaHan WangNathan Wagner
Antoine BajoletHannes JanetzekNathaniel Clay
Ariel MashrakiHans LemuetNicolas Roelandt
Arno RenevierHaribabu KommiNikita Shulga
Arthur BazinHarrissou Sant-annaNikolai Berkoff
Arthur LesuisseHavard TveiteNorman Barker
Artur ZakirovIIDA TetsushiNorman Vine
Ayo AdesugbaIngvild NystuenPatricia Tozer
Barbara PhillipotJackie LengPaul Norman
Baris ErgunJames AddisonPaulo Cesar Coronado
Bas CouwenbergJames MarcaPavel Seleznev
Ben JubbJan KatinsPawel Ostrowski
Benjamin MorelJan TojnarPeter Nguyen
Bernd ReißJason SmithPierre Cardinal
Bernhard ReiterJean FelderRafal Magda
Bill MillJeff AdamsRalph Mason
Björn EsserJelte FennemaRémi Cura
Brian HamlinJim JonesRichard Greenwood
Bruce RindahlJoe ConwayRobert Coup
Bruno Wolff IIIJonne SavolainenRodrigo Smarzaro
Bryce L. NordgrenJorge Gustavo RochaRoger Crew
Carl AndersonJorge SanzRon Mayer
Carlos López QuintanillaJose Carlos Martinez LlariSam Peters
Charles KarneyJostein LeiraSergei Shoulbakov
Charlie SavageJörg HabenichtSergey Fedoseev
Chris MayoJuan Sebastian Jimenez AldanaShinichi Sugiyama
Christian SchroederJuergen E. FischerShoaib Burq
Christoph BergJulien MonticoloSilvio Grosso
Christoph Moench-TegederJulien RouhaudStefan Corneliu Petrea
Dan FaudemerKashif RasulSteffen Macke
Dan LevyKlaus FoersterStepan Kuzmin
Dane SpringmeyerKris JurkaStephen Frost
Daniel NylanderKristian ThyStephen Woodbridge
Dapeng WangLars Aksel OpsahlSteven Ottens
Daryl HerzmannLaurențiu NicolaTalha Rizwan
Dave FuhryLaurenz AlbeTemuri Doghonadze
David G. JohnstonLars RoessigerTeramoto Ikuhiro
David GarnierLauri KajanThomas Muguet
David SkeaLeo HsuThomas Petazzoni
David TecherLoic DacharyTobias Bussmann
Denys KovshunLouis DescoteauxTom Glancy
Devrim GündüzLuca DelucchiTom van Tilburg
Dian M FayLuca S. PercichVictor Collod
Dmitry VasilyevLucas C. Villa RealVincent Bre
Edouard ChoinièreLudovic HirlimannVincent Mora
Eduin CarrilloMaksim KorotkovVincent Picavet
Egor IvkovManuel MorilloVolf Tomáš
Esteban ZimanyiMaria Arias de ReynaYoichi Kayama
Eugene AntimirovMarc DucobuYuri Astrakhan
Evan SiMark SondheimZuo Chenwei
Even RouaultMarkus Schaber 

Corporate Sponsors

These are corporate entities that have contributed developer time, hosting, or direct monetary funding to the PostGIS project. In alphabetical order:

Crowd Funding Campaigns

Crowd funding campaigns are campaigns we run to get badly wanted features funded that can service a large number of people. Each campaign is specifically focused on a particular feature or set of features. Each sponsor chips in a small fraction of the needed funding and with enough people/organizations contributing, we have the funds to pay for the work that will help many. If you have an idea for a feature you think many others would be willing to co-fund, please post to the PostGIS newsgroup your thoughts and together we can make it happen.

PostGIS has experimented with community fundraising for features in the past. We used PledgeBank and we got two successful campaigns out of it.

postgistopology - 10 plus sponsors each contributed $250 USD to build toTopoGeometry function and beef up topology support in 2.0.0. It happened.

postgis64windows - 20 someodd sponsors each contributed $100 USD to pay for the work needed to work out PostGIS 64-bit issues on windows. It happened.

External Libraries and Platforms

PostgreSQL, the extensible database system on which PostGIS is built. PostgreSQL provides the SQL engine, transactions, query planner, extension framework, and index access methods used by PostGIS.

The GEOS geometry operations library.

The PROJ coordinate transformation and geodesic calculation library.

The GDAL Geospatial Data Abstraction Library used to power much of the raster functionality introduced in PostGIS 2. In kind, improvements needed in GDAL to support PostGIS are contributed back to the GDAL project.

LibXML2 for XML-based spatial formats, and JSON-C for GeoJSON input.

The GNU Multiple Precision Arithmetic Library (GMP) for precision-sensitive topology operations.

protobuf-c for Mapbox Vector Tile and Geobuf output.

The iconv API, supplied by the C library or GNU libiconv, for character encoding conversion in the shapefile loader.

SFCGAL for advanced 2D and 3D functions, together with the CGAL algorithms that SFCGAL exposes.

Bundled Libraries and Source Code

PostGIS ships selected source from FlatGeobuf and FlatBuffers to support FlatGeobuf input and output.

Wagyu and Mapbox Geometry provide polygon clipping and validation for Mapbox Vector Tile output.

Ryu provides round-trip-safe floating-point formatting, and uthash provides in-process hash tables.

The shapefile loader and dumper include code derived from ShapeLib, originally by Frank Warmerdam and Even Rouault. They also include public-domain getopt code from AT&T.

liblwgeom/lookup3.c contains the public-domain lookup3 hash function by Bob Jenkins.

부록 A. Release Notes

A.1. PostGIS 3.7.0

2026/xx/xx

This version requires GEOS 3.10+, PostgreSQL 14-19beta1, Proj 6.1+, libgmp. To take advantage of all features postgis extension features, GEOS 3.15+ is needed. To take advantage of all postgis_sfcgal extension features SFCGAL 2.3+ is needed.

A.1.1. Breaking Changes

#5688, [topology] topology building functions now interpret tolerance 0 (old default) to really mean 0 and want -1 (new default) to mean "use topology precision" (Sandro Santilli)

#6024, Remove support for PostgreSQL 12 and 13 (Regina Obe)

#6040, ST_GeoHash round trip through ST_GeomFromGeoHash (Paul Ramsey)

#6053, [address_standardizer] Extension removed and moved to https://github.com/postgis/address_standardizer (Paul Ramsey)

#6052, [tiger_geocoder] Extension removed and moved to https://git.osgeo.org/postgis/postgis_tiger_geocoder (Regina Obe)

#6079, Remove support for GEOS < 3.10 (Sandro Santilli)

#1793, Remove ST_MemCollect aggregate (Darafei Praliaskouski)

GH-848, CG_AlphaShape now returns a MultiPolygon (Jean Felder)

A.1.2. New Features

#1124, #2935, #3033, #4658, #4659, [loader] Rework loader arguments: shp2pgsql can create UNLOGGED tables and choose the feature id column name, shp2pgsql --drop-table can emit DROP TABLE before prepare output, raster2pgsql/shp2pgsql expose loader actions as long options, both loaders accept long aliases for existing options, and

-if-not-exists makes creation actions idempotent (Darafei Praliaskouski)

#4208, Add single-geometry variants of ST_MaxDistance and ST_LongestLine (Darafei Praliaskouski)

[topology] FindVertexSegmentPairsBelowDistance function (Sandro Santilli)

ST_CoverageEdges, returns MultiLinestring of distinct shared edges in polygonal coverage (Paul Ramsey)

ST_MinimumSpanningTree, window function to calculate MST (Paul Ramsey)

#5993, [topology] Add max_edges parameter to TopoGeo_AddLinestring (Sandro Santilli)

#6001, support MultiLineString in ST_MakeLine (Paul Ramsey)

#2858, ST_MMin and ST_MMax (Paul Ramsey)

#5941, [raster] Support GDT_Float16 pixel type (Darafei Praliaskouski)

#5992, Optimize GiST index for repeated edge subdivision in topology (Darafei Praliaskouski)

#5702, Allow the compiler to detect the parallelism -flto=auto (Darafei Praliaskouski)

#4798, ST_AsGeoJSON warns about duplicate property keys (Darafei Praliaskouski)

#5950, Document POSTGIS_REGRESS_DB_OWNER for sandboxed regression roles (Darafei Praliaskouski)

#4332, Clarify the scope of several Function Reference categories (Darafei Praliaskouski)

#4222, [raster] ST_DumpAsPolygons honours PostgreSQL interrupts (Darafei Praliaskouski)

#5109, Document the meaning of topology.next_left_edge and topology.next_right_edge links (Darafei Praliaskouski)

#5889, [topology] Include representative locations in topology build errors (Darafei Praliaskouski)

#2614, Use GEOSPreparedDistance and caching to accelerate ST_DWithin (Paul Ramsey)

#6022, Document ST_AsMVTGeom tile-coordinate simplification (Darafei Praliaskouski)

GH-839, ST_Multi support for TIN and surfaces (Loïc Bartoletti)

#4398, Add ST_CatmullSmoothing smoothes but retains original vertices (Paul Ramsey)

#4560, ST_3DInterpolatePoint for M interpolation from XYZ inputs (Paul Ramsey)

#1291, ST_MakePolygon support for curved rings (Darafei Praliaskouski)

GT-270, Add NURBSCurve (Loïc Bartoletti)

#2863, Add ST_XSize, ST_YSize, ST_ZSize, and ST_MSize dimension helpers (Darafei Praliaskouski)

[fuzzers] Centralize OSS-Fuzz build/dependency logic in PostGIS scripts, prefer requested CXX over pg_config --cc for internal C++ checks, and make fuzzer linking/runtime dependency packaging portable (Darafei Praliaskouski)

A.1.3. Enhancements

#2045, pgsql2shp query dumps no longer require temporary table privileges (Darafei Praliaskouski)

#1577, [loader] Report unsupported .zip archive input before trying to open shapefile sidecar files (Darafei Praliaskouski)

#3158, Move geometry and geography typmod bit helpers out of the public liblwgeom header (Darafei Praliaskouski)

#4678, [raster] Move st_sum4ma neighborhood callback to C (Darafei Praliaskouski)

#2116, [raster] Add ST_Value nearest-neighbor boundary options (Darafei Praliaskouski)

#2804, #4315, [raster] Support two-argument ST_MapAlgebra callbacks and pass callback call data as actual arguments (Darafei Praliaskouski)

#2898, Document SQL function cost tiers for contributors

#6062, [topology] Stop using recursive snapping, for improved robustness (Sandro Santilli)

#6065, Improved winding order computation robustness for rings having collapsed elements (Sandro Santilli)

#3743, #4385, [raster loader] Document raster2pgsql -s FROM_SRID:SRID reprojection support and clarify index creation timing for append loads (Darafei Praliaskouski)

#2137, [raster] Reuse matching source raster overviews in raster2pgsql -l (Darafei Praliaskouski)

#4749, Use point-in-polygon predicate fast paths for point-only GeometryCollections (Darafei Praliaskouski)

#5532, Validate the manual against DocBook XMLSchema in check-xml (Darafei Praliaskouski)

#6087, Add a repository-owned CI status checker and static dashboard generator (Darafei Praliaskouski)

#2807, [raster] Preserve missing NODATA values in ST_MapAlgebra outputs (Darafei Praliaskouski)

#2832, [raster] Avoid padding single-tile raster2pgsql overviews when padding is not requested (Darafei Praliaskouski)

#2623, Generate a pgsql2shp GID field when exporting geometry-only shapefiles (Darafei Praliaskouski)

#2850, Preserve pgsql2shp numeric precision and scale in DBF metadata (Darafei Praliaskouski)

#2386, Add raster2pgsql man page (Darafei Praliaskouski)

Build PostgreSQL extension modules with `-fno-semantic-interposition` when available so LTO can optimize same-DSO calls to exported PostGIS entry points directly instead of routing through the module PLT; in a local PostgreSQL 18 `pgbench` microbenchmark over 100k four-point groups this reduced `ST_Collect` aggregate latency by about 4% (Darafei Praliaskouski)

#5973, Install PostGIS utilities under `pg_config --bindir` by default and document `pg_config`-derived install paths more accurately (Darafei Praliaskouski)

#2808, Clarify postgis_full_version() output when installed component scripts are newer than core scripts (Darafei Praliaskouski)

#5593, Docs: render manual images with GraphicsMagick without temporary files, enabling parallel builds, keeping ImageMagick fallbacks working, and documenting the generator workflow for contributors (Darafei Praliaskouski)

#5645, Docs: keep code operators ("=>") intact in translated manuals by enforcing verbatim CSS (Darafei Praliaskouski)

#1408, Docs: flatten transparent manual images onto white backgrounds for PDF builds while keeping HTML images transparent (Darafei Praliaskouski)

#2838, Emit valid X3D Coordinate nodes for 2D polygon output (Darafei Praliaskouski)

#1705, Infer constraint metadata for direct view and materialized view geometry columns (Darafei Praliaskouski)

GH-899, [raster] Honor PostgreSQL interrupts in long-running GDAL progress callbacks (Darafei Praliaskouski)

#2583, Preserve Z/ZM dimensional qualifiers in ST_AsEWKT output for TIN (Darafei Praliaskouski)