PostGIS — це розширення для об'єктно-реляційної системи баз даних PostgreSQL, яке дозволяє зберігати об'єкти ГІС (географічних інформаційних систем) у базі даних. PostGIS підтримує просторові індекси R-Tree на основі GiST, а також функції для аналізу та обробки об'єктів ГІС.
Це інструкція для версії 3.6.3
Ця робота ліцензована за ліцензією Creative Commons Attribution-Share Alike 3.0 License. Ви можете використовувати цей матеріал будь-яким чином, але просимо вас вказати посилання на проект PostGIS та, по можливості, на https://postgis.net.
PostGIS — це просторове розширення для реляційної бази даних PostgreSQL, створене компанією Refractions Research Inc. як проект з дослідження технологій просторових баз даних. Refractions — це компанія з консалтингу в галузі ГІС та баз даних, розташована у місті Вікторія, Британська Колумбія, Канада, що спеціалізується на інтеграції даних та розробці програмного забезпечення на замовлення.
PostGIS зараз є проєктом Фонду OSGeo, розробляється і фінансується багатьма розробниками FOSS4G і організаціями по всьому світу, які отримують величезну користь від його функціональності та універсальності.
Група розробників проєкту PostGIS планує підтримувати та вдосконалювати PostGIS для кращої підтримки ряду важливих функціональних можливостей ГІС в області просторових стандартів OGC і SQL/MM, розширених топологічних конструкцій (покриття, поверхні, сітки), джерел даних для інструментів для перегляду і редагування даних ГІС, а також інструментів вебдоступу до них.
Координаційний комітет проекту PostGIS (PSC) координує загальний напрямок, цикли випуску, документацію та інформаційно-просвітницьку діяльність проекту PostGIS. Крім того, PSC надає загальну підтримку користувачам, приймає та затверджує виправлення від загальної спільноти PostGIS і голосує з різних питань, що стосуються PostGIS, таких як доступ розробників до комітів, нові члени PSC або значні зміни API.
Підтримка MVT, виправлення помилок, поліпшення продуктивності та стабільності, курація GitHub, узгодження PostGIS з релізами PostgreSQL
CI та обслуговування веб-сайту, виробництво та експериментальні збірки Windows, документація, узгодження PostGIS з випусками PostgreSQL, підтримка X3D, підтримка геокодера TIGER, функції управління.
Покращення індексу, виправлення помилок та покращення функцій геометрії/географії, SFCGAL, растр, курація GitHub та обслуговування ci.
Співзасновник проекту PostGIS. Загальне виправлення помилок, підтримка географії, підтримка географічних та геометричних індексів (2D, 3D, nD індекси та будь-які просторові індекси), внутрішні структури геометрії, інтеграція функціональності GEOS та узгодження з релізами GEOS, узгодження PostGIS з релізами PostgreSQL, завантажувач/вивантажувач та завантажувач Shapefile GUI.
Виправлення помилок та технічне обслуговування, обслуговування CI, управління дзеркалами Git, функції управління, інтеграція нових функцій GEOS та узгодження з випусками GEOS, підтримка топології, а також функції растрової структури та API низького рівня.
Покращення функції відстані (включно з функціями 3D-відстані та взаємозв'язку) та доповнення, формат виводу Tiny WKB (TWKB) та загальна підтримка користувачів
Покращення та обслуговування SFCGAL і підтримка ci
Додавання функцій кластеризації геометрії, інші вдосконалення алгоритмів геометрії, вдосконалення GEOS та загальна підтримка користувачів
Удосконалення та документація GEOS
Функції MapBox Vector Tile, GeoBuf та Flatgeobuf. Тестування Gitea та експерименти GitLab.
Обробка геометрії, PostgreSQL gist, загальне виправлення помилок
Колишній член PSC. Розробка растрових даних, інтеграція з GDAL, завантажувач растрових даних, підтримка користувачів, загальне виправлення помилок, тестування на різних ОС (Slackware, Mac, Windows та інші)
Колишній член PSC. Координація виправлення помилок та технічного обслуговування, вибірковості та прив'язки просторового індексу, завантажувача/вивантажувача, а також Shapefile GUI Loader, інтеграція нових та вдосконалених функцій.
Розробка растрових даних, підтримка драйвера GDAL, завантажувач
(Почесний) Функції введення/виведення XML (KML, GML)/GeoJSON, підтримка 3D та виправлення помилок.
Колишній член PSC. Загальний розвиток, обслуговування сайту та buildbot, управління інкубацією OSGeo
Підтримка CMake для PostGIS, вбудований оригінальний завантажувач растрових даних на Python та функції низького рівня для роботи з растровими даними
Колишній член PSC. Документація та інструменти підтримки документації, обслуговування buildbot, підтримка досвідчених користувачів у новинній групі PostGIS та вдосконалення функцій обслуговування PostGIS.
Оригінальний розробник/співзасновник PostGIS. Дейв написав об'єкти серверної частини, індексні прив'язки та багато аналітичних функцій серверної частини.
Оригінальна розробка завантажувача/вивантажувача Shapefile.
Постійне обслуговування та розвиток основних функцій. Покращена підтримка кривих. Завантажувач Shapefile GUI.
Архітектор реалізації растрових даних PostGIS. Загальна архітектура растрових даних, прототипування, підтримка програмування
Розробка растрових даних (переважно аналітичні функції алгебри карт)
| Алекс Боднару | Джеральд Феной | Матіас Бей |
| Алекс Майрхофер | Джино Лукрезі | Максим Гійо |
| Андреа Пері | Грег Троксел | Максима ван Ноппен |
| Андреас Форо Толлефсен | Гійом Леларж | Максим Шеманс |
| Андреас Нойман | Джузеппе Брокколо | Меган Ма |
| Ендрю Герт | Хан Ван | Майкл Фур |
| Енн Гісла | Ганс Лемует | Майк Тоус |
| Антуан Бажоле | Харібабу Коммі | Натан Вагнер |
| Артур Лесуа | Хавард Твейте | Натаніель Клей |
| Артур Закіров | ІІДА Тетсуші | Nikolai Berkoff |
| Айо Адесугба | Інгвільд Нюстен | Микита Шульга |
| Барбара Філліпот | Джекі Ленг | Норман Вайн |
| Бен Джубб | Джеймс Аддісон | Патрісія Тозер |
| Бернхард Райтер | Джеймс Марка | Рафал Магда |
| Бйорн Ессер | Ян Катінс | Ральф Мейсон |
| Брайан Хемлін | Ян Тожнар | Ремі Кура |
| Брюс Ріндал | Джейсон Сміт | Річард Грінвуд |
| Бруно Вольф III | Джефф Адамс | Роберт Куп |
| Брайс Л. Нордгрен | Джелте Феннема | Роджер Крю |
| Карл Андерсон | Джим Джонс | Рон Майер |
| Чарлі Сейвідж | Джо Конвей | Сем Пітерс |
| Кріс Майо | Йонне Саволайнен | Себастьян Коувенберг |
| Крістіан Шредер | Хосе Карлос Мартінес Лларі | Сергій Шульбаков |
| Крістоф Берг | Йорг Хабеніхт | Сергій Федосєєв |
| Крістоф Менх-Тегедер | Жюльєн Руо | Шінічі Сугіяма |
| Дейн Спрінгмейер | Кашиф Расул | Шоаїб Бурк |
| Даніель Нюландер | Клаус Ферстер | Сільвіо Гроссо |
| Дапен Ван | Кріс Юрка | Стефан Корнеліу Петреа |
| Деріл Герцманн | Лаурентіу Нікола | Стеффен Макке |
| Дейв Фурі | Лауренц Альбе | Степан Кузьмін |
| Девід Гарньє | Ларс Роессігер | Стівен Фрост |
| Девід Скі | Лео Хсу | Стівен Оттенс |
| Девід Течер | Лоїк Дачарі | Талха Різван |
| Denys Kovshun | Лука С. Перчіч | Терамото Ікухіро |
| Діан М. Фей | Лукас С. Вілла Реаль | Том Гленсі |
| Дмитро Василєв | Максим Коротков | Том ван Тільбург |
| Едуїн Каррільо | Марія Аріас де Рейна | Віктор Колод |
| Естебан Зімані | Марк Дюкубу | Вінсент Бре |
| Євген Антиміров | Марк Сондхайм | Вінсент Мора |
| Навіть Руо | Маркус Шабер | Вінсент Пікаве |
| Флоріан Ваймер | Маркус Ваннер | Вольф Томаш |
| Френк Вармердам | Метт Амос | Зуо Ченвей |
| Джордж Сільва | Метт Бретл |
Це корпоративні організації, які надали розробникам час, хостинг або пряме фінансове фінансування для проекту PostGIS. У алфавітному порядку:
Кампанії з краудфандингу — це кампанії, які ми проводимо, щоб зібрати кошти на реалізацію дуже потрібних функцій, які можуть бути корисними для великої кількості людей. Кожна кампанія зосереджена на конкретній функції або наборі функцій. Кожен спонсор вносить невелику частину необхідних коштів, і за умови, що достатня кількість людей/організацій долучиться до кампанії, ми отримаємо кошти для оплати роботи, яка допоможе багатьом. Якщо у вас є ідея щодо функції, яку, на вашу думку, багато інших людей були б готові спільно фінансувати, будь ласка, опублікуйте її в групі новин PostGIS, і разом ми зможемо її реалізувати.
PostGIS 2.0.0 був першим випуском, в якому ми випробували цю стратегію. Ми використовували PledgeBank і провели дві успішні кампанії.
postgistopology - 10 спонсорів внесли по 250 доларів США на створення функції toTopoGeometry та покращення підтримки топології в версії 2.0.0. Це сталося.
postgis64windows - 20 спонсорів внесли по 100 доларів США для оплати робіт, необхідних для вирішення проблем PostGIS 64-bit на Windows. Це сталося.
Бібліотека геометричних операцій GEOS
Бібліотека абстракції геопросторових даних GDAL використовується для забезпечення більшості функцій роботи з растровими даними, представлених у PostGIS 2. Відповідно, поліпшення, необхідні в GDAL для підтримки PostGIS, вносяться назад у проект GDAL.
Бібліотека картографічних проекцій PROJ
І останнє, але не менш важливе, PostgreSQL, гігант, на якому стоїть PostGIS. Більша частина швидкості та гнучкості PostGIS була б неможливою без розширюваності, чудового планувальника запитів, індексу GIST та безлічі функцій SQL, що надаються PostgreSQL.
У цьому розділі детально описано кроки, необхідні для встановлення PostGIS.
Щоб скомпілювати, припускаючи, що у вашому шляху пошуку є всі залежності:
tar -xvzf postgis-3.6.3.tar.gz cd postgis-3.6.3 ./configure make make install
Після встановлення PostGIS його потрібно ввімкнути (Section 3.3, “Створення просторових баз даних”) або оновити (Section 3.4, “Оновлення просторових баз даних”) в кожній окремій базі даних, в якій ви хочете його використовувати.
![]() | |
Багато операційних систем зараз містять готові пакети для PostgreSQL/PostGIS. У більшості випадків компіляція необхідна лише якщо ви хочете отримати найновіші версії або ви є розробником пакету. Цей розділ містить загальні інструкції з компіляції. Якщо ви компілюєте для Windows тощо або іншої ОС, додаткову детальну допомогу можна знайти за посиланням Посібники з компіляції, надані користувачами PostGIS та PostGIS Dev Wiki. Готові пакети для різних операційних систем перелічені в Готові пакети PostGIS Якщо ви користуєтеся Windows, ви можете отримати стабільні збірки через Stackbuilder або сайт завантаження PostGIS для Windows. Ми також маємо дуже новітні експериментальні збірки для Windows, які зазвичай створюються один-два рази на тиждень або коли трапляється щось цікаве. Ви можете використовувати їх для експериментів з поточними версіями PostGIS |
Модуль PostGIS є розширенням серверного бекенду PostgreSQL. Як такий, PostGIS 3.6.3 вимагає повного доступу до заголовків сервера PostgreSQL для компіляції. Його можна скомпілювати для версій PostgreSQL 12 - 18. Раніші версії PostgreSQL не підтримуються.
Якщо ви ще не встановили PostgreSQL, зверніться до інструкцій з інсталяції PostgreSQL. https://www.postgresql.org .
![]() | |
Для роботи GEOS, під час встановлення PostgreSQL може знадобитися явно пов'язати PostgreSQL зі стандартною бібліотекою C++: LDFLAGS=-lstdc++ ./configure [YOUR OPTIONS HERE] Це обхідний шлях для вирішення проблеми взаємодії помилкових винятків C++ зі старими інструментами розробки. Якщо ви зіткнулися з дивними проблемами (несподіване закриття бекенду або подібні речі), спробуйте цей трюк. Звичайно, для цього потрібно буде перекомпілювати PostgreSQL з нуля. |
Наступні кроки описують конфігурацію та компіляцію вихідного коду PostGIS. Вони написані для користувачів Linux і не працюватимуть на Windows або Mac.
Завантажте архів PostGIS з веб-сайту завантажень https://download.osgeo.org/postgis/source/postgis-3.6.3.tar.gz
wget https://download.osgeo.org/postgis/source/postgis-3.6.3.tar.gz tar -xvzf postgis-3.6.3.tar.gz cd postgis-3.6.3
Це створить каталог з назвою postgis-3.6.3 у поточному робочому каталозі.
Або перегляньте джерело з репозиторію git https://git.osgeo.org/gitea/postgis/postgis/ .
git clone https://git.osgeo.org/gitea/postgis/postgis.git postgis
cd postgis
sh autogen.sh
Перейдіть до новоствореного каталогу postgis, щоб продовжити встановлення.
./configure
PostGIS має наступні вимоги до побудови та використання:
Необхідно
PostgreSQL 12 - 18. Потрібна повна інсталяція PostgreSQL (включно з заголовками сервера). PostgreSQL доступний за адресою https://www.postgresql.org 18 .
Повна матриця підтримки PostgreSQL / PostGIS та матриця підтримки PostGIS/GEOS наведена за посиланням https://trac.osgeo.org/postgis/wiki/UsersWikiPostgreSQLPostGIS
Компілятор GNU C (gcc). Для компіляції PostGIS можна використовувати й інші компілятори ANSI C, але при компіляції за допомогою gcc ми зустрічаємо набагато менше проблем.
GNU Make (gmake або make). Для багатьох систем GNU make є стандартною версією make. Перевірте версію, викликавши make -v. Інші версії make можуть не обробляти PostGIS Makefile належним чином.
Бібліотека перепроекції Proj. Потрібна версія Proj 6.1 або вище. Бібліотека Proj використовується для забезпечення підтримки перепроекції координат у PostGIS. Proj можна завантажити за адресою https://proj.org/ .
Бібліотека геометрії GEOS, версія 3.8.0 або вище, але для повного використання всіх нових функцій і можливостей необхідна версія GEOS 3.14+. GEOS можна завантажити за адресою https://libgeos.org .
LibXML2, версія 2.5.x або вище. LibXML2 наразі використовується в деяких функціях імпорту (ST_GeomFromGML та ST_GeomFromKML). LibXML2 можна завантажити за адресою https://gitlab.gnome.org/GNOME/libxml2/-/releases.
JSON-C, версія 0.9 або вище. JSON-C наразі використовується для імпорту GeoJSON за допомогою функції ST_GeomFromGeoJson. JSON-C можна завантажити за посиланням https://github.com/json-c/json-c/releases/.
GDAL, версія 3+ є кращою. Це необхідно для підтримки растрових даних. https://gdal.org/download.html.
При компіляції з PostgreSQL+JIT необхідна версія LLVM >=6 https://trac.osgeo.org/postgis/ticket/4125.
Додатково
GDAL (псевдоопціональний) тільки якщо ви не хочете растрові дані, ви можете залишити його поза увагою. Також переконайтеся, що ви ввімкнули драйвери, які ви хочете використовувати, як описано в Section 3.2, “Налаштування підтримки растрів”.
GTK (потрібно GTK+2.0, 2.8+) для компіляції завантажувача файлів shp2pgsql-gui. http://www.gtk.org/ .
SFCGAL, 1.4.1 або вище, а для використання всіх функцій необхідна версія 2.1+. SFCGAL можна використовувати для надання додаткових функцій розширеного 2D- та 3D-аналізу для PostGIS cf Chapter 8, SFCGAL Functions Reference. А також дозволяє використовувати SFCGAL замість GEOS для деяких 2D-функцій, що надаються обома бекендами (наприклад, ST_Intersection або ST_Area). Конфігураційна змінна PostgreSQL postgis.backend дозволяє кінцевому користувачеві контролювати, який бекенд він хоче використовувати, якщо встановлено SFCGAL (за замовчуванням GEOS). Примітка: SFCGAL 1.2 вимагає принаймні CGAL 4.3 та Boost 1.54 (див.: https://sfcgal.org) https://gitlab.com/sfcgal/SFCGAL/.
Для побудови Section 12.1, “Стандартизатор адрес” вам також знадобиться PCRE 1 або 2 http://www.pcre.org (яка, як правило, вже встановлена в системах nix). Section 12.1, “Стандартизатор адрес” буде створено автоматично, якщо буде виявлено бібліотеку PCRE, або якщо ви передасте дійсний --with-pcre-dir=/path/to/pcre під час конфігурації.
Щоб увімкнути ST_AsMVT, потрібна бібліотека protobuf-c 1.1.0 або вище (для використання) та компілятор protoc-c (для побудови). Також для перевірки мінімальної версії protobuf-c необхідний pkg-config. Див. protobuf-c. За замовчуванням Postgis використовує Wagyu для швидшої перевірки полігонів MVT, що вимагає компілятора c++11. Він використовуватиме CXXFLAGS і той самий компілятор, що й інсталяція PostgreSQL. Щоб вимкнути це і замість цього використовувати GEOS, під час конфігурації вкажіть --without-wagyu.
CUnit (CUnit). Це потрібно для регресійного тестування. http://cunit.sourceforge.net/
Для створення документації необхідний DocBook (xsltproc). Docbook доступний за адресою http://www.docbook.org/ .
DBLatex (dblatex) необхідний для створення документації у форматі PDF. DBLatex доступний за адресою http://dblatex.sourceforge.net/ .
Для створення зображень, що використовуються в документації, необхідна програма ImageMagick (convert). ImageMagick доступна за адресою http://www.imagemagick.org/ .
Як і в більшості випадків встановлення Linux, першим кроком є створення файлу Makefile, який буде використовуватися для компіляції вихідного коду. Це робиться за допомогою виконання скрипта оболонки
./configure
Без додаткових параметрів ця команда спробує автоматично знайти необхідні компоненти та бібліотеки, потрібні для компіляції вихідного коду PostGIS у вашій системі. Хоча це найпоширеніший спосіб використання ./configure, скрипт приймає кілька параметрів для тих, хто має необхідні бібліотеки та програми в нестандартних місцях.
У наведеному нижче списку вказані лише найчастіше використовувані параметри. Повний список можна отримати за допомогою параметрів --help або --help=short.
--with-library-minor-versionПочинаючи з PostGIS 3.0, файли бібліотеки, що генеруються за замовчуванням, більше не матимуть незначну версію як частину імені файлу. Це означає, що всі бібліотеки PostGIS 3 будуть закінчуватися на postgis-3. Це було зроблено для спрощення pg_upgrade, але має той недолік, що ви можете встановити на сервер лише одну версію PostGIS 3. Щоб повернути стару поведінку файлів із включенням другорядної версії, наприклад postgis-3.0, додайте цей перемикач до вашої конфігураційної команди.
--prefix=PREFIXЦе місце, куди будуть встановлені виконувані файли завантажувача PostGIS та спільні бібліотеки. За замовчуванням це місце збігається з місцем встановлення PostgreSQL.
![]() | |
Цей параметр наразі не працює, оскільки пакет встановлюється лише в каталог інсталяції PostgreSQL. Відвідайте http://trac.osgeo.org/postgis/ticket/635 , щоб відстежити цю помилку. |
--with-pgconfig=FILEPostgreSQL надає утиліту під назвою pg_config для увімкнення розширень, таких як PostGIS, для пошуку каталогу інсталяції PostgreSQL. Використовуйте цей параметр (--with-pgconfig=/path/to/pg_config), щоб вручну вказати конкретну інсталяцію PostgreSQL, на основі якої буде побудовано PostGIS.
--with-gdalconfig=FILEGDAL, необхідна бібліотека, надає функціональність, необхідну для підтримки растрових даних gdal-config, щоб програмне забезпечення могло знайти каталог інсталяції GDAL. Використовуйте цей параметр (--with-gdalconfig=/path/to/gdal-config), щоб вручну вказати конкретну інсталяцію GDAL, на основі якої буде побудовано PostGIS.
--with-geosconfig=FILEGEOS, необхідна бібліотека геометрії, надає утиліту під назвою geos-config для того, щоб програмне забезпечення могло знайти каталог інсталяції GEOS. Використовуйте цей параметр (--with-geosconfig=/path/to/geos-config), щоб вручну вказати конкретну інсталяцію GEOS, на основі якої буде побудовано PostGIS.
--with-xml2config=FILELibXML — це бібліотека, необхідна для виконання процесів GeomFromKML/GML. Зазвичай вона знаходиться, якщо у вас встановлено libxml, але якщо її немає або ви хочете використовувати конкретну версію, вам потрібно вказати PostGIS на конкретний файл конфігурації xml2-config, щоб програмне забезпечення могло знайти каталог установки LibXML. Використовуйте цей параметр (>--with-xml2config=/path/to/xml2-config), щоб вручну вказати конкретну інсталяцію LibXML, на основі якої буде побудовано PostGIS.
--with-projdir=DIRProj — це бібліотека перепроекції, необхідна для PostGIS. Використовуйте цей параметр (--with-projdir=/path/to/projdir), щоб вручну вказати конкретний каталог інсталяції Proj, на основі якого буде побудовано PostGIS.
--with-libiconv=DIRКаталог, в якому встановлено iconv.
--with-jsondir=DIRJSON-C — це бібліотека JSON з ліцензією MIT, необхідна для підтримки PostGIS ST_GeomFromJSON. Використовуйте цей параметр (--with-jsondir=/path/to/jsondir), щоб вручну вказати конкретний каталог інсталяції JSON-C, на основі якого буде побудовано PostGIS.
--with-pcredir=DIRPCRE — це бібліотека регулярних виразів, сумісна з Perl, що має ліцензію BSD і потрібна для розширення address_standardizer. Використовуйте цей параметр (--with-pcredir=/path/to/pcredir), щоб вручну вказати конкретний каталог інсталяції PCRE, на основі якого буде побудовано PostGIS.
--with-guiСкомпілюйте графічний інтерфейс імпорту даних (потрібен GTK+2.0). Це створить графічний інтерфейс shp2pgsql-gui для shp2pgsql.
--without-rasterСкомпілюйте без підтримки растрових зображень.
--without-tigerDisables tiger geocoder support.
--without-topologyCompile without topology support.
--with-gettext=noЗа замовчуванням PostGIS спробує виявити підтримку gettext і скомпілювати з нею, однак якщо ви зіткнетеся з проблемами несумісності, які спричиняють порушення роботи завантажувача, ви можете повністю вимкнути її за допомогою цієї команди. Дивіться квиток http://trac.osgeo.org/postgis/ticket/748 для прикладу проблеми, вирішеної за допомогою цієї конфігурації. ПРИМІТКА: ви нічого не втратите, вимкнувши цю опцію. Вона використовується для підтримки міжнародної довідки/міток для завантажувача GUI, яка ще не задокументована і все ще є експериментальною.
--with-sfcgal=PATHЗа замовчуванням PostGIS не встановлюється з підтримкою sfcgal без цього параметра. PATH — це необов'язковий аргумент, який дозволяє вказати альтернативний шлях до sfcgal-config.
--without-phony-revisionВимкнути оновлення postgis_revision.h, щоб відповідати поточній версії HEAD репозиторію git.
![]() | |
Якщо ви отримали PostGIS з репозиторію коду , першим кроком є запуск скрипта ./autogen.sh Цей скрипт створить скрипт configure, який, у свою чергу, використовується для налаштування встановлення PostGIS. Якщо ви отримали PostGIS у вигляді архіву tar, запускати ./autogen.sh не потрібно, оскільки configure вже було згенеровано. |
Після створення Makefile, збірка PostGIS зводиться до виконання команди
make
Останній рядок виводу повинен бути таким: "PostGIS було успішно скомпільовано. Готово до встановлення."
Починаючи з PostGIS v1.4.0, всі функції мають коментарі, згенеровані з документації. Якщо ви бажаєте встановити ці коментарі у ваші просторові бази даних пізніше, запустіть команду, яка вимагає docbook. Файли postgis_comments.sql та інші файли коментарів пакету raster_comments.sql, topology_comments.sql також упаковані у tar.gz дистрибутив у папці doc, тому немає потреби створювати коментарі, якщо ви встановлюєте з tar-архіву. Коментарі також включені як частина інсталяції CREATE EXTENSION.
make comments
Введено в PostGIS 2.0. Ця функція створює HTML-шпаргалки, які можна використовувати для швидкого довідкового пошуку або як роздатковий матеріал для студентів. Для створення потрібно xsltproc, після чого в папці doc буде створено 4 файли: topology_cheatsheet.html, tiger_geocoder_cheatsheet.html, raster_cheatsheet.html, postgis_cheatsheet.html
Ви можете завантажити готові приклади у форматі html та pdf з Посібників з PostGIS / PostgreSQL
make cheatsheets
Розширення PostGIS створюються та встановлюються автоматично, якщо ви використовуєте PostgreSQL 9.1+.
Якщо ви компілюєте з репозиторію вихідного коду, спочатку потрібно скомпілювати описи функцій. Вони компілюються, якщо у вас встановлено docbook. Ви також можете скомпілювати їх вручну за допомогою команди:
make comments
Створювати коментарі не потрібно, якщо ви створюєте з архіву tar, оскільки вони вже попередньо вбудовані в архів tar.
Розширення повинні автоматично створюватися в рамках процесу make install. При необхідності ви можете створити їх з папок розширень або скопіювати файли, якщо вони потрібні вам на іншому сервері.
cd extensions cd postgis make clean make export PGUSER=postgres #overwrite psql variables make check #to test before install make install # to test extensions make check RUNTESTFLAGS=--extension
![]() | |
|
Файли розширення завжди будуть однаковими для однієї версії PostGIS і PostgreSQL незалежно від ОС, тому можна копіювати файли розширення з однієї ОС на іншу, якщо на ваших серверах вже встановлено бінарні файли PostGIS.
Якщо ви хочете встановити розширення вручну на окремому сервері, відмінному від вашого сервера розробки, вам потрібно скопіювати наступні файли з папки розширень у папку PostgreSQL / share / extension вашої інсталяції PostgreSQL, а також необхідні бінарні файли для звичайного PostGIS, якщо вони ще не встановлені на сервері.
Це контрольні файли, які містять таку інформацію, як версія розширення, яке потрібно встановити, якщо вона не вказана. postgis.control, postgis_topology.control.
Усі файли в папці /sql кожного розширення. Зверніть увагу, що їх потрібно скопіювати в корінь папки PostgreSQL share/extension extensions/postgis/sql/*.sql, extensions/postgis_topology/sql/*.sql
Після цього ви повинні побачити postgis, postgis_topology як доступні розширення в PgAdmin -> розширення.
Якщо ви використовуєте psql, ви можете перевірити, чи встановлені розширення, виконавши такий запит:
SELECT name, default_version,installed_version
FROM pg_available_extensions WHERE name LIKE 'postgis%' or name LIKE 'address%';
name | default_version | installed_version
------------------------------+-----------------+-------------------
address_standardizer | 3.6.3 | 3.6.3
address_standardizer_data_us | 3.6.3 | 3.6.3
postgis | 3.6.3 | 3.6.3
postgis_raster | 3.6.3 | 3.6.3
postgis_sfcgal | 3.6.3 |
postgis_tiger_geocoder | 3.6.3 | 3.6.3
postgis_topology | 3.6.3 |
(6 rows)Якщо розширення встановлено в базі даних, яку ви запитуєте, ви побачите згадку в стовпці installed_version. Якщо ви не отримали жодних записів, це означає, що на сервері взагалі не встановлено розширень postgis. PgAdmin III 1.14+ також надасть цю інформацію в розділі extensions дерева браузера бази даних і навіть дозволить оновити або видалити розширення, клацнувши правою кнопкою миші.
Якщо у вас доступні розширення, ви можете встановити розширення postgis у вибраній базі даних за допомогою інтерфейсу розширення pgAdmin або виконавши такі команди sql:
CREATE EXTENSION postgis; CREATE EXTENSION postgis_raster; CREATE EXTENSION postgis_sfcgal; CREATE EXTENSION fuzzystrmatch; --needed for postgis_tiger_geocoder --optional used by postgis_tiger_geocoder, or can be used standalone CREATE EXTENSION address_standardizer; CREATE EXTENSION address_standardizer_data_us; CREATE EXTENSION postgis_tiger_geocoder; CREATE EXTENSION postgis_topology;
У psql ви можете переглянути, які версії ви встановили, а також, в якій схемі вони встановлені.
\connect mygisdb \x \dx postgis*
List of installed extensions -[ RECORD 1 ]------------------------------------------------- Name | postgis Version | 3.6.3 Schema | public Description | PostGIS geometry, geography, and raster spat.. -[ RECORD 2 ]------------------------------------------------- Name | postgis_raster Version | 3.0.0dev Schema | public Description | PostGIS raster types and functions -[ RECORD 3 ]------------------------------------------------- Name | postgis_tiger_geocoder Version | 3.6.3 Schema | tiger Description | PostGIS tiger geocoder and reverse geocoder -[ RECORD 4 ]------------------------------------------------- Name | postgis_topology Version | 3.6.3 Schema | topology Description | PostGIS topology spatial types and functions
![]() | |
Таблиці розширення |
Якщо ви встановили 3.6.3 без використання нашої чудової системи розширень, ви можете змінити його на розширення, виконавши наведені нижче команди, щоб упакувати функції у відповідні розширення. Встановлення за допомогою `unpackaged` було видалено в PostgreSQL 13, тому перед оновленням до PostgreSQL 13 рекомендується перейти на збірку розширення.
CREATE EXTENSION postgis FROM unpackaged; CREATE EXTENSION postgis_raster FROM unpackaged; CREATE EXTENSION postgis_topology FROM unpackaged; CREATE EXTENSION postgis_tiger_geocoder FROM unpackaged;
Якщо ви бажаєте протестувати збірку PostGIS, запустіть
make check
Вищезазначена команда виконає різні перевірки та регресійні тести, використовуючи створену бібліотеку та реальну базу даних PostgreSQL.
![]() | |
Якщо ви налаштували PostGIS, використовуючи нестандартні розташування PostgreSQL, GEOS або Proj, можливо, вам доведеться додати розташування їхніх бібліотек до змінної середовища |
![]() | |
Наразі команда make check під час виконання перевірок використовує змінні середовища |
Якщо все пройде успішно, команда make check видасть результат майже 500 тестів. Результати будуть схожими на наведені нижче (багато рядків опущено):
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Розширення postgis_tiger_geocoder та address_standardizer наразі підтримують лише стандартну перевірку інсталяції PostgreSQL. Щоб перевірити їх, скористайтеся наведеним нижче кодом. Примітка: команда make install не потрібна, якщо ви вже виконали make install у кореневому каталозі коду PostGIS.
Для address_standardizer:
cd extensions/address_standardizer
make install
make installcheck
Результат повинен виглядати так:
============== dropping database "contrib_regression" ============== DROP DATABASE ============== creating database "contrib_regression" ============== CREATE DATABASE ALTER DATABASE ============== running regression test queries ============== test test-init-extensions ... ok test test-parseaddress ... ok test test-standardize_address_1 ... ok test test-standardize_address_2 ... ok ===================== All 4 tests passed. =====================
Для геокодера tiger переконайтеся, що у вашому екземплярі PostgreSQL доступні розширення postgis та fuzzystrmatch. Тести address_standardizer також запустяться, якщо ви створили postgis із підтримкою address_standardizer:
cd extensions/postgis_tiger_geocoder
make install
make installcheck
результат повинен виглядати так:
============== dropping database "contrib_regression" ============== DROP DATABASE ============== creating database "contrib_regression" ============== CREATE DATABASE ALTER DATABASE ============== installing fuzzystrmatch ============== CREATE EXTENSION ============== installing postgis ============== CREATE EXTENSION ============== installing postgis_tiger_geocoder ============== CREATE EXTENSION ============== installing address_standardizer ============== CREATE EXTENSION ============== running regression test queries ============== test test-normalize_address ... ok test test-pagc_normalize_address ... ok ===================== All 2 tests passed. =====================
Щоб встановити PostGIS, введіть
make install
Це скопіює файли інсталяції PostGIS у відповідний підкаталог, вказаний параметром конфігурації --prefix. Зокрема:
Бінарні файли завантажувача та вивантажувача встановлюються в [prefix]/bin.
Файли SQL, такі як postgis.sql, встановлюються в [prefix]/share/contrib.
Бібліотеки PostGIS встановлюються в [prefix]/lib.
Якщо ви раніше запустили команду make comments для створення файлів postgis_comments.sql та raster_comments.sql, встановіть файл sql, виконавши команду
make comments-install
![]() | |
|
Розширення address_standardizer раніше було окремим пакетом, який потрібно було завантажувати окремо. Починаючи з PostGIS 2.2, воно входить до складу пакета. Більше інформації про address_standardize, його функції та налаштування відповідно до ваших потреб дивіться у Section 12.1, “Стандартизатор адрес”.
Цей стандартизатор можна використовувати разом із розширенням PostGIS packaged tiger geocoder як заміну для Normalize_Address, про яке йшлося вище. Щоб використовувати його як заміну, зверніться до Section 2.4.2, “Використання розширення Address Standardizer з геокодером Tiger”. Ви також можете використовувати його як будівельний блок для власного геокодера або для стандартизації адрес, щоб полегшити їх порівняння.
Стандартизатор адрес використовує PCRE, який зазвичай вже встановлений на багатьох системах Nix, але ви можете завантажити останню версію за адресою: http://www.pcre.org. Якщо під час Section 2.2.3, “Конфігурація збірки” буде знайдено PCRE, розширення стандартизатора адрес буде автоматично скомпільовано. Якщо ви хочете використовувати власну версію pcre, передайте в конфігурацію --with-pcredir=/path/to/pcre, де /path/to/pcre — коренева папка для ваших каталогів pcre include та lib.
Для користувачів Windows пакет PostGIS 2.1+ вже містить address_standardizer, тому компілювати не потрібно і можна переходити безпосередньо до кроку CREATE EXTENSION.
Після встановлення ви можете підключитися до бази даних і запустити SQL:
CREATE EXTENSION address_standardizer;
Наступний тест не вимагає правил, газів або лексичних таблиць
SELECT num, street, city, state, zip
FROM parse_address('1 Devonshire Place PH301, Boston, MA 02109');Результат повинен бути таким
num | street | city | state | zip -----+------------------------+--------+-------+------- 1 | Devonshire Place PH301 | Boston | MA | 02109
Додаткові компоненти, такі як геокодер Tiger, можуть не входити до складу вашого дистрибутива PostGIS. Якщо вам бракує розширення tiger geocoder або ви хочете мати новішу версію, ніж та, що входить до вашої інсталяції, скористайтеся файлами share/extension/postgis_tiger_geocoder.* з пакетів у розділі Windows Unreleased Versions для вашої версії PostgreSQL. Хоча ці пакети призначені для Windows, файли розширення postgis_tiger_geocoder працюватимуть на будь-якій ОС, оскільки розширення є розширенням тільки для SQL/plpgsql.
Ці вказівки передбачають, що у вашій установці PostgreSQL вже встановлено розширення postgis_tiger_geocoder.
Підключіться до бази даних за допомогою psql, pgAdmin або іншого інструменту та виконайте наступні команди SQL. Зверніть увагу, що якщо ви встановлюєте програму в базу даних, яка вже має postgis, перший крок виконувати не потрібно. Якщо ви вже встановили розширення fuzzystrmatch, другий крок також виконувати не потрібно.
CREATE EXTENSION postgis; CREATE EXTENSION fuzzystrmatch; CREATE EXTENSION postgis_tiger_geocoder; --this one is optional if you want to use the rules based standardizer (pagc_normalize_address) CREATE EXTENSION address_standardizer;
Якщо ви вже встановили розширення postgis_tiger_geocoder і просто хочете оновити його до останньої версії, виконайте наступні дії:
ALTER EXTENSION postgis UPDATE; ALTER EXTENSION postgis_tiger_geocoder UPDATE;
Якщо ви зробили власні записи або змінили tiger.loader_platform та tiger.loader_variables, можливо, вам доведеться їх оновити.
Щоб переконатися, що інсталяція працює правильно, виконайте цей sql-запит у вашій базі даних:
SELECT na.address, na.streetname,na.streettypeabbrev, na.zip
FROM normalize_address('1 Devonshire Place, Boston, MA 02109') AS na;Що повинно вивести
address | streetname | streettypeabbrev | zip
---------+------------+------------------+-------
1 | Devonshire | Pl | 02109Створіть новий запис у таблиці tiger.loader_platform із шляхами до ваших виконуваних файлів та сервера.
Наприклад, щоб створити профіль під назвою debbie, який дотримується конвенції sh, потрібно зробити наступне:
INSERT INTO tiger.loader_platform(os, declare_sect, pgbin, wget, unzip_command, psql, path_sep,
loader, environ_set_command, county_process_command)
SELECT 'debbie', declare_sect, pgbin, wget, unzip_command, psql, path_sep,
loader, environ_set_command, county_process_command
FROM tiger.loader_platform
WHERE os = 'sh';А потім відредагуйте шляхи в стовпці declare_sect відповідно до шляхів, що відповідають розташуванню pg, unzip, shp2pgsql, psql тощо у Debbie.
Якщо ви не відредагуєте цю таблицю loader_platform, вона буде містити лише загальні розташування елементів, і вам доведеться редагувати скрипт після його створення.
Починаючи з PostGIS 2.4.1, крок завантаження 5-значного поштового індексу zcta5 було переглянуто, щоб завантажувати поточні дані zcta5, і він є частиною Loader_Generate_Nation_Script, коли ввімкнено. За замовчуванням він вимкнений, оскільки завантаження займає досить багато часу (від 20 до 60 хвилин), займає чимало місця на диску і використовується не так часто.
Щоб увімкнути цю функцію, виконайте такі дії:
UPDATE tiger.loader_lookuptables SET load = true WHERE table_name = 'zcta520';
Якщо присутня функція Geocode, вона може використовувати її, якщо додано фільтр меж, щоб обмежити пошук лише поштовими індексами в цих межах. Функція Reverse_Geocode використовує її, якщо у повернутій адресі відсутній поштовий індекс, що часто трапляється при зворотному геокодуванні автомагістралей.
Створіть папку з назвою gisdata в кореневому каталозі сервера або на вашому локальному комп'ютері, якщо у вас швидке підключення до сервера. У цю папку будуть завантажуватися та оброблятися файли tiger. Якщо ви не хочете, щоб папка знаходилася в кореневому каталозі сервера, або просто хочете змінити папку для тимчасового зберігання, відредагуйте поле staging_fold в таблиці tiger.loader_variables.
Створіть папку з назвою temp у папці gisdata або в будь-якому іншому місці, яке ви призначили для staging_fold. Це буде папка, куди завантажувач витягне завантажені дані tiger.
Потім запустіть функцію SQL Loader_Generate_Nation_Script, обов'язково вкажіть ім'я вашого власного профілю та скопіюйте скрипт у файл .sh або .bat. Наприклад, щоб створити націю, завантажте:
psql -c "SELECT Loader_Generate_Nation_Script('debbie')" -d geocoder -tA > /gisdata/nation_script_load.shЗапустіть скрипти командного рядка для завантаження нації, що були створені.
cd /gisdata sh nation_script_load.sh
Після завершення виконання скрипта nation у схемі tiger_data має бути три таблиці, які повинні бути заповнені даними. Перевірте це, виконавши наступні запити з psql або pgAdmin
SELECT count(*) FROM tiger_data.county_all;
count ------- 3235 (1 row)
SELECT count(*) FROM tiger_data.state_all;
count
-------
56
(1 row)
Це буде містити дані тільки в тому випадку, якщо ви позначили zcta5 для завантаження
SELECT count(*) FROM tiger_data.zcta5_all;
count ------- 33933 (1 row)
За замовчуванням таблиці, що відповідають bg, tract, tabblock20, не завантажуються. Ці таблиці не використовуються геокодером, але використовуються для статистики населення. Якщо ви хочете завантажити їх як частину завантаження даних про стан, виконайте наступну команду, щоб увімкнути їх.
UPDATE tiger.loader_lookuptables SET load = true WHERE load = false AND lookup_name IN('tract', 'bg', 'tabblock20');Або ви можете завантажити тільки ці таблиці після завантаження даних про стан за допомогою Loader_Generate_Census_Script
Для кожного стану, для якого ви хочете завантажити дані, створіть скрипт стану Loader_Generate_Script.
![]() | |
НЕ створюйте скрипт штату, поки не завантажили дані про країну, оскільки скрипт штату використовує список округів, завантажений скриптом країни. |
psql -c "SELECT Loader_Generate_Script(ARRAY['MA'], 'debbie')" -d geocoder -tA > /gisdata/ma_load.sh
Запустіть скрипти командного рядка, що були створені.
cd /gisdata sh ma_load.sh
Після завантаження всіх даних або на етапі зупинки рекомендується проаналізувати всі таблиці tiger, щоб оновити статистику (включно зі статистикою, що успадковується)
SELECT install_missing_indexes(); vacuum (analyze, verbose) tiger.addr; vacuum (analyze, verbose) tiger.edges; vacuum (analyze, verbose) tiger.faces; vacuum (analyze, verbose) tiger.featnames; vacuum (analyze, verbose) tiger.place; vacuum (analyze, verbose) tiger.cousub; vacuum (analyze, verbose) tiger.county; vacuum (analyze, verbose) tiger.state; vacuum (analyze, verbose) tiger.zcta5; vacuum (analyze, verbose) tiger.zip_lookup_base; vacuum (analyze, verbose) tiger.zip_state; vacuum (analyze, verbose) tiger.zip_state_loc;
Однією з багатьох скарг користувачів є функція нормалізації адреси Normalize_Address, яка нормалізує адресу для підготовки до геокодування. Нормалізатор далеко не ідеальний, і спроби виправити його недоліки вимагають значних ресурсів. Тому ми інтегрували інший проект, який має набагато кращий механізм стандартизації адрес. Щоб використовувати цей новий address_standardizer, скомпілюйте розширення, як описано в Section 2.3, “Встановлення та використання стандартизатора адрес”, і встановіть його як розширення у вашій базі даних.
Після встановлення цього розширення в тій самій базі даних, де встановлено postgis_tiger_geocoder, замість Normalize_Address можна використовувати Pagc_Normalize_Address. Це розширення не залежить від tiger, тому його можна використовувати з іншими джерелами даних, такими як міжнародні адреси. Розширення tiger geocoder постачається у комплекті з власними версіями rules table ( tiger.pagc_rules) , gaz table (tiger.pagc_gaz) та lex table (tiger.pagc_lex). Ви можете додавати та оновлювати їх, щоб покращити стандартизацію відповідно до власних потреб.
Процес завантаження завантажує дані з веб-сайту перепису населення для відповідних файлів країн, запитуваних штатів, витягує файли, а потім завантажує кожен штат у свій окремий набір таблиць штатів. Кожна таблиця штату успадковує таблиці, визначені в схемі tiger, так що достатньо просто зробити запит до цих таблиць, щоб отримати доступ до всіх даних, і видалити набір таблиць штатів у будь-який час за допомогою Drop_State_Tables_Generate_Script, якщо вам потрібно перезавантажити штат або він вам більше не потрібен.
Для завантаження даних вам знадобляться такі інструменти:
Інструмент для розпакування zip-файлів з веб-сайту перепису населення.
Для систем типу Unix: unzip виконуваний файл, який зазвичай вже встановлений на більшості платформ типу Unix.
Для Windows можна завантажити безкоштовну програму для стиснення/розпакування файлів 7-zip за посиланням http://www.7-zip.org/
Командний рядок shp2pgsql, який встановлюється за замовчуванням під час інсталяції PostGIS.
wget — це інструмент для завантаження веб-сторінок, який зазвичай встановлюється на більшості систем Unix/Linux.
Якщо ви використовуєте Windows, ви можете завантажити попередньо скомпільовані бінарні файли з http://gnuwin32.sourceforge.net/packages/wget.htm
Якщо ви оновлюєте систему з tiger_2010, спочатку потрібно створити та запустити Drop_Nation_Tables_Generate_Script. Перед завантаженням будь-яких даних про стан, потрібно завантажити загальнонаціональні дані за допомогою Loader_Generate_Nation_Script. Це створить для вас скрипт завантажувача. Loader_Generate_Nation_Script — це одноразовий крок, який потрібно виконати для оновлення (з даних перепису тигрів за попередній рік) та для нових інсталяцій.
Щоб завантажити дані про стан, зверніться до Loader_Generate_Script, щоб створити скрипт завантаження даних для вашої платформи для потрібних вам станів. Зверніть увагу, що ви можете встановлювати їх по частинах. Не обов'язково завантажувати всі потрібні стани одночасно. Ви можете завантажувати їх у міру необхідності.
Після завантаження потрібних штатів обов'язково виконайте команду:
SELECT install_missing_indexes();
відповідно до опису в Install_Missing_Indexes.
Щоб перевірити, чи все працює як слід, спробуйте виконати геокодування адреси у вашому штаті, використовуючи Geocode
Спочатку оновіть розширення postgis_tiger_geocoder наступним чином:
ALTER EXTENSION postgis_tiger_geocoder UPDATE;
Далі видаліть усі таблиці країн і завантажте нові. Створіть скрипт видалення за допомогою цього SQL-запиту, як описано в Drop_Nation_Tables_Generate_Script
SELECT drop_nation_tables_generate_script();
Виконайте згенеровані оператори SQL для створення таблиць.
Створіть скрипт завантаження нації за допомогою цієї команди SELECT, як описано в Loader_Generate_Nation_Script
Для windows
SELECT loader_generate_nation_script('windows'); Для Unix/Linux
SELECT loader_generate_nation_script('sh');Інструкції щодо запуску скрипту генерації див. у Section 2.4.1, “Tiger Geocoder Увімкнення бази даних PostGIS”. Це потрібно зробити лише один раз.
![]() | |
Ви можете мати комбінацію таблиць стану за різні роки та оновлювати кожен стан окремо. Перед оновленням стану спочатку потрібно видалити таблиці стану за попередній рік для цього стану за допомогою Drop_State_Tables_Generate_Script. |
Якщо установка або оновлення не відбуваються так, як ви очікували, слід перевірити кілька речей.
Переконайтеся, що ви встановили PostgreSQL 12 або новішу версію, і що ви компілюєте з тією ж версією вихідного коду PostgreSQL, що і версія PostgreSQL, яка працює. Плутанина може виникнути, якщо у вашому дистрибутиві (Linux) вже встановлено PostgreSQL або ви раніше встановлювали PostgreSQL і забули про це. PostGIS працюватиме лише з PostgreSQL 12 або новішою версією, а використання старішої версії призведе до появи дивних, несподіваних повідомлень про помилки. Щоб перевірити версію PostgreSQL, що працює, під’єднайтеся до бази даних за допомогою psql і виконайте цей запит:
SELECT version();
Якщо ви використовуєте дистрибутив на основі RPM, ви можете перевірити наявність попередньо встановлених пакетів за допомогою команди rpm наступним чином: rpm -qa | grep postgresql
Якщо оновлення не вдалося, переконайтеся, що ви відновлюєте дані в базу, в якій вже встановлено PostGIS.
SELECT postgis_full_version();
Також перевірте, чи конфігуратор правильно визначив розташування та версію PostgreSQL, бібліотеки Proj та бібліотеки GEOS.
Вихідні дані команди configure використовуються для створення файлу postgis_config.h. Перевірте, чи правильно встановлено змінні POSTGIS_PGSQL_VERSION, POSTGIS_PROJ_VERSION та POSTGIS_GEOS_VERSION.
Налаштування продуктивності PostGIS дуже схоже на налаштування будь-якого робочого навантаження PostgreSQL. Єдиним додатковим моментом, який слід врахувати, є те, що геометрії та растри зазвичай мають великий розмір, тому оптимізації, пов'язані з пам'яттю, зазвичай мають більший вплив на PostGIS, ніж на інші типи запитів PostgreSQL.
Загальні відомості про оптимізацію PostgreSQL див. у розділі Налаштування сервера PostgreSQL.
У PostgreSQL версії 9.4 і вище конфігурацію можна встановити на рівні сервера без редагування файлів postgresql.conf або postgresql.auto.conf за допомогою команди ALTER SYSTEM.
ALTER SYSTEM SET work_mem = '256MB'; -- this forces non-startup configs to take effect for new connections SELECT pg_reload_conf(); -- show current setting value -- use SHOW ALL to see all settings SHOW work_mem;
Окрім налаштувань Postgres, PostGIS має деякі власні налаштування, які перелічені в Section 7.22, “Великі уніфіковані змінні (GUC)”.
Ці налаштування конфігуруються в postgresql.conf:
За замовчуванням: partition
Зазвичай використовується для розділення таблиць. За замовчуванням встановлено значення "partition", яке ідеально підходить для PostgreSQL 8.4 і вище, оскільки змушує планувальник аналізувати таблиці на предмет обмежень тільки в тому випадку, якщо вони знаходяться в успадкованій ієрархії, і не застосовувати штрафні санкції до планувальника в інших випадках.
За замовчуванням: ~128 МБ у PostgreSQL 9.6
Встановіть приблизно 25% до 40% доступної оперативної пам'яті. У Windows ви не зможете встановити таке високе значення.
max_worker_processes Цей параметр доступний тільки для PostgreSQL 9.4+. Для PostgreSQL 9.6+ це налаштування має додаткове значення, оскільки воно контролює максимальну кількість процесів, які можна використовувати для паралельних запитів.
За замовчуванням: 8
Встановлює максимальну кількість фонових процесів, які може підтримувати система. Цей параметр можна встановити тільки під час запуску сервера.
work_mem - встановлює розмір пам'яті, що використовується для операцій сортування та складних запитів
За замовчуванням: 1-4 МБ
Налаштуйте для великих баз даних, складних запитів, великого обсягу оперативної пам'яті
Зменште налаштування для великої кількості одночасних користувачів або малої оперативної пам'яті.
Якщо у вас багато оперативної пам'яті і мало розробників:
SET work_mem TO '256MB';
maintenance_work_mem - розмір пам'яті, що використовується для VACUUM, CREATE INDEX тощо.
За замовчуванням: 16-64 МБ
Зазвичай занадто низький - блокує введення-виведення, блокує об'єкти під час обміну пам'яттю
Рекомендуємо від 32 МБ до 1 ГБ на виробничих серверах з великим об'ємом оперативної пам'яті, але це залежить від кількості одночасних користувачів. Якщо у вас багато оперативної пам'яті і мало розробників:
SET maintenance_work_mem TO '1GB';
max_parallel_workers_per_gather
Це налаштування доступне лише у PostgreSQL версії 9.6 і вище та впливає лише на PostGIS 2.3 і новіші версії, оскільки тільки PostGIS 2.3 і вище підтримує паралельні запити. Якщо встановити значення більше за 0, деякі запити, наприклад ті, що використовують реляційні функції, як-от ST_Intersects, можуть виконуватись із використанням кількох процесів і працювати більш ніж удвічі швидше. Якщо у вас багато вільних процесорів, варто встановити це значення рівним кількості наявних процесорів. Також переконайтеся, що параметр max_worker_processes встановлений принаймні на таке саме значення.
За замовчуванням: 0
Встановлює максимальну кількість воркерів, які може запустити один вузол Gather. Паралельні воркери беруться з пулу процесів, створеного параметром max_worker_processes. Зауважте, що запитувана кількість воркерів може бути недоступною під час виконання. Якщо це станеться, план виконання буде працювати з меншою кількістю воркерів, ніж очікувалося, що може призвести до неефективності. Встановлення цього значення в 0, що є значенням за замовчуванням, вимикає виконання паралельних запитів.
Якщо ви увімкнули підтримку растрів, ви можете прочитати нижче, як правильно її налаштувати.
Починаючи з версії PostGIS 2.1.3, растри поза базою даних та всі растрові драйвери стандартно вимкнено. Для того, щоб їх увімкнути, вам потрібно встановити наступні змінні оточення POSTGIS_GDAL_ENABLED_DRIVERS та POSTGIS_ENABLE_OUTDB_RASTERS у серверному середовищі. Для PostGIS 2.2 ви можете скористатися більш кросплатформним підходом, встановивши відповідні Section 7.22, “Великі уніфіковані змінні (GUC)”.
Якщо ви хочете увімкнути офлайн-растр:
POSTGIS_ENABLE_OUTDB_RASTERS=1
Будь-який інший параметр або відсутність параметра взагалі вимкне растри з db.
Щоб увімкнути всі драйвери GDAL, доступні у вашому встановленні GDAL, встановіть цю змінну оточення наступним чином
POSTGIS_GDAL_ENABLED_DRIVERS=ENABLE_ALL
Якщо ви хочете увімкнути лише певні драйвери, налаштуйте змінну оточення наступним чином:
POSTGIS_GDAL_ENABLED_DRIVERS="GTiff PNG JPEG GIF XYZ"
![]() | |
Якщо ви використовуєте Windows не беріть перелік драйверів в лапки |
Налаштування змінних оточення залежить від операційної системи. Для PostgreSQL, встановленого на Ubuntu або Debian за допомогою apt-postgresql, найкращим способом є редагування /etc/postgresql/, де 10 позначає версію PostgreSQL, а main — кластер.10/main/environment
У Windows, якщо ви запускаєте службу, ви можете встановити системні змінні, до яких у Windows 7 можна потрапити, клацнувши правою кнопкою миші на Компʼютер - Властивості - Додаткові параметри системи або в провіднику перейшовши до Панель керування\Всі елементи панелі керування\Система. Потім натисніть Додаткові системні налаштування ->Додаткові ->Змінні середовища і додайте нові системні змінні.
Після того, як ви встановите змінні оточення, вам потрібно буде перезапустити службу PostgreSQL, щоб зміни набули чинності.
Якщо ви використовуєте PostgreSQL 9.1+ і скомпілювали та встановили модулі extensions/postgis, ви можете перетворити базу даних на просторову за допомогою механізму EXTENSION.
Основне розширення PostGIS включає геометрію, географію, spatial_ref_sys та всі функції і коментарі. Растр і топологія упаковані як окреме розширення.
Виконайте наступний фрагмент SQL-коду в базі даних, яку ви хочете активувати просторове розширення:
CREATE EXTENSION IF NOT EXISTS plpgsql;
CREATE EXTENSION postgis;
CREATE EXTENSION postgis_raster; -- OPTIONAL
CREATE EXTENSION postgis_topology; -- OPTIONAL
![]() | |
Зазвичай це потрібно лише в тому випадку, якщо ви не можете або не хочете встановлювати PostGIS у каталозі розширень PostgreSQL (наприклад, під час тестування, розробки або в обмеженому середовищі). |
Додавання об'єктів PostGIS та визначень функцій до вашої бази даних здійснюється шляхом завантаження різних файлів sql, розташованих у [prefix]/share/contrib, як зазначено під час фази побудови.
Основні об'єкти PostGIS (типи геометрії та географії, а також функції їх підтримки) містяться у скрипті postgis.sql. Растрові об'єкти містяться у скрипті rtpostgis.sql. Топологічні об'єкти містяться у скрипті topology.sql.
Для отримання повного набору ідентифікаторів визначення системи координат EPSG ви також можете завантажити файл визначень spatial_ref_sys.sql і заповнити таблицю spatial_ref_sys. Це дозволить вам виконувати операції ST_Transform() над геометріями.
Якщо ви бажаєте додати коментарі до функцій PostGIS, ви можете знайти їх у скрипті postgis_comments.sql. Коментарі можна переглянути, просто ввівши \dd [function_name] у вікні терміналу psql.
Виконайте наступні команди Shell у терміналі:
DB=[yourdatabase]
SCRIPTSDIR=`pg_config --sharedir`/contrib/postgis-3.5/
# 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
Оновлення існуючих просторових баз даних може бути складним, оскільки вимагає заміни або впровадження нових визначень об'єктів PostGIS.
На жаль, не всі визначення можна легко замінити в активній базі даних, тому іноді найкращим варіантом є процес дампа/перезавантаження.
PostGIS надає процедуру SOFT UPGRADE для незначних випусків або випусків з виправленням помилок, а також процедуру HARD UPGRADE для основних випусків.
Перед тим, як спробувати оновити PostGIS, завжди варто зробити резервну копію ваших даних. Якщо ви використовуєте прапор -Fc для pg_dump, ви завжди зможете відновити дамп за допомогою HARD UPGRADE.
Якщо ви встановили базу даних за допомогою розширень, вам також потрібно буде оновити її за допомогою моделі розширень. Якщо ви встановили базу даних за допомогою старого скрипту sql, рекомендуємо перейти на розширення, оскільки скрипт більше не підтримується.
Якщо ви спочатку встановили PostGIS з розширеннями, то вам потрібно також оновити розширення. Незначне оновлення з розширеннями є досить простим.
Якщо ви використовуєте PostGIS 3 або вище, то вам слід скористатися функцією PostGIS_Extensions_Upgrade, щоб оновити систему до останньої версії, яку ви встановили.
SELECT postgis_extensions_upgrade();
Якщо ви використовуєте PostGIS 2.5 або нижчу версію, виконайте наступні дії:
ALTER EXTENSION postgis UPDATE; SELECT postgis_extensions_upgrade(); -- This second call is needed to rebundle postgis_raster extension SELECT postgis_extensions_upgrade();
Якщо у вас встановлено кілька версій PostGIS і ви не хочете оновлювати їх до останньої версії, ви можете явно вказати версію наступним чином:
ALTER EXTENSION postgis UPDATE TO "3.6.3"; ALTER EXTENSION postgis_topology UPDATE TO "3.6.3";
Якщо ви отримаєте повідомлення про помилку, схоже на таке:
No migration path defined for … to 3.6.3
Потім вам потрібно буде створити резервну копію вашої бази даних, створити нову, як описано в Section 3.3.1, “Активувати просторове розширення в базі данних за допомогою EXTENSION”, а потім відновити резервну копію на цій новій базі даних.
Якщо ви отримаєте таке повідомлення:
Version "3.6.3" of extension "postgis" is already installed
Тоді все вже оновлено і ви можете сміливо ігнорувати це. ЗА ВИНЯТКОМ випадків, коли ви намагаєтеся оновити версію з розробницької до наступної (яка не отримує нового номера версії); в цьому випадку ви можете додати "next" до рядка версії, а наступного разу вам потрібно буде знову видалити суфікс "next":
ALTER EXTENSION postgis UPDATE TO "3.6.3next"; ALTER EXTENSION postgis_topology UPDATE TO "3.6.3next";
![]() | |
Якщо ви спочатку встановили PostGIS без вказання версії, то часто можна пропустити перевстановлення розширення postgis перед відновленням, оскільки резервна копія містить лише |
![]() | |
Якщо ви оновлюєте розширення PostGIS з версії до 3.0.0, у вас з’явиться нове розширення postgis_raster, яке можна безпечно видалити, якщо вам не потрібна підтримка растрових даних. Видалити його можна так: DROP EXTENSION postgis_raster; |
Цей розділ стосується лише тих, хто встановив PostGIS без використання розширень. Якщо у вас є розширення і ви спробуєте оновити систему за допомогою цього підходу, ви отримаєте такі повідомлення:
can't drop … because postgis extension depends on it
ПРИМІТКА: якщо ви переходите з PostGIS 1.* на PostGIS 2.* або з PostGIS 2.* до версії r7409, ви не можете використовувати цю процедуру, а повинні виконати ЖОРСТКЕ ОНОВЛЕННЯ.
Після компіляції та встановлення (make install) ви повинні знайти набір файлів *_upgrade.sql в папках інсталяції. Ви можете перелічити їх усі за допомогою:
ls `pg_config --sharedir`/contrib/postgis-3.6.3/*_upgrade.sql
Завантажте їх по черзі, починаючи з postgis_upgrade.sql.
psql -f postgis_upgrade.sql -d your_spatial_database
Така сама процедура застосовується до розширень raster, topology та sfcgal, з файлами оновлення, що мають назви rtpostgis_upgrade.sql, topology_upgrade.sql та sfcgal_upgrade.sql відповідно. Якщо вони вам потрібні:
psql -f rtpostgis_upgrade.sql -d your_spatial_database
psql -f topology_upgrade.sql -d your_spatial_database
psql -f sfcgal_upgrade.sql -d your_spatial_database
Рекомендується перейти на інсталяцію на основі розширення, виконавши команду
psql -c "SELECT postgis_extensions_upgrade();"
![]() | |
Якщо ви не можете знайти файл |
Функція PostGIS_Full_Version повинна повідомити вас про необхідність виконання такого оновлення за допомогою повідомлення "procs need upgrade" (процедури потребують оновлення).
Під HARD UPGRADE ми маємо на увазі повне скидання/перезавантаження баз даних з підтримкою PostGIS. HARD UPGRADE необхідний, коли змінюється внутрішнє зберігання об'єктів PostGIS або коли SOFT UPGRADE неможливий. У додатку Release Notes для кожної версії вказано, чи потрібно для оновлення виконувати скидання/перезавантаження (HARD UPGRADE).
Процес вивантаження/перезавантаження здійснюється за допомогою скрипта postgis_restore, який пропускає з вивантаження всіх визначень, що належать до PostGIS (включаючи старі), що дозволяє відновити схеми та дані в базі даних з встановленим PostGIS без помилок дублювання символів або перенесення застарілих об'єктів.
Додаткові інструкції для користувачів Windows доступні за посиланням Windows Hard upgrade.
Процедура виглядає наступним чином:
Створіть дамп бази даних, яку ви хочете оновити, у "власному форматі" (назвемо його olddb), включіть бінарні блоки (-b) та детальний вивід (-v). Користувач може бути власником бази даних, не обов'язково мати супер-акаунт postgres.
pg_dump -h localhost -p 5432 -U postgres -Fc -b -v -f "/somepath/olddb.backup" olddb
Виконайте нову інсталяцію PostGIS у новій базі даних — ми будемо називати цю базу даних newdb. Інструкції щодо виконання цієї операції див. у розділах Section 3.3.2, “Активувати просторове розширення бази даних без використання EXTENSION (не рекомендується)” та Section 3.3.1, “Активувати просторове розширення в базі данних за допомогою EXTENSION”.
Записи spatial_ref_sys, знайдені у вашому дампі, будуть відновлені, але вони не замінять існуючі записи в spatial_ref_sys. Це зроблено для того, щоб виправлення в офіційному наборі були правильно передані до відновлених баз даних. Якщо з якоїсь причини ви дійсно хочете замінити стандартні записи своїми власними, просто не завантажуйте файл spatial_ref_sys.sql під час створення нової бази даних.
Якщо ваша база даних дуже стара або ви знаєте, що використовуєте давно застарілі функції у своїх представлень та функціях, можливо, вам доведеться завантажити legacy.sql, щоб усі ваші функції, представлень тощо знову працювали належним чином. Робіть це лише у разі _реальної_ необхідності. Якщо можливо, замість цього розгляньте можливість оновлення своїх представлень та функцій перед вивантаженням. Застарілі функції можна пізніше видалити, завантаживши uninstall_legacy.sql.
Відновіть резервну копію у новій базі даних newdb за допомогою postgis_restore. Несподівані помилки, якщо такі будуть, будуть виведені psql у стандартний потік помилок. Зберігайте їх у журналі.
postgis_restore "/somepath/olddb.backup" | psql -h localhost -p 5432 -U postgres newdb 2> errors.txt
Помилки можуть виникати в таких випадках:
Деякі з ваших представлень або функцій використовують застарілі об'єкти PostGIS. Щоб виправити це, ви можете спробувати завантажити скрипт legacy.sql перед відновленням або вам доведеться відновити версію PostGIS, яка все ще містить ці об'єкти, і спробувати міграцію знову після перенесення вашого коду. Якщо спосіб legacy.sql працює для вас, не забудьте виправити свій код, щоб припинити використання застарілих функцій, і видалити їх, завантаживши uninstall_legacy.sql.
Деякі користувацькі записи spatial_ref_sys у файлі дампа мають недійсне значення SRID. Дійсні значення SRID більші за 0 і менші за 999000. Значення в діапазоні 999000.999999 зарезервовані для внутрішнього використання, а значення > 999999 не можуть використовуватися взагалі. Усі ваші користувацькі записи з недійсними SRID будуть збережені, а ті, що > 999999, будуть переміщені в зарезервований діапазон, але таблиця spatial_ref_sys втратить обмеження перевірки, що захищає цю інваріантність, а також, можливо, і свій первинний ключ (коли кілька недійсних SRID перетворюються на одне й те саме зарезервоване значення SRID).
Щоб виправити цю ситуацію, слід скопіювати власний SRS до SRID із дійсним значенням (можливо, в діапазоні 910000..910999), перетворити всі таблиці на новий srid (див. UpdateGeometrySRID), видалити недійсний запис із spatial_ref_sys і повторно створити перевірку (перевірки) за допомогою:
ALTER TABLE spatial_ref_sys ADD CONSTRAINT spatial_ref_sys_srid_check check (srid > 0 AND srid < 999000 );
ALTER TABLE spatial_ref_sys ADD PRIMARY KEY(srid));
Якщо ви оновлюєте стару базу даних, що містить французьку IGN картографію, у вас, ймовірно, будуть SRID поза діапазоном, і під час імпортування бази даних ви побачите такі проблеми:
WARNING: SRID 310642222 converted to 999175 (in reserved zone)
У цьому випадку ви можете спробувати виконати наступні кроки: спочатку повністю видаліть IGN із sql, що є результатом postgis_restore. Отже, після виконання:
postgis_restore "/somepath/olddb.backup" > olddb.sql
виконайте цю команду:
grep -v IGNF olddb.sql > olddb-without-IGN.sql
Створіть нову базу даних newdb, активуйте необхідні розширення Postgis і правильно вставте французьку систему IGN за допомогою: цього скрипту Після цих операцій імпортуйте свої дані:
psql -h localhost -p 5432 -U postgres -d newdb -f olddb-without-IGN.sql 2> errors.txt
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.
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 Section 4.5, “Spatial Reference Systems”.
The geometry dimension is a property of geometry types. Point types have dimension 0, linear types have dimension 1, and polygonal types have dimension 2. 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 Section 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.
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 the 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 Section 4.4, “Geometry Validation”
A Point is a 0-dimensional geometry that represents a single location in coordinate space.
POINT (1 2) POINT Z (1 2 3) POINT ZM (1 2 3 4)
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.
LINESTRING (1 2, 3 4, 5 6)
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.
LINEARRING (0 0 0, 4 0 0, 4 4 0, 0 4 0, 0 0 0)
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.
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))
A MultiPoint is a collection of Points.
MULTIPOINT ( (0 0), (1 2) )
A MultiLineString is a collection of LineStrings. A MultiLineString is closed if each of its elements is closed.
MULTILINESTRING ( (0 0,1 1,1 2), (2 3,3 2,5 4) )
A MultiPolygon is a collection of non-overlapping, non-adjacent Polygons. Polygons in the collection may touch only at a finite number of points.
MULTIPOLYGON (((1 5, 5 5, 5 1, 1 1, 1 5)), ((6 5, 9 1, 6 1, 6 5)))
A GeometryCollection is a heterogeneous (mixed) collection of geometries.
GEOMETRYCOLLECTION ( POINT(2 3), LINESTRING(2 3, 3 4))
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.
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)) )
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.
TRIANGLE ((0 0, 0 9, 9 0, 0 0))
A TIN is a collection of non-overlapping Triangles representing a Triangulated Irregular Network.
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)) )
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.
![]() | |
All floating point comparisons within the SQL-MM implementation are performed to a specified tolerance, currently 1E-8. |
CircularString is the basic curve type, similar to a LineString in the linear world. A single arc segment is specified by three points: the start and end points (first and third) and some other point on the arc. To specify a closed circle the start and end points are the same and the middle point is the opposite point on the circle diameter (which is the center of the arc). In a sequence of arcs the end point of the previous arc is the start point of the next arc, just like the segments of a LineString. This means that a CircularString must have an odd number of points greater than 1.
CIRCULARSTRING(0 0, 1 1, 1 0) CIRCULARSTRING(0 0, 4 0, 4 4, 0 4, 0 0)
A CompoundCurve is a single continuous curve that may contain both circular arc segments and linear segments. That means that in addition to having well-formed components, the end point of every component (except the last) must be coincident with the start point of the following component.
COMPOUNDCURVE( CIRCULARSTRING(0 0, 1 1, 1 0),(1 0, 0 1))
A CurvePolygon is like a polygon, with an outer ring and zero or more inner rings. The difference is that a ring can be a CircularString or CompoundCurve as well as a LineString.
As of PostGIS 1.4 PostGIS supports compound curves in a curve polygon.
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
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) )A MultiCurve is a collection of curves which can include LineStrings, CircularStrings or CompoundCurves.
MULTICURVE( (0 0, 5 5), CIRCULARSTRING(4 0, 4 4, 8 4))
A MultiSurface is a collection of surfaces, which can be (linear) Polygons or CurvePolygons.
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)))The OGC SFA specification defines two formats for representing geometry values for external use: Well-Known Text (WKT) and Well-Known Binary (WKB). Both WKT and WKB include information about the type of the object and the coordinates which define it.
Well-Known Text (WKT) provides a standard textual representation of spatial data. Examples of WKT representations of spatial objects are:
POINT(0 0)
POINT Z (0 0 0)
POINT ZM (0 0 0 0)
POINT EMPTY
LINESTRING(0 0,1 1,1 2)
LINESTRING EMPTY
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 Z ((0 0 0),(1 2 3))
MULTIPOINT EMPTY
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 EMPTY
Input and output of WKT is provided by the functions ST_AsText and ST_GeomFromText:
text WKT = ST_AsText(geometry); geometry = ST_GeomFromText(text WKT, SRID);
For example, a statement to create and insert a spatial object from WKT and a SRID is:
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:
WKT: POINT(1 1)
WKB: 0101000000000000000000F03F000000000000F03
WKT: LINESTRING (2 2, 9 9)
WKB: 0102000000020000000000000000000040000000000000004000000000000022400000000000002240
Input and output of WKB is provided by the functions ST_AsBinary and ST_GeomFromWKB:
bytea WKB = ST_AsBinary(geometry); geometry = ST_GeomFromWKB(bytea WKB, SRID);
For example, a statement to create and insert a spatial object from WKB is:
INSERT INTO geotable ( geom, name )
VALUES ( ST_GeomFromWKB('\x0101000000000000000000f03f000000000000f03f', 312), 'A Place');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 compute 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 Chapter 7, Довідка PostGIS 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". |
The SFA standard specifies that spatial objects include a Spatial Reference System identifier (SRID). The SRID is required when creating spatial objects for insertion into the database (it may be defaulted to 0). See ST_SRID and Section 4.5, “Spatial Reference Systems”
To make querying geometry efficient PostGIS defines various kinds of spatial indexes, and spatial operators to use them. See Section 4.9, “Spatial Indexes” and Section 5.2, “Using Spatial Indexes” for details.
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:
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:
OGC: POINT Z (1 2 3)
EWKT: POINT (1 2 3)
For 3DM geometries the M qualifier is included:
OGC: POINT M (1 2 3)
EWKT: POINTM (1 2 3)
For 4D geometries the ZM qualifier is omitted:
OGC: POINT ZM (1 2 3 4)
EWKT: POINT (1 2 3 4)
EWKT avoids over-specifying dimensionality and the inconsistencies that can occur with the OGC/ISO format, such as:
POINT ZM (1 1)
POINT ZM (1 1 1)
POINT (1 1 1 1)
![]() | |
PostGIS extended formats are currently a superset of the OGC ones, so that every valid OGC WKB/WKT is also valid EWKB/EWKT. However, this might vary in the future, if the OGC extends a format in a way that conflicts with the PosGIS definition. Thus you SHOULD NOT rely on this compatibility! |
Examples of the EWKT text representation of spatial objects are:
POINT(0 0 0) -- XYZ
SRID=32632;POINT(0 0) -- XY with SRID
POINTM(0 0 0) -- XYM
POINT(0 0 0 0) -- XYZM
SRID=4326;MULTIPOINTM(0 0 0,1 2 1) -- XYM with SRID
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 10, 10 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)) )
Input and output using these formats is available using the following functions:
bytea EWKB = ST_AsEWKB(geometry); text EWKT = ST_AsEWKT(geometry); geometry = ST_GeomFromEWKB(bytea EWKB); geometry = ST_GeomFromEWKT(text EWKT);
For example, a statement to create and insert a PostGIS spatial object using EWKT is:
INSERT INTO geotable ( geom, name )
VALUES ( ST_GeomFromEWKT('SRID=312;POINTM(-126.4 45.32 15)'), 'A Place' )The PostGIS geography data type provides native support for spatial features represented on "geographic" coordinates (sometimes called "geodetic" coordinates, or "lat/lon", or "lon/lat"). Geographic coordinates are spherical coordinates expressed in angular units (degrees).
The basis for the PostGIS geometry data type is a plane. The shortest path between two points on the plane is a straight line. That means functions on geometries (areas, distances, lengths, intersections, etc) are calculated using straight line vectors and cartesian mathematics. This makes them simpler to implement and faster to execute, but also makes them inaccurate for data on the spheroidal surface of the earth.
The PostGIS geography data type is based on a spherical model. The shortest path between two points on the sphere is a great circle arc. Functions on geographies (areas, distances, lengths, intersections, etc) are calculated using arcs on the sphere. By taking the spheroidal shape of the world into account, the functions provide more accurate results.
Because the underlying mathematics is more complicated, there are fewer functions defined for the geography type than for the geometry type. Over time, as new algorithms are added the capabilities of the geography type will expand. As a workaround one can convert back and forth between geometry and geography types.
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. (Prior to PostGIS 2.2, the geography type supported only WGS 84 geodetic (SRID:4326)). You can add your own custom geodetic spatial reference system as described in Section 4.5.2, “User-Defined Spatial Reference Systems”.
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.
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):
CREATE TABLE global_points (
id SERIAL PRIMARY KEY,
name VARCHAR(64),
location geography(POINT,4326)
);The geography type supports two optional type modifiers:
the spatial type modifier restricts the kind of shapes and dimensions allowed in the column. Values allowed for the spatial type are: POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING, MULTIPOLYGON, GEOMETRYCOLLECTION. The geography type does not support curves, TINS, or POLYHEDRALSURFACEs. The modifier supports coordinate dimensionality restrictions by adding suffixes: Z, M and ZM. For example, a modifier of 'LINESTRINGM' only allows linestrings with three dimensions, and treats the third dimension as a measure. Similarly, 'POINTZM' requires four dimensional (XYZM) data.
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:
Create a table with 2D POINT geography with the default SRID 4326 (WGS84 long/lat):
CREATE TABLE ptgeogwgs(gid serial PRIMARY KEY, geog geography(POINT) );
Create a table with 2D POINT geography in NAD83 longlat:
CREATE TABLE ptgeognad83(gid serial PRIMARY KEY, geog geography(POINT,4269) );
Create a table with 3D (XYZ) POINTs and an explicit SRID of 4326:
CREATE TABLE ptzgeogwgs84(gid serial PRIMARY KEY, geog geography(POINTZ,4326) );
Create a table with 2D LINESTRING geography with the default SRID 4326:
CREATE TABLE lgeog(gid serial PRIMARY KEY, geog geography(LINESTRING) );
Create a table with 2D POLYGON geography with the SRID 4267 (NAD 1927 long lat):
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:
SELECT * FROM geography_columns;
Creating a spatial index works the same as for geometry columns. PostGIS will note that the column type is GEOGRAPHY and create an appropriate sphere-based index instead of the usual planar index used for GEOMETRY.
-- Index the test table with a spherical index CREATE INDEX global_points_gix ON global_points USING GIST ( location );
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.
-- Add some data into the test table
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.
-- NAD 83 lon/lat
SELECT 'SRID=4269;POINT(-123 34)'::geography;
geography
----------------------------------------------------
0101000020AD1000000000000000C05EC00000000000004140
-- NAD27 lon/lat
SELECT 'SRID=4267;POINT(-123 34)'::geography;
geography
----------------------------------------------------
0101000020AB1000000000000000C05EC00000000000004140
-- NAD83 UTM zone meters - gives an error since it is a meter-based planar projection SELECT 'SRID=26910;POINT(-123 34)'::geography; ERROR: Only lon/lat coordinate systems are supported in geography.
Query and measurement functions use units of meters. So distance parameters should be expressed in meters, and return values should be expected in meters (or square meters for areas).
-- A distance query using a 1000km tolerance SELECT name FROM global_points WHERE ST_DWithin(location, 'SRID=4326;POINT(-110 29)'::geography, 1000000);
You can see the power of geography in action by calculating how close a plane flying a great circle route from Seattle to London (LINESTRING(-122.33 47.606, 0.0 51.5)) comes to Reykjavik (POINT(-21.96 64.15)) (map the route).
The geography type calculates the true shortest distance of 122.235 km over the sphere between Reykjavik and the great circle flight path between Seattle and London.
-- Distance calculation using GEOGRAPHY
SELECT ST_Distance('LINESTRING(-122.33 47.606, 0.0 51.5)'::geography, 'POINT(-21.96 64.15)'::geography);
st_distance
-----------------
122235.23815667The geometry type calculates a meaningless cartesian distance between Reykjavik and the straight line path from Seattle to London plotted on a flat map of the world. The nominal units of the result is "degrees", but the result doesn't correspond to any true angular difference between the points, so even calling them "degrees" is inaccurate.
-- Distance calculation using GEOMETRY
SELECT ST_Distance('LINESTRING(-122.33 47.606, 0.0 51.5)'::geometry, 'POINT(-21.96 64.15)'::geometry);
st_distance
--------------------
13.342271221453624
The geography data type allows you to store data in longitude/latitude coordinates, but at a cost: there are fewer functions defined on GEOGRAPHY than there are on GEOMETRY; those functions that are defined take more CPU time to execute.
The data type you choose should be determined by the expected working area of the application you are building. Will your data span the globe or a large continental area, or is it local to a state, county or municipality?
If your data is contained in a small area, you might find that choosing an appropriate projection and using GEOMETRY is the best solution, in terms of performance and functionality available.
If your data is global or covers a continental region, you may find that GEOGRAPHY allows you to build a system without having to worry about projection details. You store your data in longitude/latitude, and use the functions that have been defined on GEOGRAPHY.
If you don't understand projections, and you don't want to learn about them, and you're prepared to accept the limitations in functionality available in GEOGRAPHY, then it might be easier for you to use GEOGRAPHY than GEOMETRY. Simply load your data up as longitude/latitude and go from there.
Refer to Section 13.11, “Матриця підтримки функцій PostGIS” for compare between what is supported for Geography vs. Geometry. For a brief listing and description of Geography functions, refer to Section 13.4, “Функції підтримки географії PostGIS”
4.3.4.1. | Do you calculate on the sphere or the spheroid? |
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 will 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. All the geography functions have the option of using a sphere calculation, by setting a final boolean parameter to 'FALSE'. This will somewhat speed up calculations, particularly for cases where the geometries are very simple. | |
4.3.4.2. | What about the date-line and the poles? |
All the calculations have no conception of date-line or poles, the coordinates are spherical (longitude/latitude) so a shape that crosses the dateline is, from a calculation point of view, no different from any other shape. | |
4.3.4.3. | What is the longest arc you can process? |
We use great circle arcs as the "interpolation line" between two points. That means any two points are actually joined up two ways, depending on which direction you travel along the great circle. All our code assumes that the points are joined by the *shorter* of the two paths along the great circle. As a consequence, shapes that have arcs of more than 180 degrees will not be correctly modelled. | |
4.3.4.4. | Why is it so slow to calculate the area of Europe / Russia / insert big geographic region here ? |
Because the polygon is so darned huge! Big areas are bad for two reasons: their bounds are huge, so the index tends to pull the feature no matter what query you run; the number of vertices is huge, and tests (distance, containment) have to traverse the vertex list at least once and sometimes N times (with N being the number of vertices in the other candidate feature). As with GEOMETRY, we recommend that when you have very large polygons, but are doing queries in small areas, you "denormalize" your geometric data into smaller chunks so that the index can effectively subquery parts of the object and so queries don't have to pull out the whole object every time. Please consult ST_Subdivide function documentation. Just because you *can* store all of Europe in one polygon doesn't mean you *should*. |
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.)
A simple geometry is one that has no anomalous geometric points, such as self intersection or self tangency.
A POINT is inherently simple as a 0-dimensional geometry object.
MULTIPOINTs are simple if no two coordinates (POINTs) are equal (have identical coordinate values).
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.
(a) and (c) are simple |
![]() (a) | ![]() (b) |
![]() (c) | ![]() (d) |
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.
(e) and (f) are simple |
![]() (e) | ![]() (f) | ![]() (g) |
POLYGONs are formed from linear rings, so valid polygonal geometry is always simple.
To test if a geometry is simple use the ST_IsSimple function:
SELECT
ST_IsSimple('LINESTRING(0 0, 100 100)') AS straight,
ST_IsSimple('LINESTRING(0 0, 100 100, 100 0, 0 100)') AS crossing;
straight | crossing
----------+----------
t | f
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.
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:
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").
boundary rings do not cross
boundary rings may touch at points but only as a tangent (i.e. not in a line)
interior rings are contained in the exterior ring
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)
(h) and (i) are valid |
![]() (h) | ![]() (i) | ![]() (j) |
![]() (k) | ![]() (l) | ![]() (m) |
A MULTIPOLYGON is valid if:
its element POLYGONs are valid
elements do not overlap (i.e. their interiors must not intersect)
elements touch only at points (i.e. not along a line)
(n) is a valid |
![]() (n) | ![]() (o) | ![]() (p) |
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.
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
POINT and MULTIPOINT geometries have no validity rules.
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:
SELECT ST_IsValid('POLYGON ((20 180, 180 180, 180 20, 20 20, 20 180))');
-----------------
t
Information about the nature and location of an geometry invalidity are provided by the ST_IsValidDetail function:
SELECT valid, reason, ST_AsText(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.56976744186045)
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:
ALTER TABLE mytable
ADD CONSTRAINT geometry_valid_check
CHECK (ST_IsValid(geom));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.
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.
The spatial_ref_sys table definition is:
CREATE TABLE spatial_ref_sys ( srid INTEGER NOT NULL PRIMARY KEY, auth_name VARCHAR(256), auth_srid INTEGER, srtext VARCHAR(2048), proj4text VARCHAR(2048) )
The columns are:
sridAn integer code that uniquely identifies the Spatial Reference System (SRS) within the database.
auth_nameThe name of the standard or standards body that is being cited for this reference system. For example, "EPSG" is a valid auth_name.
auth_sridThe 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.
srtextThe Well-Known Text representation of the Spatial Reference System. An example of a WKT SRS representation is:
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.
proj4textPostGIS uses the PROJ library to provide coordinate transformation capabilities. The proj4text column contains the PROJ coordinate definition string for a particular SRID. For example:
+proj=utm +zone=10 +ellps=clrk66 +datum=NAD27 +units=m
For more information see the PROJ web site. The spatial_ref_sys.sql file contains both srtext and proj4text definitions for all EPSG projections.
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.
The PostGIS spatial_ref_sys table contains over 3000 of the most common spatial reference system definitions that are handled by the PROJ projection library. But there are many coordinate systems that it does not contain. You can add SRS definitions to the table if you have the required information about the spatial reference system. Or, you can define your own custom spatial reference system if you are familiar with PROJ constructs. Keep in mind that most spatial reference systems are regional and have no meaning when used outside of the bounds they were intended for.
A resource for finding spatial reference systems not defined in the core set is 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. (To determine which UTM zone to use for your area of interest, see the utmzone PostGIS plpgsql helper function.)
US states use State Plane spatial reference systems (meter or feet based) - usually one or 2 exists per state. Most of the meter-based ones are in the core set, but many of the feet-based ones or ESRI-created ones will need to be copied from 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:
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' );
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):
CREATE TABLE roads (
id SERIAL PRIMARY KEY,
name VARCHAR(64),
geom geometry(LINESTRING,3005)
);The geometry type supports two optional type modifiers:
the spatial type modifier restricts the kind of shapes and dimensions allowed in the column. The value can be any of the supported geometry subtypes (e.g. POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING, MULTIPOLYGON, GEOMETRYCOLLECTION, etc). The modifier supports coordinate dimensionality restrictions by adding suffixes: Z, M and ZM. For example, a modifier of 'LINESTRINGM' allows only linestrings with three dimensions, and treats the third dimension as a measure. Similarly, 'POINTZM' requires four dimensional (XYZM) data.
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:
CREATE TABLE geoms(gid serial PRIMARY KEY, geom geometry );
Create a table with 2D POINT geometry with the default SRID:
CREATE TABLE pts(gid serial PRIMARY KEY, geom geometry(POINT) );
Create a table with 3D (XYZ) POINTs and an explicit SRID of 3005:
CREATE TABLE pts(gid serial PRIMARY KEY, geom geometry(POINTZ,3005) );
Create a table with 4D (XYZM) LINESTRING geometry with the default SRID:
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):
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:
ALTER TABLE roads ADD COLUMN geom2 geometry(LINESTRINGZ,4326);
The OGC Simple Features Specification for SQL defines the GEOMETRY_COLUMNS metadata table to describe geometry table structure. In PostGIS geometry_columns is a view reading from database system catalog tables. This ensures that the spatial metadata information is always consistent with the currently defined tables and views. The view structure is:
\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) |The columns are:
f_table_catalog, f_table_schema, f_table_nameThe fully qualified name of the feature table containing the geometry column. There is no PostgreSQL analogue of "catalog" so that column is left blank. For "schema" the PostgreSQL schema name is used (public is the default).
f_geometry_columnThe name of the geometry column in the feature table.
coord_dimensionThe coordinate dimension (2, 3 or 4) of the column.
sridThe ID of the spatial reference system used for the coordinate geometry in this table. It is a foreign key reference to the spatial_ref_sys table (see Section 4.5.1, “SPATIAL_REF_SYS Table”).
typeThe type of the spatial object. To restrict the spatial column to a single type, use one of: POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING, MULTIPOLYGON, GEOMETRYCOLLECTION or corresponding XYM versions POINTM, LINESTRINGM, POLYGONM, MULTIPOINTM, MULTILINESTRINGM, MULTIPOLYGONM, GEOMETRYCOLLECTIONM. For heterogeneous (mixed-type) collections, you can use "GEOMETRY" as the type.
Two of the cases where you may need this are the case of SQL Views and bulk inserts. For bulk insert case, you can correct the registration in the geometry_columns table by constraining the column or doing an alter table. For views, you could expose using a CAST operation. Note, if your column is typmod based, the creation process would register it correctly, so no need to do anything. Also views that have no spatial function applied to the geometry will register the same as the underlying table geometry column.
-- Lets say you have a view created like this
CREATE VIEW public.vwmytablemercator AS
SELECT gid, ST_Transform(geom, 3395) As geom, f_name
FROM public.mytable;
-- For it to register correctly
-- You need to cast the geometry
--
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 you know the geometry type for sure is a 2D POLYGON then you could do
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;--Lets say you created a derivative table by doing a bulk insert
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 2D index on new table
CREATE INDEX idx_myschema_myspecialpois_geom_gist
ON myschema.my_special_pois USING gist(geom);
-- If your points are 3D points or 3M points,
-- then you might want to create an nd index instead of a 2D index
CREATE INDEX my_special_pois_geom_gist_nd
ON my_special_pois USING gist(geom gist_geometry_ops_nd);
-- To manually register this new table's geometry column in geometry_columns.
-- Note it will also change the underlying structure of the table to
-- to make the column typmod based.
SELECT populate_geometry_columns('myschema.my_special_pois'::regclass);
-- If you are using PostGIS 2.0 and for whatever reason, you
-- you need the constraint based definition behavior
-- (such as case of inherited tables where all children do not have the same type and srid)
-- set optional use_typmod argument to false
SELECT populate_geometry_columns('myschema.my_special_pois'::regclass, false); Although the old-constraint based method is still supported, a constraint-based geometry column used directly in a view, will not register correctly in geometry_columns, as will a typmod one. In this example we define a column using typmod and another using constraints.
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 in psql
\d pois_ny;
We observe they are defined differently -- one is typmod, one is constraint
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)In geometry_columns, they both register correctly
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
However -- if we were to create a view like this
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';The typmod based geom view column registers correctly, but the constraint based one does not.
f_table_name | f_geometry_column | srid | type ------------------+-------------------+------+---------- vw_pois_ny_parks | geom | 4326 | POINT vw_pois_ny_parks | geom_2160 | 0 | GEOMETRY
This may change in future versions of PostGIS, but for now to force the constraint-based view column to register correctly, you need to do this:
DROP VIEW vw_pois_ny_parks;
CREATE VIEW vw_pois_ny_parks AS
SELECT gid, poi_name, cat,
geom,
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
Once you have created a spatial table, you are ready to upload spatial data to the database. There are two built-in ways to get spatial data into a PostGIS/PostgreSQL database: using formatted SQL statements or using the Shapefile loader.
If spatial data can be converted to a text representation (as either WKT or WKB), then using SQL might be the easiest way to get data into PostGIS. Data can be bulk-loaded into PostGIS/PostgreSQL by loading a text file of SQL INSERT statements using the psql SQL utility.
A SQL load file (roads.sql for example) might look like this:
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;
The SQL file can be loaded into PostgreSQL using psql:
psql -d [database] -f roads.sql
The shp2pgsql data loader converts Shapefiles into SQL suitable for insertion into a PostGIS/PostgreSQL database either in geometry or geography format. The loader has several operating modes selected by command line flags.
There is also a shp2pgsql-gui graphical interface with most of the options as the command-line loader. This may be easier to use for one-off non-scripted loading or if you are new to PostGIS. It can also be configured as a plugin to PgAdminIII.
-cCreates a new table and populates it from the Shapefile. This is the default mode.
-aAppends data from the Shapefile into the database table. Note that to use this option to load multiple files, the files must have the same attributes and same data types.
-dDrops the database table before creating a new table with the data in the Shapefile.
-pOnly produces the table creation SQL code, without adding any actual data. This can be used if you need to completely separate the table creation and data loading steps.
-?Display help screen.
-DUse the PostgreSQL "dump" format for the output data. This can be combined with -a, -c and -d. It is much faster to load than the default "insert" SQL format. Use this for very large data sets.
-s [<FROM_SRID>:]<SRID>Creates and populates the geometry tables with the specified SRID. Optionally specifies that the input shapefile uses the given FROM_SRID, in which case the geometries will be reprojected to the target SRID.
-kKeep identifiers' case (column, schema and attributes). Note that attributes in Shapefile are all UPPERCASE.
-iCoerce all integers to standard 32-bit integers, do not create 64-bit bigints, even if the DBF header signature appears to warrant it.
-ICreate a GiST index on the geometry column.
-m-m a_file_name 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
-SGenerate simple geometries instead of MULTI geometries. Will only succeed if all the geometries are actually single (I.E. a MULTIPOLYGON with a single shell, or or a MULTIPOINT with a single vertex).
-t <dimensionality>Force the output geometry to have the specified dimensionality. Use the following strings to indicate the dimensionality: 2D, 3DZ, 3DM, 4D.
If the input has fewer dimensions that specified, the output will have those dimensions filled in with zeroes. If the input has more dimensions that specified, the unwanted dimensions will be stripped.
-wOutput WKT format, instead of WKB. Note that this can introduce coordinate drifts due to loss of precision.
-eExecute each statement on its own, without using a transaction. This allows loading of the majority of good data when there are some bad geometries that generate errors. Note that this cannot be used with the -D flag as the "dump" format always uses a transaction.
-W <encoding>Specify encoding of the input data (dbf file). When used, all attributes of the dbf are converted from the specified encoding to UTF8. The resulting SQL output will contain a SET CLIENT_ENCODING to UTF8 command, so that the backend will be able to reconvert from UTF8 to whatever encoding the database is configured to use internally.
-N <policy>NULL geometries handling policy (insert*,skip,abort)
-n-n Only import DBF file. If your data has no corresponding shapefile, it will automatically switch to this mode and load just the dbf. So setting this flag is only needed if you have a full shapefile set, and you only want the attribute data and no geometry.
-GUse geography type instead of geometry (requires lon/lat data) in WGS84 long lat (SRID=4326)
-T <tablespace>Specify the tablespace for the new table. Indexes will still use the default tablespace unless the -X parameter is also used. The PostgreSQL documentation has a good description on when to use custom tablespaces.
-X <tablespace>Specify the tablespace for the new table's indexes. This applies to the primary key index, and the GIST spatial index if -I is also used.
-ZWhen used, this flag will prevent the generation of ANALYZE statements. Without the -Z flag (default behavior), the ANALYZE statements will be generated.
An example session using the loader to create an input file and loading it might look like this:
# shp2pgsql -c -D -s 4269 -i -I shaperoads.shp myschema.roadstable > roads.sql # psql -d roadsdb -f roads.sql
A conversion and load can be done in one step using UNIX pipes:
# shp2pgsql shaperoads.shp myschema.roadstable | psql -d roadsdb
Spatial data can be extracted from the database using either SQL or the Shapefile dumper. The section on SQL presents some of the functions available to do comparisons and queries on spatial tables.
The most straightforward way of extracting spatial data out of the database is to use a SQL SELECT query to define the data set to be extracted and dump the resulting columns into a parsable text file:
db=# SELECT road_id, ST_AsText(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)There will be times when some kind of restriction is necessary to cut down the number of records returned. In the case of attribute-based restrictions, use the same SQL syntax as used with a non-spatial table. In the case of spatial restrictions, the following functions are useful:
ST_IntersectsThis function tells whether two geometries share any space.
=This tests whether two geometries are geometrically identical. For example, if 'POLYGON((0 0,1 1,1 0,0 0))' is the same as 'POLYGON((0 0,1 1,1 0,0 0))' (it is).
Next, you can use these operators in queries. Note that when specifying geometries and boxes on the SQL command line, you must explicitly turn the string representations into geometries function. The 312 is a fictitious spatial reference system that matches our data. So, for example:
SELECT road_id, road_name FROM roads WHERE roads_geom='SRID=312;LINESTRING(191232 243118,191108 243242)'::geometry;
The above query would return the single record from the "ROADS_GEOM" table in which the geometry was equal to that value.
To check whether some of the roads passes in the area defined by a polygon:
SELECT road_id, road_name FROM roads WHERE ST_Intersects(roads_geom, 'SRID=312;POLYGON((...))');
The most common spatial query will probably be a "frame-based" query, used by client software, like data browsers and web mappers, to grab a "map frame" worth of data for display.
When using the "&&" operator, you can specify either a BOX3D as the comparison feature or a GEOMETRY. When you specify a GEOMETRY, however, its bounding box will be used for the comparison.
Using a "BOX3D" object for the frame, such a query looks like this:
SELECT ST_AsText(roads_geom) AS geom FROM roads WHERE roads_geom && ST_MakeEnvelope(191232, 243117,191232, 243119,312);
Note the use of the SRID 312, to specify the projection of the envelope.
The pgsql2shp table dumper connects to the database and converts a table (possibly defined by a query) into a shape file. The basic syntax is:
pgsql2shp [<options >] <database > [<schema >.]<table>
pgsql2shp [<options >] <database > <query>
The commandline options are:
-f <filename>Write the output to a particular filename.
-h <host>The database host to connect to.
-p <port>The port to connect to on the database host.
-P <password>The password to use when connecting to the database.
-u <user>The username to use when connecting to the database.
-g <geometry column>In the case of tables with multiple geometry columns, the geometry column to use when writing the shape file.
-bUse a binary cursor. This will make the operation faster, but will not work if any NON-geometry attribute in the table lacks a cast to text.
-rRaw mode. Do not drop the gid field, or escape column names.
-m filenameRemap identifiers to ten character names. The content of the file is lines of two symbols separated by a single white space and no trailing or leading space: VERYLONGSYMBOL SHORTONE ANOTHERVERYLONGSYMBOL SHORTER etc.
Spatial indexes make using a spatial database for large data sets possible. Without indexing, a search for features requires a sequential scan of every record in the database. Indexing speeds up searching by organizing the data into a structure which can be quickly traversed to find matching records.
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) indexes break up data into "things to one side", "things which overlap", "things which are inside" and can be used on a wide range of data-types, including GIS data. PostGIS uses an R-Tree index implemented on top of GiST to index spatial data. GiST is the most commonly-used and versatile spatial index method, and offers very good query performance.
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 Section 5.2, “Using Spatial Indexes”.
See also the PostGIS Workshop section on spatial indexes, and the PostgreSQL manual.
GiST stands for "Generalized Search Tree" and is a generic form of indexing for multi-dimensional data. PostGIS uses an R-Tree index implemented on top of GiST to index spatial data. GiST is the most commonly-used and versatile spatial index method, and offers very good query performance. Other implementations of GiST are used to speed up searches on all kinds of irregular data structures (integer arrays, spectral data, etc) which are not amenable to normal B-Tree indexing. For more information see the PostgreSQL manual.
Once a spatial data table exceeds a few thousand rows, you will want to build an index to speed up spatial searches of the data (unless all your searches are based on attributes, in which case you'll want to build a normal index on the attribute fields).
The syntax for building a GiST index on a "geometry" column is as follows:
CREATE INDEX [indexname] ON [tablename] USING GIST ( [geometryfield] );
The above syntax will always build a 2D-index. To get the an n-dimensional index for the geometry type, you can create one using this syntax:
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:
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:
VACUUM ANALYZE [table_name] [(column_name)];
BRIN stands for "Block Range Index". It is a general-purpose index method introduced in PostgreSQL 9.5. 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.
Once a spatial table exceeds a few thousand rows, you will want to build an index to speed up spatial searches of the data. GiST indexes are very performant as long as their size doesn't exceed the amount of RAM available for the database, and as long as you can afford the index storage size, and the cost of index update on write. Otherwise, for very large tables BRIN index can be considered as an alternative.
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):
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:
CREATE INDEX idx_temp_geohash ON table
USING btree (ST_GeoHash( ST_Transform( geom, 4326 ), 20));
CLUSTER table USING idx_temp_geohash;
The syntax for building a BRIN index on a geometry column is:
CREATE INDEX [indexname] ON [tablename] USING BRIN ( [geome_col] );
The above syntax builds a 2D index. To build a 3D-dimensional index, use this syntax:
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:
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
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
The geography datatype is supported for BRIN indexing. The syntax for building a BRIN index on a geography column is:
CREATE INDEX [indexname] ON [tablename] USING BRIN ( [geog_col] );
The above syntax builds a 2D-index for geospatial objects on the spheroid.
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.
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.
Once a GIS data table exceeds a few thousand rows, an SP-GiST index may be used to speed up spatial searches of the data. The syntax for building an SP-GiST index on a "geometry" column is as follows:
CREATE INDEX [indexname] ON [tablename] USING SPGIST ( [geometryfield] );
The above syntax will build a 2-dimensional index. A 3-dimensional index for the geometry type can be created using the 3D operator class:
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:
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:
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.
Ordinarily, indexes invisibly speed up data access: once an index is built, the PostgreSQL query planner automatically decides when to use it to improve query performance. But there are some situations where the planner does not choose to use existing indexes, so queries end up using slow sequential scans instead of a spatial index.
If you find your spatial indexes are not being used, there are a few things you can do:
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.
If vacuuming does not help, you can temporarily force the planner to use the index information by using the command SET ENABLE_SEQSCAN TO OFF;. This way you can check whether the planner is at all able to generate an index-accelerated query plan for your query. You should only use this command for debugging; generally speaking, the planner knows better than you do about when to use indexes. Once you have run your query, do not forget to run SET ENABLE_SEQSCAN TO ON; so that the planner will operate normally for other queries.
If SET ENABLE_SEQSCAN TO OFF; helps your query to run faster, your Postgres is likely not tuned for your hardware. If you find the planner wrong about the cost of sequential versus index scans try reducing the value of RANDOM_PAGE_COST in postgresql.conf, or use SET RANDOM_PAGE_COST TO 1.1;. The default value for RANDOM_PAGE_COST is 4.0. Try setting it to 1.1 (for SSD) or 2.0 (for fast magnetic disks). Decreasing the value makes the planner more likely to use index scans.
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.
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.
Spatial relationships indicate how two geometries interact with one another. They are a fundamental capability for querying geometry.
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:
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.
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.
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:
| Interior | Boundary | Exterior | |
|---|---|---|---|
| Interior | dim( I(a) ∩ I(b) ) | dim( I(a) ∩ B(b) ) | dim( I(a) ∩ E(b) ) |
| Boundary | dim( B(a) ∩ I(b) ) | dim( B(a) ∩ B(b) ) | dim( B(a) ∩ E(b) ) |
| Exterior | dim( E(a) ∩ I(b) ) | dim( E(a) ∩ B(b) ) | dim( E(a) ∩ E(b) ) |
Visually, for two overlapping polygonal geometries, this looks like:
| ||||||||||||||||||
|
|
Reading from left to right and top to bottom, the intersection matrix is represented as the text string '212101212'.
For more information, refer to:
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:
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.
In some cases the named spatial relationships are insufficient to provide a desired spatial filter condition.
![]() For example, consider a linear dataset representing a road network. It may be required to identify all road segments that cross each other, not at a point, but in a line (perhaps to validate some business rule). In this case ST_Crosses does not provide the necessary spatial filter, since for linear features it returns A two-step solution would be to first compute the actual intersection (ST_Intersection) of pairs of road lines that spatially intersect (ST_Intersects), and then check if the intersection's ST_GeometryType is ' Clearly, a simpler and faster solution is desirable. |
![]() A second example is locating wharves that intersect a lake's boundary on a line and where one end of the wharf is up on shore. In other words, where a wharf is within but not completely contained by a lake, intersects the boundary of a lake on a line, and where exactly one of the wharf's endpoints is within or on the boundary of the lake. It is possible to use a combination of spatial predicates to find the required features:
|
These requirements can be met by computing the full DE-9IM intersection matrix. PostGIS provides the ST_Relate function to do this:
SELECT ST_Relate( 'LINESTRING (1 1, 5 5)',
'POLYGON ((3 3, 3 7, 7 7, 7 3, 3 3))' );
st_relate
-----------
1010F0212
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 in a more succinct way. The ST_Relate and the ST_RelateMatch functions can be used to test intersection matrix patterns. For the first example above, the intersection matrix pattern specifying two lines intersecting in a line is '1*1***1**':
-- Find road segments that intersect in a line
SELECT a.id
FROM roads a, roads b
WHERE a.id != b.id
AND a.geom && b.geom
AND ST_Relate(a.geom, b.geom, '1*1***1**');For the second example, the intersection matrix pattern specifying a line partly inside and partly outside a polygon is '102101FF2':
-- Find wharves partly on a lake's shoreline
SELECT a.lake_id, b.wharf_id
FROM lakes a, wharfs b
WHERE a.geom && b.geom
AND ST_Relate(a.geom, b.geom, '102101FF2');
When constructing queries using spatial conditions, for best performance it is important to ensure that a spatial index is used, if one exists (see Section 4.9, “Spatial Indexes”). 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 Section 7.10.1, “Оператори обмежувальної рамки” for the full list) and the distance operators used in nearest-neighbor queries (the most common being <->; see Section 7.10.2, “Оператори відстані” 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:
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:
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.
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: 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): 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: 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): 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.47553551242 VANCOUVER | 1450.33093486576 LANGLEY DISTRICT | 833.793392535662 BURNABY | 773.769091404338 PRINCE GEORGE | 694.37554369147 ... 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: 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? |
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? |
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 |
Поточні версії PostgreSQL (включно з 9.6) мають недолік оптимізатора запитів щодо таблиць TOAST. Таблиці TOAST — це свого роду "розширення", що використовуються для зберігання великих (у сенсі розміру даних) значень, які не вміщуються на звичайних сторінках даних (наприклад, довгі тексти, зображення або складні геометричні фігури з великою кількістю вершин). Докладнішу інформацію див. документації PostgreSQL щодо TOAST для отримання додаткової інформації).
Проблема виникає, якщо у вас є таблиця з досить великими геометріями, але не надто великою кількістю рядків (наприклад, таблиця, що містить межі всіх європейських країн у високій роздільній здатності). Тоді сама таблиця є невеликою, але використовує багато простору TOAST. У нашому прикладі таблиця мала близько 80 рядків і використовувала лише 3 сторінки даних, але таблиця TOAST використовувала 8225 сторінок.
Тепер виконайте запит, в якому використовується оператор геометрії && для пошуку обмежувального прямокутника, який відповідає лише деяким із цих рядків. Тепер оптимізатор запитів бачить, що таблиця має лише 3 сторінки та 80 рядків. Він оцінює, що послідовне сканування такої невеликої таблиці буде набагато швидшим, ніж використання індексу. Тому він вирішує проігнорувати індекс GIST. Зазвичай така оцінка є правильною. Але в нашому випадку оператор && повинен витягнути кожну геометрію з диска, щоб порівняти обмежувальні прямокутники, тим самим прочитавши також усі сторінки TOAST.
Щоб перевірити, чи є у вас ця проблема, скористайтеся командою postgresql "EXPLAIN ANALYZE". Більш детальну інформацію та технічні подробиці можна знайти у темі на форумі PostgreSQL performance mailing list: http://archives.postgresql.org/pgsql-performance/2005-02/msg00030.php
та новіша тема на PostGIS https://lists.osgeo.org/pipermail/postgis-devel/2017-June/026209.html
Розробники PostgreSQL намагаються вирішити цю проблему, зробивши оцінку запиту TOAST-сумісною. Наразі існують два обхідні шляхи:
Перший спосіб вирішення проблеми полягає в тому, щоб змусити планувальник запитів використовувати індекс. Перед відправкою запиту надішліть на сервер команду "SET enable_seqscan TO off;". Це змусить планувальник запитів уникати послідовного сканування, коли це можливо. Таким чином, він буде використовувати індекс GIST, як зазвичай. Але цей прапор потрібно встановлювати для кожного з'єднання, і це призводить до неправильних оцінок планувальника запитів в інших випадках, тому після запиту слід виконати команду "SET enable_seqscan TO on;".
Другий спосіб вирішення проблеми полягає в тому, щоб зробити послідовне сканування таким же швидким, як вважає планувальник запитів. Це можна досягти, створивши додатковий стовпець, який "кешує" bbox, і зіставляючи його з цим стовпцем. У нашому прикладі команди виглядають так:
SELECT AddGeometryColumn('myschema','mytable','bbox','4326','GEOMETRY','2');
UPDATE mytable SET bbox = ST_Envelope(ST_Force2D(geom));Тепер змініть запит, щоб використовувати оператор && для bbox замість geom_column, наприклад:
SELECT geom_column
FROM mytable
WHERE bbox && ST_SetSRID('BOX3D(0 0,1 1)'::box3d,4326);
Звичайно, якщо ви змінюєте або додаєте рядки до таблиці mytable, ви повинні синхронізувати bbox. Найпростіший спосіб зробити це — використовувати тригери, але ви також можете змінити свою програму, щоб стовпець bbox завжди був актуальним, або виконувати запит UPDATE після кожної зміни.
Для таблиць, які в основному є тільки для читання і де для більшості запитів використовується один індекс, PostgreSQL пропонує команду CLUSTER. Ця команда фізично перевпорядковує всі рядки даних у тому ж порядку, що й критерії індексу, що дає дві переваги в продуктивності: По-перше, для сканування діапазону індексу кількість пошуків у таблиці даних значно зменшується. По-друге, якщо робочий набір зосереджений на невеликих інтервалах індексів, ви отримуєте більш ефективне кешування, оскільки рядки даних розподіляються між меншою кількістю сторінок даних. (Запрошуємо вас ознайомитися з документацією команди CLUSTER у посібнику PostgreSQL.)
Однак на даний момент PostgreSQL не дозволяє кластеризацію на індексах PostGIS GIST, оскільки індекси GIST просто ігнорують значення NULL, і ви отримуєте таке повідомлення про помилку:
lwgeom=# CLUSTER my_geom_index ON my_table; ERROR: cannot cluster when index access method does not handle null values HINT: You may be able to work around this by marking column "geom" NOT NULL.
Як вказує повідомлення HINT, цю недоліку можна обійти, додавши до таблиці обмеження "not null":
lwgeom=# ALTER TABLE my_table ALTER COLUMN geom SET not null; ALTER TABLE
Звичайно, це не спрацює, якщо вам насправді потрібні значення NULL у стовпці геометрії. Крім того, ви повинні використовувати вищезазначений метод для додавання обмеження, використання обмеження CHECK, такого як "ALTER TABLE blubb ADD CHECK (geometry is not null);" не спрацює.
Іноді в таблиці трапляються дані 3D або 4D, але доступ до них завжди здійснюється за допомогою функцій ST_AsText() або ST_AsBinary(), сумісних з OpenGIS, які виводять тільки 2D-геометрії. Вони роблять це шляхом внутрішнього виклику функції ST_Force2D(), що створює значне навантаження для великих геометрій. Щоб уникнути цього навантаження, можна попередньо видалити ці додаткові виміри один раз і назавжди:
UPDATE mytable SET geom = ST_Force2D(geom); VACUUM FULL ANALYZE mytable;
Зверніть увагу, що якщо ви додали стовпець геометрії за допомогою AddGeometryColumn(), буде обмеження на розмір геометрії. Щоб обійти це обмеження, вам потрібно буде видалити обмеження. Не забудьте оновити запис у таблиці geometry_columns і потім знову створити обмеження.
У разі великих таблиць може бути доцільним розділити це оновлення на менші частини, обмеживши оновлення частиною таблиці за допомогою оператора WHERE та вашого первинного ключа або іншого можливого критерію, а також виконавши просту команду "VACUUM;" між оновленнями. Це значно зменшує потребу в тимчасовому дисковому просторі. Крім того, якщо ви маєте змішані геометрії розмірів, обмеження UPDATE за допомогою "WHERE dimension(geom)>2" пропускає перезапис геометрій, які вже є у 2D.
Нижче наведено функції, які можуть знадобитися користувачеві PostGIS. Існують також інші функції, які є необхідними допоміжними функціями для об'єктів PostGIS, але не використовуються звичайними користувачами.
![]() | |
PostGIS розпочав перехід від існуючої конвенції іменування до конвенції, орієнтованої на SQL-MM. В результаті, більшість функцій, які ви знаєте і любите, були перейменовані з використанням стандартного префікса просторового типу (ST). Попередні функції все ще доступні, хоча вони не вказані в цьому документі, де наведено оновлені функції, які є еквівалентними. Функції, що не вказані в цій документації, є застарілими і будуть видалені в майбутніх версіях, тому ПРИПИНІТЬ ЇХ ВИКОРИСТОВУВАТИ. |
This section lists the custom PostgreSQL data types installed by PostGIS to represent spatial data.
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.
box2d is a spatial data type used to represent the two-dimensional bounding box enclosing a geometry or collection of geometries. For example, the ST_Extent aggregate function returns a box2d object.
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).
This table lists the automatic and explicit casts allowed for this data type:
| Приведення типів в | Поведінка |
| box3d | автоматичне |
| geometry | автоматичне |
box3d — The type representing a 3-dimensional bounding box.
box3d is a PostGIS spatial data type used to represent the three-dimensional bounding box enclosing a geometry or collection of geometries. For example, the ST_3DExtent aggregate function returns a box3d object.
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).
This table lists the automatic and explicit casts allowed for this data type:
| Приведення типів в | Поведінка |
| box | автоматичне |
| box2d | автоматичне |
| geometry | автоматичне |
geometry — The type representing spatial features with planar coordinate systems.
geometry is a fundamental PostGIS spatial data type used to represent a feature in planar (Euclidean) coordinate systems.
All spatial operations on geometry use the units of the Spatial Reference System the geometry is in.
This table lists the automatic and explicit casts allowed for this data type:
| Приведення типів в | Поведінка |
| 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 is a spatial data type used to represent a feature in geodetic coordinate systems. Geodetic coordinate systems model the earth using an ellipsoid.
Spatial operations on the geography type provide more accurate results by taking the ellipsoidal model into account.
This table lists the automatic and explicit casts allowed for this data type:
| Приведення типів в | Поведінка |
| geometry | explicit |
Ці функції допомагають визначати таблиці, що містять стовпці геометрії.
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” . Якщо schema_name не існує (або не видно в поточному search_path) або вказаний SRID, тип геометрії або розмір є недійсними, виникає помилка.
![]() | |
Змінено: 2.0.0 Ця функція більше не оновлює geometry_columns, оскільки geometry_columns є поданням, яке зчитує дані з системних каталогів. За замовчуванням вона також не створює обмежень, а замість цього використовує вбудовану поведінку модифікатора типу PostgreSQL. Наприклад, створення стовпця wgs84 POINT за допомогою цієї функції тепер еквівалентно: Змінено: 2.0.0 Якщо вам потрібна стара поведінка обмежень, використовуйте стандартне значення |
![]() | |
Змінено: 2.0.0 Види більше не можна реєструвати вручну в geometry_columns, однак види, побудовані на основі геометрій таблиць типу typmod і використовувані без функцій-обгортки, реєструватимуться правильно, оскільки вони успадковують поведінку типу typmod стовпця батьківської таблиці. Види, які використовують функції геометрії, що виводять інші геометрії, потрібно буде перетворити на геометрії типу typmod, щоб ці стовпці геометрії виду були зареєстровані правильно в geometry_columns. Див. Section 4.6.3, “Manually Registering 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 замість стовпця на основі обмежень.
-- Create schema to hold data
CREATE SCHEMA my_schema;
-- Create a new simple PostgreSQL table
CREATE TABLE my_schema.my_spatial_table (id serial);
-- Describing the table shows a simple table with a single "id" column.
postgis=# \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
SELECT AddGeometryColumn ('my_schema','my_spatial_table','geom',4326,'POINT',2);
-- Add a point using the old constraint based behavior
SELECT AddGeometryColumn ('my_schema','my_spatial_table','geom_c',4326,'POINT',2, false);
--Add a curvepolygon using old constraint behavior
SELECT AddGeometryColumn ('my_schema','my_spatial_table','geomcp_c',4326,'CURVEPOLYGON',2, false);
-- Describe the table again reveals the addition of a new geometry columns.
\d my_schema.my_spatial_table
addgeometrycolumn
-------------------------------------------------------------------------
my_schema.my_spatial_table.geomcp_c SRID:4326 TYPE:CURVEPOLYGON DIMS:2
(1 row)
Table "my_schema.my_spatial_table"
Column | Type | Modifiers
----------+----------------------+-------------------------------------------------------------------------
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)
-- geometry_columns view also registers the new columns --
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 повинен відповідати полю f_table_schema рядка таблиці в таблиці 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 Ця функція надається для забезпечення зворотної сумісності. Тепер, коли geometry_columns є видом системних каталогів, ви можете видалити стовпець geometry так само, як і будь-який інший стовпець таблиці, за допомогою |
SELECT DropGeometryColumn ('my_schema','my_spatial_table','geom');
----RESULT output ---
dropgeometrycolumn
------------------------------------------------------
my_schema.my_spatial_table.geom effectively removed.
-- In PostGIS 2.0+ the above is also equivalent to the standard
-- the standard alter table. Both will deregister from geometry_columns
ALTER TABLE my_schema.my_spatial_table DROP column geom;
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. Примітка: використовує current_schema() в установках pgsql, що підтримують схеми, якщо схема не вказана.
![]() | |
Змінено: 2.0.0 Ця функція надається для забезпечення зворотної сумісності. Тепер, коли geometry_columns є переглядом системних каталогів, ви можете видалити таблицю з геометричними стовпцями, як і будь-яку іншу таблицю, за допомогою |
SELECT DropGeometryTable ('my_schema','my_spatial_table');
----RESULT output ---
my_schema.my_spatial_table dropped.
-- The above is now equivalent to --
DROP TABLE my_schema.my_spatial_table;
Find_SRID — Повертає SRID, визначений для стовпця геометрії.
integer Find_SRID(varchar a_schema_name, varchar a_table_name, varchar a_geomfield_name);
Повертає ціле значення SRID вказаного стовпця геометрії, шукаючи його в таблиці GEOMETRY_COLUMNS. Якщо стовпець геометрії не був доданий належним чином (наприклад, за допомогою функції AddGeometryColumn), ця функція не працюватиме.
SELECT Find_SRID('public', 'tiger_us_state_2007', 'geom_4269');
find_srid
----------
4269
Populate_Geometry_Columns — Забезпечує, щоб стовпці геометрії були визначені з модифікаторами типу або мали відповідні просторові обмеження.
text Populate_Geometry_Columns(boolean use_typmod=true);
int Populate_Geometry_Columns(oid relation_oid, boolean use_typmod=true);
Забезпечує, щоб стовпці геометрії мали відповідні модифікатори типу або просторові обмеження, щоб гарантувати їх правильну реєстрацію в перегляді geometry_columns. За замовчуванням перетворює всі стовпці геометрії без модифікатора типу на стовпці з модифікаторами типу.
Для забезпечення зворотної сумісності та для просторових потреб, таких як успадкування таблиць, де кожна дочірня таблиця може мати різний тип геометрії, все ще підтримується старе поведінка перевірки обмежень. Якщо вам потрібна стара поведінка, потрібно передати новий необов'язковий аргумент як false use_typmod=false. Після цього стовпці геометрії будуть створені без модифікаторів типу, але з 3 визначеними обмеженнями. Зокрема, це означає, що кожен стовпець геометрії, що належить до таблиці, має принаймні три обмеження:
enforce_dims_geom - гарантує, що всі геометричні об'єкти мають однакові розміри (див. ST_NDims)
enforce_geotype_geom - гарантує, що всі геометричні об'єкти мають однаковий тип (див. GeometryType)
enforce_srid_geom - гарантує, що всі геометричні об'єкти мають однакову проекцію (див. ST_SRID)
Якщо вказано таблицю oid, ця функція намагається визначити srid, розмірність та тип геометрії всіх стовпців геометрії в таблиці, додаючи обмеження за необхідності. У разі успіху відповідний рядок вставляється в таблицю geometry_columns, інакше виникає виняток і з'являється повідомлення про помилку з описом проблеми.
Якщо вказано oid перегляду, як і в разі табличного oid, ця функція намагається визначити srid, розмірність і тип усіх геометрій у перегляді, вставляючи відповідні записи в таблицю geometry_columns, але не виконує жодних дій для забезпечення обмежень.
Варіант без параметрів є простим обгорткою для параметризованого варіанту, який спочатку обрізає і заповнює таблицю geometry_columns для кожної просторової таблиці і перегляду в базі даних, додаючи просторові обмеження до таблиць, де це доречно. Він повертає підсумок кількості стовпців геометрії, виявлених в базі даних, і кількості, які були вставлені в таблицю geometry_columns. Параметризована версія просто повертає кількість рядків, вставлених у таблицю geometry_columns.
Доступність: 1.4.0
Змінено: 2.0.0 За замовчуванням тепер для обмеження типів геометрії використовуються модифікатори типів замість обмежень перевірки. Ви все ще можете використовувати поведінку обмежень перевірки, використовуючи новий параметр use_typmod і встановивши його значення false.
Покращено: 2.0.0 use_typmod додано опціональний аргумент, який дозволяє контролювати, чи створюються стовпці з типовими модифікаторами або з перевірками обмежень.
CREATE TABLE public.myspatial_table(gid serial, geom geometry);
INSERT INTO myspatial_table(geom) VALUES(ST_GeomFromText('LINESTRING(1 2, 3 4)',4326) );
-- This will now use typ modifiers. For this to work, there must exist data
SELECT Populate_Geometry_Columns('public.myspatial_table'::regclass);
populate_geometry_columns
--------------------------
1
\d myspatial_table
Table "public.myspatial_table"
Column | Type | Modifiers
--------+---------------------------+---------------------------------------------------------------
gid | integer | not null default nextval('myspatial_table_gid_seq'::regclass)
geom | geometry(LineString,4326) |
-- This will change the geometry columns to use constraints if they are not typmod or have constraints already.
--For this to work, there must exist data
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);
populate_geometry_columns
--------------------------
1
\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 — Оновлює SRID всіх об'єктів у стовпці геометрії та метадані таблиці.
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);
Оновлює SRID всіх об'єктів у стовпці геометрії, оновлюючи обмеження та посилання в geometry_columns. Якщо стовпець був застосований за допомогою визначення типу, визначення типу буде змінено. Примітка: використовує current_schema() в установках pgsql, що підтримують схеми, якщо схема не вказана.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves.
Вставте геометрії в таблицю доріг із вже встановленим SRID, використовуючи формат EWKT:
COPY roads (geom) FROM STDIN;
SRID=4326;LINESTRING(0 0, 10 10)
SRID=4326;LINESTRING(10 10, 15 0)
\.
Це змінить srid таблиці доріг на 4326 з будь-якого попереднього значення:
SELECT UpdateGeometrySRID('roads','geom',4326);Попередній приклад еквівалентний цій DDL-інструкція:
ALTER TABLE roads
ALTER COLUMN geom TYPE geometry(MULTILINESTRING, 4326)
USING ST_SetSRID(geom,4326);Якщо ви неправильно вказали проекцію (або вказали її як невідому) під час завантаження і хочете перетворити все в веб-меркатор за один раз, ви можете зробити це за допомогою DDL, але в PostGIS немає еквівалентної функції для виконання цієї операції за один раз.
ALTER TABLE roads ALTER COLUMN geom TYPE geometry(MULTILINESTRING, 3857) USING ST_Transform(ST_SetSRID(geom,4326),3857) ;
ST_Collect — Створює GeometryCollection або Multi* геометрію з набору геометрій.
geometry ST_Collect(geometry g1, geometry g2);
geometry ST_Collect(geometry[] g1_array);
geometry ST_Collect(geometry set g1field);
Збирає геометрії в колекцію геометрій. Результатом є або Multi*, або GeometryCollection, залежно від того, чи мають вхідні геометрії однаковий або різний тип (однорідні або неоднорідні). Вхідні геометрії залишаються незмінними в колекції.
Варіант 1: приймає дві вхідні геометрії
Варіант 2: приймає масив геометрій
Варіант 3: агрегатна функція, що приймає набір рядків геометрій.
![]() | |
Якщо будь-яка з вхідних геометрій є колекцією (Multi* або GeometryCollection), ST_Collect повертає GeometryCollection (оскільки це єдиний тип, який може містити вкладені колекції). Щоб цього уникнути, використовуйте ST_Dumpу підзапиті, щоб розгорнути вхідні колекції до їхніх атомних елементів (див. приклад нижче). |
![]() | |
ST_Collect і ST_Union виглядають схожими, але насправді працюють зовсім по-різному. ST_Collect об'єднує геометрії в колекцію, не змінюючи їх жодним чином. ST_Union геометрично об'єднує геометрії в місцях їх перетину і розділяє лінії в точках перетину. При розчиненні меж може повертати окремі геометрії. |
Доступність: 1.4.0 — додано ST_Collect(geomarray). ST_Collect було вдосконалено для швидшої обробки більшої кількості геометрій.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves.
Збір 2D точок.
SELECT ST_AsText( ST_Collect( ST_GeomFromText('POINT(1 2)'),
ST_GeomFromText('POINT(-2 3)') ));
st_astext
----------
MULTIPOINT((1 2),(-2 3))
Збір 3D-точок.
SELECT ST_AsEWKT( ST_Collect( ST_GeomFromEWKT('POINT(1 2 3)'),
ST_GeomFromEWKT('POINT(1 2 4)') ) );
st_asewkt
-------------------------
MULTIPOINT(1 2 3,1 2 4)
Збір кривих.
SELECT ST_AsText( ST_Collect( 'CIRCULARSTRING(220268 150415,220227 150505,220227 150406)',
'CIRCULARSTRING(220227 150406,2220227 150407,220227 150406)'));
st_astext
------------------------------------------------------------------------------------
MULTICURVE(CIRCULARSTRING(220268 150415,220227 150505,220227 150406),
CIRCULARSTRING(220227 150406,2220227 150407,220227 150406))
Використання конструктора масиву для підзапиту.
SELECT ST_Collect( ARRAY( SELECT geom FROM sometable ) );
Використання конструктора масиву для значень.
SELECT ST_AsText( ST_Collect(
ARRAY[ ST_GeomFromText('LINESTRING(1 2, 3 4)'),
ST_GeomFromText('LINESTRING(3 4, 4 5)') ] )) As wktcollect;
--wkt collect --
MULTILINESTRING((1 2,3 4),(3 4,4 5))
Створення декількох колекцій шляхом групування геометрій у таблиці.
SELECT stusps, ST_Collect(f.geom) as geom
FROM (SELECT stusps, (ST_Dump(geom)).geom As geom
FROM
somestatetable ) As f
GROUP BY stusps
ST_LineFromMultiPoint — Створює LineString з геометрії MultiPoint.
geometry ST_LineFromMultiPoint(geometry aMultiPoint);
Створює LineString з геометрії MultiPoint.
Використовуйте ST_MakeLine для створення ліній з вхідних даних Point або LineString.
This function supports 3d and will not drop the z-index.
Створити 3D лінію з 3D MultiPoint
SELECT ST_AsEWKT( ST_LineFromMultiPoint('MULTIPOINT(1 2 3, 4 5 6, 7 8 9)') );
--result--
LINESTRING(1 2 3,4 5 6,7 8 9)
ST_MakeEnvelope — Створює прямокутний полігон з мінімальних і максимальних координат.
geometry ST_MakeEnvelope(float xmin, float ymin, float xmax, float ymax, integer srid=unknown);
Створює прямокутний полігон з мінімальних і максимальних значень для X і Y. Вхідні значення повинні бути в просторовій системі координат, визначеній SRID. Якщо SRID не вказано, використовується невідома просторова система координат (SRID 0).
Доступність: 1.5
Покращено: 2.0: Додано можливість вказати конверт без вказання SRID.
SELECT ST_AsText( ST_MakeEnvelope(10, 10, 11, 11, 4326) ); st_asewkt ----------- POLYGON((10 10, 10 11, 11 11, 11 10, 10 10))
ST_MakeLine — Створює LineString з геометрій Point, MultiPoint або LineString.
geometry ST_MakeLine(geometry geom1, geometry geom2);
geometry ST_MakeLine(geometry[] geoms_array);
geometry ST_MakeLine(geometry set geoms);
Створює об'єкт LineString, що містить точки геометрій Point, MultiPoint або LineString. Інші типи геометрії спричиняють помилку.
Варіант 1: приймає дві вхідні геометрії
Варіант 2: приймає масив геометрій
Варіант 3: агрегатна функція, що приймає набір рядків геометрій. Щоб забезпечити порядок вхідних геометрій, використовуйте ORDER BY у виклику функції або підзапит із розділом ORDER BY.
Повторювані вузли на початку вхідних рядків LineStrings об'єднуються в одну точку. Повторювані точки у вхідних даних Point і MultiPoint не об'єднуються. ST_RemoveRepeatedPointsможна використовувати для об'єднання повторюваних точок з вихідної лінії.
This function supports 3d and will not drop the z-index.
Доступність: 2.3.0 — додано підтримку елементів введення MultiPoint
Доступність: 2.0.0 - Додано підтримку елементів введення LineString
Доступність: 1.4.0 — додано ST_MakeLine(geomarray). Агрегатні функції ST_MakeLine було вдосконалено для швидшої обробки більшої кількості точок.
Створити лінію, що складається з двох точок.
SELECT ST_AsText( ST_MakeLine(ST_Point(1,2), ST_Point(3,4)) );
st_astext
---------------------
LINESTRING(1 2,3 4)
Створити 3D лінію з двох 3D точок.
SELECT ST_AsEWKT( ST_MakeLine(ST_MakePoint(1,2,3), ST_MakePoint(3,4,5) ));
st_asewkt
-------------------------
LINESTRING(1 2 3,3 4 5)
Створити лінію з двох роз'єднаних LineStrings.
select ST_AsText( ST_MakeLine( 'LINESTRING(0 0, 1 1)', 'LINESTRING(2 2, 3 3)' ) );
st_astext
-----------------------------
LINESTRING(0 0,1 1,2 2,3 3)
Створити лінію з масиву, сформованого підзапитом із сортуванням.
SELECT ST_MakeLine( ARRAY( SELECT ST_Centroid(geom) FROM visit_locations ORDER BY visit_time) );
Створити 3D лінію з масиву 3D точок
SELECT ST_AsEWKT( ST_MakeLine(
ARRAY[ ST_MakePoint(1,2,3), ST_MakePoint(3,4,5), ST_MakePoint(6,6,6) ] ));
st_asewkt
-------------------------
LINESTRING(1 2 3,3 4 5,6 6 6)
У цьому прикладі запитуються послідовності точок GPS за часом із набору треків і створюється один запис для кожного треку. Результатом є геометрії LineStrings, що складаються з точок треку GPS у порядку руху.
Використання агрегату ORDER BY забезпечує правильний порядок LineString.
SELECT gps.track_id, ST_MakeLine(gps.geom ORDER BY gps_time) As geom
FROM gps_points As gps
GROUP BY track_id;До PostgreSQL 9 можна було використовувати сортування в підзапиті. Однак іноді план запиту може не дотримуватися порядку підзапиту.
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 track_id;ST_RemoveRepeatedPoints, ST_AsEWKT, ST_AsText, ST_GeomFromText, ST_MakePoint, ST_Point
ST_MakePoint — Створює 2D, 3DZ або 4D точку.
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);
Створює геометрію точки 2D XY, 3D XYZ або 4D XYZM. Використовуйте ST_MakePointM, щоб створити точки з координатами XYM.
Використовуйте ST_SetSRID, щоб вказати SRID для створеної точки.
Хоча ST_MakePoint не відповідає стандарту OGC, він працює швидше, ніж ST_GeomFromText та ST_PointFromText. Він також простіший у використанні для числових значень координат.
![]() | |
Для геодезичних координат |
![]() | |
Функції ST_Point, ST_PointZ, ST_PointM та ST_PointZM можна використовувати для створення точок із заданим SRID. |
This function supports 3d and will not drop the z-index.
-- Create a point with unknown SRID SELECT ST_MakePoint(-71.1043443253471, 42.3150676015829); -- Create a point in the WGS 84 geodetic CRS SELECT ST_SetSRID(ST_MakePoint(-71.1043443253471, 42.3150676015829),4326); -- Create a 3D point (e.g. has altitude) SELECT ST_MakePoint(1, 2,1.5); -- Get z of point SELECT ST_Z(ST_MakePoint(1, 2,1.5)); result ------- 1.5
ST_GeomFromText, ST_PointFromText, ST_SetSRID, ST_MakePointM, ST_Point, ST_PointZ, ST_PointM, ST_PointZM
ST_MakePointM — Створює точку з значень X, Y та M.
geometry ST_MakePointM(float x, float y, float m);
Створює точку з координатами X, Y та M (вимірювання). Використовуйте ST_MakePoint, щоб створити точки з координатами XY, XYZ або XYZM.
Використовуйте ST_SetSRID, щоб вказати SRID для створеної точки.
![]() | |
Для геодезичних координат |
![]() | |
Функції ST_PointM та ST_PointZM можна використовувати для створення точок із значенням M та заданим SRID. |
Створити точку з невідомим SRID.
SELECT ST_AsEWKT( ST_MakePointM(-71.1043443253471, 42.3150676015829, 10) );
st_asewkt
-----------------------------------------------
POINTM(-71.1043443253471 42.3150676015829 10)
Створити точку з виміром у геодезичній системі координат WGS 84.
SELECT ST_AsEWKT( ST_SetSRID( ST_MakePointM(-71.104, 42.315, 10), 4326));
st_asewkt
---------------------------------------------------------
SRID=4326;POINTM(-71.104 42.315 10)
Отримати розмір створеної точки.
SELECT ST_M( ST_MakePointM(-71.104, 42.315, 10) ); result ------- 10
ST_MakePolygon — Створює полігон з оболонки та опціонального списку отворів.
geometry ST_MakePolygon(geometry linestring);
geometry ST_MakePolygon(geometry outerlinestring, geometry[] interiorlinestrings);
Створює полігон, утворений заданою оболонкою та опціональним масивом отворів. Вхідні геометрії повинні бути закритими лініями (кільцями).
Варіант 1: Приймає оболонку LineString.
Варіант 2: Приймає оболонку LineString та масив внутрішніх (діркових) LineStrings. Масив геометрії можна побудувати за допомогою конструкцій PostgreSQL array_agg(), ARRAY[] або ARRAY().
![]() | |
Ця функція не приймає MultiLineStrings. Використовуйте ST_LineMergeдля створення LineString або ST_Dumpдля вилучення LineStrings. |
This function supports 3d and will not drop the z-index.
Створити полігон з 2D LineString.
SELECT ST_MakePolygon( ST_GeomFromText('LINESTRING(75 29,77 29,77 29, 75 29)'));
Створіть полігон з відкритої лінії, використовуючи ST_StartPointта ST_AddPointдля його закриття.
SELECT ST_MakePolygon( ST_AddPoint(foo.open_line, ST_StartPoint(foo.open_line)) )
FROM (
SELECT ST_GeomFromText('LINESTRING(75 29,77 29,77 29, 75 29)') As open_line) As foo;
Створіть полігон із 3D-лінії
SELECT ST_AsEWKT( ST_MakePolygon( 'LINESTRING(75.15 29.53 1,77 29 1,77.6 29.5 1, 75.15 29.53 1)')); st_asewkt ----------- POLYGON((75.15 29.53 1,77 29 1,77.6 29.5 1,75.15 29.53 1))
Створює полігон з лінії з вимірами
SELECT ST_AsEWKT( ST_MakePolygon( 'LINESTRINGM(75.15 29.53 1,77 29 1,77.6 29.5 2, 75.15 29.53 2)' )); st_asewkt ---------- POLYGONM((75.15 29.53 1,77 29 1,77.6 29.5 2,75.15 29.53 2))
Створити полігон у формі пончика з додатковим отвором
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;
Створити набір меж провінцій з отворами, що позначають озера. Вхідними даними є таблиця полігонів/мультиполігонів провінцій та таблиця лінійних об'єктів, що позначають водойми. Лінії, що утворюють озера, визначаються за допомогою ST_IsClosed. Лінії провінцій витягуються за допомогою ST_Boundary. Відповідно до вимог ST_MakePolygon, межа примусово перетворюється на єдину лінію за допомогою ST_LineMerge. (Однак, зверніть увагу, що якщо провінція має більше одного регіону або має острови, це призведе до створення недійсного полігону.) Використання LEFT JOIN гарантує, що всі провінції будуть включені, навіть якщо вони не мають озер.
![]() | |
Конструкція CASE використовується, оскільки передача нульового масиву в ST_MakePolygon призводить до повернення значення NULL. |
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
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;
Інший метод полягає у використанні корельованого підзапиту та конструктора ARRAY(), який перетворює набір рядків у масив.
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 — Створює точку із значеннями X, Y та SRID.
geometry ST_Point(float x, float y);
geometry ST_Point(float x, float y, integer srid=unknown);
Повертає точку з заданими значеннями координат X та Y. Це еквівалент SQL-MM для ST_MakePoint, який приймає тільки X та Y.
![]() | |
Для геодезичних координат |
Покращено: 3.2.0 Додано srid як додатковий опціональний аргумент. Старіші версії вимагають поєднання з ST_SetSRID для позначення srid на геометрії.
This method implements the SQL/MM specification. SQL-MM 3: 6.1.2
SELECT ST_Point( -71.104, 42.315);
Створення точки із зазначеним SRID:
SELECT ST_Point( -71.104, 42.315, 4326);
Альтернативний спосіб вказати SRID:
SELECT ST_SetSRID( ST_Point( -71.104, 42.315), 4326);
Створіть точки географії за допомогою синтаксису перетворення :::
SELECT ST_Point( -71.104, 42.315, 4326)::geography;
Код до PostGIS 3.2, що використовує CAST:
SELECT CAST( ST_SetSRID(ST_Point( -71.104, 42.315), 4326) AS geography);
Якщо координати точки не знаходяться в геодезичній системі координат (такій як WGS84), то перед перенесенням в географічну систему їх необхідно перепроектувати. У цьому прикладі точка в системі координат Pennsylvania State Plane feet (SRID 2273) перепроектована в систему WGS84 (SRID 4326).
SELECT ST_Transform( ST_Point( 3637510, 3014852, 2273), 4326)::geography;
ST_MakePoint, ST_PointZ, ST_PointM, ST_PointZM, ST_SetSRID, ST_Transform
ST_PointZ — Створює точку з координатами X, Y, Z та значенням SRID.
geometry ST_PointZ(float x, float y, float z, integer srid=unknown);
Повертає точку з заданими значеннями координат X, Y і Z, а також, за бажанням, номер SRID.
Покращено: 3.2.0 Додано srid як додатковий опціональний аргумент. Старіші версії вимагають поєднання з ST_SetSRID для позначення srid на геометрії.
SELECT ST_PointZ(-71.104, 42.315, 3.4, 4326)
SELECT ST_PointZ(-71.104, 42.315, 3.4, srid => 4326)
SELECT ST_PointZ(-71.104, 42.315, 3.4)
ST_PointM — Створює точку з значеннями X, Y, M та SRID.
geometry ST_PointM(float x, float y, float m, integer srid=unknown);
Повертає точку з заданими значеннями координат X, Y і M, а також, за бажанням, номер SRID.
Покращено: 3.2.0 Додано srid як додатковий опціональний аргумент. Старіші версії вимагають поєднання з ST_SetSRID для позначення srid на геометрії.
SELECT ST_PointM(-71.104, 42.315, 3.4, 4326)
SELECT ST_PointM(-71.104, 42.315, 3.4, srid => 4326)
SELECT ST_PointM(-71.104, 42.315, 3.4)
ST_PointZM — Створює точку з значеннями X, Y, Z, M та SRID.
geometry ST_PointZM(float x, float y, float z, float m, integer srid=unknown);
Повертає точку з заданими значеннями координат X, Y, Z і M, а також, за бажанням, номер SRID.
Покращено: 3.2.0 Додано srid як додатковий опціональний аргумент. Старіші версії вимагають поєднання з ST_SetSRID для позначення srid на геометрії.
SELECT ST_PointZM(-71.104, 42.315, 3.4, 4.5, 4326)
SELECT ST_PointZM(-71.104, 42.315, 3.4, 4.5, srid => 4326)
SELECT ST_PointZM(-71.104, 42.315, 3.4, 4.5)
ST_Polygon — Створює полігон з LineString із заданим SRID.
geometry ST_Polygon(geometry lineString, integer srid);
Повертає полігон, побудований з заданого LineString, і встановлює систему просторових координат з srid.
ST_Polygon схожий на ST_MakePolygonВаріант 1 з додаванням налаштування SRID.
Для створення полігонів з отворами використовуйте ST_MakePolygonВаріант 2, а потім ST_SetSRID.
![]() | |
Ця функція не приймає MultiLineStrings. Використовуйте ST_LineMergeдля створення LineString або ST_Dumpдля вилучення LineStrings. |
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.
Створити 2D полігон.
SELECT ST_AsText( ST_Polygon('LINESTRING(75 29, 77 29, 77 29, 75 29)'::geometry, 4326) );
-- result --
POLYGON((75 29, 77 29, 77 29, 75 29))
Створити 3D полігон.
SELECT ST_AsEWKT( ST_Polygon( ST_GeomFromEWKT('LINESTRING(75 29 1, 77 29 2, 77 29 3, 75 29 1)'), 4326) );
-- result --
SRID=4326;POLYGON((75 29 1, 77 29 2, 77 29 3, 75 29 1))
ST_AsEWKT, ST_AsText, ST_GeomFromEWKT, ST_GeomFromText, ST_LineMerge, ST_MakePolygon
ST_TileEnvelope — Створює прямокутний полігон у Web Mercator (SRID:3857) за допомогою системи тайлів XYZ.
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);
Створює прямокутний полігон, що визначає розмір плитки в системі плиток XYZ. Плитка визначається рівнем масштабування Z та індексом XY плитки в сітці на цьому рівні. Може використовуватися для визначення меж плитки, необхідних для ST_AsMVTGeom для перетворення геометрії в координатну систему плиток MVT.
За замовчуванням контур плитки знаходиться в системі координат Web Mercator (SRID:3857) з використанням стандартного діапазону системи Web Mercator (-20037508.342789, 20037508.342789). Це найпоширеніша система координат, що використовується для плиток MVT. Додатковий параметр bounds можна використовувати для створення плиток у будь-якій системі координат. Це геометрія, що має SRID і розмір квадрата "Рівень масштабування нуль", в якому вписана система плиток XYZ.
Додатковий параметр margin можна використовувати для розширення плитки на заданий відсоток. Наприклад, margin=0.125 розширює плитку на 12,5%, що еквівалентно buffer=512, коли розмір плитки становить 4096, як використовується в ST_AsMVTGeom. Це корисно для створення буфера плиток, щоб включити дані, які лежать за межами видимої області плитки, але наявність яких впливає на візуалізацію плитки. Наприклад, назва міста (точка) може бути поблизу краю плитки, тому її мітка повинна бути візуалізована на двох плитках, навіть якщо точка розташована у видимій області лише однієї плитки. Використання розширених плиток у запиті дозволить включити точку міста в обидві плитки. Для зменшення плитки використовуйте від'ємне значення. Значення менше -0.5 заборонені, оскільки це призведе до повного видалення плитки. Не вказуйте поле при використанні з ST_AsMVTGeom. Дивіться приклад для ST_AsMVT.
Покращено: 3.1.0 Додано параметр поля.
Доступність: 3.0.0
SELECT ST_AsText( ST_TileEnvelope(2, 1, 1) );
st_astext
------------------------------
POLYGON((-10018754.1713945 0,-10018754.1713945 10018754.1713945,0 10018754.1713945,0 0,-10018754.1713945 0))
SELECT ST_AsText( ST_TileEnvelope(3, 1, 1, ST_MakeEnvelope(-180, -90, 180, 90, 4326) ) );
st_astext
------------------------------------------------------
POLYGON((-135 45,-135 67.5,-90 67.5,-90 45,-135 45))
ST_HexagonGrid — Повертає набір шестикутників та індексів комірок, які повністю покривають межі аргументу геометрії.
setof record ST_HexagonGrid(float8 size, geometry bounds);
Починається з концепції шестикутної мозаїки площини. (Це не шестикутна мозаїка земної кулі, це не схема мозаїки H3). Для заданої плоскої SRS і заданого розміру ребра, починаючи від початку координат SRS, існує одне унікальне шестикутне покриття площини, Tiling(SRS, Size). Ця функція відповідає на питання: які шестикутники в заданому Tiling(SRS, Size) перекриваються з заданими межами.

SRS для вихідних шестикутників — це SRS, що надається геометрією меж.
Подвоєння або потроєння розміру ребра шестикутника створює нову батьківську мозаїку, яка відповідає вихідній мозаїці. На жаль, неможливо створити батьківську мозаїку з шестикутників, в яку ідеально вписуються дочірні плитки.

Доступність: 3.1.0
Щоб зробити підсумок точок на шестикутній мозаїці, створіть шестикутну сітку, використовуючи межі точок як обмеження, а потім просторово з'єднайте її з цією сіткою.
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;Якщо ми створимо набір шестикутників для кожної межі полігону і відфільтруємо ті, що не перетинаються з їх шестикутниками, ми отримаємо мозаїку для кожного полігону.

У результаті мозаїчного покриття кожен стан покривається шестикутником, а на межі між станами утворюються перекриваються шестикутники.
![]() | |
Ключове слово LATERAL є імпліцитним для функцій, що повертають набір, коли вони посилаються на попередню таблицю в списку FROM. Тому CROSS JOIN LATERAL, CROSS JOIN або просто є еквівалентними конструкціями для цього прикладу. |
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_EstimatedExtent, ST_SetSRID, ST_SquareGrid, ST_TileEnvelope
ST_Hexagon — Повертає один шестикутник, використовуючи заданий розмір ребра та координати комірки в просторі шестикутної сітки.
geometry ST_Hexagon(float8 size, integer cell_i, integer cell_j, geometry origin);
Використовує ту саму концепцію шестикутної мозаїки, що й ST_HexagonGrid, але створює лише один шестикутник у бажаних координатах комірки. За бажанням можна налаштувати координати початку мозаїки, за замовчуванням початок знаходиться в точці 0,0.
Шестикутники генеруються без заданого SRID, тому використовуйте ST_SetSRID, щоб задати SRID відповідно до ваших очікувань.
Доступність: 3.1.0
SELECT ST_AsText(ST_SetSRID(ST_Hexagon(1.0, 0, 0), 3857));
POLYGON((-1 0,-0.5
-0.866025403784439,0.5
-0.866025403784439,1
0,0.5
0.866025403784439,-0.5
0.866025403784439,-1 0)) ST_SquareGrid — Повертає набір квадратів сітки та індексів комірок, які повністю покривають межі аргументу геометрії.
setof record ST_SquareGrid(float8 size, geometry bounds);
Починається з концепції квадратного покриття площини. Для заданої плоскої SRS і заданого розміру ребра, починаючи від початку SRS, існує одне унікальне квадратне покриття площини, Tiling(SRS, Size). Ця функція відповідає на питання: які сітки в заданому Tiling(SRS, Size) перекриваються з заданими межами.
SRS для вихідних квадратів — це SRS, що надається геометрією меж.
Подвоєння або розмір краю квадрата створює нову батьківську мозаїку, яка ідеально підходить до оригінальної мозаїки. Стандартні веб-карти в проекції Меркатора — це просто квадратні сітки, що є степенями числа два в площині Меркатора.
Доступність: 3.1.0
Сітка заповнить всю територію країни, тому якщо вам потрібні лише квадрати, що торкаються країни, вам доведеться потім відфільтрувати їх за допомогою ST_Intersects.
WITH grid AS ( SELECT (ST_SquareGrid(1, ST_Transform(geom,4326))).* FROM admin0 WHERE name = 'Canada' ) SELEcT ST_AsText(geom) FROM grid
Щоб зробити підсумок точок на квадратній мозаїці, створіть квадратну сітку, використовуючи межі точок як обмеження, а потім просторово з'єднайте її з цією сіткою. Зверніть увагу, що приблизна площа може відрізнятися від фактичної, тому будьте обережні і, як мінімум, переконайтеся, що ви проаналізували свою таблицю.
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Це дає той самий результат, що й у першому прикладі, але буде повільніше для великої кількості точок
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.geomST_TileEnvelope, ST_HexagonGrid , ST_EstimatedExtent , ST_SetSRID
ST_Square — Повертає один квадрат, використовуючи заданий розмір сторони та координати комірки в просторі квадратної сітки.
geometry ST_Square(float8 size, integer cell_i, integer cell_j, geometry origin='POINT(0 0)');
Використовує ту саму концепцію квадратної мозаїки, що й ST_SquareGrid, але створює лише один квадрат у бажаних координатах комірки. За бажанням можна налаштувати координати початку мозаїки, за замовчуванням початок знаходиться в точці 0,0.
Квадрати генеруються з SRID заданого початку координат. Використовуйте ST_SetSRID, щоб встановити SRID, якщо заданий початок координат має невідомий SRID (як це відбувається за замовчуванням).
Доступність: 3.1.0
SELECT ST_AsText(ST_SetSRID(ST_Square(1.0, 0, 0), 3857)); POLYGON((0 0,0 1,1 1,1 0,0 0))
ST_Letters — Повертає введені літери, відтворені як геометрія, з початковою позицією за замовчуванням в початку координат і висотою тексту за замовчуванням 100.
geometry ST_Letters(text letters, json font);
Використовує вбудований шрифт для відображення рядка як мультиполігональної геометрії. За замовчуванням висота тексту становить 100,0, відстань від нижньої частини нижнього виступу до верхньої частини великої літери. За замовчуванням початкова позиція розміщує початок базової лінії в точці початку координат. Для заміни шрифту потрібно передати карту json, де ключем є символ, а TWKB, закодований у base64, — форма шрифту, висота шрифтів становить 1000 одиниць від нижньої частини нижнього виступу до верхньої частини великої літери.
Текст за замовчуванням генерується в точці початку координат, тому щоб змінити його положення та розмір, спочатку застосуйте функцію ST_Scale, а потім функцію ST_Translate.
Доступність: 3.3.0
SELECT ST_AsText(ST_Letters('Yo'), 1);
Листи, створені ST_Letters
SELECT ST_Translate(ST_Scale(ST_Letters('Yo'), 10, 10), 100,100);geometry_dump для компонентів геометрії.geometry_dump для координат у геометрії.geometry_dump для сегментів у геометрії.geometry_dump для зовнішнього та внутрішнього кілець полігону.GeometryType — Повертає тип геометрії у вигляді тексту.
text GeometryType(geometry geomA);
Повертає тип геометрії у вигляді рядка. Наприклад: “LINESTRING”, “POLYGON”, “MULTIPOINT” тощо.
OGC SPEC s2.1.1.1 - Повертає ім'я підтипу Geometry, який можна інстанціювати, до якого належить цей екземпляр Geometry. Ім'я підтипу Geometry, який можна інстанціювати, повертається у вигляді рядка.
![]() | |
Ця функція також вказує, чи вимірюється геометрія, повертаючи рядок у вигляді “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).
SELECT GeometryType(ST_GeomFromText('LINESTRING(77.29 29.07,77.42 29.26,77.27 29.31,77.29 29.07)'));
geometrytype
--------------
LINESTRING
SELECT ST_GeometryType(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)) )'));
--result
POLYHEDRALSURFACE
SELECT GeometryType(geom) as result
FROM
(SELECT
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 geom
) AS g;
result
--------
TIN ST_Boundary — Повертає межі геометрії.
geometry ST_Boundary(geometry geomA);
Повертає закриття комбінаторної межі цієї геометрії. Комбінаторна межа визначається, як описано в розділі 3.12.3.2 специфікації OGC. Оскільки результат цієї функції є закриттям, а отже, топологічно замкнутим, отриману межу можна представити за допомогою примітивних елементів геометрії, як описано в розділі 3.12.2 специфікації OGC.
Виконано модулем GEOS
![]() | |
До версії 2.0.0 ця функція викликає виняток, якщо використовується з |
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 додано підтримку Triangle
Змінено: 3.2.0 підтримка TIN, не використовує geos, не лінеаризує криві
![]() Лінія з накладеними граничними точками
SELECT ST_Boundary(geom)
FROM (SELECT 'LINESTRING(100 150,50 60, 70 80, 160 170)'::geometry As geom) As f;
ST_AsText output
MULTIPOINT((100 150),(160 170))
| ![]() отвори полігону з межею, що складається з декількох ліній
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;
ST_AsText output
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))
|
SELECT ST_AsText(ST_Boundary(ST_GeomFromText('LINESTRING(1 1,0 0, -1 1)')));
st_astext
-----------
MULTIPOINT((1 1),(-1 1))
SELECT ST_AsText(ST_Boundary(ST_GeomFromText('POLYGON((1 1,0 0, -1 1, 1 1))')));
st_astext
----------
LINESTRING(1 1,0 0,-1 1,1 1)
--Using a 3d polygon
SELECT ST_AsEWKT(ST_Boundary(ST_GeomFromEWKT('POLYGON((1 1 1,0 0 1, -1 1 1, 1 1 1))')));
st_asewkt
-----------------------------------
LINESTRING(1 1 1,0 0 1,-1 1 1,1 1 1)
--Using a 3d multilinestring
SELECT ST_AsEWKT(ST_Boundary(ST_GeomFromEWKT('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) )')));
st_asewkt
----------
MULTIPOINT((-1 1 1),(1 1 0.75))
ST_BoundingDiagonal — Повертає діагональ обмежувального прямокутника геометрії.
geometry ST_BoundingDiagonal(geometry geom, boolean fits=false);
Повертає діагональ обмежувальної рамки наданої геометрії у вигляді LineString. Діагональ — це 2-точковий LineString із мінімальними значеннями кожного виміру в початковій точці та максимальними значеннями в кінцевій точці. Якщо вхідна геометрія порожня, діагональна лінія є LINESTRING EMPTY.
Додатковий параметр fits визначає, чи потрібно знайти найкраще співпадіння. Якщо значення false, можна прийняти діагональ дещо більшої обмежувальної рамки (що швидше обчислюється для геометрій з великою кількістю вершин). У будь-якому випадку обмежувальна рамка поверненої діагональної лінії завжди охоплює вхідну геометрію.
Повернена геометрія зберігає SRID та розмірність (наявність Z та M) вхідної геометрії.
![]() | |
У виняткових випадках (тобто, якщо у вхідних даних є лише одна вершина) повернутий ланцюжок ліній буде формально недійсним (не має внутрішньої частини). Результат все одно залишається топологічно правильним. |
Доступність: 2.2.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
-- Get the minimum X in a buffer around a point
SELECT ST_X(ST_StartPoint(ST_BoundingDiagonal(
ST_Buffer(ST_Point(0,0),10)
)));
st_x
------
-10
ST_StartPoint, ST_EndPoint, ST_X, ST_Y, ST_Z, ST_M, ST_Envelope
ST_CoordDim — Повертає розмірність координат геометрії.
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).
SELECT ST_CoordDim('CIRCULARSTRING(1 2 3, 1 3 4, 5 6 7, 8 9 10, 11 12 13)');
---result--
3
SELECT ST_CoordDim(ST_Point(1,2));
--result--
2
ST_Dimension — Повертає топологічну розмірність геометрії.
integer ST_Dimension(geometry g);
Повертає топологічну розмірність цього об'єкта Geometry, яка повинна бути меншою або дорівнювати розмірності координат. OGC SPEC s2.1.1.1 - повертає 0 для POINT, 1 для LINESTRING, 2 для POLYGON і найбільший вимір компонентів GEOMETRYCOLLECTION. Якщо розмір невідомий (наприклад, для порожнього GEOMETRYCOLLECTION), повертається 0.
This method implements the SQL/MM specification. SQL-MM 3: 5.1.2
Покращено: 2.0.0 додано підтримку багатогранних поверхонь і TIN. Більше не виникає виняток, якщо задано порожню геометрію.
![]() | |
До версії 2.0.0 ця функція викликає виняток, якщо використовується з порожньою геометрією. |
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
SELECT ST_Dimension('GEOMETRYCOLLECTION(LINESTRING(1 1,0 0),POINT(0 0))');
ST_Dimension
-----------
1
ST_Dump — Повертає набір рядків geometry_dump для компонентів геометрії.
geometry_dump[] ST_Dump(geometry g1);
Функція повернення набору (SRF), яка витягує компоненти геометрії. Вона повертає набір geometry_dumpрядків, кожен з яких містить геометрію (поле geom) та масив цілих чисел (поле path).
Для типу атомарної геометрії (POINT, LINESTRING, POLYGON) повертається один запис з порожнім масивом path і вхідною геометрією як geom. Для колекції або мультигеометрії повертається запис для кожного компонента колекції, а path позначає положення компонента всередині колекції.
ST_Dump корисний для розширення геометрій. Він є оберненим до ST_Collect/ GROUP BY, оскільки створює нові рядки. Наприклад, його можна використовувати для розширення MULTIPOLYGONS в POLYGONS.
Покращено: 2.0.0 додано підтримку багатогранних поверхонь, трикутників і TIN.
Доступність: PostGIS 1.0.0RC1. Потрібна PostgreSQL 7.3 або вище.
![]() | |
До версії 1.3.4 ця функція виходила з ладу при використанні з геометріями, що містять КРИВІ. Ця проблема вирішена у версії 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.
SELECT sometable.field1, sometable.field1,
(ST_Dump(sometable.geom)).geom AS geom
FROM sometable;
-- Break a compound curve into its constituent linestrings and circularstrings
SELECT ST_AsEWKT(a.geom), ST_HasArc(a.geom)
FROM ( SELECT (ST_Dump(p_geom)).geom AS geom
FROM (SELECT ST_GeomFromEWKT('COMPOUNDCURVE(CIRCULARSTRING(0 0, 1 1, 1 0),(1 0, 0 1))') 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)-- Polyhedral surface example
-- Break a Polyhedral surface into its faces
SELECT (a.p_geom).path[1] As path, ST_AsEWKT((a.p_geom).geom) As geom_ewkt
FROM (SELECT ST_Dump(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 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))-- TIN --
SELECT (g.gdump).path, ST_AsEWKT((g.gdump).geom) as wkt
FROM
(SELECT
ST_Dump( 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 gdump
) AS g;
-- result --
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))
ST_DumpPoints — Повертає набір рядків geometry_dump для координат у геометрії.
geometry_dump[] ST_DumpPoints(geometry geom);
Функція повернення набору (SRF), яка витягує координати (вершини) геометрії. Вона повертає набір geometry_dumpрядків, кожен з яких містить геометрію (поле geom) та масив цілих чисел (поле path).
поле geom POINTs представляє координати наданої геометрії.
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.
Щоб отримати єдину геометрію, що містить координати, використовуйте ST_Points.
Покращено: 2.1.0 Вища швидкість. Перероблено як 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.
SELECT edge_id, (dp).path[1] As index, ST_AsText((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)
SELECT path, ST_AsText(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)-- Polyhedral surface cube --
SELECT (g.gdump).path, ST_AsEWKT((g.gdump).geom) as wkt
FROM
(SELECT
ST_DumpPoints(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 gdump
) AS g;
-- result --
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)-- Triangle --
SELECT (g.gdump).path, ST_AsText((g.gdump).geom) as wkt
FROM
(SELECT
ST_DumpPoints( ST_GeomFromEWKT('TRIANGLE ((
0 0,
0 9,
9 0,
0 0
))') ) AS gdump
) AS g;
-- result --
path | wkt
------+------------
{1} | POINT(0 0)
{2} | POINT(0 9)
{3} | POINT(9 0)
{4} | POINT(0 0)
-- TIN --
SELECT (g.gdump).path, ST_AsEWKT((g.gdump).geom) as wkt
FROM
(SELECT
ST_DumpPoints( 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 gdump
) AS g;
-- result --
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)
ST_DumpSegments — Повертає набір рядків geometry_dump для сегментів у геометрії.
geometry_dump[] ST_DumpSegments(geometry geom);
Функція повернення набору (SRF), яка витягує сегменти геометрії. Вона повертає набір geometry_dumpрядків, кожен з яких містить геометрію (поле geom) та масив цілих чисел (поле path).
поле geom LINESTRINGs представляє лінійні сегменти наданої геометрії, а CIRCULARSTRINGs представляє сегменти дуги.
поле path (тип integer[]) є індексом, що перелічує позиції початкових точок сегментів в елементах наданої геометрії. Індекси починаються з 1. Наприклад, для LINESTRING шляхи є {i}, де i є n-тою початковою точкою сегмента в LINESTRING. Для POLYGON шляхи мають вигляд {i,j}, де i — номер кільця (1 — зовнішнє, внутрішні кільця йдуть за ним), а j — позиція початку сегмента в кільці.
Доступність: 3.2.0
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
This function supports 3d and will not drop the z-index.
SELECT path, ST_AsText(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)-- Triangle --
SELECT path, ST_AsText(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)
-- TIN --
SELECT path, ST_AsEWKT(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)
ST_DumpRings — Повертає набір рядків geometry_dump для зовнішнього та внутрішнього кілець полігону.
geometry_dump[] ST_DumpRings(geometry a_polygon);
Функція повернення набору (SRF), яка витягує кільця полігону. Вона повертає набір geometry_dumpрядків, кожен з яких містить геометрію (поле geom) та масив цілих чисел (поле path).
Поле geom містить кожне кільце як POLYGON. Поле path є цілочисельним масивом довжиною 1, що містить індекс кільця полігону. Зовнішнє кільце (оболонка) має індекс 0. Внутрішні кільця (отвори) мають індекси 1 і вище.
![]() | |
Це працює тільки для геометрії POLYGON. Не працює для MULTIPOLYGONS |
Доступність: PostGIS 1.1.3. Вимагає PostgreSQL 7.3 або вище.
This function supports 3d and will not drop the z-index.
Загальна форма запиту.
SELECT polyTable.field1, polyTable.field1,
(ST_DumpRings(polyTable.geom)).geom As geom
FROM polyTable;
Полігон з одним отвором.
SELECT path, ST_AsEWKT(geom) As geom
FROM ST_DumpRings(
ST_GeomFromEWKT('POLYGON((-8149064 5133092 1,-8149064 5132986 1,-8148996 5132839 1,-8148972 5132767 1,-8148958 5132508 1,-8148941 5132466 1,-8148924 5132394 1,
-8148903 5132210 1,-8148930 5131967 1,-8148992 5131978 1,-8149237 5132093 1,-8149404 5132211 1,-8149647 5132310 1,-8149757 5132394 1,
-8150305 5132788 1,-8149064 5133092 1),
(-8149362 5132394 1,-8149446 5132501 1,-8149548 5132597 1,-8149695 5132675 1,-8149362 5132394 1))')
) as foo;
path | geom
----------------------------------------------------------------------------------------------------------------
{0} | POLYGON((-8149064 5133092 1,-8149064 5132986 1,-8148996 5132839 1,-8148972 5132767 1,-8148958 5132508 1,
| -8148941 5132466 1,-8148924 5132394 1,
| -8148903 5132210 1,-8148930 5131967 1,
| -8148992 5131978 1,-8149237 5132093 1,
| -8149404 5132211 1,-8149647 5132310 1,-8149757 5132394 1,-8150305 5132788 1,-8149064 5133092 1))
{1} | POLYGON((-8149362 5132394 1,-8149446 5132501 1,
| -8149548 5132597 1,-8149695 5132675 1,-8149362 5132394 1))ST_EndPoint — Повертає останню точку LineString або CircularLineString.
geometry ST_EndPoint(geometry g);
Повертає останню точку геометрії LINESTRING або CIRCULARLINESTRING як POINT. Повертає NULL, якщо вхідні дані не є LINESTRING або CIRCULARLINESTRING.
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 більше не працює з одномірними MultiLineStrings. У старих версіях PostGIS одномірний MultiLineString працював з цією функцією і повертав кінцеву точку. У 2.0.0 він повертає NULL, як і будь-який інший MultiLineString. Стара поведінка була недокументованою функцією, але користувачі, які вважали, що їхні дані зберігаються як LINESTRING, можуть зіткнутися з поверненням NULL у 2.0.0. |
End point of a LineString
postgis=# SELECT ST_AsText(ST_EndPoint('LINESTRING(1 1, 2 2, 3 3)'::geometry));
st_astext
------------
POINT(3 3)
Кінцева точка нелінійного об'єкта LineString має значення NULL
SELECT ST_EndPoint('POINT(1 1)'::geometry) IS NULL AS is_null;
is_null
----------
t
Кінцева точка 3D-лінії
--3d endpoint
SELECT ST_AsEWKT(ST_EndPoint('LINESTRING(1 1 2, 1 2 3, 0 0 5)'));
st_asewkt
--------------
POINT(0 0 5)
Кінцева точка CircularString
SELECT ST_AsText(ST_EndPoint('CIRCULARSTRING(5 2,-3 1.999999, -2 1, -4 2, 6 3)'::geometry));
st_astext
------------
POINT(6 3)
ST_Envelope — Повертає геометрію, що представляє обмежувальну рамку геометрії.
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
SELECT ST_AsText(ST_Envelope('POINT(1 3)'::geometry));
st_astext
------------
POINT(1 3)
(1 row)
SELECT ST_AsText(ST_Envelope('LINESTRING(0 0, 1 3)'::geometry));
st_astext
--------------------------------
POLYGON((0 0,0 3,1 3,1 0,0 0))
(1 row)
SELECT ST_AsText(ST_Envelope('POLYGON((0 0, 0 1, 1.0000001 1, 1.0000001 0, 0 0))'::geometry));
st_astext
--------------------------------------------------------------
POLYGON((0 0,0 1,1.00000011920929 1,1.00000011920929 0,0 0))
(1 row)
SELECT ST_AsText(ST_Envelope('POLYGON((0 0, 0 1, 1.0000000001 1, 1.0000000001 0, 0 0))'::geometry));
st_astext
--------------------------------------------------------------
POLYGON((0 0,0 1,1.00000011920929 1,1.00000011920929 0,0 0))
(1 row)
SELECT Box3D(geom), Box2D(geom), ST_AsText(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;

Огинаюча точки та лінійного відрізка.
SELECT ST_AsText(ST_Envelope(
ST_Collect(
ST_GeomFromText('LINESTRING(55 75,125 150)'),
ST_Point(20, 80))
)) As wktenv;
wktenv
-----------
POLYGON((20 75,20 150,125 150,125 75,20 75))ST_ExteriorRing — Повертає LineString, що представляє зовнішнє кільце полігону
geometry ST_ExteriorRing(geometry a_polygon);
Повертає LineString, що представляє зовнішнє кільце полігону.
![]() | |
Ця функція не підтримує MULTIPOLYGON. Для MULTIPOLYGON використовуйте разом з ST_GeometryNабо 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.
--If you have a table of polygons
SELECT gid, ST_ExteriorRing(geom) AS ering
FROM sometable;
--If you have a table of MULTIPOLYGONs
--and want to return a MULTILINESTRING composed of the exterior rings of each polygon
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;
--3d Example
SELECT ST_AsEWKT(
ST_ExteriorRing(
ST_GeomFromEWKT('POLYGON((0 0 1, 1 1 1, 1 2 1, 1 1 1, 0 0 1))')
)
);
st_asewkt
---------
LINESTRING(0 0 1,1 1 1,1 2 1,1 1 1,0 0 1)
ST_GeometryN — Повернути елемент колекції геометрії.
geometry ST_GeometryN(geometry geomA, integer n);
Повертає N-й елемент геометрії, починаючи з 1, вхідної геометрії, яка є GEOMETRYCOLLECTION, MULTIPOINT, MULTILINESTRING, MULTICURVE, MULTI)POLYGON або POLYHEDRALSURFACE. В іншому випадку повертає NULL.
![]() | |
Індекс базується на 1, як і в специфікаціях OGC, починаючи з версії 0.8.0. У попередніх версіях це реалізовано на основі 0. |
![]() | |
Щоб витягти всі елементи геометрії, ST_Dumpє більш ефективним і працює для атомних геометрій. |
Покращено: 2.0.0 додано підтримку багатогранних поверхонь, трикутників і TIN.
Змінено: 2.0.0 Попередні версії повертали NULL для геометрій в однині. Це було змінено, щоб повертати геометрію для випадку ST_GeometryN(..,1).
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
SELECT n, ST_AsEWKT(ST_GeometryN(geom, n)) As geomewkt
FROM (
VALUES (ST_GeomFromEWKT('MULTIPOINT((1 2 7), (3 4 7), (5 6 7), (8 9 10))') ),
( ST_GeomFromEWKT('MULTICURVE(CIRCULARSTRING(2.5 2.5,4.5 2.5, 3.5 3.5), (10 11, 12 11))') )
)As foo(geom)
CROSS JOIN generate_series(1,100) n
WHERE n <= ST_NumGeometries(geom);
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)
--Extracting all geometries (useful when you want to assign an id)
SELECT gid, n, ST_GeometryN(geom, n)
FROM sometable CROSS JOIN generate_series(1,100) n
WHERE n <= ST_NumGeometries(geom);
-- Polyhedral surface example
-- Break a Polyhedral surface into its faces
SELECT ST_AsEWKT(ST_GeometryN(p_geom,3)) As geom_ewkt
FROM (SELECT 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 p_geom ) AS a;
geom_ewkt
------------------------------------------
POLYGON((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0))-- TIN --
SELECT ST_AsEWKT(ST_GeometryN(geom,2)) as wkt
FROM
(SELECT
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 geom
) AS g;
-- result --
wkt
-------------------------------------
TRIANGLE((0 0 0,0 1 0,1 1 0,0 0 0))ST_GeometryType — Повертає тип SQL-MM геометрії у вигляді тексту.
text ST_GeometryType(geometry g1);
Повертає тип геометрії у вигляді рядка. Наприклад: “ST_LineString”, “ST_Polygon”,'ST_MultiPolygon' тощо. Ця функція відрізняється від GeometryType(geometry) тим, що повертає строку і ST на початку, а також тим, що не вказує, чи виміряно геометрію.
Покращено: 2.0.0 додано підтримку багатогранних поверхонь.
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.
SELECT ST_GeometryType(ST_GeomFromText('LINESTRING(77.29 29.07,77.42 29.26,77.27 29.31,77.29 29.07)'));
--result
ST_LineStringSELECT ST_GeometryType(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)) )'));
--result
ST_PolyhedralSurfaceSELECT ST_GeometryType(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)) )'));
--result
ST_PolyhedralSurfaceSELECT ST_GeometryType(geom) as result
FROM
(SELECT
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 geom
) AS g;
result
--------
ST_Tin ST_HasArc — Тестує, чи містить геометрія кругову дугу
boolean ST_HasArc(geometry geomA);
Повертає true, якщо геометрія або колекція геометрій містить циклічну строку
Доступність: 1.2.3?
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves.
SELECT ST_HasArc(ST_Collect('LINESTRING(1 2, 3 4, 5 6)', 'CIRCULARSTRING(1 1, 2 3, 4 5, 6 7, 5 6)'));
st_hasarc
--------
t
ST_InteriorRingN — Повертає N-те внутрішнє кільце (отвір) полігону.
geometry ST_InteriorRingN(geometry a_polygon, integer n);
Повертає N-те внутрішнє кільце (отвір) геометрії POLYGON як LINESTRING. Індекс починається з 1. Повертає NULL, якщо геометрія не є полігоном або індекс виходить за межі діапазону.
![]() | |
Ця функція не підтримує MULTIPOLYGON. Для MULTIPOLYGON використовуйте разом з ST_GeometryNабо 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.
SELECT ST_AsText(ST_InteriorRingN(geom, 1)) As geom
FROM (SELECT ST_BuildArea(
ST_Collect(ST_Buffer(ST_Point(1,2), 20,3),
ST_Buffer(ST_Point(1, 2), 10,3))) As geom
) as foo;
ST_NumCurves — Повернути кількість кривих компонентів у CompoundCurve.
integer ST_NumCurves(geometry a_compoundcurve);
Повертає кількість компонентних кривих у CompoundCurve, нуль для порожнього CompoundCurve або NULL для вхідних даних, що не є CompoundCurve.
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.
-- Returns 3
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)
)');
-- Returns 0
SELECT ST_NumCurves('COMPOUNDCURVE EMPTY');
ST_CurveN, ST_Dump, ST_ExteriorRing, ST_NumInteriorRings, ST_NumGeometries
ST_CurveN — Повертає геометрію N-го компонента кривої CompoundCurve.
geometry ST_CurveN(geometry a_compoundcurve, integer index);
Повертає геометрію N-го компонента кривої CompoundCurve. Індекс починається з 1. Повертає NULL, якщо геометрія не є CompoundCurve або індекс знаходиться поза діапазоном.
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.
SELECT ST_AsText(ST_CurveN('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)
)', 1));
ST_NumCurves, ST_Dump, ST_ExteriorRing, ST_NumInteriorRings, ST_NumGeometries
ST_IsClosed — Перевіряє, чи збігаються початкова та кінцева точки LineStrings. Для PolyhedralSurface перевіряє, чи є вона закритою (об'ємною).
boolean ST_IsClosed(geometry g);
Повертає TRUE, якщо початкова та кінцева точки LINESTRING збігаються. Для поліедральних поверхонь повідомляє, чи поверхня є плоскою (відкритою) чи об'ємною (закритою).
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 визначає результат |
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves.
Покращено: 2.0.0 додано підтримку багатогранних поверхонь.
This function supports Polyhedral surfaces.
postgis=# SELECT ST_IsClosed('LINESTRING(0 0, 1 1)'::geometry);
st_isclosed
-------------
f
(1 row)
postgis=# SELECT ST_IsClosed('LINESTRING(0 0, 0 1, 1 1, 0 0)'::geometry);
st_isclosed
-------------
t
(1 row)
postgis=# SELECT ST_IsClosed('MULTILINESTRING((0 0, 0 1, 1 1, 0 0),(0 0, 1 1))'::geometry);
st_isclosed
-------------
f
(1 row)
postgis=# SELECT ST_IsClosed('POINT(0 0)'::geometry);
st_isclosed
-------------
t
(1 row)
postgis=# SELECT ST_IsClosed('MULTIPOINT((0 0), (1 1))'::geometry);
st_isclosed
-------------
t
(1 row)-- A cube --
SELECT ST_IsClosed(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)) )'));
st_isclosed
-------------
t
-- Same as cube but missing a side --
SELECT ST_IsClosed(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)) )'));
st_isclosed
-------------
f
ST_IsCollection — Перевіряє, чи є геометрія типом колекції геометрії.
boolean ST_IsCollection(geometry g);
Повертає TRUE, якщо тип геометрії аргументу є типом колекції геометрії. Типи колекцій є такими:
GEOMETRYCOLLECTION
MULTI{POINT,POLYGON,LINESTRING,CURVE,SURFACE}
COMPOUNDCURVE
![]() | |
Ця функція аналізує тип геометрії. Це означає, що вона поверне |
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves.
postgis=# SELECT ST_IsCollection('LINESTRING(0 0, 1 1)'::geometry);
st_iscollection
-------------
f
(1 row)
postgis=# SELECT ST_IsCollection('MULTIPOINT EMPTY'::geometry);
st_iscollection
-------------
t
(1 row)
postgis=# SELECT ST_IsCollection('MULTIPOINT((0 0))'::geometry);
st_iscollection
-------------
t
(1 row)
postgis=# SELECT ST_IsCollection('MULTIPOINT((0 0), (42 42))'::geometry);
st_iscollection
-------------
t
(1 row)
postgis=# SELECT ST_IsCollection('GEOMETRYCOLLECTION(POINT(0 0))'::geometry);
st_iscollection
-------------
t
(1 row)ST_IsEmpty — Перевіряє, чи геометрія порожня.
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.
![]() | |
Змінено: 2.0.0 У попередніх версіях PostGIS ST_GeomFromText(“GEOMETRYCOLLECTION(EMPTY)”) було дозволено. Тепер це є незаконним у PostGIS 2.0.0 для кращої відповідності стандартам SQL/MM |
SELECT ST_IsEmpty(ST_GeomFromText('GEOMETRYCOLLECTION EMPTY'));
st_isempty
------------
t
(1 row)
SELECT ST_IsEmpty(ST_GeomFromText('POLYGON EMPTY'));
st_isempty
------------
t
(1 row)
SELECT ST_IsEmpty(ST_GeomFromText('POLYGON((1 2, 3 4, 5 6, 1 2))'));
st_isempty
------------
f
(1 row)
SELECT ST_IsEmpty(ST_GeomFromText('POLYGON((1 2, 3 4, 5 6, 1 2))')) = false;
?column?
----------
t
(1 row)
SELECT ST_IsEmpty(ST_GeomFromText('CIRCULARSTRING EMPTY'));
st_isempty
------------
t
(1 row)
ST_IsPolygonCCW — Перевіряє, чи мають полігони зовнішні кільця, орієнтовані проти годинникової стрілки, і внутрішні кільця, орієнтовані за годинниковою стрілкою.
boolean ST_IsPolygonCCW ( geometry geom );
Повертає true, якщо всі полігональні компоненти вхідної геометрії використовують орієнтацію проти годинникової стрілки для зовнішнього кільця і за годинниковою стрілкою для всіх внутрішніх кілець.
Повертає true, якщо геометрія не має полігональних компонентів.
![]() | |
Закриті лінії не вважаються полігональними компонентами, тому ви все одно отримаєте правильний результат, передавши одну закриту лінію незалежно від її орієнтації. |
![]() | |
Якщо полігональна геометрія не використовує зворотну орієнтацію для внутрішніх кілець (тобто, якщо одне або більше внутрішніх кілець орієнтовані в тому ж напрямку, що і зовнішнє кільце), то обидва ST_IsPolygonCW і ST_IsPolygonCCW повернуть false. |
Доступність: 2.4.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_IsPolygonCW — Перевіряє, чи полігони мають зовнішні кільця, орієнтовані за годинниковою стрілкою, а внутрішні кільця — проти годинникової стрілки.
boolean ST_IsPolygonCW ( geometry geom );
Повертає true, якщо всі полігональні компоненти вхідної геометрії використовують орієнтацію за годинниковою стрілкою для зовнішнього кільця і проти годинникової стрілки для всіх внутрішніх кілець.
Повертає true, якщо геометрія не має полігональних компонентів.
![]() | |
Закриті лінії не вважаються полігональними компонентами, тому ви все одно отримаєте правильний результат, передавши одну закриту лінію незалежно від її орієнтації. |
![]() | |
Якщо полігональна геометрія не використовує зворотну орієнтацію для внутрішніх кілець (тобто, якщо одне або більше внутрішніх кілець орієнтовані в тому ж напрямку, що і зовнішнє кільце), то обидва ST_IsPolygonCW і ST_IsPolygonCCW повернуть false. |
Доступність: 2.4.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_IsRing — Перевіряє, чи лінія LineString є замкнутою та простою.
boolean ST_IsRing(geometry g);
Повертає TRUE, якщо цей LINESTRING є одночасно ST_IsClosed(ST_StartPoint(g) ~= ST_Endpoint(g)) і ST_IsSimple(не перетинається сам із собою).
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 визначає результат |
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) 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)
ST_IsSimple — Перевіряє, чи геометрія не має точок самоперетину або самодотику.
boolean ST_IsSimple(geometry geomA);
Повертає значення true, якщо ця геометрія не має аномальних геометричних точок, таких як самоперетин або самодотичність. Для отримання додаткової інформації про визначення простоти та валідності геометрії OGC див. "Забезпечення відповідності геометрій стандарту OpenGIS"
![]() | |
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.
SELECT ST_IsSimple(ST_GeomFromText('POLYGON((1 2, 3 4, 5 6, 1 2))'));
st_issimple
-------------
f
(1 row)
SELECT ST_IsSimple(ST_GeomFromText('LINESTRING(1 1,2 2,2 3.5,1 3,1 2,2 1)'));
st_issimple
-------------
f
(1 row)ST_M — Повертає координату M точки.
float ST_M(geometry a_point);
Повертає координату M точки або NULL, якщо вона недоступна. Вхідні дані повинні бути точкою.
![]() | |
Це (поки що) не є частиною специфікації OGC, але наведено тут для повноти переліку функцій вилучення координат точок. |
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.
SELECT ST_M(ST_GeomFromEWKT('POINT(1 2 3 4)'));
st_m
------
4
(1 row)
ST_MemSize — Повертає обсяг пам'яті, який займає геометрія.
integer ST_MemSize(geometry geomA);
Повертає обсяг пам'яті (у байтах), який займає геометрія.
Це доповнює вбудовані в PostgreSQL функції об'єктів бази даних pg_column_size, pg_size_pretty, pg_relation_size, pg_total_relation_size.
![]() | |
pg_relation_size, що повертає розмір таблиці в байтах, може повернути розмір, менший за ST_MemSize. Це відбувається тому, що pg_relation_size не додає розмір тостованих таблиць, а великі геометрії зберігаються в таблицях TOAST. pg_total_relation_size - включає таблицю, тостовані таблиці та індекси. pg_column_size повертає, скільки місця займає геометрія в стовпці з урахуванням стиснення, тому може бути менше, ніж 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).
Змінено: 2.2.0 назва змінено на ST_MemSize відповідно до правил іменування.
--Return how much byte space Boston takes up in our Mass data set
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)*1.00 /
SUM(ST_MemSize(geom))*100 As numeric(10,2)) As perbos
FROM towns;
totgeomsum bossum perbos
---------- ------ ------
1522 kB 30 kB 1.99
SELECT ST_MemSize(ST_GeomFromText('CIRCULARSTRING(220268 150415,220227 150505,220227 150406)'));
---
73
--What percentage of our table is taken up by just the geometry
SELECT pg_total_relation_size('public.neighborhoods') As fulltable_size, sum(ST_MemSize(geom)) As geomsize,
sum(ST_MemSize(geom))*1.00/pg_total_relation_size('public.neighborhoods')*100 As pergeom
FROM neighborhoods;
fulltable_size geomsize pergeom
------------------------------------------------
262144 96238 36.71188354492187500000
ST_NDims — Повертає розмір координат геометрії.
integer ST_NDims(geometry g1);
Повертає розмірність координат геометрії. PostGIS підтримує 2 - (x,y) , 3 - (x,y,z) або 2D з мірою - x,y,m, і 4 - 3D з мірою простору x,y,z,m
This function supports 3d and will not drop the z-index.
SELECT ST_NDims(ST_GeomFromText('POINT(1 1)')) As d2point,
ST_NDims(ST_GeomFromEWKT('POINT(1 1 2)')) As d3point,
ST_NDims(ST_GeomFromEWKT('POINTM(1 1 0.5)')) As d2pointm;
d2point | d3point | d2pointm
---------+---------+----------
2 | 3 | 3
ST_NPoints — Повертає кількість точок (вершин) у геометрії.
integer ST_NPoints(geometry g1);
Повертає кількість точок у геометрії. Працює для всіх геометрій.
Покращено: 2.0.0 додано підтримку багатогранних поверхонь.
![]() | |
До версії 1.3.4 ця функція виходила з ладу при використанні з геометріями, що містять КРИВІ. Ця проблема вирішена у версії 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.
SELECT ST_NPoints(ST_GeomFromText('LINESTRING(77.29 29.07,77.42 29.26,77.27 29.31,77.29 29.07)'));
--result
4
--Polygon in 3D space
SELECT ST_NPoints(ST_GeomFromEWKT('LINESTRING(77.29 29.07 1,77.42 29.26 0,77.27 29.31 -1,77.29 29.07 3)'))
--result
4ST_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.
SELECT ST_NRings(geom) As Nrings, ST_NumInteriorRings(geom) As ninterrings
FROM (SELECT ST_GeomFromText('POLYGON((1 2, 3 4, 5 6, 1 2))') As geom) As foo;
nrings | ninterrings
--------+-------------
1 | 0
(1 row)
ST_NumGeometries — Повертає кількість елементів у колекції геометрії.
integer ST_NumGeometries(geometry geom);
Повертає кількість елементів у колекції геометрій (GEOMETRYCOLLECTION або MULTI*). Для не порожніх атомарних геометрій повертає 1. Для порожніх геометрій повертає 0.
Покращено: 2.0.0 додано підтримку багатогранних поверхонь, трикутників і TIN.
Змінено: 2.0.0 У попередніх версіях це повертало NULL, якщо геометрія не була типом колекції/MULTI. 2.0.0+ тепер повертає 1 для одиночних геометрій, наприклад POLYGON, LINESTRING, POINT.
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).
--Prior versions would have returned NULL for this -- in 2.0.0 this returns 1
SELECT ST_NumGeometries(ST_GeomFromText('LINESTRING(77.29 29.07,77.42 29.26,77.27 29.31,77.29 29.07)'));
--result
1
--Geometry Collection Example - multis count as one geom in a collection
SELECT ST_NumGeometries(ST_GeomFromEWKT('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)))'));
--result
3
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 - у попередніх версіях дозволялося передавати MULTIPOLYGON, повертаючи кількість внутрішніх кілець першого POLYGON.
--If you have a regular polygon
SELECT gid, field1, field2, ST_NumInteriorRings(geom) AS numholes
FROM sometable;
--If you have multipolygons
--And you want to know the total number of interior rings in the MULTIPOLYGON
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 — Повертає кількість внутрішніх кілець (отворів) полігону. Aias для ST_NumInteriorRings
integer ST_NumInteriorRing(geometry a_polygon);
ST_NumPatches — Повертає кількість граней на багатогранній поверхні. Для небагатогранних геометрій повертає нуль.
integer ST_NumPatches(geometry g1);
Повертає кількість граней на багатогранній поверхні. Для геометрій, що не є багатогранними, повертає нуль. Це псевдонім для ST_NumGeometries для підтримки іменування MM. Якщо вам не важлива конвенція MM, швидше використовувати ST_NumGeometries.
Доступність: 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.
SELECT ST_NumPatches(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)) )'));
--result
6
ST_NumPoints — Повертає кількість точок у LineString або 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
SELECT ST_NumPoints(ST_GeomFromText('LINESTRING(77.29 29.07,77.42 29.26,77.27 29.31,77.29 29.07)'));
--result
4
ST_PatchN — Повертає N-ту геометрію (грань) багатогранної поверхні.
geometry ST_PatchN(geometry geomA, integer n);
Повертає N-ту геометрію (грань), починаючи з 1, якщо геометрія є POLYHEDRALSURFACE або POLYHEDRALSURFACEM. В іншому випадку повертає NULL. Повертає той самий результат, що й ST_GeometryN для PolyhedralSurfaces. Використання ST_GeometryN є швидшим.
![]() | |
Індекс починається з 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.
--Extract the 2nd face of the polyhedral surface
SELECT ST_AsEWKT(ST_PatchN(geom, 2)) As geomewkt
FROM (
VALUES (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 foo(geom);
geomewkt
---+-----------------------------------------
POLYGON((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0))
ST_AsEWKT, ST_GeomFromEWKT, ST_Dump, ST_GeometryN, ST_NumGeometries
ST_PointN — Повертає N-ту точку в першому LineString або круговому LineString в геометрії.
geometry ST_PointN(geometry a_linestring, integer n);
Повертає N-ту точку в одній лінійній або круговій лінійній геометрії. Негативні значення відраховуються назад від кінця LineString, так що -1 є останньою точкою. Повертає NULL, якщо в геометрії немає лінійної геометрії.
![]() | |
Індекс починається з 1, як і в специфікаціях OGC, починаючи з версії 0.8.0. Зворотне індексування (негативний індекс) не передбачено в OGC. У попередніх версіях це реалізовано як індекс, що починається з 0. |
![]() | |
Якщо ви хочете отримати N-ту точку кожного LineString у MultiLineString, використовуйте разом із 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 — останній пункт) |
-- Extract all POINTs from a LINESTRING
SELECT ST_AsText(
ST_PointN(
column1,
generate_series(1, ST_NPoints(column1))
))
FROM ( VALUES ('LINESTRING(0 0, 1 1, 2 2)'::geometry) ) AS foo;
st_astext
------------
POINT(0 0)
POINT(1 1)
POINT(2 2)
(3 rows)
--Example circular string
SELECT ST_AsText(ST_PointN(ST_GeomFromText('CIRCULARSTRING(1 2, 3 2, 1 2)'), 2));
st_astext
------------
POINT(3 2)
(1 row)
SELECT ST_AsText(f)
FROM ST_GeomFromText('LINESTRING(0 0 0, 1 1 1, 2 2 2)') AS g
,ST_PointN(g, -2) AS f; -- 1 based index
st_astext
-----------------
POINT Z (1 1 1)
(1 row)
ST_Points — Повертає об'єкт MultiPoint, що містить координати геометрії.
geometry ST_Points( geometry geom );
Повертає MultiPoint, що містить усі координати геометрії. Дублікати точок зберігаються, включаючи початкову та кінцеву точки кільцевих геометрій. (За бажанням дублікати точок можна видалити, викликавши ST_RemoveRepeatedPoints на результаті).
Щоб отримати інформацію про положення кожної координати в батьківській геометрії, використовуйте ST_DumpPoints.
Координати M і Z зберігаються, якщо вони є.
This method supports Circular Strings and Curves.
This function supports 3d and will not drop the z-index.
Доступність: 2.3.0
SELECT ST_AsText(ST_Points('POLYGON Z ((30 10 4,10 30 5,40 40 6, 30 10))'));
--result
MULTIPOINT Z ((30 10 4),(10 30 5),(40 40 6),(30 10 4))
ST_StartPoint — Повертає першу точку LineString.
geometry ST_StartPoint(geometry geomA);
Повертає першу точку геометрії LINESTRING або CIRCULARLINESTRING як POINT. Повертає NULL, якщо вхідні дані не є LINESTRING або CIRCULARLINESTRING.
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.
![]() | |
Покращено: 3.2.0 повертає точку для всіх геометрій. Попередня поведінка повертала NULL, якщо вхідні дані не були LineString. Змінено: 2.0.0 більше не працює з одномірними геометричними об'єктами MultiLineStrings. У старих версіях PostGIS одномірний MultiLineString працював з цією функцією без проблем і повертав початкову точку. У 2.0.0 він просто повертає NULL, як і будь-який інший MultiLineString. Стара поведінка була недокументованою функцією, але користувачі, які вважали, що їхні дані зберігаються як LINESTRING, можуть зіткнутися з поверненням NULL у 2.0.0. |
Початкова точка лінії
SELECT ST_AsText(ST_StartPoint('LINESTRING(0 1, 0 2)'::geometry));
st_astext
------------
POINT(0 1)
Початкова точка нелінійного об'єкта LineString має значення NULL
SELECT ST_StartPoint('POINT(0 1)'::geometry) IS NULL AS is_null;
is_null
----------
t
Початкова точка 3D-лінії
SELECT ST_AsEWKT(ST_StartPoint('LINESTRING(0 1 1, 0 2 2)'::geometry));
st_asewkt
------------
POINT(0 1 1)
Початкова точка CircularString
SELECT ST_AsText(ST_StartPoint('CIRCULARSTRING(5 2,-3 1.999999, -2 1, -4 2, 6 3)'::geometry));
st_astext
------------
POINT(5 2)
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 і кривих
=# SELECT ST_Summary(ST_GeomFromText('LINESTRING(0 0, 1 1)')) as geom,
ST_Summary(ST_GeogFromText('POLYGON((0 0, 1 1, 1 2, 1 1, 0 0))')) geog;
geom | geog
-----------------------------+--------------------------
LineString[B] with 2 points | Polygon[BGS] with 1 rings
| ring 0 has 5 points
:
(1 row)
=# SELECT ST_Summary(ST_GeogFromText('LINESTRING(0 0 1, 1 1 1)')) As geog_line,
ST_Summary(ST_GeomFromText('SRID=4326;POLYGON((0 0 1, 1 1 2, 1 2 3, 1 1 1, 0 0 1))')) 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 — Повертає координату X точки.
float ST_X(geometry a_point);
Повертає координату X точки або NULL, якщо вона недоступна. Вхідні дані повинні бути точкою.
![]() | |
Щоб отримати мінімальне та максимальне значення X координат геометрії, використовуйте функції ST_XMin та 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.
SELECT ST_X(ST_GeomFromEWKT('POINT(1 2 3 4)'));
st_x
------
1
(1 row)
SELECT ST_Y(ST_Centroid(ST_GeomFromEWKT('LINESTRING(1 2 3 4, 1 1 1 1)')));
st_y
------
1.5
(1 row)
ST_Centroid, ST_GeomFromEWKT, ST_M, ST_XMax, ST_XMin, ST_Y, ST_Z
ST_Y — Повертає координату Y точки.
float ST_Y(geometry a_point);
Повертає координату Y точки або NULL, якщо вона недоступна. Вхідні дані повинні бути точкою.
![]() | |
Щоб отримати мінімальне та максимальне значення Y координат геометрії, використовуйте функції ST_YMin та 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.
SELECT ST_Y(ST_GeomFromEWKT('POINT(1 2 3 4)'));
st_y
------
2
(1 row)
SELECT ST_Y(ST_Centroid(ST_GeomFromEWKT('LINESTRING(1 2 3 4, 1 1 1 1)')));
st_y
------
1.5
(1 row)
ST_Centroid, ST_GeomFromEWKT, ST_M, ST_X, ST_YMax, ST_YMin, ST_Z
ST_Z — Повертає координату Z точки.
float ST_Z(geometry a_point);
Повертає координату Z точки або NULL, якщо вона недоступна. Вхідні дані повинні бути точкою.
![]() | |
Щоб отримати мінімальне та максимальне значення Z координат геометрії, використовуйте функції ST_ZMin та ST_ZMax. |
This method implements the SQL/MM specification.
This function supports 3d and will not drop the z-index.
SELECT ST_Z(ST_GeomFromEWKT('POINT(1 2 3 4)'));
st_z
------
3
(1 row)
ST_Zmflag — Повертає код, що вказує на розмірність координат ZM геометрії.
smallint ST_Zmflag(geometry geomA);
Повертає код, що вказує на розмірність координат ZM геометрії.
Значення: 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.
SELECT ST_Zmflag(ST_GeomFromEWKT('LINESTRING(1 2, 3 4)'));
st_zmflag
-----------
0
SELECT ST_Zmflag(ST_GeomFromEWKT('LINESTRINGM(1 2 3, 3 4 3)'));
st_zmflag
-----------
1
SELECT ST_Zmflag(ST_GeomFromEWKT('CIRCULARSTRING(1 2 3, 3 4 3, 5 6 3)'));
st_zmflag
-----------
2
SELECT ST_Zmflag(ST_GeomFromEWKT('POINT(1 2 3 4)'));
st_zmflag
-----------
3
ST_HasZ — Перевіряє, чи має геометрія розмір Z.
boolean ST_HasZ(geometry geom);
Перевіряє, чи має вхідна геометрія розмір Z, і повертає логічне значення. Якщо геометрія має розмір Z, повертає true; інакше повертає false.
Геометричні об'єкти з розміром Z зазвичай представляють тривимірні (3D) геометрії, тоді як об'єкти без цього розміру є двовимірними (2D) геометріями.
Ця функція корисна для визначення, чи має геометрія інформацію про висоту.
Доступність: 3.5.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
SELECT ST_HasZ(ST_GeomFromText('POINT(1 2 3)'));
--result
true
SELECT ST_HasZ(ST_GeomFromText('LINESTRING(0 0, 1 1)'));
--result
false
ST_HasM — Перевіряє, чи має геометрія розмір M (вимір).
boolean ST_HasM(geometry geom);
Перевіряє, чи має вхідна геометрія розмір M (вимір), і повертає булеве значення. Якщо геометрія має розмір M, повертає true; інакше повертає false.
Геометричні об'єкти з розмірністю M зазвичай представляють вимірювання або додаткові дані, пов'язані з просторовими характеристиками.
Ця функція корисна для визначення, чи містить геометрія інформацію про виміри.
Доступність: 3.5.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
SELECT ST_HasM(ST_GeomFromText('POINTM(1 2 3)'));
--result
true
SELECT ST_HasM(ST_GeomFromText('LINESTRING(0 0, 1 1)'));
--result
false
Ці функції створюють модифіковані геометрії шляхом зміни типу, структури або вершин.
ST_AddPoint — Додати точку до LineString.
geometry ST_AddPoint(geometry linestring, geometry point);
geometry ST_AddPoint(geometry linestring, geometry point, integer position = -1);
Додає точку до LineString перед індексом position (використовуючи індекс, що починається з 0). Якщо параметр position пропущено або дорівнює -1, точка додається в кінець LineString.
Доступність: 1.1.0
This function supports 3d and will not drop the z-index.
Додати точку в кінець 3D лінії
SELECT ST_AsEWKT(ST_AddPoint('LINESTRING(0 0 1, 1 1 1)', ST_MakePoint(1, 2, 3)));
st_asewkt
----------
LINESTRING(0 0 1,1 1 1,1 2 3)
Гарантуйте, що всі лінії в таблиці закриті, додавши початкову точку кожної лінії до кінця лінії тільки для тих, які не закриті.
UPDATE sometable SET geom = ST_AddPoint(geom, ST_StartPoint(geom)) FROM sometable WHERE ST_IsClosed(geom) = false;
ST_CollectionExtract — За заданою колекцією геометрій повертає мультигеометрію, що містить тільки елементи заданого типу.
geometry ST_CollectionExtract(geometry collection);
geometry ST_CollectionExtract(geometry collection, integer type);
За заданою колекцією геометрій повертає однорідну мультигеометрію.
Якщо type не вказано, повертає мультигеометрію, що містить тільки геометрії найвищого виміру. Тому полігони мають пріоритет над лініями, які мають пріоритет над точками.
Якщо вказано type, повертає мультигеометрію, що містить тільки цей тип. Якщо немає підгеометрій потрібного типу, повертається геометрія EMPTY. Підтримуються тільки точки, лінії та полігони. Номери типів:
1 == POINT
2 == LINESTRING
3 == POLYGON
Для вхідних даних атомарної геометрії геометрія повертається без змін, якщо тип вхідних даних відповідає запитуваному типу. В іншому випадку результатом є геометрія EMPTY заданого типу. За необхідності їх можна перетворити на мультигеометрії за допомогою ST_Multi.
![]() | |
Результати MultiPolygon не перевіряються на валідність. Якщо компоненти полігону є суміжними або перекриваються, результат буде недійсним. (Наприклад, це може статися при застосуванні цієї функції до результату ST_Split.) Цю ситуацію можна перевірити за допомогою ST_IsValid і виправити за допомогою ST_MakeValid. |
Доступність: 1.5.0
![]() | |
До версії 1.5.3 ця функція повертала атомарні вхідні дані без змін, незалежно від типу. У версії 1.5.3 невідповідні одиничні геометрії повертали результат NULL. У версії 2.0.0 невідповідні одиничні геометрії повертають результат EMPTY запитуваного типу. |
Витяг типу найвищого виміру:
SELECT ST_AsText(ST_CollectionExtract(
'GEOMETRYCOLLECTION( POINT(0 0), LINESTRING(1 1, 2 2) )'));
st_astext
---------------
MULTILINESTRING((1 1, 2 2))
Витягнути точки (тип 1 == POINT):
SELECT ST_AsText(ST_CollectionExtract(
'GEOMETRYCOLLECTION(GEOMETRYCOLLECTION(POINT(0 0)))',
1 ));
st_astext
---------------
MULTIPOINT((0 0))
Витягнути лінії (тип 2 == LINESTRING):
SELECT ST_AsText(ST_CollectionExtract(
'GEOMETRYCOLLECTION(GEOMETRYCOLLECTION(LINESTRING(0 0, 1 1)),LINESTRING(2 2, 3 3))',
2 ));
st_astext
---------------
MULTILINESTRING((0 0, 1 1), (2 2, 3 3))
ST_CollectionHomogenize — Повертає найпростіше представлення колекції геометрії.
geometry ST_CollectionHomogenize(geometry collection);
За заданою колекцією геометрії повертає "найпростіше" представлення вмісту.
Однорідні (однотипні) колекції повертаються як відповідна мультигеометрія.
Гетерогенні (змішані) колекції об'єднуються в одну колекцію GeometryCollection.
Колекції, що містять один атомарний елемент, повертаються як цей елемент.
Атомарні геометрії повертаються без змін. При необхідності їх можна перетворити на мультигеометрії за допомогою ST_Multi.
![]() | |
Ця функція не гарантує, що результат є дійсним. Зокрема, колекція, що містить сусідні або перекриваються полігони, створить недійсний MultiPolygon. Цю ситуацію можна перевірити за допомогою ST_IsValid і виправити за допомогою ST_MakeValid. |
Доступність: 2.0.0
Одноелементна колекція, перетворена в атомарну геометрію
SELECT ST_AsText(ST_CollectionHomogenize('GEOMETRYCOLLECTION(POINT(0 0))'));
st_astext
------------
POINT(0 0)
Вкладена колекція з одним елементом, перетворена в атомарну геометрію:
SELECT ST_AsText(ST_CollectionHomogenize('GEOMETRYCOLLECTION(MULTIPOINT((0 0)))'));
st_astext
------------
POINT(0 0)
Колекція перетворена на багатогеометрію:
SELECT ST_AsText(ST_CollectionHomogenize('GEOMETRYCOLLECTION(POINT(0 0),POINT(1 1))'));
st_astext
---------------------
MULTIPOINT((0 0),(1 1))
Вкладені неоднорідні колекції, сплощені до GeometryCollection:
SELECT ST_AsText(ST_CollectionHomogenize('GEOMETRYCOLLECTION(POINT(0 0), GEOMETRYCOLLECTION( LINESTRING(1 1, 2 2)))'));
st_astext
---------------------
GEOMETRYCOLLECTION(POINT(0 0),LINESTRING(1 1,2 2))
Колекція полігонів, перетворених у (недійсний) MultiPolygon:
SELECT ST_AsText(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)))'));
st_astext
---------------------
MULTIPOLYGON(((10 50,50 50,50 10,10 10,10 50)),((90 50,90 10,50 10,50 50,90 50)))
ST_CurveToLine — Перетворює геометрію, що містить криві, на лінійну геометрію.
geometry ST_CurveToLine(geometry curveGeom, float tolerance, integer tolerance_type, integer flags);
Перетворює CIRCULAR STRING у звичайний LINESTRING або CURVEPOLYGON у POLYGON або MULTISURFACE у MULTIPOLYGON. Корисно для виведення на пристрої, які не підтримують типи геометрії CIRCULARSTRING
Перетворює задану геометрію в лінійну геометрію. Кожна крива геометрія або сегмент перетворюється в лінійне наближення з використанням заданого `допуску` та опцій (32 сегменти на квадрант і жодних опцій за замовчуванням).
Аргумент "tolerance_type" визначає інтерпретацію аргументу "tolerance". Він може приймати наступні значення:
0 (за замовчуванням): Допустиме відхилення — максимальна кількість сегментів на квадрант.
1: Допуск — це максимальне відхилення лінії від кривої в одиницях джерела.
2: Допуск — це максимальний кут, виражений в радіанах, між радіусами, що утворюють.
Аргумент "flags" є бітовим полем. За замовчуванням має значення 0. Підтримуються такі біти:
1: Симетричний (незалежний від орієнтації) вихід.
2: Зберігає кут, запобігає зменшенню кутів (довжини сегментів) під час створення симетричного виводу. Не діє, якщо прапор Symmetric вимкнено.
Доступність: 1.3.0
Покращено: у версії 2.4.0 додано підтримку максимального відхилення та максимального кута допуску, а також симетричного виводу.
Покращено: у версії 3.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: 7.1.7
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves.
SELECT ST_AsText(ST_CurveToLine(ST_GeomFromText('CIRCULARSTRING(220268 150415,220227 150505,220227 150406)')));
--Result --
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)
--3d example
SELECT ST_AsEWKT(ST_CurveToLine(ST_GeomFromEWKT('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)')));
Output
------
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
SELECT ST_AsText(ST_CurveToLine(ST_GeomFromText('CIRCULARSTRING(220268 150415,220227 150505,220227 150406)'),2));
st_astext
------------------------------
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)
-- Ensure approximated line is no further than 20 units away from
-- original curve, and make the result direction-neutral
SELECT ST_AsText(ST_CurveToLine(
'CIRCULARSTRING(0 0,100 -100,200 0)'::geometry,
20, -- Tolerance
1, -- Above is max distance between curve and line
1 -- Symmetric flag
));
st_astext
-------------------------------------------------------------------------------------------
LINESTRING(0 0,50 -86.6025403784438,150 -86.6025403784439,200 -1.1331077795296e-13,200 0)
ST_Scroll — Змінити початкову точку замкнутої лінії LineString.
geometry ST_Scroll(geometry linestring, geometry point);
Змінює початкову/кінцеву точку замкнутої лінії LineString на задану вершину point.
Доступність: 3.2.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
Зробіть закриту лінію, починаючи з її третьої вершини
SELECT ST_AsEWKT(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)'));
st_asewkt
----------
SRID=4326;LINESTRING(5 5 4 2,0 0 0 1,10 0 2 0,5 5 4 2)
ST_FlipCoordinates — Повертає версію геометрії з перевернутими осями X та Y.
geometry ST_FlipCoordinates(geometry geom);
Повертає версію заданої геометрії з перевернутими осями X та Y. Корисно для виправлення геометрій, які містять координати, виражені у вигляді широти/довготи (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).
SELECT ST_AsEWKT(ST_FlipCoordinates(GeomFromEWKT('POINT(1 2)')));
st_asewkt
------------
POINT(2 1)
ST_Force2D — Примусово переведіть геометрії в "2-вимірний режим".
geometry ST_Force2D(geometry geomA);
Примусово переводить геометрії в "двовимірний режим", щоб усі вихідні представлення мали тільки координати X і Y. Це корисно для виведення даних, сумісних із OGC (оскільки OGC визначає тільки двовимірні геометрії).
Покращено: 2.0.0 додано підтримку багатогранних поверхонь.
Змінено: 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.
SELECT ST_AsEWKT(ST_Force2D(ST_GeomFromEWKT('CIRCULARSTRING(1 1 2, 2 3 2, 4 5 2, 6 7 2, 5 6 2)')));
st_asewkt
-------------------------------------
CIRCULARSTRING(1 1,2 3,4 5,6 7,5 6)
SELECT ST_AsEWKT(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))'));
st_asewkt
----------------------------------------------
POLYGON((0 0,0 5,5 0,0 0),(1 1,3 1,1 3,1 1))
ST_Force3D — Примусово перевести геометрії в режим XYZ. Це псевдонім для ST_Force3DZ.
geometry ST_Force3D(geometry geomA, float Zvalue = 0.0);
Примусово переводить геометрії в режим XYZ. Це псевдонім для ST_Force3DZ. Якщо геометрія не має компонента Z, то додається координата Z Zvalue.
Покращено: 2.0.0 додано підтримку багатогранних поверхонь.
Змінено: 2.1.0. До версії 2.0.x це називалося ST_Force_3D.
Змінено: 3.1.0. Додано підтримку для надання значення Z, відмінного від нуля.
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
SELECT ST_AsEWKT(ST_Force3D(ST_GeomFromEWKT('CIRCULARSTRING(1 1 2, 2 3 2, 4 5 2, 6 7 2, 5 6 2)')));
st_asewkt
-----------------------------------------------
CIRCULARSTRING(1 1 2,2 3 2,4 5 2,6 7 2,5 6 2)
SELECT ST_AsEWKT(ST_Force3D('POLYGON((0 0,0 5,5 0,0 0),(1 1,3 1,1 3,1 1))'));
st_asewkt
--------------------------------------------------------------
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))
ST_Force3DZ — Примусово перевести геометрії в режим XYZ.
geometry ST_Force3DZ(geometry geomA, float Zvalue = 0.0);
Примусово переводить геометрії в режим XYZ. Якщо геометрія не має компонента Z, то додається координата Z Zvalue.
Покращено: 2.0.0 додано підтримку багатогранних поверхонь.
Змінено: 2.1.0. До версії 2.0.x це називалося ST_Force_3DZ.
Змінено: 3.1.0. Додано підтримку для надання значення Z, відмінного від нуля.
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
SELECT ST_AsEWKT(ST_Force3DZ(ST_GeomFromEWKT('CIRCULARSTRING(1 1 2, 2 3 2, 4 5 2, 6 7 2, 5 6 2)')));
st_asewkt
-----------------------------------------------
CIRCULARSTRING(1 1 2,2 3 2,4 5 2,6 7 2,5 6 2)
SELECT ST_AsEWKT(ST_Force3DZ('POLYGON((0 0,0 5,5 0,0 0),(1 1,3 1,1 3,1 1))'));
st_asewkt
--------------------------------------------------------------
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))
ST_Force3DM — Примусово перевести геометрії в режим XYM.
geometry ST_Force3DM(geometry geomA, float Mvalue = 0.0);
Примусово переводить геометрії в режим XYM. Якщо геометрія не має компонента M, то додається координата Mvalue M. Якщо вона має компонент Z, то Z видаляється
Змінено: 2.1.0. До версії 2.0.x це називалося ST_Force_3DM.
Змінено: 3.1.0. Додано підтримку для надання значення M, відмінного від нуля.
This method supports Circular Strings and Curves.
--Nothing happens to an already 3D geometry
SELECT ST_AsEWKT(ST_Force3DM(ST_GeomFromEWKT('CIRCULARSTRING(1 1 2, 2 3 2, 4 5 2, 6 7 2, 5 6 2)')));
st_asewkt
------------------------------------------------
CIRCULARSTRINGM(1 1 0,2 3 0,4 5 0,6 7 0,5 6 0)
SELECT ST_AsEWKT(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))'));
st_asewkt
---------------------------------------------------------------
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))
ST_AsEWKT, ST_Force2D, ST_Force3DM, ST_Force3D, ST_GeomFromEWKT
ST_Force4D — Примусово перевести геометрії в режим XYZM.
geometry ST_Force4D(geometry geomA, float Zvalue = 0.0, float Mvalue = 0.0);
Примусово переводить геометрії в режим XYZM. Zvalue та Mvalue додаються для відсутніх розмірів Z та M відповідно.
Змінено: 2.1.0. До версії 2.0.x це називалося ST_Force_4D.
Змінено: 3.1.0. Додано підтримку для надання ненульових значень Z та M.
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
SELECT ST_AsEWKT(ST_Force4D(ST_GeomFromEWKT('CIRCULARSTRING(1 1 2, 2 3 2, 4 5 2, 6 7 2, 5 6 2)')));
st_asewkt
---------------------------------------------------------
CIRCULARSTRING(1 1 2 0,2 3 2 0,4 5 2 0,6 7 2 0,5 6 2 0)
SELECT ST_AsEWKT(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))'));
st_asewkt
--------------------------------------------------------------------------------------
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))
ST_ForceCollection — Перетворити геометрію в GEOMETRYCOLLECTION.
geometry ST_ForceCollection(geometry geomA);
Перетворює геометрію в GEOMETRYCOLLECTION. Це корисно для спрощення представлення WKB.
Покращено: 2.0.0 додано підтримку багатогранних поверхонь.
Доступність: 1.2.2, до версії 1.3.4 ця функція буде виходити з ладу з кривими. Ця проблема вирішена в версії 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.
SELECT ST_AsEWKT(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))'));
st_asewkt
----------------------------------------------------------------------------------
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)))
SELECT ST_AsText(ST_ForceCollection('CIRCULARSTRING(220227 150406,2220227 150407,220227 150406)'));
st_astext
--------------------------------------------------------------------------------
GEOMETRYCOLLECTION(CIRCULARSTRING(220227 150406,2220227 150407,220227 150406))
(1 row)
-- POLYHEDRAL example --
SELECT ST_AsEWKT(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)))'))
st_asewkt
----------------------------------------------------------------------------------
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))
)
ST_AsEWKT, ST_Force2D, ST_Force3DM, ST_Force3D, ST_GeomFromEWKT
ST_ForceCurve — Перетворити геометрію в її вигнутий тип, якщо це можливо.
geometry ST_ForceCurve(geometry g);
Перетворює геометрію в її криве представлення, якщо це можливо: лінії стають складеними кривими, мультилінії стають мультикривими, полігони стають криволінійними полігонами, мультиполігоанми стають багатоповерхневими. Якщо вхідна геометрія вже є кривим представленням, повертається те саме, що і вхідні дані.
Доступність: 2.2.0
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves.
SELECT ST_AsText(
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
)
);
st_astext
----------------------------------------------------------------------
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))
(1 row)ST_ForcePolygonCCW — Всі зовнішні кільця орієнтуйте проти годинникової стрілки, а всі внутрішні кільця — за годинниковою стрілкою.
geometry ST_ForcePolygonCCW ( geometry geom );
Змушує (Мульти)Полігони) використовувати орієнтацію проти годинникової стрілки для зовнішнього кільця та орієнтацію за годинниковою стрілкою для внутрішніх кілець. Неполігональні геометрії повертаються без змін.
Доступність: 2.4.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_ForcePolygonCW — Всі зовнішні кільця орієнтуйте за годинниковою стрілкою, а всі внутрішні кільця — проти годинникової стрілки.
geometry ST_ForcePolygonCW ( geometry geom );
Змушує (Мульти)Полігони) використовувати орієнтацію за годинниковою стрілкою для зовнішнього кільця та проти годинникової стрілки для внутрішніх кілець. Неполігональні геометрії повертаються без змін.
Доступність: 2.4.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_ForceSFS — Змусити геометрії використовувати тільки типи геометрії SFS 1.1.
geometry ST_ForceSFS(geometry geomA);
geometry ST_ForceSFS(geometry geomA, text version);
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.
ST_ForceRHR — Примусово встановити орієнтацію вершин полігону відповідно до правила правої руки.
geometry ST_ForceRHR(geometry g);
Примушує орієнтацію вершин полігону слідувати правилу правої руки, за яким область, обмежена полігоном, знаходиться праворуч від межі. Зокрема, зовнішнє кільце орієнтовано за годинниковою стрілкою, а внутрішні кільця - проти годинникової стрілки. Ця функція є синонімом ST_ForcePolygonCW
![]() | |
Вищезазначене визначення правила правої руки суперечить визначенням, що використовуються в інших контекстах. Щоб уникнути плутанини, рекомендується використовувати ST_ForcePolygonCW. |
Покращено: 2.0.0 додано підтримку багатогранних поверхонь.
This function supports 3d and will not drop the z-index.
This function supports Polyhedral surfaces.
SELECT ST_AsEWKT(
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))'
)
);
st_asewkt
--------------------------------------------------------------
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))
(1 row)ST_ForcePolygonCCW , ST_ForcePolygonCW , ST_IsPolygonCCW , ST_IsPolygonCW , ST_BuildArea, ST_Polygonize, ST_Reverse
ST_LineExtend — Повертає лінію, розширений вперед і назад на вказані відстані.
geometry ST_LineExtend(geometry line, float distance_forward, float distance_backward=0.0);
Повертає лінію, продовжену вперед і назад шляхом додавання нових початкових (і кінцевих) точок на заданій відстані (відстанях). Відстань, рівна нулю, не додає точку. Допускаються тільки невід'ємні відстані. Напрямок доданих точок визначається першими (і останніми) двома відмінними точками лінії. Повторювані точки ігноруються.
Доступність: 3.4.0
SELECT ST_AsText(ST_LineExtend('LINESTRING(0 0, 0 10)'::geometry, 5, 6));
--------------------------------------------
LINESTRING(0 -6,0 0,0 10,0 15)
ST_LineToCurve — Перетворює лінійну геометрію на криву геометрію.
geometry ST_LineToCurve(geometry geomANoncircular);
Перетворює прості LINESTRING/POLYGON в CIRCULAR STRINGs і вигнуті полігони. Зверніть увагу, що для опису вигнутого еквівалента потрібно набагато менше точок.
![]() | |
Якщо вхідні дані LINESTRING/POLYGON недостатньо вигнуті, щоб чітко відобразити криву, функція поверне ту саму вхідну геометрію. |
Доступність: 1.3.0
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves.
-- 2D Example
SELECT ST_AsText(ST_LineToCurve(foo.geom)) As curvedastext,ST_AsText(foo.geom) As non_curvedastext
FROM (SELECT ST_Buffer('POINT(1 3)'::geometry, 3) As geom) As foo;
curvedatext non_curvedastext
--------------------------------------------------------------------|-----------------------------------------------------------------
CURVEPOLYGON(CIRCULARSTRING(4 3,3.12132034355964 0.878679656440359, | POLYGON((4 3,3.94235584120969 2.41472903395162,3.77163859753386 1.85194970290473,
1 0,-1.12132034355965 5.12132034355963,4 3)) | 3.49440883690764 1.33328930094119,3.12132034355964 0.878679656440359,
| 2.66671069905881 0.505591163092366,2.14805029709527 0.228361402466141,
| 1.58527096604839 0.0576441587903094,1 0,
| 0.414729033951621 0.0576441587903077,-0.148050297095264 0.228361402466137,
| -0.666710699058802 0.505591163092361,-1.12132034355964 0.878679656440353,
| -1.49440883690763 1.33328930094119,-1.77163859753386 1.85194970290472
| --ETC-- ,3.94235584120969 3.58527096604839,4 3))
--3D example
SELECT ST_AsText(ST_LineToCurve(geom)) As curved, ST_AsText(geom) AS not_curved
FROM (SELECT ST_Translate(ST_Force3D(ST_Boundary(ST_Buffer(ST_Point(1,3), 2,2))),0,0,3) AS geom) AS foo;
curved | not_curved
------------------------------------------------------+---------------------------------------------------------------------
CIRCULARSTRING Z (3 3 3,-1 2.99999999999999 3,3 3 3) | LINESTRING Z (3 3 3,2.4142135623731 1.58578643762691 3,1 1 3,
| -0.414213562373092 1.5857864376269 3,-1 2.99999999999999 3,
| -0.414213562373101 4.41421356237309 3,
| 0.999999999999991 5 3,2.41421356237309 4.4142135623731 3,3 3 3)
(1 row)
ST_Multi — Повернути геометрію як геометрію MULTI*.
geometry ST_Multi(geometry geom);
Повертає геометрію як колекцію геометрії MULTI*. Якщо геометрія вже є колекцією, вона повертається без змін.
SELECT ST_AsText(ST_Multi('POLYGON ((10 30, 30 30, 30 10, 10 10, 10 30))'));
st_astext
-------------------------------------------------
MULTIPOLYGON(((10 30,30 30,30 10,10 10,10 30)))
ST_Normalize — Повернути геометрію в канонічній формі.
geometry ST_Normalize(geometry geom);
Повертає геометрію в нормалізованому/канонічному вигляді. Може змінювати порядок вершин у кільцях полігонів, кільцях у полігоні, елементах у багатогеометричному комплексі.
В основному корисний тільки для тестування (порівняння очікуваних і отриманих результатів).
Доступність: 2.3.0
SELECT ST_AsText(ST_Normalize(ST_GeomFromText(
'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)
)
)'
)));
st_astext
----------------------------------------------------------------------------------------------------------------------------------------------------
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))
(1 row)
ST_Project — Повертає точку, спроектовану від початкової точки на відстань і азимут.
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);
Повертає точку, спроектовану з точки вздовж геодезичної лінії з використанням заданої відстані та азимута (пеленга). Це відоме як пряма геодезична задача.
Двоточкова версія використовує шлях від першої до другої точки для неявного визначення азимута і використовує відстань, як і раніше.
Відстань вказана в метрах. Підтримуються від'ємні значення.
Азимут (також відомий як курс або пеленг) вимірюється в радіанах. Він вимірюється за годинниковою стрілкою від справжнього півночі.
Північ — це азимут нуль (0 градусів)
Схід — азимут π/2 (90 градусів)
Південь — азимут π (180 градусів)
Захід знаходиться на азимуті 3π/2 (270 градусів)
Підтримуються від'ємні значення азимута та значення, більші за 2π (360 градусів).
Доступність: 2.0.0
Покращено: 2.4.0 Дозволено негативну відстань і ненормалізований азимут.
Покращено: 3.4.0 Дозволено аргументи геометрії та двоточкову форму з пропуском азимута.
SELECT ST_AsText(ST_Project('POINT(0 0)'::geography, 100000, radians(45.0)));
--------------------------------------------
POINT(0.635231029125537 0.639472334729198)
ST_QuantizeCoordinates — Встановлює найменш значущі біти координат у нуль
geometry ST_QuantizeCoordinates ( geometry g , int prec_x , int prec_y , int prec_z , int prec_m );
ST_QuantizeCoordinates визначає кількість бітів (N), необхідних для представлення значення координати з заданою кількістю цифр після десяткової крапки, а потім встановлює всі біти, крім N найстарших, в нуль. Отримане значення координати все одно буде округлено до початкового значення, але його стисливість буде покращено. Це може призвести до значного зменшення використання дискового простору за умови, що стовпець геометрії використовує стисливий тип зберігання. Функція дозволяє вказати різну кількість цифр після десяткової крапки в кожному вимірі; невизначені виміри вважаються такими, що мають точність виміру x. Негативні цифри інтерпретуються як цифри ліворуч від десяткової крапки (тобто prec_x=-2 збереже значення координат з точністю до 100.
Координати, отримані за допомогою ST_QuantizeCoordinates, не залежать від геометрії, що містить ці координати, та відносного положення цих координат у геометрії. Як результат, використання цієї функції не впливає на існуючі топологічні відносини між геометріями. Функція може створити недійсну геометрію, якщо її викликати з кількістю цифр, меншою за внутрішню точність геометрії.
Доступність: 2.5.0
PostGIS зберігає всі значення координат у вигляді цілих чисел з подвійною точністю, які можуть надійно представляти 15 значущих цифр. Однак PostGIS може використовуватися для управління даними, які за своєю суттю мають менше 15 значущих цифр. Прикладом є дані TIGER, які надаються у вигляді географічних координат з точністю до шести цифр після десяткової крапки (отже, потрібно лише дев'ять значущих цифр довготи та вісім значущих цифр широти)
Коли доступно 15 значущих цифр, існує багато можливих представлень числа з 9 значущими цифрами. Число з подвійною точністю з плаваючою комою використовує 52 явних біти для представлення значущої частини (мантиси) координати. Для представлення мантиси з 9 значущими цифрами потрібно лише 30 бітів, що залишає 22 не значущих біти; ми можемо встановити їх значення на будь-яке, яке нам подобається, і все одно отримаємо число, яке округлюється до вхідного значення. Наприклад, значення 100,123456 можна представити числами з плаваючою комою, найближчими до 100,123456000000, 100,123456000001 та 100,123456432199. Усі вони є однаково дійсними, оскільки ST_AsText(geom, 6) поверне однаковий результат для будь-якого з цих вхідних значень. Оскільки ми можемо встановити ці біти на будь-яке значення, ST_QuantizeCoordinates встановлює 22 незначущі біти на нуль. Для довгої послідовності координат це створює шаблон блоків послідовних нулів, який PostgreSQL стискає більш ефективно.
![]() | |
На розмір геометрії на диску потенційно впливає лише |
SELECT ST_AsText(ST_QuantizeCoordinates('POINT (100.123456 0)'::geometry, 4));
st_astext
-------------------------
POINT(100.123455047607 0)
WITH test AS (SELECT 'POINT (123.456789123456 123.456789123456)'::geometry AS geom) SELECT digits, encode(ST_QuantizeCoordinates(geom, digits), 'hex'), ST_AsText(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 | 01010000005f9a72083cdd5e405f9a72083cdd5e40 | POINT(123.456789123456 123.456789123456) 12 | 01010000005c9a72083cdd5e405c9a72083cdd5e40 | POINT(123.456789123456 123.456789123456) 11 | 0101000000409a72083cdd5e40409a72083cdd5e40 | POINT(123.456789123456 123.456789123456) 10 | 0101000000009a72083cdd5e40009a72083cdd5e40 | POINT(123.456789123455 123.456789123455) 9 | 0101000000009072083cdd5e40009072083cdd5e40 | POINT(123.456789123418 123.456789123418) 8 | 0101000000008072083cdd5e40008072083cdd5e40 | POINT(123.45678912336 123.45678912336) 7 | 0101000000000070083cdd5e40000070083cdd5e40 | POINT(123.456789121032 123.456789121032) 6 | 0101000000000040083cdd5e40000040083cdd5e40 | POINT(123.456789076328 123.456789076328) 5 | 0101000000000000083cdd5e40000000083cdd5e40 | POINT(123.456789016724 123.456789016724) 4 | 0101000000000000003cdd5e40000000003cdd5e40 | POINT(123.456787109375 123.456787109375) 3 | 0101000000000000003cdd5e40000000003cdd5e40 | POINT(123.456787109375 123.456787109375) 2 | 01010000000000000038dd5e400000000038dd5e40 | POINT(123.45654296875 123.45654296875) 1 | 01010000000000000000dd5e400000000000dd5e40 | POINT(123.453125 123.453125) 0 | 01010000000000000000dc5e400000000000dc5e40 | POINT(123.4375 123.4375) -1 | 01010000000000000000c05e400000000000c05e40 | POINT(123 123) -2 | 01010000000000000000005e400000000000005e40 | POINT(120 120) -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)
ST_RemovePoint — Видалити точку з лінії.
geometry ST_RemovePoint(geometry linestring, integer offset);
Видаляє точку з LineString, задавши її індекс (починаючи з 0). Корисно для перетворення замкнутої лінії (кільця) у відкриту лінію.
Покращено: 3.2.0
Доступність: 1.1.0
This function supports 3d and will not drop the z-index.
Гарантує, що лінії не будуть закриті, видаляючи кінцеву точку закритих ліній (кільця). Припускає, що геометрична фігура має тип LINESTRING
UPDATE sometable
SET geom = ST_RemovePoint(geom, ST_NPoints(geom) - 1)
FROM sometable
WHERE ST_IsClosed(geom);
ST_RemoveRepeatedPoints — Повертає версію геометрії з видаленими дублікатами точок.
geometry ST_RemoveRepeatedPoints(geometry geom, float8 tolerance = 0.0);
Повертає версію заданої геометрії з видаленими дублюючими послідовними точками. Функція обробляє тільки (Multi)LineStrings, (Multi)Polygons і MultiPoints, але її можна викликати з будь-яким типом геометрії. Елементи GeometryCollections обробляються індивідуально. Кінцеві точки LineStrings зберігаються.
Якщо вказано ненульовий параметр tolerance, вершини, що знаходяться на відстані, яка не перевищує допуск, вважаються дублікатами. Відстань обчислюється у 2D (площина XY).
Покращено: 3.2.0
Доступність: 2.2.0
This function supports Polyhedral surfaces.
This function supports 3d and will not drop the z-index.
SELECT ST_AsText( ST_RemoveRepeatedPoints( 'MULTIPOINT ((1 1), (2 2), (3 3), (2 2))')); ------------------------- MULTIPOINT(1 1,2 2,3 3)
SELECT ST_AsText( 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)
Приклад: Елементи колекції обробляються окремо.
SELECT ST_AsText( 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))
Приклад: Повторне видалення точок з допуском відстані.
SELECT ST_AsText( ST_RemoveRepeatedPoints( 'LINESTRING (0 0, 0 0, 1 1, 5 5, 1 1, 2 2)', 2)); ------------------------- LINESTRING(0 0,5 5,2 2)
ST_RemoveIrrelevantPointsForView — Видаляє точки, які не мають значення для візуалізації певного прямокутного виду геометрії.
geometry ST_RemoveIrrelevantPointsForView(geometry geom, box2d bounds, boolean cartesian_hint = false);
Повертає geometryбез точок, що не мають значення для візуалізації геометрії в заданому прямокутному вікні.
Ця функція може бути використана для швидкої попередньої обробки геометрій, які повинні бути відтворені тільки в певних межах.
Оцінюються тільки геометрії типу (MULTI)POLYGON і (MULTI)LINESTRING. Інші геометрії залишаються без змін.
На відміну від ST_ClipByBox2D(), ця функція
сортує точки без обчислення нових точок перетину, що дозволяє уникнути помилок округлення і, як правило, підвищує продуктивність,
повертає геометрію з однаковою або схожою кількістю точок,
призводить до однакового результату візуалізації в межах заданого виду, і
може призвести до самоперетину, що зробить отриману геометрію недійсною (див. приклад нижче).
Якщо cartesian_hint встановлено на true, алгоритм застосовує додаткові оптимізації, що включають декартову математику, для подальшого зменшення кількості отриманих точок. Зверніть увагу, що використання цієї опції може призвести до появи артефактів рендерингу, якщо отримані координати перед рендерингом проектуються в іншу (не декартову) систему координат.
![]() | |
Для полігонів ця функція наразі не гарантує, що результат є дійсним. Цю ситуацію можна перевірити за допомогою ST_IsValid та виправити за допомогою ST_MakeValid. |

Приклад: ST_RemoveIrrelevantPointsForView() застосовано до полігону. Сині точки залишаються, результат візуалізації (світло-синя область) у сірій області перегляду також залишається.

Приклад: Оскільки точки лише сортуються і нові точки не обчислюються, результат функції ST_RemoveIrrelevantPointsForView() може містити самоперетини.
Доступність: 3.5.0
SELECT ST_AsText(
ST_RemoveIrrelevantPointsForView(
ST_GeomFromText('MULTIPOLYGON(((10 10, 20 10, 30 10, 40 10, 20 20, 10 20, 10 10)),((10 10, 20 10, 20 20, 10 20, 10 10)))'),
ST_MakeEnvelope(12,12,18,18), true));
st_astext
---------
MULTIPOLYGON(((10 10,40 10,20 20,10 20,10 10)),((10 10,20 10,20 20,10 20,10 10)))
SELECT ST_AsText(
ST_RemoveIrrelevantPointsForView(
ST_GeomFromText('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))'),
ST_MakeEnvelope(12,12,18,18), true));
st_astext
---------
MULTILINESTRING((10 15,15 15,20 15),(13 13,15 15,17 17))
SELECT ST_AsText(
ST_RemoveIrrelevantPointsForView(
ST_GeomFromText('LINESTRING(0 0, 10 0,20 0,30 0)'),
ST_MakeEnvelope(12,12,18,18), true));
st_astext
---------
LINESTRING EMPTY
SELECT ST_AsText(
ST_RemoveIrrelevantPointsForView(
ST_GeomFromText('POLYGON((0 30, 15 30, 30 30, 30 0, 0 0, 0 30))'),
ST_MakeEnvelope(12,12,18,18), true));
st_astext
---------
POLYGON((15 30,30 0,0 0,15 30))
SELECT ST_AsText(
ST_RemoveIrrelevantPointsForView(
ST_GeomFromText('POLYGON((0 30, 15 30, 30 30, 30 0, 0 0, 0 30))'),
ST_MakeEnvelope(12,12,18,18)));
st_astext
---------
POLYGON((0 30,30 30,30 0,0 0,0 30))
ST_RemoveSmallParts — Видаляє невеликі частини (кільця полігону або лінії) геометрії.
geometry ST_RemoveSmallParts(geometry geom, double precision minSizeX, double precision minSizeY);
Повертає geometry без дрібних частин (зовнішніх або внутрішніх кілець полігону або лінійних елементів).
Ця функція може бути використана як попередній етап обробки для створення спрощених карт, наприклад, для видалення невеликих островів або отворів.
Він оцінює тільки геометрії типу (MULTI)POLYGON і (MULTI)LINESTRING. Інші геометрії залишаються без змін.
Якщо minSizeX більше 0, частини сортуються, якщо їх ширина менше minSizeX.
Якщо minSizeY більше 0, деталі сортуються, якщо їх висота менше minSizeY.
Обидва параметри minSizeX та minSizeY вимірюються в одиницях системи координат геометрії.
Для типів полігонів оцінка проводиться окремо для кожного кільця, що може призвести до одного з наступних результатів:
оригінальна геометрія,
POLYGON з усіма кільцями з меншою кількістю вершин,
POLYGON зі зменшеною кількістю внутрішніх кілець (можливо, з меншою кількістю вершин),
POLYGON EMPTY, або
MULTIPOLYGON зі зменшеною кількістю полігонів (можливо, з меншою кількістю внутрішніх кілець або вершин), або
MULTIPOLYGON EMPTY.
Для типів лінійних рядків оцінка виконується для кожної лінії, що може призвести до одного з таких результатів:
оригінальна геометрія,
LINESTRING зі зменшеною кількістю вершин,
LINESTRING EMPTY,
MULTILINESTRING зі зменшеною кількістю лінійних ланцюгів (які можуть мати менше вершин), або
MULTILINESTRING EMPTY.

Приклад: ST_RemoveSmallParts() застосовано до мультиполігону. Сині частини залишаються.
Доступність: 3.5.0
SELECT ST_AsText(
ST_RemoveSmallParts(
ST_GeomFromText('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));
st_astext
---------
MULTIPOLYGON(((60 160,120 160,120 220,60 220,60 160)),((85 75,155 75,155 145,85 145,85 75)))
SELECT ST_AsText(
ST_RemoveSmallParts(
ST_GeomFromText('LINESTRING(10 10, 20 20)'),
50, 50));
st_astext
---------
LINESTRING EMPTY
ST_Reverse — Повернути геометрію з оберненим порядком вершин.
geometry ST_Reverse(geometry g1);
Може використовуватися для будь-якої геометрії та змінює порядок вершин.
Покращено: 2.4.0 додано підтримку кривих.
This function supports 3d and will not drop the z-index.
This function supports Polyhedral surfaces.
SELECT ST_AsText(geom) as line, ST_AsText(ST_Reverse(geom)) As reverseline
FROM
(SELECT ST_MakeLine(ST_Point(1,2),
ST_Point(1,10)) As geom) as foo;
--result
line | reverseline
---------------------+----------------------
LINESTRING(1 2,1 10) | LINESTRING(1 10,1 2)
ST_Segmentize — Повертає змінену геометрію/географію, в якій немає сегментів, довжина яких перевищує задану відстань.
geometry ST_Segmentize(geometry geom, float max_segment_length);
geography ST_Segmentize(geography geog, float max_segment_length);
Повертає змінену геометрію/географію, в якій немає сегментів довжиною більше max_segment_length. Довжина обчислюється у 2D. Сегменти завжди розділяються на підсегменти однакової довжини.
Для геометрії максимальна довжина вимірюється в одиницях просторової системи відліку.
Для географії максимальна довжина вимірюється в метрах. Відстані обчислюються на сфері. Додані вершини створюються вздовж дуг сферичного великого кола, визначених кінцевими точками відрізків.
![]() | |
Це тільки скорочує довгі сегменти. Сегменти, довжина яких не перевищує максимальну, не подовжуються. |
![]() | |
Для вхідних даних, що містять довгі сегменти, вказання відносно короткого |
Доступність: 1.2.2
Покращено: 3.0.0 Сегментація геометрії тепер створює підсегменти однакової довжини
Покращено: 2.3.0 Сегментація географії тепер створює підсегменти однакової довжини
Покращено: 2.1.0 додано підтримку географії.
Змінено: 2.1.0 В результаті впровадження підтримки географії використання ST_Segmentize(“LINESTRING(1 2, 3 4)”, 0.5) спричиняє помилку неоднозначної функції. Вхідні дані потрібно правильно вказати як геометрію або географію. Використовуйте ST_GeomFromText, ST_GeogFromText або перетворення до необхідного типу (наприклад, ST_Segmentize(“LINESTRING(1 2, 3 4)”::geometry, 0.5) )
Сегментація лінії. Довгі сегменти розділяються рівномірно, а короткі сегменти не розділяються.
SELECT ST_AsText(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))
Сегментація полігону:
SELECT ST_AsText(
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))
Сегментація географічної лінії з використанням максимальної довжини сегмента 2000 кілометрів. Вершини додаються вздовж дуги великого кола, що з'єднує кінцеві точки.
SELECT ST_AsText(
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)

Географічна лінія, сегментована вздовж дуги великого кола
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
SELECT ST_AsText(ST_SetPoint('LINESTRING(-1 2,-1 3)', 0, 'POINT(-1 1)'));
st_astext
-----------------------
LINESTRING(-1 1,-1 3)
---Change last point in a line string (lets play with 3d linestring this time)
SELECT ST_AsEWKT(ST_SetPoint(foo.geom, ST_NumPoints(foo.geom) - 1, ST_GeomFromEWKT('POINT(-1 1 3)')))
FROM (SELECT ST_GeomFromEWKT('LINESTRING(-1 2 3,-1 3 4, 5 6 7)') As geom) As foo;
st_asewkt
-----------------------
LINESTRING(-1 2 3,-1 3 4,-1 1 3)
SELECT ST_AsText(ST_SetPoint(g, -3, p))
FROM ST_GEomFromText('LINESTRING(0 0, 1 1, 2 2, 3 3, 4 4)') AS g
, ST_PointN(g,1) as p;
st_astext
-----------------------
LINESTRING(0 0,1 1,0 0,3 3,4 4)
ST_AddPoint, ST_NPoints, ST_NumPoints, ST_PointN, ST_RemovePoint
ST_ShiftLongitude — Змінює координати довготи геометрії в діапазоні від -180 до 180 і від 0 до 360.
geometry ST_ShiftLongitude(geometry geom);
Зчитує кожну точку/вершину в геометрії та зміщує її координату довготи з -180..0 на 180..360 і навпаки, якщо вона знаходиться в цих діапазонах. Ця функція є симетричною, тому результатом є представлення даних -180..180 у вигляді 0..360 та представлення даних 0..360 у вигляді -180..180.
![]() | |
Це корисно тільки для даних з координатами в довготі/широті; наприклад, SRID 4326 (географічна система WGS 84). |
![]() | |
Помилка версії до 1.3.4 заважала цій функції працювати з MULTIPOINT. Версія 1.3.4+ також працює з MULTIPOINT. |
This function supports 3d and will not drop the z-index.
Покращено: 2.0.0 додано підтримку багатогранних поверхонь та TIN.
ПРИМІТКА: ця функція була перейменована з "ST_Shift_Longitude" у версії 2.2.0
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
--single point forward transformation
SELECT ST_AsText(ST_ShiftLongitude('SRID=4326;POINT(270 0)'::geometry))
st_astext
----------
POINT(-90 0)
--single point reverse transformation
SELECT ST_AsText(ST_ShiftLongitude('SRID=4326;POINT(-90 0)'::geometry))
st_astext
----------
POINT(270 0)
--for linestrings the functions affects only to the sufficient coordinates
SELECT ST_AsText(ST_ShiftLongitude('SRID=4326;LINESTRING(174 12, 182 13)'::geometry))
st_astext
----------
LINESTRING(174 12,-178 13)
ST_WrapX — Оберніть геометрію навколо значення X.
geometry ST_WrapX(geometry geom, float8 wrap, float8 move);
Ця функція розділяє вхідні геометрії, а потім переміщує кожен отриманий компонент, що потрапляє праворуч (для від'ємного значення “move”) або ліворуч (для додатного значення “move”) від заданої лінії “wrap” у напрямку, визначеному параметром “move”, і нарешті знову об'єднує частини разом.
![]() | |
Це корисно для "перецентрування" вхідних даних довготи та широти, щоб об'єкти, що представляють інтерес, не з'являлися з одного боку на інший. |
Доступність: 2.3.0 вимагає GEOS
This function supports 3d and will not drop the z-index.
-- Move all components of the given geometries whose bounding box
-- falls completely on the left of x=0 to +360
select ST_WrapX(geom, 0, 360);
-- Move all components of the given geometries whose bounding box
-- falls completely on the left of x=-30 to +360
select ST_WrapX(geom, -30, 360);
ST_SnapToGrid — Прив'яжіть всі точки вхідної геометрії до регулярної сітки.
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: Прив'язати всі точки вхідної геометрії до сітки, визначеної її початком і розміром комірки. Видалити послідовні точки, що потрапляють на одну комірку, і в кінцевому підсумку повернути NULL, якщо вихідних точок недостатньо для визначення геометрії заданого типу. Зібрані геометрії в колекції видаляються з неї. Корисно для зменшення точності.
Варіант 4: Введено в версії 1.1.0 — прив'язує всі точки вхідної геометрії до сітки, визначеної її початком (другий аргумент, повинен бути точкою) і розмірами комірок. Вкажіть 0 як розмір для будь-якого виміру, який не потрібно прив'язувати до сітки.
![]() | |
Повернена геометрія може втратити свою простоту (див. ST_IsSimple). |
![]() | |
До версії 1.1.0 ця функція завжди повертала 2D-геометрію. Починаючи з версії 1.1.0, повернена геометрія матиме ту саму розмірність, що й вхідна, а значення вищих розмірностей залишатимуться незмінними. Використовуйте версію, що приймає другий аргумент геометрії, щоб визначити всі розмірності сітки. |
Доступність: 1.0.0RC1
Доступність: 1.1.0 - підтримка Z і M
This function supports 3d and will not drop the z-index.
--Snap your geometries to a precision grid of 10^-3
UPDATE mytable
SET geom = ST_SnapToGrid(geom, 0.001);
SELECT ST_AsText(ST_SnapToGrid(
ST_GeomFromText('LINESTRING(1.1115678 2.123, 4.111111 3.2374897, 4.11112 3.23748667)'),
0.001)
);
st_astext
-------------------------------------
LINESTRING(1.112 2.123,4.111 3.237)
--Snap a 4d geometry
SELECT ST_AsEWKT(ST_SnapToGrid(
ST_GeomFromEWKT('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)'),
ST_GeomFromEWKT('POINT(1.12 2.22 3.2 4.4444)'),
0.1, 0.1, 0.1, 0.01) );
st_asewkt
------------------------------------------------------------------------------
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)
--With a 4d geometry - the ST_SnapToGrid(geom,size) only touches x and y coords but keeps m and z the same
SELECT ST_AsEWKT(ST_SnapToGrid(ST_GeomFromEWKT('LINESTRING(-1.1115678 2.123 3 2.3456,
4.111111 3.2374897 3.1234 1.1111)'),
0.01) );
st_asewkt
---------------------------------------------------------
LINESTRING(-1.11 2.12 3 2.3456,4.11 3.24 3.1234 1.1111)
ST_Snap, ST_AsEWKT, ST_AsText, ST_GeomFromText, ST_GeomFromEWKT, ST_Simplify
ST_Snap — Прив'язати сегменти та вершини вхідної геометрії до вершин еталонної геометрії.
geometry ST_Snap(geometry input, geometry reference, float tolerance);
Прив'язує вершини та сегменти геометрії до вершин іншої геометрії. Для контролю місця прив'язки використовується допуск відстані прив'язки. Результатом є геометрія з прив'язаними вершинами. Якщо прив'язка не відбувається, геометрія залишається без змін.
З'єднання однієї геометрії з іншою може підвищити надійність операцій накладання, усуваючи майже збіжні краї (які спричиняють проблеми під час обчислення вузлів і перетинів).
Занадто часте прив'язування може призвести до створення некоректної топології, тому кількість і розташування прив'язаних вершин визначається за допомогою евристичних методів, які визначають, коли прив'язування є безпечним. Однак це може призвести до пропуску деяких потенційних прив'язок.
![]() | |
Повернена геометрія може втратити свою простоту (див. ST_IsSimple) та валідність (див. ST_IsValid). |
Виконується модулем GEOS.
Доступність: 2.0.0
![]() Мультиполігон, показаний лінією (до будь-якого прив'язування) | |
![]() Мультиполігон, прив'язаний до лінії з точністю до 1,01 відстані. Новий мультиполігону відображається з посиланням на лінію
SELECT ST_AsText(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;
polysnapped
---------------------------------------------------------------------
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)))
| ![]() Мультиполігон, прив'язаний до лінії з допуском: 1,25 відстані. Новий мультиполігон відображається з посиланням на лінію
SELECT ST_AsText(
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;
polysnapped
---------------------------------------------------------------------
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)))
|
![]() Лінія прив'язалася до вихідного мультиполігону з допуском 1,01 відстані. Нова лінія відображається з посиланням на мультиполігон
SELECT ST_AsText(
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;
linesnapped
----------------------------------------
LINESTRING(5 107,26 125,54 84,101 100)
| ![]() Лінія прив'язалася до вихідного мультиполігону з допуском 1,25 відстані. Нова лінія відображається з посиланням на мультиполігон
SELECT ST_AsText(
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;
linesnapped
---------------------------------------
LINESTRING(26 125,54 84,101 100)
|
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).
-- Scale M value by 2
SELECT ST_AsText(
ST_SwapOrdinates(
ST_Scale(
ST_SwapOrdinates(g,'xm'),
2, 1
),
'xm')
) FROM ( SELECT 'POINT ZM (0 0 0 2)'::geometry g ) foo;
st_astext
--------------------
POINT ZM (0 0 0 4)
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.
valid_detail row stating if a geometry is valid or if not a reason and a location.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 Section 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. |
SELECT ST_IsValid(ST_GeomFromText('LINESTRING(0 0, 1 1)')) As good_line,
ST_IsValid(ST_GeomFromText('POLYGON((0 0, 1 1, 1 2, 1 1, 0 0))')) As bad_poly
--results
NOTICE: Self-intersection at or near point 0 0
good_line | bad_poly
-----------+----------
t | f
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
--First 3 Rejects from a successful quintuplet experiment
SELECT gid, reason(ST_IsValidDetail(geom)), ST_AsText(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)
--simple example
SELECT * FROM ST_IsValidDetail('LINESTRING(220227 150406,2220227 150407,222020 150410)');
valid | reason | location
-------+--------+----------
t | |
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.
-- invalid bow-tie polygon
SELECT ST_IsValidReason(
'POLYGON ((100 200, 100 100, 200 200,
200 100, 100 200))'::geometry) as validity_info;
validity_info
--------------------------
Self-intersection[150 150]
--First 3 Rejects from a successful quintuplet experiment
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
SELECT ST_IsValidReason('LINESTRING(220227 150406,2220227 150407,222020 150410)');
st_isvalidreason
------------------
Valid Geometry
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 original algorithm, and builds valid geometries by first extracting all lines, noding that linework together, then building a value output from the linework.
"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 "keepcollapsed" key is only valid for the "structure" algorithm, and takes a value of "true" or "false". When set to "false", geometry components that collapse to a lower dimensionality, for example a one-point linestring would be dropped.
Виконується модулем 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.
![]() before_geom: MULTIPOLYGON of 2 overlapping polygons
![]() after_geom: MULTIPOLYGON of 4 non-overlapping polygons
![]() after_geom_structure: MULTIPOLYGON of 1 non-overlapping polygon
SELECT f.geom AS before_geom, ST_MakeValid(f.geom) AS after_geom, ST_MakeValid(f.geom, 'method=structure') AS after_geom_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 geom) AS f;
|
![]() before_geom: MULTIPOLYGON of 6 overlapping polygons
![]() after_geom: MULTIPOLYGON of 14 Non-overlapping polygons
![]() after_geom_structure: MULTIPOLYGON of 1 Non-overlapping polygon
SELECT c.geom AS before_geom,
ST_MakeValid(c.geom) AS after_geom,
ST_MakeValid(c.geom, 'method=structure') AS after_geom_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 geom) AS c;
|
SELECT ST_AsText(ST_MakeValid(
'LINESTRING(0 0, 0 0)',
'method=structure keepcollapsed=true'
));
st_astext
------------
POINT(0 0)
SELECT ST_AsText(ST_MakeValid(
'LINESTRING(0 0, 0 0)',
'method=structure keepcollapsed=false'
));
st_astext
------------------
LINESTRING EMPTYThese 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.
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.
Доступність: 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
-- Inverse direction
SELECT ST_AsText(ST_InverseTransformPipeline('POINT(426857.9877165967 5427937.523342293)'::geometry,
'urn:ogc:def:coordinateOperation:EPSG::16031')) AS wgs_geom;
wgs_geom
----------------------------
POINT(2 48.99999999999999)
(1 row)
GDA2020 example.
-- using ST_Transform with automatic selection of a conversion pipeline.
SELECT ST_AsText(ST_Transform('SRID=4939;POINT(143.0 -37.0)'::geometry, 7844)) AS gda2020_auto;
gda2020_auto
-----------------------------------------------
POINT(143.00000635638918 -36.999986706128176)
(1 row)
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 long lat --
SELECT ST_SetSRID(ST_Point(-123.365556, 48.428611),4326) As wgs84long_lat;
-- the ewkt representation (wrap with ST_AsEWKT) -
SRID=4326;POINT(-123.365556 48.428611)
-- Mark a point as WGS 84 long lat and then transform to web mercator (Spherical Mercator) --
SELECT ST_Transform(ST_SetSRID(ST_Point(-123.365556, 48.428611),4326),3785) As spere_merc;
-- the ewkt representation (wrap with ST_AsEWKT) -
SRID=3785;POINT(-13732990.8753491 6178458.96425423)
ST_SRID — Returns the spatial reference identifier for a geometry.
integer ST_SRID(geometry g1);
Повертає ідентифікатор просторової прив'язки для ST_Geometry, як визначено в таблиці spatial_ref_sys. Section 4.5, “Spatial Reference Systems”
![]() | |
Таблиця spatial_ref_sys — це таблиця, яка каталогізує всі системи просторових посилань, відомі PostGIS, і використовується для перетворення з однієї системи просторових посилань в іншу. Тому, якщо ви плануєте перетворювати геометрії, важливо перевірити, чи маєте ви правильний ідентифікатор системи просторових посилань. |
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.
SELECT ST_SRID(ST_GeomFromText('POINT(-71.1043 42.315)',4326));
--result
4326
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 ця функція виходила з ладу при використанні з геометріями, що містять КРИВІ. Ця проблема вирішена у версії 1.3.4+ |
Покращено: 2.0.0 додано підтримку багатогранних поверхонь.
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
SELECT ST_AsText(ST_Transform(ST_GeomFromText('POLYGON((743238 2967416,743238 2967450,
743265 2967450,743265.625 2967416,743238 2967416))',2249),4326)) As wgs_geom;
wgs_geom
---------------------------
POLYGON((-71.1776848522251 42.3902896512902,-71.1776843766326 42.3903829478009,
-71.1775844305465 42.3903826677917,-71.1775825927231 42.3902893647987,-71.177684
8522251 42.3902896512902));
(1 row)
--3D Circular String example
SELECT ST_AsEWKT(ST_Transform(ST_GeomFromEWKT('SRID=2249;CIRCULARSTRING(743238 2967416 1,743238 2967450 2,743265 2967450 3,743265.625 2967416 3,743238 2967416 4)'),4326));
st_asewkt
--------------------------------------------------------------------------------------
SRID=4326;CIRCULARSTRING(-71.1776848522251 42.3902896512902 1,-71.1776843766326 42.3903829478009 2,
-71.1775844305465 42.3903826677917 3,
-71.1775825927231 42.3902893647987 3,-71.1776848522251 42.3902896512902 4)
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.
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/
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_AsText(
ST_Transform(
ST_Intersection(ST_Transform(p1, gnom), ST_Transform(p2, gnom)),
gnom, 4326))
FROM data;
st_astext
--------------------------------------------------------------------------------
POLYGON((-170 74.053793645338,-141 73.4268621378904,-141 68,-170 68,-170 74.053793645338))
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:
+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:
+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:
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.
Доступність: 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
-- Forward direction
SELECT ST_AsText(ST_TransformPipeline('SRID=4326;POINT(2 49)'::geometry,
'urn:ogc:def:coordinateOperation:EPSG::16031')) AS utm_geom;
utm_geom
--------------------------------------------
POINT(426857.9877165967 5427937.523342293)
(1 row)
-- Inverse direction
SELECT ST_AsText(ST_InverseTransformPipeline('POINT(426857.9877165967 5427937.523342293)'::geometry,
'urn:ogc:def:coordinateOperation:EPSG::16031')) AS wgs_geom;
wgs_geom
----------------------------
POINT(2 48.99999999999999)
(1 row)
GDA2020 example.
-- using ST_Transform with automatic selection of a conversion pipeline.
SELECT ST_AsText(ST_Transform('SRID=4939;POINT(143.0 -37.0)'::geometry, 7844)) AS gda2020_auto;
gda2020_auto
-----------------------------------------------
POINT(143.00000635638918 -36.999986706128176)
(1 row)
-- using a defined conversion (EPSG:8447)
SELECT ST_AsText(ST_TransformPipeline('SRID=4939;POINT(143.0 -37.0)'::geometry,
'urn:ogc:def:coordinateOperation:EPSG::8447')) AS gda2020_code;
gda2020_code
----------------------------------------------
POINT(143.0000063280214 -36.999986718287545)
(1 row)
-- using a PROJ pipeline definition matching EPSG:8447, as returned from
-- 'projinfo -s EPSG:4939 -t EPSG:7844'.
-- NOTE: any 'axisswap' steps must be removed.
SELECT ST_AsText(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;
gda2020_pipeline
----------------------------------------------
POINT(143.0000063280214 -36.999986718287545)
(1 row)
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.
Доступність: 3.4.0
Proj version 6+
List the first ten codes associated with the EPSG authority.
SELECT * FROM postgis_srs_codes('EPSG') LIMIT 10;
postgis_srs_codes
-------------------
2000
20004
20005
20006
20007
20008
20009
2001
20010
20011
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.
Доступність: 3.4.0
Proj version 6+
Get the metadata for EPSG:3005.
SELECT * FROM postgis_srs('EPSG', '3005');
auth_name | EPSG
auth_srid | 3005
srname | NAD83 / BC Albers
srtext | PROJCS["NAD83 / BC Albers", ... ]]
proj4text | +proj=aea +lat_0=45 +lon_0=-126 +lat_1=50 +lat_2=58.5 +x_0=1000000 +y_0=0 +datum=NAD83 +units=m +no_defs +type=crs
point_sw | 0101000020E6100000E17A14AE476161C00000000000204840
point_ne | 0101000020E610000085EB51B81E855CC0E17A14AE47014E40
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.
Доступність: 3.4.0
Proj version 6+
Get the first 10 metadata records from the Proj database.
SELECT auth_name, auth_srid, srname FROM postgis_srs_all() LIMIT 10; auth_name | auth_srid | srname -----------+-----------+------------------------------------------ EPSG | 2000 | Anguilla 1957 / British West Indies Grid EPSG | 20004 | Pulkovo 1995 / Gauss-Kruger zone 4 EPSG | 20005 | Pulkovo 1995 / Gauss-Kruger zone 5 EPSG | 20006 | Pulkovo 1995 / Gauss-Kruger zone 6 EPSG | 20007 | Pulkovo 1995 / Gauss-Kruger zone 7 EPSG | 20008 | Pulkovo 1995 / Gauss-Kruger zone 8 EPSG | 20009 | Pulkovo 1995 / Gauss-Kruger zone 9 EPSG | 2001 | Antigua 1943 / British West Indies Grid EPSG | 20010 | Pulkovo 1995 / Gauss-Kruger zone 10 EPSG | 20011 | Pulkovo 1995 / Gauss-Kruger zone 11
postgis_srs_search — Return metadata records for projected coordinate systems that have areas of usage that fully contain the bounds parameter.
setof record postgis_srs_search(geometry bounds, text auth_name=EPSG);
Return a set of metadata records for projected coordinate systems that have areas of usage that fully contain the bounds parameter. Each record will have the auth_name, auth_srid, srname, srtext, proj4text, and the corners of the area of usage, point_sw and point_ne.
The search only looks for projected coordinate systems, and is intended for users to explore the possible systems that work for the extent of their data.
Доступність: 3.4.0
Proj version 6+
Search for projected coordinate systems in Louisiana.
SELECT auth_name, auth_srid, srname,
ST_AsText(point_sw) AS point_sw,
ST_AsText(point_ne) AS point_ne
FROM postgis_srs_search('SRID=4326;LINESTRING(-90 30, -91 31)')
LIMIT 3;
auth_name | auth_srid | srname | point_sw | point_ne
-----------+-----------+--------------------------------------+---------------------+---------------------
EPSG | 2801 | NAD83(HARN) / Louisiana South | POINT(-93.94 28.85) | POINT(-88.75 31.07)
EPSG | 3452 | NAD83 / Louisiana South (ftUS) | POINT(-93.94 28.85) | POINT(-88.75 31.07)
EPSG | 3457 | NAD83(HARN) / Louisiana South (ftUS) | POINT(-93.94 28.85) | POINT(-88.75 31.07)
Scan a table for max extent and find projected coordinate systems that might suit.
WITH ext AS ( SELECT ST_Extent(geom) AS geom, Max(ST_SRID(geom)) AS srid FROM foo ) SELECT auth_name, auth_srid, srname, ST_AsText(point_sw) AS point_sw, ST_AsText(point_ne) AS point_ne FROM ext CROSS JOIN postgis_srs_search(ST_SetSRID(ext.geom, ext.srid)) LIMIT 3;
Ці функції створюють геометричні об'єкти з різних текстових або бінарних форматів.
ST_BdPolyFromText — Побудувати полігон, заданий довільною сукупністю замкнутих лінійних відрізків у вигляді добре відомого текстового представлення MultiLineString.
geometry ST_BdPolyFromText(text WKT, integer srid);
Побудувати полігон, заданий довільною сукупністю замкнутих лінійних відрізків у вигляді добре відомого текстового представлення MultiLineString.
![]() | |
Видає помилку, якщо WKT не є MULTILINESTRING. Видає помилку, якщо вихідні дані є MULTIPOLYGON; у цьому випадку використовуйте ST_BdMPolyFromText або дивіться ST_BuildArea() для підходу, специфічного для postgis. |
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2
Виконується модулем GEOS.
Доступність: 1.1.0
ST_BdMPolyFromText — Побудувати мультиполігон на основі довільної сукупності замкнутих лінійних відрізків у вигляді текстового представлення MultiLineString. Загальновідоме текстове представлення.
geometry ST_BdMPolyFromText(text WKT, integer srid);
Побудувати полігон, заданий довільною сукупністю замкнутих ліній, полігонів, багатолінійних ліній у вигляді добре відомого текстового представлення.
![]() | |
Видає помилку, якщо WKT не є MULTILINESTRING. Примусово виводить MULTIPOLYGON, навіть якщо результат насправді складається лише з одного POLYGON; використовуйте ST_BdPolyFromText, якщо ви впевнені, що в результаті операції буде отримано один POLYGON, або дивіться ST_BuildArea() для підходу, специфічного для postgis. |
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2
Виконується модулем GEOS.
Доступність: 1.1.0
ST_GeogFromText — Повернути вказане географічне значення з представлення Well-Known Text або розширеного (WKT).
geography ST_GeogFromText(text EWKT);
Повертає географічний об'єкт із відомого тексту або розширеного відомого представлення. Якщо не вказано, використовується SRID 4326. Це псевдонім для ST_GeographyFromText. Точки завжди виражаються у форматі довготи та широти.
--- converting lon lat coords to geography
ALTER TABLE sometable ADD COLUMN geog geography(POINT,4326);
UPDATE sometable SET geog = ST_GeogFromText('SRID=4326;POINT(' || lon || ' ' || lat || ')');
--- specify a geography point using EPSG:4267, NAD27
SELECT ST_AsEWKT(ST_GeogFromText('SRID=4267;POINT(-77.0092 38.889588)'));
ST_GeographyFromText — Повернути вказане географічне значення з представлення Well-Known Text або розширеного (WKT).
geography ST_GeographyFromText(text EWKT);
Повертає географічний об'єкт із загальновідомого текстового представлення. Якщо не вказано, використовується SRID 4326.
ST_GeomCollFromText — Створює колекцію Geometry з колекції WKT із заданим SRID. Якщо SRID не задано, за замовчуванням використовується 0.
geometry ST_GeomCollFromText(text WKT, integer srid);
geometry ST_GeomCollFromText(text WKT);
Створює колекцію Geometry з представлення Well-Known-Text (WKT) із заданим SRID. Якщо SRID не вказано, за замовчуванням використовується 0.
OGC SPEC 3.2.6.2 — опція SRID взята з набору вимог відповідності
Повертає null, якщо WKT не є GEOMETRYCOLLECTION
![]() | |
Якщо ви абсолютно впевнені, що всі ваші геометрії 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.
SELECT ST_GeomCollFromText('GEOMETRYCOLLECTION(POINT(1 2),LINESTRING(1 2, 3 4))');
ST_GeomFromEWKT — Повернути вказане значення ST_Geometry з розширеного представлення добре відомого тексту (EWKT).
geometry ST_GeomFromEWKT(text EWKT);
Створює об'єкт PostGIS ST_Geometry з представлення OGC Extended Well-Known text (EWKT).
![]() | |
Формат EWKT не є стандартом OGC, а специфічним форматом PostGIS, що включає ідентифікатор просторової системи координат (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).
SELECT ST_GeomFromEWKT('SRID=4269;LINESTRING(-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932)');
SELECT ST_GeomFromEWKT('SRID=4269;MULTILINESTRING((-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932))');
SELECT ST_GeomFromEWKT('SRID=4269;POINT(-71.064544 42.28787)');
SELECT 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))');
SELECT 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)))');
--3d circular string
SELECT ST_GeomFromEWKT('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)');
--Polyhedral Surface example
SELECT 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))
)');
ST_GeomFromMARC21 — Приймає географічні дані MARC21/XML як вхідні дані та повертає геометричний об'єкт PostGIS.
geometry ST_GeomFromMARC21 ( text marcxml );
Ця функція створює геометрію PostGIS з запису MARC21/XML, який може містити POINT або POLYGON. У разі наявності декількох географічних даних в одному записі MARC21/XML, буде повернуто MULTIPOINT або MULTIPOLYGON. Якщо запис містить змішані типи геометрії, буде повернуто GEOMETRYCOLLECTION. Повертає NULL, якщо запис MARC21/XML не містить географічних даних (поле даних: 034).
Підтримувані версії LOC MARC21/XML:
Доступність: 3.3.0, вимагає libxml2 2.6+
![]() | |
Кодовані картографічні математичні дані MARC21/XML наразі не надають жодних засобів для опису просторової системи координат закодованих координат, тому ця функція завжди повертатиме геометрію з |
![]() | |
Повернуті геометрії |
Перетворення географічних даних MARC21/XML, що містять один POINT, закодований як hddd.dddddd
SELECT
ST_AsText(
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
>'));
st_astext
-------------------
POINT(-4.5 54.25)
(1 row)
Перетворення географічних даних MARC21/XML, що містять один POLYGON, закодований як hdddmmss
SELECT
ST_AsText(
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
>'));
st_astext
-----------------------------------------------------------------------------------------------------------------------
POLYGON((13.1 52.65,13.516666666666667 52.65,13.516666666666667 52.38333333333333,13.1 52.38333333333333,13.1 52.65))
(1 row)
Перетворення географічних даних MARC21/XML, що містять POLYGON та POINT:
SELECT
ST_AsText(
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
>'));
st_astext
-------------------------------------------------------------------------------------------------------------------------------------------------------------
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))
(1 row)
ST_GeometryFromText — Повертає вказане значення ST_Geometry з представлення Well-Known Text (WKT). Це псевдонім для ST_GeomFromText.
geometry ST_GeometryFromText(text WKT);
geometry ST_GeometryFromText(text WKT, integer srid);
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.4
ST_GeomFromText — Повертає вказане значення ST_Geometry з представлення Well-Known Text (WKT).
geometry ST_GeomFromText(text WKT);
geometry ST_GeomFromText(text WKT, integer srid);
Створює об'єкт PostGIS ST_Geometry на основі текстового представлення OGC Well-Known.
![]() | |
Існує два варіанти функції ST_GeomFromText. Перший не приймає SRID і повертає геометрію без визначеної системи просторових координат (SRID=0). Другий приймає SRID як другий аргумент і повертає геометрію, яка включає цей SRID як частину своїх метаданих. |
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2 - опція SRID належить до набору вимог відповідності.
This method implements the SQL/MM specification. SQL-MM 3: 5.1.4
This method supports Circular Strings and Curves.
![]() | |
Хоча ST_MakePoint не відповідає стандарту OGC, він працює швидше, ніж ST_GeomFromText і ST_PointFromText. Він також простіший у використанні для числових значень координат. ST_Point — це інший варіант, схожий за швидкістю на ST_MakePoint і сумісний з OGC, але підтримує тільки 2D-точки. |
![]() | |
Змінено: 2.0.0 У попередніх версіях PostGIS ST_GeomFromText(“GEOMETRYCOLLECTION(EMPTY)”) було дозволено. Тепер це є некоректним у PostGIS 2.0.0 для кращої відповідності стандартам SQL/MM. Тепер це слід писати як ST_GeomFromText(“GEOMETRYCOLLECTION EMPTY”) |
SELECT ST_GeomFromText('LINESTRING(-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932)');
SELECT ST_GeomFromText('LINESTRING(-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932)',4269);
SELECT ST_GeomFromText('MULTILINESTRING((-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932))');
SELECT ST_GeomFromText('POINT(-71.064544 42.28787)');
SELECT ST_GeomFromText('POLYGON((-71.1776585052917 42.3902909739571,-71.1776820268866 42.3903701743239,
-71.1776063012595 42.3903825660754,-71.1775826583081 42.3903033653531,-71.1776585052917 42.3902909739571))');
SELECT 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);
SELECT ST_GeomFromText('CIRCULARSTRING(220268 150415,220227 150505,220227 150406)');
ST_LineFromText — Створює геометрію з представлення WKT із заданим SRID. Якщо SRID не задано, за замовчуванням використовується 0.
geometry ST_LineFromText(text WKT);
geometry ST_LineFromText(text WKT, integer srid);
Створює геометрію з WKT із заданим SRID. Якщо SRID не вказано, за замовчуванням використовується 0. Якщо переданий WKT не є LINESTRING, повертається null.
![]() | |
OGC SPEC 3.2.6.2 — опція SRID належить до набору вимог відповідності. |
![]() | |
Якщо ви знаєте, що всі ваші геометрії є LINESTRINGS, ефективніше просто використовувати 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
SELECT ST_LineFromText('LINESTRING(1 2, 3 4)') AS aline, ST_LineFromText('POINT(1 2)') AS null_return;
aline | null_return
------------------------------------------------
010200000002000000000000000000F ... | t
ST_MLineFromText — Повернути вказане значення ST_MultiLineString з представлення WKT.
geometry ST_MLineFromText(text WKT, integer srid);
geometry ST_MLineFromText(text WKT);
Створює геометрію з добре відомого тексту (WKT) із заданим SRID. Якщо SRID не задано, за замовчуванням використовується 0.
OGC SPEC 3.2.6.2 — опція SRID взята з набору вимог відповідності
Повертає null, якщо WKT не є MULTILINESTRING
![]() | |
Якщо ви абсолютно впевнені, що всі ваші геометрії 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
SELECT ST_MLineFromText('MULTILINESTRING((1 2, 3 4), (4 5, 6 7))');ST_MPointFromText — Створює геометрію з WKT із заданим SRID. Якщо SRID не вказано, за замовчуванням використовується 0.
geometry ST_MPointFromText(text WKT, integer srid);
geometry ST_MPointFromText(text WKT);
Створює геометрію з WKT із заданим SRID. Якщо SRID не вказано, за замовчуванням використовується значення 0.
OGC SPEC 3.2.6.2 — опція SRID взята з набору вимог відповідності
Повертає null, якщо WKT не є MULTIPOINT
![]() | |
Якщо ви абсолютно впевнені, що всі ваші геометрії 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
SELECT ST_MPointFromText('MULTIPOINT((1 2),(3 4))');
SELECT ST_MPointFromText('MULTIPOINT((-70.9590 42.1180),(-70.9611 42.1223))', 4326);ST_MPolyFromText — Створює геометрію MultiPolygon з WKT із заданим SRID. Якщо SRID не задано, за замовчуванням використовується 0.
geometry ST_MPolyFromText(text WKT, integer srid);
geometry ST_MPolyFromText(text WKT);
Створює багатокутник з WKT із заданим SRID. Якщо SRID не задано, за замовчуванням використовується 0.
OGC SPEC 3.2.6.2 — опція SRID взята з набору вимог відповідності
Видає помилку, якщо WKT не є MULTIPOLYGON
![]() | |
Якщо ви абсолютно впевнені, що всі ваші геометрії 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
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)))');
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);
ST_PointFromText — Створює точку Геометрія з WKT із заданим SRID. Якщо SRID не вказано, за замовчуванням використовується невідомий.
geometry ST_PointFromText(text WKT);
geometry ST_PointFromText(text WKT, integer srid);
Створює об'єкт точки PostGIS ST_Geometry з текстового представлення OGC Well-Known. Якщо SRID не вказано, за замовчуванням використовується невідоме значення (наразі 0). Якщо геометрія не є представленням точки WKT, повертає null. Якщо WKT повністю недійсне, видає помилку.
![]() | |
Існує 2 варіанти функції ST_PointFromText, перший не приймає SRID і повертає геометрію без визначеної системи просторових координат. Другий приймає ідентифікатор просторової координатної системи як другий аргумент і повертає ST_Geometry, що включає цей srid як частину своїх метаданих. SRID повинен бути визначений у таблиці spatial_ref_sys. |
![]() | |
Якщо ви абсолютно впевнені, що всі ваші геометрії WKT є точками, не використовуйте цю функцію. Вона працює повільніше, ніж ST_GeomFromText, оскільки додає додатковий крок перевірки. Якщо ви створюєте точки з координат довготи та широти і для вас важливіша продуктивність та точність, ніж відповідність OGC, використовуйте ST_MakePointабо псевдонім, що відповідає OGC ST_Point. |
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2 - опція SRID належить до набору вимог відповідності.
This method implements the SQL/MM specification. SQL-MM 3: 6.1.8
SELECT ST_PointFromText('POINT(-71.064544 42.28787)');
SELECT ST_PointFromText('POINT(-71.064544 42.28787)', 4326);
ST_PolygonFromText — Створює геометрію з WKT із заданим SRID. Якщо SRID не вказано, за замовчуванням використовується 0.
geometry ST_PolygonFromText(text WKT);
geometry ST_PolygonFromText(text WKT, integer srid);
Створює геометрію з WKT із заданим SRID. Якщо SRID не задано, за замовчуванням використовується 0. Повертає null, якщо WKT не є полігоном.
OGC SPEC 3.2.6.2 — опція SRID взята з набору вимог відповідності
![]() | |
Якщо ви абсолютно впевнені, що всі ваші геометрії 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
SELECT ST_PolygonFromText('POLYGON((-71.1776585052917 42.3902909739571,-71.1776820268866 42.3903701743239,
-71.1776063012595 42.3903825660754,-71.1775826583081 42.3903033653531,-71.1776585052917 42.3902909739571))');
st_polygonfromtext
------------------
010300000001000000050000006...
SELECT ST_PolygonFromText('POINT(1 2)') IS NULL as point_is_notpoly;
point_is_not_poly
----------
t
ST_WKTToSQL — Повертає вказане значення ST_Geometry з представлення Well-Known Text (WKT). Це псевдонім для ST_GeomFromText.
geometry ST_WKTToSQL(text WKT);
This method implements the SQL/MM specification. SQL-MM 3: 5.1.34
LINESTRING з WKB із заданим SRIDST_GeogFromWKB — Створює географічний екземпляр на основі добре відомого двійкового геометричного представлення (WKB) або розширеного добре відомого двійкового представлення (EWKB).
geography ST_GeogFromWKB(bytea wkb);
Функція ST_GeogFromWKB бере добре відоме двійкове представлення (WKB) геометрії або PostGIS Extended WKB і створює екземпляр відповідного типу географії. Ця функція виконує роль Geometry Factory в SQL.
Якщо SRID не вказано, за замовчуванням використовується значення 4326 (WGS 84 long lat).
This method supports Circular Strings and Curves.
--Although bytea rep contains single \, these need to be escaped when inserting into a table
SELECT ST_AsText(
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@')
);
st_astext
------------------------------------------------------
LINESTRING(-113.98 39.198,-113.981 39.195)
(1 row)
ST_GeomFromEWKB — Повернути вказане значення ST_Geometry з розширеного добре відомого двійкового представлення (EWKB).
geometry ST_GeomFromEWKB(bytea EWKB);
Створює об'єкт PostGIS ST_Geometry з представлення OGC Extended Well-Known binary (EWKT).
![]() | |
Формат EWKB не є стандартом OGC, а специфічним форматом PostGIS, що включає ідентифікатор просторової системи координат (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).
лінія бінарне представлення LINESTRING(-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932) in NAD 83 long lat (4269).
![]() | |
ПРИМІТКА: Незважаючи на те, що масиви байтів розділяються символом \ і можуть містити символ “, нам потрібно екранувати обидва символи за допомогою \ і ”', якщо стандарт standard_conforming_strings вимкнено. Тому це не виглядає точно так, як його представлення в AsEWKB. |
SELECT ST_GeomFromEWKB(E'\\001\\002\\000\\000 \\255\\020\\000\\000\\003\\000\\000\\000\\344J=
\\013B\\312Q\\300n\\303(\\010\\036!E@''\\277E''K
\\312Q\\300\\366{b\\235*!E@\\225|\\354.P\\312Q
\\300p\\231\\323e1!E@');![]() | |
У PostgreSQL 9.1+ - standard_conforming_strings за замовчуванням встановлено на on, тоді як у попередніх версіях було встановлено на off. Ви можете змінити значення за замовчуванням за потреби для окремого запиту або на рівні бази даних чи сервера. Нижче наведено, як це зробити, якщо standard_conforming_strings = on. У цьому випадку ми екрануємо “ за допомогою стандартного ansi ”, але коси риски не екрануються |
set standard_conforming_strings = on;
SELECT ST_GeomFromEWKB('\001\002\000\000 \255\020\000\000\003\000\000\000\344J=\012\013B
\312Q\300n\303(\010\036!E@''\277E''K\012\312Q\300\366{b\235*!E@\225|\354.P\312Q\012\300p\231\323e1')ST_GeomFromWKB — Створює екземпляр геометрії з добре відомого двійкового представлення геометрії (WKB) та опціонального SRID.
geometry ST_GeomFromWKB(bytea geom);
geometry ST_GeomFromWKB(bytea geom, integer srid);
Функція ST_GeomFromWKB приймає добре відоме двійкове представлення геометрії та ідентифікатор просторової системи відліку (SRID) і створює екземпляр відповідного типу геометрії. Ця функція виконує роль Geometry Factory в SQL. Це альтернативна назва для ST_WKBToSQL.
Якщо SRID не вказано, за замовчуванням використовується значення 0 (Невідомо).
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s3.2.7.2 - необов'язковий SRID з набору вимог відповідності
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.
SELECT ST_AsEWKT(
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)
);
st_asewkt
------------------------------------------------------
SRID=4326;LINESTRING(-113.98 39.198,-113.981 39.195)
(1 row)
SELECT
ST_AsText(
ST_GeomFromWKB(
ST_AsEWKB('POINT(2 5)'::geometry)
)
);
st_astext
------------
POINT(2 5)
(1 row)ST_LineFromWKB — Створює LINESTRING з WKB із заданим SRID
geometry ST_LineFromWKB(bytea WKB);
geometry ST_LineFromWKB(bytea WKB, integer srid);
Функція ST_LineFromWKB приймає добре відоме двійкове представлення геометрії та ідентифікатор просторової системи відліку (SRID) і створює екземпляр відповідного типу геометрії — у цьому випадку геометрії LINESTRING. Ця функція виконує роль Geometry Factory в SQL.
Якщо SRID не вказано, за замовчуванням використовується значення 0. Якщо вхідний параметр bytea не представляє LINESTRING, повертається NULL.
![]() | |
OGC SPEC 3.2.6.2 — опція SRID належить до набору вимог відповідності. |
![]() | |
Якщо ви знаєте, що всі ваші геометрії є |
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
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
------------------------------------------------
010200000002000000000000000000F ... | t
ST_LinestringFromWKB — Створює геометрію з WKB із заданим SRID.
geometry ST_LinestringFromWKB(bytea WKB);
geometry ST_LinestringFromWKB(bytea WKB, integer srid);
Функція ST_LinestringFromWKB приймає добре відоме двійкове представлення геометрії та ідентифікатор просторової системи координат (SRID) і створює екземпляр відповідного типу геометрії — у цьому випадку геометрії LINESTRING. Ця функція виконує роль фабрики геометрії в SQL.
Якщо SRID не вказано, за замовчуванням використовується 0. NULL повертається, якщо вхідний bytea не представляє геометрію LINESTRING. Це псевдонім для ST_LineFromWKB.
![]() | |
OGC SPEC 3.2.6.2 — необов'язковий SRID взято з набору вимог відповідності. |
![]() | |
Якщо ви знаєте, що всі ваші геометрії є |
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
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
------------------------------------------------
010200000002000000000000000000F ... | tST_PointFromWKB — Створює геометрію з WKB із заданим SRID
geometry ST_GeomFromWKB(bytea geom);
geometry ST_GeomFromWKB(bytea geom, integer srid);
Функція ST_PointFromWKB приймає добре відоме двійкове представлення геометрії та ідентифікатор просторової системи відліку (SRID) і створює екземпляр відповідного типу геометрії — у цьому випадку геометрії POINT. Ця функція виконує роль Geometry Factory в SQL.
Якщо SRID не вказано, за замовчуванням використовується 0. Якщо вхідний параметр bytea не представляє геометрію POINT, повертається 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.
SELECT
ST_AsText(
ST_PointFromWKB(
ST_AsEWKB('POINT(2 5)'::geometry)
)
);
st_astext
------------
POINT(2 5)
(1 row)
SELECT
ST_AsText(
ST_PointFromWKB(
ST_AsEWKB('LINESTRING(2 5, 2 6)'::geometry)
)
);
st_astext
-----------
(1 row)ST_WKBToSQL — Повертає вказане значення ST_Geometry з добре відомого двійкового представлення (WKB). Це псевдонім для ST_GeomFromWKB, який не приймає srid.
geometry ST_WKBToSQL(bytea WKB);
This method implements the SQL/MM specification. SQL-MM 3: 5.1.36
ST_Box2dFromGeoHash — Повернути BOX2D із рядка GeoHash.
box2d ST_Box2dFromGeoHash(text geohash, integer precision=full_precision_of_geohash);
Повернути BOX2D із рядка GeoHash.
Якщо не вказано precision, ST_Box2dFromGeoHash повертає BOX2D на основі повної точності вхідного рядка GeoHash.
Якщо вказано precision, ST_Box2dFromGeoHash використає стільки символів з GeoHash, щоб створити BOX2D. Менші значення точності дають більші BOX2D, а більші значення збільшують точність.
Доступність: 2.1.0
SELECT ST_Box2dFromGeoHash('9qqj7nmxncgyy4d0dbxqz0');
st_geomfromgeohash
--------------------------------------------------
BOX(-115.172816 36.114646,-115.172816 36.114646)
SELECT ST_Box2dFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 0);
st_box2dfromgeohash
----------------------
BOX(-180 -90,180 90)
SELECT ST_Box2dFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 10);
st_box2dfromgeohash
---------------------------------------------------------------------------
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
SELECT ST_AsText(ST_GeomFromGeoHash('9qqj7nmxncgyy4d0dbxqz0'));
st_astext
--------------------------------------------------------------------------------------------------------------------------
POLYGON((-115.172816 36.114646,-115.172816 36.114646,-115.172816 36.114646,-115.172816 36.114646,-115.172816 36.114646))
SELECT ST_AsText(ST_GeomFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 4));
st_astext
------------------------------------------------------------------------------------------------------------------------------
POLYGON((-115.3125 36.03515625,-115.3125 36.2109375,-114.9609375 36.2109375,-114.9609375 36.03515625,-115.3125 36.03515625))
SELECT ST_AsText(ST_GeomFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 10));
st_astext
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
POLYGON((-115.17282128334 36.1146408319473,-115.17282128334 36.1146461963654,-115.172810554504 36.1146461963654,-115.172810554504 36.1146408319473,-115.17282128334 36.1146408319473))
ST_GeomFromGML — Приймає в якості вхідних даних GML-представлення геометрії та видає об'єкт геометрії PostGIS
geometry ST_GeomFromGML(text geomgml);
geometry ST_GeomFromGML(text geomgml, integer srid);
Створює об'єкт PostGIS ST_Geometry з представлення OGC GML.
ST_GeomFromGML працює тільки для фрагментів геометрії GML. При спробі використання на всьому документі GML видає помилку.
Підтримувані версії OGC GML:
GML 3.2.1 Namespace
GML 3.1.1 Simple Features profile 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 додано підтримку багатогранних поверхонь та TIN.
Покращено: 2.0.0 додано опціональний параметр srid за замовчуванням.
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 дозволяє змішані розміри (наприклад, 2D і 3D в одній MultiGeometry). Оскільки геометрії PostGIS цього не дозволяють, ST_GeomFromGML перетворює всю геометрію в 2D, якщо знаходить відсутній розмір Z.
GML підтримує змішані SRS всередині одного MultiGeometry. Оскільки геометрії PostGIS цього не роблять, ST_GeomFromGML у цьому випадку перепроектує всі підгеометрії до кореневого вузла SRS. Якщо для кореневого вузла GML недоступний атрибут srsName, функція видає помилку.
Функція ST_GeomFromGML не є педантичною щодо явного простору імен GML. Ви можете не згадувати його явно для загального використання. Але він необхідний, якщо ви хочете використовувати функцію XLink всередині GML.
![]() | |
Функція ST_GeomFromGML не підтримує геометрії кривих SQL/MM. |
SELECT 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>
$$);
SELECT ST_GeomFromGML($$
<gml:LineString xmlns:gml="http://www.opengis.net/gml"
xmlns:xlink="http://www.w3.org/1999/xlink"
srsName="urn:ogc:def:crs:EPSG::4269">
<gml:pointProperty>
<gml:Point gml:id="p1"
><gml:pos
>42.258729 -71.16028</gml:pos
></gml:Point>
</gml:pointProperty>
<gml:pos
>42.259112 -71.160837</gml:pos>
<gml:pointProperty>
<gml:Point xlink:type="simple" xlink:href="#p1"/>
</gml:pointProperty>
</gml:LineString>
$$);
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
>'));
-- result --
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_GeomFromGeoJSON — Приймає в якості вхідних даних геометричне представлення у форматі geojson і видає геометричний об'єкт PostGIS
geometry ST_GeomFromGeoJSON(text geomjson);
geometry ST_GeomFromGeoJSON(json geomjson);
geometry ST_GeomFromGeoJSON(jsonb geomjson);
Створює об'єкт геометрії PostGIS з представлення GeoJSON.
ST_GeomFromGeoJSON працює тільки для фрагментів JSON Geometry. При спробі використання на всьому документі JSON видається помилка.
Покращено: 3.0.0, якщо не вказано інше, геометрія за замовчуванням аналізується як SRID=4326.
Покращено: версія 2.5.0 тепер підтримує json та jsonb як вхідні дані.
Доступність: 2.0.0 вимагає - JSON-C >= 0.9
![]() | |
Якщо JSON-C не ввімкнено, замість виводу ви отримаєте повідомлення про помилку. Щоб увімкнути JSON-C, запустіть configure --with-jsondir=/path/to/json-c. Детальніше див. Section 2.2.3, “Конфігурація збірки”. |
This function supports 3d and will not drop the z-index.
SELECT ST_AsText(ST_GeomFromGeoJSON('{"type":"Point","coordinates":[-48.23456,20.12345]}')) As wkt;
wkt
------
POINT(-48.23456 20.12345)
-- a 3D linestring
SELECT ST_AsText(ST_GeomFromGeoJSON('{"type":"LineString","coordinates":[[1,2,3],[4,5,6],[7,8,9]]}')) As wkt;
wkt
-------------------
LINESTRING(1 2,4 5,7 8)
ST_GeomFromKML — Приймає в якості вхідних даних KML-представлення геометрії та видає об'єкт геометрії PostGIS
geometry ST_GeomFromKML(text geomkml);
Створює об'єкт PostGIS ST_Geometry з представлення OGC KML.
ST_GeomFromKML працює тільки для фрагментів геометрії KML. При спробі використання на всьому документі KML видається помилка.
Підтримувані версії OGC KML:
Простір імен KML 2.2.0
Стандарти OGC KML, див.: http://www.opengeospatial.org/standards/kml:
Доступність: 1.5, вимагає libxml2 2.6+
This function supports 3d and will not drop the z-index.
![]() | |
Функція ST_GeomFromKML не підтримує геометрії кривих SQL/MM. |
SELECT ST_GeomFromKML($$
<LineString>
<coordinates
>-71.1663,42.2614
-71.1667,42.2616</coordinates>
</LineString>
$$);
ST_GeomFromTWKB — Створює екземпляр геометрії з представлення геометрії TWKB ("Tiny Well-Known Binary").
geometry ST_GeomFromTWKB(bytea twkb);
Функція ST_GeomFromTWKB приймає геометричне представлення TWKB ("Tiny Well-Known Binary") (WKB) і створює екземпляр відповідного типу геометрії.
SELECT ST_AsText(ST_GeomFromTWKB(ST_AsTWKB('LINESTRING(126 34, 127 35)'::geometry)));
st_astext
-----------------------------
LINESTRING(126 34, 127 35)
(1 row)
SELECT ST_AsEWKT(
ST_GeomFromTWKB(E'\\x620002f7f40dbce4040105')
);
st_asewkt
------------------------------------------------------
LINESTRING(-113.98 39.198,-113.981 39.195)
(1 row)
ST_GMLToSQL — Повертає вказане значення ST_Geometry з представлення GML. Це псевдонім для ST_GeomFromGML.
geometry ST_GMLToSQL(text geomgml);
geometry ST_GMLToSQL(text geomgml, integer srid);
This method implements the SQL/MM specification. SQL-MM 3: 5.1.50 (крім підтримки кривих).
Доступність: 1.5, вимагає libxml2 1.6+
Покращено: 2.0.0 додано підтримку багатогранних поверхонь та TIN.
Покращено: 2.0.0 додано опціональний параметр srid за замовчуванням.
ST_LineFromEncodedPolyline — Створює LineString з закодованої полілінії.
geometry ST_LineFromEncodedPolyline(text polyline, integer precision=5);
Створює об'єкт LineString із кодованої полілінії.
Опціональний параметр precision визначає, скільки десяткових знаків буде збережено в кодованій полілінії. Значення повинно бути однаковим при кодуванні та декодуванні, інакше координати будуть неправильними.
Див. http://developers.google.com/maps/documentation/utilities/polylinealgorithm
Доступність: 2.2.0
-- Create a line string from a polyline
SELECT ST_AsEWKT(ST_LineFromEncodedPolyline('_p~iF~ps|U_ulLnnqC_mqNvxq`@'));
-- result --
SRID=4326;LINESTRING(-120.2 38.5,-120.95 40.7,-126.453 43.252)
-- Select different precision that was used for polyline encoding
SELECT ST_AsEWKT(ST_LineFromEncodedPolyline('_p~iF~ps|U_ulLnnqC_mqNvxq`@',6));
-- result --
SRID=4326;LINESTRING(-12.02 3.85,-12.095 4.07,-12.6453 4.3252)
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
SELECT ST_AsText(ST_PointFromGeoHash('9qqj7nmxncgyy4d0dbxqz0'));
st_astext
------------------------------
POINT(-115.172816 36.114646)
SELECT ST_AsText(ST_PointFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 4));
st_astext
-----------------------------------
POINT(-115.13671875 36.123046875)
SELECT ST_AsText(ST_PointFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 10));
st_astext
-------------------------------------------
POINT(-115.172815918922 36.1146435141563)
ST_FromFlatGeobufToTable — Створює таблицю на основі структури даних FlatGeobuf.
void ST_FromFlatGeobufToTable(text schemaname, text tablename, bytea FlatGeobuf input data);
Створює таблицю на основі структури даних FlatGeobuf. (http://flatgeobuf.org).
schema Ім'я схеми.
table Ім'я таблиці.
data Введіть дані FlatGeobuf.
Доступність: 3.2.0
ST_FromFlatGeobuf — Зчитує дані FlatGeobuf.
setof anyelement ST_FromFlatGeobuf(anyelement Table reference, bytea FlatGeobuf input data);
Читає дані FlatGeobuf (http://flatgeobuf.org). ПРИМІТКА: PostgreSQL bytea не може перевищувати 1 ГБ.
tabletype посилання на тип таблиці.
data вхідні дані FlatGeobuf.
Доступність: 3.2.0
Ці функції перетворюють геометричні об'єкти в різні текстові або двійкові формати.
ST_AsEWKT — Повернути представлення геометрії у вигляді добре відомого тексту (WKT) з метаданими 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);
Повертає добре відоме текстове представлення геометрії з префіксом SRID. Опціональний аргумент maxdecimaldigits може використовуватися для зменшення максимальної кількості десяткових цифр після плаваючої коми, що використовуються у вихідних даних (за замовчуванням — 15).
Для виконання зворотного перетворення представлення EWKT у геометрію PostGIS використовуйте ST_GeomFromEWKT.
![]() | |
Використання параметра |
![]() | |
Специфікація WKT не включає SRID. Щоб отримати формат OGC WKT, використовуйте ST_AsText. |
![]() | |
Формат WKT не зберігає точність, тому щоб запобігти обрізанню плаваючої точки, для передачі використовуйте формат ST_AsBinaryабо ST_AsEWKB. |
Покращено: 3.1.0 підтримка опціонального параметра точності.
Покращено: 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).
SELECT ST_AsEWKT('0103000020E61000000100000005000000000000
000000000000000000000000000000000000000000000000000000
F03F000000000000F03F000000000000F03F000000000000F03
F000000000000000000000000000000000000000000000000'::geometry);
st_asewkt
--------------------------------
SRID=4326;POLYGON((0 0,0 1,1 1,1 0,0 0))
(1 row)
SELECT ST_AsEWKT('0108000080030000000000000060E30A4100000000785C0241000000000000F03F0000000018
E20A4100000000485F024100000000000000400000000018
E20A4100000000305C02410000000000000840')
--st_asewkt---
CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)
ST_AsText — Повернути представлення геометрії/географії у вигляді добре відомого тексту (WKT) без метаданих 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);
Повертає представлення геометрії/географії у форматі OGC Well-Known Text (WKT). Опціональний аргумент maxdecimaldigits може використовуватися для обмеження кількості цифр після десяткової крапки у вихідних координатах (за замовчуванням — 15).
Для виконання зворотного перетворення представлення WKT в геометрію PostGIS використовуйте ST_GeomFromText.
![]() | |
Стандартне представлення OGC WKT не включає SRID. Щоб включити SRID як частину вихідного представлення, використовуйте нестандартну функцію PostGIS ST_AsEWKT |
![]() | |
Текстове представлення чисел у WKT може не зберігати повну точність з плаваючою комою. Щоб забезпечити повну точність зберігання або передачі даних, найкраще використовувати формат Well-Known Binary (WKB) (див. ST_AsBinaryта |
![]() | |
Використання параметра |
Доступність: 1.5 — додано підтримку географії.
Покращено: 2.5 — додано опційний параметр точності.
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.
SELECT ST_AsText('01030000000100000005000000000000000000
000000000000000000000000000000000000000000000000
F03F000000000000F03F000000000000F03F000000000000F03
F000000000000000000000000000000000000000000000000');
st_astext
--------------------------------
POLYGON((0 0,0 1,1 1,1 0,0 0))
Повна точність виводу є стандартною настройкою.
SELECT ST_AsText('POINT(111.1111111 1.1111111)'));
st_astext
------------------------------
POINT(111.1111111 1.1111111)
Аргумент maxdecimaldigits можна використовувати для обмеження точності виводу.
SELECT ST_AsText('POINT(111.1111111 1.1111111)'), 2);
st_astext
--------------------
POINT(111.11 1.11)
ST_AsBinary — Повернути представлення геометрії/географії у форматі OGC/ISO Well-Known Binary (WKB) без метаданих SRID.
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);
Повертає представлення геометрії у форматі OGC/ISO Well-Known Binary (WKB). Перший варіант функції за замовчуванням використовує кодування, що відповідає ендіану сервера. Другий варіант функції приймає текстовий аргумент, що визначає кодування ендіана: “NDR” для little-endian або “XDR” для big-endian. Введення невідомих аргументів призведе до виведення little-endian.
Формат WKB корисний для читання геометричних даних з бази даних та збереження повної числової точності. Це дозволяє уникнути округлення точності, яке може відбуватися у текстових форматах, таких як WKT.
Для виконання зворотного перетворення WKB в геометрію PostGIS використовуйте ST_GeomFromWKB.
![]() | |
Формат OGC/ISO WKB не включає SRID. Щоб отримати формат EWKB, який включає SRID, використовуйте ST_AsEWKB |
![]() | |
Стандартна поведінка в PostgreSQL 9.0 була змінена на виведення bytea в шістнадцятковому кодуванні. Якщо ваші графічні інструменти вимагають старої поведінки, то встановіть SET bytea_output=“escape” у вашій базі даних. |
Покращено: 2.0.0 додано підтримку багатогранних поверхонь, трикутників і TIN.
Покращено: 2.0.0 додано підтримку вищих розмірностей координат.
Покращено: 2.0.0 додано підтримку вказання ендіанності для географічних даних.
Доступність: 1.5.0 додано підтримку географії.
Змінено: 2.0.0 Вхідні дані для цієї функції не можуть бути невідомими — вони повинні бути геометрією. Такі конструкції, як ST_AsBinary(“POINT(1 2)”), більше не є дійсними, і ви отримаєте помилку n st_asbinary(unknown) is not unique. Такий код потрібно змінити на ST_AsBinary(“POINT(1 2)”::geometry);. Якщо це неможливо, встановіть 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.
SELECT ST_AsBinary(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326));
st_asbinary
--------------------------------
\x01030000000100000005000000000000000000000000000000000000000000000000000000000000
000000f03f000000000000f03f000000000000f03f000000000000f03f0000000000000000000000
00000000000000000000000000
SELECT ST_AsBinary(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326), 'XDR');
st_asbinary
--------------------------------
\x000000000300000001000000050000000000000000000000000000000000000000000000003ff000
00000000003ff00000000000003ff00000000000003ff00000000000000000000000000000000000
00000000000000000000000000
ST_AsEWKB — Повернути розширене добре відоме двійкове (EWKB) представлення геометрії з метаданими SRID.
bytea ST_AsEWKB(geometry g1);
bytea ST_AsEWKB(geometry g1, text NDR_or_XDR);
Повертає представлення геометрії у форматі Extended Well-Known Binary (EWKB) з метаданими SRID. Перший варіант функції за замовчуванням використовує кодування, що відповідає порядку байтів на сервері. Другий варіант функції приймає текстовий аргумент, що визначає кодування ендіана: “NDR” для little-endian або “XDR” для big-endian. Введення невідомих аргументів призведе до виведення little-endian.
Формат WKB корисний для читання геометричних даних з бази даних та збереження повної числової точності. Це дозволяє уникнути округлення точності, яке може відбуватися у текстових форматах, таких як WKT.
Для виконання зворотного перетворення EWKB в геометрію PostGIS використовуйте ST_GeomFromEWKB.
![]() | |
Щоб отримати формат OGC/ISO WKB, використовуйте ST_AsBinary. Зверніть увагу, що формат OGC/ISO WKB не включає 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).
SELECT ST_AsEWKB(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326));
st_asewkb
--------------------------------
\x0103000020e610000001000000050000000000000000000000000000000000000000000000000000
00000000000000f03f000000000000f03f000000000000f03f000000000000f03f00000000000000
0000000000000000000000000000000000
SELECT ST_AsEWKB(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326), 'XDR');
st_asewkb
--------------------------------
\x0020000003000010e600000001000000050000000000000000000000000000000000000000000000
003ff00000000000003ff00000000000003ff00000000000003ff000000000000000000000000000
0000000000000000000000000000000000
ST_AsHEXEWKB — Повертає геометрію у форматі HEXEWKB (у вигляді тексту) з використанням кодування little-endian (NDR) або big-endian (XDR).
text ST_AsHEXEWKB(geometry g1, text NDRorXDR);
text ST_AsHEXEWKB(geometry g1);
Повертає геометрію у форматі HEXEWKB (у вигляді тексту) з використанням кодування little-endian (NDR) або big-endian (XDR). Якщо кодування не вказано, використовується NDR.
![]() | |
Доступність: 1.2.2 |
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves.
SELECT ST_AsHEXEWKB(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326));
which gives same answer as
SELECT ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326)::text;
st_ashexewkb
--------
0103000020E6100000010000000500
00000000000000000000000000000000
00000000000000000000000000000000F03F
000000000000F03F000000000000F03F000000000000F03
F000000000000000000000000000000000000000000000000ST_AsEncodedPolyline — Повертає закодовану полілінію з геометрії LineString.
text ST_AsEncodedPolyline(geometry geom, integer precision=5);
Повертає геометрію у вигляді закодованої полілінії. Цей формат використовується Google Maps з точністю = 5 та Open Source Routing Machine з точністю = 5 і 6.
Опціональний параметр precision визначає, скільки десяткових знаків буде збережено в кодованій полілінії. Значення повинно бути однаковим при кодуванні та декодуванні, інакше координати будуть неправильними.
Доступність: 2.2.0
Базовий
SELECT ST_AsEncodedPolyline(GeomFromEWKT('SRID=4326;LINESTRING(-120.2 38.5,-120.95 40.7,-126.453 43.252)'));
--result--
|_p~iF~ps|U_ulLnnqC_mqNvxq`@
Використовуйте разом із географічними лініями та географічною сегментацією, а також розмістіть на картах Google
-- the SQL for Boston to San Francisco, segments every 100 KM
SELECT ST_AsEncodedPolyline(
ST_Segmentize(
ST_GeogFromText('LINESTRING(-71.0519 42.4935,-122.4483 37.64)'),
100000)::geometry) As encodedFlightPath;javascript буде виглядати приблизно так, де змінну $ ви замінюєте результатом запиту
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=geometry"
></script>
<script type="text/javascript">
flightPath = new google.maps.Polyline({
path: google.maps.geometry.encoding.decodePath("$encodedFlightPath"),
map: map,
strokeColor: '#0000CC',
strokeOpacity: 1.0,
strokeWeight: 4
});
</script>
ST_AsFlatGeobuf — Повернути представлення FlatGeobuf набору рядків.
bytea ST_AsFlatGeobuf(anyelement set row);
bytea ST_AsFlatGeobuf(anyelement row, bool index);
bytea ST_AsFlatGeobuf(anyelement row, bool index, text geom_name);
Повертає представлення FlatGeobuf (http://flatgeobuf.org) набору рядків, що відповідають FeatureCollection. ПРИМІТКА: PostgreSQL bytea не може перевищувати 1 ГБ.
row дані рядка, що містять принаймні стовпець геометрії.
index вмикає/вимикає створення просторового індексу. За замовчуванням встановлено значення false.
geom_name — це назва стовпця геометрії в даних рядка. Якщо NULL, за замовчуванням буде використано перший знайдений стовпець геометрії.
Доступність: 3.2.0
ST_AsGeobuf — Повернути представлення Geobuf набору рядків.
bytea ST_AsGeobuf(anyelement set row);
bytea ST_AsGeobuf(anyelement row, text geom_name);
Повертає представлення Geobuf (https://github.com/mapbox/geobuf) набору рядків, що відповідають FeatureCollection. Кожна вхідна геометрія аналізується для визначення максимальної точності для оптимального зберігання. Зверніть увагу, що Geobuf у його поточній формі не може бути переданий потоком, тому повний вихід буде зібраний у пам'яті.
row дані рядка, що містять принаймні стовпець геометрії.
geom_name — це назва стовпця геометрії в даних рядка. Якщо NULL, за замовчуванням буде використано перший знайдений стовпець геометрії.
Доступність: 2.4.0
SELECT encode(ST_AsGeobuf(q, 'geom'), 'base64')
FROM (SELECT ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))') AS geom) AS q;
st_asgeobuf
----------------------------------
GAAiEAoOCgwIBBoIAAAAAgIAAAE=
ST_AsGeoJSON — Повернути геометрію або об'єкт у форматі GeoJSON.
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);
Повертає геометрію як об'єкт GeoJSON "geometry" або рядок як об'єкт GeoJSON "feature".
Отримані геометричні та об'єктні представлення GeoJSON відповідають специфікаціям GeoJSON RFC 7946, за винятком випадків, коли розібрані геометрії посилаються на CRS, відмінну від WGS84 довготи та широти (EPSG:4326, urn:ogc:def:crs:OGC::CRS84); у такому випадку до об'єкта геометрії GeoJSON за замовчуванням буде додано короткий ідентифікатор CRS SRID. Підтримуються як 2D, так і 3D геометрії. GeoJSON підтримує тільки типи геометрії SFS 1.1 (наприклад, не підтримуються криві).
Параметр geom_column використовується для розрізнення декількох стовпців геометрії. Якщо його опустити, буде визначено перший стовпець геометрії в записі. І навпаки, передача цього параметра збереже пошуки типів стовпців.
Аргумент maxdecimaldigits можна використовувати для зменшення максимальної кількості десяткових знаків, що використовуються у вихідних даних (за замовчуванням — 9). Якщо ви використовуєте EPSG:4326 і виводите геометрію тільки для відображення, для багатьох карт хорошим вибором може бути maxdecimaldigits=6.
![]() | |
Використання параметра |
Аргумент options можна використовувати для додавання BBOX або CRS у вихідні дані GeoJSON:
0: означає відсутність опції
1: GeoJSON BBOX
2: GeoJSON коротка CRS (наприклад, EPSG:4326)
4: GeoJSON Long CRS (наприклад, urn:ogc:def:crs:EPSG::4326)
8: GeoJSON Короткий CRS, якщо не EPSG:4326 (за замовчуванням)
Параметр id_column використовується для встановлення елемента "id" повернутих об'єктів GeoJSON. Відповідно до GeoJSON RFC, це ПОВИННО використовуватися, коли елемент має загальновживаний ідентифікатор, такий як первинний ключ. Якщо це не вказано, створені елементи не отримають елемент "id", а всі стовпці, крім геометрії, включаючи будь-які потенційні ключі, просто потраплять в елемент "properties" елемента.
Специфікація GeoJSON визначає, що полігони орієнтуються за правилом правої руки, і деякі клієнти вимагають такої орієнтації. Це можна забезпечити за допомогою ST_ForcePolygonCCW . Специфікація також вимагає, щоб геометрія була в системі координат WGS84 (SRID = 4326). За необхідності геометрію можна спроектувати в WGS84 за допомогою ST_Transform: ST_Transform( geom, 4326 ).
GeoJSON можна протестувати та переглянути онлайн за адресами geojson.io та geojsonlint.com. Він широко підтримується веб-картографічними фреймворками:
Доступність: 1.3.4
Доступність: 1.5.0 додано підтримку географії.
Змінено: 2.0.0 підтримка аргументів за замовчуванням та іменованих аргументів.
Змінено: 3.0.0 підтримка записів як вхідних даних
Змінено: 3.0.0 виведення SRID, якщо не EPSG:4326.
Змінено: 3.5.0 Дозволено вказувати стовпець, що містить feature id
This function supports 3d and will not drop the z-index.
Створити колекцію об'єктів:
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"}}]}Створити Feature:
SELECT ST_AsGeoJSON(t.*, id_column = > 'id') FROM (VALUES (1, 'one', 'POINT(1 1)'::geometry)) AS t(id, name, geom);
st_asgeojson
-----------------------------------------------------------------------------------------------------------------
{"type": "Feature", "geometry": {"type":"Point","coordinates":[1,1]}, "id": 1, "properties": {"name": "one"}}
Не забудьте перетворити дані в довготу WGS84, широту, щоб вони відповідали специфікації GeoJSON:
SELECT ST_AsGeoJSON(ST_Transform(geom,4326)) from fe_edges limit 1;
st_asgeojson
-----------------------------------------------------------------------------------------------------------
{"type":"MultiLineString","coordinates":[[[-89.734634999999997,31.492072000000000],
[-89.734955999999997,31.492237999999997]]]}
Підтримуються 3D-геометрії:
SELECT ST_AsGeoJSON('LINESTRING(1 2 3, 4 5 6)');{"type":"LineString","coordinates":[[1,2,3],[4,5,6]]}Аргумент Options можна використовувати для додавання BBOX і CRS у вихідні дані GeoJSON:
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 або 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);
Повернути геометрію як елемент мови географічної розмітки (GML). Параметр version, якщо вказано, може мати значення 2 або 3. Якщо параметр version не вказано, за замовчуванням використовується значення 2. Аргумент maxdecimaldigits можна використовувати для зменшення максимальної кількості десяткових знаків, що використовуються у вихідних даних (за замовчуванням 15).
![]() | |
Використання параметра |
GML 2 відноситься до версії 2.1.2, GML 3 – до версії 3.1.1
Аргумент "options" є бітовим полем. Він може використовуватися для визначення типу виводу CRS у виводі GML та для оголошення даних як lat/lon:
0: Коротка CRS GML (наприклад, EPSG:4326), значення за замовчуванням
1: GML Long CRS (наприклад, urn:ogc:def:crs:EPSG::4326)
2: Тільки для GML 3, видаліть атрибут srsDimension з вихідних даних.
4: Тільки для GML 3 використовуйте тег <LineString> замість <Curve> для ліній.
16: Заявити, що дані є широтою/довготою (наприклад, srid=4326). За замовчуванням вважається, що дані є планарними. Ця опція корисна тільки для виводу GML 3.1.1, пов'язаного з порядком осей. Тому, якщо ви її встановите, координати будуть поміняні місцями, і порядок буде широта-довгота замість довгота-широта, як у базі даних.
32: Вивести прямокутник геометрії (контур).
Аргумент "namespace prefix" може використовуватися для вказання власного префікса простору імен або відсутності префікса (якщо поле порожнє). Якщо префікс "gml" нульовий або пропущений, використовується префікс "gml"
Доступність: 1.3.2
Доступність: 1.5.0 додано підтримку географії.
Покращено: додано підтримку префікса 2.0.0. Додано опцію 4 для GML3, що дозволяє використовувати тег LineString замість Curve для ліній. Додано підтримку GML3 для багатогранних поверхонь і TINS. Додано опцію 32 для виведення прямокутника.
Змінено: 2.0.0 використання аргументів із стандартними іменами
Покращено: 2.1.0 Додано підтримку ідентифікаторів для GML 3.
![]() | |
Тільки версія 3+ ST_AsGML підтримує багатогранні поверхні та TINS. |
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).
SELECT ST_AsGML(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326));
st_asgml
--------
<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>
-- Flip coordinates and output extended EPSG (16 | 1)--
SELECT ST_AsGML(3, ST_GeomFromText('POINT(5.234234233242 6.34534534534)',4326), 5, 17);
st_asgml
--------
<gml:Point srsName="urn:ogc:def:crs:EPSG::4326"
><gml:pos
>6.34535 5.23423</gml:pos
></gml:Point>
-- Output the envelope (32) --
SELECT ST_AsGML(3, ST_GeomFromText('LINESTRING(1 2, 3 4, 10 20)',4326), 5, 32);
st_asgml
--------
<gml:Envelope srsName="EPSG:4326">
<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 --
SELECT ST_AsGML(3, ST_GeomFromText('LINESTRING(1 2, 3 4, 10 20)',4326), 5, 49);
st_asgml
--------
<gml:Envelope srsName="urn:ogc:def:crs:EPSG::4326">
<gml:lowerCorner
>2 1</gml:lowerCorner>
<gml:upperCorner
>20 10</gml:upperCorner>
</gml:Envelope>
-- Polyhedral Example --
SELECT ST_AsGML(3, 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)) )'));
st_asgml
--------
<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 — Повернути геометрію як елемент KML.
text ST_AsKML(geometry geom, integer maxdecimaldigits=15, text nprefix=NULL);
text ST_AsKML(geography geog, integer maxdecimaldigits=15, text nprefix=NULL);
Повернути геометрію як елемент мови розмітки Keyhole (KML). Максимальна кількість десяткових знаків за замовчуванням — 15, простір імен за замовчуванням — без префікса.
![]() | |
Використання параметра |
![]() | |
Потрібно, щоб PostGIS було скомпільовано з підтримкою Proj. Використовуйте PostGIS_Full_Version, щоб підтвердити, що підтримка proj скомпільована. |
![]() | |
Доступність: 1.2.2 — пізніші варіанти, що містять параметр версії, з'явилися в 1.3.2 |
![]() | |
Покращено: 2.0.0 - Додано префікс простору імен, використання аргументів за замовчуванням та іменованих аргументів |
![]() | |
Змінено: 3.0.0 - Вилучено підпис варіанту "versioned" |
![]() | |
Вихідні дані AsKML не працюватимуть з геометріями, які не мають SRID |
This function supports 3d and will not drop the z-index.
SELECT ST_AsKML(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326));
st_askml
--------
<Polygon
><outerBoundaryIs
><LinearRing
><coordinates
>0,0 0,1 1,1 1,0 0,0</coordinates
></LinearRing
></outerBoundaryIs
></Polygon>
--3d linestring
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 для широти). |
Параметр text є рядком формату, що містить формат для отриманого тексту, подібний до рядка формату дати. Допустимі символи: "D" для градусів, "M" для хвилин, "S" для секунд і "C" для основних напрямків (NSEW). Символи DMS можна повторювати, щоб вказати бажану ширину та точність ("SSS.SSSS" означає "1,0023").
"M", "S" та "C" є необов'язковими. Якщо "C" опущено, градуси позначаються знаком "-", якщо вони південні або західні. Якщо "S" опущено, хвилини відображаються у вигляді десяткових чисел із точністю до заданої кількості цифр. Якщо "M" також опущено, градуси відображаються у вигляді десяткових чисел із точністю до заданої кількості цифр.
Якщо рядок формату пропущено (або має нульову довжину), буде використано формат за замовчуванням.
Доступність: 2.0
Формат за замовчуванням.
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)'));
st_aslatlontext
----------------------------
2°19'29.928"S 3°14'3.243"W
Надання формату (такого самого, як за замовчуванням).
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)', 'D°M''S.SSS"C'));
st_aslatlontext
----------------------------
2°19'29.928"S 3°14'3.243"W
Символи, крім D, M, S, C і ., просто пропускаються.
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)', 'D degrees, M minutes, S seconds to the C'));
st_aslatlontext
--------------------------------------------------------------------------------------
2 degrees, 19 minutes, 30 seconds to the S 3 degrees, 14 minutes, 3 seconds to the W
Підписані ступені замість основних напрямків.
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)', 'D°M''S.SSS"'));
st_aslatlontext
----------------------------
-2°19'29.928" -3°14'3.243"
Десятичні градуси.
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)', 'D.DDDD degrees C'));
st_aslatlontext
-----------------------------------
2.3250 degrees S 3.2342 degrees W
Надмірно великі значення нормалізуються.
SELECT (ST_AsLatLonText('POINT (-302.2342342 -792.32498)'));
st_aslatlontext
-------------------------------
72°19'29.928"S 57°45'56.757"E
ST_AsMARC21 — Повертає геометрію у вигляді запису MARC21/XML із полем географічних даних (034).
text ST_AsMARC21 ( geometry geom , text format='hdddmmss' );
Ця функція повертає запис MARC21/XML з Кодованими картографічними математичними даними, що представляють обмежувальну рамку заданої геометрії. Параметр format дозволяє кодувати координати в підполях $d,$e,$f та $g у всіх форматах, що підтримуються стандартом MARC21/XML. Допустимі формати:
основний напрямок, градуси, хвилини та секунди (за замовчуванням): hdddmmss
десятиградусні градуси з основним напрямком: hddd.dddddd
десятиградусні градуси без вказівки сторони світу: ddd.dddddd
десятикратні хвилини з основним напрямком: hdddmm.mmmm
десятинні хвилини без вказівки напрямку: dddmm.mmmm
десятинні секунди з основним напрямком: hdddmmss.sss
Знак десяткового числа може бути також комою, наприклад hdddmm,mmmm.
Точність десяткових форматів може бути обмежена кількістю символів після десяткового знака, наприклад hdddmm.mm для десяткових хвилин з точністю до двох десяткових знаків.
Ця функція ігнорує розміри Z і M.
Підтримувані версії LOC MARC21/XML:
Доступність: 3.3.0
![]() | |
Ця функція не підтримує геометрії, що не є lon/lat, оскільки вони не підтримуються стандартом MARC21/XML (Coded Cartographic Mathematical Data). |
![]() | |
Стандарт MARC21/XML не передбачає жодних засобів для анотування просторової системи координат для кодованих картографічних математичних даних, що означає, що ця інформація буде втрачена після перетворення у формат MARC21/XML. |
Перетворення POINT у формат MARC21/XML у вигляді hdddmmss (за замовчуванням)
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>
Перетворення POLYGON у формат MARC21/XML з десятковими градусами
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>
Перетворення GEOMETRYCOLLECTION у формат MARC21/XML з десятковими хвилинами. Порядок геометрій у вихідних даних MARC21/XML відповідає їхньому порядку в колекції.
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 — Перетворює геометрію в координатну систему плитки MVT.
geometry ST_AsMVTGeom(geometry geom, box2d bounds, integer extent=4096, integer buffer=256, boolean clip_geom=true);
Перетворює геометрію в координатну систему плитки MVT (Mapbox Vector Tile), обрізаючи її до меж плитки, якщо потрібно. Геометрія повинна бути в системі координат цільової карти (використовуючи ST_Transform, якщо потрібно). Зазвичай це Web Mercator (SRID:3857).
Функція намагається зберегти правильність геометрії та виправити її, якщо це необхідно. Це може призвести до скорочення геометрії результату до нижчого виміру.
Необхідно вказати прямокутні межі плитки в просторі координат цільової карти, щоб можна було трансформувати геометрію та обрізати її за необхідності. Межі можна створити за допомогою ST_TileEnvelope.
Ця функція використовується для перетворення геометрії в координатну систему плиток, необхідну для ST_AsMVT.
geom — геометрія, яку потрібно трансформувати в системі координат цільової карти.
bounds — прямокутні межі плитки в просторі координат карти, без буфера.
extent — розмір площі плитки в просторі координат плитки, як визначено в специфікації MVT. За замовчуванням — 4096.
buffer — розмір буфера в просторі координат плиток для обрізки геометрії. За замовчуванням — 256.
clip_geom — це логічне значення, яке визначає, чи геометрії обрізаються або кодуються без змін. За замовчуванням встановлено значення true.
Доступність: 2.4.0
![]() | |
Починаючи з версії 3.0, під час конфігурації можна вибрати Wagyu для обрізання та перевірки полігонів MVT. Ця бібліотека працює швидше та дає більш правильні результати, ніж стандартна GEOS, але може пропускати невеликі полігони. |
SELECT ST_AsText(ST_AsMVTGeom(
ST_GeomFromText('POLYGON ((0 0, 10 0, 10 5, 0 -5, 0 0))'),
ST_MakeBox2D(ST_Point(0, 0), ST_Point(4096, 4096)),
4096, 0, false));
st_astext
--------------------------------------------------------------------
MULTIPOLYGON(((5 4096,10 4091,10 4096,5 4096)),((5 4096,0 4101,0 4096,5 4096)))
Канонічний приклад для плитки Web Mercator з використанням обчислених меж плитки для запиту та обрізки геометрії. Припускається, що стовпець data.geom має srid 4326.
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 — Агрегатна функція, що повертає MVT-представлення набору рядків.
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);
Агрегатна функція, яка повертає двійкове Mapbox Vector Tile представлення набору рядків, що відповідають шару плиток. Рядки повинні містити стовпець геометрії, який буде закодований як геометрія об'єкта. Геометрія повинна бути в просторі координат плитки та відповідати специфікації MVT. ST_AsMVTGeom можна використовувати для перетворення геометрії в простір координат плитки. Інші стовпці рядків кодуються як атрибути об'єкта.
Формат Mapbox Vector Tile може зберігати об'єкти з різними наборами атрибутів. Щоб скористатися цією можливістю, надайте стовпець JSONB у даних рядка, що містить об'єкти Json одного рівня. Ключі та значення в значеннях JSONB будуть закодовані як атрибути об'єктів.
Плитки з декількома шарами можна створити, об'єднавши кілька викликів цієї функції за допомогою || або STRING_AGG.
![]() | |
Не викликайте з |
row дані рядка, що містять принаймні стовпець геометрії.
name — це назва шару. За замовчуванням використовується рядок "default".
extent — це розмір плитки в просторі екрана, як визначено в специфікації. За замовчуванням — 4096.
geom_name — це ім'я стовпця геометрії в даних рядка. За замовчуванням це перший стовпець геометрії. Зверніть увагу, що PostgreSQL за замовчуванням автоматично перетворює ідентифікатори без лапок у нижній регістр, що означає, що якщо стовпець геометрії не взято в лапки, наприклад "MyMVTGeom", цей параметр повинен бути вказаний малими літерами.
feature_id_name — це назва стовпця Feature ID у даних рядка. Якщо значення NULL або від’ємне, Feature ID не встановлюється. Перший стовпець, що відповідає назві та дійсному типу (smallint, integer, bigint), буде використано як Feature ID, а всі наступні стовпці будуть додано як властивості. Властивості JSON не підтримуються.
Покращено: 3.0 — додано підтримку ідентифікатора функції.
Покращено: 2.5.0 — додано підтримку паралельних запитів.
Доступність: 2.4.0
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 — Повертає дані SVG-шляху для геометрії.
text ST_AsSVG(geometry geom, integer rel=0, integer maxdecimaldigits=15);
text ST_AsSVG(geography geog, integer rel=0, integer maxdecimaldigits=15);
Повернути геометрію як дані шляху Scalar Vector Graphics (SVG). Використовуйте 1 як другий аргумент, щоб дані шляху були реалізовані у вигляді відносних переміщень, за замовчуванням (або 0) використовуються абсолютні переміщення. Третій аргумент може бути використаний для зменшення максимальної кількості десяткових цифр, що використовуються у вихідних даних (за замовчуванням 15). Точкові геометрії будуть відображатися як cx/cy, коли аргумент “rel” дорівнює 0, x/y, коли “rel” дорівнює 1. Багатоточкові геометрії розділяються комами (","), геометрії GeometryCollection розділяються крапками з комою (";").
Для роботи з графікою PostGIS SVG, ознайомтеся з бібліотекою pg_svg, яка надає функції plpgsql для роботи з результатами ST_AsSVG.
Покращено: 3.4.0 для підтримки всіх типів кривих
Змінено: 2.0.0 для використання аргументів за замовчуванням та підтримки іменованих аргументів
![]() | |
Доступність: 1.2.2. Доступність: 1.4.0 Змінено в PostGIS 1.4.0, щоб включити команду L в абсолютний шлях для відповідності http://www.w3.org/TR/SVG/paths.html#PathDataBNF |
This method supports Circular Strings and Curves.
SELECT ST_AsSVG('POLYGON((0 0,0 1,1 1,1 0,0 0))'::geometry);
st_assvg
--------
M 0 0 L 0 -1 1 -1 1 0 ZCircular string
SELECT ST_AsSVG( ST_GeomFromText('CIRCULARSTRING(-2 0,0 2,2 0,0 2,2 4)') );
st_assvg
--------
M -2 0 A 2 2 0 0 1 2 0 A 2 2 0 0 1 2 -4Multi-curve
SELECT ST_AsSVG('MULTICURVE((5 5,3 5,3 3,0 3),
CIRCULARSTRING(0 0,2 1,2 2))'::geometry, 0, 0);
st_assvg
------------------------------------------------
M 5 -5 L 3 -5 3 -3 0 -3 M 0 0 A 2 2 0 0 0 2 -2
Multi-surface
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);
st_assvg
---------------------------------------------------------
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
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, а код для створення клієнта JavaScript можна знайти за адресою https://github.com/TWKB/twkb.js. |
Покращено: 2.4.0 покращення пам'яті та швидкості.
Доступність: 2.2.0
SELECT ST_AsTWKB('LINESTRING(1 1,5 5)'::geometry);
st_astwkb
--------------------------------------------
\x02000202020808
Щоб створити агрегований об'єкт TWKB, що містить ідентифікатори, спочатку агрегуйте потрібні геометрії та об'єкти за допомогою функції "array_agg()", а потім викличте відповідну функцію TWKB.
SELECT ST_AsTWKB(array_agg(geom), array_agg(gid)) FROM mytable;
st_astwkb
--------------------------------------------
\x040402020400000202
ST_GeomFromTWKB, ST_AsBinary, ST_AsEWKB, ST_AsEWKT, ST_GeomFromText
ST_AsX3D — Повертає геометрію у форматі елемента вузла X3D xml: ISO-IEC-19776-1.2-X3DEncodings-XML
text ST_AsX3D(geometry g1, integer maxdecimaldigits=15, integer options=0);
Повертає геометрію у вигляді елемента вузла у форматі X3D xml http://www.web3d.org/standards/number/19776-1. Якщо maxdecimaldigits (точність) не вказано, то за замовчуванням використовується значення 15.
![]() | |
Існують різні варіанти перетворення геометрії PostGIS у X3D, оскільки типи геометрії X3D не відповідають безпосередньо типам геометрії PostGIS, а деякі новіші типи X3D, які можуть бути кращими відповідниками, ми уникнули, оскільки більшість інструментів візуалізації наразі їх не підтримують. Ось відповідники, на яких ми зупинилися. Якщо у вас є думки щодо цієї ідеї або способів, як ми можемо дозволити користувачам вказувати свої бажані відповідники, будь ласка, повідомте нам про це. Нижче наведено, як ми наразі відображаємо типи PostGIS 2D/3D у типи X3D |
Аргумент "options" є бітовим полем. У PostGIS 2.2+ він використовується для позначення того, чи слід представляти координати за допомогою геопросторового вузла X3D GeoCoordinates, а також чи слід міняти осі x/y. За замовчуванням ST_AsX3D виводить дані у формі бази даних (long,lat або X,Y), але може бути краще використовувати стандартні для X3D значення lat/lon, y/x.
0: X/Y у порядку бази даних (наприклад, long/lat = X,Y є стандартним порядком бази даних), значення за замовчуванням та непросторові координати (просто звичайний старий тег Coordinate).
1: Перевернути X і Y. Якщо використовується разом з опцією GeoCoordinate, то вихідні дані будуть за замовчуванням "latitude_first", а координати також будуть перевернуті.
2: Вивести координати в GeoSpatial GeoCoordinates. Ця опція видасть помилку, якщо геометрії не відповідають WGS 84 long lat (srid: 4326). Наразі це єдиний підтримуваний тип GeoCoordinate. Дивіться специфікації 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 |
| MULTIPOINT | Polypoint2D | PointSet |
| POINT | виводить координати, розділені пробілами | виводить координати, розділені пробілами |
| (MULTI) POLYGON, POLYHEDRALSURFACE | Недійсна розмітка X3D | IndexedFaceSet (внутрішні кільця наразі виводяться як інший набір облич) |
| TIN | TriangleSet2D (ще не реалізовано) | IndexedTriangleSet |
![]() | |
Підтримка 2D-геометрії ще не завершена. Внутрішні кільця наразі малюються як окремі полігони. Ми працюємо над цим. |
У 3D-просторі відбувається багато прогресивних змін, особливо в області інтеграції X3D з HTML5
Також є гарний відкритий X3D-переглядач, який можна використовувати для перегляду відтворених геометрій. Безкоштовні бінарні файли Free Wrl http://freewrl.sourceforge.net/ доступні для Mac, Linux та Windows. Для перегляду геометрій використовуйте пакет FreeWRL_Launcher.
Також зверніть увагу на мінімалістичний переглядач PostGIS X3D, який використовує цю функцію, та відкритий набір інструментів x3dDom html/js.
Доступність: 2.0.0: ISO-IEC-19776-1.2-X3DEncodings-XML
Покращено: 2.2.0: Підтримка геокоординат та перевертання осей (x/y, long/lat). Детальніше дивіться в налаштуваннях.
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).
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>
Скопіюйте та вставте результат цього запиту в x3d scene viewer і натисніть Show (Показати)
SELECT string_agg('<Shape
>' || ST_AsX3D(ST_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);

Будівлі, утворені шляхом поділу PostGIS та екструзії
SELECT ST_AsX3D(
ST_Translate(
ST_Force_3d(
ST_Buffer(ST_Point(10,10),5, 'quad_segs=2')), 0,0,
3)
,6) As x3dfrag;
x3dfrag
--------
<IndexedFaceSet 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>
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>
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);
Обчислює GeoHash представлення геометрії. GeoHash кодує географічну точку в текстову форму, яку можна сортувати та шукати за префіксом. Коротший GeoHash є менш точним представленням точки. Його можна уявити як прямокутник, що містить точку.
Значення геометрії, що не є точками, з ненульовим розміром також можна відобразити у кодах GeoHash. Точність коду залежить від географічного розміру геометрії.
Якщо maxchars не вказано, повертається код GeoHash для найменшої комірки, що містить вхідну геометрію. Точки повертають GeoHash з точністю 20 символів (це приблизно достатньо для повної подвійної точності вхідних даних). Інші геометричні типи можуть повертати GeoHash з меншою точністю, залежно від розміру геометрії. Більші геометрії представлені з меншою точністю, менші — з більшою. Коробка, визначена кодом GeoHash, завжди містить вхідний об'єкт.
Якщо вказано maxchars, то повернений код GeoHash має не більше цього значення символів. Він відображається на (можливо) менш точне представлення вхідної геометрії. Для не точкових об'єктів початковою точкою обчислення є центр обмежувальної рамки геометрії.
Доступність: 1.4.0
![]() | |
ST_GeoHash вимагає, щоб вхідні геометричні дані були в географічних координатах (довгота/широта). |
This method supports Circular Strings and Curves.
SELECT ST_GeoHash( ST_Point(-126,48) );
st_geohash
----------------------
c0w3hf1s70w3hf1s70w3
SELECT ST_GeoHash( ST_Point(-126,48), 5);
st_geohash
------------
c0w3h
-- This line contains the point, so the GeoHash is a prefix of the point code
SELECT ST_GeoHash('LINESTRING(-126 48, -126.1 48.1)'::geometry);
st_geohash
------------
c0w3
ST_GeomFromGeoHash, ST_PointFromGeoHash, ST_Box2dFromGeoHash
TRUE, якщо 2D обмежувальна рамка A перетинається з 2D обмежувальною рамкою B.TRUE, якщо (кешована) 2D обмежувальна рамка геометрії перетинає 2D обмежувальну рамку з плаваючою точністю (BOX2DF).TRUE, якщо 2D обмежувальна рамка з плаваючою точністю (BOX2DF) перетинає (кешовану) 2D обмежувальну рамку геометрії.TRUE, якщо дві обмежувальні рамки 2D з плаваючою точністю (BOX2DF) перетинаються між собою.TRUE, якщо n-D обмежувальна рамка A перетинається з n-D обмежувальною рамкою B.TRUE, якщо (кешована) n-вимірна обмежувальна рамка геометрії перетинає n-вимірну обмежувальну рамку з плаваючою точністю (GIDX).TRUE, якщо обмежувальна рамка з n-вимірною точністю (GIDX) перетинає (кешовану) n-вимірну обмежувальну рамку геометрії.TRUE, якщо дві n-вимірні обмежувальні рамки (GIDX) з плаваючою точністю перетинаються між собою.TRUE, якщо обмежувальна рамка A перекриває або знаходиться ліворуч від обмежувальної рамки B.TRUE, якщо обмежувальна рамка A перекриває або знаходиться нижче обмежувальної рамки B.TRUE, якщо обмежувальна рамка A перекриває або знаходиться праворуч від обмежувальної рамки B.TRUE, якщо обмежувальна рамка A знаходиться строго ліворуч від B.TRUE, якщо обмежувальна рамка A знаходиться строго нижче B.TRUE, якщо координати та порядок координат геометрії/географії A збігаються з координатами та порядком координат геометрії/географії B.TRUE, якщо обмежувальна рамка A знаходиться строго праворуч від B.TRUE, якщо обмежувальна рамка A міститься в обмежувальній рамці B.TRUE, якщо 2D обмежувальна рамка геометрії міститься в 2D обмежувальній рамці з плаваючою точністю (BOX2DF).TRUE, якщо 2D обмежувальна рамка з плаваючою точністю (BOX2DF) міститься в 2D обмежувальній рамці геометрії.TRUE, якщо 2D обмежувальна рамка з плаваючою точністю (BOX2DF) міститься в іншій 2D обмежувальній рамці з плаваючою точністю.TRUE, якщо обмежувальна рамка A перекриває або знаходиться над обмежувальною рамкою B.TRUE, якщо обмежувальна рамка A знаходиться строго над обмежувальною рамкою B.TRUE, якщо обмежувальна рамка A містить B.TRUE, якщо 2D обмежувальна рамка геометрії містить 2D обмежувальну рамку з плаваючою точністю (GIDX).TRUE, якщо обмежувальна рамка з плаваючою точністю 2D (BOX2DF) містить обмежувальну рамку 2D геометрії.TRUE, якщо обмежувальна рамка з точністю до 2D float (BOX2DF) містить іншу обмежувальну рамку з точністю до 2D float (BOX2DF).TRUE, якщо обмежувальна рамка A збігається з обмежувальною рамкою B.&& — Повертає TRUE, якщо 2D обмежувальна рамка A перетинається з 2D обмежувальною рамкою B.
boolean &&( geometry A , geometry B );
boolean &&( geography A , geography B );
Оператор && повертає TRUE, якщо 2D обмежувальна рамка геометрії A перетинає 2D обмежувальну рамку геометрії B.
![]() | |
Цей операнд буде використовувати будь-які індекси, які можуть бути доступні для геометрій. |
Покращено: 2.0.0 додано підтримку багатогранних поверхонь.
Доступність: 1.5.0 додано підтримку географії.
This method supports Circular Strings and Curves.
This function supports Polyhedral surfaces.
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)
&&(geometry,box2df) — Повертає TRUE, якщо (кешована) 2D обмежувальна рамка геометрії перетинає 2D обмежувальну рамку з плаваючою точністю (BOX2DF).
boolean &&( geometry A , box2df B );
Оператор && повертає TRUE, якщо кешована 2D обмежувальна рамка геометрії A перетинає 2D обмежувальну рамку B, використовуючи точність float. Це означає, що якщо B є (подвійної точності) box2d, вона буде внутрішньо перетворена в 2D обмежувальну рамку з точністю float (BOX2DF)
![]() | |
Цей операнд призначений для внутрішнього використання індексами BRIN, а не користувачами. |
Доступність: 2.3.0 додано підтримку індексів діапазону блоків (BRIN). Потрібна PostgreSQL 9.5+.
This method supports Circular Strings and Curves.
This function supports Polyhedral surfaces.
SELECT ST_Point(1,1) && ST_MakeBox2D(ST_Point(0,0), ST_Point(2,2)) AS overlaps; overlaps ---------- t (1 row)
&&(box2df,geometry) — Повертає TRUE, якщо 2D обмежувальна рамка з плаваючою точністю (BOX2DF) перетинає (кешовану) 2D обмежувальну рамку геометрії.
boolean &&( box2df A , geometry B );
Оператор && повертає TRUE, якщо 2D обмежувальна рамка A перетинає кешовану 2D обмежувальну рамку геометрії B, використовуючи точність float. Це означає, що якщо A є (подвійної точності) box2d, вона буде внутрішньо перетворена в 2D обмежувальну рамку з точністю float (BOX2DF)
![]() | |
Цей операнд призначений для внутрішнього використання індексами BRIN, а не користувачами. |
Доступність: 2.3.0 додано підтримку індексів діапазону блоків (BRIN). Потрібна PostgreSQL 9.5+.
This method supports Circular Strings and Curves.
This function supports Polyhedral surfaces.
SELECT ST_MakeBox2D(ST_Point(0,0), ST_Point(2,2)) && ST_Point(1,1) AS overlaps; overlaps ---------- t (1 row)
&&(box2df,box2df) — Повертає TRUE, якщо дві обмежувальні рамки 2D з плаваючою точністю (BOX2DF) перетинаються між собою.
boolean &&( box2df A , box2df B );
Оператор && повертає TRUE, якщо дві 2D обмежувальні рамки A і B перетинаються, використовуючи точність float. Це означає, що якщо A (або B) є (подвійної точності) box2d, вона буде внутрішньо перетворена в 2D обмежувальну рамку (BOX2DF) з точністю float
![]() | |
Цей оператор призначений для внутрішнього використання індексами BRIN, а не користувачами. |
Доступність: 2.3.0 додано підтримку індексів діапазону блоків (BRIN). Потрібна PostgreSQL 9.5+.
This method supports Circular Strings and Curves.
This function supports Polyhedral surfaces.
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)
&&& — Повертає TRUE, якщо n-D обмежувальна рамка A перетинається з n-D обмежувальною рамкою B.
boolean &&&( geometry A , geometry B );
Оператор &&& повертає TRUE, якщо n-вимірна обмежувальна рамка геометрії A перетинає n-вимірну обмежувальну рамку геометрії B.
![]() | |
Цей операнд буде використовувати будь-які індекси, які можуть бути доступні для геометрій. |
Доступність: 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.
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
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
&&&(geometry,gidx) — Повертає TRUE, якщо (кешована) n-вимірна обмежувальна рамка геометрії перетинає n-вимірну обмежувальну рамку з плаваючою точністю (GIDX).
boolean &&&( geometry A , gidx B );
Оператор &&& повертає TRUE, якщо кешована n-вимірна обмежувальна рамка геометрії A перетинає n-вимірну обмежувальну рамку B, використовуючи точність float. Це означає, що якщо B є (подвійної точності) box3d, вона буде внутрішньо перетворена в обмежувальну рамку 3D з точністю float (GIDX)
![]() | |
Цей оператор призначений для внутрішнього використання індексами BRIN, а не користувачами. |
Доступність: 2.3.0 додано підтримку індексів діапазону блоків (BRIN). Потрібна PostgreSQL 9.5+.
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.
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) — Повертає TRUE, якщо обмежувальна рамка з n-вимірною точністю (GIDX) перетинає (кешовану) n-вимірну обмежувальну рамку геометрії.
boolean &&&( gidx A , geometry B );
Оператор &&& повертає TRUE, якщо n-вимірна обмежувальна рамка A перетинає кешовану n-вимірну обмежувальну рамку геометрії B, використовуючи точність float. Це означає, що якщо A є (подвійної точності) box3d, вона буде внутрішньо перетворена в 3D обмежувальну рамку (GIDX) з точністю float
![]() | |
Цей оператор призначений для внутрішнього використання індексами BRIN, а не користувачами. |
Доступність: 2.3.0 додано підтримку індексів діапазону блоків (BRIN). Потрібна PostgreSQL 9.5+.
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.
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) — Повертає TRUE, якщо дві n-вимірні обмежувальні рамки (GIDX) з плаваючою точністю перетинаються між собою.
boolean &&&( gidx A , gidx B );
Оператор &&& повертає TRUE, якщо дві n-вимірні обмежувальні рамки A і B перетинаються, використовуючи точність float. Це означає, що якщо A (або B) є (подвійної точності) box3d, вона буде внутрішньо перетворена в обмежувальну рамку 3D з точністю float (GIDX)
![]() | |
Цей оператор призначений для внутрішнього використання індексами BRIN, а не користувачами. |
Доступність: 2.3.0 додано підтримку індексів діапазону блоків (BRIN). Потрібна PostgreSQL 9.5+.
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.
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)
&< — Повертає TRUE, якщо обмежувальна рамка A перекриває або знаходиться ліворуч від обмежувальної рамки B.
boolean &<( geometry A , geometry B );
Оператор &< повертає TRUE, якщо обмежувальна рамка геометрії A перекриває або знаходиться ліворуч від обмежувальної рамки геометрії B, або, точніше, перекриває або НЕ знаходиться праворуч від обмежувальної рамки геометрії B.
![]() | |
Цей операнд буде використовувати будь-які індекси, які можуть бути доступні для геометрій. |
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)
&<| — Повертає TRUE, якщо обмежувальна рамка A перекриває або знаходиться нижче обмежувальної рамки B.
boolean &<|( geometry A , geometry B );
Оператор &<| повертає TRUE, якщо обмежувальна рамка геометрії A перекриває або знаходиться нижче обмежувальної рамки геометрії B, або, точніше, перекриває або НЕ знаходиться вище обмежувальної рамки геометрії B.
This method supports Circular Strings and Curves.
This function supports Polyhedral surfaces.
![]() | |
Цей операнд буде використовувати будь-які індекси, які можуть бути доступні для геометрій. |
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)
&> — Повертає TRUE, якщо обмежувальна рамка A перекриває або знаходиться праворуч від обмежувальної рамки B.
boolean &>( geometry A , geometry B );
Оператор &> повертає TRUE, якщо обмежувальна рамка геометрії A перекриває або знаходиться праворуч від обмежувальної рамки геометрії B, або, точніше, перекриває або НЕ знаходиться ліворуч від обмежувальної рамки геометрії B.
![]() | |
Цей операнд буде використовувати будь-які індекси, які можуть бути доступні для геометрій. |
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)
<< — Повертає TRUE, якщо обмежувальна рамка A знаходиться строго ліворуч від B.
boolean <<( geometry A , geometry B );
Оператор << повертає TRUE, якщо обмежувальна рамка геометрії A знаходиться строго ліворуч від обмежувальної рамки геометрії B.
![]() | |
Цей операнд буде використовувати будь-які індекси, які можуть бути доступні для геометрій. |
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)
<<| — Повертає TRUE, якщо обмежувальна рамка A знаходиться строго нижче B.
boolean <<|( geometry A , geometry B );
Оператор <<| повертає TRUE, якщо обмежувальна рамка геометрії A знаходиться строго нижче обмежувальної рамки геометрії B.
![]() | |
Цей операнд буде використовувати будь-які індекси, які можуть бути доступні для геометрій. |
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)
= — Повертає TRUE, якщо координати та порядок координат геометрії/географії A збігаються з координатами та порядком координат геометрії/географії B.
boolean =( geometry A , geometry B );
boolean =( geography A , geography B );
Оператор = повертає TRUE, якщо координати та порядок координат геометрії/географії A збігаються з координатами та порядком координат геометрії/географії B. PostgreSQL використовує оператори =, < та >, визначені для геометрій, для виконання внутрішнього впорядкування та порівняння геометрій (тобто в операторах GROUP BY або ORDER BY).
![]() | |
Цей оператор вважає рівними лише геометрію/географію, які є абсолютно однаковими в усіх відношеннях, мають однакові координати в однаковому порядку. Для "просторової рівності", яка ігнорує такі речі, як порядок координат, і може виявляти об'єкти, що займають однакову просторову площу, але мають різне представлення, використовуйте ST_OrderingEqualsабо ST_Equals |
![]() | |
Цей операнд НЕ використовуватиме жодних індексів, які можуть бути доступні для геометрій. Для перевірки точної рівності за допомогою індексу поєднайте = з &&. |
Змінено: 2.4.0, у попередніх версіях це була рівність обмежувальної рамки, а не геометрична рівність. Якщо вам потрібна рівність обмежувальної рамки, використовуйте замість цього ~=.
This method supports Circular Strings and Curves.
This function supports Polyhedral surfaces.
SELECT 'LINESTRING(0 0, 0 1, 1 0)'::geometry = 'LINESTRING(1 1, 0 0)'::geometry;
?column?
----------
f
(1 row)
SELECT ST_AsText(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)
-- Note: the GROUP BY uses the "=" to compare for geometry equivalency.
SELECT ST_AsText(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)
-- In versions prior to 2.0, this used to return true --
SELECT ST_GeomFromText('POINT(1707296.37 4820536.77)') =
ST_GeomFromText('POINT(1707296.27 4820536.87)') As pt_intersect;
--pt_intersect --
f
>> — Повертає TRUE, якщо обмежувальна рамка A знаходиться строго праворуч від B.
boolean >>( geometry A , geometry B );
Оператор >> повертає TRUE, якщо обмежувальна рамка геометрії A знаходиться строго праворуч від обмежувальної рамки геометрії B.
![]() | |
Цей операнд буде використовувати будь-які індекси, які можуть бути доступні для геометрій. |
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)
@ — Повертає TRUE, якщо обмежувальна рамка A міститься в обмежувальній рамці B.
boolean @( geometry A , geometry B );
Оператор @ повертає TRUE, якщо обмежувальна рамка геометрії A повністю міститься в обмежувальній рамці геометрії B.
![]() | |
Цей операнд буде використовувати будь-які індекси, які можуть бути доступні для геометрій. |
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)
@(geometry,box2df) — Повертає TRUE, якщо 2D обмежувальна рамка геометрії міститься в 2D обмежувальній рамці з плаваючою точністю (BOX2DF).
boolean @( geometry A , box2df B );
Оператор @ повертає TRUE, якщо 2D обмежувальна рамка геометрії A міститься в 2D обмежувальній рамці B, використовуючи точність float. Це означає, що якщо B є (подвійної точності) box2d, вона буде внутрішньо перетворена в 2D обмежувальну рамку з точністю float (BOX2DF)
![]() | |
Цей операнд призначений для внутрішнього використання індексами BRIN, а не користувачами. |
Доступність: 2.3.0 додано підтримку індексів діапазону блоків (BRIN). Потрібна PostgreSQL 9.5+.
This method supports Circular Strings and Curves.
This function supports Polyhedral surfaces.
SELECT ST_Buffer(ST_GeomFromText('POINT(2 2)'), 1) @ ST_MakeBox2D(ST_Point(0,0), ST_Point(5,5)) AS is_contained;
is_contained
--------------
t
(1 row)@(box2df,geometry) — Повертає TRUE, якщо 2D обмежувальна рамка з плаваючою точністю (BOX2DF) міститься в 2D обмежувальній рамці геометрії.
boolean @( box2df A , geometry B );
Оператор @ повертає TRUE, якщо 2D обмежувальна рамка A міститься в 2D обмежувальній рамці геометрії B, використовуючи точність float. Це означає, що якщо B є (подвійної точності) box2d, вона буде внутрішньо перетворена в 2D обмежувальну рамку з точністю float (BOX2DF)
![]() | |
Цей операнд призначений для внутрішнього використання індексами BRIN, а не користувачами. |
Доступність: 2.3.0 додано підтримку індексів діапазону блоків (BRIN). Потрібна PostgreSQL 9.5+.
This method supports Circular Strings and Curves.
This function supports Polyhedral surfaces.
SELECT ST_MakeBox2D(ST_Point(2,2), ST_Point(3,3)) @ ST_Buffer(ST_GeomFromText('POINT(1 1)'), 10) AS is_contained;
is_contained
--------------
t
(1 row)@(box2df,box2df) — Повертає TRUE, якщо 2D обмежувальна рамка з плаваючою точністю (BOX2DF) міститься в іншій 2D обмежувальній рамці з плаваючою точністю.
boolean @( box2df A , box2df B );
Оператор @ повертає TRUE, якщо 2D обмежувальна рамка A міститься в 2D обмежувальній рамці B, використовуючи точність float. Це означає, що якщо A (або B) є (подвійної точності) box2d, вона буде внутрішньо перетворена в 2D обмежувальну рамку з точністю float (BOX2DF)
![]() | |
Цей операнд призначений для внутрішнього використання індексами BRIN, а не користувачами. |
Доступність: 2.3.0 додано підтримку індексів діапазону блоків (BRIN). Потрібна PostgreSQL 9.5+.
This method supports Circular Strings and Curves.
This function supports Polyhedral surfaces.
SELECT ST_MakeBox2D(ST_Point(2,2), ST_Point(3,3)) @ ST_MakeBox2D(ST_Point(0,0), ST_Point(5,5)) AS is_contained; is_contained -------------- t (1 row)
|&> — Повертає TRUE, якщо обмежувальна рамка A перекриває або знаходиться над обмежувальною рамкою B.
boolean |&>( geometry A , geometry B );
Оператор |&> повертає TRUE, якщо обмежувальна рамка геометрії A перекриває або знаходиться над обмежувальною рамкою геометрії B, або, точніше, перекриває або НЕ знаходиться нижче обмежувальної рамки геометрії B.
![]() | |
Цей операнд буде використовувати будь-які індекси, які можуть бути доступні для геометрій. |
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)
|>> — Повертає TRUE, якщо обмежувальна рамка A знаходиться строго над обмежувальною рамкою B.
boolean |>>( geometry A , geometry B );
Оператор |>> повертає TRUE, якщо обмежувальна рамка геометрії A знаходиться строго над обмежувальною рамкою геометрії B.
![]() | |
Цей операнд буде використовувати будь-які індекси, які можуть бути доступні для геометрій. |
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)~ — Повертає TRUE, якщо обмежувальна рамка A містить B.
boolean ~( geometry A , geometry B );
Оператор ~ повертає TRUE, якщо обмежувальна рамка геометрії A повністю містить обмежувальну рамку геометрії B.
![]() | |
Цей операнд буде використовувати будь-які індекси, які можуть бути доступні для геометрій. |
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)~(geometry,box2df) — Повертає TRUE, якщо 2D обмежувальна рамка геометрії містить 2D обмежувальну рамку з плаваючою точністю (GIDX).
boolean ~( geometry A , box2df B );
Оператор ~ повертає TRUE, якщо 2D обмежувальна рамка геометрії A містить 2D обмежувальну рамку B, використовуючи точність float. Це означає, що якщо B є (подвійної точності) box2d, вона буде внутрішньо перетворена в 2D обмежувальну рамку з точністю float (BOX2DF)
![]() | |
Цей операнд призначений для внутрішнього використання індексами BRIN, а не користувачами. |
Доступність: 2.3.0 додано підтримку індексів діапазону блоків (BRIN). Потрібна PostgreSQL 9.5+.
This method supports Circular Strings and Curves.
This function supports Polyhedral surfaces.
SELECT ST_Buffer(ST_GeomFromText('POINT(1 1)'), 10) ~ ST_MakeBox2D(ST_Point(0,0), ST_Point(2,2)) AS contains;
contains
----------
t
(1 row)~(box2df,geometry) — Повертає TRUE, якщо обмежувальна рамка з плаваючою точністю 2D (BOX2DF) містить обмежувальну рамку 2D геометрії.
boolean ~( box2df A , geometry B );
Оператор ~ повертає TRUE, якщо 2D обмежувальна рамка A містить обмежувальну рамку геометрії B, використовуючи точність float. Це означає, що якщо A є (подвійної точності) box2d, вона буде внутрішньо перетворена в 2D обмежувальну рамку з точністю float (BOX2DF)
![]() | |
Цей операнд призначений для внутрішнього використання індексами BRIN, а не користувачами. |
Доступність: 2.3.0 додано підтримку індексів діапазону блоків (BRIN). Потрібна PostgreSQL 9.5+.
This method supports Circular Strings and Curves.
This function supports Polyhedral surfaces.
SELECT ST_MakeBox2D(ST_Point(0,0), ST_Point(5,5)) ~ ST_Buffer(ST_GeomFromText('POINT(2 2)'), 1) AS contains;
contains
----------
t
(1 row)~(box2df,box2df) — Повертає TRUE, якщо обмежувальна рамка з точністю до 2D float (BOX2DF) містить іншу обмежувальну рамку з точністю до 2D float (BOX2DF).
boolean ~( box2df A , box2df B );
Оператор ~ повертає TRUE, якщо 2D обмежувальна рамка A містить 2D обмежувальну рамку B, використовуючи точність float. Це означає, що якщо A є (подвійної точності) box2d, вона буде внутрішньо перетворена в 2D обмежувальну рамку з точністю float (BOX2DF)
![]() | |
Цей операнд призначений для внутрішнього використання індексами BRIN, а не користувачами. |
Доступність: 2.3.0 додано підтримку індексів діапазону блоків (BRIN). Потрібна PostgreSQL 9.5+.
This method supports Circular Strings and Curves.
This function supports Polyhedral surfaces.
SELECT ST_MakeBox2D(ST_Point(0,0), ST_Point(5,5)) ~ ST_MakeBox2D(ST_Point(2,2), ST_Point(3,3)) AS contains; contains ---------- t (1 row)
~= — Повертає TRUE, якщо обмежувальна рамка A збігається з обмежувальною рамкою B.
boolean ~=( geometry A , geometry B );
Оператор ~= повертає TRUE, якщо обмежувальна рамка геометрії/географії A збігається з обмежувальною рамкою геометрії/географії B.
![]() | |
Цей операнд буде використовувати будь-які індекси, які можуть бути доступні для геометрій. |
Доступність: 1.5.0 змінено поведінку
This function supports Polyhedral surfaces.
![]() | |
У PostGIS 1.5 поведінка цього оператора змінилася: замість перевірки фактичної геометричної рівності тепер перевіряється лише рівність обмежувальної рамки. Щоб ускладнити справу, поведінка оператора також залежить від того, чи було оновлення жорстким чи м'яким. Щоб дізнатися, яку поведінку має ваша база даних, виконайте запит, наведений нижче. Щоб перевірити справжню рівність, використовуйте ST_OrderingEqualsабо ST_Equals. |
select 'LINESTRING(0 0, 1 1)'::geometry ~= 'LINESTRING(0 1, 1 0)'::geometry as equality;
equality |
-----------------+
t |
<-> — Повертає 2D відстань між A і B.
double precision <->( geometry A , geometry B );
double precision <->( geography A , geography B );
Оператор <-> повертає двовимірну відстань між двома геометріями. Використовується в розділі "ORDER BY" для отримання наборів результатів найближчих сусідів за допомогою індексу. Для PostgreSQL нижче 9.5 повертає тільки відстань до центроїда обмежувальних рамок, а для PostgreSQL 9.5+ виконує пошук справжньої відстані KNN, що дає справжню відстань між геометріями та відстань до сфери для географічних об'єктів.
![]() | |
Цей операнд використовує 2D-індекси GiST, які можуть бути доступні для геометрій. Він відрізняється від інших операторів, що використовують просторові індекси, тим, що просторовий індекс використовується тільки тоді, коли оператор знаходиться в розділі ORDER BY. |
![]() | |
Індекс спрацьовує тільки в тому випадку, якщо одна з геометрій є константою (не знаходиться в підзапиті/cte). Наприклад, “SRID=3005;POINT(1011102 450541)”::geometry замість a.geom |
Детальний приклад див. у семінарі PostGIS: Пошук найближчих сусідів.
Покращено: 2.2.0 — Поведінка True KNN ("K найближчих сусідів") для геометрії та географії для PostgreSQL 9.5+. Примітка щодо географії: KNN базується на сфері, а не на сфероїді. Для PostgreSQL 9.4 та нижчих версій підтримка географії є новою, але підтримує лише центроїдні прямокутники.
Змінено: 2.2.0 — Для користувачів PostgreSQL 9.5 старий гібридний синтаксис може працювати повільніше, тому вам слід позбутися цього хаку, якщо ви виконуєте свій код тільки на PostGIS 2.2+ 9.5+. Дивіться приклади нижче.
Доступність: 2.0.0 — Weak KNN надає найближчих сусідів на основі геометричних відстаней до центроїдів замість реальних відстаней. Точні результати для точок, неточні для всіх інших типів. Доступно для PostgreSQL 9.1+
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:
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" для двох запитів, ви побачите підвищення продуктивності для другого.
Для користувачів, які працюють з PostgreSQL < 9.5, використовуйте гібридний запит, щоб знайти найближчих сусідів. Спочатку виконайте запит CTE з використанням KNN з індексом, а потім точний запит, щоб отримати правильний порядок:
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 у найближчій точці їх зближення.
double precision |=|( geometry A , geometry B );
Оператор |=| повертає 3D відстань між двома траєкторіями (див. ST_IsValidTrajectory). Це те саме, що ST_DistanceCPA, але як оператор його можна використовувати для пошуку найближчих сусідів за допомогою N-вимірного індексу (потрібна PostgreSQL 9.5.0 або вище).
![]() | |
Цей операнд використовує індекси ND GiST, які можуть бути доступні для геометрій. Він відрізняється від інших операторів, що використовують просторові індекси, тим, що просторовий індекс використовується тільки тоді, коли оператор знаходиться в розділі ORDER BY. |
![]() | |
Індекс спрацьовує тільки в тому випадку, якщо одна з геометрій є константою (не в підзапиті/cte). Наприклад, “SRID=3005;LINESTRINGM(0 0 0,0 0 1)”::geometry замість a.geom. |
Доступність: 2.2.0. Підтримка індексу доступна тільки для PostgreSQL 9.5+
-- Save a literal query trajectory in a psql variable...
\set qt 'ST_AddMeasure(ST_MakeLine(ST_MakePointM(-350,300,0),ST_MakePointM(-410,490,0)),10,20)'
-- Run the query !
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)
<#> — Повертає 2D відстань між обмежувальними рамками A і B.
double precision <#>( geometry A , geometry B );
Оператор <#> повертає відстань між двома обмежувальними рамками з плаваючою точкою, можливо зчитуючи їх з просторового індексу (потрібна PostgreSQL 9.1+). Корисно для наближеного упорядкування найближчих сусідів за відстанню.
![]() | |
Цей операнд використовує всі індекси, які можуть бути доступні для геометрій. Він відрізняється від інших операторів, які використовують просторові індекси, тим, що просторовий індекс використовується тільки тоді, коли оператор знаходиться в розділі ORDER BY. |
![]() | |
Індекс спрацьовує тільки в тому випадку, якщо одна з геометрій є константою, наприклад ORDER BY (ST_GeomFromText(“POINT(1 2)”) <#> geom) замість g1.geom <#>. |
Доступність: 2.0.0 — KNN доступний тільки для PostgreSQL 9.1+
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)
<<->> — Повертає n-вимірну відстань між геометріями A і B або обмежувальними рамками
double precision <<->>( geometry A , geometry B );
Оператор <<->> повертає n-вимірну (евклідову) відстань між центроїдами обмежувальних рамок двох геометрій. Корисний для наближеного упорядкування найближчих сусідів за відстанню.
![]() | |
Цей операнд використовує індекси n-D GiST, які можуть бути доступні для геометрій. Він відрізняється від інших операторів, що використовують просторові індекси, тим, що просторовий індекс використовується тільки тоді, коли оператор знаходиться в розділі ORDER BY. |
![]() | |
Індекс спрацьовує тільки в тому випадку, якщо одна з геометрій є константою (не знаходиться в підзапиті/cte). Наприклад, “SRID=3005;POINT(1011102 450541)”::geometry замість a.geom |
Доступність: 2.2.0 — KNN доступний тільки для PostgreSQL 9.1+
These functions determine spatial relationships between geometries.
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
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)
SELECT ST_3DIntersects('TIN(((0 0 0,1 0 0,0 1 0,0 0 0)))'::geometry, 'POINT(.1 .1 0)'::geometry);
st_3dintersects
-----------------
tST_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 |
Виконано модулем 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 |
![]() | |
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:
![]()
| ![]()
|
![]()
| ![]()
|
ST_Contains returns FALSE in the following situations:
![]()
| ![]()
|
Due to the interior intersection condition ST_Contains returns FALSE in the following situations (whereas ST_Covers returns TRUE):
![]()
| ![]()
|
-- A circle within a circle
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 (SELECT ST_Buffer(ST_GeomFromText('POINT(1 2)'), 10) As smallc,
ST_Buffer(ST_GeomFromText('POINT(1 2)'), 20) As bigc) As foo;
-- Result
smallcontainsbig | bigcontainssmall | bigcontainsunion | bigisunion | bigcoversexterior | bigcontainsexterior
------------------+------------------+------------------+------------+-------------------+---------------------
f | t | t | t | t | f
-- Example demonstrating difference between contains and contains properly
SELECT ST_GeometryType(geomA) As geomtype, ST_Contains(geomA,geomA) AS acontainsa, ST_ContainsProperly(geomA, geomA) AS acontainspropa,
ST_Contains(geomA, ST_Boundary(geomA)) As acontainsba, ST_ContainsProperly(geomA, ST_Boundary(geomA)) 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(geomA);
geomtype | acontainsa | acontainspropa | acontainsba | acontainspropba
--------------+------------+----------------+-------------+-----------------
ST_Polygon | t | f | f | f
ST_LineString | t | f | f | f
ST_Point | t | t | f | f
ST_Boundary, ST_ContainsProperly, ST_Covers, ST_CoveredBy, ST_Equals, ST_Within
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 |
![]() | |
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 |
![]() | |
Do not use this function with invalid geometries. You will get unexpected results. |
--a circle within a circle
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 (SELECT ST_Buffer(ST_GeomFromText('POINT(1 2)'), 10) As smallc,
ST_Buffer(ST_GeomFromText('POINT(1 2)'), 20) As bigc) As foo;
--Result
smallcontainspropbig | bigcontainspropsmall | bigcontainspropunion | bigisunion | bigcoversexterior | bigcontainsexterior
------------------+------------------+------------------+------------+-------------------+---------------------
f | t | f | t | t | f
--example demonstrating difference between contains and contains properly
SELECT ST_GeometryType(geomA) As geomtype, ST_Contains(geomA,geomA) AS acontainsa, ST_ContainsProperly(geomA, geomA) AS acontainspropa,
ST_Contains(geomA, ST_Boundary(geomA)) As acontainsba, ST_ContainsProperly(geomA, ST_Boundary(geomA)) 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(geomA);
geomtype | acontainsa | acontainspropa | acontainsba | acontainspropba
--------------+------------+----------------+-------------+-----------------
ST_Polygon | t | f | f | f
ST_LineString | t | f | f | f
ST_Point | t | t | f | f
ST_GeometryType, ST_Boundary, ST_Contains, ST_Covers, ST_CoveredBy, ST_Equals, ST_Relate, ST_Within
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 |
![]() | |
Enhanced: 3.0.0 enabled support for |
![]() | |
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.
--a circle coveredby a circle
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 exeriorwithinbig
FROM (SELECT ST_Buffer(ST_GeomFromText('POINT(1 2)'), 10) As smallc,
ST_Buffer(ST_GeomFromText('POINT(1 2)'), 20) As bigc) As foo;
--Result
smallinsmall | smallcoveredbybig | exteriorcoveredbybig | exeriorwithinbig
--------------+-------------------+----------------------+------------------
t | t | t | f
(1 row) 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 |
![]() | |
Enhanced: 3.0.0 enabled support for |
![]() | |
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 — додано підтримку географії.
Доступність: 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
--a circle covering a circle
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 (SELECT ST_Buffer(ST_GeomFromText('POINT(1 2)'), 10) As smallc,
ST_Buffer(ST_GeomFromText('POINT(1 2)'), 20) As bigc) As foo;
--Result
smallinsmall | smallcoversbig | bigcoversexterior | bigcontainsexterior
--------------+----------------+-------------------+---------------------
t | f | t | f
(1 row) Geeography Example
-- a point with a 300 meter buffer compared to a point, a point and its 10 meter buffer
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(ST_GeogFromText('SRID=4326;POINT(-99.327 31.4821)'), 300) As geog_poly,
ST_GeogFromText('SRID=4326;POINT(-99.33 31.483)') 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 |
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.
![]()
| ![]()
|
![]()
| ![]()
|
Consider a situation where a user has two tables: a table of roads and a table of highways.
CREATE TABLE roads ( id serial NOT NULL, geom geometry, CONSTRAINT roads_pkey PRIMARY KEY (road_id) );
|
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:
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 |
Виконано модулем GEOS
![]() | |
This function call does not use indexes. A negated ST_Intersects predicate can be used as a more performant alternative that uses indexes: |
![]() | |
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
SELECT ST_Disjoint('POINT(0 0)'::geometry, 'LINESTRING ( 2 0, 0 2 )'::geometry);
st_disjoint
---------------
t
(1 row)
SELECT ST_Disjoint('POINT(0 0)'::geometry, 'LINESTRING ( 0 0, 0 2 )'::geometry);
st_disjoint
---------------
f
(1 row)
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 |
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
SELECT ST_Equals(ST_GeomFromText('LINESTRING(0 0, 10 10)'),
ST_GeomFromText('LINESTRING(0 0, 5 5, 10 10)'));
st_equals
-----------
t
(1 row)
SELECT ST_Equals(ST_Reverse(ST_GeomFromText('LINESTRING(0 0, 10 10)')),
ST_GeomFromText('LINESTRING(0 0, 5 5, 10 10)'));
st_equals
-----------
t
(1 row)
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).
SELECT ST_Intersects('POINT(0 0)'::geometry, 'LINESTRING ( 2 0, 0 2 )'::geometry);
st_intersects
---------------
f
(1 row)
SELECT ST_Intersects('POINT(0 0)'::geometry, 'LINESTRING ( 0 0, 0 2 )'::geometry);
st_intersects
---------------
t
(1 row)
-- Look up in table. Make sure table has a GiST index on geometry column for faster lookup.
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)
SELECT ST_Intersects(
'SRID=4326;LINESTRING(-43.23456 72.4567,-43.23456 72.4568)'::geography,
'SRID=4326;POINT(-43.23456 72.4567772)'::geography
);
st_intersects
---------------
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

Blue: Line A; Green: Line B
SELECT ST_LineCrossingDirection(lineA, lineB) As A_cross_B,
ST_LineCrossingDirection(lineB, lineA) As B_cross_A
FROM (SELECT
ST_GeomFromText('LINESTRING(25 169,89 114,40 70,86 43)') As lineA,
ST_GeomFromText('LINESTRING (20 140, 71 74, 161 53)') As lineB
) As foo;
A_cross_B | B_cross_A
-----------+-----------
-1 | 1
Example: LINE MULTICROSS END SAME FIRST LEFT and LINE MULTICROSS END SAME FIRST RIGHT

Blue: Line A; Green: Line B
SELECT ST_LineCrossingDirection(lineA, lineB) As A_cross_B,
ST_LineCrossingDirection(lineB, lineA) As B_cross_A
FROM (SELECT
ST_GeomFromText('LINESTRING(25 169,89 114,40 70,86 43)') As lineA,
ST_GeomFromText('LINESTRING(171 154,20 140,71 74,161 53)') As lineB
) As foo;
A_cross_B | B_cross_A
-----------+-----------
3 | -3
Example: LINE MULTICROSS END LEFT and LINE MULTICROSS END RIGHT

Blue: Line A; Green: Line B
SELECT ST_LineCrossingDirection(lineA, lineB) As A_cross_B,
ST_LineCrossingDirection(lineB, lineA) As B_cross_A
FROM (SELECT
ST_GeomFromText('LINESTRING(25 169,89 114,40 70,86 43)') As lineA,
ST_GeomFromText('LINESTRING(5 90, 71 74, 20 140, 171 154)') As lineB
) As foo;
A_cross_B | B_cross_A
-----------+-----------
-2 | 2
Example: Finds all streets that cross
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
SELECT ST_OrderingEquals( 'LINESTRING(0 0, 10 10)', 'LINESTRING(0 0, 5 5, 10 10)'); st_orderingequals ----------- f SELECT ST_OrderingEquals( 'LINESTRING(0 0, 10 10)', 'LINESTRING(0 0, 10 10)'); st_orderingequals ----------- t 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))'); st_orderingequals ----------- f
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 |
Виконано модулем GEOS
![]() | |
Enhanced: 3.0.0 enabled support for |
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:
![]()
| ![]()
| ![]()
|

A Point on a LineString is contained, but since it has lower dimension it does not overlap or cross.
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 ST_GeomFromText('POINT (100 100)') As a,
ST_GeomFromText('LINESTRING (30 50, 40 160, 160 40, 180 160)') AS b) AS t
overlaps | crosses | intersects | b_contains_a
---------+----------------------+--------------
f | f | t | t

A LineString that partly covers a Polygon intersects and crosses, but does not overlap since it has different dimension.
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 ST_GeomFromText('POLYGON ((40 170, 90 30, 180 100, 40 170))') AS a,
ST_GeomFromText('LINESTRING(10 10, 190 190)') AS b) AS t;
overlap | crosses | intersects | contains
---------+---------+------------+--------------
f | t | t | f

Two Polygons that intersect but with neither contained by the other overlap, but do not cross because their intersection has the same dimension.
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 ST_GeomFromText('POLYGON ((40 170, 90 30, 180 100, 40 170))') AS a,
ST_GeomFromText('POLYGON ((110 180, 20 60, 130 90, 110 180))') AS b) As t;
overlaps | crosses | intersects | b_contains_a | dim_a | dim_b | dim_int
----------+---------+------------+--------------+-------+-------+-----------
t | f | t | f | 2 | 2 | 2
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 Section 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 |
Using the boolean-valued function to test spatial relationships.
SELECT ST_Relate('POINT(1 2)', ST_Buffer( 'POINT(1 2)', 2), '0FFFFF212');
st_relate
-----------
t
SELECT ST_Relate(POINT(1 2)', ST_Buffer( 'POINT(1 2)', 2), '*FF*FF212');
st_relate
-----------
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)
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.
SELECT ST_Relate( 'POINT(1 2)',
ST_Buffer( 'POINT(1 2)', 2));
-----------
0FFFFF212
SELECT ST_Relate( 'LINESTRING(1 2, 3 4)',
'LINESTRING(5 6, 7 8)' );
-----------
FF1FF0102
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.
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
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 Section 5.1, “Determining Spatial Relationships”.
Виконано модулем GEOS
Доступність: 2.0.0
SELECT ST_RelateMatch('101202FFF', 'TTTTTTFFF') ;
-- result --
t
Patterns for common spatial relationships matched against intersection matrix values, for a line in various positions relative to a polygon
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 |
![]() | |
Enhanced: 3.0.0 enabled support for |
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.
![]()
| ![]()
| ![]()
|
![]()
| ![]()
| ![]()
|
SELECT ST_Touches('LINESTRING(0 0, 1 1, 0 2)'::geometry, 'POINT(1 1)'::geometry);
st_touches
------------
f
(1 row)
SELECT ST_Touches('LINESTRING(0 0, 1 1, 0 2)'::geometry, 'POINT(0 2)'::geometry);
st_touches
------------
t
(1 row)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 |
Виконано модулем 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 |
![]() | |
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
--a circle within a circle
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
(
SELECT ST_Buffer(ST_GeomFromText('POINT(50 50)'), 20) As smallc,
ST_Buffer(ST_GeomFromText('POINT(50 50)'), 40) As bigc) As foo;
--Result
smallinsmall | smallinbig | biginsmall | unioninbig | biginunion | bigisunion
--------------+------------+------------+------------+------------+------------
t | t | f | t | t | t
(1 row)
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
-- Geometry example - units in meters (SRID: 2163 US National Atlas Equal area) (3D point and line compared 2D point and line)
-- Note: currently no vertical datum support so Z is not transformed and assumed to be same units as final.
SELECT ST_3DDWithin(
ST_Transform(ST_GeomFromEWKT('SRID=4326;POINT(-72.1235 42.3521 4)'),2163),
ST_Transform(ST_GeomFromEWKT('SRID=4326;LINESTRING(-72.1260 42.45 15, -72.123 42.1546 20)'),2163),
126.8
) As within_dist_3d,
ST_DWithin(
ST_Transform(ST_GeomFromEWKT('SRID=4326;POINT(-72.1235 42.3521 4)'),2163),
ST_Transform(ST_GeomFromEWKT('SRID=4326;LINESTRING(-72.1260 42.45 15, -72.123 42.1546 20)'),2163),
126.8
) As within_dist_2d;
within_dist_3d | within_dist_2d
----------------+----------------
f | t
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 compares the difference between fully within and distance within as well
-- as the distance fully within for the 2D footprint of the line/point vs. the 3d fully within
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
(select ST_GeomFromEWKT('POINT(1 1 2)') as geom_a,
ST_GeomFromEWKT('LINESTRING(1 5 2, 2 7 20, 1 9 100, 14 12 3)') as geom_b) t1;
d3dfullywithin10 | d3dwithin10 | d2dfullywithin20 | d3dfullywithin20
------------------+-------------+------------------+------------------
f | t | t | f 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.
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)', 'LINESTRING(1 5, 2 7, 1 9, 14 12)')
) AS v(geom_a, geom_b)
dfullywithin10 | dwithin10 | dfullywithin20
----------------+-----------+----------------
f | t | t
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
Покращено: 2.1.0 покращено швидкість роботи з географією. Детальніше див. Пришвидшення роботи з географією.
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.
-- 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
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 is in units of spatial ref (e.g. meters, feet, degrees)
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 broadcasting towers that receiver with limited range can receive.
-- Data is geometry in Spherical Mercator (SRID=3857), ranges are approximate.
-- Create geometry index that will check proximity limit of user to tower
CREATE INDEX ON broadcasting_towers using gist (geom);
-- Create geometry index that will check proximity limit of tower to user
CREATE INDEX ON broadcasting_towers using gist (ST_Expand(geom, sending_range));
-- Query towers that 4-kilometer receiver in Minsk Hackerspace can get
-- Note: two conditions, because shorter LEAST(b.sending_range, 4000) will not use index.
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
SELECT ST_PointInsideCircle(ST_Point(1,2), 0.5, 2, 3); st_pointinsidecircle ------------------------ t
Ці функції обчислюють відстані, площі та кути. Існують також функції для обчислення геометричних величин, визначених за вимірами.
ST_LengthST_Perimeter.ST_Area — Повертає площу полігональної геометрії.
float ST_Area(geometry g1);
float ST_Area(geography geog, boolean use_spheroid = true);
Повертає площу полігональної геометрії. Для типів геометрії обчислюється площина 2D (плоска) з одиницями, визначеними SRID. Для типів географії за замовчуванням площа визначається на сфероїді з одиницями в квадратних метрах. Для обчислення площі за допомогою швидшої, але менш точної сферичної моделі використовуйте ST_Area(geog,false).
Покращено: 2.0.0 - додано підтримку 2D багатогранних поверхонь.
Покращено: 2.2.0 — вимірювання на сфероїді виконується за допомогою GeographicLib для підвищення точності та надійності. Для використання нової функції потрібно PROJ >= 4.9.0.
Змінено: 3.0.0 - більше не залежить від SFCGAL.
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.
![]() | |
Для багатогранних поверхонь підтримуються тільки 2D багатогранні поверхні (не 2.5D). Для 2.5D може бути надано відповідь, відмінну від нуля, але тільки для граней, які повністю лежать у площині XY. |
Площа ділянки в квадратних футах для ділянки землі в штаті Массачусетс і помножте на коефіцієнт перетворення, щоб отримати квадратні метри. Зверніть увагу, що це квадратні фути, оскільки EPSG:2249 — це система координат штату Массачусетс
select ST_Area(geom) sqft,
ST_Area(geom) * 0.3048 ^ 2 sqm
from (
select 'SRID=2249;POLYGON((743238 2967416,743238 2967450,
743265 2967450,743265.625 2967416,743238 2967416))' :: geometry geom
) subquery;
┌─────────┬─────────────┐
│ sqft │ sqm │
├─────────┼─────────────┤
│ 928.625 │ 86.27208552 │
└─────────┴─────────────┘
Введіть площу в квадратних футах і переведіть її в метри площини штату Массачусетс (EPSG:26986), щоб отримати площу в квадратних метрах. Зверніть увагу, що значення вказано в квадратних футах, оскільки 2249 — це фути площини штату Массачусетс, а перетворена площа вказана в квадратних метрах, оскільки EPSG:26986 — це метри площини штату Массачусетс.
select ST_Area(geom) sqft,
ST_Area(ST_Transform(geom, 26986)) As sqm
from (
select
'SRID=2249;POLYGON((743238 2967416,743238 2967450,
743265 2967450,743265.625 2967416,743238 2967416))' :: geometry geom
) subquery;
┌─────────┬─────────────────┐
│ sqft │ sqm │
├─────────┼─────────────────┤
│ 928.625 │ 86.272430607008 │
└─────────┴─────────────────┘
Поверніть площу в квадратних футах і квадратних метрах, використовуючи тип даних "географія". Зверніть увагу, що ми перетворюємо геометрію в географію (перед тим, як це зробити, переконайтеся, що ваша геометрія відповідає стандарту WGS 84 long lat 4326). Географія завжди вимірюється в метрах. Це лише для демонстрації та порівняння. Зазвичай ваша таблиця вже зберігається в типі даних "географія".
select ST_Area(geog) / 0.3048 ^ 2 sqft_spheroid,
ST_Area(geog, false) / 0.3048 ^ 2 sqft_sphere,
ST_Area(geog) sqm_spheroid
from (
select ST_Transform(
'SRID=2249;POLYGON((743238 2967416,743238 2967450,743265 2967450,743265.625 2967416,743238 2967416))'::geometry,
4326
) :: geography geog
) as subquery;
┌──────────────────┬──────────────────┬──────────────────┐
│ sqft_spheroid │ sqft_sphere │ sqm_spheroid │
├──────────────────┼──────────────────┼──────────────────┤
│ 928.684405784452 │ 927.049336105925 │ 86.2776044979692 │
└──────────────────┴──────────────────┴──────────────────┘
Якщо ваші дані вже знаходяться в географії:
select ST_Area(geog) / 0.3048 ^ 2 sqft,
ST_Area(the_geog) sqm
from somegeogtable;ST_3DArea, ST_GeomFromText, ST_GeographyFromText, ST_SetSRID, ST_Transform
ST_Azimuth — Повертає азимут на північ від лінії між двома точками.
float ST_Azimuth(geometry origin, geometry target);
float ST_Azimuth(geography origin, geography target);
Повертає азимут в радіанах від точки відліку до точки призначення або NULL, якщо ці дві точки збігаються. Кут азимута є додатним кутом за годинниковою стрілкою, відлічуваним від додатної осі Y (геометрія) або північного меридіана (географія): Північ = 0; Північний схід = π/4; Схід = π/2; Південний схід = 3π/4; Південь = π; Південний захід 5π/4; Захід = 3π/2; Північний захід = 7π/4.
Для типу географії рішення азимута відоме як обернена геодезична задача.
Азимут — це математичне поняття, яке визначається як кут між опорним вектором і точкою, вимірюється в радіанах. Результат у радіанах можна перетворити в градуси за допомогою функції PostgreSQL degrees().
Азимут можна використовувати разом з ST_Translate для зміщення об'єкта вздовж його перпендикулярної осі. Дивіться функцію upgis_lineshift() у PostGIS wiki для реалізації цього.
Доступність: 1.1.0
Покращено: 2.0.0 додано підтримку географії.
Покращено: вимірювання 2.2.0 на сфероїді, виконане за допомогою GeographicLib для підвищення точності та надійності. Для використання нової функції потрібно PROJ >= 4.9.0.
Геометрія Азимут у градусах
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.2736890060937 | 222.273689006094
![]() Синій: точка відліку (25,45); Зелений: точка призначення (75, 100); Жовтий: вісь Y або північ; Червоний: кут азимута.
| ![]() Синій: точка відліку (75, 100); Зелений: точка призначення (25, 45); Жовтий: вісь Y або північ; Червоний: кут азимута.
|
ST_Angle, ST_Point, ST_Translate, ST_Project, Математичні функції PostgreSQL
ST_Angle — Повертає кут між двома векторами, визначеними 3 або 4 точками, або 2 лініями.
float ST_Angle(geometry point1, geometry point2, geometry point3, geometry point4);
float ST_Angle(geometry line1, geometry line2);
Обчислює кут за годинниковою стрілкою між двома векторами.
Варіант 1: обчислює кут, утворений точками P1-P2-P3. Якщо вказано четверту точку, обчислюється кут між точками P1-P2 і P3-P4
Варіант 2: обчислює кут між двома векторами S1-E1 і S2-E2, визначеними початковою і кінцевою точками вхідних ліній
Результатом є позитивний кут між 0 і 2π радіанами. Результат у радіанах можна перетворити на градуси за допомогою функції PostgreSQL degrees().
Зверніть увагу, що ST_Angle(P1,P2,P3) = ST_Angle(P2,P1,P2,P3).
Доступність: 2.5.0
Кут між трьома точками
SELECT degrees( ST_Angle('POINT(0 0)', 'POINT(10 10)', 'POINT(20 0)') );
degrees
---------
270
Кут між векторами, визначеними чотирма точками
SELECT degrees( ST_Angle('POINT (10 10)', 'POINT (0 0)', 'POINT(90 90)', 'POINT (100 80)') );
degrees
-------------------
269.9999999999999
Кут між векторами, визначеними початковою та кінцевою точками ліній
SELECT degrees( ST_Angle('LINESTRING(0 0, 0.3 0.7, 1 1)', 'LINESTRING(0 0, 0.2 0.5, 1 0)') );
degrees
--------------
45
ST_ClosestPoint — Повертає 2D точку на g1, яка найближча до g2. Це перша точка найкоротшої лінії від однієї геометрії до іншої.
geometry ST_ClosestPoint(geometry geom1, geometry geom2);
geography ST_ClosestPoint(geography geom1, geography geom2, boolean use_spheroid = true);
Повертає двовимірну точку на geom1, яка найближча до geom2. Це перша точка найкоротшої лінії між геометріями (розрахована за допомогою ST_ShortestLine).
![]() | |
Якщо у вас є 3D-геометрія, ви можете скористатися ST_3DClosestPoint. |
Покращено: 3.4.0 - Підтримка географії.
Доступність: 1.5.0

Найближчою точкою для точки та лінійного елемента є сама точка. Найближчою точкою для лінійного елемента та точки є точка на лінії.
SELECT ST_AsText( ST_ClosestPoint(pt,line)) AS cp_pt_line,
ST_AsText( 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)

Найближча точка полігону A до полігону B
SELECT ST_AsText( ST_ClosestPoint(
'POLYGON ((190 150, 20 10, 160 70, 190 150))',
ST_Buffer('POINT(80 160)', 30) )) As ptwkt;
------------------------------------------
POINT(131.59149149528952 101.89887534906197)
ST_3DClosestPoint, ST_Distance, ST_LongestLine, ST_ShortestLine, ST_MaxDistance
ST_3DClosestPoint — Повертає 3D точку на g1, яка найближча до g2. Це перша точка найкоротшої 3D лінії.
geometry ST_3DClosestPoint(geometry g1, geometry g2);
Повертає тривимірну точку на g1, яка найближча до g2. Це перша точка найкоротшої лінії в 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 - якщо введено 2 2D геометрії, повертається 2D точка (замість старого поведінки, що припускає 0 для відсутнього Z). У випадку 2D і 3D, Z більше не вважається 0 для відсутнього Z.
лінія та точка — як 3D, так і 2D найближча точка SELECT ST_AsEWKT(ST_3DClosestPoint(line,pt)) AS cp3d_line_pt,
ST_AsEWKT(ST_ClosestPoint(line,pt)) As cp2d_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;
cp3d_line_pt | cp2d_line_pt
-----------------------------------------------------------+------------------------------------------
POINT(54.6993798867619 128.935022917228 11.5475869506606) | POINT(73.0769230769231 115.384615384615)
|
лінія та багатоточка — як 3D, так і 2D найближча точка SELECT ST_AsEWKT(ST_3DClosestPoint(line,pt)) AS cp3d_line_pt,
ST_AsEWKT(ST_ClosestPoint(line,pt)) As cp2d_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;
cp3d_line_pt | cp2d_line_pt
-----------------------------------------------------------+--------------
POINT(54.6993798867619 128.935022917228 11.5475869506606) | POINT(50 75)
|
Багатолінійні та полігони, як 3D, так і 2D, найближчі точки SELECT ST_AsEWKT(ST_3DClosestPoint(poly, mline)) As cp3d,
ST_AsEWKT(ST_ClosestPoint(poly, mline)) As cp2d
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;
cp3d | cp2d
-------------------------------------------+--------------
POINT(39.993580415989 54.1889925532825 5) | POINT(20 40)
|
ST_AsEWKT, ST_ClosestPoint, ST_3DDistance, ST_3DShortestLine
ST_Distance — Повертає відстань між двома геометричними або географічними значеннями.
float ST_Distance(geometry g1, geometry g2);
float ST_Distance(geography geog1, geography geog2, boolean use_spheroid = true);
Для типів geometry повертає мінімальну 2D декартову (плоску) відстань між двома геометріями в проекційних одиницях (одиницях просторової прив'язки).
Для типів geography за замовчуванням повертається мінімальна геодезична відстань між двома географічними об'єктами в метрах, обчислена на сфероїді, визначеному SRID. Якщо use_spheroid має значення false, використовується швидший сферичний розрахунок.
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 Підтримка географії була впроваджена в версії 1.5. Покращення швидкості для плоских об'єктів для кращої обробки великих або численних вершин геометрії
Покращено: 2.1.0 покращено швидкість роботи з географією. Детальніше див. Пришвидшення роботи з географією.
Покращено: 2.1.0 — додано підтримку кривих геометрій.
Покращено: 2.2.0 — вимірювання на сфероїді виконується за допомогою GeographicLib для підвищення точності та надійності. Для використання нової функції потрібно PROJ >= 4.9.0.
Змінено: 3.0.0 - більше не залежить від SFCGAL.
Приклад геометрії - одиниці виміру в плоских градусах 4326 - це довжина в градусах за системою WGS 84, одиниці виміру - градуси.
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Приклад геометрії — одиниці виміру в метрах (SRID: 3857, пропорційно до пікселів на популярних веб-мапах). Хоча значення не відповідає дійсності, сусідні значення можна порівняти правильно, що робить цей вибір хорошим для таких алгоритмів, як KNN або KMeans.
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Приклад геометрії — одиниці виміру в метрах (SRID: 3857, як вище, але скориговано за допомогою cos(lat) для врахування спотворення)
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Приклад геометрії — одиниці виміру в метрах (SRID: 26986 метри площини штату Массачусетс) (найточніше для штату Массачусетс)
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Приклад геометрії — одиниці виміру в метрах (SRID: 2163 US National Atlas Equal area) (найменша точність)
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Те саме, що й у прикладі з геометрією, але зверніть увагу на одиниці виміру в метрах — для трохи швидшого та менш точного обчислення використовуйте сферу.
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.475736916397ST_3DDistance — Повертає мінімальну 3D декартову відстань (на основі просторової референції) між двома геометріями в проекційних одиницях.
float ST_3DDistance(geometry g1, geometry g2);
Повертає 3-вимірну мінімальну декартову відстань між двома геометріями в проекційних одиницях (одиницях просторової прив'язки).
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 більше не вважається рівним 0 для відсутнього Z.
Змінено: 3.0.0 - Вилучено версію SFCGAL
-- Geometry example - units in meters (SRID: 2163 US National Atlas Equal area) (3D point and line compared 2D point and line)
-- Note: currently no vertical datum support so Z is not transformed and assumed to be same units as final.
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
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.716635696066337 | 0
ST_DistanceSphere — Повертає мінімальну відстань у метрах між двома геометріями довготи/широти, використовуючи модель сферичної Землі.
float ST_DistanceSphere(geometry geomlonlatA, geometry geomlonlatB, float8 radius=6371008);
Повертає мінімальну відстань у метрах між двома точками lon/lat. Використовує сферичну Землю та радіус, отриманий із сфероїда, визначеного SRID. Швидше, ніж ST_DistanceSpheroid, але менш точне. У версіях PostGIS до 1.5 реалізовано тільки для точок.
Доступність: 1.5 — додано підтримку інших типів геометрії, крім точок. Попередні версії працюють тільки з точками.
Змінено: 2.2.0 У попередніх версіях це називалося ST_Distance_Sphere
SELECT round(CAST(ST_DistanceSphere(ST_Centroid(geom), ST_GeomFromText('POINT(-118 38)',4326)) As numeric),2) As dist_meters,
round(CAST(ST_Distance(ST_Transform(ST_Centroid(geom),32611),
ST_Transform(ST_GeomFromText('POINT(-118 38)', 4326),32611)) As numeric),2) As dist_utm11_meters,
round(CAST(ST_Distance(ST_Centroid(geom), ST_GeomFromText('POINT(-118 38)', 4326)) As numeric),5) As dist_degrees,
round(CAST(ST_Distance(ST_Transform(geom,32611),
ST_Transform(ST_GeomFromText('POINT(-118 38)', 4326),32611)) As numeric),2) As min_dist_line_point_meters
FROM
(SELECT ST_GeomFromText('LINESTRING(-118.584 38.374,-118.583 38.5)', 4326) As geom) as foo;
dist_meters | dist_utm11_meters | dist_degrees | min_dist_line_point_meters
-------------+-------------------+--------------+----------------------------
70424.47 | 70438.00 | 0.72900 | 65871.18
ST_DistanceSpheroid — Повертає мінімальну відстань між двома геометріями lon/lat, використовуючи сфероїдальну модель Землі.
float ST_DistanceSpheroid(geometry geomlonlatA, geometry geomlonlatB, spheroid measurement_spheroid=WGS84);
Повертає мінімальну відстань у метрах між двома геометріями lon/lat, заданими для певного сфероїда. Див. пояснення сфероїдів, наведене для ST_LengthSpheroid.
![]() | |
Ця функція не враховує SRID геометрії. Вона припускає, що координати геометрії базуються на наданому сфероїді. |
Доступність: 1.5 — додано підтримку інших типів геометрії, крім точок. Попередні версії працюють тільки з точками.
Змінено: 2.2.0 У попередніх версіях це називалося ST_Distance_Spheroid
SELECT round(CAST(
ST_DistanceSpheroid(ST_Centroid(geom), ST_GeomFromText('POINT(-118 38)',4326), 'SPHEROID["WGS 84",6378137,298.257223563]')
As numeric),2) As dist_meters_spheroid,
round(CAST(ST_DistanceSphere(ST_Centroid(geom), ST_GeomFromText('POINT(-118 38)',4326)) As numeric),2) As dist_meters_sphere,
round(CAST(ST_Distance(ST_Transform(ST_Centroid(geom),32611),
ST_Transform(ST_GeomFromText('POINT(-118 38)', 4326),32611)) As numeric),2) As dist_utm11_meters
FROM
(SELECT ST_GeomFromText('LINESTRING(-118.584 38.374,-118.583 38.5)', 4326) As geom) as foo;
dist_meters_spheroid | dist_meters_sphere | dist_utm11_meters
----------------------+--------------------+-------------------
70454.92 | 70424.47 | 70438.00
ST_FrechetDistance — Повертає відстань Фреше між двома геометріями.
float ST_FrechetDistance(geometry g1, geometry g2, float densifyFrac = -1);
Реалізує алгоритм обчислення відстані Фреше, обмеженої дискретними точками для обох геометрій, на основі Computing Discrete Fréchet Distance. Відстань Фреше — це міра подібності кривих, що враховує розташування та порядок точок уздовж кривих. Тому вона часто є кращою за відстань Гаусдорфа.
Коли вказано опціональний параметр densifyFrac, ця функція виконує ущільнення сегментів перед обчисленням дискретної відстані Фреше. Параметр densifyFrac встановлює частку, на яку ущільнюється кожен сегмент. Кожен сегмент буде розділений на декілька підсегментів однакової довжини, частка яких у загальній довжині найближча до заданої частки.
Одиниці вимірювання відповідають одиницям просторової системи координат геометрії.
![]() | |
Поточна реалізація підтримує тільки вершини як дискретні місця розташування. Це можна розширити, щоб дозволити використання довільної щільності точок. |
![]() | |
Чим менше значення densifyFrac ми вказуємо, тим точніше буде відстань Фреше. Однак час обчислення та використання пам'яті зростають пропорційно до квадрату кількості підсегментів. |
Виконується модулем GEOS.
Availability: 2.4.0 - requires GEOS >= 3.7.0
postgres=# SELECT st_frechetdistance('LINESTRING (0 0, 100 0)'::geometry, 'LINESTRING (0 0, 50 50, 100 0)'::geometry);
st_frechetdistance
--------------------
70.7106781186548
(1 row)
SELECT st_frechetdistance('LINESTRING (0 0, 100 0)'::geometry, 'LINESTRING (0 0, 50 50, 100 0)'::geometry, 0.5);
st_frechetdistance
--------------------
50
(1 row)
ST_HausdorffDistance — Повертає відстань Гаусдорфа між двома геометріями.
float ST_HausdorffDistance(geometry g1, geometry g2);
float ST_HausdorffDistance(geometry g1, geometry g2, float densifyFrac);
Повертає відстань Гаусдорфа між двома геометріями. Відстань Гаусдорфа — це міра схожості або відмінності двох геометрій.
Функція фактично обчислює "дискретну відстань Гаусдорфа". Це відстань Гаусдорфа, обчислена в дискретних точках геометрії. Параметр densifyFrac можна вказати, щоб отримати більш точний результат шляхом ущільнення сегментів перед обчисленням дискретної відстані Гаусдорфа. Кожен сегмент розділяється на кілька підсегментів однакової довжини, частка яких у довжині сегмента найближча до заданої частки.
Одиниці вимірювання відповідають одиницям просторової системи координат геометрії.
![]() | |
Цей алгоритм НЕ є еквівалентним стандартній відстані Гаусдорфа. Однак він обчислює наближення, яке є правильним для великої підмножини корисних випадків. Одним з важливих випадків є лінійні рядки, які приблизно паралельні один одному і мають приблизно однакову довжину. Це корисний показник для зіставлення ліній. |
Доступність: 1.5.0

Відстань Гаусдорфа (червоний) і відстань (жовтий) між двома лініями
SELECT ST_HausdorffDistance(geomA, geomB),
ST_Distance(geomA, geomB)
FROM (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) AS t;
st_hausdorffdistance | st_distance
----------------------+-------------
37.26206567625497 | 20
Приклад: Відстань Гаусдорфа з ущільненням.
SELECT ST_HausdorffDistance(
'LINESTRING (130 0, 0 0, 0 150)'::geometry,
'LINESTRING (10 10, 10 150, 130 10)'::geometry,
0.5);
----------------------
70
Приклад: Для кожної будівлі знайдіть ділянку, яка найкраще її представляє. Спочатку ми вимагаємо, щоб ділянка перетиналася з геометрією будівлі. DISTINCT ON гарантує, що кожна будівля буде вказана тільки один раз. ORDER BY .. ST_HausdorffDistance вибирає ділянку, яка найбільш схожа на будівлю.
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 — Повертає 2D довжину лінійної геометрії.
float ST_Length(geometry a_2dlinestring);
float ST_Length(geography geog, boolean use_spheroid = true);
Для типів геометрії: повертає двовимірну декартову довжину геометрії, якщо це LineString, MultiLineString, ST_Curve, ST_MultiCurve. Для плоских геометрій повертається 0; замість цього використовуйте ST_Perimeter. Одиниці довжини визначаються просторовою системою відліку геометрії.
Для географічних типів: обчислення виконується за допомогою оберненого геодезичного розрахунку. Одиниці довжини вказані в метрах. Якщо PostGIS скомпільовано з PROJ версії 4.8.0 або пізнішої, сфероїд визначається за SRID, інакше він є ексклюзивним для WGS84. Якщо use_spheroid = false, обчислення базується на сфері, а не на сфероїді.
Наразі для геометрії це псевдонім для ST_Length2D, але це може змінитися для підтримки вищих вимірів.
![]() | |
Змінено: 2.0.0 Істотна зміна — у попередніх версіях застосування цього до MULTI/POLYGON типу geography давало периметр POLYGON/MULTIPOLYGON. У 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 була введена в версії 1.5.
Довжина повернення в футах для рядка рядка. Зверніть увагу, що це в футах, оскільки EPSG:2249 - це фути штату Массачусетс
SELECT ST_Length(ST_GeomFromText('LINESTRING(743238 2967416,743238 2967450,743265 2967450,
743265.625 2967416,743238 2967416)',2249));
st_length
---------
122.630744000095
--Transforming WGS 84 LineString to Massachusetts state plane meters
SELECT ST_Length(
ST_Transform(
ST_GeomFromEWKT('SRID=4326;LINESTRING(-72.1260 42.45, -72.1240 42.45666, -72.123 42.1546)'),
26986
)
);
st_length
---------
34309.4563576191
Повернути довжину географічної лінії WGS 84
-- the default calculation uses a spheroid
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.5703627288 | 34346.2060960742
ST_Length2D — Повертає 2D довжину лінійної геометрії. Псевдонім для ST_Length
float ST_Length2D(geometry a_2dlinestring);
Повертає 2D довжину геометрії, якщо це лінія або багатолінійна лінія. Це псевдонім для ST_Length
ST_3DLength — Повертає 3D довжину лінійної геометрії.
float ST_3DLength(geometry a_3dlinestring);
Повертає тривимірну або двовимірну довжину геометрії, якщо це LineString або MultiLineString. Для двовимірних ліній повертається лише двовимірна довжина (так само, як 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
Довжина повернення в футах для 3D-кабелю. Зверніть увагу, що це в футах, оскільки EPSG:2249 — це фути штату Массачусетс
SELECT ST_3DLength(ST_GeomFromText('LINESTRING(743238 2967416 1,743238 2967450 1,743265 2967450 3,
743265.625 2967416 3,743238 2967416 3)',2249));
ST_3DLength
-----------
122.704716741457
ST_LengthSpheroid — Повертає 2D або 3D довжину/периметр геометрії lon/lat на сфероїді.
float ST_LengthSpheroid(geometry a_geometry, spheroid a_spheroid);
Обчислює довжину або периметр геометрії на еліпсоїді. Це корисно, якщо координати геометрії задані в градусах довготи/широти, а довжина потрібна без перепроекції. Сфероїд задається текстовим значенням у такому форматі:
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.
SELECT ST_LengthSpheroid( geometry_column,
'SPHEROID["GRS_1980",6378137,298.257222101]' )
FROM geometry_table;
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 (SELECT ST_GeomFromText('MULTILINESTRING((-118.584 38.374,-118.583 38.5),
(-71.05957 42.3589 , -71.061 43))') As geom,
CAST('SPHEROID["GRS_1980",6378137,298.257222101]' As spheroid) As sph_m) as foo;
tot_len | len_line1 | len_line2
------------------+------------------+------------------
85204.5207562955 | 13986.8725229309 | 71217.6482333646
--3D
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 (SELECT ST_GeomFromEWKT('MULTILINESTRING((-118.584 38.374 20,-118.583 38.5 30),
(-71.05957 42.3589 75, -71.061 43 90))') As geom,
CAST('SPHEROID["GRS_1980",6378137,298.257222101]' As spheroid) As sph_m) as foo;
tot_len | len_line1 | len_line2
------------------+-----------------+------------------
85204.5259107402 | 13986.876097711 | 71217.6498130292
ST_LongestLine — Повертає найдовшу 2D лінію між двома геометріями.
geometry ST_LongestLine(geometry g1, geometry g2);
Повертає найдовшу двовимірну лінію між точками двох геометрій. Повернена лінія починається в точці g1 і закінчується в точці g2.
Найдовша лінія завжди проходить між двома вершинами. Якщо знайдено більше однієї лінії, функція повертає першу найдовшу лінію. Довжина лінії дорівнює відстані, поверненій функцією ST_MaxDistance.
Якщо g1 і g2 мають однакову геометрію, повертає лінію між двома найвіддаленішими вершинами в геометрії. Кінцеві точки лінії лежать на колі, обчисленому за допомогою ST_MinimumBoundingCircle.
Доступність: 1.5.0

Найдовша лінія між точкою і прямою
SELECT ST_AsText( 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)

Найдовша лінія між двома полігонами
SELECT ST_AsText( ST_LongestLine(
'POLYGON ((190 150, 20 10, 160 70, 190 150))',
ST_Buffer('POINT(80 160)', 30)
) ) AS llinewkt;
-----------------
LINESTRING(20 10,105.3073372946034 186.95518130045156)

Найдовша лінія, що проходить через одну геометрію. Довжина лінії дорівнює максимальній відстані. Кінцеві точки лінії лежать на мінімальному обмежувальному колі.
SELECT ST_AsText( ST_LongestLine( geom, geom)) AS llinewkt,
ST_MaxDistance( geom, geom) AS max_dist,
ST_Length( ST_LongestLine(geom, 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
ST_3DLongestLine — Повертає найдовшу 3D лінію між двома геометріями
geometry ST_3DLongestLine(geometry g1, geometry g2);
Повертає найдовшу тривимірну лінію між двома геометріями. Якщо таких ліній більше однієї, функція повертає першу найдовшу лінію. Повернена лінія починається в g1 і закінчується в g2. Тривимірна довжина лінії дорівнює відстані, поверненій функцією ST_3DMaxDistance.
Доступність: 2.0.0
Змінено: 2.2.0 - якщо введено 2 2D геометрії, повертається 2D точка (замість старого поведінки, що припускає 0 для відсутнього Z). У випадку 2D і 3D, Z більше не вважається 0 для відсутнього Z.
This function supports 3d and will not drop the z-index.
This function supports Polyhedral surfaces.
лінія та точка — найдовша лінія у 3D та 2D SELECT ST_AsEWKT(ST_3DLongestLine(line,pt)) AS lol3d_line_pt,
ST_AsEWKT(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)
|
лінія та мультиточка — найдовша лінія в 3D та 2D SELECT ST_AsEWKT(ST_3DLongestLine(line,pt)) AS lol3d_line_pt,
ST_AsEWKT(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)
|
MultiLineString і Polygon, як 3D, так і 2D найдовша лінія SELECT ST_AsEWKT(ST_3DLongestLine(poly, mline)) As lol3d,
ST_AsEWKT(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)
|
ST_MaxDistance — Повертає найбільшу відстань між двома геометріями в проекційних одиницях.
float ST_MaxDistance(geometry g1, geometry g2);
Повертає максимальну відстань між двома геометріями у двовимірному просторі, в проекційних одиницях. Максимальна відстань завжди виникає між двома вершинами. Це довжина лінії, повернена функцією ST_LongestLine.
Якщо g1 і g2 мають однакову геометрію, повертає відстань між двома найвіддаленішими вершинами в цій геометрії.
Доступність: 1.5.0
Максимальна відстань між точкою та лініями.
SELECT ST_MaxDistance('POINT(0 0)'::geometry, 'LINESTRING ( 2 0, 0 2 )'::geometry);
-----------------
2
SELECT ST_MaxDistance('POINT(0 0)'::geometry, 'LINESTRING ( 2 2, 2 2 )'::geometry);
------------------
2.82842712474619
Максимальна відстань між вершинами однієї геометрії.
SELECT ST_MaxDistance('POLYGON ((10 10, 10 0, 0 0, 10 10))'::geometry,
'POLYGON ((10 10, 10 0, 0 0, 10 10))'::geometry);
------------------
14.142135623730951
ST_3DMaxDistance — Повертає максимальну 3D-відстань (на основі просторової референції) між двома геометріями в проекційних одиницях.
float ST_3DMaxDistance(geometry g1, geometry g2);
Повертає тривимірну максимальну декартову відстань між двома геометріями в проекційних одиницях (одиницях просторової прив'язки).
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 більше не вважається рівним 0 для відсутнього Z.
-- Geometry example - units in meters (SRID: 2163 US National Atlas Equal area) (3D point and line compared 2D point and line)
-- Note: currently no vertical datum support so Z is not transformed and assumed to be same units as final.
SELECT ST_3DMaxDistance(
ST_Transform(ST_GeomFromEWKT('SRID=4326;POINT(-72.1235 42.3521 10000)'),2163),
ST_Transform(ST_GeomFromEWKT('SRID=4326;LINESTRING(-72.1260 42.45 15, -72.123 42.1546 20)'),2163)
) As dist_3d,
ST_MaxDistance(
ST_Transform(ST_GeomFromEWKT('SRID=4326;POINT(-72.1235 42.3521 10000)'),2163),
ST_Transform(ST_GeomFromEWKT('SRID=4326;LINESTRING(-72.1260 42.45 15, -72.123 42.1546 20)'),2163)
) As dist_2d;
dist_3d | dist_2d
------------------+------------------
24383.7467488441 | 22247.8472107251
ST_MinimumClearance — Повертає мінімальний зазор геометрії, міру міцності геометрії.
float ST_MinimumClearance(geometry g);
Геометрія може відповідати критеріям валідності згідно з ST_IsValid(полігони) або ST_IsSimple(лінії), але стати невалідною, якщо одна з її вершин буде переміщена на невелику відстань. Це може статися через втрату точності під час перетворення в текстові формати (такі як WKT, KML, GML, GeoJSON) або бінарні формати, які не використовують координати з подвійною точністю з плаваючою комою (наприклад, MapInfo TAB).
Мінімальний зазор — це кількісна міра стійкості геометрії до зміни точності координат. Це найбільша відстань, на яку можна перемістити вершини геометрії, не порушуючи її цілісності. Більші значення мінімального зазору вказують на більшу стійкість.
Якщо геометрія має мінімальний зазор e, то:
У геометрії немає двох різних вершин, відстань між якими менша за e.
Жодна вершина не знаходиться ближче, ніж e до відрізка лінії, кінцевою точкою якого вона не є.
Якщо для геометрії не існує мінімального зазору (наприклад, для окремої точки або для MultiPoint, точки якого є ідентичними), повертається значення Infinity.
Щоб уникнути проблем з валідністю, спричинених втратою точності, ST_ReducePrecisionможе зменшити точність координат, гарантуючи при цьому валідність полігональної геометрії.
Доступність: 2.3.0
SELECT ST_MinimumClearance('POLYGON ((0 0, 1 0, 1 1, 0.5 3.2e-4, 0 0))');
st_minimumclearance
---------------------
0.00032
ST_MinimumClearanceLine, ST_IsSimple, ST_IsValid, ST_ReducePrecision
ST_MinimumClearanceLine — Повертає двоточкову лінію LineString, що охоплює мінімальний простір геометрії.
Geometry ST_MinimumClearanceLine(geometry g);
Повертає двоточкову лінію LineString, що охоплює мінімальний зазор геометрії. Якщо геометрія не має мінімального зазору, повертається LINESTRING EMPTY.
Виконується модулем GEOS.
Доступність: 2.3.0 - вимагає GEOS >= 3.6.0
SELECT ST_AsText(ST_MinimumClearanceLine('POLYGON ((0 0, 1 0, 1 1, 0.5 3.2e-4, 0 0))'));
-------------------------------
LINESTRING(0.5 0.00032,0.5 0)
ST_Perimeter — Повертає довжину межі полігональної геометрії або географії.
float ST_Perimeter(geometry g1);
float ST_Perimeter(geography geog, boolean use_spheroid = true);
Повертає 2D периметр геометрії/географії, якщо це ST_Surface, ST_MultiSurface (Polygon, MultiPolygon). Для геометрій, що не мають площі, повертається 0. Для лінійних геометрій використовуйте ST_Length. Для типів геометрії одиниці виміру периметра визначаються просторовою системою відліку геометрії.
Для географічних типів обчислення виконуються за допомогою оберненої геодезичної задачі, де одиниці периметра вимірюються в метрах. Якщо PostGIS скомпільовано з PROJ версії 4.8.0 або пізнішої, сфероїд визначається SRID, інакше він є ексклюзивним для WGS84. Якщо use_spheroid = false, обчислення будуть наближатися до сфери, а не до сфероїда.
Наразі це псевдонім для 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: додано підтримку географії
Повернути периметр у футах для полігону та мультиполігону. Зверніть увагу, що це фути, оскільки EPSG:2249 — це фути штату Массачусетс.
SELECT ST_Perimeter(ST_GeomFromText('POLYGON((743238 2967416,743238 2967450,743265 2967450,
743265.625 2967416,743238 2967416))', 2249));
st_perimeter
---------
122.630744000095
(1 row)
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));
st_perimeter
---------
845.227713366825
(1 row)
Повернути периметр у метрах і футах для полігону та мультиполігону. Зверніть увагу, що це географічні координати (WGS 84 long lat)
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.3790462565251 | 122.634666195949
-- MultiPolygon example --
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
ST_Perimeter2D — Повертає 2D периметр полігональної геометрії. Псевдонім для ST_Perimeter.
float ST_Perimeter2D(geometry geomA);
Повертає двовимірний периметр багатокутної геометрії.
![]() | |
Наразі це псевдонім для ST_Perimeter. У майбутніх версіях ST_Perimeter може повертати найбільший периметр для геометрії. Це питання ще розглядається |
ST_3DPerimeter — Повертає 3D периметр полігональної геометрії.
float ST_3DPerimeter(geometry geomA);
Повертає тривимірний периметр геометрії, якщо це полігон або мультиполігон. Якщо геометрія двовимірна, то повертається двовимірний периметр.
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
Периметр злегка піднятого полігону в повітрі в штаті Массачусетс, фути площини штату
SELECT ST_3DPerimeter(geom), ST_Perimeter2d(geom), ST_Perimeter(geom) FROM
(SELECT ST_GeomFromEWKT('SRID=2249;POLYGON((743238 2967416 2,743238 2967450 1,
743265.625 2967416 1,743238 2967416 2))') As geom) As foo;
ST_3DPerimeter | st_perimeter2d | st_perimeter
------------------+------------------+------------------
105.465793597674 | 105.432997272188 | 105.432997272188
ST_ShortestLine — Повертає найкоротшу 2D лінію між двома геометріями
geometry ST_ShortestLine(geometry geom1, geometry geom2);
geography ST_ShortestLine(geography geom1, geography geom2, boolean use_spheroid = true);
Повертає найкоротшу двовимірну лінію між двома геометріями. Повернена лінія починається в geom1 і закінчується в geom2. Якщо geom1 і geom2 перетинаються, результатом є лінія, що починається і закінчується в точці перетину. Довжина лінії дорівнює значенню, яке повертає ST_Distance для g1 і g2.
Покращено: 3.4.0 - підтримка географії.
Доступність: 1.5.0

Найкоротша лінія між точкою та лінією
SELECT ST_AsText( 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)

Найкоротша лінія між полігонами
SELECT ST_AsText( ST_ShortestLine(
'POLYGON ((190 150, 20 10, 160 70, 190 150))',
ST_Buffer('POINT(80 160)', 30)
) ) AS llinewkt;
-----------------
LINESTRING(131.59149149528952 101.89887534906197,101.21320343559644 138.78679656440357)
ST_ClosestPoint, ST_Distance, ST_LongestLine, ST_MaxDistance
ST_3DShortestLine — Повертає найкоротшу 3D лінію між двома геометріями
geometry ST_3DShortestLine(geometry g1, geometry g2);
Повертає найкоротшу тривимірну лінію між двома геометріями. Якщо функція знаходить більше однієї найкоротшої лінії, вона повертає тільки першу. Якщо g1 і g2 перетинаються тільки в одній точці, функція повертає лінію, початок і кінець якої знаходяться в цій точці перетину. Якщо g1 і g2 перетинаються в більш ніж одній точці, функція поверне лінію, початок і кінець якої знаходяться в одній точці, але це може бути будь-яка з точок перетину. Повернена лінія завжди починатиметься в g1 і закінчуватиметься в g2. Тривимірна довжина лінії, яку повертає ця функція, завжди буде такою ж, як ST_3DDistanceповертає для g1 і g2.
Доступність: 2.0.0
Змінено: 2.2.0 - якщо введено 2 2D геометрії, повертається 2D точка (замість старого поведінки, що припускає 0 для відсутнього Z). У випадку 2D і 3D, Z більше не вважається 0 для відсутнього Z.
This function supports 3d and will not drop the z-index.
This function supports Polyhedral surfaces.
лінія та точка — найкоротша лінія в 3D та 2D SELECT ST_AsEWKT(ST_3DShortestLine(line,pt)) AS shl3d_line_pt,
ST_AsEWKT(ST_ShortestLine(line,pt)) As shl2d_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;
shl3d_line_pt | shl2d_line_pt
----------------------------------------------------------------------------+------------------------------------------------------
LINESTRING(54.6993798867619 128.935022917228 11.5475869506606,100 100 30) | LINESTRING(73.0769230769231 115.384615384615,100 100)
|
лінія та мультиточка — найкоротша лінія в 3D та 2D SELECT ST_AsEWKT(ST_3DShortestLine(line,pt)) AS shl3d_line_pt,
ST_AsEWKT(ST_ShortestLine(line,pt)) As shl2d_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;
shl3d_line_pt | shl2d_line_pt
---------------------------------------------------------------------------+------------------------
LINESTRING(54.6993798867619 128.935022917228 11.5475869506606,100 100 30) | LINESTRING(50 75,50 74)
|
MultiLineString і полігон, як 3D, так і 2D найкоротша лінія SELECT ST_AsEWKT(ST_3DShortestLine(poly, mline)) As shl3d,
ST_AsEWKT(ST_ShortestLine(poly, mline)) As shl2d
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;
shl3d | shl2d
---------------------------------------------------------------------------------------------------+------------------------
LINESTRING(39.993580415989 54.1889925532825 5,40.4078575708294 53.6052383805529 5.03423778139177) | LINESTRING(20 40,20 40)
|
Ці функції обчислюють результати, що виникають при накладенні двох геометрій. Вони також відомі як булеві операції теорії множин точок. Також надаються деякі пов'язані функції.
ST_ClipByBox2D — Обчислює частину геометрії, що потрапляє в прямокутник.
geometry ST_ClipByBox2D(geometry geom, box2d box);
Обрізає геометрію за допомогою 2D-коробки швидким і толерантним, але, можливо, некоректним способом. Топологічно некоректні вхідні геометрії не призводять до виникнення виняткових ситуацій. Не гарантується коректність вихідної геометрії (зокрема, можуть виникнути самоперетини для полігону).
Виконується модулем GEOS.
Доступність: 2.2.0
-- Rely on implicit cast from geometry to box2d for the second parameter
SELECT ST_ClipByBox2D(geom, ST_MakeEnvelope(0,0,10,10)) FROM mytab;
ST_Difference — Обчислює геометрію, що представляє частину геометрії A, яка не перетинається з геометрією B.
geometry ST_Difference(geometry geomA, geometry geomB, float8 gridSize = -1);
Повертає геометрію, що представляє частину геометрії A, яка не перетинається з геометрією B. Це еквівалентно A - ST_Intersection(A,B). Якщо A повністю міститься в B, то повертається порожня атомарна геометрія відповідного типу.
![]() | |
Це єдина функція накладання, де порядок введення має значення. ST_Difference(A, 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 grid of the specified size. For the operation to give predictable results all the input vertices must fall already on the specified grid, see ST_ReducePrecision.
Виконано модулем GEOS
Покращено: 3.1.0 приймає параметр gridSize.
Для використання параметра gridSize необхідна версія GEOS >= 3.9.0.
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. Однак результат обчислюється тільки за допомогою XY. Значення результату Z копіюються, усереднюються або інтерполюються.
|
![]() Вхідні ліній
|
![]() Різниця між двома рядками
|
Різниця між 2D лініями.
SELECT ST_AsText(
ST_Difference(
'LINESTRING(50 100, 50 200)'::geometry,
'LINESTRING(50 50, 50 150)'::geometry
)
);
st_astext
---------
LINESTRING(50 150,50 200)
Різниця між 3D-точками.
SELECT ST_AsEWKT( 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
) );
st_asewkt
---------
MULTIPOINT(-118.6 38.329 6,-118.58 38.38 5)
ST_SymDifference, ST_Intersection, ST_Union, ST_ReducePrecision
ST_Intersection — Обчислює геометрію, що представляє спільну частину геометрій A і B.
geometry ST_Intersection( geometry geomA , geometry geomB , float8 gridSize = -1 );
geography ST_Intersection( geography geogA , geography geogB );
Повертає геометрію, що представляє перетин двох геометрій. Іншими словами, це та частина геометрії A і геометрії B, яка є спільною для обох геометрій.
Якщо геометрії не мають спільних точок (тобто є роз'єднаними), то повертається порожня атомарна геометрія відповідного типу.
If the optional gridSize parameter is given (GEOS-3.9.0 or higher required), all result vertices are guaranteed to fall on a grid of the specified size. For the operation to give predictable results all the input vertices must fall already on the specified grid, see ST_ReducePrecision.
ST_Intersection у поєднанні з ST_Intersects корисний для обрізання геометрій, наприклад, у запитах на обмежувальну рамку, буфер або регіон, де потрібна лише частина геометрії, що знаходиться всередині країни або регіону, що цікавить.
![]() | |
|
![]() | |
Ця функція видалить значення координати M, якщо вони присутні. |
![]() | |
ST_3DIntersection яка виконує правильне 3D перетин для 3D геометрій. Хоча ця функція працює з Z-координатами, вона виконує усереднення Z-координат. |
Виконано модулем GEOS
Покращено: 3.1.0 приймає параметр gridSize
Для використання параметра gridSize необхідна версія GEOS >= 3.9.0
Змінено: 3.0.0 не залежить від SFCGAL.
Доступність: 1.5 додано підтримку типу даних географії.
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. Однак результат обчислюється тільки за допомогою XY. Значення результату Z копіюються, усереднюються або інтерполюються.
SELECT ST_AsText(ST_Intersection('POINT(0 0)'::geometry, 'LINESTRING ( 2 0, 0 2 )'::geometry));
st_astext
---------------
GEOMETRYCOLLECTION EMPTY
SELECT ST_AsText(ST_Intersection('POINT(0 0)'::geometry, 'LINESTRING ( 0 0, 0 2 )'::geometry));
st_astext
---------------
POINT(0 0)Виріжте всі лінії (треки) за країною. Тут ми припускаємо, що геометрія країни є POLYGON або MULTIPOLYGONS. ПРИМІТКА: ми зберігаємо тільки перетини, які утворюють LINESTRING або MULTILINESTRING, оскільки нас не цікавлять траси, які просто мають спільну точку. Дамп необхідний для розширення колекції геометрії в окремі частини MULT*. Нижче наведено досить загальний приклад, який підійде для полігонів тощо, якщо змінити умову where.
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;Для полігонів, наприклад, орієнтирів полігону, ви також можете використовувати іноді швидший хак, який буферизує все, крім полігону, на 0,0, що призводить до порожньої колекції геометрії. (Таким чином, колекція геометрії, що містить полігони, лінії та точки, буферизовані на 0,0, залишить тільки полігони і розчиниться оболонку колекції.)
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));Приклади: 2.5D
select ST_AsText(ST_Intersection(linestring, polygon)) As wkt
from ST_GeomFromText('LINESTRING Z (2 2 6,1.5 1.5 7,1 1 8,0.5 0.5 8,0 0 10)') AS linestring
CROSS JOIN ST_GeomFromText('POLYGON((0 0 8, 0 1 8, 1 1 8, 1 0 8, 0 0 8))') AS polygon;
st_astext
---------------------------------------
LINESTRING Z (1 1 8,0.5 0.5 8,0 0 10)
ST_MemUnion — Агрегатна функція, яка об'єднує геометрії в пам'яті ефективним, але повільнішим способом.
geometry ST_MemUnion(geometry set geomfield);
Агрегатна функція, яка об'єднує вхідні геометрії, зливаючи їх для отримання геометрії результату без перекриттів. Результатом може бути одна геометрія, MultiGeometry або Geometry Collection.
![]() | |
Дає той самий результат, що й ST_Union, але використовує менше пам'яті та більше процесорного часу. Ця агрегатна функція працює шляхом послідовного об'єднання геометрій, на відміну від агрегату ST_Union, який спочатку накопичує масив, а потім об'єднує вміст за допомогою швидкого алгоритму. |
This function supports 3d and will not drop the z-index. Однак результат обчислюється тільки за допомогою XY. Значення результату Z копіюються, усереднюються або інтерполюються.
SELECT id,
ST_MemUnion(geom) as singlegeom
FROM sometable f
GROUP BY id;
ST_Node — Вузли — сукупність ліній.
geometry ST_Node(geometry geom);
Повертає (Multi)LineString, що представляє повністю вузлову версію колекції лінійних рядків. Вузли зберігають усі вхідні вузли та вводять мінімально можливу кількість нових вузлів. Результуюча лінія розчиняється (дублі ліній видаляються).
Це хороший спосіб створити повністю вузлові лінії, які можна використовувати як вхідні дані для ST_Polygonize.
ST_UnaryUnion також може використовуватися для з'єднання та роз'єднання ліній. Він надає можливість вказати розмір сітки gridSize, що дозволяє отримати простіший та надійніший результат. Див. також ST_Unionдля агрегованого варіанту.
This function supports 3d and will not drop the z-index.
Виконується модулем GEOS.
Доступність: 2.0.0
Змінено: 2.4.0 ця функція використовує GEOSNode внутрішньо замість GEOSUnaryUnion. Це може призвести до того, що отримані лінійні рядки матимуть інший порядок і напрямок порівняно з PostGIS < 2.4.
Вузли 3D-лінії, що перетинається сама з собою
SELECT ST_AsText(
ST_Node('LINESTRINGZ(0 0 0, 10 10 10, 0 10 5, 10 0 3)'::geometry)
) As output;
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))
З'єднання двох лінійних об'єктів, які мають спільні лінії. Зверніть увагу, що лінія результату розчиняється.
SELECT ST_AsText(
ST_Node('MULTILINESTRING ((2 5, 2 1, 7 1), (6 1, 4 1, 2 3, 2 5))'::geometry)
) As output;
output
-----------
MULTILINESTRING((2 5,2 3),(2 3,2 1,4 1),(4 1,2 3),(4 1,6 1),(6 1,7 1))
ST_Split — Повертає колекцію геометрій, створених шляхом розділення однієї геометрії іншою геометрією.
geometry ST_Split(geometry input, geometry blade);
Функція підтримує розділення LineString за межею (Multi)Point, (Multi)LineString або (Multi)Polygon, або (Multi)Polygon за LineString. Коли (Multi)Polygon використовується як лезо, його лінійні компоненти (межа) використовуються для розділення вхідних даних. Результуюча геометрія завжди є колекцією.
Ця функція в певному сенсі є протилежною до ST_Union. Застосування ST_Union до повернутої колекції теоретично повинно дати вихідну геометрію (хоча через числове округлення це може бути не зовсім так).
![]() | |
Якщо вхідні дані та лезо не перетинаються через проблеми з числовою точністю, вхідні дані можуть не розділитися як очікується. Щоб уникнути такої ситуації, може бути необхідним спочатку прив'язати вхідні дані до леза за допомогою ST_Snap з невеликим допуском. |
Доступність: 2.0.0 вимагає GEOS
Покращено: 2.2.0 додано підтримку розділення лінії мультилінією, мультиточкою або (мульти)полігоном.
Покращено: 2.5.0 додано підтримку розділення полігону мультилінією.
Розділити полігон лінією.
|
![]() До розділення
|
![]() Після розділення
|
SELECT ST_AsText( ST_Split(
ST_Buffer(ST_GeomFromText('POINT(100 90)'), 50), -- circle
ST_MakeLine(ST_Point(10, 10),ST_Point(190, 190)) -- line
));
-- result --
GEOMETRYCOLLECTION(
POLYGON((150 90,149.039264020162 80.2454838991936,146.193976625564 70.8658283817455,..),
POLYGON(..))
)
Розділити MultiLineString за точкою, яка лежить точно на обох елементах LineStrings.
|
![]() До розділення
|
![]() Після розділення
|
SELECT ST_AsText(ST_Split(
'MULTILINESTRING((10 10, 190 190), (15 15, 30 30, 100 90))',
ST_Point(30,30))) As split;
split
------
GEOMETRYCOLLECTION(
LINESTRING(10 10,30 30),
LINESTRING(30 30,190 190),
LINESTRING(15 15,30 30),
LINESTRING(30 30,100 90)
)
Розділити лінію String за точкою, яка не лежить точно на лінії. Показано за допомогою ST_Snap, щоб прив'язати лінію до точки, щоб її можна було розділити.
WITH data AS (SELECT
'LINESTRING(0 0, 100 100)'::geometry AS line,
'POINT(51 50)':: geometry AS point
)
SELECT ST_AsText( ST_Split( ST_Snap(line, point, 1), point)) AS snapped_split,
ST_AsText( ST_Split(line, point)) AS not_snapped_not_split
FROM data;
snapped_split | not_snapped_not_split
---------------------------------------------------------------------+---------------------------------------------
GEOMETRYCOLLECTION(LINESTRING(0 0,51 50),LINESTRING(51 50,100 100)) | GEOMETRYCOLLECTION(LINESTRING(0 0,100 100))
ST_Subdivide — Обчислює прямолінійний поділ геометрії.
setof geometry ST_Subdivide(geometry geom, integer max_vertices=256, float8 gridSize = -1);
Повертає набір геометрій, які є результатом поділу geom на частини за допомогою прямолінійних ліній, причому кожна частина містить не більше ніж max_vertices.
max_vertices має бути 5 або більше, оскільки для зображення закритого прямокутника потрібно 5 точок.
If the optional gridSize parameter is given (GEOS-3.9.0 or higher required), all result vertices are guaranteed to fall on a grid of the specified size. For the operation to give predictable results all the input vertices must fall already on the specified grid, see ST_ReducePrecision.
Операції типу "точка в полігоні" та інші просторові операції зазвичай виконуються швидше для індексованих підрозділених набори даних. Оскільки обмежувальні рамки для частин зазвичай охоплюють меншу площу, ніж оригінальна геометрія bbox, запити до індексу дають менше випадків "влучання". Випадки "влучання" обробляються швидше, оскільки просторові операції, що виконуються індексом, перевіряють менше точок.
![]() | |
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. |
![]() | |
Це функція повернення набору (SRF), яка повертає набір рядків, що містять окремі значення геометрії. Її можна використовувати в списку SELECT або в розділі FROM для створення набору результатів з одним записом для кожної геометрії результату. |
Виконується модулем GEOS.
Доступність: 2.2.0
Покращено: 2.5.0 повторно використовує існуючі точки при розділенні полігону, кількість вершин зменшено з 8 до 5.
Покращено: 3.1.0 приймає параметр gridSize.
Для використання параметра gridSize необхідна версія GEOS >= 3.9.0
Приклад: Розділіть полігон на частини з не більше ніж 10 вершинами та присвойте кожній частині унікальний ідентифікатор.

Розділено на максимум 10 вершин
SELECT row_number() OVER() As rn, ST_AsText(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((119 23,85 35,68 29,66 28,32 56,22 64,29.8260869565217 100,119 100,119 23)) 2 │ POLYGON((132 10,119 23,119 56,186 56,186 52,178 34,168 18,147 13,132 10)) 3 │ POLYGON((119 56,119 100,190 100,185 79,186 56,119 56)) 4 │ POLYGON((29.8260869565217 100,32 110,40 119,36 150,57 158,75 171,92 182,114 184,114 100,29.8260869565217 100)) 5 │ POLYGON((114 184,132 186,146 178,176 184,179 162,184 141,190 122,190 100,114 100,114 184))
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.

Ущільнені та розділені лінії.
SELECT ST_AsText( 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)
Приклад: Розділіть складні геометрії таблиці на місці. Оригінальні записи геометрії видаляються з вихідної таблиці, а нові записи для кожної розділеної геометрії результату вставляються.
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;
Приклад: Створіть нову таблицю, що містить поділені геометрії, зберігаючи ключ оригінальної геометрії, щоб нову таблицю можна було об'єднати з вихідною таблицею. Оскільки ST_Subdivide є функцією, що повертає набір (таблицю) і повертає набір рядків з одним значенням, ця синтаксична конструкція автоматично створює таблицю з одним рядком для кожної частини результату.
CREATE TABLE subdivided_geoms AS
SELECT pkey, ST_Subdivide(geom) AS geom
FROM original_geoms;
ST_ClipByBox2D, ST_Segmentize, ST_Split, ST_NPoints, ST_ReducePrecision
ST_SymDifference — Обчислює геометрію, що представляє частини геометрій A і B, які не перетинаються.
geometry ST_SymDifference(geometry geomA, geometry geomB, float8 gridSize = -1);
Повертає геометрію, що представляє частини геометрій A і B, які не перетинаються. Це еквівалентно ST_Union(A,B) - ST_Intersection(A,B). Це називається симетричною різницею, оскільки 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 grid of the specified size. For the operation to give predictable results all the input vertices must fall already on the specified grid, see ST_ReducePrecision.
Виконано модулем GEOS
Покращено: 3.1.0 приймає параметр gridSize.
Для використання параметра gridSize необхідна версія GEOS >= 3.9.0
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. Однак результат обчислюється тільки за допомогою XY. Значення результату Z копіюються, усереднюються або інтерполюються.
|
![]() Оригінальні лініЇ, показані разом
|
![]() Симетрична різниця двох лінійних рядків
|
--Safe for 2d - symmetric difference of 2 linestrings
SELECT ST_AsText(
ST_SymDifference(
ST_GeomFromText('LINESTRING(50 100, 50 200)'),
ST_GeomFromText('LINESTRING(50 50, 50 150)')
)
);
st_astext
---------
MULTILINESTRING((50 150,50 200),(50 50,50 100))
--When used in 3d doesn't quite do the right thing
SELECT ST_AsEWKT(ST_SymDifference(ST_GeomFromEWKT('LINESTRING(1 2 1, 1 4 2)'),
ST_GeomFromEWKT('LINESTRING(1 1 3, 1 3 4)')))
st_astext
------------
MULTILINESTRING((1 3 2.75,1 4 2),(1 1 3,1 2 2.25))
ST_Difference, ST_Intersection, ST_Union, ST_ReducePrecision
ST_UnaryUnion — Обчислює об'єднання компонентів однієї геометрії.
geometry ST_UnaryUnion(geometry geom, float8 gridSize = -1);
Одновхідний варіант ST_Union. Вхідними даними може бути одна геометрія, MultiGeometry або GeometryCollection. Об'єднання застосовується до окремих елементів вхідних даних.
Цю функцію можна використовувати для виправлення полігонів MultiPolygons, які є недійсними через перекриття компонентів. Однак кожний з компонентів вхідних даних повинен бути дійсним. Недійсний компонент вхідних даних, такий як полігон у формі метелика, може спричинити помилку. З цієї причини краще використовувати ST_MakeValid.
Інше застосування цієї функції — об'єднання та роз'єднання набору лінійних рядків, які перетинаються або перекриваються, щоб зробити їх простими. (ST_Node також виконує цю функцію, але не надає опцію gridSize.)
Можна поєднати ST_UnaryUnion з ST_Collect, щоб точно налаштувати кількість геометрій, які об'єднуються одночасно. Це дозволяє досягти компромісу між використанням пам'яті та часом обчислення, забезпечуючи баланс між ST_Union та 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 grid of the specified size. For the operation to give predictable results all the input vertices must fall already on the specified grid, see ST_ReducePrecision.
This function supports 3d and will not drop the z-index. Однак результат обчислюється тільки за допомогою XY. Значення результату Z копіюються, усереднюються або інтерполюються.
Покращено: 3.1.0 приймає параметр gridSize.
Для використання параметра gridSize необхідна версія GEOS >= 3.9.0
Доступність: 2.0.0
ST_Union, ST_MemUnion, ST_MakeValid, ST_Collect, ST_Node, ST_ReducePrecision
ST_Union — Обчислює геометрію, що представляє об'єднання множин точок вхідних геометрій.
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);
Об'єднує геометрії вхідних даних, об'єднуючи геометрію для отримання геометрії результату без перекриттів. Результатом може бути атомна геометрія, MultiGeometry або колекція геометрій. Існує в декількох варіантах:
Варіант з двома входами: повертає геометрію, яка є об'єднанням двох вхідних геометрій. Якщо будь-який з входів має значення NULL, то повертається NULL.
Варіант масиву: повертає геометрію, яка є об'єднанням масиву геометрій.
Агрегований варіант: повертає геометрію, яка є об'єднанням набору рядків геометрій. Функція ST_Union() є "агрегованою" функцією в термінології PostgreSQL. Це означає, що вона працює з рядками даних так само, як функції SUM() та AVG(), і, як більшість агрегатів, ігнорує геометрії NULL.
Див. ST_UnaryUnionдля неагрегованого варіанту з одним вхідним параметром.
Масив ST_Union та варіанти набору використовують швидкий алгоритм каскадного об'єднання, описаний у 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 grid of the specified size. For the operation to give predictable results all the input vertices must fall already on the specified grid, see ST_ReducePrecision.
![]() | |
ST_Collect іноді може використовуватися замість ST_Union, якщо результат не повинен бути неперекривним. ST_Collect зазвичай працює швидше, ніж ST_Union, оскільки не виконує обробку зібраних геометрій. |
Виконується модулем GEOS.
ST_Union створює MultiLineString і не з'єднує LineStrings в один LineString. Для з'єднання LineStrings використовуйте ST_LineMerge.
ПРИМІТКА: раніше ця функція називалася GeomUnion(), але була перейменована з "Union", оскільки UNION є зарезервованим словом SQL.
Покращено: 3.1.0 приймає параметр gridSize.
Для використання параметра gridSize необхідна версія GEOS >= 3.9.0
Змінено: 3.0.0 не залежить від SFCGAL.
Доступність: 1.4.0 — ST_Union було вдосконалено. Було впроваджено ST_Union(geomarray), а також пришвидшено збір агрегатів у PostgreSQL.
This method implements the OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.3
![]() | |
Агрегована версія не визначена явно в OGC SPEC. |
This method implements the SQL/MM specification. SQL-MM 3: 5.1.19 z-індекс (висота) при використанні полігонів.
This function supports 3d and will not drop the z-index. Однак результат обчислюється тільки за допомогою XY. Значення результату Z копіюються, усереднюються або інтерполюються.
Приклад агрегату
SELECT id,
ST_Union(geom) as singlegeom
FROM sometable f
GROUP BY id;
Неагрегований приклад
select ST_AsText(ST_Union('POINT(1 2)' :: geometry, 'POINT(-2 3)' :: geometry))
st_astext
----------
MULTIPOINT(-2 3,1 2)
select ST_AsText(ST_Union('POINT(1 2)' :: geometry, 'POINT(1 2)' :: geometry))
st_astext
----------
POINT(1 2)3D-приклад — часткова підтримка 3D (і з змішаними розмірами!)
select ST_AsEWKT(ST_Union(geom))
from (
select 'POLYGON((-7 4.2,-7.1 4.2,-7.1 4.3, -7 4.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;
st_asewkt
---------
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)));
3D-приклад без змішування розмірів
select ST_AsEWKT(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;
st_asewkt
---------
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)))
--Examples using new Array construct
SELECT ST_Union(ARRAY(SELECT geom FROM sometable));
SELECT ST_AsText(ST_Union(ARRAY[ST_GeomFromText('LINESTRING(1 2, 3 4)'),
ST_GeomFromText('LINESTRING(3 4, 4 5)')])) As wktunion;
--wktunion---
MULTILINESTRING((3 4,4 5),(1 2,3 4))
Ці функції обчислюють геометричні конструкції або змінюють розмір чи форму геометрії.
ST_Buffer — Обчислює геометрію, що охоплює всі точки в межах заданої відстані від геометрії.
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);
Обчислює POLYGON або MULTIPOLYGON, що представляє всі точки, відстань яких від геометрії/географії менше або дорівнює заданій відстані. Від'ємна відстань зменшує геометрію, а не розширює її. Від'ємна відстань може повністю зменшити полігон, і в цьому випадку повертається POLYGON EMPTY. Для точок і ліній від'ємні відстані завжди повертають порожні результати.
Для геометрії відстань вказується в одиницях просторової системи координат геометрії. Для географії відстань вказується в метрах.
Опціональний третій параметр контролює точність і стиль буфера. Точність кругових дуг у буфері визначається як кількість лінійних сегментів, що використовуються для апроксимації чверті кола (за замовчуванням — 8). Стиль буфера можна вказати, надавши список пар ключ=значення, розділених пробілами, як показано нижче:
“quad_segs=#” : кількість відрізків лінії, що використовуються для апроксимації чверті кола (за замовчуванням — 8).
“endcap=round|flat|square” : стиль кінцевої частини (за замовчуванням "round"). “butt” приймається як синонім “flat”.
“join=round|mitre|bevel” : стиль з'єднання (за замовчуванням "round"). “miter” приймається як синонім “mitre”.
“mitre_limit=#.#” : обмеження кута зрізу (впливає тільки на стиль з'єднання з кутом зрізу). “miter_limit” приймається як синонім “mitre_limit”.
“side=both|left|right” : “left” або “right” виконує односторонній буфер на геометрії, причому сторона буфера відносна до напрямку лінії. Це застосовується тільки до геометрії LINESTRING і не впливає на геометрії POINT або POLYGON. За замовчуванням кінці є квадратними.
![]() | |
|
![]() | |
Буфер може обробляти недійсні вхідні дані, а вихідні дані завжди мають дійсну полігональну геометрію. Буферизація за відстанню 0 іноді використовується як спосіб виправлення недійсних полігонів. ST_MakeValidбільш підходить для цього процесу, оскільки може обробляти мультиполігони. |
![]() | |
Буферизація іноді використовується для виконання пошуку в межах певної відстані. Для цього випадку використання ефективніше використовувати ST_DWithin. |
![]() | |
Ця функція ігнорує вимір Z. Вона завжди дає двовимірний результат, навіть якщо використовується для тривимірної геометрії. |
Покращено: 2.5.0 - Підтримка геометрії ST_Buffer була покращена, щоб дозволити вказати бічне буферизування side=both|left|right.
Доступність: 1.5 - ST_Buffer було вдосконалено для підтримки різних кінцевих капсул та типів з'єднання. Це корисно, наприклад, для перетворення лінійних дорожніх об'єктів у полігонні дороги з плоскими або квадратними краями замість заокруглених. Додано тонкий обгортковий об'єкт для географії.
Виконується модулем 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
![]() quad_segs=8 (за замовчуванням)
SELECT ST_Buffer(
ST_GeomFromText('POINT(100 90)'),
50, 'quad_segs=8');
| ![]() quad_segs=2 (неповноцінний)
SELECT ST_Buffer(
ST_GeomFromText('POINT(100 90)'),
50, 'quad_segs=2');
| |
![]() endcap=round join=round (за замовчуванням)
SELECT ST_Buffer(
ST_GeomFromText(
'LINESTRING(50 50,150 150,150 50)'
), 10, 'endcap=round join=round');
| ![]() endcap=square
SELECT ST_Buffer(
ST_GeomFromText(
'LINESTRING(50 50,150 150,150 50)'
), 10, 'endcap=square join=round');
| ![]() endcap=flat
SELECT ST_Buffer(
ST_GeomFromText(
'LINESTRING(50 50,150 150,150 50)'
), 10, 'endcap=flat join=round');
|
![]() join=bevel
SELECT ST_Buffer(
ST_GeomFromText(
'LINESTRING(50 50,150 150,150 50)'
), 10, 'join=bevel');
| ![]() join=mitre mitre_limit=5.0 (стандартне обмеження mitre)
SELECT ST_Buffer(
ST_GeomFromText(
'LINESTRING(50 50,150 150,150 50)'
), 10, 'join=mitre mitre_limit=5.0');
| ![]() join=mitre mitre_limit=1
SELECT ST_Buffer(
ST_GeomFromText(
'LINESTRING(50 50,150 150,150 50)'
), 10, 'join=mitre mitre_limit=1.0');
|
![]() side=left
SELECT ST_Buffer(
ST_GeomFromText(
'LINESTRING(50 50,150 150,150 50)'
), 10, 'side=left');
| ![]() side=right
SELECT ST_Buffer(
ST_GeomFromText(
'LINESTRING(50 50,150 150,150 50)'
), 10, 'side=right');
| ![]() side=left join=mitre
SELECT ST_Buffer(
ST_GeomFromText(
'LINESTRING(50 50,150 150,150 50)'
), 10, 'side=left join=mitre');
|
![]() right-hand-winding, polygon boundary side=left
SELECT ST_Buffer(
ST_ForceRHR(
ST_Boundary(
ST_GeomFromText(
'POLYGON ((50 50, 50 150, 150 150, 150 50, 50 50))'))),
), 20, 'side=left');
| ![]() right-hand-winding, polygon boundary side=right
SELECT ST_Buffer(
ST_ForceRHR(
ST_Boundary(
ST_GeomFromText(
'POLYGON ((50 50, 50 150, 150 150, 150 50, 50 50))'))
), 20,'side=right')
|
--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)
SELECT ST_NPoints(ST_Buffer(ST_GeomFromText('POINT(100 90)'), 50)) As promisingcircle_pcount,
ST_NPoints(ST_Buffer(ST_GeomFromText('POINT(100 90)'), 50, 2)) As lamecircle_pcount;
promisingcircle_pcount | lamecircle_pcount
------------------------+-------------------
33 | 9
--A lighter but lamer circle
-- only 2 points per quarter circle is an octagon
--Below is a 100 meter octagon
-- Note coordinates are in NAD 83 long lat which we transform
to Mass state plane meter and then buffer to get measurements in meters;
SELECT ST_AsText(ST_Buffer(
ST_Transform(
ST_SetSRID(ST_Point(-71.063526, 42.35785),4269), 26986)
,100,2)) As octagon;
----------------------
POLYGON((236057.59057465 900908.759918696,236028.301252769 900838.049240578,235
957.59057465 900808.759918696,235886.879896532 900838.049240578,235857.59057465
900908.759918696,235886.879896532 900979.470596815,235957.59057465 901008.759918
696,236028.301252769 900979.470596815,236057.59057465 900908.759918696))
ST_Collect, ST_DWithin, ST_SetSRID, ST_Transform, ST_Union, ST_MakeValid
ST_BuildArea — Створює полігональну геометрію, утворену лініями геометрії.
geometry ST_BuildArea(geometry geom);
Створює площинну геометрію, утворену лініями, що складають вхідну геометрію. Вхідними даними можуть бути LineString, MultiLineString, Polygon, MultiPolygon або GeometryCollection. Результатом є Polygon або MultiPolygon, залежно від вхідних даних. Якщо вхідні лінії не утворюють полігонів, повертається NULL.
На відміну від ST_MakePolygon, ця функція приймає кільця, утворені декількома лініями, і може утворювати будь-яку кількість полігонів.
Ця функція перетворює внутрішні кільця на отвори. Щоб перетворити внутрішні кільця також на полігони, використовуйте ST_Polygonize.
![]() | |
Для коректної роботи цієї функції вхідні лінії повинні бути правильно позначені вузлами. Для позначення ліній можна використовувати ST_Node. Якщо вхідні лінії перетинаються, ця функція створить недійсні полігони. ST_MakeValidможна використовувати для забезпечення дійсності вихідних даних. |
Доступність: 1.1.0
![]() Вхідні лінії
|
![]() Результати за площею
|
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_AsText( ST_BuildArea( ST_Collect( geom )))
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))

Створити кільце з двох круглих полігонів
SELECT ST_BuildArea(ST_Collect(inring,outring))
FROM (SELECT
ST_Buffer('POINT(100 90)', 25) As inring,
ST_Buffer('POINT(100 90)', 50) As outring) As t;
ST_Collect, ST_MakePolygon, ST_MakeValid, ST_Node, ST_Polygonize, ST_BdPolyFromText, ST_BdMPolyFromText (обгортки для цієї функції зі стандартним інтерфейсом OGC)
ST_Centroid — Повертає геометричний центр геометрії.
geometry ST_Centroid(geometry g1);
geography ST_Centroid(geography g1, boolean use_spheroid = true);
Обчислює точку, яка є геометричним центром маси геометрії. Для [MULTI]POINTs, центроїд є середнім арифметичним вхідних координат. Для [MULTI]LINESTRINGs, центроїд обчислюється за допомогою зваженої довжини кожного відрізка лінії. Для [MULTI]POLYGONs, центроїд обчислюється за площею. Якщо надано порожню геометрію, повертається порожній GEOMETRYCOLLECTION. Якщо вказано NULL, повертається NULL. Якщо вказано CIRCULARSTRING або COMPOUNDCURVE, вони спочатку перетворюються на лінії за допомогою CurveToLine, а потім так само, як для LINESTRING
Для вхідних даних змішаного розміру результат дорівнює центроїду компонента Геометрії найвищого розміру (оскільки геометрії нижчого розміру не мають "ваги" для центроїда).
Зверніть увагу, що для полігональних геометрій центр ваги не обов'язково лежить всередині полігону. Наприклад, дивіться схему нижче, що зображує центр ваги С-подібного полігону. Щоб побудувати точку, яка гарантовано лежить всередині полігону, використовуйте ST_PointOnSurface.
Нове в версії 2.3.0: підтримка CIRCULARSTRING та COMPOUNDCURVE (за допомогою CurveToLine)
Доступність: 2.4.0 додано підтримку географії.
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
На наступних ілюстраціях червона точка є центром ваги вихідної геометрії.
![]() Центроїд | ![]() Центроїд |
![]() Центроїд | ![]() Центроїд |
SELECT ST_AsText(ST_Centroid('MULTIPOINT ( -1 0, -1 2, -1 3, -1 4, -1 7, 0 1, 0 3, 1 1, 2 0, 6 0, 7 8, 9 8, 10 6 )'));
st_astext
------------------------------------------
POINT(2.30769230769231 3.30769230769231)
(1 row)
SELECT ST_AsText(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 ;
------------------------------------------
POINT(0.5 1)
SELECT ST_AsText(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;
------------------------------------------
POINT(0.5 1)
ST_ChaikinSmoothing — Повертає згладжену версію геометрії, використовуючи алгоритм Чайкіна.
geometry ST_ChaikinSmoothing(geometry geom, integer nIterations = 1, boolean preserveEndPoints = false);
Згладжує лінійну або полігональну геометрію за допомогою алгоритму Чайкіна. Ступінь згладжування контролюється параметром nIterations. На кожній ітерації кожна внутрішня вершина замінюється двома вершинами, розташованими на 1/4 довжини відрізків лінії перед і після вершини. Розумний ступінь згладжування забезпечується 3 ітераціями; максимальне значення обмежено 5.
Якщо preserveEndPoints має значення true, кінцеві точки кілець полігону не згладжуються. Кінцеві точки лінійних об'єктів завжди зберігаються.
![]() | |
Кількість вершин подвоюється з кожною ітерацією, тому геометрія результату може мати набагато більше точок, ніж вхідні дані. Щоб зменшити кількість точок, скористайтеся функцією спрощення результату (див. ST_Simplify, ST_SimplifyPreserveTopologyта ST_SimplifyVW). |
Результатом є інтерпольовані значення для розмірів Z і M, якщо вони присутні.
This function supports 3d and will not drop the z-index.
Доступність: 2.5.0
Згладжування трикутника:
SELECT ST_AsText(ST_ChaikinSmoothing(geom)) smoothed
FROM (SELECT 'POLYGON((0 0, 8 8, 0 16, 0 0))'::geometry geom) AS foo;
smoothed
───────────────────────────────────────────
POLYGON((2 2,6 6,6 10,2 14,0 12,0 4,2 2))
Згладжування полігону за допомогою 1, 2 і 3 ітерацій:
![]() nIterations = 1 | ![]() nIterations = 2 | ![]() nIterations = 3 |
SELECT 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))',
generate_series(1, 3) );
Згладжування LineString за допомогою 1, 2 і 3 ітерацій:
![]() nIterations = 1 | ![]() nIterations = 2 | ![]() nIterations = 3 |
SELECT ST_ChaikinSmoothing(
'LINESTRING (10 140, 80 130, 100 190, 190 150, 140 20, 120 120, 50 30, 30 100)',
generate_series(1, 3) );
ST_ConcaveHull — Обчислює можливу увігнуту геометрію, яка містить усі вершини вхідної геометрії
geometry ST_ConcaveHull(geometry param_geom, float param_pctconvex, boolean param_allow_holes = false);
Увігнутий контур — це (зазвичай) увігнута геометрія, яка містить вхідні дані, а її вершини є підмножиною вершин вхідних даних. У загальному випадку увігнутий корпус є полігоном. Увігнутий корпус двох або більше колінеарних точок є двоточковим LineString. Увігнутий корпус однієї або більше ідентичних точок є точкою. Полігон не буде містити отворів, якщо опціональний аргумент param_allow_holes не вказано як true.
Уявіть собі увігнутий контур, що "обгортає" набір точок. Це відрізняється від опуклого контуру, який більше нагадує гумку, натягнуту навколо точок. Увігнутий контур зазвичай має меншу площу і є більш природною межею для вхідних точок.
Параметр param_pctconvex контролює увігнутість обчислюваної оболонки. Значення 1 створює опуклу оболонку. Значення від 1 до 0 створюють оболонки із зростаючою увігнутістю. Значення 0 створює оболонку з максимальною увігнутістю (але все одно єдиний полігон). Вибір відповідного значення залежить від характеру вхідних даних, але часто значення між 0,3 і 0,1 дають прийнятні результати.
![]() | |
Технічно, параметр |
Для точкових і лінійних вхідних даних оболонка охоплюватиме всі точки вхідних даних. Для полігональних вхідних даних оболонка охоплюватиме всі точки вхідних даних а також всі області, що охоплюються вхідними даними. Якщо ви хочете отримати точкову оболонку полігональних вхідних даних, спочатку перетворіть їх у точки за допомогою ST_Points.
Це не агрегатна функція. Для обчислення увігнутої оболонки набору геометрій використовуйте ST_Collect(наприклад, ST_ConcaveHull( ST_Collect( geom ), 0.80).
Доступність: 2.0.0
Покращено: 3.3.0, увімкнено вбудовану реалізацію GEOS для GEOS 3.11+

Увігнутий корпус багатоточкового пристрою
SELECT ST_AsText( 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))

Увігнутий корпус багатоточкового пристрою, що дозволяє робити отвори
SELECT ST_AsText( 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))
![]()
| ![]()
|
Порівняння увігнутого корпусу полігону з увігнутим корпусом складових точок. Корпус дотримується меж полігону, тоді як оболонка на основі точок цього не робить.
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;
Використання з ST_Collect для обчислення увігнутої оболонки набору геометрій.
-- Compute estimate of infected area based on point observations
SELECT disease_type,
ST_ConcaveHull( ST_Collect(obs_pnt), 0.3 ) AS geom
FROM disease_obs
GROUP BY disease_type;
ST_ConvexHull, ST_Collect, ST_AlphaShape, ST_OptimalAlphaShape
ST_ConvexHull — Обчислює опуклу оболонку геометрії.
geometry ST_ConvexHull(geometry geomA);
Обчислює опуклу оболонку геометрії. Опукла оболонка — це найменша опукла геометрія, яка охоплює всі геометрії у вхідних даних.
Опуклу оболонку можна уявити як геометрію, отриману шляхом обертання гумової стрічки навколо набору геометрій. Це відрізняється від увігнутої оболонки, яка аналогічна "упаковці" геометрій. Опукла оболонка часто використовується для визначення зони впливу на основі набору точкових спостережень.
У загальному випадку опукла оболонка є полігоном. Опукла оболонка двох або більше колінеарних точок є двоточковою лінією. Опукла оболонка однієї або більше однакових точок є точкою.
Це не агрегатна функція. Щоб обчислити опуклу оболонку набору геометрій, використовуйте ST_Collect, щоб об'єднати їх у колекцію геометрій (наприклад, 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.

Опукла оболонка багатолінійної та мультиточкової фігури
SELECT ST_AsText(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))
Використання разом із ST_Collect для обчислення опуклих оболонок наборів геометричних фігур.
--Get estimate of infected area based on point observations
SELECT d.disease_type,
ST_ConvexHull(ST_Collect(d.geom)) As geom
FROM disease_obs As d
GROUP BY d.disease_type;
ST_DelaunayTriangles — Повертає триангуляцію Делауея вершин геометрії.
geometry ST_DelaunayTriangles(geometry g1, float tolerance = 0.0, int4 flags = 0);
Обчислює триангуляцію Делоне вершин вхідної геометрії. Опціональний параметр tolerance можна використовувати для з'єднання сусідніх вхідних вершин, що в деяких ситуаціях підвищує надійність. Результуюча геометрія обмежується опуклою оболонкою вхідних вершин. Представлення результуючої геометрії визначається кодом flags:
0 - GEOMETRYCOLLECTION трикутних полігонів (за замовчуванням)
1 - MULTILINESTRING граней триангуляції
2 - TIN триангуляції
Виконується модулем 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).
![]() Оригінальні полігони our original geometry
ST_Union(ST_GeomFromText('POLYGON((175 150, 20 40,
50 60, 125 100, 175 150))'),
ST_Buffer(ST_GeomFromText('POINT(110 170)'), 20)
) |
![]() ST_DelaunayTriangles з 2 полігонів: трикутники Делоне, кожен трикутник виділений різним кольором
geometries overlaid multilinestring triangles
SELECT
ST_DelaunayTriangles(
ST_Union(ST_GeomFromText('POLYGON((175 150, 20 40,
50 60, 125 100, 175 150))'),
ST_Buffer(ST_GeomFromText('POINT(110 170)'), 20)
))
As dtriag;
|
![]() -- трикутники Делоне як мультилінія
SELECT
ST_DelaunayTriangles(
ST_Union(ST_GeomFromText('POLYGON((175 150, 20 40,
50 60, 125 100, 175 150))'),
ST_Buffer(ST_GeomFromText('POINT(110 170)'), 20)
),0.001,1)
As dtriag;
|
![]() -- трикутники Делоне з 45 точками як 55 трикутних полігонів
this produces a table of 42 points that form an L shape SELECT (ST_DumpPoints(ST_GeomFromText( '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)'))).geom INTO TABLE l_shape; output as individual polygon triangles SELECT ST_AsText((ST_Dump(geom)).geom) As wkt FROM ( SELECT ST_DelaunayTriangles(ST_Collect(geom)) As geom FROM l_shape) As foo; wkt 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))
|
Приклад використання вершин із значеннями Z.
3D multipoint SELECT ST_AsText(ST_DelaunayTriangles(ST_GeomFromText( 'MULTIPOINT Z(14 14 10, 150 14 100,34 6 25, 20 10 150)'))) As wkt; wkt 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 — Видаляє вершини на основі їхнього значення M
geometry ST_FilterByM(geometry geom, double precision min, double precision max = null, boolean returnM = false);
Відфільтровує вершинні точки на основі їх M-значення. Повертає геометрію, що містить тільки вершинні точки, M-значення яких більше або дорівнює мінімальному значенню і менше або дорівнює максимальному значенню. Якщо аргумент max-value не вказано, враховується тільки значення min. Якщо четвертий аргумент не вказано, m-значення не буде включено в результуючу геометрію. Якщо в результуючій геометрії залишилося занадто мало вершинних точок для її типу, буде повернута порожня геометрія. У колекції геометрій геометрії без достатньої кількості точок просто пропускаються без повідомлення.
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 |
Доступність: 2.5.0
A linestring is filtered
SELECT ST_AsText(ST_FilterByM(geom,30)) simplified
FROM (SELECT ST_SetEffectiveArea('LINESTRING(5 2, 3 8, 6 20, 7 25, 10 10)'::geometry) geom) As foo;
result
simplified
----------------------------
LINESTRING(5 2,7 25,10 10)
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

Generated a multipoint consisting of 12 Points overlaid on top of original polygon using a random seed value 1996
SELECT ST_GeneratePoints(geom, 12, 1996)
FROM (
SELECT ST_Buffer(
ST_GeomFromText(
'LINESTRING(50 50,150 150,150 50)'),
10, 'endcap=round join=round') AS geom
) AS s;
Given a table of polygons s, return 12 individual points per polygon. Results will be different each time you run.
SELECT s.id, dp.path[1] AS pt_id, dp.geom FROM s, ST_DumpPoints(ST_GeneratePoints(s.geom,12)) AS dp;
ST_GeometricMedian — Returns the geometric median of a MultiPoint.
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).
Якщо аргумент tolerance не вказано, значення допуску обчислюється на основі розмірів вхідної геометрії.
Якщо присутні, значення вхідної точки M інтерпретуються як їх відносні ваги.
Доступність: 2.3.0
Покращено: 2.5.0 Додано підтримку M як ваги точок.
This function supports 3d and will not drop the z-index.
This function supports M coordinates.

Порівняння геометричної медіани (червоний) та центроїда (бірюзовий) MultiPoint.
WITH test AS (
SELECT 'MULTIPOINT((10 10), (10 40), (40 10), (190 190))'::geometry geom)
SELECT
ST_AsText(ST_Centroid(geom)) centroid,
ST_AsText(ST_GeometricMedian(geom)) median
FROM test;
centroid | median
--------------------+----------------------------------------
POINT(62.5 62.5) | POINT(25.01778421249728 25.01778421249728)
(1 row)
ST_LineMerge — Повернути лінії, утворені зшиванням MultiLineString.
geometry ST_LineMerge(geometry amultilinestring);
geometry ST_LineMerge(geometry amultilinestring, boolean directed);
Повертає LineString або MultiLineString, утворений шляхом з'єднання лінійних елементів MultiLineString. Лінії з'єднуються в кінцевих точках на двосторонніх перетинах. Лінії не з'єднуються на перетинах з трьома або більше точками.
Якщо directed має значення TRUE, то ST_LineMerge не змінюватиме порядок точок у LineStrings, тому лінії з протилежними напрямками не будуть об'єднані
![]() | |
Використовуйте тільки з MultiLineString/LineStrings. Інші типи геометрії повертають порожній GeometryCollection |
Виконується модулем GEOS.
Покращено: 3.3.0 приймає спрямований параметр.
Для використання параметра directed необхідна версія GEOS >= 3.11.0.
Доступність: 1.1.0
![]() | |
Ця функція видаляє розмірність M. |

Об'єднання ліній з різною орієнтацією.
SELECT ST_AsText(ST_LineMerge(
'MULTILINESTRING((10 160, 60 120), (120 140, 60 120), (120 140, 180 120))'
));
--------------------------------------------
LINESTRING(10 160,60 120,120 140,180 120)

Лінії не об'єднуються на перетинах зі ступенем > 2.
SELECT ST_AsText(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))
Якщо об'єднання неможливе через непересічні лінії, повертається оригінальний MultiLineString.
SELECT ST_AsText(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))

Лінії з протилежними напрямками не об'єднуються, якщо directed = TRUE.
SELECT ST_AsText(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))
Приклад, що ілюструє обробку Z-виміру.
SELECT ST_AsText(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)
ST_MaximumInscribedCircle — Обчислює найбільше коло, що міститься в геометрії.
(geometry, geometry, double precision) ST_MaximumInscribedCircle(geometry geom);
Знаходить найбільше коло, яке міститься в (мульти)полігоні або не перетинається з лініями та точками. Повертає запис із полями:
center - центр кола
nearest - точка на геометрії, найближча до центру
radius - радіус кола
Для полігональних вхідних даних коло вписується в межі кільця, використовуючи внутрішні кільця як межі. Для лінійних і точкових вхідних даних коло вписується в опуклу оболонку вхідних даних, використовуючи лінії і точки вхідних даних як додаткові межі.
Доступність: 3.1.0.
Потрібна версія GEOS >= 3.9.0.

Максимальне вписане коло полігону. Повертаються центр, найближча точка та радіус.
SELECT radius, ST_AsText(center) AS center, ST_AsText(nearest) AS nearest
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))');
radius | center | nearest
-----------------+----------------------------+---------------
45.165845650018 | POINT(96.953125 76.328125) | POINT(140 90)

Максимальне вписане коло багатолінійної фігури. Повертаються центр, найближча точка та радіус.
ST_LargestEmptyCircle — Обчислює найбільше коло, яке не перетинається з геометрією.
(geometry, geometry, double precision) ST_LargestEmptyCircle(geometry geom, double precision tolerance=0.0, geometry boundary=POINT EMPTY);
Знаходить найбільше коло, яке не перетинається з набором точкових і лінійних перешкод. (Полігональні геометрії можуть бути включені як перешкоди, але використовуються тільки їх межі.) Центр кола обмежений межами полігональної фігури, яка за замовчуванням є опуклою оболонкою вхідної геометрії. Центр кола — це точка всередині межі, яка має найбільшу відстань від перешкод. Саме коло задається центром і найближчою точкою, що лежить на перешкоді, яка визначає радіус кола.
Центр кола визначається з заданою точністю, яка визначається допуском на відстань, за допомогою ітераційного алгоритму. Якщо точність відстані не вказана, використовується розумне значення за замовчуванням.
Повертає запис із полями:
center - центр кола
nearest - точка на геометрії, найближча до центру
radius - радіус кола
Щоб знайти найбільше порожнє коло всередині полігону, див. ST_MaximumInscribedCircle.
Доступність: 3.4.0.
Потрібна версія GEOS >= 3.9.0.
SELECT radius,
center,
nearest
FROM ST_LargestEmptyCircle(
'MULTILINESTRING (
(10 100, 60 180, 130 150, 190 160),
(20 50, 70 70, 90 20, 110 40),
(160 30, 100 100, 180 100))');
Найбільше порожнє коло в наборі ліній.
SELECT radius,
center,
nearest
FROM ST_LargestEmptyCircle(
ST_Collect(
'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),
0,
'POLYGON ((90 190, 10 100, 60 10, 190 40, 120 100, 190 180, 90 190))'::geometry
);
Найбільше порожнє коло в наборі точок, обмежене полігоном. Межа полігону обмеження повинна бути включена як перешкода, а також вказана як обмеження для центру кола.
ST_MinimumBoundingCircle — Повертає найменший полігон кола, що містить геометрію.
geometry ST_MinimumBoundingCircle(geometry geomA, integer num_segs_per_qt_circ=48);
Повертає найменший полігон кола, що містить геометрію.
![]() | |
Обмежувальне коло наближається полігоном із 48 сегментами на чверть кола за замовчуванням. Оскільки полігон є наближенням мінімального обмежувального кола, деякі точки в геометрії вхідних даних можуть не міститися в полігоні. Наближення можна поліпшити, збільшивши кількість сегментів. Для додатків, де наближення не підходить, можна використовувати ST_MinimumBoundingRadius. |
Використовуйте з ST_Collect, щоб отримати мінімальне обмежуюче коло набору геометрій.
Щоб обчислити дві точки, що лежать на мінімальному колі (максимальний діаметр), використовуйте ST_LongestLine.
Відношення площі полігону до площі його мінімального обмежувального кола називається коефіцієнтом компактності Реока.
Виконується модулем GEOS.
Доступність: 1.4.0
SELECT d.disease_type,
ST_MinimumBoundingCircle(ST_Collect(d.geom)) As geom
FROM disease_obs As d
GROUP BY d.disease_type;

Мінімальне обмежуюче коло точки та лінії. Використання 8 сегментів для наближення чверті кола
SELECT ST_AsText(ST_MinimumBoundingCircle(
ST_Collect(
ST_GeomFromText('LINESTRING(55 75,125 150)'),
ST_Point(20, 80)), 8
)) As wktmbc;
wktmbc
-----------
POLYGON((135.59714732062 115,134.384753327498 102.690357210921,130.79416296937 90.8537670908995,124.963360620072 79.9451031602111,117.116420743937 70.3835792560632,107.554896839789 62.5366393799277,96.6462329091006 56.70583703063,84.8096427890789 53.115246672502,72.5000000000001 51.9028526793802,60.1903572109213 53.1152466725019,48.3537670908996 56.7058370306299,37.4451031602112 62.5366393799276,27.8835792560632 70.383579256063,20.0366393799278 79.9451031602109,14.20583703063 90.8537670908993,10.615246672502 102.690357210921,9.40285267938019 115,10.6152466725019 127.309642789079,14.2058370306299 139.1462329091,20.0366393799275 150.054896839789,27.883579256063 159.616420743937,
37.4451031602108 167.463360620072,48.3537670908992 173.29416296937,60.190357210921 176.884753327498,
72.4999999999998 178.09714732062,84.8096427890786 176.884753327498,96.6462329091003 173.29416296937,107.554896839789 167.463360620072,
117.116420743937 159.616420743937,124.963360620072 150.054896839789,130.79416296937 139.146232909101,134.384753327498 127.309642789079,135.59714732062 115))
ST_MinimumBoundingRadius — Повертає центр і радіус найменшого кола, що містить геометрію.
(geometry, double precision) ST_MinimumBoundingRadius(geometry geom);
Обчислює центр і радіус найменшого кола, що містить геометрію. Повертає запис із полями:
center - центр кола
radius - радіус кола
Використовуйте з ST_Collect, щоб отримати мінімальне обмежуюче коло набору геометрій.
Щоб обчислити дві точки, що лежать на мінімальному колі (максимальний діаметр), використовуйте ST_LongestLine.
Доступність - 2.3.0
SELECT ST_AsText(center), radius FROM ST_MinimumBoundingRadius('POLYGON((26426 65078,26531 65242,26075 65136,26096 65427,26426 65078))');
st_astext | radius
------------------------------------------+------------------
POINT(26284.8418027133 65267.1145090825) | 247.436045591407
ST_OrientedEnvelope — Повертає прямокутник з мінімальною площею, що містить геометрію.
geometry ST_OrientedEnvelope( geometry geom );
Повертає прямокутник з мінімальною площею, що охоплює геометрію. Зверніть увагу, що може існувати більше одного такого прямокутника. У разі вироджених вхідних даних може повертати Point або LineString.
Availability: 2.5.0.
Requires GEOS >= 3.6.0.
SELECT ST_AsText(ST_OrientedEnvelope('MULTIPOINT ((0 0), (-1 -1), (3 2))'));
st_astext
------------------------------------------------
POLYGON((3 2,2.88 2.16,-1.12 -0.84,-1 -1,3 2))

Oriented envelope of a point and linestring.
SELECT ST_AsText(ST_OrientedEnvelope(
ST_Collect(
ST_GeomFromText('LINESTRING(55 75,125 150)'),
ST_Point(20, 80))
)) As wktenv;
wktenv
-----------
POLYGON((19.9999999999997 79.9999999999999,33.0769230769229 60.3846153846152,138.076923076924 130.384615384616,125.000000000001 150.000000000001,19.9999999999997 79.9999999999999))
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.
Units of distance are measured in units of the spatial reference system.
Note that output may be a MULTILINESTRING or EMPTY for some jigsaw-shaped input geometries.
The optional third parameter allows specifying a list of blank-separated key=value pairs to tweak operations as follows:
'quad_segs=#' : number of segments used to approximate a quarter circle (defaults to 8).
'join=round|mitre|bevel' : join style (defaults to "round"). 'miter' is also accepted as a synonym for 'mitre'.
'mitre_limit=#.#' : mitre ratio limit (only affects mitred join style). 'miter_limit' is also accepted as a synonym for 'mitre_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
![]() | |
Ця функція ігнорує вимір Z. Вона завжди дає двовимірний результат, навіть якщо використовується для тривимірної геометрії. |
Compute an open buffer around roads
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;
![]() 15, 'quad_segs=4 join=round' original line and its offset 15 units.
SELECT ST_AsText(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'));
output
LINESTRING(164 1,18 1,12.2597485145237 2.1418070123307,
7.39339828220179 5.39339828220179,
5.39339828220179 7.39339828220179,
2.14180701233067 12.2597485145237,1 18,1 195)
| ![]() -15, 'quad_segs=4 join=round' original line and its offset -15 units
SELECT ST_AsText(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;
notsocurvy
LINESTRING(31 195,31 31,164 31)
|
![]() double-offset to get more curvy, note the first reverses direction, so -30 + 15 = -15
SELECT ST_AsText(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;
morecurvy
LINESTRING(164 31,46 31,40.2597485145236 32.1418070123307,
35.3933982822018 35.3933982822018,
32.1418070123307 40.2597485145237,31 46,31 195)
| ![]() double-offset to get more curvy,combined with regular offset 15 to get parallel lines. Overlaid with original.
SELECT ST_AsText(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;
parallel curves
MULTILINESTRING((164 1,18 1,12.2597485145237 2.1418070123307,
7.39339828220179 5.39339828220179,5.39339828220179 7.39339828220179,
2.14180701233067 12.2597485145237,1 18,1 195),
(164 31,46 31,40.2597485145236 32.1418070123307,35.3933982822018 35.3933982822018,
32.1418070123307 40.2597485145237,31 46,31 195))
|
![]() 15, 'quad_segs=4 join=bevel' shown with original line
SELECT ST_AsText(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'));
output
LINESTRING(164 1,18 1,7.39339828220179 5.39339828220179,
5.39339828220179 7.39339828220179,1 18,1 195)
| ![]() 15,-15 collected, join=mitre mitre_limit=2.1
SELECT ST_AsText(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;
output
MULTILINESTRING((164 1,11.7867965644036 1,1 11.7867965644036,1 195),
(31 195,31 31,164 31))
|
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 | ![]() Point on surface of a |
![]() Point on surface of a | ![]() Point on surface of a |
SELECT ST_AsText(ST_PointOnSurface('POINT(0 5)'::geometry));
------------
POINT(0 5)
SELECT ST_AsText(ST_PointOnSurface('LINESTRING(0 5, 0 10)'::geometry));
------------
POINT(0 5)
SELECT ST_AsText(ST_PointOnSurface('POLYGON((0 0, 0 5, 5 5, 5 0, 0 0))'::geometry));
----------------
POINT(2.5 2.5)
SELECT ST_AsEWKT(ST_PointOnSurface(ST_GeomFromEWKT('LINESTRING(0 5 1, 0 0 1, 0 10 2)')));
----------------
POINT(0 0 1)
Example: The result of ST_PointOnSurface is guaranteed to lie within polygons, whereas the point computed by ST_Centroid may be outside.

Red: point on surface; Green: centroid
SELECT ST_AsText(ST_PointOnSurface(geom)) AS pt_on_surf,
ST_AsText(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)
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
![]() Вхідні лінії
|
![]() Polygonized result
|
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_AsText( 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 ((20 90, 20 160, 70 190, 80 130, 70 70, 20 90)),
POLYGON ((160 160, 80 130, 70 190, 160 160)),
POLYGON ((80 60, 120 130, 150 80, 80 60)))
Polygonizing a table of linestrings:
SELECT ST_AsEWKT(ST_Polygonize(geom_4269)) As geomtextrep
FROM (SELECT geom_4269 FROM ma.suffolk_edges) As foo;
-------------------------------------
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)))
--Use ST_Dump to dump out the polygonize geoms into individual polygons
SELECT ST_AsEWKT((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;
------------------------
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))
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)
Доступність: 3.1.0.
Потрібна версія GEOS >= 3.9.0.
SELECT ST_AsText(ST_ReducePrecision('POINT(1.412 19.323)', 0.1));
st_astext
-----------------
POINT(1.4 19.3)
SELECT ST_AsText(ST_ReducePrecision('POINT(1.412 19.323)', 1.0));
st_astext
-------------
POINT(1 19)
SELECT ST_AsText(ST_ReducePrecision('POINT(1.412 19.323)', 10));
st_astext
-------------
POINT(0 20)
Precision reduction can reduce number of vertices
SELECT ST_AsText(ST_ReducePrecision('LINESTRING (10 10, 19.6 30.1, 20 30, 20.3 30, 40 40)', 1));
st_astext
-------------
LINESTRING (10 10, 20 30, 40 40)
Precision reduction splits polygons if needed to ensure validity
SELECT ST_AsText(ST_ReducePrecision('POLYGON ((10 10, 60 60.1, 70 30, 40 40, 50 10, 10 10))', 10));
st_astext
-------------
MULTIPOLYGON (((60 60, 70 30, 40 40, 60 60)), ((40 40, 50 10, 10 10, 40 40)))
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 too much becomes a triangle, medium an octagon,
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_triangle,
(ST_Simplify(geom, 100) is null) AS np100_geometrygoesaway
FROM (SELECT ST_Buffer('POINT(1 3)', 10,12) As geom) AS t;
np_before | np01_notbadcircle | np05_notquitecircle | np1_octagon | np10_triangle | np100_geometrygoesaway
-----------+-------------------+---------------------+-------------+---------------+------------------------
49 | 33 | 17 | 9 | 4 | t
Simplifying a set of lines. Lines may intersect after simplification.

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))',
40);
Simplifying a MultiPolygon. Polygonal results may be invalid.

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)))',
40);
ST_IsSimple, ST_SimplifyPreserveTopology, ST_SimplifyVW, ST_CoverageSimplify, Topology ST_Simplify
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.
Availability: 1.3.3
For the same example as ST_Simplify, ST_SimplifyPreserveTopology prevents oversimplification. The circle can at most become a square.
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_square,
ST_NPoints(ST_SimplifyPreserveTopology(geom, 100)) AS np100_stillsquare
FROM (SELECT ST_Buffer('POINT(1 3)', 10,12) AS geom) AS t;
np_before | np01_notbadcircle | np05_notquitecircle | np1_octagon | np10_square | np100_stillsquare
-----------+-------------------+---------------------+-------------+-------------+-------------------
49 | 33 | 17 | 9 | 5 | 5
Simplifying a set of lines, preserving topology of non-intersecting lines.

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))',
40);
Simplifying a MultiPolygon, preserving topology of shells and holes.

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)))',
40);
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
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))',
0.3);

Inner hull of a Polygon
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))',
0.3, false);

Outer hull simplification of a MultiPolygon, with segmentization
SELECT ST_SimplifyPolygonHull(
ST_Segmentize(ST_Letters('xt'), 2.0),
0.1);
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 the 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 function does not preserve boundaries shared between polygons. Use ST_CoverageSimplify if this is required. |
![]() | |
This function handles 3D and the third dimension will affect the result. |
Доступність: 2.2.0
A LineString is simplified with a minimum-area tolerance of 30.
SELECT ST_AsText(ST_SimplifyVW(geom,30)) simplified FROM (SELECT 'LINESTRING(5 2, 3 8, 6 20, 7 25, 10 10)'::geometry AS geom) AS t; simplified ------------------------------ LINESTRING(5 2,7 25,10 10)
Simplifying a line.

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)',
1600);
Simplifying a polygon.

SELECT ST_SimplifyVW(
'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)))',
40);
ST_SetEffectiveArea, ST_Simplify, ST_SimplifyPreserveTopology, ST_CoverageSimplify, Topology ST_Simplify
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);
Sets the effective area for each vertex, using the Visvalingam-Whyatt algorithm. The effective area is stored as the M-value of the vertex. If the optional "threshold" parameter is used, a simplified geometry will be returned, containing only vertices with an effective area greater than or equal to the threshold value.
This function can be used for server-side simplification when a threshold is specified. Another option is to use a threshold value of zero. In this case, the full geometry will be returned with effective areas as M-values, which can be used by the client to simplify very quickly.
Will actually do something only with (multi)lines and (multi)polygons but you can safely call it with any kind of geometry. Since simplification occurs on a object-by-object basis you can also feed a GeometryCollection to this function.
![]() | |
Note that returned geometry might lose its simplicity (see ST_IsSimple) |
![]() | |
Note topology may not be preserved and may result in invalid geometries. Use (see ST_SimplifyPreserveTopology) to preserve topology. |
![]() | |
The output geometry will lose all previous information in the M-values |
![]() | |
This function handles 3D and the third dimension will affect the effective area |
Доступність: 2.2.0
Calculating the effective area of a LineString. Because we use a threshold value of zero, all vertices in the input geometry are returned.
select ST_AsText(ST_SetEffectiveArea(geom)) all_pts, ST_AsText(ST_SetEffectiveArea(geom,30) ) thrshld_30
FROM (SELECT 'LINESTRING(5 2, 3 8, 6 20, 7 25, 10 10)'::geometry geom) As foo;
-result
all_pts | thrshld_30
-----------+-------------------+
LINESTRING M (5 2 3.40282346638529e+38,3 8 29,6 20 1.5,7 25 49.5,10 10 3.40282346638529e+38) | LINESTRING M (5 2 3.40282346638529e+38,7 25 49.5,10 10 3.40282346638529e+38)
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.
SELECT ST_AsText(
ST_TriangulatePolygon('POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))'));
st_astext
---------------------------------------------------------------------------
GEOMETRYCOLLECTION(POLYGON((0 0,0 1,1 1,0 0)),POLYGON((1 1,1 0,0 0,1 1)))
Triangulation of the letter P.
SELECT ST_AsText(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))'
));

Polygon Triangulation
SELECT ST_TriangulatePolygon(
'POLYGON (( 10 190, 10 70, 80 70, 80 130, 50 160, 120 160, 120 190, 10 190 ))'::geometry
);ST_AsText output
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)))
![]() Original polygon |
![]() Triangulated Polygon |
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.
Optional parameters:
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 tolerance of 30 units
SELECT ST_VoronoiLines(
'MULTIPOINT (50 30, 60 30, 100 100,10 150, 110 120)'::geometry,
30) AS geom;
ST_AsText output
MULTILINESTRING((135.555555555556 270,36.8181818181818 92.2727272727273),(36.8181818181818 92.2727272727273,-110 43.3333333333333),(230 -45.7142857142858,36.8181818181818 92.2727272727273))
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.
Optional parameters:
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 Voronoi diagram
SELECT ST_VoronoiPolygons(
'MULTIPOINT (50 30, 60 30, 100 100,10 150, 110 120)'::geometry
) AS geom;
ST_AsText output
GEOMETRYCOLLECTION(POLYGON((-110 43.3333333333333,-110 270,100.5 270,59.3478260869565 132.826086956522,36.8181818181818 92.2727272727273,-110 43.3333333333333)),
POLYGON((55 -90,-110 -90,-110 43.3333333333333,36.8181818181818 92.2727272727273,55 79.2857142857143,55 -90)),
POLYGON((230 47.5,230 -20.7142857142857,55 79.2857142857143,36.8181818181818 92.2727272727273,59.3478260869565 132.826086956522,230 47.5)),POLYGON((230 -20.7142857142857,230 -90,55 -90,55 79.2857142857143,230 -20.7142857142857)),
POLYGON((100.5 270,230 270,230 47.5,59.3478260869565 132.826086956522,100.5 270)))

Voronoi diagram, with tolerance of 30 units
SELECT ST_VoronoiPolygons(
'MULTIPOINT (50 30, 60 30, 100 100,10 150, 110 120)'::geometry,
30) AS geom;
ST_AsText output
GEOMETRYCOLLECTION(POLYGON((-110 43.3333333333333,-110 270,100.5 270,59.3478260869565 132.826086956522,36.8181818181818 92.2727272727273,-110 43.3333333333333)),
POLYGON((230 47.5,230 -45.7142857142858,36.8181818181818 92.2727272727273,59.3478260869565 132.826086956522,230 47.5)),POLYGON((230 -45.7142857142858,230 -90,-110 -90,-110 43.3333333333333,36.8181818181818 92.2727272727273,230 -45.7142857142858)),
POLYGON((100.5 270,230 270,230 47.5,59.3478260869565 132.826086956522,100.5 270)))
Ці функції працюють з наборами полігональної геометрії, що утворюють "неявні покриття". Щоб утворити дійсне покриття, полігони не повинні перекриватися, а вершини суміжних ребер повинні збігатися. Покриття швидко обробляються і можуть оброблятися за допомогою віконних функцій, які зберігають топологію покриття всередині розділу вікна при зміні ребер.
ST_CoverageInvalidEdges — Віконна функція, яка знаходить місця, де полігони не утворюють дійсного покриття.
geometry ST_CoverageInvalidEdges(geometry winset geom, float8 tolerance = 0);
Віконна функція, яка перевіряє, чи полігони у вікні утворюють дійсне полігональне покриття. Вона повертає лінійні індикатори, що показують розташування недійсних країв (якщо такі є) у кожному полігоні.
Набір дійсних полігонів є дійсним покриттям, якщо виконуються такі умови:
Неперекриваються - полігони не перекриваються (їх внутрішні частини не перетинаються)
Edge-Matched - вершини вздовж спільних ребер є ідентичними
Як віконна функція, для кожного вхідного полігону повертається значення. Для полігонів, які порушують одну або кілька умов дійсності, значенням, що повертається, є MULTILINESTRING, що містить проблемні краї. Полігони з дійсним покриттям повертають значення NULL. Неполігональні або порожні геометрії також дають значення NULL.
Умови дозволяють дійсному покриттю містити отвори (проміжки між полігонами), якщо сусідні полігони збігаються по краях. Однак дуже вузькі проміжки часто є небажаними. Якщо параметр tolerance задано з відстанню, відмінною від нуля, краї, що утворюють вужчі проміжки, також будуть повернуті як недійсні.
Полігони, що перевіряються на валідність покриття, також повинні бути валідними геометріями. Це можна перевірити за допомогою ST_IsValid.
Доступність: 3.4.0
Потрібна версія GEOS >= 3.12.0

Недійсні ребра, спричинені перекриттям і невідповідністю вершин
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_AsText(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
-- Test entire table for coverage validity
SELECT true = ALL (
SELECT ST_CoverageInvalidEdges(geom) OVER () IS NULL
FROM coverage
);
ST_IsValid, ST_CoverageUnion, ST_CoverageClean, ST_CoverageSimplify
ST_CoverageSimplify — Віконна функція, яка спрощує краї полігонального покриття.
geometry ST_CoverageSimplify(geometry winset geom, float8 tolerance, boolean simplifyBoundary = true);
Віконна функція, яка спрощує краї полігонів у полігональному покритті. Спрощення зберігає топологію покриття. Це означає, що спрощені вихідні полігони є сумісними вздовж спільних країв і все ще утворюють дійсне покриття.
Спрощення використовує варіант алгоритму Visvalingam–Whyatt. Параметр tolerance має одиниці виміру відстані і приблизно дорівнює квадратному кореню з площі трикутників, що спрощуються.
Щоб спростити тільки "внутрішні" краї покриття (ті, що є спільними для двох полігонів), встановіть параметр simplifyBoundary на значення false.
![]() | |
Якщо вхідні дані не є дійсним покриттям, у вихідних даних можуть з'явитися несподівані артефакти (наприклад, перетини меж або розділені межі, які здавалися спільними). Використовуйте ST_CoverageInvalidEdges, щоб визначити, чи є покриття дійсним. |
Доступність: 3.4.0
Потрібна версія GEOS >= 3.12.0
![]() Покриття вхідних даних
|
![]() Спрощене покриття
|
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_AsText(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))
ST_CoverageUnion — Обчислює об'єднання набору полігонів, що утворюють покриття, видаляючи спільні ребра.
geometry ST_CoverageUnion(geometry set geom);
Агрегуюча функція, яка об'єднує набір полігонів, що утворюють полігональне покриття. Результатом є полігональна геометрія, що покриває ту саму площу, що й покриття. Ця функція дає той самий результат, що й ST_Union, але використовує структуру покриття для значно швидшого обчислення об'єднання.
![]() | |
Якщо вхідні дані не є дійсним покриттям, у вихідних даних можуть з'явитися несподівані артефакти (наприклад, не об'єднані або перекриваються полігони). Використовуйте ST_CoverageInvalidEdges, щоб визначити, чи є покриття дійсним. |
Доступність: 3.4.0 - вимагає GEOS >= 3.8.0
![]() Покриття вхідних даних
|
![]() Результат об'єднання
|
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_AsText(ST_CoverageUnion(geom))
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)))
ST_CoverageClean — Обчислює чисте (збіжні краї, без перекриттів, без прогалин) полігональне покриття, задане нечистим вхідним даними.
geometry ST_CoverageClean(geometry winset geom, float8 gapMaximumWidth = 0, float8 snappingDistance = -1, text overlapMergeStrategy = 'MERGE_LONGEST_BORDER');
Віконна функція, яка змінює краї полігонального покриття, щоб жоден з полігонів не перекривався, невеликі проміжки були видалені, а всі спільні краї були абсолютно ідентичними. Результатом є чисте покриття, яке пройде тести валідації, такі як ST_CoverageInvalidEdges
Параметр gapMaximumWidth контролює очищення проміжків між полігонами. Проміжки, менші за цей допуск, будуть закриті.
Параметр snappingDistance контролює крок прив'язки вузлів, коли сусідні вершини прив'язуються одна до одної. За замовчуванням (-1) застосовується автоматична відстань прив'язки на основі аналізу вхідних даних. Встановіть значення 0,0, щоб вимкнути всі прив'язки.
Параметр overlapMergeStrategy контролює алгоритм, що використовується для визначення сусідніх полігонів, в які слід об'єднати перекриваються області.
MERGE_LONGEST_BORDER вибирає полігон з найдовшою спільною межею
MERGE_MAX_AREA вибирає полігон з максимальною площею
MERGE_MIN_AREA вибирає полігон з мінімальною площею
MERGE_MIN_INDEX вибирає полігон з найменшим індексом вхідних даних
Доступність: 3.6.0 - вимагає GEOS >= 3.14.0
-- Populate demo table
CREATE TABLE example AS SELECT * FROM (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)
) AS v(id, geom);
-- Prove it is a dirty coverage
SELECT ST_AsText(ST_CoverageInvalidEdges(geom) OVER ())
FROM example;
-- Clean the coverage
CREATE TABLE example_clean AS
SELECT id, ST_CoverageClean(geom) OVER () AS GEOM
FROM example;
-- Prove it is a clean coverage
SELECT ST_AsText(ST_CoverageInvalidEdges(geom) OVER ())
FROM example_clean;
These functions change the position and shape of geometries using affine transformations.
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
ST_Affine(geom, a, b, c, d, e, f, g, h, i, xoff, yoff, zoff)
represents the transformation matrix
/ a b c xoff \ | d e f yoff | | g h i zoff | \ 0 0 0 1 /
and the vertices are transformed as follows:
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
ST_Affine(geom, a, b, d, e, xoff, yoff)
represents the transformation matrix
/ 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:
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 ця функція виходила з ладу при використанні з геометріями, що містять КРИВІ. Ця проблема вирішена у версії 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();
SELECT ST_AsEWKT(ST_Affine(geom, cos(pi()), -sin(pi()), 0, sin(pi()), cos(pi()), 0, 0, 0, 1, 0, 0, 0)) As using_affine,
ST_AsEWKT(ST_Rotate(geom, pi())) As using_rotate
FROM (SELECT ST_GeomFromEWKT('LINESTRING(1 2 3, 1 4 3)') As geom) As foo;
using_affine | using_rotate
-----------------------------+-----------------------------
LINESTRING(-1 -2 3,-1 -4 3) | LINESTRING(-1 -2 3,-1 -4 3)
(1 row)
--Rotate a 3d line 180 degrees in both the x and z axis
SELECT ST_AsEWKT(ST_Affine(geom, cos(pi()), -sin(pi()), 0, sin(pi()), cos(pi()), -sin(pi()), 0, sin(pi()), cos(pi()), 0, 0, 0))
FROM (SELECT ST_GeomFromEWKT('LINESTRING(1 2 3, 1 4 3)') As geom) As foo;
st_asewkt
-------------------------------
LINESTRING(-1 -2 -3,-1 -4 -3)
(1 row)
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).
--Rotate 180 degrees
SELECT ST_AsEWKT(ST_Rotate('LINESTRING (50 160, 50 50, 100 50)', pi()));
st_asewkt
---------------------------------------
LINESTRING(-50 -160,-50 -50,-100 -50)
(1 row)
--Rotate 30 degrees counter-clockwise at x=50, y=160
SELECT ST_AsEWKT(ST_Rotate('LINESTRING (50 160, 50 50, 100 50)', pi()/6, 50, 160));
st_asewkt
---------------------------------------------------------------------------
LINESTRING(50 160,105 64.7372055837117,148.301270189222 89.7372055837117)
(1 row)
--Rotate 60 degrees clockwise from centroid
SELECT ST_AsEWKT(ST_Rotate(geom, -pi()/3, ST_Centroid(geom)))
FROM (SELECT 'LINESTRING (50 160, 50 50, 100 50)'::geometry AS geom) AS foo;
st_asewkt
--------------------------------------------------------------
LINESTRING(116.4225 130.6721,21.1597 75.6721,46.1597 32.3708)
(1 row)
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.
![]() | |
|
Покращено: 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).
--Rotate a line 90 degrees along x-axis
SELECT ST_AsEWKT(ST_RotateX(ST_GeomFromEWKT('LINESTRING(1 2 3, 1 1 1)'), pi()/2));
st_asewkt
---------------------------
LINESTRING(1 -3 2,1 -1 1)
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.
![]() | |
|
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).
--Rotate a line 90 degrees along y-axis
SELECT ST_AsEWKT(ST_RotateY(ST_GeomFromEWKT('LINESTRING(1 2 3, 1 1 1)'), pi()/2));
st_asewkt
---------------------------
LINESTRING(3 2 -1,1 1 -1)
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 |
![]() | |
|
Покращено: 2.0.0 додано підтримку багатогранних поверхонь, трикутників і TIN.
Availability: 1.1.2. Name changed from RotateZ to ST_RotateZ in 1.2.2
![]() | |
До версії 1.3.4 ця функція виходила з ладу при використанні з геометріями, що містять КРИВІ. Ця проблема вирішена у версії 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).
--Rotate a line 90 degrees along z-axis
SELECT ST_AsEWKT(ST_RotateZ(ST_GeomFromEWKT('LINESTRING(1 2 3, 1 1 1)'), pi()/2));
st_asewkt
---------------------------
LINESTRING(-2 1 3,-1 1 1)
--Rotate a curved circle around z-axis
SELECT ST_AsEWKT(ST_RotateZ(geom, pi()/2))
FROM (SELECT ST_LineToCurve(ST_Buffer(ST_GeomFromText('POINT(234 567)'), 3)) As geom) As foo;
st_asewkt
----------------------------------------------------------------------------------------------------------------------------
CURVEPOLYGON(CIRCULARSTRING(-567 237,-564.87867965644 236.12132034356,-564 234,-569.12132034356 231.87867965644,-567 237))
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 ця функція виходила з ладу при використанні з геометріями, що містять КРИВІ. Ця проблема вирішена у версії 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.
--Version 1: scale X, Y, Z
SELECT ST_AsEWKT(ST_Scale(ST_GeomFromEWKT('LINESTRING(1 2 3, 1 1 1)'), 0.5, 0.75, 0.8));
st_asewkt
--------------------------------------
LINESTRING(0.5 1.5 2.4,0.5 0.75 0.8)
--Version 2: Scale X Y
SELECT ST_AsEWKT(ST_Scale(ST_GeomFromEWKT('LINESTRING(1 2 3, 1 1 1)'), 0.5, 0.75));
st_asewkt
----------------------------------
LINESTRING(0.5 1.5 3,0.5 0.75 1)
--Version 3: Scale X Y Z M
SELECT ST_AsEWKT(ST_Scale(ST_GeomFromEWKT('LINESTRING(1 2 3 4, 1 1 1 1)'),
ST_MakePoint(0.5, 0.75, 2, -1)));
st_asewkt
----------------------------------------
LINESTRING(0.5 1.5 6 -4,0.5 0.75 2 -1)
--Version 4: Scale X Y using false origin
SELECT ST_AsText(ST_Scale('LINESTRING(1 1, 2 2)', 'POINT(2 2)', 'POINT(1 1)'::geometry));
st_astext
---------------------
LINESTRING(1 1,3 3)
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.
![]() | |
До версії 1.3.4 ця функція виходила з ладу при використанні з геометріями, що містять КРИВІ. Ця проблема вирішена у версії 1.3.4+ |
Доступність: 1.2.2
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves.
Move a point 1 degree longitude
SELECT ST_AsText(ST_Translate(ST_GeomFromText('POINT(-71.01 42.37)',4326),1,0)) As wgs_transgeomtxt;
wgs_transgeomtxt
---------------------
POINT(-70.01 42.37)
Move a linestring 1 degree longitude and 1/2 degree latitude
SELECT ST_AsText(ST_Translate(ST_GeomFromText('LINESTRING(-71.01 42.37,-71.11 42.38)',4326),1,0.5)) As wgs_transgeomtxt;
wgs_transgeomtxt
---------------------------------------
LINESTRING(-70.01 42.87,-70.11 42.88)
Move a 3d point
SELECT ST_AsEWKT(ST_Translate(CAST('POINT(0 0 0)' As geometry), 5, 12,3));
st_asewkt
---------
POINT(5 12 3)
Move a curve and a point
SELECT ST_AsText(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));
st_astext
------------------------------------------------------------------------------------------------------------
GEOMETRYCOLLECTION(CURVEPOLYGON(CIRCULARSTRING(5 5,4.12 2.878,2 2,-0.121 7.1213,7 9,9 11,5 5)),POINT(2 5))
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.
![]() | |
|
![]() | |
До версії 1.3.4 ця функція виходила з ладу при використанні з геометріями, що містять КРИВІ. Ця проблема вирішена у версії 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.
SELECT ST_AsEWKT(ST_TransScale(ST_GeomFromEWKT('LINESTRING(1 2 3, 1 1 1)'), 0.5, 1, 1, 2));
st_asewkt
-----------------------------
LINESTRING(1.5 6 3,1.5 4 1)
--Buffer a point to get an approximation of a circle, convert to curve and then translate 1,2 and scale it 3,4
SELECT ST_AsText(ST_Transscale(ST_LineToCurve(ST_Buffer('POINT(234 567)', 3)),1,2,3,4));
st_astext
------------------------------------------------------------------------------------------------------------------------------
CURVEPOLYGON(CIRCULARSTRING(714 2276,711.363961030679 2267.51471862576,705 2264,698.636038969321 2284.48528137424,714 2276))
Ці функції реалізують алгоритми кластеризації для наборів геометрій.
ST_ClusterDBSCAN — Функція вікна, яка повертає ідентифікатор кластера для кожної вхідної геометрії за допомогою алгоритму DBSCAN.
integer ST_ClusterDBSCAN(geometry winset geom, float8 eps, integer minpoints);
Віконна функція, яка повертає номер кластера для кожної вхідної геометрії, використовуючи 2D алгоритм просторового кластеризації додатків на основі щільності з шумом (DBSCAN). На відміну від ST_ClusterKMeans, вона не вимагає вказання кількості кластерів, а замість цього використовує бажані параметри відстань (eps) та щільність (minpoints) для визначення кожного кластера.
Геометрія входу додається до кластера, якщо вона:
Зверніть увагу, що геометрії меж можуть знаходитися на відстані eps від геометрій ядра в більш ніж одному кластері. Будь-яке призначення буде правильним, тому геометрія межі буде довільно призначена одному з доступних кластерів. У цій ситуації можливе створення правильного кластера з меншою кількістю геометрій, ніж minpoints. Щоб забезпечити детермінований прив'язку геометрій меж (так, щоб повторні виклики ST_ClusterDBSCAN давали однакові результати), використовуйте оператор ORDER BY у визначенні вікна. Неоднозначні прив'язки кластерів можуть відрізнятися від інших реалізацій DBSCAN.
![]() | |
Геометріям, які не відповідають критеріям для приєднання до будь-якого кластера, присвоюється номер кластера NULL. |
Доступність: 2.3.0
This method supports Circular Strings and Curves.
Групування полігонів на відстані 50 метрів один від одного, при цьому в кожній групі має бути не менше 2 полігонів.
![]() Кластери в межах 50 метрів з щонайменше 2 елементами в кожному кластері. Одиночні елементи мають NULL для cid
SELECT name, ST_ClusterDBSCAN(geom, eps =
> 50, minpoints =
> 2) over () AS cid
FROM boston_polys
WHERE name
> '' AND building
> ''
AND ST_DWithin(geom,
ST_Transform(
ST_GeomFromText('POINT(-71.04054 42.35141)', 4326), 26986),
500);
|
name | bucket
-------------------------------------+--------
Manulife Tower | 0
Park Lane Seaport I | 0
Park Lane Seaport II | 0
Renaissance Boston Waterfront Hotel | 0
Seaport Boston Hotel | 0
Seaport Hotel & World Trade Center | 0
Waterside Place | 0
World Trade Center East | 0
100 Northern Avenue | 1
100 Pier 4 | 1
The Institute of Contemporary Art | 1
101 Seaport | 2
District Hall | 2
One Marina Park Drive | 2
Twenty Two Liberty | 2
Vertex | 2
Vertex | 2
Watermark Seaport | 2
Blue Hills Bank Pavilion | NULL
World Trade Center West | NULL
(20 rows)
|
Приклад об'єднання ділянок з однаковим номером кластера в геометричні колекції.
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 — Агрегуюча функція, яка групує вхідні геометрії у зв'язані набори.
geometry[] ST_ClusterIntersecting(geometry set g);
Агрегатна функція, яка повертає масив GeometryCollections, розділяючи вхідні геометрії на з'єднані кластери, які не перетинаються. Кожна геометрія в кластері перетинається принаймні з однією іншою геометрією в кластері і не перетинається з жодною геометрією в інших кластерах.
Доступність: 2.2.0
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 ST_AsText(unnest(ST_ClusterIntersecting(geom))) FROM testdata;
--result
st_astext
---------
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))
ST_ClusterIntersectingWin — Віконна функція, яка повертає ідентифікатор кластера для кожної вхідної геометрії, групуючи вхідні геометрії у пов'язані набори.
integer ST_ClusterIntersectingWin(geometry winset geom);
Віконна функція, яка будує з'єднані кластери геометрій, що перетинаються. Можна пройти всі геометрії в кластері, не виходячи з нього. Повертається номер кластера, до якого належить аргумент геометрії, або null для нульових вхідних даних.
Доступність: 3.4.0
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,
ST_AsText(geom),
ST_ClusterIntersectingWin(geom) 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
ST_ClusterKMeans — Віконна функція, яка повертає ідентифікатор кластера для кожної вхідної геометрії за допомогою алгоритму K-means.
integer ST_ClusterKMeans( geometry winset geom , integer k , float8 max_radius );
Повертає K-means номер кластера для кожної вхідної геометрії. Відстань, що використовується для кластеризації, - це відстань між центроїдами для 2D-геометрій і відстань між центрами обмежувальних рамок для 3D-геометрій. Для вхідних даних POINT координата M буде розглядатися як вага вхідних даних і повинна бути більшою за 0.
max_radius, якщо встановлено, змусить ST_ClusterKMeans генерувати більше кластерів, ніж k, гарантуючи, що жоден кластер у вихідних даних не матиме радіус, більший за max_radius. Це корисно для аналізу доступності.
Покращено: 3.2.0 Підтримка max_radius
Покращено: 3.1.0 Підтримка 3D-геометрії та ваги
Доступність: 2.3.0
Створити фіктивний набір посилок для прикладів:
CREATE TABLE parcels AS
SELECT lpad((row_number() over())::text,3,'0') As parcel_id, geom,
('{residential, commercial}'::text[])[1 + mod(row_number()OVER(),2)] As type
FROM
ST_Subdivide(ST_Buffer('SRID=3857;LINESTRING(40 100, 98 100, 100 150, 60 90)'::geometry,
40, 'endcap=square'),12) As geom;

Пакунки, позначені кольором за номером кластера (cid)
SELECT ST_ClusterKMeans(geom, 3) OVER() AS cid, parcel_id, geom
FROM parcels;
cid | parcel_id | geom -----+-----------+--------------- 0 | 001 | 0103000000... 0 | 002 | 0103000000... 1 | 003 | 0103000000... 0 | 004 | 0103000000... 1 | 005 | 0103000000... 2 | 006 | 0103000000... 2 | 007 | 0103000000...
Розподіл кластерів ділянок за типом:
SELECT ST_ClusterKMeans(geom, 3) over (PARTITION BY type) AS cid, parcel_id, type
FROM parcels;cid | parcel_id | type -----+-----------+------------- 1 | 005 | commercial 1 | 003 | commercial 2 | 007 | commercial 0 | 001 | commercial 1 | 004 | residential 0 | 002 | residential 2 | 006 | residential
Приклад: Кластеризація попередньо агрегованого набору даних про населення планетарного масштабу за допомогою 3D-кластеризації та зважування. Визначте щонайменше 20 регіонів на основі даних про населення Kontur, які не простягаються більше ніж на 3000 км від їхнього центру:
create table kontur_population_3000km_clusters as
select
geom,
ST_ClusterKMeans(
ST_Force4D(
ST_Transform(ST_Force3D(geom), 4978), -- cluster in 3D XYZ CRS
mvalue => population -- set clustering to be weighed by population
),
20, -- aim to generate at least 20 clusters
max_radius => 3000000 -- but generate more to make each under 3000 km radius
) over () as cid
from
kontur_population;

Населення світу, скупчене вище зазначених показників, утворює 46 кластерів. Кластери зосереджені в густонаселених регіонах (Нью-Йорк, Москва). Гренландія є одним кластером. Існують острівні кластери, що простягаються через антимеридіан. Краї кластерів повторюють кривизну Землі.
ST_ClusterWithin — Агрегатна функція, яка групує геометрії за відстанню розділення.
geometry[] ST_ClusterWithin(geometry set g, float8 distance);
Агрегатна функція, яка повертає масив GeometryCollections, де кожна колекція є кластером, що містить деякі вхідні геометрії. Кластеризація розділяє вхідні геометрії на набори, в яких кожна геометрія знаходиться в межах заданої відстані від принаймні однієї іншої геометрії в тому самому кластері. Відстані є декартовими відстанями в одиницях SRID.
ST_ClusterWithin еквівалентний виконанню ST_ClusterDBSCAN з minpoints => 0.
Доступність: 2.2.0
This method supports Circular Strings and Curves.
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 ST_AsText(unnest(ST_ClusterWithin(geom, 1.4))) FROM testdata;
--result
st_astext
---------
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))
ST_ClusterWithinWin — Віконна функція, яка повертає ідентифікатор кластера для кожної вхідної геометрії, кластеризуючи за відстанню розділення.
integer ST_ClusterWithinWin(geometry winset geom, float8 distance);
Віконна функція, яка повертає номер кластера для кожної вхідної геометрії. Кластеризація розділяє геометрії на набори, в яких кожна геометрія знаходиться в межах заданої відстані distance від принаймні однієї іншої геометрії в тому самому кластері. Відстані є декартовими відстанями в одиницях SRID.
ST_ClusterWithinWin еквівалентно виконанню ST_ClusterDBSCAN з minpoints => 0.
Доступність: 3.4.0
This method supports Circular Strings and Curves.
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,
ST_AsText(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
Ці функції створюють або оперують обмежувальними рамками. Вони також можуть надавати та приймати значення геометрії, використовуючи автоматичні або явні приведення типів.
Див. також Section 13.7, “Функції PostGIS Box”.
Box2D — Повертає BOX2D, що представляє 2D розмір геометрії.
box2d Box2D(geometry geom);
Повертає box2d, що представляє 2D розмір геометрії.
Покращено: 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).
SELECT Box2D(ST_GeomFromText('LINESTRING(1 2, 3 4, 5 6)'));
box2d
---------
BOX(1 2,5 6)
SELECT Box2D(ST_GeomFromText('CIRCULARSTRING(220268 150415,220227 150505,220227 150406)'));
box2d
--------
BOX(220186.984375 150406,220288.25 150506.140625)
Box3D — Повертає BOX3D, що представляє 3D-розмір геометрії.
box3d Box3D(geometry geom);
Повертає box3d, що представляє 3D-розмір геометрії.
Покращено: 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.
SELECT Box3D(ST_GeomFromEWKT('LINESTRING(1 2 3, 3 4 5, 5 6 5)'));
Box3d
---------
BOX3D(1 2 3,5 6 5)
SELECT Box3D(ST_GeomFromEWKT('CIRCULARSTRING(220268 150415 1,220227 150505 1,220227 150406 1)'));
Box3d
--------
BOX3D(220227 150406 1,220268 150415 1)
ST_EstimatedExtent — Повертає приблизний діапазон просторової таблиці.
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);
Повертає приблизний діапазон просторової таблиці у вигляді box2d. Якщо не вказано, використовується поточна схема. Приблизний діапазон береться зі статистики стовпця геометрії. Зазвичай це набагато швидше, ніж обчислення точного діапазону таблиці за допомогою ST_Extent або ST_3DExtent.
За замовчуванням також використовуються статистичні дані, зібрані з дочірніх таблиць (таблиць з INHERITS), якщо вони доступні. Якщо parent_only встановлено на TRUE, використовуються тільки статистичні дані для заданої таблиці, а дочірні таблиці ігноруються.
Для PostgreSQL >= 8.0.0 статистика збирається за допомогою VACUUM ANALYZE, а результат буде приблизно 95% від фактичного. Для PostgreSQL <8.0.0 статистика збирається за допомогою update_geometry_stats(), а результат є точним.
![]() | |
За відсутності статистики (порожня таблиця або не викликано ANALYZE) ця функція повертає NULL. До версії 1.5.4 замість цього виникало виключення. |
![]() | |
Для імен таблиць та/або просторів імен, що містять спеціальні символи та лапки, може знадобитися спеціальна обробка. Користувач зазначає: "Для схем і таблиць використовуйте правила екранування ідентифікаторів, щоб створити рядок у подвійних лапках, а потім видаліть перший і останній символи подвійних лапок. Для стовпця геометрії передайте як є" |
Доступність: 1.0.0
Змінено: 2.1.0. До версії 2.0.x це називалося ST_Estimated_Extent.
This method supports Circular Strings and Curves.
SELECT ST_EstimatedExtent('ny', 'edges', 'geom');
--result--
BOX(-8877653 4912316,-8010225.5 5589284)
SELECT ST_EstimatedExtent('feature_poly', 'geom');
--result--
BOX(-124.659652709961 24.6830825805664,-67.7798080444336 49.0012092590332)
ST_Expand — Повертає обмежувальну рамку, розширену з іншої обмежувальної рамки або геометрії.
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);
Повертає обмежувальну рамку, розширену від обмежувальної рамки вхідних даних, або шляхом вказання єдиної відстані, на яку слід розширити рамку по обох осях, або шляхом вказання відстані розширення для кожної осі. Використовує подвійну точність. Може використовуватися для запитів відстані або для додавання фільтра обмежувальної рамки до запиту, щоб скористатися перевагами просторового індексу.
На додаток до версії ST_Expand, яка приймає та повертає геометрію, надаються варіанти, які приймають та повертають типи даних box2d та box3d.
Відстані вказані в одиницях просторової системи координат вхідних даних.
ST_Expand схожий на ST_Buffer, за винятком того, що під час буферизації геометрія розширюється в усіх напрямках, а ST_Expand розширює обмежувальну рамку вздовж кожної осі.
![]() | |
До версії 1.3 ST_Expand використовувався разом з ST_Distance для виконання індексованих запитів на відстань. Наприклад, |
Доступність: 1.5.0 поведінка змінена на виведення координат подвійної точності замість float4.
Покращено: 2.0.0 додано підтримку багатогранних поверхонь, трикутників і TIN.
Покращено: додано підтримку версії 2.3.0 для розширення поля на різну величину в різних вимірах.
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
![]() | |
У наведених нижче прикладах використовується карта США National Atlas Equal Area (SRID=2163), яка є метровою проекцією |
--10 meter expanded box around bbox of a linestring
SELECT CAST(ST_Expand(ST_GeomFromText('LINESTRING(2312980 110676,2312923 110701,2312892 110714)', 2163),10) As box2d);
st_expand
------------------------------------
BOX(2312882 110666,2312990 110724)
--10 meter expanded 3D box of a 3D box
SELECT ST_Expand(CAST('BOX3D(778783 2951741 1,794875 2970042.61545891 10)' As box3d),10)
st_expand
-----------------------------------------------------
BOX3D(778773 2951731 -9,794885 2970052.61545891 20)
--10 meter geometry astext rep of a expand box around a point geometry
SELECT ST_AsEWKT(ST_Expand(ST_GeomFromEWKT('SRID=2163;POINT(2312980 110676)'),10));
st_asewkt
-------------------------------------------------------------------------------------------------
SRID=2163;POLYGON((2312970 110666,2312970 110686,2312990 110686,2312990 110666,2312970 110666))
ST_Extent — Агрегатна функція, яка повертає обмежувальну рамку геометрій.
box2d ST_Extent(geometry set geomfield);
Агрегатна функція, яка повертає обмежувальну рамку box2d, що обмежує набір геометрій.
Координати обмежувальної рамки знаходяться в просторовій системі координат вхідних геометрій.
ST_Extent за своєю концепцією схожий на SDO_AGGR_MBR Oracle Spatial/Locator.
![]() | |
ST_Extent повертає прямокутники тільки з координатами X і Y, навіть для 3D-геометрій. Щоб повернути координати XYZ, використовуйте ST_3DExtent. |
![]() | |
Повернене значення |
Покращено: 2.0.0 додано підтримку багатогранних поверхонь, трикутників і TIN.
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
![]() | |
У наведених нижче прикладах використовується система координат штату Массачусетс (SRID=2249) |
SELECT ST_Extent(geom) as bextent FROM sometable;
st_bextent
------------------------------------
BOX(739651.875 2908247.25,794875.8125 2970042.75)
--Return extent of each category of geometries
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
--Force back into a geometry
-- and render the extended text representation of that geometry
SELECT ST_SetSRID(ST_Extent(geom),2249) as bextent FROM sometable;
bextent
--------------------------------------------------------------------------------
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 — Агрегатна функція, яка повертає 3D обмежувальну рамку геометрій.
box3d ST_3DExtent(geometry set geomfield);
Агрегатна функція, яка повертає обмежувальну рамку box3d(включає координату Z), що обмежує набір геометрій.
Координати обмежувальної рамки знаходяться в просторовій системі координат вхідних геометрій.
![]() | |
Повернене значення |
Покращено: 2.0.0 додано підтримку багатогранних поверхонь, трикутників і TIN.
Змінено: 2.0.0 У попередніх версіях це називалося 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).
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;
b3extent
--------------------
BOX3D(1 1 0,3 2 2)
--Get the extent of various elevated circular strings
SELECT ST_3DExtent(foo.geom) As b3extent
FROM (SELECT ST_Translate(ST_Force_3DZ(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;
b3extent
--------------------
BOX3D(1 0 0,4 2 2)
ST_MakeBox2D — Створює BOX2D, визначений двома 2D точковими геометріями.
box2d ST_MakeBox2D(geometry pointLowLeft, geometry pointUpRight);
Створює box2d, визначений двома геометріями Point. Це корисно для виконання запитів діапазону.
--Return all features that fall reside 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)
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 — Створює BOX3D, визначений двома геометріями 3D-точок.
box3d ST_3DMakeBox(geometry point3DLowLeftBottom, geometry point3DUpRightTop);
Створює box3d, визначений двома геометріями 3D Point.
Ця функція підтримує 3D і не знижує z-індекс.
Змінено: 2.0.0 У попередніх версіях це називалося ST_MakeBox3D
SELECT ST_3DMakeBox(ST_MakePoint(-989502.1875, 528439.5625, 10),
ST_MakePoint(-987121.375 ,529933.1875, 10)) As abb3d
--bb3d--
--------
BOX3D(-989502.1875 528439.5625 10,-987121.375 529933.1875 10)
ST_XMax — Повертає X максимум 2D або 3D обмежувальної рамки або геометрії.
float ST_XMax(box3d aGeomorBox2DorBox3D);
Повертає X максимум 2D або 3D обмежувальної рамки або геометрії.
![]() | |
Хоча ця функція визначена тільки для box3d, вона також працює для значень box2d і geometry завдяки автоматичному перетворенню. Однак вона не приймає текстове представлення geometry або box2d, оскільки вони не перетворюються автоматично. |
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves.
SELECT ST_XMax('BOX3D(1 2 3, 4 5 6)');
st_xmax
-------
4
SELECT ST_XMax(ST_GeomFromText('LINESTRING(1 3 4, 5 6 7)'));
st_xmax
-------
5
SELECT ST_XMax(CAST('BOX(-3 2, 3 4)' As box2d));
st_xmax
-------
3
--Observe THIS DOES NOT WORK because it will try to auto-cast the string representation to a BOX3D
SELECT ST_XMax('LINESTRING(1 3, 5 6)');
--ERROR: BOX3D parser - doesn't start with BOX3D(
SELECT ST_XMax(ST_GeomFromEWKT('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)'));
st_xmax
--------
220288.248780547
ST_XMin — Повертає мінімальне значення X для 2D або 3D обмежувальної рамки або геометрії.
float ST_XMin(box3d aGeomorBox2DorBox3D);
Повертає мінімальне значення X для 2D або 3D обмежувальної рамки або геометрії.
![]() | |
Хоча ця функція визначена тільки для box3d, вона також працює для значень box2d і geometry завдяки автоматичному перетворенню. Однак вона не приймає текстове представлення geometry або box2d, оскільки вони не перетворюються автоматично. |
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves.
SELECT ST_XMin('BOX3D(1 2 3, 4 5 6)');
st_xmin
-------
1
SELECT ST_XMin(ST_GeomFromText('LINESTRING(1 3 4, 5 6 7)'));
st_xmin
-------
1
SELECT ST_XMin(CAST('BOX(-3 2, 3 4)' As box2d));
st_xmin
-------
-3
--Observe THIS DOES NOT WORK because it will try to auto-cast the string representation to a BOX3D
SELECT ST_XMin('LINESTRING(1 3, 5 6)');
--ERROR: BOX3D parser - doesn't start with BOX3D(
SELECT ST_XMin(ST_GeomFromEWKT('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)'));
st_xmin
--------
220186.995121892
ST_YMax — Повертає максимальне значення Y 2D або 3D обмежувальної рамки або геометрії.
float ST_YMax(box3d aGeomorBox2DorBox3D);
Повертає максимальне значення Y 2D або 3D обмежувальної рамки або геометрії.
![]() | |
Хоча ця функція визначена тільки для box3d, вона також працює для значень box2d і geometry завдяки автоматичному перетворенню. Однак вона не приймає текстове представлення geometry або box2d, оскільки вони не перетворюються автоматично. |
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves.
SELECT ST_YMax('BOX3D(1 2 3, 4 5 6)');
st_ymax
-------
5
SELECT ST_YMax(ST_GeomFromText('LINESTRING(1 3 4, 5 6 7)'));
st_ymax
-------
6
SELECT ST_YMax(CAST('BOX(-3 2, 3 4)' As box2d));
st_ymax
-------
4
--Observe THIS DOES NOT WORK because it will try to auto-cast the string representation to a BOX3D
SELECT ST_YMax('LINESTRING(1 3, 5 6)');
--ERROR: BOX3D parser - doesn't start with BOX3D(
SELECT ST_YMax(ST_GeomFromEWKT('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)'));
st_ymax
--------
150506.126829327
ST_YMin — Повертає мінімальне значення Y для 2D або 3D обмежувальної рамки або геометрії.
float ST_YMin(box3d aGeomorBox2DorBox3D);
Повертає мінімальне значення Y 2D або 3D обмежувальної рамки або геометрії.
![]() | |
Хоча ця функція визначена тільки для box3d, вона також працює для значень box2d і geometry завдяки автоматичному перетворенню. Однак вона не приймає текстове представлення geometry або box2d, оскільки вони не перетворюються автоматично. |
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves.
SELECT ST_YMin('BOX3D(1 2 3, 4 5 6)');
st_ymin
-------
2
SELECT ST_YMin(ST_GeomFromText('LINESTRING(1 3 4, 5 6 7)'));
st_ymin
-------
3
SELECT ST_YMin(CAST('BOX(-3 2, 3 4)' As box2d));
st_ymin
-------
2
--Observe THIS DOES NOT WORK because it will try to auto-cast the string representation to a BOX3D
SELECT ST_YMin('LINESTRING(1 3, 5 6)');
--ERROR: BOX3D parser - doesn't start with BOX3D(
SELECT ST_YMin(ST_GeomFromEWKT('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)'));
st_ymin
--------
150406
ST_ZMax — Повертає максимальне значення Z для 2D або 3D обмежувальної рамки або геометрії.
float ST_ZMax(box3d aGeomorBox2DorBox3D);
Повертає максимальне значення Z для 2D або 3D обмежувальної рамки або геометрії..
![]() | |
Хоча ця функція визначена тільки для box3d, вона також працює для значень box2d і geometry завдяки автоматичному перетворенню. Однак вона не приймає текстове представлення geometry або box2d, оскільки вони не перетворюються автоматично. |
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves.
SELECT ST_ZMax('BOX3D(1 2 3, 4 5 6)');
st_zmax
-------
6
SELECT ST_ZMax(ST_GeomFromEWKT('LINESTRING(1 3 4, 5 6 7)'));
st_zmax
-------
7
SELECT ST_ZMax('BOX3D(-3 2 1, 3 4 1)' );
st_zmax
-------
1
--Observe THIS DOES NOT WORK because it will try to auto-cast the string representation to a BOX3D
SELECT ST_ZMax('LINESTRING(1 3 4, 5 6 7)');
--ERROR: BOX3D parser - doesn't start with BOX3D(
SELECT ST_ZMax(ST_GeomFromEWKT('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)'));
st_zmax
--------
3
ST_ZMin — Повертає мінімальне значення Z для 2D або 3D обмежувальної рамки або геометрії.
float ST_ZMin(box3d aGeomorBox2DorBox3D);
Повертає мінімальне значення Z 2D- або 3D-обмежувальної рамки або геометрії.
![]() | |
Хоча ця функція визначена тільки для box3d, вона також працює для значень box2d і geometry завдяки автоматичному перетворенню. Однак вона не приймає текстове представлення geometry або box2d, оскільки вони не перетворюються автоматично. |
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves.
SELECT ST_ZMin('BOX3D(1 2 3, 4 5 6)');
st_zmin
-------
3
SELECT ST_ZMin(ST_GeomFromEWKT('LINESTRING(1 3 4, 5 6 7)'));
st_zmin
-------
4
SELECT ST_ZMin('BOX3D(-3 2 1, 3 4 1)' );
st_zmin
-------
1
--Observe THIS DOES NOT WORK because it will try to auto-cast the string representation to a BOX3D
SELECT ST_ZMin('LINESTRING(1 3 4, 5 6 7)');
--ERROR: BOX3D parser - doesn't start with BOX3D(
SELECT ST_ZMin(ST_GeomFromEWKT('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)'));
st_zmin
--------
1
ST_GeomFromEWKT, ST_GeomFromText, ST_XMin, ST_XMax, ST_YMax, ST_YMin, ST_ZMax
ST_LineInterpolatePoint — Повертає точку, інтерпольовану вздовж лінії в дробовому місці.
geometry ST_LineInterpolatePoint(geometry a_linestring, float8 a_fraction);
geography ST_LineInterpolatePoint(geography a_linestring, float8 a_fraction, boolean use_spheroid = true);
Повертає точку, інтерпольовану вздовж лінії в дробовому місці. Перший аргумент повинен бути LINESTRING. Другий аргумент — це число з плаваючою комою від 0 до 1, що позначає дрібну частину довжини лінії, де має бути розташована точка. Значення Z і M інтерполюються, якщо вони є.
Див. ST_LineLocatePointдля обчислення найближчого до точки місця розташування лінії.
![]() | |
ST_3DLineInterpolatePoint обчислює точки в 3D і інтерполює тільки значення M. |
![]() | |
Починаючи з версії 1.1.1, ця функція також інтерполює значення M і Z (якщо вони присутні), тоді як у попередніх версіях вони встановлювалися на 0,0. |
Доступність: 0.8.2, підтримка Z і M додана в 1.1.1
Змінено: 2.1.0. До версії 2.0.x ця функція називалася ST_Line_Interpolate_Point.
This function supports 3d and will not drop the z-index.

LineString з інтерпольованою точкою в положенні 20% (0,20)
-- The point 20% along a line
SELECT ST_AsEWKT( ST_LineInterpolatePoint(
'LINESTRING(25 50, 100 125, 150 190)',
0.2 ));
----------------
POINT(51.5974135047432 76.5974135047432)
Середина 3D лінії:
SELECT ST_AsEWKT( ST_LineInterpolatePoint('
LINESTRING(1 2 3, 4 5 6, 6 7 8)',
0.5 ));
--------------------
POINT(3.5 4.5 5.5)
Найближча точка на прямій до точки:
SELECT ST_AsText( ST_LineInterpolatePoint( line.geom,
ST_LineLocatePoint( line.geom, 'POINT(4 3)')))
FROM (SELECT ST_GeomFromText('LINESTRING(1 2, 4 5, 6 7)') As geom) AS line;
------------
POINT(3 4)
ST_3DLineInterpolatePoint — Повертає точку, інтерпольовану вздовж 3D-лінії в дробовому місці.
geometry ST_3DLineInterpolatePoint(geometry a_linestring, float8 a_fraction);
Повертає точку, інтерпольовану вздовж 3D-лінії в дробовому місці. Перший аргумент повинен бути LINESTRING. Другий аргумент — це число з плаваючою комою від 0 до 1, що позначає місце розташування точки як дробу довжини лінії. Якщо значення M присутнє, воно інтерполюється.
![]() | |
ST_LineInterpolatePoint обчислює точки в 2D, а потім інтерполює значення для Z і M, тоді як ця функція обчислює точки в 3D і інтерполює тільки значення M. |
Доступність: 3.0.0
This function supports 3d and will not drop the z-index.
Точка повернення 20% вздовж 3D лінії
SELECT ST_AsText(
ST_3DLineInterpolatePoint('LINESTRING(25 50 70, 100 125 90, 150 190 200)',
0.20));
st_asetext
----------------
POINT Z (59.0675892910822 84.0675892910822 79.0846904776219)
ST_LineInterpolatePoints — Повертає точки, інтерпольовані вздовж лінії з дробовим інтервалом.
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);
Повертає одну або кілька точок, інтерпольованих вздовж лінії з дробовим інтервалом. Перший аргумент повинен бути LINESTRING. Другий аргумент — це float8 від 0 до 1, що представляє відстань між точками як дріб довжини лінії. Якщо третій аргумент має значення false, буде побудовано не більше однієї точки (що еквівалентно ST_LineInterpolatePoint)
Якщо результат має нуль або один пункт, він повертається як POINT. Якщо він має два або більше пунктів, він повертається як MULTIPOINT.
Доступність: 2.5.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.

Лінія String з точками, інтерпольованими кожні 20%
--Return points each 20% along a 2D line
SELECT ST_AsText(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))
ST_LineLocatePoint — Повертає дробове значення відстані найближчої точки на лінії до заданої точки.
float8 ST_LineLocatePoint(geometry a_linestring, geometry a_point);
float8 ST_LineLocatePoint(geography a_linestring, geography a_point, boolean use_spheroid = true);
Повертає число з плаваючою комою в діапазоні від 0 до 1, що представляє розташування найближчої точки на LineString до заданої точки Point, як частку довжини 2d line.
Ви можете використовувати повернуте місце розташування для вилучення точки (ST_LineInterpolatePoint) або підрядка (ST_LineSubstring).
Це корисно для наближення кількості адрес
Доступність: 1.1.0
Змінено: 2.1.0. До версії 2.0.x це називалося ST_Line_Locate_Point.
--Rough approximation of finding the street number of a point along the street
--Note the whole foo thing is just to generate dummy data that looks
--like house centroids and street
--We use ST_DWithin to exclude
--houses too far away from the street to be considered on the street
SELECT ST_AsText(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 ST_GeomFromText('LINESTRING(1 2, 3 4)') 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
--find closest point on a line to a point or other geometry
SELECT ST_AsText(ST_LineInterpolatePoint(foo.the_line, ST_LineLocatePoint(foo.the_line, ST_GeomFromText('POINT(4 3)'))))
FROM (SELECT ST_GeomFromText('LINESTRING(1 2, 4 5, 6 7)') As the_line) As foo;
st_astext
----------------
POINT(3 4)
ST_DWithin, ST_Length2D, ST_LineInterpolatePoint, ST_LineSubstring
ST_LineSubstring — Повертає частину лінії між двома дробовими позиціями.
geometry ST_LineSubstring(geometry a_linestring, float8 startfraction, float8 endfraction);
geography ST_LineSubstring(geography a_linestring, float8 startfraction, float8 endfraction);
Обчислює лінію, яка є ділянкою вхідної лінії, що починається і закінчується в заданих дробових точках. Перший аргумент повинен бути LINESTRING. Другий і третій аргументи є значеннями в діапазоні [0, 1], що представляють початкову і кінцеву точки як дроби довжини лінії. Значення Z і M інтерполюються для доданих кінцевих точок, якщо вони є.
Якщо startfraction та endfraction мають однакове значення, це еквівалентно ST_LineInterpolatePoint.
![]() | |
Це працює тільки з LINESTRING. Щоб використовувати на суміжних MULTILINESTRING, спочатку об'єднайте їх за допомогою ST_LineMerge. |
![]() | |
Починаючи з версії 1.1.1, ця функція інтерполює значення M і Z. У попередніх версіях Z і M встановлювалися на невизначені значення. |
Покращено: 3.4.0 - Додано підтримку географії.
Змінено: 2.1.0. До версії 2.0.x це називалося ST_Line_Substring.
Доступність: 1.1.0, підтримка Z і M додана в 1.1.1
This function supports 3d and will not drop the z-index.

Лінія LineString, на яку накладено 1/3 середнього діапазону (0,333, 0,666)
SELECT ST_AsText(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)
Якщо початкова та кінцева точки однакові, результатом є ТОЧКА.
SELECT ST_AsText(ST_LineSubstring( 'LINESTRING(25 50, 100 125, 150 190)', 0.333, 0.333)); ------------------------------------------ POINT(69.2846934853974 94.2846934853974)
Запит для розрізання LineString на секції довжиною 100 або менше. Він використовує generate_series() з CROSS JOIN LATERAL для створення еквівалента циклу FOR.
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_AsText( 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)
-- skip last i if line length is exact multiple of sublen
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)
Заходи з реалізації географії вздовж сфероїда, геометрія вздовж лінії
SELECT ST_AsText(ST_LineSubstring( 'LINESTRING(-118.2436 34.0522, -71.0570 42.3611)'::geography, 0.333, 0.666),6) AS geog_sub
, ST_AsText(ST_LineSubstring('LINESTRING(-118.2436 34.0522, -71.0570 42.3611)'::geometry, 0.333, 0.666),6) AS geom_sub;
---------------------------------------------------------------
geog_sub | LINESTRING(-104.167064 38.854691,-87.674646 41.849854)
geom_sub | LINESTRING(-102.530462 36.819064,-86.817324 39.585927)
ST_Length, ST_LineExtend, ST_LineInterpolatePoint, ST_LineMerge
ST_LocateAlong — Повертає точку (точки) на геометрії, яка відповідає значенню міри.
geometry ST_LocateAlong(geometry geom_with_measure, float8 measure, float8 offset = 0);
Повертає місцезнаходження вздовж виміряної геометрії, яке має задані значення вимірювання. Результатом є точка або багатоточка. Полігональні вхідні дані не підтримуються.
Якщо вказано offset, результат буде зміщений вліво або вправо від лінії введення на вказану відстань. Позитивне зміщення буде вліво, а негативне — вправо.
![]() | |
Використовуйте цю функцію тільки для лінійних геометрій з компонентом M |
Семантика визначається стандартом ISO/IEC 13249-3 SQL/MM Spatial.
Доступність: 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
SELECT ST_AsText(
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))
ST_LocateBetween — Повертає частини геометрії, які відповідають діапазону вимірювання.
geometry ST_LocateBetween(geometry geom, float8 measure_start, float8 measure_end, float8 offset = 0);
Повернути геометрію (колекцію) з частинами виміряної геометрії вхідних даних, які відповідають заданому діапазону вимірювання (включно).
Якщо вказано offset, результат буде зміщений вліво або вправо від вхідної лінії на вказану відстань. Позитивне зміщення буде вліво, а негативне — вправо.
Обрізка не опуклого полігону може призвести до некоректної геометрії.
Семантика визначається стандартом ISO/IEC 13249-3 SQL/MM Spatial.
Доступність: 1.1.0 під старою назвою ST_Locate_Between_Measures.
Змінено: 2.0.0 — у попередніх версіях ця функція називалася ST_Locate_Between_Measures.Змінено: 2.0.0 — у попередніх версіях ця функція називалася ST_Locate_Between_Measures.
Покращено: 3.0.0 - додано підтримку POLYGON, TIN, TRIANGLE.
This function supports M coordinates.
This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 5.1
SELECT ST_AsText(
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))

LineString із відрізком між мірками 2 та 8, зміщений ліворуч
SELECT ST_AsText( ST_LocateBetween(
ST_AddMeasure('LINESTRING (20 180, 50 20, 100 120, 180 20)', 0, 10),
2, 8,
20
));
------------------------------------------------------------------------
MULTILINESTRING((54.49835019899045 104.53426957938231,58.70056060327303 82.12248075654186,69.16695286779743 103.05526528559065,82.11145618000168 128.94427190999915,84.24893681714357 132.32493442618113,87.01636951231555 135.21267035596549,90.30307285299679 137.49198684843182,93.97759758337769 139.07172433557758,97.89298381958797 139.8887023914453,101.89263860095893 139.9102465862721,105.81659870902816 139.13549527600819,109.50792827749828 137.5954340631298,112.81899532549731 135.351656550512,115.6173761888606 132.49390095108848,145.31017306064817 95.37790486135405))
ST_LocateBetweenElevations — Повертає частини геометрії, що лежать у діапазоні висоти (Z).
geometry ST_LocateBetweenElevations(geometry geom, float8 elevation_start, float8 elevation_end);
Повертає геометрію (колекцію) з частинами геометрії, що лежать у діапазоні висоти (Z).
Обрізка не опуклого полігону може призвести до некоректної геометрії.
Доступність: 1.4.0
Покращено: 3.0.0 - додано підтримку POLYGON, TIN, TRIANGLE.
This function supports 3d and will not drop the z-index.
SELECT ST_AsText(
ST_LocateBetweenElevations(
'LINESTRING(1 2 3, 4 5 6)'::geometry,
2, 4 ));
st_astext
-----------------------------------
MULTILINESTRING Z ((1 2 3,2 3 4))
SELECT ST_AsText(
ST_LocateBetweenElevations(
'LINESTRING(1 2 6, 4 5 -1, 7 8 9)',
6, 9)) As ewelev;
ewelev
-----------------------------------------------------------------------
GEOMETRYCOLLECTION Z (POINT Z (1 2 6),LINESTRING Z (6.1 7.1 6,7 8 9))
ST_InterpolatePoint — Повертає інтерпольоване значення геометрії, найближчої до точки.
float8 ST_InterpolatePoint(geometry linear_geom_with_measure, geometry point);
Повертає інтерпольоване значення вимірювання лінійної геометрії в місці, найближчому до заданої точки.
![]() | |
Використовуйте цю функцію тільки для лінійних геометрій з компонентом M |
Доступність: 2.0.0
This function supports 3d and will not drop the z-index.
SELECT ST_InterpolatePoint('LINESTRING M (0 0 0, 10 0 20)', 'POINT(5 5)');
---------------------
10
ST_AddMeasure — Інтерполює виміри вздовж лінійної геометрії.
geometry ST_AddMeasure(geometry geom_mline, float8 measure_start, float8 measure_end);
Повертає похідну геометрію з лінійно інтерпольованими значеннями вимірювання між початковою та кінцевою точками. Якщо геометрія не має вимірювального виміру, він додається. Якщо геометрія має вимірювальний вимір, він перезаписується новими значеннями. Підтримуються лише LINESTRINGS та MULTILINESTRINGS.
Доступність: 1.5.0
This function supports 3d and will not drop the z-index.
SELECT ST_AsText(ST_AddMeasure(
ST_GeomFromEWKT('LINESTRING(1 0, 2 0, 4 0)'),1,4)) As ewelev;
ewelev
--------------------------------
LINESTRINGM(1 0 1,2 0 2,4 0 4)
SELECT ST_AsText(ST_AddMeasure(
ST_GeomFromEWKT('LINESTRING(1 0 4, 2 0 4, 4 0 4)'),10,40)) As ewelev;
ewelev
----------------------------------------
LINESTRING(1 0 4 10,2 0 4 20,4 0 4 40)
SELECT ST_AsText(ST_AddMeasure(
ST_GeomFromEWKT('LINESTRINGM(1 0 4, 2 0 4, 4 0 4)'),10,40)) As ewelev;
ewelev
----------------------------------------
LINESTRINGM(1 0 10,2 0 20,4 0 40)
SELECT ST_AsText(ST_AddMeasure(
ST_GeomFromEWKT('MULTILINESTRINGM((1 0 4, 2 0 4, 4 0 4),(1 0 4, 2 0 4, 4 0 4))'),10,70)) As ewelev;
ewelev
-----------------------------------------------------------------
MULTILINESTRINGM((1 0 10,2 0 20,4 0 40),(1 0 40,2 0 50,4 0 70))
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.
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.
-- A valid trajectory SELECT ST_IsValidTrajectory(ST_MakeLine( ST_MakePointM(0,0,1), ST_MakePointM(0,1,2)) ); t -- An invalid trajectory 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) st_isvalidtrajectory ---------------------- 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
WITH inp AS ( SELECT
ST_AddMeasure('LINESTRING Z (0 0 0, 10 0 5)'::geometry,
extract(epoch from '2015-05-26 10:00'::timestamptz),
extract(epoch from '2015-05-26 11:00'::timestamptz)
) a,
ST_AddMeasure('LINESTRING Z (0 2 10, 12 1 2)'::geometry,
extract(epoch from '2015-05-26 10:00'::timestamptz),
extract(epoch from '2015-05-26 11:00'::timestamptz)
) 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) t,
ST_3DDistance(pa,pb) distance,
ST_AsText(pa, 2) AS pa, ST_AsText(pb, 2) AS pb
FROM points, cpa;
t | distance | pa | pb
-------------------------------+--------------------+--------------------------------------+----------------------------------------
2015-05-26 10:45:31.034483-07 | 1.9652147377620688 | POINT ZM (7.59 0 3.79 1432662331.03) | POINT ZM (9.1 1.24 3.93 1432662331.03)
ST_IsValidTrajectory, ST_DistanceCPA, ST_LocateAlong, ST_AddMeasure
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
WITH inp AS ( SELECT
ST_AddMeasure('LINESTRING Z (0 0 0, 10 0 5)'::geometry,
extract(epoch from '2015-05-26 10:00'::timestamptz),
extract(epoch from '2015-05-26 11:00'::timestamptz)
) a,
ST_AddMeasure('LINESTRING Z (0 2 10, 12 1 2)'::geometry,
extract(epoch from '2015-05-26 10:00'::timestamptz),
extract(epoch from '2015-05-26 11:00'::timestamptz)
) b
)
SELECT ST_DistanceCPA(a,b) distance FROM inp;
distance
-------------------
1.965214737762069
ST_IsValidTrajectory, ST_ClosestPointOfApproach, ST_AddMeasure, |=|
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.
WITH inp AS ( SELECT
ST_AddMeasure('LINESTRING Z (0 0 0, 10 0 5)'::geometry,
extract(epoch from '2015-05-26 10:00'::timestamptz),
extract(epoch from '2015-05-26 11:00'::timestamptz)
) a,
ST_AddMeasure('LINESTRING Z (0 2 10, 12 1 2)'::geometry,
extract(epoch from '2015-05-26 10:00'::timestamptz),
extract(epoch from '2015-05-26 11:00'::timestamptz)
) b
)
SELECT ST_CPAWithin(a,b,2), ST_DistanceCPA(a,b) distance FROM inp;
st_cpawithin | distance
--------------+------------------
t | 1.96521473776207
ST_IsValidTrajectory, ST_ClosestPointOfApproach, ST_DistanceCPA, |=|
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, postgis_topology, and postgis_tiger_geocoder.
Доступність: 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. |
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
NOTICE: Extension postgis_tiger_geocoder is not available or not packagable for some reason
postgis_extensions_upgrade
-------------------------------------------------------------------
Upgrade completed, run SELECT postgis_full_version(); for details
(1 row)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
SELECT PostGIS_Full_Version();
postgis_full_version
----------------------------------------------------------------------------------
POSTGIS="3.4.0dev 3.3.0rc2-993-g61bdf43a7" [EXTENSION] PGSQL="160" GEOS="3.12.0dev-CAPI-1.18.0" SFCGAL="1.3.8" PROJ="7.2.1 NETWORK_ENABLED=OFF URL_ENDPOINT=https://cdn.proj.org USER_WRITABLE_DIRECTORY=/tmp/proj DATABASE_PATH=/usr/share/proj/proj.db" GDAL="GDAL 3.2.2, released 2021/03/05" LIBXML="2.9.10" LIBJSON="0.15" LIBPROTOBUF="1.3.3" WAGYU="0.5.0 (Internal)" TOPOLOGY RASTER
(1 row)
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.
SELECT PostGIS_GEOS_Version(); postgis_geos_version ---------------------- 3.12.0dev-CAPI-1.18.0 (1 row)
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.
Доступність: 3.4.0
SELECT PostGIS_GEOS_Compiled_Version(); postgis_geos_compiled_version ------------------------------- 3.12.0 (1 row)
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/
SELECT PostGIS_Liblwgeom_Version(); postgis_liblwgeom_version -------------------------- 3.4.0dev 3.3.0rc2-993-g61bdf43a7 (1 row)
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
SELECT PostGIS_LibXML_Version(); postgis_libxml_version ---------------------- 2.9.10 (1 row)
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.
SELECT PostGIS_LibJSON_Version(); 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.
SELECT PostGIS_Lib_Build_Date(); postgis_lib_build_date ------------------------ 2023-06-22 03:56:11 (1 row)
PostGIS_Lib_Version — Returns the version number of the PostGIS library.
text PostGIS_Lib_Version();
Returns the version number of the PostGIS library.
SELECT PostGIS_Lib_Version(); postgis_lib_version --------------------- 3.4.0dev (1 row)
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
SELECT PostGIS_PROJ_Version(); 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 (1 row)
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.
Доступність: 3.5.0
SELECT PostGIS_PROJ_Compiled_Version(); postgis_proj_compiled_version ------------------------------- 9.1.1 (1 row)
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.
SELECT PostGIS_Wagyu_Version(); postgis_wagyu_version ----------------------- 0.5.0 (Internal) (1 row)
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
SELECT PostGIS_Scripts_Build_Date(); postgis_scripts_build_date ------------------------- 2023-06-22 03:56:11 (1 row)
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
SELECT PostGIS_Scripts_Installed(); postgis_scripts_installed ------------------------- 3.4.0dev 3.3.0rc2-993-g61bdf43a7 (1 row)
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
SELECT PostGIS_Scripts_Released(); postgis_scripts_released ------------------------- 3.4.0dev 3.3.0rc2-993-g61bdf43a7 (1 row)
PostGIS_Version — Returns PostGIS version number and compile-time options.
text PostGIS_Version();
Returns PostGIS version number and compile-time options.
SELECT PostGIS_Version();
postgis_version
---------------------------------------
3.4 USE_GEOS=1 USE_PROJ=1 USE_STATS=1
(1 row)У цьому розділі перелічено власні великі уніфіковані змінні PostGIS (GUC). Їх можна налаштувати глобально, для бази даних, для сеансу або для транзакції. Найкраще налаштовувати на глобальному рівні або на рівні бази даних.
Більше прикладів використання див. SQL SET та SQL ALTER SYSTEM
postgis.gdal_datapath — Параметр конфігурації для призначення значення параметра GDAL_DATA GDAL. Якщо не встановлено, використовується змінна GDAL_DATA, встановлена в середовищі.
Змінна PostgreSQL GUC для встановлення значення опції GDAL_DATA GDAL. Значення postgis.gdal_datapath повинно бути повним фізичним шляхом до файлів даних GDAL.
Ця опція конфігурації найбільш корисна для платформ Windows, де шлях до файлів даних GDAL не є жорстко заданим. Цю опцію також слід встановити, якщо файли даних GDAL не знаходяться в очікуваному GDAL шляху.
![]() | |
Цей параметр можна встановити у файлі конфігурації PostgreSQL postgresql.conf. Його також можна встановити для окремого з'єднання або транзакції. |
Доступність: 2.2.0
![]() | |
Додаткова інформація про GDAL_DATA доступна в розділі "Параметри конфігурації" на сайті GDAL Опція конфігурації. |
Встановити та скинути postgis.gdal_datapath
SET postgis.gdal_datapath TO '/usr/local/share/gdal.hidden';
SET postgis.gdal_datapath TO default;
Налаштування Windows для певної бази даних
ALTER DATABASE gisdb SET postgis.gdal_datapath = 'C:/Program Files/PostgreSQL/9.3/gdal-data';
postgis.gdal_enabled_drivers — Параметр конфігурації для встановлення увімкнених драйверів GDAL у середовищі PostGIS. Впливає на змінну конфігурації GDAL GDAL_SKIP.
Параметр конфігурації для встановлення увімкнених драйверів GDAL у середовищі PostGIS. Впливає на змінну конфігурації GDAL GDAL_SKIP. Цей параметр можна встановити у файлі конфігурації PostgreSQL: postgresql.conf. Його також можна встановити для з'єднання або транзакції.
Початкове значення postgis.gdal_enabled_drivers також можна встановити, передавши змінну середовища POSTGIS_GDAL_ENABLED_DRIVERS зі списком увімкнених драйверів процесу, що запускає PostgreSQL.
Увімкнені драйвери GDAL можна вказати за короткою назвою або кодом драйвера. Короткі назви або коди драйверів можна знайти за посиланням GDAL Raster Formats. Можна вказати кілька драйверів, розділивши їх пробілом.
![]() | |
Для
Коли |
![]() | |
У стандартній установці PostGIS |
![]() | |
Додаткова інформація про GDAL_SKIP доступна в розділі "Параметри конфігурації" на сайті GDAL Опція конфігурації. |
Доступність: 2.2.0
Встановити та скинути postgis.gdal_enabled_drivers для поточного сеансу
SET postgis.gdal_enabled_drivers = 'ENABLE_ALL';
SET postgis.gdal_enabled_drivers = default;
Встановити для всіх нових підключень до певної бази даних конкретні драйвери
ALTER DATABASE mygisdb SET postgis.gdal_enabled_drivers TO 'GTiff PNG JPEG';
Налаштування для всього кластера бази даних, щоб увімкнути всі драйвери. Потрібен доступ суперкористувача. Також зверніть увагу, що налаштування бази даних, сеансу та користувача мають пріоритет над цими налаштуваннями.
--writes to postgres.auto.conf
ALTER SYSTEM SET postgis.gdal_enabled_drivers TO 'ENABLE_ALL';
--Reloads postgres conf
SELECT pg_reload_conf();
postgis.enable_outdb_rasters — Булева опція конфігурації для увімкнення доступу до растрових смуг out-db.
Булева опція конфігурації для увімкнення доступу до растрових смуг out-db. Цю опцію можна встановити у файлі конфігурації PostgreSQL: postgresql.conf. Її також можна встановити для з'єднання або транзакції.
Початкове значення postgis.enable_outdb_rasters також можна встановити, передавши змінну середовища POSTGIS_ENABLE_OUTDB_RASTERS з значенням, відмінним від нуля, процесу, що запускає PostgreSQL.
![]() | |
Навіть якщо |
![]() | |
У стандартній установці PostGIS |
Доступність: 2.2.0
Встановити та скинути postgis.enable_outdb_rasters для поточної сесії
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;
Встановити для всіх нових підключень до певної бази даних
ALTER DATABASE gisdb SET postgis.enable_outdb_rasters = true;
Налаштування для всього кластера бази даних. Потрібен доступ суперкористувача. Також зверніть увагу, що налаштування бази даних, сеансу та користувача мають пріоритет над цими налаштуваннями.
--writes to postgres.auto.conf
ALTER SYSTEM SET postgis.enable_outdb_rasters = true;
--Reloads postgres conf
SELECT pg_reload_conf();
postgis.gdal_vsi_options — Конфігурація рядка для встановлення параметрів, що використовуються під час роботи з растровим файлом out-db.
Конфігурація рядка для встановлення опцій, що використовуються під час роботи з растровим файлом out-db. Опції конфігурації контролюють такі параметри, як обсяг простору, що GDAL виділяє для локального кешу даних, чи читати огляди та які ключі доступу використовувати для віддалених джерел даних out-db.
Доступність: 3.2.0
Встановити postgis.gdal_vsi_options для поточної сесії:
SET postgis.gdal_vsi_options = 'AWS_ACCESS_KEY_ID=xxxxxxxxxxxxxxx AWS_SECRET_ACCESS_KEY=yyyyyyyyyyyyyyyyyyyyyyyyyy';
Встановіть postgis.gdal_vsi_options тільки для поточної транзакції за допомогою ключового слова LOCAL:
SET LOCAL postgis.gdal_vsi_options = 'AWS_ACCESS_KEY_ID=xxxxxxxxxxxxxxx AWS_SECRET_ACCESS_KEY=yyyyyyyyyyyyyyyyyyyyyyyyyy';
postgis.gdal_cpl_debug — Булева конфігурація для ввімкнення та вимкнення реєстрації повідомлень про налагодження GDAL.
За замовчуванням, журнали GDAL друкуються на stderr, а повідомлення нижчого рівня не друкуються взагалі. Встановлення цього GUC на true призведе до надсилання журналів GDAL до потоку журналів PostgreSQL, тож ви зможете бачити більше або менше з них, змінюючи client_min_message PostgreSQL GUC.
Доступність: 3.6.0
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 — Додати обмежувальну рамку до геометрії.
geometry PostGIS_AddBBox(geometry geomA);
Додати обмежувальну рамку до геометрії. Це пришвидшить запити на основі обмежувальної рамки, але збільшить розмір геометрії.
![]() | |
Обмежувальні рамки автоматично додаються до геометрій, тому, як правило, це не потрібно, якщо тільки створена обмежувальна рамка якимось чином не пошкодилася або у вас стара версія, в якій відсутні обмежувальні рамки. Тоді вам потрібно видалити стару і додати нову. |
This method supports Circular Strings and Curves.
UPDATE sometable SET geom = PostGIS_AddBBox(geom) WHERE PostGIS_HasBBox(geom) = false;
PostGIS_DropBBox — Видалити кеш обмежувальної рамки з геометрії.
geometry PostGIS_DropBBox(geometry geomA);
Видалити кеш обмежувальної рамки з геометрії. Це зменшує розмір геометрії, але уповільнює запити на основі обмежувальної рамки. Також використовується для видалення пошкодженої обмежувальної рамки. Ознакою пошкодження кешованої обмежувальної рамки є те, що ST_Intersects та інші запити на відношення пропускають геометрії, які повинні повертати значення true.
![]() | |
Обмежувальні рамки автоматично додаються до геометрій і покращують швидкість запитів, тому, як правило, це не потрібно, якщо тільки створена обмежувальна рамка якимось чином не пошкодилася або у вас стара версія, в якій відсутні обмежувальні рамки. У такому випадку потрібно видалити старі та додати заново. Таке пошкодження спостерігалося в серіях 8.3-8.3.6, де кешовані bboxes не завжди перераховувалися при зміні геометрії, і оновлення до нової версії без перезавантаження дампа не виправляє вже пошкоджені рамки. Тому можна вручну виправити за допомогою наведеного нижче коду та додати bbox заново або виконати перезавантаження дампа. |
This method supports Circular Strings and Curves.
--This example drops bounding boxes where the cached box is not correct
--The force to ST_AsBinary before applying Box2D forces a recalculation of the box, and Box2D applied to the table geometry always
-- returns the cached bounding box.
UPDATE sometable
SET geom = PostGIS_DropBBox(geom)
WHERE Not (Box2D(ST_AsBinary(geom)) = Box2D(geom));
UPDATE sometable
SET geom = PostGIS_AddBBox(geom)
WHERE Not PostGIS_HasBBOX(geom);
PostGIS_HasBBox — Повертає TRUE, якщо bbox цієї геометрії кешована, і FALSE в іншому випадку.
boolean PostGIS_HasBBox(geometry geomA);
Повертає TRUE, якщо bbox цієї геометрії кешована, і FALSE в іншому випадку. Використовуйте PostGIS_AddBBoxта PostGIS_DropBBoxдля керування кешуванням.
This method supports Circular Strings and Curves.
SELECT geom FROM sometable WHERE PostGIS_HasBBox(geom) = false;
SFCGAL is a C++ wrapper library around CGAL that provides advanced 2D and 3D spatial functions. For robustness, geometry coordinates have an exact rational number representation.
Installation instructions for the library can be found on the SFCGAL home page (http://www.sfcgal.org). To enable the functions use create extension postgis_sfcgal.
This section lists functions for determining version of SFCGAL and library dependencies you are running.
postgis_sfcgal_version — Returns the version of SFCGAL in use
text postgis_sfcgal_version(void);
Returns the version of SFCGAL in use
Доступність: 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_full_version(void);
Returns the full version of SFCGAL in use including CGAL and Boost versions
Доступність: 3.3.0
This method needs SFCGAL backend.
These functions access or set properties of geometries. Geometries primarily supported by these functions are TINS and Polyhedral Surfaces.
CG_ForceLHR — Force LHR orientation
geometry CG_ForceLHR(geometry geom);
Доступність: 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_IsPlanar — Check if a surface is or not planar
boolean CG_IsPlanar(geometry geom);
Доступність: 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 — Test if the geometry is a solid. No validity check is performed.
boolean CG_IsSolid(geometry geom1);
Доступність: 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_MakeSolid — Cast the geometry into a solid. No check is performed. To obtain a valid solid, the input geometry must be a closed Polyhedral Surface or a closed TIN.
geometry CG_MakeSolid(geometry geom1);
Доступність: 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 — Determine surface orientation
integer CG_Orientation(geometry geom);
The function only applies to polygons. It returns -1 if the polygon is counterclockwise oriented and 1 if the polygon is clockwise oriented.
Доступність: 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. |
Доступність: 3.5.0
This method needs SFCGAL backend.
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))');
cg_area
--------
25
(1 row)CG_3DArea — Computes area of 3D surface geometries. Will return 0 for solids.
floatCG_3DArea(geometry geom1);
Доступність: 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).
Note: By default a PolyhedralSurface built from WKT is a surface geometry, not solid. It therefore has surface area. Once converted to a solid, no area.
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 solid. If applied to surface (even closed) geometries will return 0.
float CG_Volume(geometry geom1);
Доступність: 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)
When closed surfaces are created with WKT, they are treated as areal rather than solid. To make them solid, you need to use CG_MakeSolid. Areal geometries have no volume. Here is an example to demonstrate.
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
------------------+-------------------
0 | 1
ST_ForceLHR — Force LHR orientation
geometry ST_ForceLHR(geometry geom);
![]() | |
ST_ForceLHR is deprecated as of 3.5.0. Use CG_ForceLHR instead. |
Доступність: 2.1.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).
ST_IsPlanar — Check if a surface is or not planar
boolean ST_IsPlanar(geometry geom);
![]() | |
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.
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).
ST_IsSolid — Test if the geometry is a solid. No validity check is performed.
boolean ST_IsSolid(geometry geom1);
![]() | |
ST_IsSolid is deprecated as of 3.5.0. Use CG_IsSolid instead. |
Доступність: 2.2.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).
ST_MakeSolid — Cast the geometry into a solid. No check is performed. To obtain a valid solid, the input geometry must be a closed Polyhedral Surface or a closed TIN.
geometry ST_MakeSolid(geometry geom1);
![]() | |
ST_MakeSolid is deprecated as of 3.5.0. Use CG_MakeSolid instead. |
Доступність: 2.2.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).
ST_Orientation — Determine surface orientation
integer ST_Orientation(geometry geom);
![]() | |
ST_Orientation is deprecated as of 3.5.0. Use CG_Orientation instead. |
The function only applies to polygons. It returns -1 if the polygon is counterclockwise oriented and 1 if the polygon is clockwise oriented.
Доступність: 2.1.0
This method needs SFCGAL backend.
This function supports 3d and will not drop the z-index.
ST_3DArea — Computes area of 3D surface geometries. Will return 0 for solids.
floatST_3DArea(geometry geom1);
Доступність: 2.1.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).
Note: By default a PolyhedralSurface built from WKT is a surface geometry, not solid. It therefore has surface area. Once converted to a solid, no area.
SELECT ST_3DArea(geom) As cube_surface_area,
ST_3DArea(ST_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 ST_Volume — Computes the volume of a 3D solid. If applied to surface (even closed) geometries will return 0.
float ST_Volume(geometry geom1);
Доступність: 2.2.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 ST_3DVolume)
When closed surfaces are created with WKT, they are treated as areal rather than solid. To make them solid, you need to use ST_MakeSolid. Areal geometries have no volume. Here is an example to demonstrate.
SELECT ST_Volume(geom) As cube_surface_vol,
ST_Volume(ST_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
------------------+-------------------
0 | 1
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. |
Доступність: 3.5.0
This method needs SFCGAL backend.
SELECT ST_AsText(CG_Intersection('LINESTRING(0 0, 5 5)', 'LINESTRING(5 0, 0 5)'));
cg_intersection
-----------------
POINT(2.5 2.5)
(1 row)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. |
Доступність: 3.5.0
This method needs SFCGAL backend.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
SELECT CG_Intersects('POINT(0 0)'::geometry, 'LINESTRING ( 2 0, 0 2 )'::geometry);
cg_intersects
---------------
f
(1 row)
SELECT CG_Intersects('POINT(0 0)'::geometry, 'LINESTRING ( 0 0, 0 2 )'::geometry);
cg_intersects
---------------
t
(1 row)
CG_3DIntersects, ST_3DIntersects, ST_Intersects, ST_Disjoint
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. |
Доступність: 3.5.0
This method needs SFCGAL backend.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
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)))');
cg_3dintersects
---------------
t
(1 row)
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. |
Доступність: 3.5.0
This method needs SFCGAL backend.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
SELECT ST_AsText(CG_Difference('POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))'::geometry, 'LINESTRING(0 0, 2 2)'::geometry));
cg_difference
---------------
POLYGON((0 0,1 0,1 1,0 1,0 0))
(1 row)ST_3DDifference — Perform 3D difference
geometry ST_3DDifference(geometry geom1, geometry geom2);
![]() | |
ST_3DDifference is deprecated as of 3.5.0. Use CG_3DDifference instead. |
Returns that part of geom1 that is not part of geom2.
Доступність: 2.2.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).
CG_3DDifference — Perform 3D difference
geometry CG_3DDifference(geometry geom1, geometry geom2);
Returns that part of geom1 that is not part of geom2.
Доступність: 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 images were generated using PostGIS ST_AsX3D and rendering in HTML using X3Dom HTML Javascript rendering library.
SELECT CG_Extrude(ST_Buffer(ST_GeomFromText('POINT(100 90)'),
50, 'quad_segs=2'),0,0,30) AS geom1,
CG_Extrude(ST_Buffer(ST_GeomFromText('POINT(80 80)'),
50, 'quad_segs=1'),0,0,30) AS geom2;
![]() Original 3D geometries overlaid. geom2 is the part that will be removed. |
SELECT CG_3DDifference(geom1,geom2)
FROM ( SELECT CG_Extrude(ST_Buffer(ST_GeomFromText('POINT(100 90)'),
50, 'quad_segs=2'),0,0,30) AS geom1,
CG_Extrude(ST_Buffer(ST_GeomFromText('POINT(80 80)'),
50, 'quad_segs=1'),0,0,30) AS geom2 ) As t;
![]() What's left after removing geom2 |
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. |
Доступність: 3.5.0
This method needs SFCGAL backend.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
SELECT CG_Distance('LINESTRING(0.0 0.0,-1.0 -1.0)', 'LINESTRING(3.0 4.0,4.0 5.0)');
cg_distance
-------------
2.0
(1 row)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. |
Доступність: 3.5.0
This method needs SFCGAL backend.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
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))');
cg_3ddistance
----------------
1
(1 row)ST_3DConvexHull — Computes the 3D convex hull of a geometry.
geometry ST_3DConvexHull(geometry geom1);
![]() | |
ST_3DConvexHull is deprecated as of 3.5.0. Use CG_3DConvexHull instead. |
Доступність: 3.3.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_3DConvexHull — Computes the 3D convex hull of a geometry.
geometry CG_3DConvexHull(geometry geom1);
Доступність: 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).
SELECT ST_AsText(CG_3DConvexHull('LINESTRING Z(0 0 5, 1 5 3, 5 7 6, 9 5 3 , 5 7 5, 6 3 5)'::geometry));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)))
WITH f AS (SELECT i, CG_Extrude(geom, 0,0, i ) AS geom
FROM ST_Subdivide(ST_Letters('CH'),5) WITH ORDINALITY AS sd(geom,i)
)
SELECT CG_3DConvexHull(ST_Collect(f.geom) )
FROM f;

Original geometry overlaid with 3D convex hull
ST_3DIntersection — Perform 3D intersection
geometry ST_3DIntersection(geometry geom1, geometry geom2);
![]() | |
ST_3DIntersection is deprecated as of 3.5.0. Use CG_3DIntersection instead. |
Return a geometry that is the shared portion between geom1 and geom2.
Доступність: 2.1.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).
CG_3DIntersection — Perform 3D intersection
geometry CG_3DIntersection(geometry geom1, geometry geom2);
Return a geometry that is the shared portion between geom1 and geom2.
Доступність: 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 images were generated using PostGIS ST_AsX3D and rendering in HTML using X3Dom HTML Javascript rendering library.
SELECT CG_Extrude(ST_Buffer(ST_GeomFromText('POINT(100 90)'),
50, 'quad_segs=2'),0,0,30) AS geom1,
CG_Extrude(ST_Buffer(ST_GeomFromText('POINT(80 80)'),
50, 'quad_segs=1'),0,0,30) AS geom2;
![]() Original 3D geometries overlaid. geom2 is shown semi-transparent |
SELECT CG_3DIntersection(geom1,geom2)
FROM ( SELECT CG_Extrude(ST_Buffer(ST_GeomFromText('POINT(100 90)'),
50, 'quad_segs=2'),0,0,30) AS geom1,
CG_Extrude(ST_Buffer(ST_GeomFromText('POINT(80 80)'),
50, 'quad_segs=1'),0,0,30) AS geom2 ) As t;
![]() Intersection of geom1 and geom2 |
3D linestrings and polygons
SELECT ST_AsText(CG_3DIntersection(linestring, polygon)) As wkt
FROM ST_GeomFromText('LINESTRING Z (2 2 6,1.5 1.5 7,1 1 8,0.5 0.5 8,0 0 10)') AS linestring
CROSS JOIN ST_GeomFromText('POLYGON((0 0 8, 0 1 8, 1 1 8, 1 0 8, 0 0 8))') AS polygon;
wkt
--------------------------------
LINESTRING Z (1 1 8,0.5 0.5 8)
Cube (closed Polyhedral Surface) and Polygon Z
SELECT ST_AsText(CG_3DIntersection(
ST_GeomFromText('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))'::geometry))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)))
Intersection of 2 solids that result in volumetric intersection is also a solid (ST_Dimension returns 3)
SELECT ST_AsText(CG_3DIntersection( CG_Extrude(ST_Buffer('POINT(10 20)'::geometry,10,1),0,0,30),
CG_Extrude(ST_Buffer('POINT(10 20)'::geometry,10,1),2,0,10) ));POLYHEDRALSURFACE Z (((13.3333333333333 13.3333333333333 10,20 20 0,20 20 10,13.3333333333333 13.3333333333333 10)),
((20 20 10,16.6666666666667 23.3333333333333 10,13.3333333333333 13.3333333333333 10,20 20 10)),
((20 20 0,16.6666666666667 23.3333333333333 10,20 20 10,20 20 0)),
((13.3333333333333 13.3333333333333 10,10 10 0,20 20 0,13.3333333333333 13.3333333333333 10)),
((16.6666666666667 23.3333333333333 10,12 28 10,13.3333333333333 13.3333333333333 10,16.6666666666667 23.3333333333333 10)),
((20 20 0,9.99999999999995 30 0,16.6666666666667 23.3333333333333 10,20 20 0)),
((10 10 0,9.99999999999995 30 0,20 20 0,10 10 0)),((13.3333333333333 13.3333333333333 10,12 12 10,10 10 0,13.3333333333333 13.3333333333333 10)),
((12 28 10,12 12 10,13.3333333333333 13.3333333333333 10,12 28 10)),
((16.6666666666667 23.3333333333333 10,9.99999999999995 30 0,12 28 10,16.6666666666667 23.3333333333333 10)),
((10 10 0,0 20 0,9.99999999999995 30 0,10 10 0)),
((12 12 10,11 11 10,10 10 0,12 12 10)),((12 28 10,11 11 10,12 12 10,12 28 10)),
((9.99999999999995 30 0,11 29 10,12 28 10,9.99999999999995 30 0)),((0 20 0,2 20 10,9.99999999999995 30 0,0 20 0)),
((10 10 0,2 20 10,0 20 0,10 10 0)),((11 11 10,2 20 10,10 10 0,11 11 10)),((12 28 10,11 29 10,11 11 10,12 28 10)),
((9.99999999999995 30 0,2 20 10,11 29 10,9.99999999999995 30 0)),((11 11 10,11 29 10,2 20 10,11 11 10)))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. |
Доступність: 3.5.0
This method needs SFCGAL backend.
SELECT CG_Union('POINT(.5 0)', 'LINESTRING(-1 0,1 0)');
cg_union
-----------
LINESTRING(-1 0,0.5 0,1 0)
(1 row)ST_3DUnion — Perform 3D union.
geometry ST_3DUnion(geometry geom1, geometry geom2);
geometry ST_3DUnion(geometry set g1field);
![]() | |
ST_3DUnion is deprecated as of 3.5.0. Use CG_3DUnion instead. |
Доступність: 2.2.0
Availability: 3.3.0 aggregate variant was added
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 ST_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.
CG_3DUnion — Perform 3D union using postgis_sfcgal.
geometry CG_3DUnion(geometry geom1, geometry geom2);
geometry CG_3DUnion(geometry set g1field);
Доступність: 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.
3D images were generated using PostGIS ST_AsX3D and rendering in HTML using X3Dom HTML Javascript rendering library.
SELECT CG_Extrude(ST_Buffer(ST_GeomFromText('POINT(100 90)'),
50, 'quad_segs=2'),0,0,30) AS geom1,
CG_Extrude(ST_Buffer(ST_GeomFromText('POINT(80 80)'),
50, 'quad_segs=1'),0,0,30) AS geom2;
![]() Original 3D geometries overlaid. geom2 is the one with transparency. |
SELECT CG_3DUnion(geom1,geom2)
FROM ( SELECT CG_Extrude(ST_Buffer(ST_GeomFromText('POINT(100 90)'),
50, 'quad_segs=2'),0,0,30) AS geom1,
CG_Extrude(ST_Buffer(ST_GeomFromText('POINT(80 80)'),
50, 'quad_segs=1'),0,0,30) AS geom2 ) As t;
![]() Union of geom1 and geom2 |
ST_AlphaShape — Computes an Alpha-shape enclosing a geometry
geometry ST_AlphaShape(geometry geom, float alpha, boolean allow_holes = false);
![]() | |
ST_AlphaShape is deprecated as of 3.5.0. Use CG_AlphaShape instead. |
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.
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.

Alpha-shape of a MultiPoint (same example As CG_OptimalAlphaShape)
SELECT ST_AsText(CG_AlphaShape('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,80.2));
POLYGON((89 53,91 50,87 42,90 30,88 29,84 19,78 16,73 16,65 16,53 18,43 19,
37 23,30 22,28 33,23 36,26 44,27 54,23 60,24 67,27 77,
24 82,26 85,34 86,39 88,45 90,49 95,52 98,57 97,
64 97,72 95,76 88,75 84,83 72,85 71,88 58,89 53))

Alpha-shape of a MultiPoint, allowing holes (same example as CG_OptimalAlphaShape)
SELECT ST_AsText(CG_AlphaShape('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, 100.1,true))
POLYGON((89 53,91 50,87 42,90 30,84 19,78 16,73 16,65 16,53 18,43 19,30 22,28 33,23 36, 26 44,27 54,23 60,24 67,27 77,24 82,26 85,34 86,39 88,45 90,49 95,52 98,57 97,64 97,72 95, 76 88,75 84,83 72,85 71,88 58,89 53),(36 61,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))

Alpha-shape of a MultiPoint, allowing holes (same example as ST_ConcaveHull)
SELECT ST_AsText(CG_AlphaShape(
'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,102.2, true));
POLYGON((26 20,32 36,35 45,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,114 64,99 64,90 69,81 64,63 64,57 49,52 36,46 20,37 20,26 20),
(74 93,81 109,88 124,92 138,103 138,110 122,114 109,121 96,112 82,99 82,83 82,74 93))
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.

Approximal Convex Partition (same example As CG_YMonotonePartition, CG_GreeneApproxConvexPartition and CG_OptimalConvexPartition)
SELECT ST_AsText(CG_ApproxConvexPartition('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));
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)))
ST_ApproximateMedialAxis — Compute the approximate medial axis of an areal geometry.
geometry ST_ApproximateMedialAxis(geometry geom);
![]() | |
ST_ApproximateMedialAxis is deprecated as of 3.5.0. Use CG_ApproximateMedialAxis instead. |
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).
Доступність: 2.2.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_ApproximateMedialAxis — Compute the approximate medial axis of an areal geometry.
geometry CG_ApproximateMedialAxis(geometry geom);
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).
Доступність: 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).
SELECT CG_ApproximateMedialAxis(ST_GeomFromText('POLYGON (( 190 190, 10 190, 10 10, 190 10, 190 20, 160 30, 60 30, 60 130, 190 140, 190 190 ))'));![]() A polygon and its approximate medial axis |
ST_ConstrainedDelaunayTriangles — Return a constrained Delaunay triangulation around the given input geometry.
geometry ST_ConstrainedDelaunayTriangles(geometry g1);
![]() | |
ST_ConstrainedDelaunayTriangles is deprecated as of 3.5.0. Use CG_ConstrainedDelaunayTriangles instead. |
Return a Constrained Delaunay triangulation around the vertices of the input geometry. Output is a TIN.
This method needs SFCGAL backend.
Доступність: 3.0.0
This function supports 3d and will not drop the z-index.
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.
Доступність: 3.0.0
This function supports 3d and will not drop the z-index.
![]() CG_ConstrainedDelaunayTriangles of 2 polygons
select CG_ConstrainedDelaunayTriangles(
ST_Union(
'POLYGON((175 150, 20 40, 50 60, 125 100, 175 150))'::geometry,
ST_Buffer('POINT(110 170)'::geometry, 20)
)
);
| ![]() ST_DelaunayTriangles of 2 polygons. Triangle edges cross polygon boundaries.
select ST_DelaunayTriangles(
ST_Union(
'POLYGON((175 150, 20 40, 50 60, 125 100, 175 150))'::geometry,
ST_Buffer('POINT(110 170)'::geometry, 20)
)
);
|
ST_Extrude — Extrude a surface to a related volume
geometry ST_Extrude(geometry geom, float x, float y, float z);
![]() | |
ST_Extrude is deprecated as of 3.5.0. Use CG_Extrude instead. |
Доступність: 2.1.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_Extrude — Extrude a surface to a related volume
geometry CG_Extrude(geometry geom, float x, float y, float z);
Доступність: 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).
3D images were generated using PostGIS ST_AsX3D and rendering in HTML using X3Dom HTML Javascript rendering library.
SELECT ST_Buffer(ST_GeomFromText('POINT(100 90)'),
50, 'quad_segs=2'),0,0,30);
![]() Original octagon formed from buffering point |
CG_Extrude(ST_Buffer(ST_GeomFromText('POINT(100 90)'),
50, 'quad_segs=2'),0,0,30);
![]() Hexagon extruded 30 units along Z produces a PolyhedralSurfaceZ |
SELECT ST_GeomFromText('LINESTRING(50 50, 100 90, 95 150)')
![]() Original linestring |
SELECT CG_Extrude(
ST_GeomFromText('LINESTRING(50 50, 100 90, 95 150)'),0,0,10));
![]() LineString Extruded along Z produces a PolyhedralSurfaceZ |
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.
SELECT ST_AsText(CG_ExtrudeStraightSkeleton('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))', 3.0, 2.0));
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.5 2.5 2.5,0 0 2,0.5 0.5 2.5,0.5 2.5 2.5)),((1 3 3,0 4 2,0.5 2.5 2.5,1 3 3)),((0.5 2.5 2.5,0 4 2,0 0 2,0.5 2.5 2.5)),((2.5 0.5 2.5,5 0 2,3.5 1.5 3.5,2.5 0.5 2.5)),((0 0 2,5 0 2,2.5 0.5 2.5,0 0 2)),((0.5 0.5 2.5,0 0 2,2.5 0.5 2.5,0.5 0.5 2.5)),((4.5 3.5 2.5,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,4.5 3.5 2.5,3.5 2.5 3.5)),((4.5 3.5 2.5,5 0 2,5 5 2,4.5 3.5 2.5)),((3.5 1.5 3.5,5 0 2,4.5 3.5 2.5,3.5 1.5 3.5)),((5 5 2,4 5 2,4.5 4.5 2.5,5 5 2)),((4.5 4.5 2.5,4 4 2,4.5 3.5 2.5,4.5 4.5 2.5)),((4.5 4.5 2.5,4 5 2,4 4 2,4.5 4.5 2.5)),((3 3 3,0 4 2,1 3 3,3 3 3)),((3.5 2.5 3.5,4.5 3.5 2.5,3 3 3,3.5 2.5 3.5)),((3 3 3,4 4 2,0 4 2,3 3 3)),((4.5 3.5 2.5,4 4 2,3 3 3,4.5 3.5 2.5)),((2 1 2,1 1 2,0.5 0.5 2.5,2 1 2)),((2.5 0.5 2.5,2 1 2,0.5 0.5 2.5,2.5 0.5 2.5)),((1 1 2,1 2 2,0.5 2.5 2.5,1 1 2)),((0.5 0.5 2.5,1 1 2,0.5 2.5 2.5,0.5 0.5 2.5)),((1 3 3,2 2 2,3 3 3,1 3 3)),((0.5 2.5 2.5,1 2 2,1 3 3,0.5 2.5 2.5)),((1 3 3,1 2 2,2 2 2,1 3 3)),((2 2 2,2 1 2,2.5 0.5 2.5,2 2 2)),((3.5 2.5 3.5,3 3 3,3.5 1.5 3.5,3.5 2.5 3.5)),((3.5 1.5 3.5,2 2 2,2.5 0.5 2.5,3.5 1.5 3.5)),((3 3 3,2 2 2,3.5 1.5 3.5,3 3 3)))
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 Approximal Convex Partition (same example As CG_YMonotonePartition, CG_ApproxConvexPartition and CG_OptimalConvexPartition)
SELECT ST_AsText(CG_GreeneApproxConvexPartition('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));
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)))
ST_MinkowskiSum — Performs Minkowski sum
geometry ST_MinkowskiSum(geometry geom1, geometry geom2);
![]() | |
ST_MinkowskiSum is deprecated as of 3.5.0. Use CG_MinkowskiSum instead. |
This function performs a 2D minkowski sum of a point, line or polygon with a polygon.
A minkowski sum of two geometries A and B is the set of all points that are the sum of any point in A and B. Minkowski sums are often used in motion planning and computer-aided design. More details on Wikipedia Minkowski addition.
The first parameter can be any 2D geometry (point, linestring, polygon). If a 3D geometry is passed, it will be converted to 2D by forcing Z to 0, leading to possible cases of invalidity. The second parameter must be a 2D polygon.
Implementation utilizes CGAL 2D Minkowskisum.
Доступність: 2.1.0
This method needs SFCGAL backend.
CG_MinkowskiSum — Performs Minkowski sum
geometry CG_MinkowskiSum(geometry geom1, geometry geom2);
This function performs a 2D minkowski sum of a point, line or polygon with a polygon.
A minkowski sum of two geometries A and B is the set of all points that are the sum of any point in A and B. Minkowski sums are often used in motion planning and computer-aided design. More details on Wikipedia Minkowski addition.
The first parameter can be any 2D geometry (point, linestring, polygon). If a 3D geometry is passed, it will be converted to 2D by forcing Z to 0, leading to possible cases of invalidity. The second parameter must be a 2D polygon.
Implementation utilizes CGAL 2D Minkowskisum.
Доступність: 3.5.0
This method needs SFCGAL backend.
Minkowski Sum of Linestring and circle polygon where Linestring cuts thru the circle
|
![]() Before Summing
|
![]() After summing
|
SELECT CG_MinkowskiSum(line, circle))
FROM (SELECT
ST_MakeLine(ST_Point(10, 10),ST_Point(100, 100)) As line,
ST_Buffer(ST_GeomFromText('POINT(50 50)'), 30) As circle) As foo;
-- wkt --
MULTIPOLYGON(((30 59.9999999999999,30.5764415879031 54.1472903395161,32.2836140246614 48.5194970290472,35.0559116309237 43.3328930094119,38.7867965644036 38.7867965644035,43.332893009412 35.0559116309236,48.5194970290474 32.2836140246614,54.1472903395162 30.5764415879031,60.0000000000001 30,65.8527096604839 30.5764415879031,71.4805029709527 32.2836140246614,76.6671069905881 35.0559116309237,81.2132034355964 38.7867965644036,171.213203435596 128.786796564404,174.944088369076 133.332893009412,177.716385975339 138.519497029047,179.423558412097 144.147290339516,180 150,179.423558412097 155.852709660484,177.716385975339 161.480502970953,174.944088369076 166.667106990588,171.213203435596 171.213203435596,166.667106990588 174.944088369076,
161.480502970953 177.716385975339,155.852709660484 179.423558412097,150 180,144.147290339516 179.423558412097,138.519497029047 177.716385975339,133.332893009412 174.944088369076,128.786796564403 171.213203435596,38.7867965644035 81.2132034355963,35.0559116309236 76.667106990588,32.2836140246614 71.4805029709526,30.5764415879031 65.8527096604838,30 59.9999999999999)))
Minkowski Sum of a polygon and multipoint
|
![]() Before Summing
|
![]() After summing: polygon is duplicated and translated to position of points
|
SELECT CG_MinkowskiSum(mp, poly)
FROM (SELECT 'MULTIPOINT(25 50,70 25)'::geometry As mp,
'POLYGON((130 150, 20 40, 50 60, 125 100, 130 150))'::geometry As poly
) As foo
-- wkt --
MULTIPOLYGON(
((70 115,100 135,175 175,225 225,70 115)),
((120 65,150 85,225 125,275 175,120 65))
)
ST_OptimalAlphaShape — Computes an Alpha-shape enclosing a geometry using an "optimal" alpha value.
geometry ST_OptimalAlphaShape(geometry geom, boolean allow_holes = false, integer nb_components = 1);
![]() | |
ST_OptimalAlphaShape is deprecated as of 3.5.0. Use CG_OptimalAlphaShape instead. |
Computes the "optimal" alpha-shape of the points in a geometry. The alpha-shape is computed using a value of α chosen so that:
the number of polygon elements is equal to or smaller than nb_components (which defaults to 1)
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.3.0 - requires SFCGAL >= 1.4.1.
This method needs SFCGAL backend.
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:
the number of polygon elements is equal to or smaller than nb_components (which defaults to 1)
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.

Optimal alpha-shape of a MultiPoint (same example as CG_AlphaShape)
SELECT ST_AsText(CG_OptimalAlphaShape('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));
POLYGON((89 53,91 50,87 42,90 30,88 29,84 19,78 16,73 16,65 16,53 18,43 19,37 23,30 22,28 33,23 36,
26 44,27 54,23 60,24 67,27 77,24 82,26 85,34 86,39 88,45 90,49 95,52 98,57 97,64 97,72 95,76 88,75 84,75 77,83 72,85 71,83 64,88 58,89 53))

Optimal alpha-shape of a MultiPoint, allowing holes (same example as CG_AlphaShape)
SELECT ST_AsText(CG_OptimalAlphaShape('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, allow_holes => true));
POLYGON((89 53,91 50,87 42,90 30,88 29,84 19,78 16,73 16,65 16,53 18,43 19,37 23,30 22,28 33,23 36,26 44,27 54,23 60,24 67,27 77,24 82,26 85,34 86,39 88,45 90,49 95,52 98,57 97,64 97,72 95,76 88,75 84,75 77,83 72,85 71,83 64,88 58,89 53),(36 61,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))
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.

Optimal Convex Partition (same example As CG_YMonotonePartition, CG_ApproxConvexPartition and CG_GreeneApproxConvexPartition)
SELECT ST_AsText(CG_OptimalConvexPartition('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));
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)))
CG_StraightSkeleton — Compute a straight skeleton from a geometry
geometry CG_StraightSkeleton(geometry geom, boolean use_distance_as_m = false);
Доступність: 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).
SELECT CG_StraightSkeleton(ST_GeomFromText('POLYGON (( 190 190, 10 190, 10 10, 190 10, 190 20, 160 30, 60 30, 60 130, 190 140, 190 190 ))'));SELECT ST_AsText(CG_StraightSkeleton('POLYGON((0 0,1 0,1 1,0 1,0 0))', true);
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))Note that valid inputs with rings that touch at a single point will raise an error.
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.
![]() Original polygon | ![]() Straight Skeleton of polygon |
ST_StraightSkeleton — Compute a straight skeleton from a geometry
geometry ST_StraightSkeleton(geometry geom);
![]() | |
ST_StraightSkeleton is deprecated as of 3.5.0. Use CG_StraightSkeleton instead. |
Доступність: 2.1.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).
SELECT ST_StraightSkeleton(ST_GeomFromText('POLYGON (( 190 190, 10 190, 10 10, 190 10, 190 20, 160 30, 60 30, 60 130, 190 140, 190 190 ))'));![]() Original polygon | ![]() Straight Skeleton of polygon |
ST_Tesselate — Perform surface Tessellation of a polygon or polyhedralsurface and returns as a TIN or collection of TINS
geometry ST_Tesselate(geometry geom);
![]() | |
ST_Tesselate is deprecated as of 3.5.0. Use CG_Tesselate instead. |
Takes as input a surface such a MULTI(POLYGON) or POLYHEDRALSURFACE and returns a TIN representation via the process of tessellation using triangles.
![]() | |
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. |
Доступність: 2.1.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_Tesselate — Perform surface Tessellation of a polygon or polyhedralsurface and returns as a TIN or collection of TINS
geometry CG_Tesselate(geometry geom);
Takes as input a surface such a MULTI(POLYGON) or POLYHEDRALSURFACE and returns a TIN representation via the process of tessellation using triangles.
![]() | |
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. |
Доступність: 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).
SELECT ST_GeomFromText('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)) )');
![]() Original Cube |
SELECT CG_Tesselate(ST_GeomFromText('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)) )'));
ST_AsText output: 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)))
![]() Tessellated Cube with triangles colored |
SELECT 'POLYGON (( 10 190, 10 70, 80 70, 80 130, 50 160, 120 160, 120 190, 10 190 ))'::geometry;
![]() Original polygon |
SELECT
CG_Tesselate('POLYGON (( 10 190, 10 70, 80 70, 80 130, 50 160, 120 160, 120 190, 10 190 ))'::geometry);
ST_AsText output TIN(((80 130,50 160,80 70,80 130)),((50 160,10 190,10 70,50 160)),
((80 70,50 160,10 70,80 70)),((120 160,120 190,50 160,120 160)),
((120 190,10 190,50 160,120 190)))
![]() Tessellated Polygon |
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. |
Доступність: 3.5.0
This method needs SFCGAL backend.
SELECT CG_Triangulate('POLYGON((0.0 0.0,1.0 0.0,1.0 1.0,0.0 1.0,0.0 0.0),(0.2 0.2,0.2 0.8,0.8 0.8,0.8 0.2,0.2 0.2))');
cg_triangulate
----------------
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)))
(1 row)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);
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).
SELECT CG_Visibility('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, 'POINT(91 87)'::geometry);SELECT CG_Visibility('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,'POINT(78.5 68)'::geometry, 'POINT(98.5 68)'::geometry);![]() Original polygon | ![]() Visibility from the point | ![]() Visibility from the segment |
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.
![]() Original polygon | ![]() Y-Monotone Partition (same example As CG_ApproxConvexPartition, CG_GreeneApproxConvexPartition and CG_OptimalConvexPartition) |
SELECT ST_AsText(CG_YMonotonePartition('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));
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)))
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.
SELECT ST_AsText(CG_StraightSkeletonPartition('POLYGON((0 0, 4 0, 2 2, 0 0))', true));
-- Result: MULTIPOLYGON(((0 0,2 0.83,2 2)),((4 0,2 0.83,0 0)),((2 2,2 0.83,4 0)))SELECT CG_StraightSkeletonPartition(ST_GeomFromText('POLYGON (( 190 190, 10 190, 10 10, 190 10, 190 20
, 160 30, 60 30, 60 130, 190 140, 190 190 ))')
, true );![]() Original polygon | ![]() Straight Skeleton Partition of polygon |
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.
SELECT ST_AsText(CG_3DBuffer('POINT(0 0 0)', 1, 8, 0));
-- Result: POLYHEDRALSURFACE Z (((0 0 1, 0.5 -0.5 0.71, 0 -0.71 0.71, 0 0 1)), ... )The following images were rendered pasting the output of the ST_AsX3D query into X3D Viewer.
SELECT string_agg('<Shape
>' || ST_AsX3D(cgbuffer3d_output) || '<Appearance>
<Material diffuseColor="0 0.8 0.2" specularColor="0 1 0"/>
</Appearance>
</Shape
>', '');![]() segments=32 (rounded buffer)
SELECT CG_3DBuffer(ST_GeomFromText('POINT(100 90)'), 50,32,0);
| ![]() 5 segments rounded
SELECT CG_3DBuffer(
ST_GeomFromText('POINT(100 90)'),
50,5,0);
|
![]() 32 segments, round
SELECT CG_3DBuffer(
ST_GeomFromText(
'LINESTRING(50 50,150 150,150 50)'
),
10,32,0);
| ![]() 32 segments, square
SELECT CG_3DBuffer(
ST_GeomFromText(
'LINESTRING(50 50,150 150,150 50)'
),
10,32,2);
|
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.
SELECT ST_AsText(CG_Rotate('LINESTRING(1 0, 0 1)', pi()/2));
-- Result: LINESTRING(0 1, -1 0)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.
SELECT ST_AsText(CG_2DRotate('POINT(1 0)', pi()/2, 1, 1));
-- Result: POINT(2 1)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.
SELECT ST_AsText(CG_3DRotate('POINT(1 0 0)', pi()/2, 0, 0, 1));
-- Result: POINT(0 1 0)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.
SELECT ST_AsText(CG_RotateX('POINT(0 1 0)', pi()/2));
-- Result: POINT(0 0 1)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.
SELECT ST_AsText(CG_RotateY('POINT(1 0 0)', pi()/2));
-- Result: POINT(0 0 -1)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.
SELECT ST_AsText(CG_RotateZ('POINT(1 0 0)', pi()/2));
-- Result: POINT(0 1 0)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.
SELECT ST_AsText(CG_Scale('LINESTRING(1 1, 2 2)', 2));
-- Result: LINESTRING(2 2, 4 4)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.
SELECT ST_AsText(CG_3DScale('POINT(1 1 1)', 2, 3, 4));
-- Result: POINT(2 3 4)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.
SELECT ST_AsText(CG_3DScaleAroundCenter('POINT(2 2 2)', 0.5, 0.5, 0.5, 1, 1, 1));
-- Result: POINT(1.5 1.5 1.5)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.
SELECT ST_AsText(CG_Translate('LINESTRING(1 1, 2 2)', 1, -1));
-- Result: LINESTRING(2 0, 3 1)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.
SELECT ST_AsText(CG_3DTranslate('POINT(1 1 1)', 1, -1, 2));
-- Result: POINT(2 0 3)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.
geomInput geometry
thresholdMaximum distance threshold (in geometry unit) for simplification. The higher this value, the more simplified the resulting geometry will be.
preserveTopologyIf 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.
Returns a simplified geometry with preserved Z and M values.
-- Simplify a polygon with a threshold of 0.5
SELECT ST_AsText(CG_Simplify(ST_GeomFromText('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));
-- Simplify a 3D terrain geometry while preserving topology and Z values
SELECT ST_AsText(CG_Simplify(ST_GeomFromText('LINESTRING Z(0 0 0, 0 1 1, 0.1 1 1, 0.2 1 1, 0.3 1 1, 1 1 2)'), 0.2, true));
-- Simplify a geometry with both Z and M values
SELECT ST_AsText(CG_Simplify(ST_GeomFromText('LINESTRING ZM(0 0 0 1, 0 1 1 2, 0.1 1 1 3, 0.2 1 1 4, 0.3 1 1 5, 1 1 2 6)'), 0.2));
-- Simplify two geometry together preserving Z and M values, without topology
SELECT ST_AsText(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));
-- Simplify two geometry together preserving Z and M values, with topology
SELECT ST_AsText(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));
WITH depts_pds 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 FROM depts_pds;

Originals geometries
WITH depts_pds 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 (ST_Dump(CG_Simplify(geom, 0.5, true))).geom FROM depts_pds;

Simplification with 0.5 and topology preserved
WITH depts_pds 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 (ST_Dump(CG_Simplify(geom, 0.5, false))).geom FROM depts_pds;

Simplification with 0.5 without topology preservation
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 can have values from 0 to infinity. Smaller relative_alpha values result in simpler outputs, but they are less accurate representations of the original input.
The relative_offset parameter controls the tightness of the result. It can 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.
SELECT CG_3DAlphaWrapping('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,10);

Alpha wrapping of a MultiPoint (same example As CG_OptimalAlphaShape)
SELECT CG_3DAlphaWrapping('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,14);

Alpha wrapping of a MultiPoint (same example as ST_ConcaveHull)

Effect of the relative_alpha parameter with values 5, 10 and 20. A value of 5 results in a coarse output. Increasing the parameter up to 20 significantly improves the precision and granularity of the result.
Типи та функції топології PostGIS використовуються для управління топологічними об'єктами, такими як грані, ребра та вузли.
Презентація Сандро Сантіллі на конференції PostGIS Day Paris 2011 містить хороший огляд топології PostGIS та її перспектив Топологія з PostGIS 2.0, презентація.
Вінсент Пікавет надає хороший огляд та узагальнення того, що таке топологія, як вона використовується, а також різних інструментів FOSS4G, які її підтримують, у PostGIS Topology PGConf EU 2012.
Прикладом топологічної бази даних ГІС є база даних US Census Topologically Integrated Geographic Encoding and Referencing System (TIGER) (Топологічно інтегрована система географічного кодування та посилань перепису населення США). Якщо ви хочете поекспериментувати з топологією PostGIS і вам потрібні дані, перегляньте Topology_Load_Tiger.
Модуль топології PostGIS існував у попередніх версіях PostGIS, але ніколи не був частиною офіційної документації PostGIS. У PostGIS 2.0.0 проводиться основне очищення з метою видалення всіх застарілих функцій, виправлення відомих проблем з користуванням, покращення документації щодо можливостей та функцій, додавання нових функцій та вдосконалення для більшої відповідності стандартам SQL-MM.
Детальнішу інформацію про цей проект можна знайти за посиланням PostGIS Topology Wiki
Усі функції та таблиці, пов'язані з цим модулем, встановлюються у схемі під назвою topology.
Функції, які визначені в стандарті SQL/MM, мають префікс ST_, а функції, специфічні для PostGIS, не мають префікса.
Підтримка топології вбудована за замовчуванням, починаючи з PostGIS 2.0, і може бути вимкнена, вказавши опцію --without-topology під час компіляції, як описано в Chapter 2, Встановлення PostGIS
У цьому розділі перелічено типи даних PostgreSQL, встановлені PostGIS Topology. Зверніть увагу, що ми описуємо поведінку цих типів при перетворенні, що є дуже важливим, особливо при розробці власних функцій.
ValidateTopology.getfaceedges_returntype — Комбінований тип, що складається з порядкового номера та номера ребра.
Композитний тип, що складається з порядкового номера та номера ребра. Це тип повернення для функцій ST_GetFaceEdges та GetNodeEdges.
sequence integer: Посилається на топологію, визначену в таблиці topology.topology, яка визначає схему топології та srid.
edge integer: ідентифікатор ребра.
TopoGeometry — Композитний тип, що представляє топологічно визначену геометрію.
Композитний тип, що посилається на геометрію топології в конкретному шарі топології, має конкретний тип і конкретний ідентифікатор. Елементами TopoGeometry є властивості: topology_id, layer_id, id integer, type integer.
topology_id integer: Посилається на топологію, визначену в таблиці topology.topology, яка визначає схему топології та srid.
layer_id integer: layer_id у таблиці шарів, до якої належить TopoGeometry. Поєднання topology_id та layer_id забезпечує унікальне посилання в таблиці topology.layers.
id integer: id — це автоматично згенерований порядковий номер, який однозначно визначає топогеометрію у відповідному шарі топології.
type integer від 1 до 4, що визначає тип геометрії: 1:[multi]point, 2:[multi]line, 3:[multi]poly, 4:collection
У цьому розділі перелічено автоматичні та явні приведення типів, дозволені для цього типу даних
| Приведення типів в | Поведінка |
| geometry | автоматичне |
validatetopology_returntype — Комбінований тип, що складається з повідомлення про помилку та ідентифікаторів id1 та id2 для позначення місця помилки. Це тип повернення для ValidateTopology.
Композитний тип, що складається з повідомлення про помилку та двох цілих чисел. Функція ValidateTopology повертає набір таких елементів для позначення помилок перевірки, а також ідентифікатори id1 та id2 для позначення ідентифікаторів об'єктів топології, пов'язаних із помилкою.
error є varchar: Позначає тип помилки.
Поточні описи помилок: збіжні вузли, перетин ребер з вузлами, не прості ребра, невідповідність геометрії кінцевих вузлів ребер, невідповідність геометрії початкових вузлів ребер, перекриття граней, грань всередині грані,
id1 integer позначає ідентифікатор ребра / грані / вузлів, що містить помилку.
id2 integer: для помилок, що стосуються 2 об'єктів, позначає вторинний край / або вузол
У цьому розділі перелічено домени PostgreSQL, встановлені PostGIS Topology. Домени можна використовувати як типи об'єктів, наприклад, як об'єкти, що повертаються функціями, або стовпці таблиць. Відмінність домену від типу полягає в тому, що домен — це існуючий тип, до якого прив'язано обмеження перевірки.
TopoElement — Масив із 2 цілих чисел, що зазвичай використовується для ідентифікації компонента TopoGeometry.
Масив із 2 цілих чисел, що використовується для представлення одного компонента простого або ієрархічного TopoGeometry.
У випадку простої TopoGeometry перший елемент масиву представляє ідентифікатор топологічного примітиву, а другий елемент представляє його тип (1:вузол, 2:ребро, 3:грань). У випадку ієрархічної TopoGeometry перший елемент масиву представляє ідентифікатор дочірньої TopoGeometry, а другий елемент представляє ідентифікатор її шару.
![]() | |
Для будь-якої ієрархічної TopoGeometry всі дочірні елементи TopoGeometry будуть походити з того самого дочірнього шару, як зазначено в записі topology.layer для шару TopoGeometry, що визначається. |
SELECT te[1] AS id, te[2] AS type FROM
( SELECT ARRAY[1,2]::topology.topoelement AS te ) f;
id | type
----+------
1 | 2
SELECT ARRAY[1,2]::topology.topoelement;
te
-------
{1,2}
--Example of what happens when you try to case a 3 element array to topoelement
-- NOTE: topoement has to be a 2 element array so fails dimension check
SELECT ARRAY[1,2,3]::topology.topoelement;
ERROR: value for domain topology.topoelement violates check constraint "dimensions"
TopoElementArray — Масив об'єктів TopoElement.
Масив з 1 або більше об'єктів TopoElement, який зазвичай використовується для передачі компонентів об'єктів TopoGeometry.
SELECT '{{1,2},{4,3}}'::topology.topoelementarray As tea;
tea
-------
{{1,2},{4,3}}
-- more verbose equivalent --
SELECT ARRAY[ARRAY[1,2], ARRAY[4,3]]::topology.topoelementarray As tea;
tea
-------
{{1,2},{4,3}}
--using the array agg function packaged with topology --
SELECT topology.TopoElementArray_Agg(ARRAY[e,t]) As tea
FROM generate_series(1,4) As e CROSS JOIN generate_series(1,3) As t;
tea
--------------------------------------------------------------------------
{{1,1},{1,2},{1,3},{2,1},{2,2},{2,3},{3,1},{3,2},{3,3},{4,1},{4,2},{4,3}}
SELECT '{{1,2,4},{3,4,5}}'::topology.topoelementarray As tea;
ERROR: value for domain topology.topoelementarray violates check constraint "dimensions"
У цьому розділі перелічено функції топології для створення нових схем топології, перевірки топологій та управління стовпцями TopoGeometry
table_name у схемі schema_name та скасовує реєстрацію стовпців у таблиці topology.layer.AddTopoGeometryColumn — Додає стовпець топогеометрії до існуючої таблиці, реєструє цей новий стовпець як шар у 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);
Кожен об'єкт TopoGeometry належить до певного шару певної топології. Перед створенням об'єкта TopoGeometry потрібно створити його TopologyLayer. Топологічний шар — це зв'язок таблиці об'єктів з топологією. Він також містить інформацію про тип та ієрархію. Ми створюємо шар за допомогою функції AddTopoGeometryColumn():
Ця функція додасть запитуваний стовпець до таблиці та додасть запис до таблиці topology.layer з усією наданою інформацією.
Якщо ви не вкажете [child_layer] (або встановите його значення NULL), цей шар буде містити базові топогеометрії (складені з примітивних топологічних елементів). В іншому випадку цей шар буде містити ієрархічні топогеометрії (складені з топогеометрій з child_layer).
Після створення шару (його ідентифікатор повертається функцією AddTopoGeometryColumn) ви готові до побудови об'єктів TopoGeometry в ньому
Дійсні feature_types: POINT, MULTIPOINT, LINE, MULTILINE, POLYGON, MULTIPOLYGON, COLLECTION
Доступність: 1.1
-- Note for this example we created our new table in the ma_topo schema
-- though we could have created it in a different schema -- in which case topology_name and schema_name would be different
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');CREATE SCHEMA ri;
CREATE TABLE ri.roads(gid serial PRIMARY KEY, road_name text);
SELECT topology.AddTopoGeometryColumn('ri_topo', 'ri', 'roads', 'topo', 'LINE');
DropTopoGeometryColumn, toTopoGeom, CreateTopology, CreateTopoGeom
RenameTopoGeometryColumn — Перейменовує стовпець топогеометрії
topology.layer RenameTopoGeometryColumn(regclass layer_table, name feature_column, name new_name);
Ця функція змінює назву існуючого стовпця TopoGeometry, забезпечуючи відповідне оновлення метаданих про нього.
Доступність: 3.4.0
SELECT topology.RenameTopoGeometryColumn('public.parcels', 'topogeom', 'tgeom');
DropTopology — Використовуйте з обережністю: видаляє схему топології та її посилання з таблиці topology.topology, а також посилання на таблиці в цій схемі з таблиці geometry_columns.
integer DropTopology(varchar topology_schema_name);
Видаляє схему топології та її посилання з таблиці topology.topology, а також посилання на таблиці в цій схемі з таблиці geometry_columns. Цю функцію слід ВИКОРИСТОВУВАТИ З ОБЕРЕЖНІСТЮ, оскільки вона може знищити важливі для вас дані. Якщо схема не існує, вона просто видаляє записи посилань на вказану схему.
Доступність: 1.1
Cascade видаляє схему ma_topo та всі посилання на неї в topology.topology та geometry_columns.
SELECT topology.DropTopology('ma_topo');RenameTopology — Перейменовує топологію
varchar RenameTopology(varchar old_name, varchar new_name);
Перейменовує схему топології, оновлюючи запис метаданих у таблиці topology.topology.
Доступність: 3.4.0
Перейменуйте топологію з topo_stage на topo_prod.
SELECT topology.RenameTopology('topo_stage', 'topo_prod');DropTopoGeometryColumn — Видаляє стовпець топогеометрії з таблиці з назвою table_name у схемі schema_name та скасовує реєстрацію стовпців у таблиці topology.layer.
text DropTopoGeometryColumn(varchar schema_name, varchar table_name, varchar column_name);
Видаляє стовпець топогеометрії з таблиці з назвою table_name у схемі schema_name та скасовує реєстрацію стовпців у таблиці topology.layer. Повертає підсумок стану видалення. ПРИМІТКА: перед видаленням спочатку встановлює всі значення на NULL, щоб обійти перевірки цілісності посилань.
Доступність: 1.1
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 );
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.
Availability: 3.6.1
Fix all topology columns
SELECT topology.FixCorruptTopoGeometryColumn(schema_name, table_name, feature_column)
FROM topology.layer;
Populate_Topology_Layer — Додає відсутні записи до таблиці topology.layer, зчитуючи метадані з таблиць topo.
setof record Populate_Topology_Layer();
Додає відсутні записи до таблиці topology.layer, перевіряючи обмеження топології в таблицях. Ця функція корисна для виправлення записів у каталозі топології після відновлення схем із даними топології.
Повертає список створених записів. Повертаються стовпці schema_name, table_name, feature_column.
Доступність: 2.3.0
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');
-- this will return no records because this feature is already registered
SELECT *
FROM topology.Populate_Topology_Layer();
-- let's rebuild
TRUNCATE TABLE topology.layer;
SELECT *
FROM topology.Populate_Topology_Layer();
SELECT topology_id,layer_id, schema_name As sn, table_name As tn, feature_column As fc
FROM topology.layer;
schema_name | table_name | feature_column
-------------+------------+----------------
strk | parcels | topo
(1 row)
topology_id | layer_id | sn | tn | fc
-------------+----------+------+---------+------
2 | 2 | strk | parcels | topo
(1 row)TopologySummary — Бере ім'я топології та надає підсумкові суми типів об'єктів у топології.
text TopologySummary(varchar topology_schema_name);
Бере ім'я топології та надає підсумкові суми типів об'єктів у топології.
Доступність: 2.0.0
SELECT topology.topologysummary('city_data');
topologysummary
--------------------------------------------------------
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.featureValidateTopology — Повертає набір об'єктів validated_topology_returntype, що детально описують проблеми з топологією.
setof validatetopology_returntype ValidateTopology(varchar toponame, geometry bbox);
Повертає набір об'єктів validatetopology_returntype, що детально описують проблеми з топологією, за бажанням обмежуючи перевірку областю, вказаною параметром bbox.
Нижче наведено перелік можливих помилок, їх значення та значення повернених ідентифікаторів:
| Error | id1 | id2 | Meaning |
|---|---|---|---|
| coincident nodes | Ідентифікатор першого вузла. | Ідентифікатор другого вузла. | Два вузли мають однакову геометрію. |
| edge crosses node | Ідентифікатор ребра. | Ідентифікатор вузла. | Ребро має вузол у своїй внутрішній частині. Див. ST_Relate. |
| invalid edge | Ідентифікатор ребра. | Геометрія ребра недійсна. Див. ST_IsValid. | |
| edge not simple | Ідентифікатор ребра. | Геометрія ребра має самоперетини. Див. ST_IsSimple. | |
| edge crosses edge | Ідентифікатор першого ребра. | Ідентифікатор другого ребра. | Дві ребра мають внутрішнє перетин. Див. ST_Relate. |
| edge start node geometry mismatch | Ідентифікатор ребра. | Ідентифікатор вказаного початкового вузла. | Геометрія вузла, вказаного як початковий вузол для ребра, не відповідає першій точці геометрії ребра. Див. ST_StartPoint. |
| edge end node geometry mismatch | Ідентифікатор ребра. | Ідентифікатор вказаного кінцевого вузла. | Геометрія вузла, вказаного як кінцевий вузол для ребра, не відповідає останній точці геометрії ребра. Див. ST_EndPoint. |
| face without edges | Ідентифікатор "осиротілої" грані. | Жодне ребро не повідомляє про наявність грані з будь-якого боку (left_face, right_face). | |
| face has no rings | Ідентифікатор частково визначеної грані. | Ребра, що утворюють грань на своїх боках, не утворюють кільця. | |
| face has wrong mbr | Ідентифікатор грані з неправильним кешем mbr. | Мінімальна обмежувальна рамка грані не збігається з мінімальною обмежувальною рамкою сукупності ребер, що утворюють грань по своїх сторонах. | |
| hole not in advertised face | Підписаний ідентифікатор ребра, що ідентифікує кільце. Див. GetRingEdges. | Кільце ребер, що утворюють грань на зовнішній поверхні, міститься в іншій грані. | |
| not-isolated node has not- containing_face | Ідентифікатор неправильно визначеного вузла. | Вузол, який повідомляється як такий, що знаходиться на межі одного або декількох ребер, вказує на вмістну грань. | |
| isolated node has containing_face | Ідентифікатор неправильно визначеного вузла. | Вузол, який не вказаний як такий, що знаходиться на межі будь-яких ребер, не має позначення грані, що його містить. | |
| isolated node has wrong containing_face | Ідентифікатор неправильно представленого вузла. | Вузол, який не вказаний як такий, що знаходиться на межі будь-яких ребер, вказує на грань, що його містить, яка не є фактичною гранью, що його містить. Див. GetFaceContainingPoint. | |
| invalid next_right_edge | Ідентифікатор неправильно представленого ребра. | Підписаний ідентифікатор ребра, яке слід вказати як наступне праве ребро. | Ребро, позначене як наступне ребро, на яке натрапляєш, рухаючись праворуч від ребра, є неправильним. |
| invalid next_left_edge | Ідентифікатор неправильно представленого ребра. | Підписаний ідентифікатор ребра, яке слід вказати як наступне ліве ребро. | Ребро, вказане як наступне ребро, на яке натрапляєш, рухаючись лівою стороною ребра, є неправильним. |
| mixed face labeling in ring | Підписаний ідентифікатор ребра, що ідентифікує кільце. Див. GetRingEdges. | Ребра в кільці позначають конфліктуючі грані на стороні ходіння. Це також називається "конфліктом розташування сторін". | |
| non-closed ring | Підписаний ідентифікатор ребра, що ідентифікує кільце. Див. GetRingEdges. | Кільце ребер, утворене атрибутами next_left_edge/next_right_edge, починається і закінчується на різних вузлах. | |
| face has multiple shells | Ідентифікатор грані, що є предметом суперечки. | Підписаний ідентифікатор ребра, що ідентифікує кільце. Див. GetRingEdges. | Більше ніж одне кільце ребер вказує на ту саму грань всередині. |
Доступність: 1.0.0
Покращено: 2.0.0 більш ефективне виявлення перетину ребер та виправлення помилок, що були присутні в попередніх версіях.
Змінено: 2.2.0 значення id1 та id2 були поміняні місцями для "перетину ребер вузлом" з метою узгодження з описом помилки.
Змінено: 3.2.0 додано опційний параметр bbox, виконується перевірка маркування ребер та з'єднання ребер.
SELECT * FROM topology.ValidateTopology('ma_topo');
error | id1 | id2
-------------------+-----+-----
face without edges | 1 |
ValidateTopologyRelation — Повертає інформацію про недійсні записи топологічних відносин
setof record ValidateTopologyRelation(varchar toponame);
Повертає набір записів, що містять інформацію про недійсні елементи в таблиці відносин топології.
Доступність: 3.2.0
ValidateTopologyPrecision — Повертає неточні вершини в топології.
geometry ValidateTopologyPrecision(name toponame, geometry bbox, float8 gridSize);
Повертає всі вершини, які не округлені до топології або задані gridSize як точкова геометрія, опціонально обмежуючи перевірку областю, заданою параметром bbox.
Доступність: 3.6.0
SELECT ST_AsEWKT(g) FROM
topology.ValidateTopologyPrecision(
'city_data',
gridSize =
> 2,
bbox =
> ST_MakeEnvelope(0,0,20,20)
) g;
st_asewkt
----------------------
MULTIPOINT(9 6,9 14)
(1 row)
MakeTopologyPrecise — Прив'язати вершини топології до сітки з високою точністю.
void MakeTopologyPrecise(name toponame, geometry bbox, float8 gridSize);
Прив'язує всі вершини топології до сітки точності топології або до сітки, розмір якої вказано параметром gridSize, за бажанням обмежуючи операцію об'єктами, що перетинають область, вказану параметром bbox.
![]() | |
При використанні функції "Прив'язати" топологія може стати недійсною, тому рекомендується перевірити результат операції за допомогою ValidateTopology. |
Доступність: 3.6.0
SELECT topology.MakeTopologyPrecise(
'city_data',
gridSize =
> 2
);
maketopologyprecise
---------------------
(1 row)
FindTopology — Повертає запис топології різними способами.
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);
Приймає ідентифікатор топології або ідентифікатор об'єкта, пов'язаного з топологією, і повертає запис топології.
Доступність: 3.2.0
SELECT name(findTopology('features.land_parcels', 'feature'));
name
-----------
city_data
(1 row)
FindLayer — Повертає запис topology.layer різними способами.
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);
Приймає ідентифікатор шару або ідентифікатор об'єкта, пов'язаного з топологією, і повертає запис topology.layer.
Доступність: 3.2.0
SELECT layer_id(findLayer('features.land_parcels', 'feature'));
layer_id
----------
1
(1 row)
TotalTopologySize — Загальний обсяг дискового простору, використовуваний зазначеною топологією, включаючи всі індекси та дані TOAST.
int8 TotalTopologySize(name toponame);
Приймає ім'я топології та надає загальний обсяг дискового простору, зайнятого всіма її таблицями, включаючи індекси та дані TOAST.
Доступність: 3.6.0
SELECT topology.topologysummary('city_data');
topologysummary
--------------------------------------------------------
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.featureUpgradeTopology — Оновлює вказану топологію для підтримки великих ідентифікаторів (int8) для топології та примітивних ідентифікаторів.
void UpgradeTopology(name toponame);
Бере ім'я топології та оновлює його для підтримки великих ідентифікаторів (int8) для топології та примітивних ідентифікаторів. Функція оновлює наступне: - face (стовпець face_id з int4 до int8, face_id_seq з int4 до int8) - node (стовпець node_id з int4 до int8, столпець containing_face з int4 до int8, node_id_seq з int4 до int8) - edge_data (стовпець edge_id з int4 до int8, edge_data_edge_id_seq з int4 до int8, стовпці left_face та right_face з int4 до int8, стовпці start_node та end_node з int4 до int8, стовпці next_left_edge та next_right_edge з int4 до int8) - relation (стовпець topogeo_id з int4 до int8, element_id з int4 до int8) - topology (стовпець useslargeids встановлено на true)
Доступність: 3.6.0
SELECT topology.upgradetopology('city_data');
У цьому розділі розглядається управління статистикою бази даних під час побудови топології.
Додавання елементів до топології викликає багато запитів до бази даних для пошуку існуючих ребер, які будуть розділені, додавання вузлів та оновлення ребер, які будуть з'єднані з новою лінією. З цієї причини корисно, щоб статистичні дані про дані в таблицях топології були актуальними.
Функції заповнення та редагування топології PostGIS не оновлюють статистику автоматично, оскільки оновлення статистики після кожної зміни в топології було б надмірним, тому це обов'язок того, хто викликає функцію.
![]() | |
Статистика, оновлена за допомогою autovacuum, НЕ буде видима для транзакцій, які були запущені до завершення процесу autovacuum, тому для використання оновленої статистики довготривалі транзакції повинні самостійно виконати ANALYZE. |
У цьому розділі описано функції топології для створення нових топологій.
CreateTopology — Створює нову схему топології та реєструє її в таблиці topology.topology.
integer CreateTopology(name topology_schema_name, integer srid, double precision prec, boolean hasz, integer topoid, boolean useslargeids);
Створює нову схему топології з іменем topology_name і реєструє її в таблиці topology.topology. Топології повинні мати унікальні імена. Таблиці топологій (edge_data, face, node та relation створюються в схемі. Повертає ідентифікатор топології.
srid — це SRID просторової системи координат для топології. Якщо SRID не вказано, за замовчуванням використовується значення -1 (невідомо).
Допуск prec вимірюється в одиницях просторової системи відліку. За замовчуванням допуск дорівнює 0.
hasz за замовчуванням має значення false, якщо не вказано інше.
topoid необов'язковий явний ідентифікатор (дозволяє детерміновано присвоювати ідентифікатори топології, повинен бути унікальним)
useslargeids необов'язковий, за замовчуванням false. Якщо true, то топологія буде створена для підтримки великих ідентифікаторів (int8) для топології та примітивних ідентифікаторів.
Це схоже на SQL/MM ST_InitTopoGeo, але має більше функціональних можливостей.
Доступність: 1.1
Покращено: у версії 2.0 додано прийняття підпису hasZ
Створіть схему топології під назвою ma_topo, яка зберігає ребра та вузли в системі координат Massachusetts State Plane-meters (SRID = 26986). Допуск становить 0,5 метра, оскільки система просторових координат базується на метрах.
SELECT topology.CreateTopology('ma_topo', 26986, 0.5);Створіть топологію для Род-Айленду під назвою ri_topo у системі просторових координат State Plane-feet (SRID = 3438)
SELECT topology.CreateTopology('ri_topo', 3438) AS topoid;
topoid
------
2CopyTopology — Створює копію топології (вузлів, ребер, граней, шарів і TopoGeometries) у новій схемі
integer CopyTopology(varchar existing_topology_name, varchar new_name);
Створює нову топологію з назвою new_name, з SRID і точністю, скопійованими з existing_topology_name. Вузли, ребра та грані в existing_topology_name копіюються в нову топологію, а також шари та пов'язані з ними TopoGeometries.
![]() | |
Нові рядки в таблиці |
Доступність: 2.0.0
Створіть резервну копію топології під назвою ma_topo.
SELECT topology.CopyTopology('ma_topo', 'ma_topo_backup');ST_InitTopoGeo — Створює нову схему топології та реєструє її в таблиці topology.topology.
text ST_InitTopoGeo(varchar topology_schema_name);
Це еквівалент SQL-MM для CreateTopology. У ньому відсутні параметри для просторової системи координат і допуску. Він повертає текстовий опис створення топології замість ідентифікатора топології.
Доступність: 1.1
This method implements the SQL/MM specification. SQL-MM 3 Topo-Geo and Topo-Net 3: Routine Details: X.3.17
SELECT topology.ST_InitTopoGeo('topo_schema_to_create') AS topocreation;
astopocreation
------------------------------------------------------------
Topology-Geometry 'topo_schema_to_create' (id:7) created.
ST_CreateTopoGeo — Додає колекцію геометрій до заданої порожньої топології та повертає повідомлення з детальною інформацією про успішність операції.
text ST_CreateTopoGeo(varchar atopology, geometry acollection);
Додає колекцію геометрій до заданої порожньої топології та повертає повідомлення з детальною інформацією про успішність виконання.
Корисно для заповнення порожньої топології.
Доступність: 2.0
This method implements the SQL/MM specification. SQL-MM: Topo-Geo and Topo-Net 3: Routine Details -- X.3.18
-- Populate topology --
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)
);
st_createtopogeo
----------------------------
Topology ri_topo populated
-- create tables and topo geometries --
CREATE TABLE ri.roads(gid serial PRIMARY KEY, road_name text);
SELECT topology.AddTopoGeometryColumn('ri_topo', 'ri', 'roads', 'topo', 'LINE');
TopoGeo_AddPoint — Додає точку до існуючої топології, використовуючи допуск і, можливо, розділяючи існуюче ребро.
bigint TopoGeo_AddPoint(varchar atopology, geometry apoint, float8 tolerance);
Додає точку до існуючої топології та повертає її ідентифікатор. Задана точка буде прив'язана до існуючих вузлів або ребер в межах заданого допуску. Існуюче ребро може бути розділене прив'язаною точкою.
Доступність: 2.0.0
TopoGeo_AddLineString — Додає лінійний елемент до існуючої топології з використанням допуску та можливого розділення існуючих ребер/граней.
SETOF bigint TopoGeo_AddLineString(varchar atopology, geometry aline, float8 tolerance);
Додає лінійний рядок до існуючої топології та повертає набір підписаних ідентифікаторів ребер, що його утворюють (негативні ідентифікатори означають, що ребро йде в протилежному напрямку від вхідного лінійного рядка). Задана лінія буде прив'язана до існуючих вузлів або ребер в межах заданого допуску. Існуючі ребра та грані можуть бути розділені лінією. Можуть бути додані нові вузли та грані.
![]() | |
Оновлення статистики про топології, що завантажуються за допомогою цієї функції, залежить від виклику, див. maintaining statistics during topology editing and population. |
Доступність: 2.0.0
Покращено: у версії 3.2.0 додано підтримку повернення підписаного ідентифікатора.
TopoGeo_AddPolygon — Додає полігон до існуючої топології, використовуючи допуск і, можливо, розділяючи існуючі ребра/грані. Повертає ідентифікатори граней.
SETOF bigint TopoGeo_AddPolygon(varchar atopology, geometry apoly, float8 tolerance);
Додає полігон до існуючої топології та повертає набір ідентифікаторів граней, що його утворюють. Межа заданого полігону буде прив'язана до існуючих вузлів або ребер з урахуванням заданого допуску. Існуючі ребра та грані можуть бути розділені межею нового полігону.
![]() | |
Оновлення статистики про топології, що завантажуються за допомогою цієї функції, залежить від виклику, див. maintaining statistics during topology editing and population. |
Доступність: 2.0.0
TopoGeo_LoadGeometry — Завантажте геометрію в існуючу топологію, при необхідності вирівнюючи та розділяючи.
void TopoGeo_LoadGeometry(varchar atopology, geometry ageom, float8 tolerance);
Завантажує геометрію в існуючу топологію. Задана геометрія буде прив'язана до існуючих вузлів або ребер в межах заданого допуску. Існуючі ребра та грані можуть бути розділені в результаті завантаження.
![]() | |
Оновлення статистики про топології, що завантажуються за допомогою цієї функції, залежить від виклику, див. maintaining statistics during topology editing and population. |
Доступність: 3.5.0
Цей розділ охоплює функції топології для додавання, переміщення, видалення та розділення ребер, граней та вузлів. Усі ці функції визначені стандартом ISO SQL/MM.
alinestring, до топології, що з'єднує два існуючі ізольовані вузли anode та anothernode, і повертає ідентифікатор нового ребра.apoint існує як вузол, виникає помилка. Повертає опис переміщення.ST_AddIsoNode — Додає ізольований вузол до грані в топології та повертає ідентифікатор нового вузла. Якщо грань має нульове значення, вузол все одно створюється.
bigint ST_AddIsoNode(varchar atopology, bigint aface, geometry apoint);
Додає ізольований вузол із точкою розташування apoint до існуючої грані з ідентифікатором грані aface до топології atopology і повертає ідентифікатор нового вузла.
Якщо система просторових координат (srid) геометрії точки не збігається з топологією, apoint не є геометрією точки, точка є нульовою або точка перетинає існуючу ребро (навіть на межі), то виникає виняток. Якщо точка вже існує як вузол, виникає виняток.
Якщо aface не дорівнює нулю, а apoint не знаходиться в межах грані, то генерується виняток.
Доступність: 1.1
This method implements the SQL/MM specification. SQL-MM: Топо-мережеві процедури: X+1.3.1
ST_AddIsoEdge — Додає ізольоване ребро, визначене геометрією alinestring, до топології, що з'єднує два існуючі ізольовані вузли anode та anothernode, і повертає ідентифікатор нового ребра.
bigint ST_AddIsoEdge(varchar atopology, bigint anode, bigint anothernode, geometry alinestring);
Додає ізольоване ребро, визначене геометрією alinestring, до топології, що з'єднує два існуючі ізольовані вузли anode та anothernode, і повертає ідентифікатор нового ребра.
Якщо система просторових посилань (srid) геометрії alinestring не збігається з топологією, будь-який з вхідних аргументів має значення null, або вузли містяться в більш ніж одній грані, або вузли є початковими або кінцевими вузлами існуючої ребра, то генерується виняток.
Якщо alinestring не знаходиться в межах грані, до якої належать anode та anothernode, то генерується виняток.
Якщо anode та anothernode не є початковою та кінцевою точками alinestring, то генерується виняток.
Доступність: 1.1
This method implements the SQL/MM specification. SQL-MM: Topo-Geo та Topo-Net 3: Деталі процедури: X.3
ST_AddEdgeNewFaces — Додайте нову ребро і, якщо при цьому розділяється грань, видаліть оригінальну грань і замініть її двома новими.
bigint ST_AddEdgeNewFaces(varchar atopology, bigint anode, bigint anothernode, geometry acurve);
Додайте нове ребро і, якщо при цьому розділяється грань, видаліть оригінальну грань і замініть її двома новими гранями. Повертає ідентифікатор новододаного ребра.
Відповідно оновлює всі існуючі з'єднані ребра та взаємозв'язки.
Якщо будь-які аргументи мають нульове значення, вказані вузли невідомі (повинні вже існувати в таблиці node схеми топології) , acurve не є LINESTRING, anode та anothernode не є початковою та кінцевою точками acurve, тоді генерується помилка.
Якщо система просторових посилань (srid) геометрії acurve не збігається з топологією, виникає виняток.
Доступність: 2.0
This method implements the SQL/MM specification. SQL-MM: Topo-Geo та Topo-Net 3: Деталі процедури: X.3.12
ST_AddEdgeModFace — Додайте нову кромку і, якщо при цьому розділяється грань, змініть вихідну грань і додайте нову.
bigint ST_AddEdgeModFace(varchar atopology, bigint anode, bigint anothernode, geometry acurve);
Додайте нове ребро і, якщо це призведе до розділення грані, змініть оригінальну грань і додайте нову.
![]() | |
Якщо можливо, нова грань буде створена зліва від нового ребра. Це буде неможливо, якщо грань зліва повинна бути необмеженою. |
Повертає ідентифікатор новододаного ребра.
Відповідно оновлює всі існуючі з'єднані ребра та взаємозв'язки.
Якщо будь-які аргументи мають нульове значення, вказані вузли невідомі (повинні вже існувати в таблиці node схеми топології) , acurve не є LINESTRING, anode та anothernode не є початковою та кінцевою точками acurve, тоді генерується помилка.
Якщо система просторових посилань (srid) геометрії acurve не збігається з топологією, виникає виняток.
Доступність: 2.0
This method implements the SQL/MM specification. SQL-MM: Topo-Geo та Topo-Net 3: Деталі процедури: X.3.13
ST_RemEdgeNewFace — Видаляє ребро і, якщо видалене ребро розділяло дві грані, видаляє оригінальні грані та замінює їх новою гранею.
bigint ST_RemEdgeNewFace(varchar atopology, bigint anedge);
Видаляє ребро і, якщо видалене ребро розділяло дві грані, видаляє оригінальні грані та замінює їх новою гранею.
Повертає ідентифікатор новоствореної грані або NULL, якщо нова грань не створена. Нова грань не створюється, якщо видалена ребро є висячою, ізольованою або обмеженою гранею всесвіту (що може призвести до затоплення всесвіту гранею з іншого боку).
Відповідно оновлює всі існуючі з'єднані ребра та взаємозв'язки.
Відмовляється видаляти край, що бере участь у визначенні існуючої TopoGeometry. Відмовляється виправляти дві грані, якщо будь-яка TopoGeometry визначена тільки однією з них (а не іншою).
Якщо будь-які аргументи мають нульове значення, задана ребро невідома (повинна вже існувати в таблиці edge схеми топології), ім'я топології недійсне, то генерується помилка.
Доступність: 2.0
This method implements the SQL/MM specification. SQL-MM: Topo-Geo та Topo-Net 3: Деталі процедури: X.3.14
ST_RemEdgeModFace — Видаляє ребро, і якщо ребро розділяє дві грані, видаляє одну грань і модифікує іншу грань, щоб покрити простір обох.
bigint ST_RemEdgeModFace(varchar atopology, bigint anedge);
Видаляє ребро, і якщо видалене ребро розділяє дві грані, видаляє одну грань і модифікує іншу грань, щоб покрити простір обох. Переважно зберігає грань праворуч, щоб забезпечити узгодженість з ST_AddEdgeModFace. Повертає ідентифікатор грані, яка зберігається.
Відповідно оновлює всі існуючі з'єднані ребра та взаємозв'язки.
Відмовляється видаляти край, що бере участь у визначенні існуючої TopoGeometry. Відмовляється виправляти дві грані, якщо будь-яка TopoGeometry визначена тільки однією з них (а не іншою).
Якщо будь-які аргументи мають нульове значення, задана ребро невідома (повинна вже існувати в таблиці edge схеми топології), ім'я топології недійсне, то генерується помилка.
Доступність: 2.0
This method implements the SQL/MM specification. SQL-MM: Topo-Geo та Topo-Net 3: Деталі процедури: X.3.15
ST_ChangeEdgeGeom — Змінює форму ребра, не впливаючи на топологічну структуру.
text ST_ChangeEdgeGeom(varchar atopology, bigint anedge, geometry acurve);
Змінює форму ребра, не впливаючи на топологічну структуру.
Якщо будь-які аргументи мають значення null, задана ребро не існує в таблиці edge схеми топології, acurve не є LINESTRING, або модифікація змінить базову топологію, то буде видано помилку.
Якщо система просторових посилань (srid) геометрії acurve не збігається з топологією, виникає виняток.
Якщо новий acurve не є простим, то виникає помилка.
Якщо переміщення ребра зі старого положення в нове призведе до зіткнення з перешкодою, буде видано помилку.
Доступність: 1.1.0
Покращено: у версії 2.0.0 додано забезпечення топологічної узгодженості
This method implements the SQL/MM specification. SQL-MM: Topo-Geo та Topo-Net 3: Деталі рутинних операцій X.3.6
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 changedST_ModEdgeSplit — Розділіть ребро, створивши новий вузол уздовж існуючого ребра, змінивши оригінальне ребро та додавши нове.
bigint ST_ModEdgeSplit(varchar atopology, bigint anedge, geometry apoint);
Розділити ребро, створивши новий вузол уздовж існуючого ребра, змінивши оригінальне ребро та додавши нове ребро. Відповідно оновлює всі існуючі з'єднані ребра та відносини. Повертає ідентифікатор новододаного вузла.
Доступність: 1.1
Змінено: 2.0 — у попередніх версіях це було неправильно названо ST_ModEdgesSplit
This method implements the SQL/MM specification. SQL-MM: Topo-Geo та Topo-Net 3: Деталі процедури: X.3.9
-- Add an edge --
SELECT topology.AddEdge('ma_topo', ST_GeomFromText('LINESTRING(227592 893910, 227600 893910)', 26986) ) As edgeid;
-- edgeid-
3
-- Split the edge --
SELECT topology.ST_ModEdgeSplit('ma_topo', 3, ST_SetSRID(ST_Point(227594,893910),26986) ) As node_id;
node_id
-------------------------
7
ST_ModEdgeHeal — Виправляє двa ребра, видаляючи вузол, що їх з'єднує, змінюючи перше ребро та видаляючи друге ребро. Повертає ідентифікатор видаленого вузла.
bigint ST_ModEdgeHeal(varchar atopology, bigint anedge, bigint anotheredge);
Виправляє два ребра, видаляючи вузол, що їх з'єднує, змінюючи перше ребро та видаляючи друге ребро. Повертає ідентифікатор видаленого вузла. Відповідно оновлює всі існуючі з'єднані ребра та відносини.
Доступність: 2.0
This method implements the SQL/MM specification. SQL-MM: Topo-Geo та Topo-Net 3: Деталі процедури: X.3.9
ST_NewEdgeHeal — Відновлює два ребра, видаляючи вузол, що їх з'єднує, видаляючи обидва ребра та замінюючи їх ребром, напрямок якого збігається з напрямком першого наданого ребра.
bigint ST_NewEdgeHeal(varchar atopology, bigint anedge, bigint anotheredge);
Виправляє дві ребра, видаляючи вузол, що їх з'єднує, видаляючи обидві ребра та замінюючи їх ребром, напрямок якого збігається з напрямком першого наданого ребра. Повертає ідентифікатор нового ребра, що замінює виправлені ребра. Відповідно оновлює всі існуючі з'єднані ребра та відносини.
Доступність: 2.0
This method implements the SQL/MM specification. SQL-MM: Topo-Geo та Topo-Net 3: Деталі процедури: X.3.9
ST_MoveIsoNode — Переміщує ізольований вузол у топології з однієї точки в іншу. Якщо нова геометрія apoint існує як вузол, виникає помилка. Повертає опис переміщення.
text ST_MoveIsoNode(varchar atopology, bigint anode, geometry apoint);
Переміщує ізольований вузол у топології з однієї точки в іншу. Якщо нова геометрія apoint існує як вузол, виникає помилка.
Якщо будь-які аргументи мають нульове значення, apoint не є точкою, існуючий вузол не є ізольованим (є початковою або кінцевою точкою існуючої ребра), нове розташування вузла перетинає існуючу ребро (навіть у кінцевих точках) або нове розташування знаходиться в іншій грані (починаючи з версії 3.2.0), то генерується виняток.
Якщо система просторових координат (srid) геометрії точки не збігається з топологією, генерується виняток.
Доступність: 2.0.0
Покращено: версія 3.2.0 гарантує, що вузол не можна перемістити на іншу грань
This method implements the SQL/MM specification. SQL-MM: Процедури Topo-Net: X.3.2
-- Add an isolated node with no face --
SELECT topology.ST_AddIsoNode('ma_topo', NULL, ST_GeomFromText('POINT(227579 893916)', 26986) ) As nodeid;
nodeid
--------
7
-- Move the new node --
SELECT topology.ST_MoveIsoNode('ma_topo', 7, ST_GeomFromText('POINT(227579.5 893916.5)', 26986) ) As descrip;
descrip
----------------------------------------------------
Isolated Node 7 moved to location 227579.5,893916.5ST_NewEdgesSplit — Розділіть ребро, створивши новий вузол уздовж існуючого ребра, видаливши оригінальне ребро і замінивши його двома новими ребрами. Повертає ідентифікатор нового вузла, створеного для з'єднання нових ребер.
bigint ST_NewEdgesSplit(varchar atopology, bigint anedge, geometry apoint);
Розділити ребро з ідентифікатором anedge шляхом створення нового вузла з точкою розташування apoint вздовж поточного ребра, видалення оригінального ребра та заміни його двома новими ребрами. Повертає ідентифікатор нового вузла, створеного для з'єднання нових ребер. Відповідно оновлює всі існуючі з'єднані ребра та відносини.
Якщо система просторових посилань (srid) геометрії точки не збігається з топологією, apoint не є геометрією точки, точка є нульовою, точка вже існує як вузол, край не відповідає існуючому краю або точка не знаходиться в межах краю, то генерується виняток.
Доступність: 1.1
This method implements the SQL/MM specification. SQL-MM: Процедури Topo-Net: X.3.8
-- Add an edge --
SELECT topology.AddEdge('ma_topo', ST_GeomFromText('LINESTRING(227575 893917,227592 893900)', 26986) ) As edgeid;
-- result-
edgeid
------
2
-- Split the new edge --
SELECT topology.ST_NewEdgesSplit('ma_topo', 2, ST_GeomFromText('POINT(227578.5 893913.5)', 26986) ) As newnodeid;
newnodeid
---------
6ST_RemoveIsoNode — Видаляє ізольований вузол і повертає опис дії. Якщо вузол не ізольований (є початком або кінцем ребра), то генерується виняток.
text ST_RemoveIsoNode(varchar atopology, bigint anode);
Видаляє ізольований вузол і повертає опис дії. Якщо вузол не ізольований (є початком або кінцем ребра), то генерується виняток.
Доступність: 1.1
This method implements the SQL/MM specification. SQL-MM: Topo-Geo та Topo-Net 3: Деталі процедури: X+1.3.3
-- Remove an isolated node with no face --
SELECT topology.ST_RemoveIsoNode('ma_topo', 7 ) As result;
result
-------------------------
Isolated node 7 removed
ST_RemoveIsoEdge — Видаляє ізольовану грань і повертає опис дії. Якщо грань не ізольована, то генерується виняток.
text ST_RemoveIsoEdge(varchar atopology, bigint anedge);
Видаляє ізольовану грань і повертає опис дії. Якщо грань не ізольована, то генерується виняток.
Доступність: 1.1
This method implements the SQL/MM specification. SQL-MM: Topo-Geo та Topo-Net 3: Деталі процедури: X+1.3.3
-- Remove an isolated node with no face --
SELECT topology.ST_RemoveIsoNode('ma_topo', 7 ) As result;
result
-------------------------
Isolated node 7 removed
aface.GetEdgeByPoint — Знаходить ідентифікатор ребра, яке перетинає задану точку.
bigint GetEdgeByPoint(varchar atopology, geometry apoint, float8 tol1);
Отримує ідентифікатор ребра, яке перетинає точку.
Функція повертає ціле число (id-edge) за заданою топологією, точкою POINT і допуском tolerance. Якщо tolerance = 0, то точка повинна перетинати край.
Якщо apoint не перетинає ребро, повертає 0 (нуль).
Якщо використання tolerance > 0 і поблизу точки є більше ніж одна грань, то виникає виняток.
![]() | |
Якщо tolerance = 0, функція використовує ST_Intersects, в іншому випадку використовує ST_DWithin. |
Виконується модулем GEOS.
Доступність: 2.0.0
У цих прикладах використовуються ребра, які ми створили в AddEdge
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
SELECT topology.GetEdgeByPoint('ma_topo',geom, 1) As nearnode
FROM ST_GeomFromEWKT('SRID=26986;POINT(227591.9 893900.4)') As geom;
-- get error --
ERROR: Two or more edges foundGetFaceByPoint — Знаходить грань, що перетинає задану точку.
bigint GetFaceByPoint(varchar atopology, geometry apoint, float8 tol1);
Знаходить грань, на яку вказує точка, з заданим допуском.
Функція ефективно шукатиме грань, що перетинає коло з центром у точці та радіусом, що відповідає допуску.
Якщо жодна поверхня не перетинає задане місце пошуку, повертається 0 (універсальна поверхня).
Якщо більше ніж одна грань перетинає місце запиту, генерується виняток.
Доступність: 2.0.0
Покращено: 3.2.0 більш ефективна реалізація та чіткіший контракт, припиняє роботу з недійсними топологіями.
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 | 0SELECT topology.GetFaceByPoint('ma_topo',geom, 1) As nearnode
FROM ST_GeomFromEWKT('POINT(227591.9 893900.4)') As geom;
-- get error --
ERROR: Two or more faces foundGetFaceContainingPoint, AddFace, GetNodeByPoint, GetEdgeByPoint
GetFaceContainingPoint — Знаходить обличчя, що містить точку.
bigint GetFaceContainingPoint(text atopology, geometry apoint);
Повертає ідентифікатор грані, що містить точку.
Якщо точка потрапляє на межу грані, генерується виняток.
![]() | |
Функція базується на дійсній топології, використовуючи зв'язки між ребрами та маркування граней. |
Доступність: 3.2.0
GetNodeByPoint — Знаходить ідентифікатор вузла в точці.
bigint GetNodeByPoint(varchar atopology, geometry apoint, float8 tol1);
Отримує ідентифікатор вузла в точці розташування.
Функція повертає ціле число (id-node) за заданою топологією, POINT і допуском. Якщо допуск = 0, це означає точне перетин, в іншому випадку витягує вузол з інтервалу.
Якщо apoint не перетинає вузол, повертає 0 (нуль).
Якщо використання tolerance > 0 і поблизу точки знаходиться більше одного вузла, то виникає виняток.
![]() | |
Якщо tolerance = 0, функція використовує ST_Intersects, в іншому випадку використовує ST_DWithin. |
Виконується модулем GEOS.
Доступність: 2.0.0
У цих прикладах використовуються ребра, які ми створили в AddEdge
SELECT topology.GetNodeByPoint('ma_topo',geom, 1) As nearnode
FROM ST_GeomFromEWKT('SRID=26986;POINT(227591.9 893900.4)') As geom;
nearnode
----------
2
SELECT topology.GetNodeByPoint('ma_topo',geom, 1000) As too_much_tolerance
FROM ST_GeomFromEWKT('SRID=26986;POINT(227591.9 893900.4)') As geom;
----get error--
ERROR: Two or more nodes found
GetTopologyID — Повертає ідентифікатор топології в таблиці topology.topology за назвою топології.
integer GetTopologyID(varchar toponame);
Повертає ідентифікатор топології в таблиці topology.topology за назвою топології.
Доступність: 1.1
SELECT topology.GetTopologyID('ma_topo') As topo_id;
topo_id
---------
1CreateTopology, DropTopology, GetTopologyName, GetTopologySRID
GetTopologySRID — Повертає SRID топології в таблиці topology.topology, задавши ім'я топології.
integer GetTopologyID(varchar toponame);
Повертає ідентифікатор просторового посилання топології в таблиці topology.topology за назвою топології.
Доступність: 2.0.0
SELECT topology.GetTopologySRID('ma_topo') As SRID;
SRID
-------
4326CreateTopology, DropTopology, GetTopologyName, GetTopologyID
GetTopologyName — Повертає назву топології (схеми) за ідентифікатором топології.
varchar GetTopologyName(integer topology_id);
Повертає ім'я топології (схему) з таблиці topology.topology, задавши ідентифікатор топології.
Доступність: 1.1
SELECT topology.GetTopologyName(1) As topo_name; topo_name ----------- ma_topo
CreateTopology, DropTopology, GetTopologyID, GetTopologySRID
ST_GetFaceEdges — Повертає набір впорядкованих ребер, що обмежують aface.
getfaceedges_returntype ST_GetFaceEdges(varchar atopology, bigint aface);
Повертає набір впорядкованих ребер, що обмежують aface. Кожен вихідний елемент складається з послідовності та edgeid. Номери послідовності починаються з значення 1.
Перелік кожного краю кільця починається з краю з найменшим ідентифікатором. Порядок країв відповідає правилу лівої руки (межа знаходиться ліворуч від кожного спрямованого краю).
Доступність: 2.0
This method implements the SQL/MM specification. SQL-MM 3 Topo-Geo та Topo-Net 3: Деталі процедури: X.3.5
-- Returns the edges bounding face 1
SELECT (topology.ST_GetFaceEdges('tt', 1)).*;
-- result --
sequence | edge
----------+------
1 | -4
2 | 5
3 | 7
4 | -6
5 | 1
6 | 2
7 | 3
(7 rows)
-- Returns the sequence, edge id
-- and geometry of the edges that bound face 1
-- If you just need geom and seq, can use ST_GetFaceGeometry
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 — Повертає багатокутник у заданій топології із зазначеним ідентифікатором грані.
geometry ST_GetFaceGeometry(varchar atopology, bigint aface);
Повертає багатокутник у заданій топології із зазначеним ідентифікатором грані. Будує багатокутник із ребер, що утворюють грань.
Доступність: 1.1
This method implements the SQL/MM specification. SQL-MM 3 Topo-Geo та Topo-Net 3: Деталі процедури: X.3.16
-- Returns the wkt of the polygon added with AddFace
SELECT ST_AsText(topology.ST_GetFaceGeometry('ma_topo', 1)) As facegeomwkt;
-- result --
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))
GetRingEdges — Повертає впорядкований набір ідентифікаторів підписаних ребер, зустрітих при проходженні по заданій стороні ребра.
getfaceedges_returntype GetRingEdges(varchar atopology, bigint aring, integer max_edges=null);
Повертає впорядкований набір ідентифікаторів підписаних ребер, зустрінутих під час проходження по заданій стороні ребра. Кожен вихідний елемент складається з послідовності та ідентифікатора підписаного ребра. Номери послідовності починаються з значення 1.
Якщо ви передаєте позитивний ідентифікатор ребра, проходження починається з лівого боку відповідного ребра і слідує за напрямком ребра. Якщо ви передаєте негативний ідентифікатор ребра, проходження починається з правого боку ребра і йде назад.
Якщо max_edges не дорівнює нулю, функція повертає не більше цих записів. Це є параметром безпеки при роботі з потенційно недійсними топологіями.
![]() | |
Ця функція використовує метадані зв'язку крайових кілець. |
Доступність: 2.0.0
GetNodeEdges — Повертає впорядкований набір ребер, що прилягають до заданого вузла.
getfaceedges_returntype GetNodeEdges(varchar atopology, bigint anode);
Повертає впорядкований набір ребер, що прилягають до заданого вузла. Кожен вихідний елемент складається з послідовності та ідентифікатора ребра зі знаком. Номери послідовності починаються з 1. Позитивне ребро починається в заданому вузлі. Негативне ребро закінчується в заданому вузлі. Замкнуті ребра з'являються двічі (з обома знаками). Порядок визначається за годинниковою стрілкою, починаючи з півночі.
![]() | |
Ця функція обчислює порядок, а не виводить його з метаданих, і тому може використовуватися для побудови зв'язків між кільцями ребер. |
Доступність: 2.0
Цей розділ описує функції для обробки топологій нестандартними способами.
Polygonize — Знаходить і реєструє всі грані, визначені краями топології.
text Polygonize(varchar toponame);
Реєструє всі грані, які можна побудувати з примітивів ребер.
Припускається, що цільова топологія не містить самоперетинаючих ребер.
![]() | |
Вже відомі грані розпізнаються, тому можна безпечно викликати Polygonize кілька разів для однієї топології. |
![]() | |
Ця функція не використовує і не встановлює поля next_left_edge та next_right_edge таблиці ребер. |
Доступність: 2.0.0
AddNode — Додає точковий вузол до таблиці вузлів у вказаній схемі топології та повертає ідентифікатор нового вузла. Якщо точка вже існує як вузол, повертається існуючий ідентифікатор вузла.
bigint AddNode(varchar toponame, geometry apoint, boolean allowEdgeSplitting=false, boolean computeContainingFace=false);
Додає точковий вузол до таблиці вузлів у вказаній схемі топології. Функція AddEdge автоматично додає початкову та кінцеву точки ребра при виклику, тому немає необхідності явно додавати вузли ребра.
Якщо виявлено будь-яке ребро, що перетинає вузол, то, залежно від значення параметра allowEdgeSplitting, або генерується виняток, або ребро розділяється.
Якщо computeContainingFace має значення true, для новододаного вузла буде обчислено правильну грань, що його містить.
![]() | |
Якщо геометрія |
Доступність: 2.0.0
SELECT topology.AddNode('ma_topo', ST_GeomFromText('POINT(227641.6 893816.5)', 26986) ) As nodeid;
-- result --
nodeid
--------
4
AddEdge — Додає лінійний край до таблиці країв ребер та пов'язані початкові та кінцеві точки до таблиці вузлів точок заданої топологічної схеми, використовуючи задану геометрію лінійного ребра, та повертає ідентифікатор нового (або існуючого) ребра.
bigint AddEdge(varchar toponame, geometry aline);
Додає ребро до таблиці ребер і пов'язані вузли до таблиці вузлів заданої схеми toponame з використанням заданої геометрії лінійного рядка та повертає edgeid нового або існуючого запису. Новододане ребро має обох боків "універсум" і пов'язане саме з собою.
![]() | |
Якщо геометрія |
![]() | |
Геометрія |
Виконується модулем GEOS.
![]() | |
AddEdge застаріло з версії 3.5.0. Замість цього використовуйте TopoGeo_AddLineString. |
Доступність: 2.0.0
SELECT topology.AddEdge('ma_topo', ST_GeomFromText('LINESTRING(227575.8 893917.2,227591.9 893900.4)', 26986) ) As edgeid;
-- result-
edgeid
--------
1
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;
-- result --
edgeid
--------
2
SELECT topology.AddEdge('ma_topo', ST_GeomFromText('LINESTRING(227591.2 893900, 227591.9 893900.4,
227704.5 893778.5)', 26986) ) As edgeid;
-- gives error --
ERROR: Edge intersects (not on endpoints) with existing edge 1
AddFace — Реєструє примітив грані в топології та отримує його ідентифікатор.
bigint AddFace(varchar toponame, geometry apolygon, boolean force_new=false);
Реєструє примітив грані в топології та отримує його ідентифікатор.
Для новододаної грані краї, що утворюють її межі, та краї, що містяться в грані, будуть оновлені, щоб мати правильні значення в полях left_face та right_face. Ізольовані вузли, що містяться в грані, також будуть оновлені, щоб мати правильне значення поля containing_face.
![]() | |
Ця функція не використовує і не встановлює поля next_left_edge та next_right_edge таблиці ребер. |
Припускається, що топологія цілі є правильною (не містить самоперетинаючих ребер). Виникає виняток, якщо: Межа багатокутника не повністю визначена існуючими ребрами або багатокутник перетинає існуючу грань.
Якщо геометрія apolygon вже існує як грань, то: якщо force_new має значення false (за замовчуванням), повертається ідентифікатор існуючої грані; якщо force_new має значення true, новому зареєстрованому грані присвоюється новий ідентифікатор.
![]() | |
Коли виконується нова реєстрація існуючої грані (force_new=true), не буде виконано жодних дій для вирішення висячих посилань на існуючу грань у таблицях ребер, вузлів та відносин, а також не буде оновлено поле MBR існуючого запису грані. Це має зробити викликаючий. |
![]() | |
Геометрія |
Доступність: 2.0.0
-- first add the edges we use generate_series as an iterator (the below
-- will only work for polygons with < 10000 points because of our max in gs)
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;
-- result --
edgeid
--------
3
4
5
6
7
8
9
10
11
12
(10 rows)
-- then add the face -
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;
-- result --
faceid
--------
1
ST_Simplify — Повертає "спрощену" версію геометрії заданої TopoGeometry за допомогою алгоритму Дугласа-Пеукера.
geometry ST_Simplify(topogeometry tg, float8 tolerance);
Повертає "спрощену" геометрію заданої TopoGeometry, використовуючи алгоритм Дугласа-Пеукера для кожного компонента ребра.
![]() | |
Повернена геометрія може бути неспрощеною або недійсна. Розділення граней компонентів може допомогти зберегти простоту/дійсність. |
Виконується модулем GEOS.
Доступність: 2.1.0
Геометрія ST_Simplify, ST_IsSimple, ST_IsValid, ST_ModEdgeSplit
RemoveUnusedPrimitives — Видаляє примітивні елементи топології, які не потрібні для визначення існуючих об'єктів TopoGeometry.
bigint RemoveUnusedPrimitives(text topology_name, geometry bbox);
Знаходить всі примітиви (вузли, ребра, грані), які не є строго необхідними для представлення існуючих об'єктів TopoGeometry, і видаляє їх, зберігаючи топологічну валідність (зв'язки ребер, маркування граней) і зайнятість простору TopoGeometry.
Нові примітивні ідентифікатори не створюються, а існуючі примітиви розширюються, щоб включити об'єднані грані (після видалення ребер) або відновлені ребра (після видалення вузлів).
Доступність: 3.3.0
Цей розділ присвячений функціям топології для створення нових топогеометрій.
topoelementarray для набору масивів element_id, type (topoelements).CreateTopoGeom — Створює новий об'єкт топографічної геометрії з масиву топографічних елементів - tg_type: 1:[multi]point, 2:[multi]line, 3:[multi]poly, 4:collection
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);
Створює об'єкт топогеометрії для шару, позначеного layer_id, і реєструє його в таблиці відносин у схемі toponame.
tg_type є цілим числом: 1:[multi]point (точкова), 2:[multi]line (лінійна), 3:[multi]poly (площа), 4:колекція. layer_id є ідентифікатором шару в таблиці topology.layer.
пунктуальні шари утворюються з набору вузлів, лінійні шари утворюються з набору ребер, площинні шари утворюються з набору граней, а колекції можуть утворюватися з суміші вузлів, ребер і граней.
Пропуск масиву компонентів призводить до створення порожнього об'єкта TopoGeometry.
Доступність: 1.1
Створіть топогеометрію в схемі ri_topo для шару 2 (наш ri_roads) типу (2) LINE для першого ребра (ми завантажили в ST_CreateTopoGeo).
INSERT INTO ri.ri_roads(road_name, topo) VALUES('Unknown', topology.CreateTopoGeom('ri_topo',2,2,'{{1,2}}'::topology.topoelementarray);Припустимо, ми маємо геометрії, які повинні бути сформовані з набору граней. Наприклад, ми маємо таблицю груп блоків і хочемо знати топологічну геометрію кожної групи блоків. Якщо наші дані були б ідеально вирівняні, ми могли б зробити так:
-- create our topo geometry column --
SELECT topology.AddTopoGeometryColumn(
'topo_boston',
'boston', 'blockgroups', 'topo', 'POLYGON');
-- addtopgeometrycolumn --
1
-- update our column assuming
-- everything is perfectly aligned with our edges
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 allow for some error
--count the face if 50% of it falls
-- within what we think is our blockgroup boundary
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))
OR
( ST_Intersects(b.geom, topology.ST_GetFaceGeometry('topo_boston', f.face_id))
AND ST_Area(ST_Intersection(b.geom, topology.ST_GetFaceGeometry('topo_boston', f.face_id) ) ) >
ST_Area(topology.ST_GetFaceGeometry('topo_boston', f.face_id))*0.5
)
GROUP BY b.gid) As foo
WHERE foo.gid = bg.gid;
-- and if we wanted to convert our topogeometry back
-- to a denormalized geometry aligned with our faces and edges
-- cast the topo to a geometry
-- The really cool thing is my new geometries
-- are now aligned with my tiger street centerlines
UPDATE boston.blockgroups SET new_geom = topo::geometry;
toTopoGeom — Перетворює просту геометрію в топологічну геометрію.
topogeometry toTopoGeom(geometry geom, varchar toponame, integer layer_id, float8 tolerance);
topogeometry toTopoGeom(geometry geom, topogeometry topogeom, float8 tolerance);
Перетворює просту геометрію в TopoGeometry.
Топологічні примітиви, необхідні для представлення вхідної геометрії, будуть додані до базової топології, можливо з розділенням існуючих, і будуть пов'язані з вихідною TopoGeometry в таблиці relation.
Існуючі об'єкти TopoGeometry (за можливим винятком topogeom, якщо вказано) збережуть свої форми.
Коли вказано tolerance, воно буде використовуватися для прив'язки вхідної геометрії до існуючих примітивів.
У першій формі буде створено нову топогеометрію для заданого шару (layer_id) заданої топології (toponame).
У другій формі примітиви, отримані в результаті перетворення, будуть додані до існуючої TopoGeometry (topogeom), можливо, додаючи простір до її остаточної форми. Щоб нова форма повністю замінила стару, див. clearTopoGeom.
Доступність: 2.0
Покращено: у версії 2.1.0 додано версію, що використовує існуючу TopoGeometry.
Це повністю автономний робочий процес
-- do this if you don't have a topology setup already
-- creates topology not allowing any tolerance
SELECT topology.CreateTopology('topo_boston_test', 2249);
-- create a new table
CREATE TABLE nei_topo(gid serial primary key, nei varchar(30));
--add a topogeometry column to it
SELECT topology.AddTopoGeometryColumn('topo_boston_test', 'public', 'nei_topo', 'topo', 'MULTIPOLYGON') As new_layer_id;
new_layer_id
-----------
1
--use new layer id in populating the new topogeometry column
-- we add the topogeoms to the new layer with 0 tolerance
INSERT INTO nei_topo(nei, topo)
SELECT nei, topology.toTopoGeom(geom, 'topo_boston_test', 1)
FROM neighborhoods
WHERE gid BETWEEN 1 and 15;
--use to verify what has happened --
SELECT * FROM
topology.TopologySummary('topo_boston_test');
-- summary--
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
UPDATE nei_topo SET topo = toTopoGeom(ST_Buffer(topo, -10), clearTopoGeom(topo), 0);
-- Get the no-one-lands left by the above operation
-- I think GRASS calls this "polygon0 layer"
SELECT ST_GetFaceGeometry('topo_boston_test', f.face_id)
FROM topo_boston_test.face f
WHERE f.face_id
> 0 -- don't consider the universe face
AND NOT EXISTS ( -- check that no TopoGeometry references the face
SELECT * FROM topo_boston_test.relation
WHERE layer_id = 1 AND element_id = f.face_id
);
TopoElementArray_Agg — Повертає topoelementarray для набору масивів element_id, type (topoelements).
topoelementarray TopoElementArray_Agg(topoelement set tefield);
SELECT topology.TopoElementArray_Agg(ARRAY[e,t]) As tea
FROM generate_series(1,3) As e CROSS JOIN generate_series(1,4) As t;
tea
--------------------------------------------------------------------------
{{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 — Перетворює топогеометрію в топоелемент.
topoelement TopoElement(topogeometry topo);
Це повністю автономний робочий процес
-- do this if you don't have a topology setup already -- Creates topology not allowing any tolerance SELECT TopoElement(topo) FROM neighborhoods;
-- using as cast SELECT topology.TopoElementArray_Agg(topo::topoelement) FROM neighborhoods GROUP BY city;
Цей розділ охоплює функції топології для редагування існуючих топогеометрій.
clearTopoGeom — Очищає вміст геометрії топографії.
topogeometry clearTopoGeom(topogeometry topogeom);
Очищає вміст TopoGeometry, перетворюючи його на порожній. Найчастіше використовується разом з toTopoGeom для заміни форми існуючих об'єктів та будь-яких залежних об'єктів на вищих ієрархічних рівнях.
Доступність: 2.1
-- Shrink all TopoGeometry polygons by 10 meters
UPDATE nei_topo SET topo = toTopoGeom(ST_Buffer(topo, -10), clearTopoGeom(topo), 0);
TopoGeom_addElement — Додає елемент до визначення TopoGeometry.
topogeometry TopoGeom_addElement(topogeometry tg, topoelement el);
Додає TopoElement до визначення об'єкта TopoGeometry. Не видає помилку, якщо елемент вже є частиною визначення.
Доступність: 2.3
-- Add edge 5 to TopoGeometry tg
UPDATE mylayer SET tg = TopoGeom_addElement(tg, '{5,2}');
TopoGeom_remElement — Видаляє елемент з визначення TopoGeometry.
topogeometry TopoGeom_remElement(topogeometry tg, topoelement el);
-- Remove face 43 from TopoGeometry tg
UPDATE mylayer SET tg = TopoGeom_remElement(tg, '{43,3}');
TopoGeom_addTopoGeom — Додає елемент TopoGeometry до визначення іншого TopoGeometry.
topogeometry TopoGeom_addTopoGeom(topogeometry tgt, topogeometry src);
Додає елементи TopoGeometry до визначення іншого TopoGeometry, можливо змінюючи його кешований тип (атрибут type) на колекцію, якщо це необхідно для збереження всіх елементів в об'єкті-джерелі.
Два об'єкти TopoGeometry повинні бути визначені відповідно до *однієї і тієї ж* топології, а якщо вони визначені ієрархічно, то повинні складатися з елементів одного і того ж дочірнього шару.
Доступність: 3.2
-- Set an "overall" TopoGeometry value to be composed by all
-- elements of specific TopoGeometry values
UPDATE mylayer SET tg_overall = TopoGeom_addTopogeom(
TopoGeom_addTopoGeom(
clearTopoGeom(tg_overall),
tg_specific1
),
tg_specific2
);
topoelementarray (масив топоелементів), що містить топологічні елементи та тип заданої TopoGeometry (примітивні елементи).topoelement, що містять топологічні element_id,element_type заданої TopoGeometry (примітивні елементи).GetTopoGeomElementArray — Повертає topoelementarray (масив топоелементів), що містить топологічні елементи та тип заданої TopoGeometry (примітивні елементи).
topoelementarray GetTopoGeomElementArray(varchar toponame, integer layer_id, bigint tg_id);
topoelementarray GetTopoGeomElementArray(topogeometry tg);
Повертає TopoElementArray, що містить топологічні елементи та тип заданої TopoGeometry (примітивні елементи). Це схоже на GetTopoGeomElements, за винятком того, що повертає елементи у вигляді масиву, а не набору даних.
tg_id — ідентифікатор топогеометрії об'єкта топогеометрії в топології в шарі, позначеному layer_id в таблиці topology.layer.
Доступність: 1.1
GetTopoGeomElements — Повертає набір об'єктів topoelement, що містять топологічні element_id,element_type заданої TopoGeometry (примітивні елементи).
setof topoelement GetTopoGeomElements(varchar toponame, integer layer_id, bigint tg_id);
setof topoelement GetTopoGeomElements(topogeometry tg);
Повертає набір element_id,element_type (topoelements), що відповідає елементам примітивної топології TopoElement (1: вузли, 2: ребра, 3: грані), з яких складається заданий об'єкт топогеометрії в схемі toponame.
tg_id — ідентифікатор топогеометрії об'єкта топогеометрії в топології в шарі, позначеному layer_id в таблиці topology.layer.
Доступність: 2.0.0
ST_SRID — Повертає ідентифікатор просторової прив'язки для топогеометрії.
integer ST_SRID(topogeometry tg);
Повертає ідентифікатор просторової прив'язки для ST_Geometry, як визначено в таблиці spatial_ref_sys. Section 4.5, “Spatial Reference Systems”
![]() | |
Таблиця spatial_ref_sys — це таблиця, яка каталогізує всі системи просторових посилань, відомі PostGIS, і використовується для перетворення з однієї системи просторових посилань в іншу. Тому, якщо ви плануєте перетворювати геометрії, важливо перевірити, чи маєте ви правильний ідентифікатор системи просторових посилань. |
Доступність: 3.2.0
This method implements the SQL/MM specification. SQL-MM 3: 14.1.5
SELECT ST_SRID(ST_GeomFromText('POINT(-71.1043 42.315)',4326));
--result
4326
AsGML — Повертає 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);
Повертає GML-представлення топогеометрії у форматі GML3. Якщо не вказано nsprefix_in, використовується gml. Передайте порожній рядок для nsprefix, щоб отримати некваліфікований простір імен. Параметри точності (за замовчуванням: 15) та опції (за замовчуванням 1), якщо вони вказані, передаються без змін до базового виклику ST_AsGML.
Параметр visitedTable, якщо він вказаний, використовується для відстеження відвіданих елементів Node та Edge, щоб використовувати перехресні посилання (xlink:xref) замість дублювання визначень. Таблиця повинна мати (принаймні) два цілочисельні поля: “element_type” та “element_id”. Користувач, який викликає функцію, повинен мати права на читання та запис у вказаній таблиці. Для найкращої продуктивності слід визначити індекс для element_type та element_id у такому порядку. Такий індекс буде створено автоматично шляхом додавання унікального обмеження до полів. Приклад:
CREATE TABLE visited ( element_type integer, element_id integer, unique(element_type, element_id) );
Параметр idprefix, якщо вказано, буде додано перед ідентифікаторами тегів Edge та Node.
Параметр gmlver, якщо вказано, буде передано до базового ST_AsGML. За замовчуванням встановлено значення 3.
Доступність: 2.0.0
Тут використовується геометрія топографії, яку ми створили в CreateTopoGeom
SELECT topology.AsGML(topo) As rdgml
FROM ri.roads
WHERE road_name = 'Unknown';
-- rdgml--
<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>
Те саме завдання, що й попереднє, але без простору імен
SELECT topology.AsGML(topo,'') As rdgml
FROM ri.roads
WHERE road_name = 'Unknown';
-- rdgml--
<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 — Повертає представлення топогеометрії у форматі TopoJSON.
text AsTopoJSON(topogeometry tg, regclass edgeMapTable);
Повертає представлення топогеометрії у форматі TopoJSON. Якщо edgeMapTable не є нульовим, воно буде використовуватися як відображення ідентифікаторів ребер на індекси дуг для пошуку/зберігання. Це необхідно для того, щоб у кінцевому документі можна було отримати компактний масив "дуг".
У таблиці, якщо вона надана, має бути поле "arc_id" типу "serial" та "edge_id" типу integer; код буде запитувати таблицю щодо "edge_id", тому рекомендується додати індекс до цього поля.
![]() | |
Індекси дуг у вихідних даних TopoJSON починаються з 0, але в таблиці "edgeMapTable" вони починаються з 1. |
Повний документ TopoJSON повинен містити, крім фрагментів, повернутих цією функцією, фактичні дуги та деякі заголовки. Див. специфікацію TopoJSON.
Доступність: 2.1.0
Покращено: у версії 2.2.1 додано підтримку вхідних сигналів puntal
CREATE TEMP TABLE edgemap(arc_id serial, edge_id int unique);
-- header
SELECT '{ "type": "Topology", "transform": { "scale": [1,1], "translate": [0,0] }, "objects": {'
-- objects
UNION ALL SELECT '"' || feature_name || '": ' || AsTopoJSON(feature, 'edgemap')
FROM features.big_parcels WHERE feature_name = 'P3P4';
-- arcs
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
-- footer
UNION ALL SELECT ']}'::text as t;
-- Result:
{ "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]]
]}
У цьому розділі перелічено функції топології, що використовуються для перевірки взаємозв'язків між топогеометріями та топологічними примітивами
Equals — Повертає true, якщо дві топогеометрії складаються з однакових топологічних примітивів.
boolean Equals(topogeometry tg1, topogeometry tg2);
Повертає true, якщо дві топогеометрії складаються з однакових топологічних примітивів: граней, ребер, вузлів.
![]() | |
Ця функція не підтримується для топогеометрій, які є колекціями геометрій. Вона також не може порівнювати топогеометрії з різних топологій. |
Доступність: 1.1.0
This function supports 3d and will not drop the z-index.
Intersects — Повертає true, якщо будь-яка пара примітивів з двох топогеометрій перетинаються.
boolean Intersects(topogeometry tg1, topogeometry tg2);
Повертає true, якщо будь-яка пара примітивів з двох топогеометрій перетинаються.
![]() | |
Ця функція не підтримується для топогеометрій, які є колекціями геометрій. Вона також не може порівнювати топогеометрії з різних топологій. Також наразі не підтримується для ієрархічних топогеометрій (топогеометрій, що складаються з інших топогеометрій). |
Доступність: 1.1.0
This function supports 3d and will not drop the z-index.
Після створення топологій і, можливо, пов'язаних топологічних шарів, ви можете експортувати їх у файловий формат для резервного копіювання або перенесення в іншу базу даних.
Використання стандартних інструментів PostgreSQL для вивантаження/відновлення є проблематичним, оскільки топології складаються з набору таблиць (4 для примітивних типів, довільна кількість для шарів) та записів у таблицях метаданих (topology.topology та topology.layer). Крім того, ідентифікатори топології не є однозначними в різних базах даних, тому параметри топології потрібно буде змінити після її відновлення.
Для спрощення експорту/відновлення топологій надається пара виконуваних файлів: pgtopo_export та pgtopo_import. Приклад використання:
pgtopo_export dev_db topo1 | pgtopo_import topo1 | psql staging_db
Скрипт pgtopo_export бере ім'я бази даних і топологію та виводить файл дампа, який можна використовувати для імпорту топології (та пов'язаних шарів) до нової бази даних.
За замовчуванням pgtopo_export записує файл дампа у стандартний вивід, щоб його можна було передати до pgtopo_import або перенаправити до файлу (відмовляючись записувати в термінал). За бажанням можна вказати ім'я файлу виводу за допомогою параметра командного рядка -f.
За замовчуванням pgtopo_export включає вивантаження всіх шарів, визначених для заданої топології. Це може бути більше даних, ніж вам потрібно, або вони можуть не працювати (у випадку, якщо таблиці шарів мають складні залежності). У такому випадку ви можете попросити пропустити шари за допомогою перемикача --skip-layers і обробити їх окремо.
Виклик pgtopo_export з параметром --help (або -h для скорочення) завжди виведе короткий текст про використання.
Формат файлу дампа — це стиснений архів tar каталогу pgtopo_export, що містить принаймні файл pgtopo_dump_version з інформацією про версію формату. Починаючи з версії 1, каталог містить CSV-файли, розділені табуляцією, з даними таблиць примітивних елементів топології (node, edge_data, face, relation), пов'язаними з ними записами топології та шарів, а також (якщо не вказано --skip-layers) дамп таблиць у форматі PostgreSQL, що повідомляються як шари заданої топології.
Скрипт pgtopo_import приймає дамп топології у форматі pgtopo_export та ім'я, яке буде надано створюваній топології, і виводить SQL-скрипт, що відтворює топологію та пов'язані з нею шари.
Створений файл SQL міститиме оператори, які створюють топологію з заданою назвою, завантажують в неї примітивні дані, відновлюють і реєструють усі шари топології, правильно пов'язуючи всі значення TopoGeometry з відповідною топологією.
За замовчуванням pgtopo_import зчитує дамп із стандартного вводу, щоб його можна було використовувати разом із pgtopo_export у конвеєрі. За бажанням можна вказати ім'я вхідного файлу за допомогою параметра командного рядка -f.
За замовчуванням pgtopo_import включає у вихідний файл SQL код для відновлення всіх шарів, знайдених у дампі.
Це може бути небажаним або непрацюючим у випадку, якщо ваша цільова база даних вже містить таблиці з такими самими іменами, як і в дампі. У такому випадку ви можете попросити пропустити рівні за допомогою перемикача --skip-layers і обробити їх окремо (або пізніше).
SQL для завантаження та зв'язування шарів тільки з топологією з іменем можна створити за допомогою перемикача --only-layers. Це може бути корисно для завантаження шарів ПІСЛЯ вирішення конфліктів імен або для зв'язування шарів з іншою топологією (наприклад, простою версією вихідної топології).
Якщо цільова топологія вже існує і ви хочете її видалити заздалегідь, ви можете передати параметр --drop-topology (починаючи з PostGIS-3.6.0).
For most use cases, you will create PostGIS rasters by loading existing raster files using the packaged raster2pgsql raster loader.
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.
![]() | |
When creating overviews of a specific factor from a set of rasters that are aligned, it is possible for the overviews to not align. Visit http://trac.osgeo.org/postgis/ticket/1764 for an example where the overviews do not align. |
An example session using the loader to create an input file and uploading it chunked in 100x100 tiles might look like this:
# -s use srid 4326 # -I create spatial index # -C use standard raster constraints # -M vacuum analyze after load # *.tif load all these files # -F include a filename column in the raster table # -t tile the output 100x100 # public.demelevation load into this table raster2pgsql -s 4326 -I -C -M -F -t 100x100 *.tif public.demelevation > elev.sql # -d connect to this database # -f read this file after connecting 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. |
A conversion and upload can be done all in one step using UNIX pipes:
raster2pgsql -s 4326 -I -C -M *.tif -F -t 100x100 public.demelevation | psql -d gisdb
Load rasters Massachusetts state plane meters aerial tiles into a schema called aerial and create a full view, 2 and 4 level overview tables, use copy mode for inserting (no intermediary file just straight to db), and -e don't force everything in a transaction (good if you want to see data in tables right away without waiting). Break up the rasters into 128x128 pixel tiles and apply raster constraints. Use copy mode instead of table insert. (-F) Include a field called filename to hold the name of the file the tiles were cut from.
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
--get a list of raster types supported: raster2pgsql -G
The -G commands 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
-?Display help screen. Help will also display if you don't pass in any arguments.
-GPrint the supported raster formats.
-cCreate new table and populate it with raster(s), this is the default mode
-aAppend raster(s) to an existing table.
-dDrop table, create new one and populate it with raster(s)
-pPrepare mode, only create the table.
-C Apply raster constraints -- srid, pixelsize etc. to ensure raster is properly registered in raster_columns view.
-x Disable setting the max extent constraint. Only applied if -C flag is also used.
-rSet the constraints (spatially unique and coverage tile) for regular blocking. Only applied if -C flag is also used.
-s <SRID>Assign output raster with specified SRID. If not provided or is zero, raster's metadata will be checked to determine an appropriate SRID.
-b BANDIndex (1-based) of band to extract from raster. For more than one band index, separate with comma (,). If unspecified, all bands of raster will be extracted.
-t TILE_SIZECut raster into tiles to be inserted one per table row. TILE_SIZE is expressed as WIDTHxHEIGHT or set to the value "auto" to allow the loader to compute an appropriate tile size using the first raster and applied to all rasters.
-PPad right-most and bottom-most tiles to guarantee that all tiles have the same width and height.
-R, --registerRegister the raster as a filesystem (out-db) raster.
Only the metadata of the raster and path location to the raster is stored in the database (not the pixels).
-l OVERVIEW_FACTORCreate 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. 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 NODATANODATA value to use on bands without a NODATA value.
-f COLUMNSpecify name of destination raster column, default is 'rast'
-FAdd a column with the name of the file
-n COLUMNSpecify the name of the filename column. Implies -F.
-qWrap PostgreSQL identifiers in quotes.
-ICreate a GiST index on the raster column.
-MVacuum analyze the raster table.
-kKeeps 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 tablespaceSpecify the tablespace for the new table. Note that indices (including the primary key) will still use the default tablespace unless the -X flag is also used.
-X tablespaceSpecify the tablespace for the table's new index. This applies to the primary key and the spatial index if the -I flag is used.
-Y max_rows_per_copy=50Use copy statements instead of insert statements. Optionally specify max_rows_per_copy; default 50 when not specified.
-eExecute each statement individually, do not use a transaction.
-E ENDIANControl endianness of generated binary output of raster; specify 0 for XDR and 1 for NDR (default); only NDR output is supported now
-V versionSpecify version of output format. Default is 0. Only 0 is supported at this time.
On many occasions, you'll want to create rasters and raster tables right in the database. There are a plethora of functions to do that. The general steps to follow.
Create a table with a raster column to hold the new raster records which can be accomplished with:
CREATE TABLE myrasters(rid serial primary key, rast raster);
There are many functions to help with that goal. If you are creating rasters not as a derivative of other rasters, you will want to start with: ST_MakeEmptyRaster, followed by ST_AddBand
You can also create rasters from geometries. To achieve that you'll want to use ST_AsRaster perhaps accompanied with other functions such as ST_Union or ST_MapAlgebraFct or any of the family of other map algebra functions.
There are even many more options for creating new raster tables from existing tables. For example you can create a raster table in a different projection from an existing one using ST_Transform
Once you are done populating your table initially, you'll want to create a spatial index on the raster column with something like:
CREATE INDEX myrasters_rast_st_convexhull_idx ON myrasters USING gist( ST_ConvexHull(rast) );
Note the use of ST_ConvexHull since most raster operators are based on the convex hull of the rasters.
![]() | |
Pre-2.0 versions of PostGIS raster were based on the envelop rather than the convex hull. For the spatial indexes to work properly you'll need to drop those and replace with convex hull based index. |
Apply raster constraints using AddRasterConstraints
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.
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.
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.
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.
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.
There are two raster catalog views that come packaged with PostGIS. Both views utilize information embedded in the constraints of the raster tables. As a result the catalog views are always consistent with the raster data in the tables since the constraints are enforced.
raster_columns this view catalogs all the raster table columns in your database.
raster_overviews this view catalogs all the raster table columns in your database that serve as overviews for a finer grained table. Tables of this type are generated when you use the -l switch during load.
The raster_columns is a catalog of all raster table columns in your database that are of type raster. It is a view utilizing the constraints on the tables so the information is always consistent even if you restore one raster table from a backup of another database. The following columns exist in the raster_columns catalog.
If you created your tables not with the loader or forgot to specify the -C flag during load, you can enforce the constraints after the fact using AddRasterConstraints so that the raster_columns catalog registers the common information about your raster tiles.
r_table_catalog The database the table is in. This will always read the current database.
r_table_schema The database schema the raster table belongs to.
r_table_name raster table
r_raster_column the column in the r_table_name table that is of type raster. There is nothing in PostGIS preventing you from having multiple raster columns per table so its possible to have a raster table listed multiple times with a different raster column for each.
srid The spatial reference identifier of the raster. Should be an entry in the Section 4.5, “Spatial Reference Systems”.
scale_x The scaling between geometric spatial coordinates and pixel. This is only available if all tiles in the raster column have the same scale_x and this constraint is applied. Refer to ST_ScaleX for more details.
scale_y The scaling between geometric spatial coordinates and pixel. This is only available if all tiles in the raster column have the same scale_y and the scale_y constraint is applied. Refer to ST_ScaleY for more details.
blocksize_x The width (number of pixels across) of each raster tile . Refer to ST_Width for more details.
blocksize_y The width (number of pixels down) of each raster tile . Refer to ST_Height for more details.
same_alignment A boolean that is true if all the raster tiles have the same alignment . Refer to ST_SameAlignment for more details.
regular_blocking If the raster column has the spatially unique and coverage tile constraints, the value with be TRUE. Otherwise, it will be FALSE.
num_bands The number of bands in each tile of your raster set. This is the same information as what is provided by ST_NumBands
pixel_types An array defining the pixel type for each band. You will have the same number of elements in this array as you have number of bands. The pixel_types are one of the following defined in ST_BandPixelType.
nodata_values An array of double precision numbers denoting the nodata_value for each band. You will have the same number of elements in this array as you have number of bands. These numbers define the pixel value for each band that should be ignored for most operations. This is similar information provided by ST_BandNoDataValue.
out_db An array of boolean flags indicating if the raster bands data is maintained outside the database. You will have the same number of elements in this array as you have number of bands.
extent This is the extent of all the raster rows in your raster set. If you plan to load more data that will change the extent of the set, you'll want to run the DropRasterConstraints function before load and then reapply constraints with AddRasterConstraints after load.
spatial_index A boolean that is true if raster column has a spatial index.
raster_overviews catalogs information about raster table columns used for overviews and additional information about them that is useful to know when utilizing overviews. Overview tables are cataloged in both raster_columns and raster_overviews because they are rasters in their own right but also serve an additional special purpose of being a lower resolution caricature of a higher resolution table. These are generated along-side the main raster table when you use the -l switch in raster loading or can be generated manually using AddOverviewConstraints.
Overview tables contain the same constraints as other raster tables as well as additional informational only constraints specific to overviews.
![]() | |
The information in |
Two main reasons for overviews are:
Low resolution representation of the core tables commonly used for fast mapping zoom-out.
Computations are generally faster to do on them than their higher resolution parents because there are fewer records and each pixel covers more territory. Though the computations are not as accurate as the high-res tables they support, they can be sufficient in many rule-of-thumb computations.
The raster_overviews catalog contains the following columns of information.
o_table_catalog The database the overview table is in. This will always read the current database.
o_table_schema The database schema the overview raster table belongs to.
o_table_name raster overview table name
o_raster_column the raster column in the overview table.
r_table_catalog The database the raster table that this overview services is in. This will always read the current database.
r_table_schema The database schema the raster table that this overview services belongs to.
r_table_name raster table that this overview services.
r_raster_column the raster column that this overview column services.
overview_factor - this is the pyramid level of the overview table. The higher the number the lower the resolution of the table. raster2pgsql if given a folder of images, will compute overview of each image file and load separately. Level 1 is assumed and always the original file. Level 2 is will have each tile represent 4 of the original. So for example if you have a folder of 5000x5000 pixel image files that you chose to chunk 125x125, for each image file your base table will have (5000*5000)/(125*125) records = 1600, your (l=2) o_2 table will have ceiling(1600/Power(2,2)) = 400 rows, your (l=3) o_3 will have ceiling(1600/Power(2,3) ) = 200 rows. If your pixels aren't divisible by the size of your tiles, you'll get some scrap tiles (tiles not completely filled). Note that each overview tile generated by raster2pgsql has the same number of pixels as its parent, but is of a lower resolution where each pixel of it represents (Power(2,overview_factor) pixels of the original).
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.
In this section, we'll demonstrate how to use the PHP PostgreSQL driver and the ST_AsGDALRaster family of functions to output band 1,2,3 of a raster to a PHP request stream that can then be embedded in an img src html tag.
The sample query demonstrates how to combine a whole bunch of raster functions together to grab all tiles that intersect a particular wgs 84 bounding box and then unions with ST_Union the intersecting tiles together returning all bands, transforms to user specified projection using ST_Transform, and then outputs the results as a png using ST_AsPNG.
You would call the below using
http://mywebserver/test_raster.php?srid=2249
to get the raster image in Massachusetts state plane feet.
<?php
/** contents of test_raster.php **/
$conn_str ='dbname=mydb host=localhost port=5432 user=myuser password=mypwd';
$dbconn = pg_connect($conn_str);
header('Content-Type: image/png');
/**If a particular projection was requested use it otherwise use mass state plane meters **/
if (!empty( $_REQUEST['srid'] ) && is_numeric( $_REQUEST['srid']) ){
$input_srid = intval($_REQUEST['srid']);
}
else { $input_srid = 26986; }
/** The set bytea_output may be needed for PostgreSQL 9.0+, but not for 8.4 **/
$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]);
?>
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 a PHP request stream that can then be embedded in an img src html tag.
You will need the npgsql .NET PostgreSQL driver for this exercise which you can get the latest of from http://npgsql.projects.postgresql.org/. Just download the latest and drop into your ASP.NET bin folder and you'll be good to go.
The sample query demonstrates how to combine a whole bunch of raster functions together to grab all tiles that intersect a particular wgs 84 bounding box and then unions with ST_Union the intersecting tiles together returning all bands, transforms to user specified projection using ST_Transform, and then outputs the results as a png using ST_AsPNG.
This is same example as Section 10.3.1, “PHP Example Outputting using ST_AsPNG in concert with other raster functions” except implemented in C#.
You would call the below using
http://mywebserver/TestRaster.ashx?srid=2249
to get the raster image in Massachusetts state plane feet.
-- web.config connection string section --
<connectionStrings>
<add name="DSN"
connectionString="server=localhost;database=mydb;Port=5432;User Id=myuser;password=mypwd"/>
</connectionStrings>
// Code for TestRaster.ashx
<%@ WebHandler Language="C#" Class="TestRaster" %>
using System;
using System.Data;
using System.Web;
using Npgsql;
public class TestRaster : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/png";
context.Response.BinaryWrite(GetResults(context));
}
public bool IsReusable {
get { return false; }
}
public byte[] GetResults(HttpContext context)
{
byte[] result = null;
NpgsqlCommand command;
string sql = null;
int input_srid = 26986;
try {
using (NpgsqlConnection conn = new NpgsqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DSN"].ConnectionString)) {
conn.Open();
if (context.Request["srid"] != null)
{
input_srid = Convert.ToInt32(context.Request["srid"]);
}
sql = @"SELECT ST_AsPNG(
ST_Transform(
ST_AddBand(
ST_Union(rast,1), ARRAY[ST_Union(rast,2),ST_Union(rast,3)])
,:input_srid) ) As new_rast
FROM aerials.boston
WHERE
ST_Intersects(rast,
ST_Transform(ST_MakeEnvelope(-71.1217, 42.227, -71.1210, 42.218,4326),26986) )";
command = new NpgsqlCommand(sql, conn);
command.Parameters.Add(new NpgsqlParameter("input_srid", input_srid));
result = (byte[]) command.ExecuteScalar();
conn.Close();
}
}
catch (Exception ex)
{
result = null;
context.Response.Write(ex.Message.Trim());
}
return result;
}
}
This is a simple java console app that takes a query that returns one image and outputs to specified file.
You can download the latest PostgreSQL JDBC drivers from http://jdbc.postgresql.org/download.html
You can compile the following code using a command something like:
set env CLASSPATH .:..\postgresql-9.0-801.jdbc4.jar javac SaveQueryImage.java jar cfm SaveQueryImage.jar Manifest.txt *.class
And call it from the command-line with something like
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 -- Class-Path: postgresql-9.0-801.jdbc4.jar Main-Class: SaveQueryImage
// Code for SaveQueryImage.java
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);
}
}
}This is a plpython stored function that creates a file in the server directory for each record. Requires you have plpython installed. Should work fine with both plpythonu and plpython3u.
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
-- note the postgresql daemon account needs to have write access to folder
-- this echos back the file names created;
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
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 first launch your psql commandline connected to your database.
Unlike the python approach, this approach creates the file on your local computer.
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);
-- you'll get an output something like --
oid | num_bytes
---------+-----------
2630819 | 74860
-- next note the oid and do this replacing the c:/test.png to file path location
-- on your local computer
\lo_export 2630819 'C:/temp/aerial_samp.png'
-- this deletes the file from large object storage on db
SELECT lo_unlink(2630819);
raster is a PostGIS type for storing and analyzing raster data.
For loading rasters from raster files please refer to Section 10.1, “Loading and Creating Rasters”
Some examples in this reference use a raster table of dummy data, created with the following 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.
This section lists the PostgreSQL data types specifically created to support raster functionality.
geomval — A spatial datatype with two fields - geom (holding a geometry object) and val (holding a double precision pixel value from a raster band).
geomval is a compound data type consisting of a geometry object referenced by the .geom field and val, a double precision value that represents the pixel value at a particular geometric location in a raster band. It is used by the ST_DumpAsPolygon and Raster intersection family of functions as an output type to explode a raster band into geometry polygons.
addbandarg — A composite type used as input into the ST_AddBand function defining the attributes and initial value of the new band.
A composite type used as input into the ST_AddBand function defining the attributes and initial value of the new band.
index integer 1-based value indicating the position where the new band will be added amongst the raster's bands. If NULL, the new band will be added at the end of the raster's bands.
pixeltype text Pixel type of the new band. One of defined pixel types as described in ST_BandPixelType.
initialvalue double precision Initial value that all pixels of new band will be set to.
nodataval double precision NODATA value of the new band. If NULL, the new band will not have a NODATA value assigned.
rastbandarg — A composite type for use when needing to express a raster and a band index of that raster.
A composite type for use when needing to express a raster and a band index of that raster.
rast raster The raster in question/
nband integer 1-based value indicating the band of raster
raster — raster spatial data type.
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.
![]() | |
Requires PostGIS be compiled with GDAL support. Currently rasters can be implicitly converted to geometry type, but the conversion returns the ST_ConvexHull of the raster. This auto casting may be removed in the near future so don't rely on it. |
У цьому розділі перелічено автоматичні та явні приведення типів, дозволені для цього типу даних
| Приведення типів в | Поведінка |
| geometry | автоматичне |
reclassarg — A composite type used as input into the ST_Reclass function defining the behavior of reclassification.
A composite type used as input into the ST_Reclass function defining the behavior of reclassification.
nband integerThe band number of band to reclassify.
reclassexpr textrange expression consisting of comma delimited range:map_range mappings. : to define mapping that defines how to map old band values to new band values. ( means >, ) means less than, ] < or equal, [ means > or equal
1. [a-b] = a <= x <= b 2. (a-b] = a < x <= b 3. [a-b) = a <= x < b 4. (a-b) = a < x < b
( notation is optional so a-b means the same as (a-b)
pixeltype textOne of defined pixel types as described in ST_BandPixelType
nodataval double precisionValue to treat as no data. For image outputs that support transparency, these will be blank.
SELECT ROW(2, '0-100:1-10, 101-500:11-150,501 - 10000: 151-254', '8BUI', 255)::reclassarg;
SELECT ROW(1, '0-100]:0, (100-255:1', '1BB', NULL)::reclassarg;
summarystats — A composite type returned by the ST_SummaryStats and ST_SummaryStatsAgg functions.
A composite type returned by the ST_SummaryStats and ST_SummaryStatsAgg functions.
Number of pixels counted for the summary statistics.
Sum of all counted pixel values.
Arithmetic mean of all counted pixel values.
Standard deviation of all counted pixel values.
Minimum value of counted pixel values.
Maximum value of counted pixel values.
unionarg — A composite type used as input into the ST_Union function defining the bands to be processed and behavior of the UNION operation.
A composite type used as input into the ST_Union function defining the bands to be processed and behavior of the UNION operation.
nband integer 1-based value indicating the band of each input raster to be processed.
uniontype text Type of UNION operation. One of defined types as described in ST_Union.
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 );
Generates constraints on a raster column that are used to display information in the raster_columns raster catalog. The rastschema is the name of the table schema the table resides in. The srid must be an integer value reference to an entry in the SPATIAL_REF_SYS table.
raster2pgsql loader uses this function to register raster tables
Valid constraint names to pass in: refer to Section 10.2.1, “Raster Columns Catalog” for more details.
blocksize sets both X and Y blocksize
blocksize_x sets X tile (width in pixels of each tile)
blocksize_y sets Y tile (height in pixels of each tile)
extent computes extent of whole table and applies constraint all rasters must be within that extent
num_bands number of bands
pixel_types reads array of pixel types for each band ensure all band n have same pixel type
regular_blocking sets spatially unique (no two rasters can be spatially the same) and coverage tile (raster is aligned to a coverage) constraints
same_alignment ensures they all have same alignment meaning any two tiles you compare will return true for. Refer to ST_SameAlignment.
srid ensures all have same srid
More -- any listed as inputs into the above functions
![]() | |
This function infers the constraints from the data already present in the table. As such for it to work, you must create the raster column first and then load it with data. |
![]() | |
If you need to load more data in your tables after you have already applied constraints, you may want to run the DropRasterConstraints if the extent of your data has changed. |
Доступність: 2.0.0
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);
-- verify if registered correctly in the raster_columns view --
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}
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');
-- get notice--
NOTICE: Adding regular blocking constraint
NOTICE: Adding blocksize-X constraint
NOTICE: Adding blocksize-Y constraintDropRasterConstraints — Drops PostGIS raster constraints that refer to a raster table column. Useful if you need to reload data or update your raster column data.
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);
Drops PostGIS raster constraints that refer to a raster table column that were added by AddRasterConstraints. Useful if you need to load more data or update your raster column data. You do not need to do this if you want to get rid of a raster table or a raster column.
To drop a raster table use the standard
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
the table will disappear from the raster_columns catalog if the column or table is dropped. However if only the constraints are dropped, the raster column will still be listed in the raster_columns catalog, but there will be no other information about it aside from the column name and table.
Доступність: 2.0.0
SELECT DropRasterConstraints ('myrasters','rast');
----RESULT output ---
t
-- verify change in raster_columns --
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 — Tag a raster column as being an overview of another.
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);
Adds constraints on a raster column that are used to display information in the raster_overviews raster catalog.
The ovfactor parameter represents the scale multiplier in the overview column: higher overview factors have lower resolution.
When the ovschema and refschema parameters are omitted, the first table found scanning the search_path will be used.
Доступність: 2.0.0
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);
-- verify if registered correctly in the raster_overviews view --
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 — Untag a raster column from being an overview of another.
boolean DropOverviewConstraints(name ovschema, name ovtable, name ovcolumn);
boolean DropOverviewConstraints(name ovtable, name ovcolumn);
Remove from a raster column the constraints used to show it as being an overview of another in the raster_overviews raster catalog.
When the ovschema parameter is omitted, the first table found scanning the search_path will be used.
Доступність: 2.0.0
PostGIS_GDAL_Version — Reports the version of the GDAL library in use by PostGIS.
text PostGIS_GDAL_Version();
Reports the version of the GDAL library in use by PostGIS. Will also check and report if GDAL can find its data files.
SELECT PostGIS_GDAL_Version();
postgis_gdal_version
-----------------------------------
GDAL 1.11dev, released 2013/04/13
PostGIS_Raster_Lib_Build_Date — Reports full raster library build date.
text PostGIS_Raster_Lib_Build_Date();
Reports raster build date
SELECT PostGIS_Raster_Lib_Build_Date(); postgis_raster_lib_build_date ----------------------------- 2010-04-28 21:15:10
PostGIS_Raster_Lib_Version — Reports full raster version and build configuration infos.
text PostGIS_Raster_Lib_Version();
Reports full raster version and build configuration infos.
SELECT PostGIS_Raster_Lib_Version(); 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);
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.
Changed: 2.0.6, 2.1.3 - by default no drivers are enabled, unless GUC or Environment variable gdal_enabled_drivers is set.
Availability: 2.0.0 - requires GDAL >= 1.6.0.
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
-- Output the create options XML column of JPEG as a table --
-- Note you can use these creator options in ST_AsGDALRaster options argument
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)
-- raw xml output for creator options for GeoTiff --
SELECT create_options
FROM st_gdaldrivers()
WHERE short_name = 'GTiff';
<CreationOptionList>
<Option name="COMPRESS" type="string-select">
<Value
>NONE</Value>
<Value
>LZW</Value>
<Value
>PACKBITS</Value>
<Value
>JPEG</Value>
<Value
>CCITTRLE</Value>
<Value
>CCITTFAX3</Value>
<Value
>CCITTFAX4</Value>
<Value
>DEFLATE</Value>
</Option>
<Option name="PREDICTOR" type="int" description="Predictor Type"/>
<Option name="JPEG_QUALITY" type="int" description="JPEG quality 1-100" default="75"/>
<Option name="ZLEVEL" type="int" description="DEFLATE compression level 1-9" default="6"/>
<Option name="NBITS" type="int" description="BITS for sub-byte files (1-7), sub-uint16 (9-15), sub-uint32 (17-31)"/>
<Option name="INTERLEAVE" type="string-select" default="PIXEL">
<Value
>BAND</Value>
<Value
>PIXEL</Value>
</Option>
<Option name="TILED" type="boolean" description="Switch to tiled format"/>
<Option name="TFW" type="boolean" description="Write out world file"/>
<Option name="RPB" type="boolean" description="Write out .RPB (RPC) file"/>
<Option name="BLOCKXSIZE" type="int" description="Tile Width"/>
<Option name="BLOCKYSIZE" type="int" description="Tile/Strip Height"/>
<Option name="PHOTOMETRIC" type="string-select">
<Value
>MINISBLACK</Value>
<Value
>MINISWHITE</Value>
<Value
>PALETTE</Value>
<Value
>RGB</Value>
<Value
>CMYK</Value>
<Value
>YCBCR</Value>
<Value
>CIELAB</Value>
<Value
>ICCLAB</Value>
<Value
>ITULAB</Value>
</Option>
<Option name="SPARSE_OK" type="boolean" description="Can newly created files have missing blocks?" default="FALSE"/>
<Option name="ALPHA" type="boolean" description="Mark first extrasample as being alpha"/>
<Option name="PROFILE" type="string-select" default="GDALGeoTIFF">
<Value
>GDALGeoTIFF</Value>
<Value
>GeoTIFF</Value>
<Value
>BASELINE</Value>
</Option>
<Option name="PIXELTYPE" type="string-select">
<Value
>DEFAULT</Value>
<Value
>SIGNEDBYTE</Value>
</Option>
<Option name="BIGTIFF" type="string-select" description="Force creation of BigTIFF file">
<Value
>YES</Value>
<Value
>NO</Value>
<Value
>IF_NEEDED</Value>
<Value
>IF_SAFER</Value>
</Option>
<Option name="ENDIANNESS" type="string-select" default="NATIVE" description="Force endianness of created file. For DEBUG purpose mostly">
<Value
>NATIVE</Value>
<Value
>INVERTED</Value>
<Value
>LITTLE</Value>
<Value
>BIG</Value>
</Option>
<Option name="COPY_SRC_OVERVIEWS" type="boolean" default="NO" description="Force copy of overviews of source dataset (CreateCopy())"/>
</CreationOptionList>
-- Output the create options XML column for GTiff as a table --
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,
array_to_string(xpath('Value/text()', g.opt),', ') As vals
FROM (SELECT unnest(xpath('/CreationOptionList/Option', create_options::xml)) As opt
FROM st_gdaldrivers()
WHERE short_name = 'GTiff') As g;
oname | otype | descrip | vals
--------------------+---------------+----------------------------------------------------------------------+---------------------------------------------------------------------------
COMPRESS | string-select | | NONE, LZW, PACKBITS, JPEG, CCITTRLE, CCITTFAX3, CCITTFAX4, DEFLATE
PREDICTOR | int | Predictor Type |
JPEG_QUALITY | int | JPEG quality 1-100 |
ZLEVEL | int | DEFLATE compression level 1-9 |
NBITS | int | BITS for sub-byte files (1-7), sub-uint16 (9-15), sub-uint32 (17-31) |
INTERLEAVE | string-select | | BAND, PIXEL
TILED | boolean | Switch to tiled format |
TFW | boolean | Write out world file |
RPB | boolean | Write out .RPB (RPC) file |
BLOCKXSIZE | int | Tile Width |
BLOCKYSIZE | int | Tile/Strip Height |
PHOTOMETRIC | string-select | | MINISBLACK, MINISWHITE, PALETTE, RGB, CMYK, YCBCR, CIELAB, ICCLAB, ITULAB
SPARSE_OK | boolean | Can newly created files have missing blocks? |
ALPHA | boolean | Mark first extrasample as being alpha |
PROFILE | string-select | | GDALGeoTIFF, GeoTIFF, BASELINE
PIXELTYPE | string-select | | DEFAULT, SIGNEDBYTE
BIGTIFF | string-select | Force creation of BigTIFF file | YES, NO, IF_NEEDED, IF_SAFER
ENDIANNESS | string-select | Force endianness of created file. For DEBUG purpose mostly | NATIVE, INVERTED, LITTLE, BIG
COPY_SRC_OVERVIEWS | boolean | Force copy of overviews of source dataset (CreateCopy()) |
(19 rows)
UpdateRasterSRID — Change the SRID of all rasters in the user-specified column and table.
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);
Change the SRID of all rasters in the user-specified column and table. The function will drop all appropriate column constraints (extent, alignment and SRID) before changing the SRID of the specified column's rasters.
![]() | |
The data (band pixel values) of the rasters are not touched by this function. Only the raster's metadata is changed. |
Доступність: 2.1.0
ST_CreateOverview — Create an reduced resolution version of a given raster coverage.
regclass ST_CreateOverview(regclass tab, name col, int factor, text algo='NearestNeighbor');
Create an overview table with resampled tiles from the source table. Output tiles will have the same size of input tiles and cover the same spatial extent with a lower resolution (pixel size will be 1/factor of the original in both directions).
The overview table will be made available in the raster_overviews catalog and will have raster constraints enforced.
Algorithm options are: 'NearestNeighbor', 'Bilinear', 'Cubic', 'CubicSpline', and 'Lanczos'. Refer to: GDAL Warp resampling methods for more details.
Доступність: 2.2.0
Output to generally better quality but slower to product format
SELECT ST_CreateOverview('mydata.mytable'::regclass, 'rast', 2, 'Lanczos');Output to faster to process default nearest neighbor
SELECT ST_CreateOverview('mydata.mytable'::regclass, 'rast', 2);ST_AddBand — Returns a raster with the new band(s) of given type added with given initial value in the given index location. If no index is specified, the band is added to the end.
(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);
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.
For the variant that takes an array of addbandarg (Variant 1), a specific addbandarg's index value is relative to the raster at the time when the band described by that addbandarg is being added to the raster. See the Multiple New Bands example below.
For the variant that takes an array of rasters (Variant 5), if torast is NULL then the fromband band of each raster in the array is accumulated into a new raster.
For the variants that take outdbfile (Variants 6 and 7), the value must include the full path to the raster file. The file must also be accessible to the postgres server process.
Enhanced: 2.1.0 support for addbandarg added.
Enhanced: 2.1.0 support for new out-db bands added.
-- Add another band of type 8 bit unsigned integer with pixels initialized to 200
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
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[]
)
);
-- output meta data of raster bands to verify all is right --
SELECT (bmd).*
FROM (SELECT ST_BandMetaData(rast,generate_series(1,2)) As bmd
FROM dummy_rast WHERE rid = 10) AS foo;
--result --
pixeltype | nodatavalue | isoutdb | path
-----------+----------------+-------------+---------+------
1BB | | f |
4BUI | | f |
-- output meta data of raster -
SELECT (rmd).width, (rmd).height, (rmd).numbands
FROM (SELECT ST_MetaData(rast) As rmd
FROM dummy_rast WHERE rid = 10) AS foo;
-- result --
upperleftx | upperlefty | width | height | scalex | scaley | skewx | skewy | srid | numbands
------------+------------+-------+--------+------------+------------+-------+-------+------+----------
0 | 0 | 100 | 100 | 1 | -1 | 0 | 0 | 0 | 2
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
---------+-----------+-------------+---------+------
1 | 8BUI | 0 | f |
2 | 32BF | -1 | f |
3 | 32BUI | 12 | f |
4 | 16BUI | 2 | f |
-- 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: The ORDER BY test_type is only supported in PostgreSQL 9.0+
-- for 8.4 and below it usually works to order your data in a subselect (but not guaranteed)
-- 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
SELECT
mouse,
ST_AddBand(NULL, array_agg(rast ORDER BY test_type), 1) As rast
FROM mice_studies
GROUP BY mouse;
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 — Converts a PostGIS geometry to a PostGIS raster.
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);
Converts a PostGIS geometry to a PostGIS raster. The many variants offers three groups of possibilities for setting the alignment and pixelsize of the resulting raster.
The first group, composed of the two first variants, produce a raster having the same alignment (scalex, scaley, gridx and gridy), pixel type and nodata value as the provided reference raster. You generally pass this reference raster by joining the table containing the geometry with the table containing the reference raster.
The second group, composed of four variants, let you set the dimensions of the raster by providing the parameters of a pixel size (scalex & scaley and skewx & skewy). The width & height of the resulting raster will be adjusted to fit the extent of the geometry. In most cases, you must cast integer scalex & scaley arguments to double precision so that PostgreSQL choose the right variant.
The third group, composed of four variants, let you fix the dimensions of the raster by providing the dimensions of the raster (width & height). The parameters of the pixel size (scalex & scaley and skewx & skewy) of the resulting raster will be adjusted to fit the extent of the geometry.
The two first variants of each of those two last groups let you specify the alignment with an arbitrary corner of the alignment grid (gridx & gridy) and the two last variants takes the upper left corner (upperleftx & upperlefty).
Each group of variant allows producing a one band raster or a multiple bands raster. To produce a multiple bands raster, you must provide an array of pixel types (pixeltype[]), an array of initial values (value) and an array of nodata values (nodataval). If not provided pixeltyped defaults to 8BUI, values to 1 and nodataval to 0.
The output raster will be in the same spatial reference as the source geometry. The only exception is for variants with a reference raster. In this case the resulting raster will get the same SRID as the reference raster.
The optional touched parameter defaults to false and maps to the GDAL ALL_TOUCHED rasterization option, which determines if pixels touched by lines or polygons will be burned. Not just those on the line render path, or whose center point is within the polygon.
This is particularly useful for rendering jpegs and pngs of geometries directly from the database when using in combination with ST_AsPNG and other ST_AsGDALRaster family of functions.
Availability: 2.0.0 - requires GDAL >= 1.6.0.
![]() | |
Not yet capable of rendering complex geometry types such as curves, TINS, and PolyhedralSurfaces, but should be able too once GDAL can. |

black circle
-- this will output a black circle taking up 150 x 150 pixels -- SELECT ST_AsPNG(ST_AsRaster(ST_Buffer(ST_Point(1,5),10),150, 150));

example from buffer rendered with just PostGIS
-- the bands map to RGB bands - the value (118,154,118) - teal --
SELECT ST_AsPNG(
ST_AsRaster(
ST_Buffer(
ST_GeomFromText('LINESTRING(50 50,150 150,150 50)'), 10,'join=bevel'),
200,200,ARRAY['8BUI', '8BUI', '8BUI'], ARRAY[118,154,118], ARRAY[0,0,0]));ST_BandPixelType, ST_Buffer, ST_GDALDrivers, ST_AsGDALRaster, ST_AsPNG, ST_AsJPEG, ST_SRID
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);
Returns a single-band raster containing the rendered version of all incoming geometries, each with its associated value.
Доступність: 3.6.0
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 — Returns one or more bands of an existing raster as a new raster. Useful for building new rasters from existing rasters.
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=,);
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.
![]() | |
For the |
Доступність: 2.0.0
-- Make 2 new rasters: 1 containing band 1 of dummy, second containing band 2 of dummy and then reclassified as a 2BUI
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
SELECT ST_NumBands(ST_Band(rast, '{2,3}'::int[])) As num_bands
FROM dummy_rast WHERE rid=2;
num_bands
----------
2
-- Return bands 2 and 3. Use array to define bands
SELECT ST_NumBands(ST_Band(rast, ARRAY[2,3])) As num_bands
FROM dummy_rast
WHERE rid=2;
![]() original (column rast) | ![]() dupe_band | ![]() sing_band |
--Make a new raster with 2nd band of original and 1st band repeated twice,
and another with just the third band
SELECT rast, ST_Band(rast, ARRAY[2,1,1]) As dupe_band,
ST_Band(rast, 3) As sing_band
FROM samples.than_chunked
WHERE rid=35;
ST_AddBand, ST_NumBands, ST_Reclass, Chapter 11, Raster Reference
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);
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.4.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).
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 | 0ST_MakeEmptyRaster — Returns an empty raster (having no bands) of given dimensions (width & height), upperleft X and Y, pixel size and rotation (scalex, scaley, skewx & skewy) and reference system (srid). If a raster is passed in, returns a new raster with the same size, alignment and SRID. If srid is left out, the spatial ref is set to unknown (0).
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);
Returns an empty raster (having no band) of given dimensions (width & height) and georeferenced in spatial (or world) coordinates with upper left X (upperleftx), upper left Y (upperlefty), pixel size and rotation (scalex, scaley, skewx & skewy) and reference system (srid).
The last version use a single parameter to specify the pixel size (pixelsize). scalex is set to this argument and scaley is set to the negative value of this argument. skewx and skewy are set to 0.
If an existing raster is passed in, it returns a new raster with the same meta data settings (without the bands).
If no srid is specified it defaults to 0. After you create an empty raster you probably want to add bands to it and maybe edit it. Refer to ST_AddBand to define bands and ST_SetValue to set initial pixel values.
INSERT INTO dummy_rast(rid,rast)
VALUES(3, ST_MakeEmptyRaster( 100, 100, 0.0005, 0.0005, 1, 1, 0, 0, 4326) );
--use an existing raster as template for new raster
INSERT INTO dummy_rast(rid,rast)
SELECT 4, ST_MakeEmptyRaster(rast)
FROM dummy_rast WHERE rid = 3;
-- output meta data of rasters we just added
SELECT rid, (md).*
FROM (SELECT rid, ST_MetaData(rast) As md
FROM dummy_rast
WHERE rid IN(3,4)) As foo;
-- output --
rid | upperleftx | upperlefty | width | height | scalex | scaley | skewx | skewy | srid | numbands
-----+------------+------------+-------+--------+------------+------------+-------+-------+------+----------
3 | 0.0005 | 0.0005 | 100 | 100 | 1 | 1 | 0 | 0 | 4326 | 0
4 | 0.0005 | 0.0005 | 100 | 100 | 1 | 1 | 0 | 0 | 4326 | 0
ST_AddBand, ST_MetaData, ST_ScaleX, ST_ScaleY, ST_SetValue, ST_SkewX, , ST_SkewY
ST_Tile — Returns a set of rasters resulting from the split of the input raster based upon the desired dimensions of the output rasters.
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);
Returns a set of rasters resulting from the split of the input raster based upon the desired dimensions of the output rasters.
If padwithnodata = FALSE, edge tiles on the right and bottom sides of the raster may have different dimensions than the rest of the tiles. If padwithnodata = TRUE, all tiles will have the same dimensions with the possibility that edge tiles being padded with NODATA values. If raster band(s) do not have NODATA value(s) specified, one can be specified by setting nodataval.
![]() | |
If a specified band of the input raster is out-of-db, the corresponding band in the output rasters will also be out-of-db. |
Доступність: 2.1.0
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 ST_Tile(rast, 3, 3, TRUE) AS rast FROM bar
)
SELECT
ST_DumpValues(rast)
FROM baz;
st_dumpvalues
------------------------------------------
(1,"{{1,1,1},{1,1,1},{1,1,1}}")
(2,"{{10,10,10},{10,10,10},{10,10,10}}")
(1,"{{2,2,2},{2,2,2},{2,2,2}}")
(2,"{{20,20,20},{20,20,20},{20,20,20}}")
(1,"{{3,3,3},{3,3,3},{3,3,3}}")
(2,"{{30,30,30},{30,30,30},{30,30,30}}")
(1,"{{4,4,4},{4,4,4},{4,4,4}}")
(2,"{{40,40,40},{40,40,40},{40,40,40}}")
(1,"{{5,5,5},{5,5,5},{5,5,5}}")
(2,"{{50,50,50},{50,50,50},{50,50,50}}")
(1,"{{6,6,6},{6,6,6},{6,6,6}}")
(2,"{{60,60,60},{60,60,60},{60,60,60}}")
(1,"{{7,7,7},{7,7,7},{7,7,7}}")
(2,"{{70,70,70},{70,70,70},{70,70,70}}")
(1,"{{8,8,8},{8,8,8},{8,8,8}}")
(2,"{{80,80,80},{80,80,80},{80,80,80}}")
(1,"{{9,9,9},{9,9,9},{9,9,9}}")
(2,"{{90,90,90},{90,90,90},{90,90,90}}")
(18 rows)
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 ST_Tile(rast, 3, 3, 2) AS rast FROM bar
)
SELECT
ST_DumpValues(rast)
FROM baz;
st_dumpvalues
------------------------------------------
(1,"{{10,10,10},{10,10,10},{10,10,10}}")
(1,"{{20,20,20},{20,20,20},{20,20,20}}")
(1,"{{30,30,30},{30,30,30},{30,30,30}}")
(1,"{{40,40,40},{40,40,40},{40,40,40}}")
(1,"{{50,50,50},{50,50,50},{50,50,50}}")
(1,"{{60,60,60},{60,60,60},{60,60,60}}")
(1,"{{70,70,70},{70,70,70},{70,70,70}}")
(1,"{{80,80,80},{80,80,80},{80,80,80}}")
(1,"{{90,90,90},{90,90,90},{90,90,90}}")
(9 rows)
ST_Retile — Return a set of configured tiles from an arbitrarily tiled raster coverage.
SETOF raster ST_Retile(regclass tab, name col, geometry ext, float8 sfx, float8 sfy, int tw, int th, text algo='NearestNeighbor');
Return a set of tiles having the specified scale (sfx, sfy) and max size (tw, th) and covering the specified extent (ext) with data coming from the specified raster coverage (tab, col).
Algorithm options are: 'NearestNeighbor', 'Bilinear', 'Cubic', 'CubicSpline', and 'Lanczos'. Refer to: GDAL Warp resampling methods for more details.
Доступність: 2.2.0
ST_FromGDALRaster — Returns a raster from a supported GDAL raster file.
raster ST_FromGDALRaster(bytea gdaldata, integer srid=NULL);
Returns a raster from a supported GDAL raster file. gdaldata is of type bytea and should be the contents of the GDAL raster file.
If srid is NULL, the function will try to automatically assign the SRID from the GDAL raster. If srid is provided, the value provided will override any automatically assigned SRID.
Доступність: 2.1.0
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)
ST_GeoReference — Returns the georeference meta data in GDAL or ESRI format as commonly seen in a world file. Default is GDAL.
text ST_GeoReference(raster rast, text format=GDAL);
Returns the georeference meta data including carriage return in GDAL or ESRI format as commonly seen in a world file. Default is GDAL if no type specified. type is string 'GDAL' or 'ESRI'.
Difference between format representations is as follows:
GDAL:
scalex skewy skewx scaley upperleftx upperlefty
ESRI:
scalex skewy skewx scaley upperleftx + scalex*0.5 upperlefty + scaley*0.5
SELECT ST_GeoReference(rast, 'ESRI') As esri_ref, ST_GeoReference(rast, 'GDAL') As gdal_ref
FROM dummy_rast WHERE rid=1;
esri_ref | gdal_ref
--------------+--------------
2.0000000000 | 2.0000000000
0.0000000000 : 0.0000000000
0.0000000000 : 0.0000000000
3.0000000000 : 3.0000000000
1.5000000000 : 0.5000000000
2.0000000000 : 0.5000000000
ST_Height — Returns the height of the raster in pixels.
integer ST_Height(raster rast);
Returns the height of the raster.
SELECT rid, ST_Height(rast) As rastheight
FROM dummy_rast;
rid | rastheight
-----+------------
1 | 20
2 | 5
ST_IsEmpty — Returns true if the raster is empty (width = 0 and height = 0). Otherwise, returns false.
boolean ST_IsEmpty(raster rast);
Returns true if the raster is empty (width = 0 and height = 0). Otherwise, returns false.
Доступність: 2.0.0
SELECT ST_IsEmpty(ST_MakeEmptyRaster(100, 100, 0, 0, 0, 0, 0, 0))
st_isempty |
-----------+
f |
SELECT ST_IsEmpty(ST_MakeEmptyRaster(0, 0, 0, 0, 0, 0, 0, 0))
st_isempty |
-----------+
t |
ST_MemSize — Returns the amount of space (in bytes) the raster takes.
integer ST_MemSize(raster rast);
Returns the amount of space (in bytes) the raster takes.
This is a nice compliment to PostgreSQL built in 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_column_size might return lower because it returns the compressed size. pg_total_relation_size - включає таблицю, тостовані таблиці та індекси. |
Доступність: 2.2.0
SELECT ST_MemSize(ST_AsRaster(ST_Buffer(ST_Point(1,5),10,1000),150, 150, '8BUI')) As rast_mem;
rast_mem
--------
22568
ST_MetaData — Returns basic meta data about a raster object such as pixel size, rotation (skew), upper, lower left, etc.
record ST_MetaData(raster rast);
Returns basic meta data about a raster object such as pixel size, rotation (skew), upper, lower left, etc. Columns returned: upperleftx | upperlefty | width | height | scalex | scaley | skewx | skewy | srid | numbands
SELECT rid, (foo.md).*
FROM (SELECT rid, ST_MetaData(rast) As md
FROM dummy_rast) As foo;
rid | upperleftx | upperlefty | width | height | scalex | scaley | skewx | skewy | srid | numbands
----+------------+------------+-------+--------+--------+-----------+-------+-------+------+-------
1 | 0.5 | 0.5 | 10 | 20 | 2 | 3 | 0 | 0 | 0 | 0
2 | 3427927.75 | 5793244 | 5 | 5 | 0.05 | -0.05 | 0 | 0 | 0 | 3
ST_NumBands — Returns the number of bands in the raster object.
integer ST_NumBands(raster rast);
Returns the number of bands in the raster object.
SELECT rid, ST_NumBands(rast) As numbands
FROM dummy_rast;
rid | numbands
----+----------
1 | 0
2 | 3
ST_PixelHeight — Returns the pixel height in geometric units of the spatial reference system.
double precision ST_PixelHeight(raster rast);
Returns the height of a pixel in geometric units of the spatial reference system. In the common case where there is no skew, the pixel height is just the scale ratio between geometric coordinates and raster pixels.
Refer to ST_PixelWidth for a diagrammatic visualization of the relationship.
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
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 — Returns the pixel width in geometric units of the spatial reference system.
double precision ST_PixelWidth(raster rast);
Returns the width of a pixel in geometric units of the spatial reference system. In the common case where there is no skew, the pixel width is just the scale ratio between geometric coordinates and raster pixels.
The following diagram demonstrates the relationship:

Pixel Width: Pixel size in the i direction
Pixel Height: Pixel size in the j direction
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
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 — Returns the X component of the pixel width in units of coordinate reference system.
float8 ST_ScaleX(raster rast);
Returns the X component of the pixel width in units of coordinate reference system. Refer to World File for more details.
Changed: 2.0.0. In WKTRaster versions this was called ST_PixelSizeX.
SELECT rid, ST_ScaleX(rast) As rastpixwidth
FROM dummy_rast;
rid | rastpixwidth
-----+--------------
1 | 2
2 | 0.05
ST_ScaleY — Returns the Y component of the pixel height in units of coordinate reference system.
float8 ST_ScaleY(raster rast);
Returns the Y component of the pixel height in units of coordinate reference system. May be negative. Refer to World File for more details.
Changed: 2.0.0. In WKTRaster versions this was called ST_PixelSizeY.
SELECT rid, ST_ScaleY(rast) As rastpixheight
FROM dummy_rast;
rid | rastpixheight
-----+---------------
1 | 3
2 | -0.05
ST_RasterToWorldCoord — Returns the raster's upper left corner as geometric X and Y (longitude and latitude) given a column and row. Column and row starts at 1.
record ST_RasterToWorldCoord(raster rast, integer xcolumn, integer yrow);
Returns the upper left corner as geometric X and Y (longitude and latitude) given a column and row. Returned X and Y are in geometric units of the georeferenced raster. Numbering of column and row starts at 1 but if either parameter is passed a zero, a negative number or a number greater than the respective dimension of the raster, it will return coordinates outside of the raster assuming the raster's grid is applicable outside the raster's bounds.
Доступність: 2.1.0
-- non-skewed raster
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
-- skewed raster
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 — Returns the geometric X coordinate upper left of a raster, column and row. Numbering of columns and rows starts at 1.
float8 ST_RasterToWorldCoordX(raster rast, integer xcolumn);
float8 ST_RasterToWorldCoordX(raster rast, integer xcolumn, integer yrow);
Returns the upper left X coordinate of a raster column row in geometric units of the georeferenced raster. Numbering of columns and rows starts at 1 but if you pass in a negative number or number higher than number of columns in raster, it will give you coordinates outside of the raster file to left or right with the assumption that the skew and pixel sizes are same as selected raster.
![]() | |
For non-skewed rasters, providing the X column is sufficient. For skewed rasters, the georeferenced coordinate is a function of the ST_ScaleX and ST_SkewX and row and column. An error will be raised if you give just the X column for a skewed raster. |
Changed: 2.1.0 In prior versions, this was called ST_Raster2WorldCoordX
-- non-skewed raster providing column is sufficient
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 lets skew it
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 — Returns the geometric Y coordinate upper left corner of a raster, column and row. Numbering of columns and rows starts at 1.
float8 ST_RasterToWorldCoordY(raster rast, integer yrow);
float8 ST_RasterToWorldCoordY(raster rast, integer xcolumn, integer yrow);
Returns the upper left Y coordinate of a raster column row in geometric units of the georeferenced raster. Numbering of columns and rows starts at 1 but if you pass in a negative number or number higher than number of columns/rows in raster, it will give you coordinates outside of the raster file to left or right with the assumption that the skew and pixel sizes are same as selected raster tile.
![]() | |
For non-skewed rasters, providing the Y column is sufficient. For skewed rasters, the georeferenced coordinate is a function of the ST_ScaleY and ST_SkewY and row and column. An error will be raised if you give just the Y row for a skewed raster. |
Changed: 2.1.0 In prior versions, this was called ST_Raster2WorldCoordY
-- non-skewed raster providing row is sufficient
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 lets skew it
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 — Returns the rotation of the raster in radian.
float8 ST_Rotation(raster rast);
Returns the uniform rotation of the raster in radian. If a raster does not have uniform rotation, NaN is returned. Refer to World File for more details.
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 — Returns the georeference X skew (or rotation parameter).
float8 ST_SkewX(raster rast);
Returns the georeference X skew (or rotation parameter). Refer to World File for more details.
SELECT rid, ST_SkewX(rast) As skewx, ST_SkewY(rast) As skewy,
ST_GeoReference(rast) as georef
FROM dummy_rast;
rid | skewx | skewy | georef
-----+-------+-------+--------------------
1 | 0 | 0 | 2.0000000000
: 0.0000000000
: 0.0000000000
: 3.0000000000
: 0.5000000000
: 0.5000000000
:
2 | 0 | 0 | 0.0500000000
: 0.0000000000
: 0.0000000000
: -0.0500000000
: 3427927.7500000000
: 5793244.0000000000
ST_SkewY — Returns the georeference Y skew (or rotation parameter).
float8 ST_SkewY(raster rast);
Returns the georeference Y skew (or rotation parameter). Refer to World File for more details.
SELECT rid, ST_SkewX(rast) As skewx, ST_SkewY(rast) As skewy,
ST_GeoReference(rast) as georef
FROM dummy_rast;
rid | skewx | skewy | georef
-----+-------+-------+--------------------
1 | 0 | 0 | 2.0000000000
: 0.0000000000
: 0.0000000000
: 3.0000000000
: 0.5000000000
: 0.5000000000
:
2 | 0 | 0 | 0.0500000000
: 0.0000000000
: 0.0000000000
: -0.0500000000
: 3427927.7500000000
: 5793244.0000000000
ST_SRID — Returns the spatial reference identifier of the raster as defined in spatial_ref_sys table.
integer ST_SRID(raster rast);
Returns the spatial reference identifier of the raster object as defined in the spatial_ref_sys table.
![]() | |
From PostGIS 2.0+ the srid of a non-georeferenced raster/geometry is 0 instead of the prior -1. |
SELECT ST_SRID(rast) As srid
FROM dummy_rast WHERE rid=1;
srid
----------------
0
ST_Summary — Returns a text summary of the contents of the raster.
text ST_Summary(raster rast);
Returns a text summary of the contents of the raster.
Доступність: 2.1.0
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
)
);
st_summary
------------------------------------------------------------------
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 — Returns the upper left X coordinate of raster in projected spatial ref.
float8 ST_UpperLeftX(raster rast);
Returns the upper left X coordinate of raster in projected spatial ref.
SELECt rid, ST_UpperLeftX(rast) As ulx
FROM dummy_rast;
rid | ulx
-----+------------
1 | 0.5
2 | 3427927.75
ST_UpperLeftY — Returns the upper left Y coordinate of raster in projected spatial ref.
float8 ST_UpperLeftY(raster rast);
Returns the upper left Y coordinate of raster in projected spatial ref.
SELECT rid, ST_UpperLeftY(rast) As uly
FROM dummy_rast;
rid | uly
-----+---------
1 | 0.5
2 | 5793244
ST_Width — Returns the width of the raster in pixels.
integer ST_Width(raster rast);
Returns the width of the raster in pixels.
SELECT ST_Width(rast) As rastwidth
FROM dummy_rast WHERE rid=1;
rastwidth
----------------
10
ST_WorldToRasterCoord — Returns the upper left corner as column and row given geometric X and Y (longitude and latitude) or a point geometry expressed in the spatial reference coordinate system of the raster.
record ST_WorldToRasterCoord(raster rast, geometry pt);
record ST_WorldToRasterCoord(raster rast, double precision longitude, double precision latitude);
Returns the upper left corner as column and row given geometric X and Y (longitude and latitude) or a point geometry. This function works regardless of whether or not the geometric X and Y or point geometry is outside the extent of the raster. Geometric X and Y must be expressed in the spatial reference coordinate system of the raster.
Доступність: 2.1.0
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 — Returns the column in the raster of the point geometry (pt) or a X and Y world coordinate (xw, yw) represented in world spatial reference system of raster.
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);
Returns the column in the raster of the point geometry (pt) or a X and Y world coordinate (xw, yw). A point, or (both xw and yw world coordinates are required if a raster is skewed). If a raster is not skewed then xw is sufficient. World coordinates are in the spatial reference coordinate system of the raster.
Changed: 2.1.0 In prior versions, this was called ST_World2RasterCoordX
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 — Returns the row in the raster of the point geometry (pt) or a X and Y world coordinate (xw, yw) represented in world spatial reference system of raster.
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);
Returns the row in the raster of the point geometry (pt) or a X and Y world coordinate (xw, yw). A point, or (both xw and yw world coordinates are required if a raster is skewed). If a raster is not skewed then xw is sufficient. World coordinates are in the spatial reference coordinate system of the raster.
Changed: 2.1.0 In prior versions, this was called ST_World2RasterCoordY
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
ST_BandMetaData — Returns basic meta data for a specific raster band. band num 1 is assumed if none-specified.
(1) record ST_BandMetaData(raster rast, integer band=1);
(2) record ST_BandMetaData(raster rast, integer[] band);
Returns basic meta data about a raster band. Columns returned: pixeltype, nodatavalue, isoutdb, path, outdbbandnum, filesize, filetimestamp.
![]() | |
If raster contains no bands then an error is thrown. |
![]() | |
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.
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 | |
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
*
FROM ST_BandMetadata(
(SELECT rast FROM foo),
ARRAY[1,3,2]::int[]
);
bandnum | pixeltype | nodatavalue | isoutdb | path | outdbbandnum | filesize | filetimestamp |
---------+-----------+-------------+---------+--------------------------------------------------------------------------------+---------------+----------+---------------+-
1 | 8BUI | | t | /home/pele/devel/geo/postgis-git/raster/test/regress/loader/Projected.tif | 1 | 12345 | 1521807257 |
3 | 8BUI | | t | /home/pele/devel/geo/postgis-git/raster/test/regress/loader/Projected.tif | 3 | 12345 | 1521807257 |
2 | 8BUI | | t | /home/pele/devel/geo/postgis-git/raster/test/regress/loader/Projected.tif | 2 | 12345 | 1521807257 |
ST_BandNoDataValue — Returns the value in a given band that represents no data. If no band num 1 is assumed.
double precision ST_BandNoDataValue(raster rast, integer bandnum=1);
Returns the value that represents no data for the band
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 — Returns true if the band is filled with only nodata values.
boolean ST_BandIsNoData(raster rast, integer band, boolean forceChecking=true);
boolean ST_BandIsNoData(raster rast, boolean forceChecking=true);
Returns true if the band is filled with only nodata values. Band 1 is assumed if not specified. If the last argument is TRUE, the entire band is checked pixel by pixel. Otherwise, the function simply returns the value of the isnodata flag for the band. The default value for this parameter is FALSE, if not specified.
Доступність: 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. |
-- Create dummy table with one raster column
create table dummy_rast (rid integer, rast raster);
-- Add raster with two bands, one pixel/band. In the first band, nodatavalue = pixel value = 3.
-- In the second band, nodatavalue = 13, pixel value = 4
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 — Returns system file path to a band stored in file system. If no bandnum specified, 1 is assumed.
text ST_BandPath(raster rast, integer bandnum=1);
Returns system file path to a band. Throws an error if called with an in db band.
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);
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.
Доступність: 2.5.0
SELECT ST_BandFileSize(rast,1) FROM dummy_rast WHERE rid = 1;
st_bandfilesize
-----------------
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);
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.
Доступність: 2.5.0
SELECT ST_BandFileTimestamp(rast,1) FROM dummy_rast WHERE rid = 1;
st_bandfiletimestamp
----------------------
1521807257
ST_BandPixelType — Returns the type of pixel for given band. If no bandnum specified, 1 is assumed.
text ST_BandPixelType(raster rast, integer bandnum=1);
Returns name describing data type and size of values stored in each cell of given band.
There are 11 pixel types. Pixel Types supported are as follows:
1BB - 1-bit boolean
2BUI - 2-bit unsigned integer
4BUI - 4-bit unsigned integer
8BSI - 8-bit signed integer
8BUI - 8-bit unsigned integer
16BSI - 16-bit signed integer
16BUI - 16-bit unsigned integer
32BSI - 32-bit signed integer
32BUI - 32-bit unsigned integer
32BF - 32-bit float
64BF - 64-bit float
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 — Returns the minimum value this pixeltype can store.
integer ST_MinPossibleValue(text pixeltype);
Returns the minimum value this pixeltype can store.
SELECT ST_MinPossibleValue('16BSI');
st_minpossiblevalue
---------------------
-32768
SELECT ST_MinPossibleValue('8BUI');
st_minpossiblevalue
---------------------
0
ST_HasNoBand — Returns true if there is no band with given band number. If no band number is specified, then band number 1 is assumed.
boolean ST_HasNoBand(raster rast, integer bandnum=1);
Returns true if there is no band with given band number. If no band number is specified, then band number 1 is assumed.
Доступність: 2.0.0
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
exclude_nodata_value is set to false, then all pixels include nodata pixels are considered to intersect and return value. If exclude_nodata_value is not passed in then reads it from metadata of raster.NODATA value of a given band's pixel specified by a columnx and rowy or a geometric point expressed in the same spatial reference coordinate system as the raster. NODATA values around a given band's pixel specified by either a columnX and rowY or a geometric point expressed in the same spatial reference coordinate system as the raster. ST_PixelAsPolygon — Returns the polygon geometry that bounds the pixel for a particular row and column.
geometry ST_PixelAsPolygon(raster rast, integer columnx, integer rowy);
Returns the polygon geometry that bounds the pixel for a particular row and column.
Доступність: 2.0.0
-- get raster pixel polygon
SELECT i,j, ST_AsText(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 — Returns the polygon geometry that bounds every pixel of a raster band along with the value, the X and the Y raster coordinates of each pixel.
setof record ST_PixelAsPolygons(raster rast, integer band=1, boolean exclude_nodata_value=TRUE);
Returns the polygon geometry that bounds every pixel of a raster band along with the value (double precision), the X and the Y raster coordinates (integers) of each pixel.
Return record format: geom geometry, val double precision, x integer, y integers.
![]() | |
When |
![]() | |
ST_PixelAsPolygons returns one polygon geometry for every pixel. This is different than ST_DumpAsPolygons where each geometry represents one or more pixels with the same pixel value. |
Доступність: 2.0.0
Enhanced: 2.1.0 exclude_nodata_value optional argument was added.
Changed: 2.1.1 Changed behavior of exclude_nodata_value.
-- get raster pixel polygon
SELECT (gv).x, (gv).y, (gv).val, ST_AsText((gv).geom) geom
FROM (SELECT ST_PixelAsPolygons(
ST_SetValue(ST_SetValue(ST_AddBand(ST_MakeEmptyRaster(2, 2, 0, 0, 0.001, -0.001, 0.001, 0.001, 4269),
'8BUI'::text, 1, 0),
2, 2, 10),
1, 1, NULL)
) gv
) foo;
x | y | val | geom
---+---+-----------------------------------------------------------------------------
1 | 1 | | POLYGON((0 0,0.001 0.001,0.002 0,0.001 -0.001,0 0))
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))
ST_PixelAsPoint — Returns a point geometry of the pixel's upper-left corner.
geometry ST_PixelAsPoint(raster rast, integer columnx, integer rowy);
Returns a point geometry of the pixel's upper-left corner.
Доступність: 2.1.0
SELECT ST_AsText(ST_PixelAsPoint(rast, 1, 1)) FROM dummy_rast WHERE rid = 1;
st_astext
----------------
POINT(0.5 0.5)
ST_PixelAsPoints — Returns a point geometry for each pixel of a raster band along with the value, the X and the Y raster coordinates of each pixel. The coordinates of the point geometry are of the pixel's upper-left corner.
setof record ST_PixelAsPoints(raster rast, integer band=1, boolean exclude_nodata_value=TRUE);
Returns a point geometry for each pixel of a raster band along with the value, the X and the Y raster coordinates of each pixel. The coordinates of the point geometry are of the pixel's upper-left corner.
Return record format: geom geometry, val double precision, x integer, y integers.
![]() | |
When |
Доступність: 2.1.0
Changed: 2.1.1 Changed behavior of exclude_nodata_value.
SELECT x, y, val, ST_AsText(geom) FROM (SELECT (ST_PixelAsPoints(rast, 1)).* FROM dummy_rast WHERE rid = 2) foo;
x | y | val | st_astext
---+---+-----+------------------------------
1 | 1 | 253 | POINT(3427927.75 5793244)
2 | 1 | 254 | POINT(3427927.8 5793244)
3 | 1 | 253 | POINT(3427927.85 5793244)
4 | 1 | 254 | POINT(3427927.9 5793244)
5 | 1 | 254 | POINT(3427927.95 5793244)
1 | 2 | 253 | POINT(3427927.75 5793243.95)
2 | 2 | 254 | POINT(3427927.8 5793243.95)
3 | 2 | 254 | POINT(3427927.85 5793243.95)
4 | 2 | 253 | POINT(3427927.9 5793243.95)
5 | 2 | 249 | POINT(3427927.95 5793243.95)
1 | 3 | 250 | POINT(3427927.75 5793243.9)
2 | 3 | 254 | POINT(3427927.8 5793243.9)
3 | 3 | 254 | POINT(3427927.85 5793243.9)
4 | 3 | 252 | POINT(3427927.9 5793243.9)
5 | 3 | 249 | POINT(3427927.95 5793243.9)
1 | 4 | 251 | POINT(3427927.75 5793243.85)
2 | 4 | 253 | POINT(3427927.8 5793243.85)
3 | 4 | 254 | POINT(3427927.85 5793243.85)
4 | 4 | 254 | POINT(3427927.9 5793243.85)
5 | 4 | 253 | POINT(3427927.95 5793243.85)
1 | 5 | 252 | POINT(3427927.75 5793243.8)
2 | 5 | 250 | POINT(3427927.8 5793243.8)
3 | 5 | 254 | POINT(3427927.85 5793243.8)
4 | 5 | 254 | POINT(3427927.9 5793243.8)
5 | 5 | 254 | POINT(3427927.95 5793243.8)
ST_PixelAsCentroid — Returns the centroid (point geometry) of the area represented by a pixel.
geometry ST_PixelAsCentroid(raster rast, integer x, integer y);
Returns the centroid (point geometry) of the area represented by a pixel.
Enhanced: 3.2.0 Faster now implemented in C.
Доступність: 2.1.0
SELECT ST_AsText(ST_PixelAsCentroid(rast, 1, 1)) FROM dummy_rast WHERE rid = 1;
st_astext
--------------
POINT(1.5 2)
ST_PixelAsCentroids — Returns the centroid (point geometry) for each pixel of a raster band along with the value, the X and the Y raster coordinates of each pixel. The point geometry is the centroid of the area represented by a pixel.
setof record ST_PixelAsCentroids(raster rast, integer band=1, boolean exclude_nodata_value=TRUE);
Returns the centroid (point geometry) for each pixel of a raster band along with the value, the X and the Y raster coordinates of each pixel. The point geometry is the centroid of the area represented by a pixel.
Return record format: geom geometry, val double precision, x integer, y integers.
![]() | |
When |
Enhanced: 3.2.0 Faster now implemented in C.
Changed: 2.1.1 Changed behavior of exclude_nodata_value.
Доступність: 2.1.0
--LATERAL syntax requires PostgreSQL 9.3+
SELECT x, y, val, ST_AsText(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)
ST_Value — Returns the value of a given band in a given columnx, rowy pixel or at a particular geometric point. Band numbers start at 1 and assumed to be 1 if not specified. If exclude_nodata_value is set to false, then all pixels include nodata pixels are considered to intersect and return value. If exclude_nodata_value is not passed in then reads it from metadata of raster.
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);
Returns the value of a given band in a given columnx, rowy pixel or at a given geometry point. Band numbers start at 1 and band is assumed to be 1 if not specified.
If exclude_nodata_value is set to true, then only non nodata pixels are considered. If exclude_nodata_value is set to false, then all pixels are considered.
The allowed values of the resample parameter are "nearest" which performs the default nearest-neighbor resampling, and "bilinear" which performs a bilinear interpolation to estimate the value between pixel centers.
Enhanced: 3.2.0 resample optional argument was added.
Enhanced: 2.0.0 exclude_nodata_value optional argument was added.
-- get raster values at particular postgis geometry points
-- the srid of your geometry should be same as for your raster
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
SELECT rid, ST_Value(rast, 3, sometable.geom) As b3pval
FROM sometable
WHERE ST_Intersects(rast,sometable.geom);
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 --
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 --
SELECT ST_AsText(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 particular polygon --
SELECT ST_AsText(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
SELECT ST_AsText(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 — Returns the nearest non-NODATA value of a given band's pixel specified by a columnx and rowy or a geometric point expressed in the same spatial reference coordinate system as the raster.
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);
Returns the nearest non-NODATA value of a given band in a given columnx, rowy pixel or at a specific geometric point. If the columnx, rowy pixel or the pixel at the specified geometric point is NODATA, the function will find the nearest pixel to the columnx, rowy pixel or geometric point whose value is not NODATA.
Band numbers start at 1 and bandnum is assumed to be 1 if not specified. If exclude_nodata_value is set to false, then all pixels include nodata pixels are considered to intersect and return value. If exclude_nodata_value is not passed in then reads it from metadata of raster.
Доступність: 2.1.0
![]() | |
ST_NearestValue is a drop-in replacement for ST_Value. |
-- pixel 2x2 has value
SELECT
ST_Value(rast, 2, 2) AS value,
ST_NearestValue(rast, 2, 2) AS nearestvalue
FROM (
SELECT
ST_SetValue(
ST_SetValue(
ST_SetValue(
ST_SetValue(
ST_SetValue(
ST_AddBand(
ST_MakeEmptyRaster(5, 5, -2, 2, 1, -1, 0, 0, 0),
'8BUI'::text, 1, 0
),
1, 1, 0.
),
2, 3, 0.
),
3, 5, 0.
),
4, 2, 0.
),
5, 4, 0.
) AS rast
) AS foo
value | nearestvalue
-------+--------------
1 | 1
-- pixel 2x3 is NODATA
SELECT
ST_Value(rast, 2, 3) AS value,
ST_NearestValue(rast, 2, 3) AS nearestvalue
FROM (
SELECT
ST_SetValue(
ST_SetValue(
ST_SetValue(
ST_SetValue(
ST_SetValue(
ST_AddBand(
ST_MakeEmptyRaster(5, 5, -2, 2, 1, -1, 0, 0, 0),
'8BUI'::text, 1, 0
),
1, 1, 0.
),
2, 3, 0.
),
3, 5, 0.
),
4, 2, 0.
),
5, 4, 0.
) AS rast
) AS foo
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);
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.
Доступність: 3.2.0
--
-- 2x2 test raster with values
--
-- 10 50
-- 40 20
--
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_AsText(
ST_SetZ(
rast,
band => 1,
geom => 'SRID=4326;LINESTRING(1.0 1.9, 1.0 0.2)'::geometry,
resample => 'bilinear'
))
FROM test_raster
st_astext
----------------------------------
LINESTRING Z (1 1.9 38,1 0.2 27)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);
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.
Доступність: 3.2.0
--
-- 2x2 test raster with values
--
-- 10 50
-- 40 20
--
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_AsText(
ST_SetM(
rast,
band => 1,
geom => 'SRID=4326;LINESTRING(1.0 1.9, 1.0 0.2)'::geometry,
resample => 'bilinear'
))
FROM test_raster
st_astext
----------------------------------
LINESTRING M (1 1.9 38,1 0.2 27)ST_Neighborhood — Returns a 2-D double precision array of the non-NODATA values around a given band's pixel specified by either a columnX and rowY or a geometric point expressed in the same spatial reference coordinate system as the raster.
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);
Returns a 2-D double precision array of the non-NODATA values around a given band's pixel specified by either a columnX and rowY or a geometric point expressed in the same spatial reference coordinate system as the raster. The distanceX and distanceY parameters define the number of pixels around the specified pixel in the X and Y axes, e.g. I want all values within 3 pixel distance along the X axis and 2 pixel distance along the Y axis around my pixel of interest. The center value of the 2-D array will be the value at the pixel specified by the columnX and rowY or the geometric point.
Band numbers start at 1 and bandnum is assumed to be 1 if not specified. If exclude_nodata_value is set to false, then all pixels include nodata pixels are considered to intersect and return value. If exclude_nodata_value is not passed in then reads it from metadata of raster.
![]() | |
The number of elements along each axis of the returning 2-D array is 2 * ( |
![]() | |
The 2-D array output can be passed to any of the raster processing builtin functions, e.g. ST_Min4ma, ST_Sum4ma, ST_Mean4ma. |
Доступність: 2.1.0
-- pixel 2x2 has value
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
st_neighborhood
---------------------------------
{{NULL,1,1},{1,1,1},{1,NULL,1}}
-- pixel 2x3 is NODATA
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
st_neighborhood
------------------------------
{{1,1,1},{1,NULL,1},{1,1,1}}
-- pixel 3x3 has value
-- exclude_nodata_value = FALSE
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
st_neighborhood
---------------------------
{{1,1,0},{0,1,1},{1,1,1}}
ST_NearestValue, ST_Min4ma, ST_Max4ma, ST_Sum4ma, ST_Mean4ma, ST_Range4ma, ST_Distinct4ma, ST_StdDev4ma
ST_SetValue — Returns modified raster resulting from setting the value of a given band in a given columnx, rowy pixel or the pixels that intersect a particular geometry. Band numbers start at 1 and assumed to be 1 if not specified.
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);
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.
Enhanced: 2.1.0 Geometry variant of ST_SetValue() now supports any geometry type, not just point. The geometry variant is a wrapper around the geomval[] variant of ST_SetValues()
-- Geometry example
SELECT (foo.geomval).val, ST_AsText(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 ...
-- Store the changed raster --
UPDATE dummy_rast SET rast = ST_SetValue(rast,1, ST_Point(3427927.75, 5793243.95),100)
WHERE rid = 2 ;
ST_SetValues — Returns modified raster resulting from setting the values of a given band.
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);
Returns modified raster resulting from setting specified pixels to new value(s) for the designated band. columnx and rowy are 1-indexed.
If keepnodata is TRUE, those pixels whose values are NODATA will not be set with the corresponding value in newvalueset.
For Variant 1, the specific pixels to be set are determined by the columnx, rowy pixel coordinates and the dimensions of the newvalueset array. noset can be used to prevent pixels with values present in newvalueset from being set (due to PostgreSQL not permitting ragged/jagged arrays). See example Variant 1.
Variant 2 is like Variant 1 but with a simple double precision nosetvalue instead of a boolean noset array. Elements in newvalueset with the nosetvalue value with be skipped. See example Variant 2.
For Variant 3, the specific pixels to be set are determined by the columnx, rowy pixel coordinates, width and height. See example Variant 3.
Variant 4 is the same as Variant 3 with the exception that it assumes that the first band's pixels of rast will be set.
For Variant 5, an array of geomval is used to determine the specific pixels to be set. If all the geometries in the array are of type POINT or MULTIPOINT, the function uses a shortcut where the longitude and latitude of each point is used to set a pixel directly. Otherwise, the geometries are converted to rasters and then iterated through in one pass. See example Variant 5.
Доступність: 2.1.0
/*
The ST_SetValues() does the following...
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 1 | 1 | 1 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | =
> | 1 | 9 | 9 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 1 | 9 | 9 |
+ - + - + - + + - + - + - +
*/
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[][]
)
) 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 ST_SetValues() does the following...
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 9 | 9 | 9 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | =
> | 9 | | 9 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 9 | 9 | 9 |
+ - + - + - + + - + - + - +
*/
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[][]
)
) AS poly
) foo
ORDER BY 1, 2;
x | y | val
---+---+-----
1 | 1 | 9
1 | 2 | 9
1 | 3 | 9
2 | 1 | 9
2 | 2 |
2 | 3 | 9
3 | 1 | 9
3 | 2 | 9
3 | 3 | 9
/*
The ST_SetValues() does the following...
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 9 | 9 | 9 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | => | 1 | | 9 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 9 | 9 | 9 |
+ - + - + - + + - + - + - +
*/
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[][]
)
) AS poly
) foo
ORDER BY 1, 2;
x | y | val
---+---+-----
1 | 1 | 9
1 | 2 | 1
1 | 3 | 9
2 | 1 | 9
2 | 2 |
2 | 3 | 9
3 | 1 | 9
3 | 2 | 9
3 | 3 | 9
/*
The ST_SetValues() does the following...
+ - + - + - + + - + - + - +
| | 1 | 1 | | | 9 | 9 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | => | 1 | | 9 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 9 | 9 | 9 |
+ - + - + - + + - + - + - +
*/
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
)
) AS poly
) foo
ORDER BY 1, 2;
x | y | val
---+---+-----
1 | 1 |
1 | 2 | 1
1 | 3 | 9
2 | 1 | 9
2 | 2 |
2 | 3 | 9
3 | 1 | 9
3 | 2 | 9
3 | 3 | 9
/*
The ST_SetValues() does the following...
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 1 | 1 | 1 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | => | 1 | 9 | 9 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 1 | 9 | 9 |
+ - + - + - + + - + - + - +
*/
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
)
) 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
/*
This example is like the previous one. Instead of nosetvalue = -1, nosetvalue = NULL
The ST_SetValues() does the following...
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 1 | 1 | 1 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | => | 1 | 9 | 9 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 1 | 9 | 9 |
+ - + - + - + + - + - + - +
*/
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
)
) 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 ST_SetValues() does the following...
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 1 | 1 | 1 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | => | 1 | 9 | 9 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 1 | 9 | 9 |
+ - + - + - + + - + - + - +
*/
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
)
) 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 ST_SetValues() does the following...
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 1 | 1 | 1 |
+ - + - + - + + - + - + - +
| 1 | | 1 | => | 1 | | 9 |
+ - + - + - + + - + - + - +
| 1 | 1 | 1 | | 1 | 9 | 9 |
+ - + - + - + + - + - + - +
*/
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
)
) AS poly
) foo
ORDER BY 1, 2;
x | y | val
---+---+-----
1 | 1 | 1
1 | 2 | 1
1 | 3 | 1
2 | 1 | 1
2 | 2 |
2 | 3 | 9
3 | 1 | 1
3 | 2 | 9
3 | 3 | 9
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
)
SELECT
rid, gid, ST_DumpValues(ST_SetValue(rast, 1, geom, gid))
FROM foo t1
CROSS JOIN bar t2
ORDER BY rid, gid;
rid | gid | st_dumpvalues
-----+-----+---------------------------------------------------------------------------------------------------------------------------------------------
1 | 1 | (1,"{{NULL,NULL,NULL,NULL,NULL},{NULL,NULL,NULL,NULL,NULL},{NULL,NULL,1,NULL,NULL},{NULL,NULL,NULL,NULL,NULL},{NULL,NULL,NULL,NULL,NULL}}")
1 | 2 | (1,"{{NULL,NULL,NULL,NULL,NULL},{NULL,2,2,2,NULL},{NULL,2,2,2,NULL},{NULL,2,2,2,NULL},{NULL,NULL,NULL,NULL,NULL}}")
1 | 3 | (1,"{{3,3,3,3,3},{3,NULL,NULL,NULL,NULL},{3,NULL,NULL,NULL,NULL},{3,NULL,NULL,NULL,NULL},{NULL,NULL,NULL,NULL,NULL}}")
1 | 4 | (1,"{{4,NULL,NULL,NULL,NULL},{NULL,NULL,NULL,NULL,NULL},{NULL,NULL,NULL,NULL,NULL},{NULL,NULL,NULL,NULL,NULL},{NULL,NULL,NULL,NULL,4}}")
(4 rows)
The following shows that geomvals later in the array can overwrite prior geomvals
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
)
SELECT
t1.rid, t2.gid, t3.gid, ST_DumpValues(ST_SetValues(rast, 1, ARRAY[ROW(t2.geom, t2.gid), ROW(t3.geom, t3.gid)]::geomval[]))
FROM foo t1
CROSS JOIN bar t2
CROSS JOIN bar t3
WHERE t2.gid = 1
AND t3.gid = 2
ORDER BY t1.rid, t2.gid, t3.gid;
rid | gid | gid | st_dumpvalues
-----+-----+-----+---------------------------------------------------------------------------------------------------------------------
1 | 1 | 2 | (1,"{{NULL,NULL,NULL,NULL,NULL},{NULL,2,2,2,NULL},{NULL,2,2,2,NULL},{NULL,2,2,2,NULL},{NULL,NULL,NULL,NULL,NULL}}")
(1 row)
This example is the opposite of the prior example
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
)
SELECT
t1.rid, t2.gid, t3.gid, ST_DumpValues(ST_SetValues(rast, 1, ARRAY[ROW(t2.geom, t2.gid), ROW(t3.geom, t3.gid)]::geomval[]))
FROM foo t1
CROSS JOIN bar t2
CROSS JOIN bar t3
WHERE t2.gid = 2
AND t3.gid = 1
ORDER BY t1.rid, t2.gid, t3.gid;
rid | gid | gid | st_dumpvalues
-----+-----+-----+---------------------------------------------------------------------------------------------------------------------
1 | 2 | 1 | (1,"{{NULL,NULL,NULL,NULL,NULL},{NULL,2,2,2,NULL},{NULL,2,1,2,NULL},{NULL,2,2,2,NULL},{NULL,NULL,NULL,NULL,NULL}}")
(1 row)
ST_DumpValues — Get the values of the specified band as a 2-dimension array.
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 );
Get the values of the specified band as a 2-dimension array (first index is row, second is column). If nband is NULL or not provided, all raster bands are processed.
Доступність: 2.1.0
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)
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)
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;
st_dumpvalues
---------------
5
(1 row)
ST_PixelOfValue — Get the columnx, rowy coordinates of the pixel whose value equals the search value.
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 );
Get the columnx, rowy coordinates of the pixel whose value equals the search value. If no band is specified, then band 1 is assumed.
Доступність: 2.1.0
SELECT
(pixels).*
FROM (
SELECT
ST_PixelOfValue(
ST_SetValue(
ST_SetValue(
ST_SetValue(
ST_SetValue(
ST_SetValue(
ST_AddBand(
ST_MakeEmptyRaster(5, 5, -2, 2, 1, -1, 0, 0, 0),
'8BUI'::text, 1, 0
),
1, 1, 0
),
2, 3, 0
),
3, 5, 0
),
4, 2, 0
),
5, 4, 255
)
, 1, ARRAY[1, 255]) AS pixels
) AS foo
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
ST_SetGeoReference — Set Georeference 6 georeference parameters in a single call. Numbers should be separated by white space. Accepts inputs in GDAL or ESRI format. Default is 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);
Set Georeference 6 georeference parameters in a single call. Accepts inputs in 'GDAL' or 'ESRI' format. Default is GDAL. If 6 coordinates are not provided will return null.
Difference between format representations is as follows:
GDAL:
scalex skewy skewx scaley upperleftx upperlefty
ESRI:
scalex skewy skewx scaley upperleftx + scalex*0.5 upperlefty + scaley*0.5
![]() | |
If the raster has out-db bands, changing the georeference may result in incorrect access of the band's externally stored data. |
Enhanced: 2.1.0 Addition of ST_SetGeoReference(raster, double precision, ...) variant
WITH foo AS (
SELECT ST_MakeEmptyRaster(5, 5, 0, 0, 1, -1, 0, 0, 0) AS rast
)
SELECT
0 AS rid, (ST_Metadata(rast)).*
FROM foo
UNION ALL
SELECT
1, (ST_Metadata(ST_SetGeoReference(rast, '10 0 0 -10 0.1 0.1', 'GDAL'))).*
FROM foo
UNION ALL
SELECT
2, (ST_Metadata(ST_SetGeoReference(rast, '10 0 0 -10 5.1 -4.9', 'ESRI'))).*
FROM foo
UNION ALL
SELECT
3, (ST_Metadata(ST_SetGeoReference(rast, 1, 1, 10, -10, 0.001, 0.001))).*
FROM foo
rid | upperleftx | upperlefty | width | height | scalex | scaley | skewx | skewy | srid | numbands
-----+--------------------+--------------------+-------+--------+--------+--------+-------+-------+------+----------
0 | 0 | 0 | 5 | 5 | 1 | -1 | 0 | 0 | 0 | 0
1 | 0.1 | 0.1 | 5 | 5 | 10 | -10 | 0 | 0 | 0 | 0
2 | 0.0999999999999996 | 0.0999999999999996 | 5 | 5 | 10 | -10 | 0 | 0 | 0 | 0
3 | 1 | 1 | 5 | 5 | 10 | -10 | 0.001 | 0.001 | 0 | 0
ST_GeoReference, ST_ScaleX, ST_ScaleY, ST_UpperLeftX, ST_UpperLeftY
ST_SetRotation — Set the rotation of the raster in radian.
raster ST_SetRotation(raster rast, float8 rotation);
Uniformly rotate the raster. Rotation is in radian. Refer to World File for more details.
SELECT
ST_ScaleX(rast1), ST_ScaleY(rast1), ST_SkewX(rast1), ST_SkewY(rast1),
ST_ScaleX(rast2), ST_ScaleY(rast2), ST_SkewX(rast2), ST_SkewY(rast2)
FROM (
SELECT ST_SetRotation(rast, 15) AS rast1, rast as rast2 FROM dummy_rast
) AS foo;
st_scalex | st_scaley | st_skewx | st_skewy | st_scalex | st_scaley | st_skewx | st_skewy
---------------------+---------------------+--------------------+--------------------+-----------+-----------+----------+----------
-1.51937582571764 | -2.27906373857646 | 1.95086352047135 | 1.30057568031423 | 2 | 3 | 0 | 0
-0.0379843956429411 | -0.0379843956429411 | 0.0325143920078558 | 0.0325143920078558 | 0.05 | -0.05 | 0 | 0
ST_SetScale — Sets the X and Y size of pixels in units of coordinate reference system. Number units/pixel width/height.
raster ST_SetScale(raster rast, float8 xy);
raster ST_SetScale(raster rast, float8 x, float8 y);
Sets the X and Y size of pixels in units of coordinate reference system. Number units/pixel width/height. If only one unit passed in, assumed X and Y are the same number.
![]() | |
ST_SetScale is different from ST_Rescale in that ST_SetScale do not resample the raster to match the raster extent. It only changes the metadata (or georeference) of the raster to correct an originally mis-specified scaling. ST_Rescale results in a raster having different width and height computed to fit the geographic extent of the input raster. ST_SetScale do not modify the width, nor the height of the raster. |
Changed: 2.0.0 In WKTRaster versions this was called ST_SetPixelSize. This was changed in 2.0.0.
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)
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 — Sets the georeference X and Y skew (or rotation parameter). If only one is passed in, sets X and Y to the same value.
raster ST_SetSkew(raster rast, float8 skewxy);
raster ST_SetSkew(raster rast, float8 skewx, float8 skewy);
Sets the georeference X and Y skew (or rotation parameter). If only one is passed in, sets X and Y to the same value. Refer to World File for more details.
-- Example 1
UPDATE dummy_rast SET rast = ST_SetSkew(rast,1,2) WHERE rid = 1;
SELECT rid, ST_SkewX(rast) As skewx, ST_SkewY(rast) As skewy,
ST_GeoReference(rast) as georef
FROM dummy_rast WHERE rid = 1;
rid | skewx | skewy | georef
----+-------+-------+--------------
1 | 1 | 2 | 2.0000000000
: 2.0000000000
: 1.0000000000
: 3.0000000000
: 0.5000000000
: 0.5000000000
-- Example 2 set both to same number:
UPDATE dummy_rast SET rast = ST_SetSkew(rast,0) WHERE rid = 1;
SELECT rid, ST_SkewX(rast) As skewx, ST_SkewY(rast) As skewy,
ST_GeoReference(rast) as georef
FROM dummy_rast WHERE rid = 1;
rid | skewx | skewy | georef
-----+-------+-------+--------------
1 | 0 | 0 | 2.0000000000
: 0.0000000000
: 0.0000000000
: 3.0000000000
: 0.5000000000
: 0.5000000000
ST_SetSRID — Sets the SRID of a raster to a particular integer srid defined in the spatial_ref_sys table.
raster ST_SetSRID(raster rast, integer srid);
Sets the SRID on a raster to a particular integer value.
![]() | |
This function does not transform the raster in any way - it simply sets meta data defining the spatial ref of the coordinate reference system that it's currently in. Useful for transformations later. |
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);
Set the value of the upper left corner of raster to the projected X and Y coordinates
SELECT ST_SetUpperLeft(rast,-71.01,42.37)
FROM dummy_rast
WHERE rid = 2;
ST_Resample — Resample a raster using a specified resampling algorithm, new dimensions, an arbitrary grid corner and a set of raster georeferencing attributes defined or borrowed from another raster.
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);
Resample a raster using a specified resampling algorithm, new dimensions (width & height), a grid corner (gridx & gridy) and a set of raster georeferencing attributes (scalex, scaley, skewx & skewy) defined or borrowed from another raster. If using a reference raster, the two rasters must have the same 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.
A maxerror percent of 0.125 is used if no maxerr is specified.
![]() | |
Refer to: GDAL Warp resampling methods for more details. |
Availability: 2.0.0 Requires GDAL 1.6.1+
Enhanced: 3.4.0 max and min resampling options added
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);
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.
When the new scalex or scaley is not a divisor of the raster width or height, the extent of the resulting raster is expanded to encompass the extent of the provided raster. If you want to be sure to retain exact input extent see 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.
![]() | |
Refer to: GDAL Warp resampling methods for more details. |
![]() | |
ST_Rescale is different from ST_SetScale in that ST_SetScale do not resample the raster to match the raster extent. ST_SetScale only changes the metadata (or georeference) of the raster to correct an originally mis-specified scaling. ST_Rescale results in a raster having different width and height computed to fit the geographic extent of the input raster. ST_SetScale do not modify the width, nor the height of the raster. |
Availability: 2.0.0 Requires GDAL 1.6.1+
Enhanced: 3.4.0 max and min resampling options added
Changed: 2.1.0 Works on rasters with no SRID
A simple example rescaling a raster from a pixel size of 0.001 degree to a pixel size of 0.0015 degree.
-- the original raster pixel size SELECT ST_PixelWidth(ST_AddBand(ST_MakeEmptyRaster(100, 100, 0, 0, 0.001, -0.001, 0, 0, 4269), '8BUI'::text, 1, 0)) width width ---------- 0.001 -- the rescaled raster raster pixel size 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 width ---------- 0.0015
ST_Resize, ST_Resample, ST_SetScale, ST_ScaleX, ST_ScaleY, ST_Transform
ST_Reskew — Resample a raster by adjusting only its skew (or rotation parameters). New pixel values are computed using the NearestNeighbor (english or american spelling), Bilinear, Cubic, CubicSpline or Lanczos resampling algorithm. Default is 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);
Resample a raster by adjusting only its skew (or rotation parameters). New pixel values are computed using the NearestNeighbor (english or american spelling), Bilinear, Cubic, CubicSpline or Lanczos resampling algorithm. The default is NearestNeighbor which is the fastest but results in the worst interpolation.
skewx and skewy define the new skew.
The extent of the new raster will encompass the extent of the provided raster.
A maxerror percent of 0.125 if no maxerr is specified.
![]() | |
Refer to: GDAL Warp resampling methods for more details. |
![]() | |
ST_Reskew is different from ST_SetSkew in that ST_SetSkew do not resample the raster to match the raster extent. ST_SetSkew only changes the metadata (or georeference) of the raster to correct an originally mis-specified skew. ST_Reskew results in a raster having different width and height computed to fit the geographic extent of the input raster. ST_SetSkew do not modify the width, nor the height of the raster. |
Availability: 2.0.0 Requires GDAL 1.6.1+
Changed: 2.1.0 Works on rasters with no SRID
A simple example reskewing a raster from a skew of 0.0 to a skew of 0.0015.
-- the original raster non-rotated SELECT ST_Rotation(ST_AddBand(ST_MakeEmptyRaster(100, 100, 0, 0, 0.001, -0.001, 0, 0, 4269), '8BUI'::text, 1, 0)); -- result 0 -- the reskewed raster raster rotation 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)); -- result -0.982793723247329
ST_Resample, ST_Rescale, ST_SetSkew, ST_SetRotation, ST_SkewX, ST_SkewY, ST_Transform
ST_SnapToGrid — Resample a raster by snapping it to a grid. New pixel values are computed using the NearestNeighbor (english or american spelling), Bilinear, Cubic, CubicSpline or Lanczos resampling algorithm. Default is 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);
Resample a raster by snapping it to a grid defined by an arbitrary pixel corner (gridx & gridy) and optionally a pixel size (scalex & scaley). New pixel values are computed using the NearestNeighbor (english or american spelling), Bilinear, Cubic, CubicSpline or Lanczos resampling algorithm. The default is NearestNeighbor which is the fastest but results in the worst interpolation.
gridx and gridy define any arbitrary pixel corner of the new grid. This is not necessarily the upper left corner of the new raster and it does not have to be inside or on the edge of the new raster extent.
You can optionally define the pixel size of the new grid with scalex and scaley.
The extent of the new raster will encompass the extent of the provided raster.
A maxerror percent of 0.125 if no maxerr is specified.
![]() | |
Refer to: GDAL Warp resampling methods for more details. |
![]() | |
Use ST_Resample if you need more control over the grid parameters. |
Availability: 2.0.0 Requires GDAL 1.6.1+
Changed: 2.1.0 Works on rasters with no SRID
A simple example snapping a raster to a slightly different grid.
-- the original raster upper left X SELECT ST_UpperLeftX(ST_AddBand(ST_MakeEmptyRaster(10, 10, 0, 0, 0.001, -0.001, 0, 0, 4269), '8BUI'::text, 1, 0)); -- result 0 -- the upper left of raster after snapping 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)); --result -0.0008
ST_Resize — Resize a raster to a new width/height
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);
Resize a raster to a new width/height. The new width/height can be specified in exact number of pixels or a percentage of the raster's width/height. The extent of the the new raster will be the same as the extent of the provided raster.
New pixel values are computed using the NearestNeighbor (english or american spelling), Bilinear, Cubic, CubicSpline or Lanczos resampling algorithm. The default is NearestNeighbor which is the fastest but results in the worst interpolation.
Variant 1 expects the actual width/height of the output raster.
Variant 2 expects decimal values between zero (0) and one (1) indicating the percentage of the input raster's width/height.
Variant 3 takes either the actual width/height of the output raster or a textual percentage ("20%") indicating the percentage of the input raster's width/height.
Availability: 2.1.0 Requires GDAL 1.6.1+
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
), bar AS (
SELECT rid, ST_Metadata(rast) AS meta, rast FROM foo
)
SELECT rid, (meta).* FROM bar
rid | upperleftx | upperlefty | width | height | scalex | scaley | skewx | skewy | srid | numbands
-----+------------+------------+-------+--------+--------+--------+-------+-------+------+----------
1 | 0 | 0 | 500 | 500 | 1 | -1 | 0 | 0 | 0 | 1
2 | 0 | 0 | 500 | 100 | 1 | -1 | 0 | 0 | 0 | 1
3 | 0 | 0 | 250 | 900 | 1 | -1 | 0 | 0 | 0 | 1
(3 rows)
ST_Transform — Reprojects a raster in a known spatial reference system to another known spatial reference system using specified resampling algorithm. Options are NearestNeighbor, Bilinear, Cubic, CubicSpline, Lanczos defaulting to 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);
Reprojects a raster in a known spatial reference system to another known spatial reference system using specified pixel warping algorithm. Uses 'NearestNeighbor' if no algorithm is specified and maxerror percent of 0.125 if no maxerr is specified.
Algorithm options are: 'NearestNeighbor', 'Bilinear', 'Cubic', 'CubicSpline', and 'Lanczos'. Refer to: GDAL Warp resampling methods for more details.
ST_Transform is often confused with ST_SetSRID(). ST_Transform actually changes the coordinates of a raster (and resamples the pixel values) from one spatial reference system to another, while ST_SetSRID() simply changes the SRID identifier of the raster.
Unlike the other variants, Variant 3 requires a reference raster as alignto. The transformed raster will be transformed to the spatial reference system (SRID) of the reference raster and be aligned (ST_SameAlignment = TRUE) to the reference raster.
![]() | |
If you find your transformation support is not working right, you may need to set the environment variable PROJSO to the .so or .dll projection library your PostGIS 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 |
![]() | |
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. |
Availability: 2.0.0 Requires GDAL 1.6.1+
Enhanced: 2.1.0 Addition of ST_Transform(rast, alignto) variant
SELECT ST_Width(mass_stm) As w_before, ST_Width(wgs_84) As w_after,
ST_Height(mass_stm) As h_before, ST_Height(wgs_84) As h_after
FROM
( SELECT rast As mass_stm, ST_Transform(rast,4326) As wgs_84
, ST_Transform(rast,4326, 'Bilinear') AS wgs_84_bilin
FROM aerials.o_2_boston
WHERE ST_Intersects(rast,
ST_Transform(ST_MakeEnvelope(-71.128, 42.2392,-71.1277, 42.2397, 4326),26986) )
LIMIT 1) As foo;
w_before | w_after | h_before | h_after
----------+---------+----------+---------
200 | 228 | 200 | 170
![]() original mass state plane meters (mass_stm) | ![]() After transform to wgs 84 long lat (wgs_84) | ![]() After transform to wgs 84 long lat with bilinear algorithm instead of NN default (wgs_84_bilin) |
The following shows the difference between using ST_Transform(raster, srid) and ST_Transform(raster, alignto)
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_SameAlignment(rast) AS rast,
ST_SameAlignment(not_aligned) AS not_aligned,
ST_SameAlignment(aligned) AS aligned
FROM baz
rast | not_aligned | aligned
------+-------------+---------
t | f | t
![]() not_aligned
| ![]() aligned
|
ST_SetBandNoDataValue — Sets the value for the given band that represents no data. Band 1 is assumed if no band is specified. To mark a band as having no nodata value, set the nodata value = NULL.
raster ST_SetBandNoDataValue(raster rast, double precision nodatavalue);
raster ST_SetBandNoDataValue(raster rast, integer band, double precision nodatavalue, boolean forcechecking=false);
Sets the value that represents no data for the band. Band 1 is assumed if not specified. This will affect results from ST_Polygon, ST_DumpAsPolygons, and the ST_PixelAs...() functions.
-- change just first band no data value
UPDATE dummy_rast
SET rast = ST_SetBandNoDataValue(rast,1, 254)
WHERE rid = 2;
-- change no data band value of bands 1,2,3
UPDATE dummy_rast
SET rast =
ST_SetBandNoDataValue(
ST_SetBandNoDataValue(
ST_SetBandNoDataValue(
rast,1, 254)
,2,99),
3,108)
WHERE rid = 2;
-- wipe out the nodata value this will ensure all pixels are considered for all processing functions
UPDATE dummy_rast
SET rast = ST_SetBandNoDataValue(rast,1, NULL)
WHERE rid = 2;
ST_SetBandIsNoData — Sets the isnodata flag of the band to TRUE.
raster ST_SetBandIsNoData(raster rast, integer band=1);
Sets the isnodata flag for the band to true. Band 1 is assumed if not specified. This function should be called only when the flag is considered dirty. That is, when the result calling ST_BandIsNoData is different using TRUE as last argument and without using it
Доступність: 2.0.0
-- Create dummy table with one raster column
create table dummy_rast (rid integer, rast raster);
-- Add raster with two bands, one pixel/band. In the first band, nodatavalue = pixel value = 3.
-- In the second band, nodatavalue = 13, pixel value = 4
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. We are going to set it to true
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);
Updates an out-db band's external raster file path and external band number.
![]() | |
If |
Доступність: 2.5.0
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,
*
FROM ST_BandMetadata(
(SELECT rast FROM foo),
ARRAY[1,3,2]::int[]
)
UNION ALL
SELECT
2,
*
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[]
)
ORDER BY 1, 2;
query | bandnum | pixeltype | nodatavalue | isoutdb | path | outdbbandnum
-------+---------+-----------+-------------+---------+---------------------------------------------------------------------------------+--------------
1 | 1 | 8BUI | | t | /home/pele/devel/geo/postgis-git/raster/test/regress/loader/Projected.tif | 1
1 | 2 | 8BUI | | t | /home/pele/devel/geo/postgis-git/raster/test/regress/loader/Projected.tif | 2
1 | 3 | 8BUI | | t | /home/pele/devel/geo/postgis-git/raster/test/regress/loader/Projected.tif | 3
2 | 1 | 8BUI | | t | /home/pele/devel/geo/postgis-git/raster/test/regress/loader/Projected.tif | 1
2 | 2 | 8BUI | | t | /home/pele/devel/geo/postgis-git/raster/test/regress/loader/Projected2.tif | 1
2 | 3 | 8BUI | | t | /home/pele/devel/geo/postgis-git/raster/test/regress/loader/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);
Updates an out-db band's external band number. This does not touch the external raster file associated with the out-db band
![]() | |
If |
![]() | |
Internally, this method replaces the PostGIS raster's band at index |
Доступність: 2.5.0
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,
*
FROM ST_BandMetadata(
(SELECT rast FROM foo),
ARRAY[1,3,2]::int[]
)
UNION ALL
SELECT
2,
*
FROM ST_BandMetadata(
(
SELECT
ST_SetBandIndex(
rast,
2,
1
) AS rast
FROM foo
),
ARRAY[1,3,2]::int[]
)
ORDER BY 1, 2;
query | bandnum | pixeltype | nodatavalue | isoutdb | path | outdbbandnum
-------+---------+-----------+-------------+---------+---------------------------------------------------------------------------------+--------------
1 | 1 | 8BUI | | t | /home/pele/devel/geo/postgis-git/raster/test/regress/loader/Projected.tif | 1
1 | 2 | 8BUI | | t | /home/pele/devel/geo/postgis-git/raster/test/regress/loader/Projected.tif | 2
1 | 3 | 8BUI | | t | /home/pele/devel/geo/postgis-git/raster/test/regress/loader/Projected.tif | 3
2 | 1 | 8BUI | | t | /home/pele/devel/geo/postgis-git/raster/test/regress/loader/Projected.tif | 1
2 | 2 | 8BUI | | t | /home/pele/devel/geo/postgis-git/raster/test/regress/loader/Projected.tif | 1
2 | 3 | 8BUI | | t | /home/pele/devel/geo/postgis-git/raster/test/regress/loader/Projected.tif | 3
ST_Count — Returns the number of pixels in a given band of a raster or raster coverage. If no band is specified defaults to band 1. If exclude_nodata_value is set to true, will only count pixels that are not equal to the nodata value.
bigint ST_Count(raster rast, integer nband=1, boolean exclude_nodata_value=true);
bigint ST_Count(raster rast, boolean exclude_nodata_value);
Returns the number of pixels in a given band of a raster or raster coverage. If no band is specified nband defaults to 1.
![]() | |
If |
Changed: 3.1.0 - The ST_Count(rastertable, rastercolumn, ...) variants removed. Use ST_CountAgg instead.
Доступність: 2.0.0
--example will count all pixels not 249 and one will count all pixels. --
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 — Aggregate. Returns the number of pixels in a given band of a set of rasters. If no band is specified defaults to band 1. If exclude_nodata_value is set to true, will only count pixels that are not equal to the NODATA value.
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);
Returns the number of pixels in a given band of a set of rasters. If no band is specified nband defaults to 1.
If exclude_nodata_value is set to true, will only count pixels with value not equal to the NODATA value of the raster. Set exclude_nodata_value to false to get count all pixels
By default will sample all pixels. To get faster response, set sample_percent to value between zero (0) and one (1)
Доступність: 2.2.0
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)
FROM foo;
st_countagg
-------------
20
(1 row)
ST_Histogram — Returns a set of record summarizing a raster or raster coverage data distribution separate bin ranges. Number of bins are autocomputed if not specified.
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);
Returns set of records consisting of min, max, count, percent for a given raster band for each bin. If no band is specified nband defaults to 1.
![]() | |
By default only considers pixel values not equal to the |
widthwidth: an array indicating the width of each category/bin. If the number of bins is greater than the number of widths, the widths are repeated.
Example: 9 bins, widths are [a, b, c] will have the output be [a, b, c, a, b, c, a, b, c]
binsNumber of breakouts -- this is the number of records you'll get back from the function if specified. If not specified then the number of breakouts is autocomputed.
rightcompute the histogram from the right rather than from the left (default). This changes the criteria for evaluating a value x from [a, b) to (a, b]
Changed: 3.1.0 Removed ST_Histogram(table_name, column_name) variant.
Доступність: 2.0.0
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.16SELECT (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.
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 — Compute quantiles for a raster or raster table coverage in the context of the sample or population. Thus, a value could be examined to be at the raster's 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);
Compute quantiles for a raster or raster table coverage in the context of the sample or population. Thus, a value could be examined to be at the raster's 25%, 50%, 75% percentile.
![]() | |
If |
Changed: 3.1.0 Removed ST_Quantile(table_name, column_name) variant.
Доступність: 2.0.0
UPDATE dummy_rast SET rast = ST_SetBandNoDataValue(rast,249) WHERE rid=2;
--Example will consider only pixels of band 1 that are not 249 and in named quantiles --
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
SELECT ST_Quantile(rast, 0.75) As value
FROM dummy_rast WHERE rid=2;
value
------
254
--real live example. Quantile of all pixels in band 2 intersecting a geometry
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_Count, ST_SummaryStats, ST_SummaryStatsAgg, ST_SetBandNoDataValue
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);
Returns summarystats consisting of count, sum, mean, stddev, min, max for a given raster band of a raster or raster coverage. If no band is specified nband defaults to 1.
![]() | |
By default only considers pixel values not equal to the |
![]() | |
By default will sample all pixels. To get faster response, set |
Changed: 3.1.0 ST_SummaryStats(rastertable, rastercolumn, ...) variants are removed. Use ST_SummaryStatsAgg instead.
Доступність: 2.0.0
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
This example 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
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
-- stats for each band --
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 -- will get better speed if set sampling to less than 100%
-- Here we set to 25% and get a much faster answer
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);
Returns summarystats consisting of count, sum, mean, stddev, min, max for a given raster band of a raster or raster coverage. If no band is specified nband defaults to 1.
![]() | |
By default only considers pixel values not equal to the |
![]() | |
By default will sample all pixels. To get faster response, set |
Доступність: 2.2.0
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,
round((stats).sum::numeric, 3),
round((stats).mean::numeric, 3),
round((stats).stddev::numeric, 3),
round((stats).min::numeric, 3),
round((stats).max::numeric, 3)
FROM (
SELECT
ST_SummaryStatsAgg(rast, 1, TRUE, 1) AS stats
FROM foo
) bar;
count | round | round | round | round | round
-------+---------+--------+-------+---------+-------
20 | -68.584 | -3.429 | 6.571 | -10.000 | 3.142
(1 row)
ST_ValueCount — Returns a set of records containing a pixel band value and count of the number of pixels in a given band of a raster (or a raster coverage) that have a given set of values. If no band is specified defaults to band 1. By default nodata value pixels are not counted. and all other values in the pixel are output and pixel band values are rounded to the nearest integer.
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);
Returns a set of records with columns value count which contain the pixel band value and count of pixels in the raster tile or raster coverage of selected band.
If no band is specified nband defaults to 1. If no searchvalues are specified, will return all pixel values found in the raster or raster coverage. If one searchvalue is given, will return an integer instead of records denoting the count of pixels having that pixel band value
![]() | |
If |
Доступність: 2.0.0
UPDATE dummy_rast SET rast = ST_SetBandNoDataValue(rast,249) WHERE rid=2;
--Example will count only pixels of band 1 that are not 249. --
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 --
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
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
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 --
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
ST_RastFromWKB — Return a raster value from a Well-Known Binary (WKB) raster.
raster ST_RastFromWKB(bytea wkb);
Given a Well-Known Binary (WKB) raster, return a raster.
Доступність: 2.5.0
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_MetaData, ST_RastFromHexWKB, ST_AsBinary/ST_AsWKB, ST_AsHexWKB
ST_RastFromHexWKB — Return a raster value from a Hex representation of Well-Known Binary (WKB) raster.
raster ST_RastFromHexWKB(text wkb);
Given a Well-Known Binary (WKB) raster in Hex representation, return a raster.
Доступність: 2.5.0
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
ST_MetaData, ST_RastFromWKB, ST_AsBinary/ST_AsWKB, ST_AsHexWKB
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);
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.
This is useful in binary cursors to pull data out of the database without converting it to a string representation.
![]() | |
By default, 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 |
Enhanced: 2.1.0 Addition of outasin
Enhanced: 2.5.0 Addition of ST_AsWKB
SELECT ST_AsBinary(rast) As rastbin FROM dummy_rast WHERE rid=1;
rastbin
---------------------------------------------------------------------------------
\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);
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 |
Доступність: 2.5.0
SELECT ST_AsHexWKB(rast) As rastbin FROM dummy_rast WHERE rid=1;
st_ashexwkb
----------------------------------------------------------------------------------------------------------------------------
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);
Returns the raster tile in the designated format. Arguments are itemized below:
format format to output. This is dependent on the drivers compiled in your libgdal library. Generally available are 'JPEG', 'GTIff', 'PNG'. Use ST_GDALDrivers to get a list of formats supported by your library.
options text array of GDAL options. Valid options are dependent on the format. Refer to GDAL Raster format options for more details.
srs The proj4text or srtext (from spatial_ref_sys) to embed in the image
Availability: 2.0.0 - requires GDAL >= 1.6.0.
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. We'lll repeat the prior example but also exporting. Note for this you'll need to have super user access to db since it uses server side lo 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.
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;
SELECT ST_AsGDALRaster(rast, 'GTiff') As rastjpg
FROM dummy_rast WHERE rid=2;
-- Out GeoTiff with jpeg compression, 90% quality
SELECT ST_AsGDALRaster(rast, 'GTiff',
ARRAY['COMPRESS=JPEG', 'JPEG_QUALITY=90'],
4269) As rasttiff
FROM dummy_rast WHERE rid=2;
ST_AsJPEG — Return the raster tile selected bands as a single Joint Photographic Exports Group (JPEG) image (byte array). If no band is specified and 1 or more than 3 bands, then only the first band is used. If only 3 bands then all 3 bands are used and mapped to 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);
Returns the selected bands of the raster as a single Joint Photographic Exports Group Image (JPEG). Use ST_AsGDALRaster if you need to export as less common raster types. If no band is specified and 1 or more than 3 bands, then only the first band is used. If 3 bands then all 3 bands are used. There are many variants of the function with many options. These are itemized below:
nband is for single band exports.
nbands is an array of bands to export (note that max is 3 for JPEG) and the order of the bands is RGB. e.g ARRAY[3,2,1] means map band 3 to Red, band 2 to green and band 1 to blue
quality number from 0 to 100. The higher the number the crisper the image.
options text Array of GDAL options as defined for JPEG (look at create_options for JPEG ST_GDALDrivers). For JPEG valid ones are PROGRESSIVE ON or OFF and QUALITY a range from 0 to 100 and default to 75. Refer to GDAL Raster format options for more details.
Availability: 2.0.0 - requires GDAL >= 1.6.0.
-- output first 3 bands 75% quality
SELECT ST_AsJPEG(rast) As rastjpg
FROM dummy_rast WHERE rid=2;
-- output only first band as 90% quality
SELECT ST_AsJPEG(rast,1,90) As rastjpg
FROM dummy_rast WHERE rid=2;
-- output first 3 bands (but make band 2 Red, band 1 green, and band 3 blue, progressive and 90% quality
SELECT ST_AsJPEG(rast,ARRAY[2,1,3],ARRAY['QUALITY=90','PROGRESSIVE=ON']) As rastjpg
FROM dummy_rast WHERE rid=2;ST_AsPNG — Return the raster tile selected bands as a single portable network graphics (PNG) image (byte array). If 1, 3, or 4 bands in raster and no bands are specified, then all bands are used. If more 2 or more than 4 bands and no bands specified, then only band 1 is used. Bands are mapped to RGB or RGBA space.
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);
Returns the selected bands of the raster as a single Portable Network Graphics Image (PNG). Use ST_AsGDALRaster if you need to export as less common raster types. If no band is specified, then the first 3 bands are exported. There are many variants of the function with many options. If no srid is specified then then srid of the raster is used. These are itemized below:
nband is for single band exports.
nbands is an array of bands to export (note that max is 4 for PNG) and the order of the bands is RGBA. e.g ARRAY[3,2,1] means map band 3 to Red, band 2 to green and band 1 to blue
compression number from 1 to 9. The higher the number the greater the compression.
options text Array of GDAL options as defined for PNG (look at create_options for PNG of ST_GDALDrivers). For PNG valid one is only ZLEVEL (amount of time to spend on compression -- default 6) e.g. ARRAY['ZLEVEL=9']. WORLDFILE is not allowed since the function would have to output two outputs. Refer to GDAL Raster format options for more details.
Availability: 2.0.0 - requires GDAL >= 1.6.0.
SELECT ST_AsPNG(rast) As rastpng
FROM dummy_rast WHERE rid=2;
-- export the first 3 bands and map band 3 to Red, band 1 to Green, band 2 to blue
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);
Returns the selected bands of the raster as a single Tagged Image File Format (TIFF). If no band is specified, will try to use all bands. This is a wrapper around ST_AsGDALRaster. Use ST_AsGDALRaster if you need to export as less common raster types. There are many variants of the function with many options. If no spatial reference SRS text is present, the spatial reference of the raster is used. These are itemized below:
nbands is an array of bands to export (note that max is 3 for PNG) and the order of the bands is RGB. e.g ARRAY[3,2,1] means map band 3 to Red, band 2 to green and band 1 to blue
compression Compression expression -- JPEG90 (or some other percent), LZW, JPEG, DEFLATE9.
options text Array of GDAL create options as defined for GTiff (look at create_options for GTiff of ST_GDALDrivers). or refer to GDAL Raster format options for more details.
srid srid of spatial_ref_sys of the raster. This is used to populate the georeference information
Availability: 2.0.0 - requires GDAL >= 1.6.0.
SELECT ST_AsTIFF(rast, 'JPEG90') As rasttiff
FROM dummy_rast WHERE rid=2;
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_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);
Returns a raster that is clipped by the input geometry geom. If band index is not specified, all bands are processed.
Rasters resulting from ST_Clip must have a nodata value assigned for areas clipped, one for each band. If none are provided and the input raster do not have a nodata value defined, nodata values of the resulting raster are set to ST_MinPossibleValue(ST_BandPixelType(rast, band)). When the number of nodata value in the array is smaller than the number of band, the last one in the array is used for the remaining bands. If the number of nodata value is greater than the number of band, the extra nodata values are ignored. All variants accepting an array of nodata values also accept a single value which will be assigned to each band.
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
Enhanced: 2.1.0 Rewritten in C
Examples here use Massachusetts aerial data available on MassGIS site MassGIS Aerial Orthos.
SELECT ST_Count(rast) AS count_pixels_in_orig, ST_Count(rast_touched) AS all_touched_pixels, ST_Count(rast_not_touched) AS default_clip
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)
, ST_Clip(r.rast, g.geom, touched =
> true) AS rast_touched
, ST_Clip(r.rast, g.geom, touched =
> false) AS rast_not_touched;
count_pixels_in_orig | all_touched_pixels | default_clip
----------------------+--------------------+--------------
2605 | 16 | 10
(1 row)
-- Clip the first band of an aerial tile by a 20 meter buffer.
SELECT ST_Clip(rast, 1,
ST_Buffer(ST_Centroid(ST_Envelope(rast)),20)
) from aerials.boston
WHERE rid = 4;
-- Demonstrate effect of crop on final dimensions of raster
-- Note how final extent is clipped to that of the geometry
-- if crop = true
SELECT ST_XMax(ST_Envelope(ST_Clip(rast, 1, clipper, true))) As xmax_w_trim,
ST_XMax(clipper) As xmax_clipper,
ST_XMax(ST_Envelope(ST_Clip(rast, 1, clipper, false))) As xmax_wo_trim,
ST_XMax(ST_Envelope(rast)) As xmax_rast_orig
FROM (SELECT rast, ST_Buffer(ST_Centroid(ST_Envelope(rast)),6) As clipper
FROM aerials.boston
WHERE rid = 6) As foo;
xmax_w_trim | xmax_clipper | xmax_wo_trim | xmax_rast_orig
------------------+------------------+------------------+------------------
230657.436173996 | 230657.436173996 | 230666.436173996 | 230666.436173996
|
![]() Full raster tile before clipping
|
![]() After Clipping
|
-- Same example as before, but we need to set crop to false to be able to use ST_AddBand
-- because ST_AddBand requires all bands be the same Width and height
SELECT ST_AddBand(ST_Clip(rast, 1,
ST_Buffer(ST_Centroid(ST_Envelope(rast)),20),false
), ARRAY[ST_Band(rast,2),ST_Band(rast,3)] ) from aerials.boston
WHERE rid = 6;
|
![]() Full raster tile before clipping
|
![]() After Clipping - surreal
|
-- Clip all bands of an aerial tile by a 20 meter buffer.
-- Only difference is we don't specify a specific band to clip
-- so all bands are clipped
SELECT ST_Clip(rast,
ST_Buffer(ST_Centroid(ST_Envelope(rast)), 20),
false
) from aerials.boston
WHERE rid = 4;
|
![]() Full raster tile before clipping
|
![]() After Clipping
|
ST_ColorMap — Creates a new raster of up to four 8BUI bands (grayscale, RGB, RGBA) from the source raster and a specified band. Band 1 is assumed if not specified.
raster ST_ColorMap(raster rast, integer nband=1, text colormap=grayscale, text method=INTERPOLATE);
raster ST_ColorMap(raster rast, text colormap, text method=INTERPOLATE);
Apply a colormap to the band at nband of rast resulting a new raster comprised of up to four 8BUI bands. The number of 8BUI bands in the new raster is determined by the number of color components defined in colormap.
If nband is not specified, then band 1 is assumed.
colormap can be a keyword of a pre-defined colormap or a set of lines defining the value and the color components.
Valid pre-defined colormap keyword:
grayscale or greyscale for a one 8BUI band raster of shades of gray.
pseudocolor for a four 8BUI (RGBA) band raster with colors going from blue to green to red.
fire for a four 8BUI (RGBA) band raster with colors going from black to red to pale yellow.
bluered for a four 8BUI (RGBA) band raster with colors going from blue to pale white to red.
Users can pass a set of entries (one per line) to colormap to specify custom colormaps. Each entry generally consists of five values: the pixel value and corresponding Red, Green, Blue, Alpha components (color components between 0 and 255). Percent values can be used instead of pixel values where 0% and 100% are the minimum and maximum values found in the raster band. Values can be separated with commas (','), tabs, colons (':') and/or spaces. The pixel value can be set to nv, null or nodata for the NODATA value. An example is provided below.
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
The syntax of colormap is similar to that of the color-relief mode of GDAL gdaldem.
Valid keywords for method:
INTERPOLATE to use linear interpolation to smoothly blend the colors between the given pixel values
EXACT to strictly match only those pixels values found in the colormap. Pixels whose value does not match a colormap entry will be set to 0 0 0 0 (RGBA)
NEAREST to use the colormap entry whose value is closest to the pixel value
![]() | |
A great reference for colormaps is ColorBrewer. |
![]() | |
The resulting bands of new raster will have no NODATA value set. Use ST_SetBandNoDataValue to set a NODATA value if one is needed. |
Доступність: 2.1.0
This is a junk table to play with
-- setup test raster table --
DROP TABLE IF EXISTS funky_shapes;
CREATE TABLE funky_shapes(rast raster);
INSERT INTO funky_shapes(rast)
WITH ref AS (
SELECT ST_MakeEmptyRaster( 200, 200, 0, 200, 1, -1, 0, 0) AS rast
)
SELECT
ST_Union(rast)
FROM (
SELECT
ST_AsRaster(
ST_Rotate(
ST_Buffer(
ST_GeomFromText('LINESTRING(0 2,50 50,150 150,125 50)'),
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
ST_NumBands(rast) As n_orig,
ST_NumBands(ST_ColorMap(rast,1, 'greyscale')) As ngrey,
ST_NumBands(ST_ColorMap(rast,1, 'pseudocolor')) As npseudo,
ST_NumBands(ST_ColorMap(rast,1, 'fire')) As nfire,
ST_NumBands(ST_ColorMap(rast,1, 'bluered')) As nbluered,
ST_NumBands(ST_ColorMap(rast,1, '
100% 255 0 0
80% 160 0 0
50% 130 0 0
30% 30 0 0
20% 60 0 0
0% 0 0 0
nv 255 255 255
')) As nred
FROM funky_shapes;
n_orig | ngrey | npseudo | nfire | nbluered | nred
--------+-------+---------+-------+----------+------
1 | 1 | 4 | 4 | 4 | 3
SELECT
ST_AsPNG(rast) As orig_png,
ST_AsPNG(ST_ColorMap(rast,1,'greyscale')) As grey_png,
ST_AsPNG(ST_ColorMap(rast,1, 'pseudocolor')) As pseudo_png,
ST_AsPNG(ST_ColorMap(rast,1, 'nfire')) As fire_png,
ST_AsPNG(ST_ColorMap(rast,1, 'bluered')) As bluered_png,
ST_AsPNG(ST_ColorMap(rast,1, '
100% 255 0 0
80% 160 0 0
50% 130 0 0
30% 30 0 0
20% 60 0 0
0% 0 0 0
nv 255 255 255
')) As red_png
FROM funky_shapes;
|
![]() orig_png
|
![]() grey_png
|
![]() pseudo_png
|
|
![]() fire_png
|
![]() bluered_png
|
![]() red_png
|
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);
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 |
Доступність: 2.5.0
SET postgis.gdal_enabled_drivers = 'ENABLE_ALL';
SET postgis.enable_outdb_rasters = True;
WITH apple AS (
SELECT ST_AddBand(
ST_MakeEmptyRaster(350, 246, 0, 0, 1, -1, 0, 0, 0),
'/tmp/apple.png'::text,
NULL::int[]
) AS rast
)
SELECT
ST_AsPNG(rast) AS original_png,
ST_AsPNG(ST_Grayscale(rast)) AS grayscale_png
FROM apple;
|
![]() original_png
|
![]() grayscale_png
|
SET postgis.gdal_enabled_drivers = 'ENABLE_ALL';
SET postgis.enable_outdb_rasters = True;
WITH apple AS (
SELECT ST_AddBand(
ST_MakeEmptyRaster(350, 246, 0, 0, 1, -1, 0, 0, 0),
'/tmp/apple.png'::text,
NULL::int[]
) AS rast
)
SELECT
ST_AsPNG(rast) AS original_png,
ST_AsPNG(ST_Grayscale(
ARRAY[
ROW(rast, 1)::rastbandarg, -- red
ROW(rast, 2)::rastbandarg, -- green
ROW(rast, 3)::rastbandarg, -- blue
]::rastbandarg[]
)) AS grayscale_png
FROM apple;
ST_Intersection — Returns a raster or a set of geometry-pixelvalue pairs representing the shared portion of two rasters or the geometrical intersection of a vectorization of the raster and a geometry.
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);
Returns a raster or a set of geometry-pixelvalue pairs representing the shared portion of two rasters or the geometrical intersection of a vectorization of the raster and a geometry.
The first three variants, returning a setof geomval, works in vector space. The raster is first vectorized (using ST_DumpAsPolygons) into a set of geomval rows and those rows are then intersected with the geometry using the ST_Intersection (geometry, geometry) PostGIS function. Geometries intersecting only with a nodata value area of a raster returns an empty geometry. They are normally excluded from the results by the proper usage of ST_Intersects in the WHERE clause.
You can access the geometry and the value parts of the resulting set of geomval by surrounding them with parenthesis and adding '.geom' or '.val' at the end of the expression. e.g. (ST_Intersection(rast, geom)).geom
The other variants, returning a raster, works in raster space. They are using the two rasters version of ST_MapAlgebraExpr to perform the intersection.
The extent of the resulting raster corresponds to the geometrical intersection of the two raster extents. The resulting raster includes 'BAND1', 'BAND2' or 'BOTH' bands, following what is passed as the returnband parameter. Nodata value areas present in any band results in nodata value areas in every bands of the result. In other words, any pixel intersecting with a nodata value pixel becomes a nodata value pixel in the result.
Rasters resulting from ST_Intersection must have a nodata value assigned for areas not intersecting. You can define or replace the nodata value for any resulting band by providing a nodataval[] array of one or two nodata values depending if you request 'BAND1', 'BAND2' or 'BOTH' bands. The first value in the array replace the nodata value in the first band and the second value replace the nodata value in the second band. If one input band do not have a nodata value defined and none are provided as an array, one is chosen using the ST_MinPossibleValue function. All variant accepting an array of nodata value can also accept a single value which will be assigned to each requested band.
In all variants, if no band number is specified band 1 is assumed. If you need an intersection between a raster and geometry that returns a raster, refer to ST_Clip.
![]() | |
To get more control on the resulting extent or on what to return when encountering a nodata value, use the two rasters version of ST_MapAlgebraExpr. |
![]() | |
To compute the intersection of a raster band with a geometry in raster space, use ST_Clip. ST_Clip works on multiple bands rasters and does not return a band corresponding to the rasterized geometry. |
![]() | |
ST_Intersection should be used in conjunction with ST_Intersects and an index on the raster column and/or the geometry column. |
Enhanced: 2.0.0 - Intersection in the raster space was introduced. In earlier pre-2.0.0 versions, only intersection performed in vector space were supported.
SELECT
foo.rid,
foo.gid,
ST_AsText((foo.geomval).geom) As geomwkt,
(foo.geomval).val
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, ST_GeomFromText('LINESTRING(3427927.85 5793243.75,3427927.8 5793243.75,3427927.8 5793243.8)')),
(3, ST_GeomFromText('LINESTRING(1 2, 3 4)'))
) As g(gid,geom)
WHERE A.rid = 2
) As foo;
rid | gid | geomwkt | val
-----+-----+---------------------------------------------------------------------------------------------
2 | 1 | POINT(3427928 5793243.85) | 249
2 | 1 | POINT(3427928 5793243.85) | 253
2 | 2 | POINT(3427927.85 5793243.75) | 254
2 | 2 | POINT(3427927.8 5793243.8) | 251
2 | 2 | POINT(3427927.8 5793243.8) | 253
2 | 2 | LINESTRING(3427927.8 5793243.75,3427927.8 5793243.8) | 252
2 | 2 | MULTILINESTRING((3427927.8 5793243.8,3427927.8 5793243.75),...) | 250
2 | 3 | GEOMETRYCOLLECTION EMPTY
geomval, ST_Intersects, ST_MapAlgebraExpr, ST_Clip, ST_AsText
ST_MapAlgebra (callback function version) — Callback function version - Returns a one-band raster given one or more input rasters, band indexes and one user-specified callback function.
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);
Returns a one-band raster given one or more input rasters, band indexes and one user-specified callback function.
rast,rast1,rast2, rastbandargsetRasters on which the map algebra process is evaluated.
rastbandargset allows the use of a map algebra operation on many rasters and/or many bands. See example Variant 1.
nband, nband1, nband2Band numbers of the raster to be evaluated. nband can be an integer or integer[] denoting the bands. nband1 is band on rast1 and nband2 is band on rast2 for the 2 raster/2band case.
callbackfuncThe 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:
CREATE OR REPLACE FUNCTION sample_callbackfunc(value double precision[][][], position integer[][], VARIADIC userargs text[])
RETURNS double precision
AS $$
BEGIN
RETURN 0;
END;
$$ LANGUAGE 'plpgsql' IMMUTABLE;
The callbackfunc must have three arguments: a 3-dimension double precision array, a 2-dimension integer array and 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 third argument userargs is for passing through any user-specified arguments.
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:
'sample_callbackfunc(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.
maskAn 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.
weightedboolean (true/false) to denote if a mask value should be weighted (multiplied by original value) or not (only applies to proto that takes a mask).
pixeltypeIf pixeltype is passed in, the one band of the new raster will be of that pixeltype. If pixeltype is passed NULL or left out, the new raster band will have the same pixeltype as the specified band of the first raster (for extent types: INTERSECTION, UNION, FIRST, CUSTOM) or the specified band of the appropriate raster (for extent types: SECOND, LAST). If in doubt, always specify pixeltype.
The resulting pixel type of the output raster must be one listed in ST_BandPixelType or left out or set to NULL.
extenttypePossible values are INTERSECTION (default), UNION, FIRST (default for one raster variants), SECOND, LAST, CUSTOM.
customextentIf extentype is CUSTOM, a raster must be provided for customextent. See example 4 of Variant 1.
distancexThe 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).
distanceyThe distance in pixels from reference cell in y direction. Height of resulting matrix would be 2*distancey + 1 .If not specified only the reference cell is considered (neighborhood of 0).
userargsThe third argument to the callbackfunc is a variadic text array. All trailing text arguments are passed through to the specified callbackfunc, and are contained in the userargs argument.
![]() | |
For more information about the VARIADIC keyword, please refer to the PostgreSQL documentation and the "SQL Functions with Variable Numbers of Arguments" section of Query Language (SQL) Functions. |
![]() | |
The text[] argument to the |
Variant 1 accepts an array of rastbandarg allowing the use of a map algebra operation on many rasters and/or many bands. See example Variant 1.
Variants 2 and 3 operate upon one or more bands of one raster. See example Variant 2 and 3.
Variant 4 operate upon two rasters with one band per raster. See example Variant 4.
Availability: 2.2.0: Ability to add a mask
Доступність: 2.1.0
One raster, one band
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
One raster, several bands
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
Several rasters, several bands
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. This query only works with PostgreSQL 9.1 or higher.
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 works with PostgreSQL 9.0.
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
)
WITH 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[],
'raster_nmapalgebra_test(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;
One raster, several bands
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
One raster, one band
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
Two rasters, two bands
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
WITH foo AS (SELECT
ST_SetBandNoDataValue(
ST_SetValue(ST_SetValue(ST_AsRaster(
ST_Buffer(
ST_GeomFromText('LINESTRING(50 50,100 90,100 50)'), 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 )
SELECT 'original' AS title, rast
FROM foo
UNION ALL
SELECT 'no mask mean value' AS title, ST_MapAlgebra(rast,1,'ST_mean4ma(double precision[], int[], text[])'::regprocedure) AS rast
FROM foo
UNION ALL
SELECT 'mask only consider neighbors, exclude center' 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 'mask weighted only consider neighbors, exclude center multi other pixel values by 2' 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;
|
![]() original
|
![]() no mask mean value (same as having all 1s in mask matrix)
|
|
![]() mask only consider neighbors, exclude center
|
![]() mask weighted only consider neighbors, exclude center multi other pixel values by 2
|
ST_MapAlgebra (expression version) — Expression version - Returns a one-band raster given one or two input rasters, band indexes and one or more user-specified SQL expressions.
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);
Expression version - Returns a one-band raster given one or two input rasters, band indexes and one or more user-specified SQL expressions.
Доступність: 2.1.0
Creates a new one band raster formed by applying a valid PostgreSQL algebraic operation defined by the expression on the input raster (rast). If nband is not provided, band 1 is assumed. The new raster will have the same georeference, width, and height as the original raster but will only have one band.
If pixeltype is passed in, then the new raster will have a band of that pixeltype. If pixeltype is passed NULL, then the new raster band will have the same pixeltype as the input rast band.
Keywords permitted for expression
[rast] - Pixel value of the pixel of interest
[rast.val] - Pixel value of the pixel of interest
[rast.x] - 1-based pixel column of the pixel of interest
[rast.y] - 1-based pixel row of the pixel of interest
Creates a new one band raster formed by applying a valid PostgreSQL algebraic operation to the two bands defined by the expression on the two input raster bands rast1, (rast2). If no band1, band2 is specified band 1 is assumed. The resulting raster will be aligned (scale, skew and pixel corners) on the grid defined by the first raster. The resulting raster will have the extent defined by the extenttype parameter.
expressionA PostgreSQL algebraic expression involving the two rasters and PostgreSQL defined functions/operators that will define the pixel value when pixels intersect. e.g. (([rast1] + [rast2])/2.0)::integer
pixeltypeThe resulting pixel type of the output raster. Must be one listed in ST_BandPixelType, left out or set to NULL. If not passed in or set to NULL, will default to the pixeltype of the first raster.
extenttypeControls the extent of resulting raster
INTERSECTION - The extent of the new raster is the intersection of the two rasters. This is the default.
UNION - The extent of the new raster is the union of the two rasters.
FIRST - The extent of the new raster is the same as the one of the first raster.
SECOND - The extent of the new raster is the same as the one of the second raster.
nodata1exprAn algebraic expression involving only rast2 or a constant that defines what to return when pixels of rast1 are nodata values and spatially corresponding rast2 pixels have values.
nodata2exprAn algebraic expression involving only rast1 or a constant that defines what to return when pixels of rast2 are nodata values and spatially corresponding rast1 pixels have values.
nodatanodatavalA numeric constant to return when spatially corresponding rast1 and rast2 pixels are both nodata values.
Keywords permitted in expression, nodata1expr and nodata2expr
[rast1] - Pixel value of the pixel of interest from rast1
[rast1.val] - Pixel value of the pixel of interest from rast1
[rast1.x] - 1-based pixel column of the pixel of interest from rast1
[rast1.y] - 1-based pixel row of the pixel of interest from rast1
[rast2] - Pixel value of the pixel of interest from rast2
[rast2.val] - Pixel value of the pixel of interest from rast2
[rast2.x] - 1-based pixel column of the pixel of interest from rast2
[rast2.y] - 1-based pixel row of the pixel of interest from rast2
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;
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 raster band version: Creates a new one band raster formed by applying a valid PostgreSQL algebraic operation on the input raster band and of pixeltype provided. Band 1 is assumed if no band is specified.
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);
![]() | |
ST_MapAlgebraExpr is deprecated as of 2.1.0. Use ST_MapAlgebra (expression version) instead. |
Creates a new one band raster formed by applying a valid PostgreSQL algebraic operation defined by the expression on the input raster (rast). If no band is specified band 1 is assumed. The new raster will have the same georeference, width, and height as the original raster but will only have one band.
If pixeltype is passed in, then the new raster will have a band of that pixeltype. If pixeltype is passed NULL, then the new raster band will have the same pixeltype as the input rast band.
In the expression you can use the term [rast] to refer to the pixel value of the original band, [rast.x] to refer to the 1-based pixel column index, [rast.y] to refer to the 1-based pixel row index.
Доступність: 2.0.0
Create a new 1 band raster from our original that is a function of modulo 2 of the original raster band.
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
Create a new 1 band raster of pixel-type 2BUI from our original that is reclassified and set the nodata value to be 0.
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
SELECT
ST_BandPixelType(map_rast2) As b1pixtyp
FROM dummy_rast
WHERE rid = 2;
b1pixtyp
----------
2BUI
|
![]() original (column rast_view)
|
![]() rast_view_ma
|
Create a new 3 band raster same pixel type from our original 3 band raster with first band altered by map algebra and remaining 2 bands unaltered.
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, ST_MapAlgebraFct, ST_BandPixelType, ST_GeoReference, ST_Value
ST_MapAlgebraExpr — 2 raster band version: Creates a new one band raster formed by applying a valid PostgreSQL algebraic operation on the two input raster bands and of pixeltype provided. band 1 of each raster is assumed if no band numbers are specified. The resulting raster will be aligned (scale, skew and pixel corners) on the grid defined by the first raster and have its extent defined by the "extenttype" parameter. Values for "extenttype" can be: 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);
![]() | |
ST_MapAlgebraExpr is deprecated as of 2.1.0. Use ST_MapAlgebra (expression version) instead. |
Creates a new one band raster formed by applying a valid PostgreSQL algebraic operation to the two bands defined by the expression on the two input raster bands rast1, (rast2). If no band1, band2 is specified band 1 is assumed. The resulting raster will be aligned (scale, skew and pixel corners) on the grid defined by the first raster. The resulting raster will have the extent defined by the extenttype parameter.
expressionA PostgreSQL algebraic expression involving the two rasters and PostgreSQL defined functions/operators that will define the pixel value when pixels intersect. e.g. (([rast1] + [rast2])/2.0)::integer
pixeltypeThe resulting pixel type of the output raster. Must be one listed in ST_BandPixelType, left out or set to NULL. If not passed in or set to NULL, will default to the pixeltype of the first raster.
extenttypeControls the extent of resulting raster
INTERSECTION - The extent of the new raster is the intersection of the two rasters. This is the default.
UNION - The extent of the new raster is the union of the two rasters.
FIRST - The extent of the new raster is the same as the one of the first raster.
SECOND - The extent of the new raster is the same as the one of the second raster.
nodata1exprAn algebraic expression involving only rast2 or a constant that defines what to return when pixels of rast1 are nodata values and spatially corresponding rast2 pixels have values.
nodata2exprAn algebraic expression involving only rast1 or a constant that defines what to return when pixels of rast2 are nodata values and spatially corresponding rast1 pixels have values.
nodatanodatavalA numeric constant to return when spatially corresponding rast1 and rast2 pixels are both nodata values.
If pixeltype is passed in, then the new raster will have a band of that pixeltype. If pixeltype is passed NULL or no pixel type specified, then the new raster band will have the same pixeltype as the input rast1 band.
Use the term [rast1.val] [rast2.val] to refer to the pixel value of the original raster bands and [rast1.x], [rast1.y] etc. to refer to the column / row positions of the pixels.
Доступність: 2.0.0
Create a new 1 band raster from our original that is a function of modulo 2 of the original raster band.
--Create a cool set of rasters --
DROP TABLE IF EXISTS fun_shapes;
CREATE TABLE fun_shapes(rid serial PRIMARY KEY, fun_name text, rast raster);
-- Insert some cool shapes around Boston in Massachusetts state plane meters --
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;
--map them -
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
|
![]() mapalgebra intersection
|
![]() map algebra union
|
-- we use ST_AsPNG to render the image so all single band ones look grey --
WITH mygeoms
AS ( SELECT 2 As bnum, ST_Buffer(ST_Point(1,5),10) As geom
UNION ALL
SELECT 3 AS bnum,
ST_Buffer(ST_GeomFromText('LINESTRING(50 50,150 150,150 50)'), 10,'join=bevel') As geom
UNION ALL
SELECT 1 As bnum,
ST_Buffer(ST_GeomFromText('LINESTRING(60 50,150 150,150 50)'), 5,'join=bevel') As geom
),
-- define our canvas to be 1 to 1 pixel to geometry
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,
Max(ST_SRID(geom)) As srid
from mygeoms
) As foo
),
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]') As rast
FROM mygeoms AS m CROSS JOIN canvas
ORDER BY m.bnum) As rasts
)
SELECT rasts[1] As rast1 , rasts[2] As rast2, rasts[3] As rast3, ST_AddBand(
ST_AddBand(rasts[1],rasts[2]), rasts[3]) As final_rast
FROM rbands;
|
![]() rast1
|
![]() rast2
|
|
![]() rast3
|
![]() final_rast
|
-- Create new 3 band raster composed of first 2 clipped bands, and overlay of 3rd band with our geometry
-- This query took 3.6 seconds on PostGIS windows 64-bit install
WITH pr AS
-- Note the order of operation: we clip all the rasters to dimensions of our region
(SELECT ST_Clip(rast,ST_Expand(geom,50) ) As rast, g.geom
FROM aerials.o_2_boston AS r INNER JOIN
-- union our parcels of interest so they form a single geometry we can later intersect with
(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))
),
-- we then union the raster shards together
-- ST_Union on raster is kinda of slow but much faster the smaller you can get the rasters
-- therefore we want to clip first and then union
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)
-- return our final raster which is the unioned shard with
-- with the overlay of our parcel boundaries
-- add first 2 bands, then mapalgebra of 3rd band + geometry
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;
|
![]() The blue lines are the boundaries of select parcels
|
ST_MapAlgebraFct — 1 band version - Creates a new one band raster formed by applying a valid PostgreSQL function on the input raster band and of pixeltype provided. Band 1 is assumed if no band is specified.
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);
![]() | |
ST_MapAlgebraFct is deprecated as of 2.1.0. Use ST_MapAlgebra (callback function version) instead. |
Creates a new one band raster formed by applying a valid PostgreSQL function specified by the onerasteruserfunc on the input raster (rast). If no band is specified, band 1 is assumed. The new raster will have the same georeference, width, and height as the original raster but will only have one band.
If pixeltype is passed in, then the new raster will have a band of that pixeltype. If pixeltype is passed NULL, then the new raster band will have the same pixeltype as the input rast band.
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:
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:
'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.
The third argument to the userfunction is a variadic text array. All trailing text arguments to any ST_MapAlgebraFct call are passed through to the specified userfunction, and are contained in the args argument.
![]() | |
For more information about the VARIADIC keyword, please refer to the PostgreSQL documentation and the "SQL Functions with Variable Numbers of Arguments" section of Query Language (SQL) Functions. |
![]() | |
The text[] argument to the |
Доступність: 2.0.0
Create a new 1 band raster from our original that is a function of modulo 2 of the original raster band.
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
Create a new 1 band raster of pixel-type 2BUI from our original that is reclassified and set the nodata value to a passed parameter to the user function (0).
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
SELECT ST_BandPixelType(map_rast2) As b1pixtyp
FROM dummy_rast WHERE rid = 2;
b1pixtyp
----------
2BUI
![]() original (column rast-view) | ![]() rast_view_ma |
Create a new 3 band raster same pixel type from our original 3 band raster with first band altered by map algebra and remaining 2 bands unaltered.
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;
ST_MapAlgebraExpr, ST_BandPixelType, ST_GeoReference, ST_SetValue
ST_MapAlgebraFct — 2 band version - Creates a new one band raster formed by applying a valid PostgreSQL function on the 2 input raster bands and of pixeltype provided. Band 1 is assumed if no band is specified. Extent type defaults to INTERSECTION if not specified.
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);
![]() | |
ST_MapAlgebraFct is deprecated as of 2.1.0. Use ST_MapAlgebra (callback function version) instead. |
Creates a new one band raster formed by applying a valid PostgreSQL function specified by the tworastuserfunc on the input raster rast1, rast2. If no band1 or band2 is specified, band 1 is assumed. The new raster will have the same georeference, width, and height as the original rasters but will only have one band.
If pixeltype is passed in, then the new raster will have a band of that pixeltype. If pixeltype is passed NULL or left out, then the new raster band will have the same pixeltype as the input rast1 band.
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:
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:
'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.
![]() | |
For more information about the VARIADIC keyword, please refer to the PostgreSQL documentation and the "SQL Functions with Variable Numbers of Arguments" section of Query Language (SQL) Functions. |
![]() | |
The text[] argument to the |
Доступність: 2.0.0
-- define our user defined function --
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;
-- prep our test table of rasters
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 with ST_AddBand
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;
|
![]() map bands overlay (canvas) (R: small road, G: circle, B: big road)
|
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)';

user defined with extra args and different bands from same raster
ST_MapAlgebraExpr, ST_BandPixelType, ST_GeoReference, ST_SetValue
ST_MapAlgebraFctNgb — 1-band version: Map Algebra Nearest Neighbor using user-defined PostgreSQL function. Return a raster which values are the result of a PLPGSQL user function involving a neighborhood of values from the input raster band.
raster ST_MapAlgebraFctNgb(raster rast, integer band, text pixeltype, integer ngbwidth, integer ngbheight, regprocedure onerastngbuserfunc, text nodatamode, text[] VARIADIC args);
![]() | |
ST_MapAlgebraFctNgb is deprecated as of 2.1.0. Use ST_MapAlgebra (callback function version) instead. |
(one raster version) Return a raster which values are the result of a PLPGSQL user function involving a neighborhood of values from the input raster band. The user function takes the neighborhood of pixel values as an array of numbers, for each pixel, returns the result from the user function, replacing pixel value of currently inspected pixel with the function result.
rastRaster on which the user function is evaluated.
bandBand number of the raster to be evaluated. Default to 1.
pixeltypeThe resulting pixel type of the output raster. Must be one listed in ST_BandPixelType or left out or set to NULL. If not passed in or set to NULL, will default to the pixeltype of the rast. Results are truncated if they are larger than what is allowed for the pixeltype.
ngbwidthThe width of the neighborhood, in cells.
ngbheightThe height of the neighborhood, in cells.
onerastngbuserfuncPLPGSQL/psql user function to apply to neighborhood pixels of a single band of a raster. The first element is a 2-dimensional array of numbers representing the rectangular pixel neighborhood
nodatamodeDefines what value to pass to the function for a neighborhood pixel that is nodata or NULL
'ignore': any NODATA values encountered in the neighborhood are ignored by the computation -- this flag must be sent to the user callback function, and the user function decides how to ignore it.
'NULL': any NODATA values encountered in the neighborhood will cause the resulting pixel to be NULL -- the user callback function is skipped in this case.
'value': any NODATA values encountered in the neighborhood are replaced by the reference pixel (the one in the center of the neighborhood). Note that if this value is NODATA, the behavior is the same as 'NULL' (for the affected neighborhood)
argsArguments to pass into the user function.
Доступність: 2.0.0
Examples utilize the katrina raster loaded as a single tile described in https://gdal.org/user/drivers/raster/postgisraster.html and then prepared in the ST_Rescale examples
--
-- A simple 'callback' user function that averages up all the values in a neighborhood.
--
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;
-- now we apply to our raster averaging pixels within 2 pixels of each other in X and Y direction --
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;
|
![]() First band of our raster
|
![]() new raster after averaging pixels within 4x4 pixels of each other
|
ST_Reclass — Creates a new raster composed of band types reclassified from original. The nband is the band to be changed. If nband is not specified assumed to be 1. All other bands are returned unchanged. Use case: convert a 16BUI band to a 8BUI and so forth for simpler rendering as viewable formats.
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);
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
Create a new raster from the original where band 2 is converted from 8BUI to 4BUI and all values from 101-254 are set to nodata value.
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
Create a new raster from the original where band 1,2,3 is converted to 1BB,4BUI, 4BUI respectively and reclassified. Note this uses the variadic reclassarg argument which can take as input an indefinite number of reclassargs (theoretically as many bands as you have)
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
Create a new 3 band (8BUI,8BUI,8BUI viewable raster) from a raster that has only one 32bf band
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_AddBand, ST_Band, ST_BandPixelType, ST_MakeEmptyRaster, reclassarg, ST_Value
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);
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.
Доступність: 3.6.0
Create a small raster and map its pixels to new values.
CREATE TABLE reclassexact (
id integer,
rast raster
);
--
-- Create a raster with just four pixels
-- [1 2]
-- [3 4]
--
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
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 pixtype
) AS rast
FROM reclassexact
WHERE id = 1
)
SELECT 'rce-1', (ST_DumpValues(rc.rast)).*
FROM rc;
ST_Union — Returns the union of a set of raster tiles into a single raster composed of 1 or more bands.
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);
Returns the union of a set of raster tiles into a single raster composed of at least one band. The resulting raster's extent is the extent of the whole set. In the case of intersection, the resulting value is defined by uniontype which is one of the following: LAST (default), 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
Enhanced: 2.1.0 Improved Speed (fully C-Based).
Availability: 2.1.0 ST_Union(rast, unionarg) variant was introduced.
Enhanced: 2.1.0 ST_Union(rast) (variant 1) unions all bands of all input rasters. Prior versions of PostGIS assumed the first band.
Enhanced: 2.1.0 ST_Union(rast, uniontype) (variant 4) unions all bands of all input rasters.
-- this creates a single band from first band of raster tiles
-- that form the original file system tile
SELECT filename, ST_Union(rast,1) As file_rast
FROM sometable WHERE filename IN('dem01', 'dem02') GROUP BY filename;
-- this creates a multi band raster collecting all the tiles that intersect a line
-- Note: 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[]
SELECT ST_Union(rast)
FROM aerials.boston
WHERE ST_Intersects(rast, ST_GeomFromText('LINESTRING(230486 887771, 230500 88772)',26986) );
Here we use the longer syntax if we only wanted a subset of bands or we want to change order of bands
-- this creates a multi band raster collecting all the tiles that intersect a line
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) );
ST_Distinct4ma — Raster processing function that calculates the number of unique pixel values in a neighborhood.
float8 ST_Distinct4ma(float8[][] matrix, text nodatamode, text[] VARIADIC args);
double precision ST_Distinct4ma(double precision[][][] value, integer[][] pos, text[] VARIADIC userargs);
Calculate the number of unique pixel values in a neighborhood of pixels.
![]() | |
Variant 1 is a specialized callback function for use as a callback parameter to ST_MapAlgebraFctNgb. |
![]() | |
Variant 2 is a specialized callback function for use as a callback parameter to ST_MapAlgebra (callback function version). |
![]() | |
Use of Variant 1 is discouraged since ST_MapAlgebraFctNgb has been deprecated as of 2.1.0. |
Доступність: 2.0.0
Enhanced: 2.1.0 Addition of Variant 2
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 — Raster processing function that interpolates a pixel's value from the pixel's neighborhood.
double precision ST_InvDistWeight4ma(double precision[][][] value, integer[][] pos, text[] VARIADIC userargs);
Calculate an interpolated value for a pixel using the Inverse Distance Weighted method.
There are two optional parameters that can be passed through userargs. The first parameter is the power factor (variable k in the equation below) between 0 and 1 used in the Inverse Distance Weighted equation. If not specified, default value is 1. The second parameter is the weight percentage applied only when the value of the pixel of interest is included with the interpolated value from the neighborhood. If not specified and the pixel of interest has a value, that value is returned.
The basic inverse distance weight equation is:

k = power factor, a real number between 0 and 1
![]() | |
This function is a specialized callback function for use as a callback parameter to ST_MapAlgebra (callback function version). |
Доступність: 2.1.0
-- NEEDS EXAMPLE
ST_Max4ma — Raster processing function that calculates the maximum pixel value in a neighborhood.
float8 ST_Max4ma(float8[][] matrix, text nodatamode, text[] VARIADIC args);
double precision ST_Max4ma(double precision[][][] value, integer[][] pos, text[] VARIADIC userargs);
Calculate the maximum pixel value in a neighborhood of pixels.
For Variant 2, a substitution value for NODATA pixels can be specified by passing that value to userargs.
![]() | |
Variant 1 is a specialized callback function for use as a callback parameter to ST_MapAlgebraFctNgb. |
![]() | |
Variant 2 is a specialized callback function for use as a callback parameter to ST_MapAlgebra (callback function version). |
![]() | |
Use of Variant 1 is discouraged since ST_MapAlgebraFctNgb has been deprecated as of 2.1.0. |
Доступність: 2.0.0
Enhanced: 2.1.0 Addition of Variant 2
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 — Raster processing function that calculates the mean pixel value in a neighborhood.
float8 ST_Mean4ma(float8[][] matrix, text nodatamode, text[] VARIADIC args);
double precision ST_Mean4ma(double precision[][][] value, integer[][] pos, text[] VARIADIC userargs);
Calculate the mean pixel value in a neighborhood of pixels.
For Variant 2, a substitution value for NODATA pixels can be specified by passing that value to userargs.
![]() | |
Variant 1 is a specialized callback function for use as a callback parameter to ST_MapAlgebraFctNgb. |
![]() | |
Variant 2 is a specialized callback function for use as a callback parameter to ST_MapAlgebra (callback function version). |
![]() | |
Use of Variant 1 is discouraged since ST_MapAlgebraFctNgb has been deprecated as of 2.1.0. |
Доступність: 2.0.0
Enhanced: 2.1.0 Addition of Variant 2
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)
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 — Raster processing function that calculates the minimum pixel value in a neighborhood.
float8 ST_Min4ma(float8[][] matrix, text nodatamode, text[] VARIADIC args);
double precision ST_Min4ma(double precision[][][] value, integer[][] pos, text[] VARIADIC userargs);
Calculate the minimum pixel value in a neighborhood of pixels.
For Variant 2, a substitution value for NODATA pixels can be specified by passing that value to userargs.
![]() | |
Variant 1 is a specialized callback function for use as a callback parameter to ST_MapAlgebraFctNgb. |
![]() | |
Variant 2 is a specialized callback function for use as a callback parameter to ST_MapAlgebra (callback function version). |
![]() | |
Use of Variant 1 is discouraged since ST_MapAlgebraFctNgb has been deprecated as of 2.1.0. |
Доступність: 2.0.0
Enhanced: 2.1.0 Addition of Variant 2
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 — Raster processing function that returns the minimum distance (in number of pixels) between the pixel of interest and a neighboring pixel with value.
double precision ST_MinDist4ma(double precision[][][] value, integer[][] pos, text[] VARIADIC userargs);
Return the shortest distance (in number of pixels) between the pixel of interest and the closest pixel with value in the neighborhood.
![]() | |
The intent of this function is to provide an informative data point that helps infer the usefulness of the pixel of interest's interpolated value from ST_InvDistWeight4ma. This function is particularly useful when the neighborhood is sparsely populated. |
![]() | |
This function is a specialized callback function for use as a callback parameter to ST_MapAlgebra (callback function version). |
Доступність: 2.1.0
-- NEEDS EXAMPLE
ST_Range4ma — Raster processing function that calculates the range of pixel values in a neighborhood.
float8 ST_Range4ma(float8[][] matrix, text nodatamode, text[] VARIADIC args);
double precision ST_Range4ma(double precision[][][] value, integer[][] pos, text[] VARIADIC userargs);
Calculate the range of pixel values in a neighborhood of pixels.
For Variant 2, a substitution value for NODATA pixels can be specified by passing that value to userargs.
![]() | |
Variant 1 is a specialized callback function for use as a callback parameter to ST_MapAlgebraFctNgb. |
![]() | |
Variant 2 is a specialized callback function for use as a callback parameter to ST_MapAlgebra (callback function version). |
![]() | |
Use of Variant 1 is discouraged since ST_MapAlgebraFctNgb has been deprecated as of 2.1.0. |
Доступність: 2.0.0
Enhanced: 2.1.0 Addition of Variant 2
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 — Raster processing function that calculates the standard deviation of pixel values in a neighborhood.
float8 ST_StdDev4ma(float8[][] matrix, text nodatamode, text[] VARIADIC args);
double precision ST_StdDev4ma(double precision[][][] value, integer[][] pos, text[] VARIADIC userargs);
Calculate the standard deviation of pixel values in a neighborhood of pixels.
![]() | |
Variant 1 is a specialized callback function for use as a callback parameter to ST_MapAlgebraFctNgb. |
![]() | |
Variant 2 is a specialized callback function for use as a callback parameter to ST_MapAlgebra (callback function version). |
![]() | |
Use of Variant 1 is discouraged since ST_MapAlgebraFctNgb has been deprecated as of 2.1.0. |
Доступність: 2.0.0
Enhanced: 2.1.0 Addition of Variant 2
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 — Raster processing function that calculates the sum of all pixel values in a neighborhood.
float8 ST_Sum4ma(float8[][] matrix, text nodatamode, text[] VARIADIC args);
double precision ST_Sum4ma(double precision[][][] value, integer[][] pos, text[] VARIADIC userargs);
Calculate the sum of all pixel values in a neighborhood of pixels.
For Variant 2, a substitution value for NODATA pixels can be specified by passing that value to userargs.
![]() | |
Variant 1 is a specialized callback function for use as a callback parameter to ST_MapAlgebraFctNgb. |
![]() | |
Variant 2 is a specialized callback function for use as a callback parameter to ST_MapAlgebra (callback function version). |
![]() | |
Use of Variant 1 is discouraged since ST_MapAlgebraFctNgb has been deprecated as of 2.1.0. |
Доступність: 2.0.0
Enhanced: 2.1.0 Addition of Variant 2
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)
ST_Aspect — Returns the aspect (in degrees by default) of an elevation raster band. Useful for analyzing terrain.
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);
Returns the aspect (in degrees by default) of an elevation raster band. Utilizes map algebra and applies the aspect equation to neighboring pixels.
units indicates the units of the aspect. Possible values are: RADIANS, DEGREES (default).
When units = RADIANS, values are between 0 and 2 * pi radians measured clockwise from North.
When units = DEGREES, values are between 0 and 360 degrees measured clockwise from North.
If slope of pixel is zero, aspect of pixel is -1.
![]() | |
For more information about Slope, Aspect and Hillshade, please refer to ESRI - How hillshade works and ERDAS Field Guide - Aspect Images. |
Доступність: 2.0.0
Enhanced: 2.1.0 Uses ST_MapAlgebra() and added optional interpolate_nodata function parameter
Changed: 2.1.0 In prior versions, return values were in radians. Now, return values default to degrees
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_Aspect(rast, 1, '32BF'))
FROM foo
st_dumpvalues
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----------------------------------
(1,"{{315,341.565063476562,0,18.4349479675293,45},{288.434936523438,315,0,45,71.5650482177734},{270,270,-1,90,90},{251.565048217773,225,180,135,108.434951782227},{225,198.43495178
2227,180,161.565048217773,135}}")
(1 row)
Complete example of tiles of a coverage. This query only works with PostgreSQL 9.1 or higher.
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 — Returns the hypothetical illumination of an elevation raster band using provided azimuth, altitude, brightness and scale inputs.
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);
Returns the hypothetical illumination of an elevation raster band using the azimuth, altitude, brightness, and scale inputs. Utilizes map algebra and applies the hill shade equation to neighboring pixels. Return pixel values are between 0 and 255.
azimuth is a value between 0 and 360 degrees measured clockwise from North.
altitude is a value between 0 and 90 degrees where 0 degrees is at the horizon and 90 degrees is directly overhead.
max_bright is a value between 0 and 255 with 0 as no brightness and 255 as max brightness.
scale is the ratio of vertical units to horizontal. For Feet:LatLon use scale=370400, for Meters:LatLon use scale=111120.
If interpolate_nodata is TRUE, values for NODATA pixels from the input raster will be interpolated using ST_InvDistWeight4ma before computing the hillshade illumination.
![]() | |
For more information about Hillshade, please refer to How hillshade works. |
Доступність: 2.0.0
Enhanced: 2.1.0 Uses ST_MapAlgebra() and added optional interpolate_nodata function parameter
Changed: 2.1.0 In prior versions, azimuth and altitude were expressed in radians. Now, azimuth and altitude are expressed in degrees
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)
Complete example of tiles of a coverage. This query only works with PostgreSQL 9.1 or higher.
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 — Returns a raster with the calculated "roughness" of a DEM.
raster ST_Roughness(raster rast, integer nband, raster customextent, text pixeltype="32BF" , boolean interpolate_nodata=FALSE );
Calculates the "roughness" of a DEM, by subtracting the maximum from the minimum for a given area.
Доступність: 2.1.0
-- needs examples
ST_Slope — Returns the slope (in degrees by default) of an elevation raster band. Useful for analyzing terrain.
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);
Returns the slope (in degrees by default) of an elevation raster band. Utilizes map algebra and applies the slope equation to neighboring pixels.
units indicates the units of the slope. Possible values are: RADIANS, DEGREES (default), PERCENT.
scale is the ratio of vertical units to horizontal. For Feet:LatLon use scale=370400, for Meters:LatLon use scale=111120.
If interpolate_nodata is TRUE, values for NODATA pixels from the input raster will be interpolated using ST_InvDistWeight4ma before computing the surface slope.
![]() | |
For more information about Slope, Aspect and Hillshade, please refer to ESRI - How hillshade works and ERDAS Field Guide - Slope Images. |
Доступність: 2.0.0
Enhanced: 2.1.0 Uses ST_MapAlgebra() and added optional units, scale, interpolate_nodata function parameters
Changed: 2.1.0 In prior versions, return values were in radians. Now, return values default to degrees
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)
Complete example of tiles of a coverage. This query only works with PostgreSQL 9.1 or higher.
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 — Returns a raster with the calculated Topographic Position Index.
raster ST_TPI(raster rast, integer nband, raster customextent, text pixeltype="32BF" , boolean interpolate_nodata=FALSE );
Calculates the Topographic Position Index, which is defined as the focal mean with radius of one minus the center cell.
![]() | |
This function only supports a focalmean radius of one. |
Доступність: 2.1.0
-- needs examples
ST_TRI — Returns a raster with the calculated Terrain Ruggedness Index.
raster ST_TRI(raster rast, integer nband, raster customextent, text pixeltype="32BF" , boolean interpolate_nodata=FALSE );
Terrain Ruggedness Index is calculated by comparing a central pixel with its neighbors, taking the absolute values of the differences, and averaging the result.
![]() | |
This function only supports a focalmean radius of one. |
Доступність: 2.1.0
-- needs examples
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);
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_pointsThe points to drive the interpolation. Any geometry with Z-values is acceptable, all points in the input will be used.
algorithm_optionsA 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"
templateA 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_numBy default the first band in the template raster is used to drive the output raster, but that can be adjusted with this parameter.
Доступність: 3.2.0
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 — 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);
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:
rastThe raster to generate the contour of
bandnumberThe band to generate the contour of
level_intervalThe elevation interval between contours generated
level_baseThe "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_levelsThe elevation interval between contours generated
polygonizeIf true, contour polygons will be created, rather than polygon lines.
Return values are a set of records with the following attributes:
geomThe geometry of the contour line.
idA unique identifier given to the contour line by GDAL.
valueThe raster value the line represents. For an elevation DEM input, this would be the elevation of the output contour.
Доступність: 3.2.0
WITH c AS ( SELECT (ST_Contour(rast, 1, fixed_levels => ARRAY[100.0, 200.0, 300.0])).* FROM dem_grid WHERE rid = 1 ) SELECT st_astext(geom), id, value FROM c;
Box3D — Returns the box 3d representation of the enclosing box of the raster.
box3d Box3D(raster rast);
Returns the box representing the extent of the raster.
The polygon is defined by the corner points of the bounding box ((MINX, MINY), (MAXX, MAXY))
Changed: 2.0.0 In pre-2.0 versions, there used to be a box2d instead of box3d. Since box2d is a deprecated type, this was changed to box3d.
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_ConvexHull — Return the convex hull geometry of the raster including pixel values equal to BandNoDataValue. For regular shaped and non-skewed rasters, this gives the same result as ST_Envelope so only useful for irregularly shaped or skewed rasters.
geometry ST_ConvexHull(raster rast);
Return the convex hull geometry of the raster including the NoDataBandValue band pixels. For regular shaped and non-skewed rasters, this gives more or less the same result as ST_Envelope so only useful for irregularly shaped or skewed rasters.
![]() | |
ST_Envelope floors the coordinates and hence add a little buffer around the raster so the answer is subtly different from ST_ConvexHull which does not floor. |
Refer to PostGIS Raster Specification for a diagram of this.
-- Note envelope and convexhull are more or less the same
SELECT ST_AsText(ST_ConvexHull(rast)) As convhull,
ST_AsText(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
SELECT ST_AsText(ST_ConvexHull(rast)) As convhull,
ST_AsText(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 — Returns a set of geomval (geom,val) rows, from a given raster band. If no band number is specified, band num defaults to 1.
setof geomval ST_DumpAsPolygons(raster rast, integer band_num=1, boolean exclude_nodata_value=TRUE);
This is a set-returning function (SRF). It returns a set of geomval rows, formed by a geometry (geom) and a pixel band value (val). Each polygon is the union of all pixels for that band that have the same pixel value denoted by val.
ST_DumpAsPolygon is useful for polygonizing rasters. It is the reverse of a GROUP BY in that it creates new rows. For example it can be used to expand a single raster into multiple POLYGONS/MULTIPOLYGONS.
Changed 3.3.0, validation and fixing is disabled to improve performance. May result invalid geometries.
Availability: Requires GDAL 1.7 or higher.
![]() | |
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. |
![]() | |
If you only care about count of pixels with a given value in a raster, it is faster to use ST_ValueCount. |
![]() | |
This is different than ST_PixelAsPolygons where one geometry is returned for each pixel regardless of pixel value. |
-- this syntax requires PostgreSQL 9.3+
SELECT val, ST_AsText(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))
geomval, ST_AsRasterAgg, ST_Value, ST_Polygon, ST_ValueCount
ST_Envelope — Returns the polygon representation of the extent of the raster.
geometry ST_Envelope(raster rast);
Returns the polygon representation of the extent of the raster in spatial coordinate units defined by srid. It is a float8 minimum bounding box represented as a polygon.
The polygon is defined by the corner points of the bounding box ((MINX, MINY), (MINX, MAXY), (MAXX, MAXY), (MAXX, MINY), (MINX, MINY))
SELECT rid, ST_AsText(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 — Return the convex hull geometry of the raster excluding NODATA pixels.
geometry ST_MinConvexHull(raster rast, integer nband=NULL);
Return the convex hull geometry of the raster excluding NODATA pixels. If nband is NULL, all bands of the raster are considered.
Доступність: 2.1.0
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
ST_AsText(ST_ConvexHull(rast)) AS hull,
ST_AsText(ST_MinConvexHull(rast)) AS mhull,
ST_AsText(ST_MinConvexHull(rast, 1)) AS mhull_1,
ST_AsText(ST_MinConvexHull(rast, 2)) AS mhull_2
FROM foo
hull | mhull | mhull_1 | mhull_2
----------------------------------+-------------------------------------+-------------------------------------+-------------------------------------
POLYGON((0 0,9 0,9 -9,0 -9,0 0)) | POLYGON((0 -3,9 -3,9 -9,0 -9,0 -3)) | POLYGON((3 -3,9 -3,9 -6,3 -6,3 -3)) | POLYGON((0 -3,6 -3,6 -9,0 -9,0 -3))
ST_Polygon — Returns a multipolygon geometry formed by the union of pixels that have a pixel value that is not no data value. If no band number is specified, band num defaults to 1.
geometry ST_Polygon(raster rast, integer band_num=1);
Changed 3.3.0, validation and fixing is disabled to improve performance. May result invalid geometries.
Availability: 0.1.6 Requires GDAL 1.7 or higher.
Enhanced: 2.1.0 Improved Speed (fully C-Based) and the returning multipolygon is ensured to be valid.
Changed: 2.1.0 In prior versions would sometimes return a polygon, changed to always return multipolygon.
-- by default no data band value is 0 or not set, so polygon will return a square polygon
SELECT ST_AsText(ST_Polygon(rast)) As geomwkt
FROM dummy_rast
WHERE rid = 2;
geomwkt
--------------------------------------------
MULTIPOLYGON(((3427927.75 5793244,3427928 5793244,3427928 5793243.75,3427927.75 5793243.75,3427927.75 5793244)))
-- now we change the no data value of first band
UPDATE dummy_rast SET rast = ST_SetBandNoDataValue(rast,1,254)
WHERE rid = 2;
SELECt rid, ST_BandNoDataValue(rast)
from dummy_rast where rid = 2;
-- ST_Polygon excludes the pixel value 254 and returns a multipolygon
SELECT ST_AsText(ST_Polygon(rast)) As geomwkt
FROM dummy_rast
WHERE rid = 2;
geomwkt
---------------------------------------------------------
MULTIPOLYGON(((3427927.9 5793243.95,3427927.85 5793243.95,3427927.85 5793244,3427927.9 5793244,3427927.9 5793243.95)),((3427928 5793243.85,3427928 5793243.8,3427927.95 5793243.8,3427927.95 5793243.85,3427927.9 5793243.85,3427927.9 5793243.9,3427927.9 5793243.95,3427927.95 5793243.95,3427928 5793243.95,3427928 5793243.85)),((3427927.8 5793243.75,3427927.75 5793243.75,3427927.75 5793243.8,3427927.75 5793243.85,3427927.75 5793243.9,3427927.75 5793244,3427927.8 5793244,3427927.8 5793243.9,3427927.8 5793243.85,3427927.85 5793243.85,3427927.85 5793243.8,3427927.85 5793243.75,3427927.8 5793243.75)))
-- Or if you want the no data value different for just one time
SELECT ST_AsText(
ST_Polygon(
ST_SetBandNoDataValue(rast,1,252)
)
) As geomwkt
FROM dummy_rast
WHERE rid =2;
geomwkt
---------------------------------
MULTIPOLYGON(((3427928 5793243.85,3427928 5793243.8,3427928 5793243.75,3427927.85 5793243.75,3427927.8 5793243.75,3427927.8 5793243.8,3427927.75 5793243.8,3427927.75 5793243.85,3427927.75 5793243.9,3427927.75 5793244,3427927.8 5793244,3427927.85 5793244,3427927.9 5793244,3427928 5793244,3427928 5793243.95,3427928 5793243.85),(3427927.9 5793243.9,3427927.9 5793243.85,3427927.95 5793243.85,3427927.95 5793243.9,3427927.9 5793243.9)))
ST_IntersectionFractions — Calculates the fraction of each raster cell that is covered by a given geometry.
raster ST_IntersectionFractions(raster rast, geometry geom);
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.
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
));
--
-- This rotated square polygon covers half of each cell in the
-- raster.
--
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}}
TRUE if A's bounding box intersects B's bounding box.TRUE if A's bounding box is to the left of B's.TRUE if A's bounding box is to the right of B's.TRUE if A's bounding box is the same as B's. Uses double precision bounding box.TRUE if A's bounding box is contained by B's. Uses double precision bounding box.TRUE, якщо обмежувальна рамка A збігається з обмежувальною рамкою B.TRUE if A's bounding box is contains B's. Uses double precision bounding box.&& — Returns TRUE if A's bounding box intersects B's bounding box.
boolean &&( raster A , raster B );
boolean &&( raster A , geometry B );
boolean &&( geometry B , raster A );
The && operator returns TRUE if the bounding box of raster/geometr A intersects the bounding box of raster/geometr B.
![]() | |
This operand will make use of any indexes that may be available on the rasters. |
Доступність: 2.0.0
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
&< — Returns TRUE if A's bounding box is to the left of B's.
boolean &<( raster A , raster B );
The &< operator returns TRUE if the bounding box of raster A overlaps or is to the left of the bounding box of raster B, or more accurately, overlaps or is NOT to the right of the bounding box of raster B.
![]() | |
This operand will make use of any indexes that may be available on the rasters. |
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
&> — Returns TRUE if A's bounding box is to the right of B's.
boolean &>( raster A , raster B );
The &> operator returns TRUE if the bounding box of raster A overlaps or is to the right of the bounding box of raster B, or more accurately, overlaps or is NOT to the left of the bounding box of raster B.
![]() | |
Цей операнд буде використовувати будь-які індекси, які можуть бути доступні для геометрій. |
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
= — Returns TRUE if A's bounding box is the same as B's. Uses double precision bounding box.
boolean =( raster A , raster B );
The = operator returns TRUE if the bounding box of raster A is the same as the bounding box of raster B. PostgreSQL uses the =, <, and > operators defined for rasters to perform internal orderings and comparison of rasters (ie. in a GROUP BY or ORDER BY clause).
![]() | |
This operand will NOT make use of any indexes that may be available on the rasters. Use ~= instead. This operator exists mostly so one can group by the raster column. |
Доступність: 2.1.0
@ — Returns TRUE if A's bounding box is contained by B's. Uses double precision bounding box.
boolean @( raster A , raster B );
boolean @( geometry A , raster B );
boolean @( raster B , geometry A );
The @ operator returns TRUE if the bounding box of raster/geometry A is contained by bounding box of raster/geometr B.
![]() | |
This operand will use spatial indexes on the rasters. |
Availability: 2.0.0 raster @ raster, raster @ geometry introduced
Availability: 2.0.5 geometry @ raster introduced
~= — Повертає TRUE, якщо обмежувальна рамка A збігається з обмежувальною рамкою B.
boolean ~=( raster A , raster B );
The ~= operator returns TRUE if the bounding box of raster A is the same as the bounding box of raster B.
![]() | |
This operand will make use of any indexes that may be available on the rasters. |
Доступність: 2.0.0
Very useful usecase is for taking two sets of single band rasters that are of the same chunk but represent different themes and creating a multi-band raster
SELECT ST_AddBand(prec.rast, alt.rast) As new_rast
FROM prec INNER JOIN alt ON (prec.rast ~= alt.rast);
~ — Returns TRUE if A's bounding box is contains B's. Uses double precision bounding box.
boolean ~( raster A , raster B );
boolean ~( geometry A , raster B );
boolean ~( raster B , geometry A );
The ~ operator returns TRUE if the bounding box of raster/geometry A is contains bounding box of raster/geometr B.
![]() | |
This operand will use spatial indexes on the rasters. |
Доступність: 2.0.0
ST_Contains — Return true if no points of raster rastB lie in the exterior of raster rastA and at least one point of the interior of rastB lies in the interior of rastA.
boolean ST_Contains( raster rastA , integer nbandA , raster rastB , integer nbandB );
boolean ST_Contains( raster rastA , raster rastB );
Raster rastA contains rastB if and only if no points of rastB lie in the exterior of rastA and at least one point of the interior of rastB lies in the interior of rastA. If the band number is not provided (or set to NULL), only the convex hull of the raster is considered in the test. If the band number is provided, only those pixels with value (not NODATA) are considered in the test.
![]() | |
This function will make use of any indexes that may be available on the rasters. |
![]() | |
To test the spatial relationship of a raster and a geometry, use ST_Polygon on the raster, e.g. ST_Contains(ST_Polygon(raster), geometry) or ST_Contains(geometry, ST_Polygon(raster)). |
![]() | |
ST_Contains() is the inverse of ST_Within(). So, ST_Contains(rastA, rastB) implies ST_Within(rastB, rastA). |
Доступність: 2.1.0
-- specified band numbers
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
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 — Return true if rastB intersects the interior of rastA but not the boundary or exterior of rastA.
boolean ST_ContainsProperly( raster rastA , integer nbandA , raster rastB , integer nbandB );
boolean ST_ContainsProperly( raster rastA , raster rastB );
Raster rastA contains properly rastB if rastB intersects the interior of rastA but not the boundary or exterior of rastA. If the band number is not provided (or set to NULL), only the convex hull of the raster is considered in the test. If the band number is provided, only those pixels with value (not NODATA) are considered in the test.
Raster rastA does not contain properly itself but does contain itself.
![]() | |
This function will make use of any indexes that may be available on the rasters. |
![]() | |
To test the spatial relationship of a raster and a geometry, use ST_Polygon on the raster, e.g. ST_ContainsProperly(ST_Polygon(raster), geometry) or ST_ContainsProperly(geometry, ST_Polygon(raster)). |
Доступність: 2.1.0
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 — Return true if no points of raster rastB lie outside raster rastA.
boolean ST_Covers( raster rastA , integer nbandA , raster rastB , integer nbandB );
boolean ST_Covers( raster rastA , raster rastB );
Raster rastA covers rastB if and only if no points of rastB lie in the exterior of rastA. If the band number is not provided (or set to NULL), only the convex hull of the raster is considered in the test. If the band number is provided, only those pixels with value (not NODATA) are considered in the test.
![]() | |
This function will make use of any indexes that may be available on the rasters. |
![]() | |
To test the spatial relationship of a raster and a geometry, use ST_Polygon on the raster, e.g. ST_Covers(ST_Polygon(raster), geometry) or ST_Covers(geometry, ST_Polygon(raster)). |
Доступність: 2.1.0
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 — Return true if no points of raster rastA lie outside raster rastB.
boolean ST_CoveredBy( raster rastA , integer nbandA , raster rastB , integer nbandB );
boolean ST_CoveredBy( raster rastA , raster rastB );
Raster rastA is covered by rastB if and only if no points of rastA lie in the exterior of rastB. If the band number is not provided (or set to NULL), only the convex hull of the raster is considered in the test. If the band number is provided, only those pixels with value (not NODATA) are considered in the test.
![]() | |
This function will make use of any indexes that may be available on the rasters. |
![]() | |
To test the spatial relationship of a raster and a geometry, use ST_Polygon on the raster, e.g. ST_CoveredBy(ST_Polygon(raster), geometry) or ST_CoveredBy(geometry, ST_Polygon(raster)). |
Доступність: 2.1.0
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 — Return true if raster rastA does not spatially intersect rastB.
boolean ST_Disjoint( raster rastA , integer nbandA , raster rastB , integer nbandB );
boolean ST_Disjoint( raster rastA , raster rastB );
Raster rastA and rastB are disjointed if they do not share any space together. If the band number is not provided (or set to NULL), only the convex hull of the raster is considered in the test. If the band number is provided, only those pixels with value (not NODATA) are considered in the test.
![]() | |
This function does NOT use any indexes. |
![]() | |
To test the spatial relationship of a raster and a geometry, use ST_Polygon on the raster, e.g. ST_Disjoint(ST_Polygon(raster), geometry). |
Доступність: 2.1.0
-- rid = 1 has no bands, hence the NOTICE and the NULL value for st_disjoint
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
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 — Return true if raster rastA spatially intersects raster 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 );
Return true if raster rastA spatially intersects raster rastB. If the band number is not provided (or set to NULL), only the convex hull of the raster is considered in the test. If the band number is provided, only those pixels with value (not NODATA) are considered in the test.
![]() | |
This function will make use of any indexes that may be available on the rasters. |
Enhanced: 2.0.0 support raster/raster intersects was introduced.
![]() | |
Changed: 2.1.0 The behavior of the ST_Intersects(raster, geometry) variants changed to match that of ST_Intersects(geometry, raster). |
-- different bands of same raster
SELECT ST_Intersects(rast, 2, rast, 3) FROM dummy_rast WHERE rid = 2;
st_intersects
---------------
t
ST_Overlaps — Return true if raster rastA and rastB intersect but one does not completely contain the other.
boolean ST_Overlaps( raster rastA , integer nbandA , raster rastB , integer nbandB );
boolean ST_Overlaps( raster rastA , raster rastB );
Return true if raster rastA spatially overlaps raster rastB. This means that rastA and rastB intersect but one does not completely contain the other. If the band number is not provided (or set to NULL), only the convex hull of the raster is considered in the test. If the band number is provided, only those pixels with value (not NODATA) are considered in the test.
![]() | |
This function will make use of any indexes that may be available on the rasters. |
![]() | |
To test the spatial relationship of a raster and a geometry, use ST_Polygon on the raster, e.g. ST_Overlaps(ST_Polygon(raster), geometry). |
Доступність: 2.1.0
-- comparing different bands of same raster
SELECT ST_Overlaps(rast, 1, rast, 2) FROM dummy_rast WHERE rid = 2;
st_overlaps
-------------
f
ST_Touches — Return true if raster rastA and rastB have at least one point in common but their interiors do not intersect.
boolean ST_Touches( raster rastA , integer nbandA , raster rastB , integer nbandB );
boolean ST_Touches( raster rastA , raster rastB );
Return true if raster rastA spatially touches raster rastB. This means that rastA and rastB have at least one point in common but their interiors do not intersect. If the band number is not provided (or set to NULL), only the convex hull of the raster is considered in the test. If the band number is provided, only those pixels with value (not NODATA) are considered in the test.
![]() | |
This function will make use of any indexes that may be available on the rasters. |
![]() | |
To test the spatial relationship of a raster and a geometry, use ST_Polygon on the raster, e.g. ST_Touches(ST_Polygon(raster), geometry). |
Доступність: 2.1.0
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 — Returns true if rasters have same skew, scale, spatial ref, and offset (pixels can be put on same grid without cutting into pixels) and false if they don't with notice detailing issue.
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 );
Non-Aggregate version (Variants 1 and 2): Returns true if the two rasters (either provided directly or made using the values for upperleft, scale, skew and srid) have the same scale, skew, srid and at least one of any of the four corners of any pixel of one raster falls on any corner of the grid of the other raster. Returns false if they don't and a NOTICE detailing the alignment issue.
Aggregate version (Variant 3): From a set of rasters, returns true if all rasters in the set are aligned. The ST_SameAlignment() 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.
Доступність: 2.0.0
Enhanced: 2.1.0 addition of Aggregate variant
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;
sm
----
t
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 st_samealignment ------------------ t f f f
ST_NotSameAlignmentReason — Returns text stating if rasters are aligned and if not aligned, a reason why.
text ST_NotSameAlignmentReason(raster rastA, raster rastB);
Returns text stating if rasters are aligned and if not aligned, a reason why.
![]() | |
If there are several reasons why the rasters are not aligned, only one reason (the first test to fail) will be returned. |
Доступність: 2.1.0
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 — Return true if no points of raster rastA lie in the exterior of raster rastB and at least one point of the interior of rastA lies in the interior of rastB.
boolean ST_Within( raster rastA , integer nbandA , raster rastB , integer nbandB );
boolean ST_Within( raster rastA , raster rastB );
Raster rastA is within rastB if and only if no points of rastA lie in the exterior of rastB and at least one point of the interior of rastA lies in the interior of rastB. If the band number is not provided (or set to NULL), only the convex hull of the raster is considered in the test. If the band number is provided, only those pixels with value (not NODATA) are considered in the test.
![]() | |
This operand will make use of any indexes that may be available on the rasters. |
![]() | |
To test the spatial relationship of a raster and a geometry, use ST_Polygon on the raster, e.g. ST_Within(ST_Polygon(raster), geometry) or ST_Within(geometry, ST_Polygon(raster)). |
![]() | |
ST_Within() is the inverse of ST_Contains(). So, ST_Within(rastA, rastB) implies ST_Contains(rastB, rastA). |
Доступність: 2.1.0
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 — Return true if rasters rastA and rastB are within the specified distance of each other.
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 );
Return true if rasters rastA and rastB are within the specified distance of each other. If the band number is not provided (or set to NULL), only the convex hull of the raster is considered in the test. If the band number is provided, only those pixels with value (not NODATA) are considered in the test.
The distance is specified in units defined by the spatial reference system of the rasters. For this function to make sense, the source rasters must both be of the same coordinate projection, having the same SRID.
![]() | |
This operand will make use of any indexes that may be available on the rasters. |
![]() | |
To test the spatial relationship of a raster and a geometry, use ST_Polygon on the raster, e.g. ST_DWithin(ST_Polygon(raster), geometry). |
Доступність: 2.1.0
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 — Return true if rasters rastA and rastB are fully within the specified distance of each other.
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 );
Return true if rasters rastA and rastB are fully within the specified distance of each other. If the band number is not provided (or set to NULL), only the convex hull of the raster is considered in the test. If the band number is provided, only those pixels with value (not NODATA) are considered in the test.
The distance is specified in units defined by the spatial reference system of the rasters. For this function to make sense, the source rasters must both be of the same coordinate projection, having the same SRID.
![]() | |
This operand will make use of any indexes that may be available on the rasters. |
![]() | |
To test the spatial relationship of a raster and a geometry, use ST_Polygon on the raster, e.g. ST_DFullyWithin(ST_Polygon(raster), geometry). |
Доступність: 2.1.0
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
This section documents various gotchas and tips related to PostGIS Raster.
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.
# 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'
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).
...
# - 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
You can inspect the current maximum number of open files for the entire system with the following example:
$ 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:
$ 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
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):
$ 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
$ 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.
...
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.
...
[Service]
LimitNOFILE=131072
...
[Install]
WantedBy=multi-user.target
...
After making the necessary systemd changes, make sure to reload the daemon
systemctl daemon-reload
У цьому розділі описано функції, що містяться в папці extras архівів вихідного коду PostGIS та репозиторії вихідного коду. Вони не завжди входять до складу бінарних випусків PostGIS, але зазвичай є скриптами на основі PL/pgSQL або стандартними скриптами оболонки, які можна запускати без змін.
Це є форком стандартизатора PAGC (оригінальний код для цієї частини був стандартизатором адрес PAGC PostgreSQL).
Стандартизатор адрес — це однорядковий аналізатор адрес, який приймає вхідну адресу та нормалізує її на основі набору правил, що зберігаються в таблиці та допоміжних таблицях lex і gaz.
Код упакований в одну бібліотеку розширення PostgreSQL під назвою address_standardizer, яке можна встановити за допомогою команди CREATE EXTENSION address_standardizer;. Окрім розширення address_standardizer, також створене прикладне розширення з даними — address_standardizer_data_us, яке містить таблиці gaz, lex і rules для даних США. Це розширення можна встановити командою: CREATE EXTENSION address_standardizer_data_us;
Код цього розширення можна знайти в PostGIS extensions/address_standardizer і на даний момент він є самостійним.
Інструкції з установки див.: Section 2.3, “Встановлення та використання стандартизатора адрес”.
Парсер працює справа наліво, спочатку перевіряючи макроелементи для поштового індексу, штату/провінції, міста, а потім перевіряє мікроелементи, щоб визначити, чи маємо ми справу з номером будинку, вулицею, перехрестям або орієнтиром. Наразі він не перевіряє код країни або назву, але це може бути додано в майбутньому.
Вважається, що місцезнаходження — США або Канада, на підставі: поштового індексу США або Канади, штату/провінції США або Канади, в іншому випадку — США
Вони розпізнаються за допомогою регулярних виразів, сумісних з Perl. Ці регулярні вирази наразі знаходяться у файлі parseaddress-api.c і їх відносно просто змінити, якщо це необхідно.
Вони розпізнаються за допомогою регулярних виразів, сумісних з Perl. Ці регулярні вирази наразі знаходяться в parseaddress-api.c, але в майбутньому можуть бути переміщені в includes для полегшення обслуговування.
У цьому розділі наведені типи даних PostgreSQL, встановлені розширенням Address Standardizer. Зверніть увагу, що ми описуємо поведінку приведення типів (casting), що є особливо важливим при розробці власних функцій.
standardize_address.stdaddr — Композитний тип, що складається з елементів адреси. Це тип повернення для функції standardize_address.
Композитний тип, що складається з елементів адреси. Це тип повернення для функції standardize_address. Деякі описи елементів запозичені з PAGC Postal Attributes.
Номери токенів позначають вихідний номер посилання в rules table.
This method needs address_standardizer extension.
buildingє текстом (номер токена 0): Позначає номер або назву будівлі. Нерозбірні ідентифікатори та типи будівель. Зазвичай для більшості адрес це поле залишається порожнім.
house_numє текстом (номер токена 1): Це номер будинку на вулиці. Приклад 75 в 75 State Street.
predirє текстом (номер токена 2): НАЗВА ВУЛИЦІ ПЕРЕД НАПРЯМКОМ, наприклад North, South, East, West тощо.
qualє текстом (номер токена 3): ПРЕДМОДИФІКАТОР НАЗВИ ВУЛИЦІ Приклад OLD в 3715 OLD HIGHWAY 99.
pretypeє текстом (номер токена 4): ПРЕФІКС ВУЛИЦІ ТИП
nameє текстом (номер токена 5): НАЗВА ВУЛИЦІ
suftypeє текстом (номер токена 6): ТИП ВУЛИЦІ, наприклад St, Ave, Cir. Тип вулиці, що йде після основної назви вулиці. Приклад STREET в 75 State Street.
sufdirє текстом (номер токена 7): STREET POST-DIRECTIONAL Модифікатор напрямку, що стоїть після назви вулиці. Приклад WEST в 3715 TENTH AVENUE WEST.
ruralrouteє текстом (номер токена 8): СІЛЬСЬКИЙ МАРШРУТ . Приклад 7 в RR 7.
extraє текстом: Додаткова інформація, така як номер поверху.
cityє текстом (номер токена 10): Приклад Бостон.
stateє текстом (номер токена 11): (Приклад MASSACHUSETTS
countryє текстом (номер токена 12): Приклад США
postcodeє текстом ПОШТОВИЙ ІНДЕКС (ЗІП-КОД) (номер токена 13): Приклад 02109
boxє текстом НОМЕР ПОШТОВОЇ СКРИНЬКИ (номер токена 14 та 15): Приклад 02109
unitє текстом Номер квартири або номер люкса (номер токена 17): Приклад 3B в APT 3B.
У цьому розділі перелічено формати таблиць PostgreSQL, які використовує address_standardizer для нормалізації адрес. Зверніть увагу, що ці таблиці не обов'язково мають мати ті самі назви, що й зазначені тут. Наприклад, ви можете мати різні таблиці lex, gaz, rules для кожної країни або для вашого власного геокодера. Назви цих таблиць передаються у функції стандартизатора адрес.
Розширення address_standardizer_data_us містить дані для стандартизації адрес у США.
rules table — Таблиця правил містить набір правил, які відображають токени вхідної послідовності адрес на стандартизовану вихідну послідовність. Правило визначається як набір вхідних токенів, за якими слідує -1 (термінатор), за яким слідує набір вихідних токенів, за яким слідує -1, за яким слідує число, що позначає тип правила, за яким слідує рейтинг правила.
Таблиця правил повинна містити принаймні такі стовпці, хоча ви можете додавати інші для власних потреб.
idПервинний ключ таблиці
ruleтекстове поле, що позначає правило. Детальніше див. Записи правил стандартизації адрес PAGC.
Правило складається з набору невід'ємних цілих чисел, що представляють вхідні маркери, закінчується -1, за яким слідує така ж кількість невід'ємних цілих чисел, що представляють поштові атрибути, закінчується -1, за яким слідує ціле число, що представляє тип правила, за яким слідує ціле число, що представляє ранг правила. Правила ранжуються від 0 (найнижчий) до 17 (найвищий).
Так, наприклад, правило 2 0 2 22 3 -1 5 5 6 7 3 -1 2 6 відображається на послідовність вихідних токенів TYPE NUMBER TYPE DIRECT QUALIF у вихідну послідовність STREET STREET SUFTYP SUFDIR QUALIF. Це правило є правилом ARC_C рангу 6.
Номери відповідних вихідних токенів наведені в stdaddr.
Кожне правило починається з набору вхідних токенів, за якими слідує роздільник -1. Дієві вхідні токени, взяті з PAGC Input Tokens, наведені нижче:
Токени введення на основі форм
AMPERS(13). Символ амперсанд (&) часто використовується для скорочення слова "and".
DASH(9). Розділовий знак.
DOUBLE(21). Послідовність двох літер. Часто використовується як ідентифікатор.
FRACT(25). Дроби іноді використовуються в цивільних числах або числах одиниць.
MIXED(23). Алфавітно-цифровий рядок, що містить як літери, так і цифри. Використовується для ідентифікаторів.
NUMBER(0). Ряд цифр.
ORD(15). Такі позначення, як "Перший" або "1-й". Часто використовуються в назвах вулиць.
ORD(18). Одна літера.
WORD(1). Слово — це послідовність літер довільної довжини. Окрема літера може бути як SINGLE так і WORD.
Функціональні вхідні токени
BOXH(14). Слова, що використовуються для позначення поштових скриньок. Наприклад, Box або PO Box.
BUILDH(19). Слова, що використовуються для позначення будівель або будівельних комплексів, зазвичай як префікс. Наприклад: Вежа в Вежа 7A.
BUILDT(24). Слова та абревіатури, що використовуються для позначення будівель або будівельних комплексів, зазвичай як суфікс. Наприклад: Торговий центр.
DIRECT(22). Слова, що використовуються для позначення напрямків, наприклад Північ.
MILE(20). Слова, що використовуються для позначення адрес кілометрових стовпців.
ROAD(6). Слова та абревіатури, що використовуються для позначення автомагістралей та доріг. Наприклад: Interstate в Interstate 5
RR(8). Слова та абревіатури, що використовуються для позначення приміських маршрутів. RR.
TYPE(2). Слова та абревіатури, що використовуються для позначення типів вулиць. Наприклад: ST або AVE.
UNITH(16). Слова та абревіатури, що використовуються для позначення внутрішніх підадрес. Наприклад, APT або UNIT.
Токени введення поштового типу
QUINT(28). 5-значний номер. Ідентифікує поштовий індекс
QUAD(29). 4-значний номер. Ідентифікує ZIP4.
PCH(27). Послідовність з 3 символів, що складається з літери, цифри та літери. Ідентифікує FSA, перші 3 символи канадського поштового індексу.
PCT(26). Послідовність з 3 символів, що складається з цифри, літери та цифри. Ідентифікує LDU, останні 3 символи канадського поштового індексу.
Стоп-слова
СТОПСЛОВА поєднуються зі СЛОВАМИ. У правилах послідовність декількох СЛІВ і СТОПСЛІВ буде представлена одним токеном СЛОВА.
STOPWORD(7). Слово з низьким лексичним значенням, яке можна опустити при розборі. Наприклад: THE.
Після першого -1 (роздільника) йдуть вихідні маркери та їх порядок, а потім термінатор -1. Номери відповідних вихідних маркерів наведені в stdaddr. Допустимі значення залежать від типу правила. Вихідні маркери, допустимі для кожного типу правила, наведені в the section called “Типи правил та їхній ранг”.
Остання частина правила - це тип правила, який позначається одним із наступних символів, за яким слідує рангове значення правила. Правила ранжуються від 0 (найнижче) до 17 (найвище).
MACRO_C
(номер токена = "0"). Клас правил для розбору MACRO класів, таких як PLACE STATE ZIP
MACRO_C вихідні токени (витяг з http://www.pagcgeo.org/docs/html/pagc-12.html#--r-typ--.
CITY(токен номер "10"). Приклад "Albany"
STATE(токен номер "11"). Приклад "NY"
NATION(токен номер "12"). Цей атрибут не використовується в більшості файлів посилань. Приклад "USA"
POSTAL(токен номер "13"). (Елементи SADS "ZIP CODE" , "PLUS 4" ). Цей атрибут використовується як для поштових індексів США, так і для поштових індексів Канади.
MICRO_C
(номер токена = "1"). Клас правил для розбору повних клаузул MICRO (таких як House, street, sufdir, predir, pretyp, suftype, qualif) (тобто ARC_C плюс CIVIC_C). Ці правила не використовуються на етапі побудови.
MICRO_C вихідні токени (витяг з http://www.pagcgeo.org/docs/html/pagc-12.html#--r-typ--.
HOUSEє текстом (номер токена 1): Це номер будинку на вулиці. Приклад 75 в 75 State Street.
predirє текстом (номер токена 2): НАЗВА ВУЛИЦІ ПЕРЕД НАПРЯМКОМ, наприклад North, South, East, West тощо.
qualє текстом (номер токена 3): ПРЕДМОДИФІКАТОР НАЗВИ ВУЛИЦІ Приклад OLD в 3715 OLD HIGHWAY 99.
pretypeє текстом (номер токена 4): ПРЕФІКС ВУЛИЦІ ТИП
streetє текстом (номер токена 5): НАЗВА ВУЛИЦІ
suftypeє текстом (номер токена 6): ТИП ВУЛИЦІ, наприклад St, Ave, Cir. Тип вулиці, що йде після основної назви вулиці. Приклад STREET в 75 State Street.
sufdirє текстом (номер токена 7): STREET POST-DIRECTIONAL Модифікатор напрямку, що стоїть після назви вулиці. Приклад WEST в 3715 TENTH AVENUE WEST.
ARC_C
(номер маркера = "2"). Клас правил для розбору клаузул MICRO, за винятком атрибуту HOUSE. Як такий, використовує той самий набір вихідних маркерів, що й MICRO_C, за винятком маркера HOUSE.
CIVIC_C
(номер токена = "3"). Клас правил для розбору атрибуту HOUSE.
EXTRA_C
(номер токена = "4"). Клас правил для розбору атрибутів EXTRA - атрибутів, виключених з геокодування. Ці правила не використовуються на етапі побудови.
EXTRA_C вихідні токени (витяг з http://www.pagcgeo.org/docs/html/pagc-12.html#--r-typ--.
BLDNG(токен номер 0): Нерозпізнані ідентифікатори та типи будівель.
BOXH(токен номер 14): БОКС в БОКС 3B
BOXT(токен номер 15): 3B в BOX 3B
RR(токен номер 8): RR в RR 7
UNITH(токен номер 16): APT в APT 3B
UNITT(токен номер 17): 3B в APT 3B
UNKNWN(токен номер 9): Вихідні дані, які не підлягають класифікації.
lex table — Таблиця lex використовується для класифікації алфавітно-цифрового вводу та пов'язування цього вводу з (а) вхідними токенами (див. the section called “Вхідні токени”) та (б) стандартизованими представленнями.
Таблиця lex (скорочення від lexicon) використовується для класифікації алфавітно-цифрового вводу та пов'язування цього вводу з the section called “Вхідні токени” та (b) стандартизованими представленнями. У цих таблицях ви знайдете ONE, що відповідає stdword: 1.
Lex має принаймні такі стовпці в таблиці. Ви можете додати
idПервинний ключ таблиці
seqinteger: definition number?
wordtext: вхідне слово
stdwordtext: вхідне слово стандартизоване слово-замінник
tokeninteger: тип слова. Замінюється тільки в цьому контексті. Див. Токени PAGC.
gaz table — Таблиця gaz використовується для стандартизації географічних назв та пов'язування цих даних з (а) вхідними токенами (див. the section called “Вхідні токени”) та (б) стандартизованими представленнями.
Таблиця gaz (скорочення від gazeteer) використовується для стандартизації назв місць та пов'язування цих даних з the section called “Вхідні токени” та (b) стандартизованими представленнями. Наприклад, якщо ви перебуваєте в США, ви можете завантажити ці дані разом із назвами штатів та відповідними абревіатурами.
Таблиця gaz має принаймні такі стовпці. Ви можете додати більше стовпців, якщо це необхідно для ваших потреб.
idПервинний ключ таблиці
seqinteger: definition number? - ідентифікатор, що використовується для цього екземпляра слова
wordtext: вхідне слово
stdwordtext: вхідне слово стандартизоване слово-замінник
tokeninteger: тип слова. Замінюється тільки в цьому контексті. Див. Токени PAGC.
debug_standardize_address — Повертає текст у форматі json із переліком розібраних токенів та стандартизацій
text debug_standardize_address(text lextab, text gaztab, text rultab, text micro, text macro=NULL);
Це функція для налагодження правил стандартизації адрес та відповідності лексичних одиниць (lex/gaz). Вона повертає текст у форматі json, що містить правила відповідності, відображення токенів та найкращу стандартизовану адресу stdaddr у вигляді вхідної адреси з використанням lex tableімен таблиць, gaz tableта rules tableімен таблиць та адреси.
Для однорядкових адрес використовуйте лише micro
Для дворядкової адреси A micro, що складається зі стандартного першого рядка поштової адреси, наприклад house_num street, та макросу, що складається зі стандартного другого рядка поштової адреси, наприклад city, state postal_code country.
Елементи, що повертаються в документі json, є такими
input_tokensДля кожного слова у вхідній адресі повертає позицію слова, категоризацію лексеми слова та стандартне слово, до якого воно відноситься. Зверніть увагу, що для деяких вхідних слів ви можете отримати кілька записів, оскільки деякі вхідні дані можуть бути віднесені до декількох категорій.
rulesНабір правил, що відповідають вхідним даним, та відповідний бал для кожного з них. Перше правило (з найвищим балом) використовується для стандартизації
stdaddrСтандартизовані елементи адреси stdaddr, які будуть повернуті при виконанні standardize_address
Доступність: 3.4.0
This method needs address_standardizer extension.
Використання розширення address_standardizer_data_us
CREATE EXTENSION address_standardizer_data_us; -- only needs to be done once
Варіант 1: Адреса в одному рядку та повернення вхідних токенів
SELECT it->>'pos' AS position, it->>'word' AS word, it->>'stdword' AS standardized_word,
it->>'token' AS token, it->>'token-code' AS token_code
FROM jsonb(
debug_standardize_address('us_lex',
'us_gaz', 'us_rules', 'One Devonshire Place, PH 301, Boston, MA 02109')
) AS s, jsonb_array_elements(s->'input_tokens') AS it;position | word | standardized_word | token | token_code ----------+------------+-------------------+--------+------------ 0 | ONE | 1 | NUMBER | 0 0 | ONE | 1 | WORD | 1 1 | DEVONSHIRE | DEVONSHIRE | WORD | 1 2 | PLACE | PLACE | TYPE | 2 3 | PH | PATH | TYPE | 2 3 | PH | PENTHOUSE | UNITT | 17 4 | 301 | 301 | NUMBER | 0 (7 rows)
Варіант 2: Багаторядкова адреса та повернення перших правил введення та оцінок
SELECT (s->'rules'->0->>'score')::numeric AS score, it->>'pos' AS position,
it->>'input-word' AS word, it->>'input-token' AS input_token, it->>'mapped-word' AS standardized_word,
it->>'output-token' AS output_token
FROM jsonb(
debug_standardize_address('us_lex',
'us_gaz', 'us_rules', 'One Devonshire Place, PH 301', 'Boston, MA 02109')
) AS s, jsonb_array_elements(s->'rules'->0->'rule_tokens') AS it;score | position | word | input_token | standardized_word | output_token ----------+----------+------------+-------------+-------------------+-------------- 0.876250 | 0 | ONE | NUMBER | 1 | HOUSE 0.876250 | 1 | DEVONSHIRE | WORD | DEVONSHIRE | STREET 0.876250 | 2 | PLACE | TYPE | PLACE | SUFTYP 0.876250 | 3 | PH | UNITT | PENTHOUSE | UNITT 0.876250 | 4 | 301 | NUMBER | 301 | UNITT (5 rows)
stdaddr, rules table, lex table, gaz table, Pagc_Normalize_Address
parse_address — Бере 1-рядкову адресу і розбиває на частини
record parse_address(text address);
Повертає адресу як вхідні дані та повертає запис, що складається з полів num, street, street2, address1, city, state, zip, zipplus, country.
Доступність: 2.2.0
This method needs address_standardizer extension.
Одинарна адреса
SELECT num, street, city, zip, zipplus
FROM parse_address('1 Devonshire Place, Boston, MA 02109-1234') AS a;num | street | city | zip | zipplus -----+------------------+--------+-------+--------- 1 | Devonshire Place | Boston | 02109 | 1234
Таблиця адрес
-- basic table
CREATE TABLE places(addid serial PRIMARY KEY, address text);
INSERT INTO places(address)
VALUES ('529 Main Street, Boston MA, 02129'),
('77 Massachusetts Avenue, Cambridge, MA 02139'),
('25 Wizard of Oz, Walaford, KS 99912323'),
('26 Capen Street, Medford, MA'),
('124 Mount Auburn St, Cambridge, Massachusetts 02138'),
('950 Main Street, Worcester, MA 01610');
-- parse the addresses
-- if you want all fields you can use (a).*
SELECT addid, (a).num, (a).street, (a).city, (a).state, (a).zip, (a).zipplus
FROM (SELECT addid, parse_address(address) As a
FROM places) AS p;addid | num | street | city | state | zip | zipplus
-------+-----+----------------------+-----------+-------+-------+---------
1 | 529 | Main Street | Boston | MA | 02129 |
2 | 77 | Massachusetts Avenue | Cambridge | MA | 02139 |
3 | 25 | Wizard of Oz | Walaford | KS | 99912 | 323
4 | 26 | Capen Street | Medford | MA | |
5 | 124 | Mount Auburn St | Cambridge | MA | 02138 |
6 | 950 | Main Street | Worcester | MA | 01610 |
(6 rows)standardize_address — Повертає форму stdaddr вхідної адреси, використовуючи таблиці lex, gaz та rule.
stdaddr standardize_address(text lextab, text gaztab, text rultab, text address);
stdaddr standardize_address(text lextab, text gaztab, text rultab, text micro, text macro);
Повертає stdaddrформу вхідної адреси, використовуючи lex tableім'я таблиці, gaz tableта rules tableімена таблиць та адресу.
Варіант 1: Приймає адресу в одному рядку.
Варіант 2: Приймає адресу у вигляді 2 частин. A micro, що складається зі стандартного першого рядка поштової адреси, наприклад house_num street, та макросу, що складається зі стандартного другого рядка поштової адреси, наприклад city, state postal_code country.
Доступність: 2.2.0
This method needs address_standardizer extension.
Використання розширення address_standardizer_data_us
CREATE EXTENSION address_standardizer_data_us; -- only needs to be done once
Варіант 1: Адреса в одному рядку. Це не працює з адресами за межами США
SELECT house_num, name, suftype, city, country, state, unit FROM standardize_address('us_lex',
'us_gaz', 'us_rules', 'One Devonshire Place, PH 301, Boston, MA 02109');house_num | name | suftype | city | country | state | unit ----------+------------+---------+--------+---------+---------------+----------------- 1 | DEVONSHIRE | PLACE | BOSTON | USA | MASSACHUSETTS | # PENTHOUSE 301
Використання таблиць, що входять до складу геокодера tiger. Цей приклад працює тільки в тому випадку, якщо ви встановили postgis_tiger_geocoder.
SELECT * FROM standardize_address('tiger.pagc_lex',
'tiger.pagc_gaz', 'tiger.pagc_rules', 'One Devonshire Place, PH 301, Boston, MA 02109-1234');Щоб полегшити читання, ми будемо виводити дані за допомогою розширення hstore CREATE EXTENSION hstore; вам потрібно встановити
SELECT (each(hstore(p))).*
FROM standardize_address('tiger.pagc_lex', 'tiger.pagc_gaz',
'tiger.pagc_rules', 'One Devonshire Place, PH 301, Boston, MA 02109') As p;key | value
------------+-----------------
box |
city | BOSTON
name | DEVONSHIRE
qual |
unit | # PENTHOUSE 301
extra |
state | MA
predir |
sufdir |
country | USA
pretype |
suftype | PL
building |
postcode | 02109
house_num | 1
ruralroute |
(16 rows)
Варіант 2: Як адреса, що складається з двох частин
SELECT (each(hstore(p))).*
FROM standardize_address('tiger.pagc_lex', 'tiger.pagc_gaz',
'tiger.pagc_rules', 'One Devonshire Place, PH 301', 'Boston, MA 02109, US') As p;key | value ------------+----------------- box | city | BOSTON name | DEVONSHIRE qual | unit | # PENTHOUSE 301 extra | state | MA predir | sufdir | country | USA pretype | suftype | PL building | postcode | 02109 house_num | 1 ruralroute | (16 rows)
stdaddr, rules table, lex table, gaz table, Pagc_Normalize_Address
Геокодер на основі plpgsql, написаний для роботи з TIGER (Topologically Integrated Geographic Encoding and Referencing system ) / Line and Master Address database export, випущеним Бюро перепису населення США.
Геокодер складається з чотирьох компонентів: функції завантаження даних, нормалізатор адрес, геокодер адрес та зворотний геокодер.
Хоча ця програма розроблена спеціально для США, багато її концепцій та функцій можна застосувати та адаптувати до адресних та дорожніх мереж інших країн.
Скрипт створює схему під назвою tiger для розміщення всіх функцій, пов'язаних з тиграми, даних для багаторазового використання, таких як префікси типів доріг, суфікси, стани, різні таблиці управління для керування завантаженням даних, а також базові таблиці-скелети, від яких успадковуються всі завантажені таблиці тигрів.
Також створюється інша схема під назвою tiger_data, яка містить усі дані перепису населення для кожного штату, які завантажувач завантажує з веб-сайту Census і завантажує в базу даних. У поточній моделі кожен набір таблиць штатів має префікс з кодом штату, наприклад ma_addr, ma_edges тощо, з обмеженнями, що застосовуються лише до даних цього штату. Кожна з цих таблиць успадковує таблиці addr, faces, edges тощо, розташовані в схемі tiger schema.
Усі функції геокодування посилаються лише на базові таблиці, тому немає вимоги, щоб схема даних називалася tiger_data або щоб дані не могли бути додатково розділені на інші схеми, наприклад, окрема схема для кожного штату, за умови, що всі таблиці успадковують таблиці зі схеми tiger.
Інструкції щодо увімкнення розширення у вашій базі даних, а також завантаження даних за його допомогою, див. Section 2.4.1, “Tiger Geocoder Увімкнення бази даних PostGIS”.
![]() | |
Якщо ви використовуєте геокодер tiger (tiger_2010), ви можете оновити скрипти за допомогою супровідних скриптів upgrade_geocoder.bat / .sh у папці extras/tiger. Одне з основних змін між |
![]() | |
Нововведенням у версії PostGIS 2.2.0 є підтримка даних Tiger 2015 та включення стандартизатора адрес до складу PostGIS. Новою функцією у версії PostGIS 2.1.0 є можливість інсталяції геокодера tiger із розширенням PostgreSQL, якщо ви використовуєте PostgreSQL 9.1+. Детальнішу інформацію див. у Section 2.4.1, “Tiger Geocoder Увімкнення бази даних PostGIS”. |
Функція Pagc_Normalize_Addressзамінює вбудовану функцію Normalize_Address. Інструкції щодо компіляції та встановлення див. у Section 2.3, “Встановлення та використання стандартизатора адрес”.
Дизайн:
Метою цього проекту є створення повністю функціонального геокодера, який може обробляти довільний рядок адреси в США і, використовуючи нормалізовані дані перепису TIGER, створювати геометрію точки та оцінку, що відображає місцезнаходження заданої адреси та ймовірність її розташування. Чим вищий рейтинг, тим гірший результат.
Функція reverse_geocode, введена в PostGIS 2.0.0, корисна для отримання адреси вулиці та перехресних вулиць з GPS-координат.
Геокодер повинен бути простим для встановлення та використання будь-яким користувачем, знайомим з PostGIS, а також легко встановлюватися та працювати на всіх платформах, що підтримуються PostGIS.
Він повинен бути достатньо надійним, щоб працювати належним чином, незважаючи на помилки форматування та орфографії.
Він повинен бути достатньо розширюваним, щоб його можна було використовувати з майбутніми оновленнями даних або альтернативними джерелами даних з мінімальними змінами в коді.
![]() | |
Щоб функції працювали належним чином, схема |
tiger_data.county_all, state_all або коду штату, за яким слідує county або state.tiger_data.normalized_address (адреса) для кожного місця та рейтинг. Чим нижчий рейтинг, тим більша ймовірність збігу. Результати сортуються за найнижчим рейтингом. Можна вказати максимальну кількість результатів, за замовчуванням — 10. Використовує дані Tiger (краї, грані, адреси), нечітке зіставлення рядків PostgreSQL (soundex, levenshtein).tiger_data. Кожен скрипт штату повертається як окремий запис.tiger_data. Кожен скрипт стану повертається як окремий запис. Остання версія підтримує структурні зміни Tiger 2010, а також завантажує таблиці перепису, групи блоків та блоки.norm_addy, що містить стандартизовані суфікс, префікс і тип дороги, вулицю, назву вулиці тощо, розділені на окремі поля. Ця функція працює лише з даними пошуку, що містяться в пакеті tiger_geocoder (дані перепису населення tiger не потрібні).norm_addy, що містить стандартизовані суфікс, префікс і тип дороги, вулицю, назву вулиці тощо, розділені на окремі поля. Ця функція працює лише з даними пошуку, що містяться в пакеті tiger_geocoder (дані перепису населення tiger не потрібні). Потрібне розширення address_standardizer.norm_addy повертає його представлення у вигляді зручного для друку формату. Зазвичай використовується разом із нормалізацією адреси.Існує ще кілька відкритих геокодерів для PostGIS, які, на відміну від tiger geocoder, мають перевагу у вигляді підтримки геокодування для різних країн
Nominatim використовує дані у форматі OpenStreetMap gazeteer. Для завантаження даних необхідні osm2pgsql, PostgreSQL 8.4+ та PostGIS 1.5+. Програма упакована як веб-інтерфейс і, судячи з усього, призначена для виклику як веб-сервіс. Так само, як і геокодер tiger, він має компоненти геокодера та зворотного геокодера. З документації не зрозуміло, чи має він чистий інтерфейс SQL, як геокодер tiger, чи значна частина логіки реалізована у веб-інтерфейсі.
GIS Graphy також використовує PostGIS і, як і Nominatim, працює з даними OpenStreetMap (OSM). Він постачається з завантажувачем для завантаження даних OSM і, подібно до Nominatim, здатний геокодувати не тільки США. Подібно до Nominatim, він працює як веб-сервіс і використовує Java 1.5, додатки Servlet, Solr. GisGraphy є кросплатформовим і має, серед інших корисних функцій, зворотний геокодер.
Drop_Indexes_Generate_Script — Створює скрипт, який видаляє всі не первинні ключі та не унікальні індекси зі схеми tiger та схеми, вказаної користувачем. Якщо схема не вказана, за замовчуванням використовується схема tiger_data.
text Drop_Indexes_Generate_Script(text param_schema=tiger_data);
Створює скрипт, який видаляє всі не первинні ключі та не унікальні індекси у схемі tiger та схемі, вказаній користувачем. Якщо схема не вказана, за замовчуванням використовується схема tiger_data
Це корисно для мінімізації роздуття індексу, яке може заплутати планувальник запитів або зайняти зайвий простір. Використовуйте разом з Install_Missing_Indexes, щоб додати тільки індекси, які використовуються геокодером.
Доступність: 2.0.0
SELECT drop_indexes_generate_script() As actionsql; actionsql --------------------------------------------------------- DROP INDEX tiger.idx_tiger_countysub_lookup_lower_name; DROP INDEX tiger.idx_tiger_edges_countyfp; DROP INDEX tiger.idx_tiger_faces_countyfp; DROP INDEX tiger.tiger_place_the_geom_gist; DROP INDEX tiger.tiger_edges_the_geom_gist; DROP INDEX tiger.tiger_state_the_geom_gist; DROP INDEX tiger.idx_tiger_addr_least_address; DROP INDEX tiger.idx_tiger_addr_tlid; DROP INDEX tiger.idx_tiger_addr_zip; DROP INDEX tiger.idx_tiger_county_countyfp; DROP INDEX tiger.idx_tiger_county_lookup_lower_name; DROP INDEX tiger.idx_tiger_county_lookup_snd_name; DROP INDEX tiger.idx_tiger_county_lower_name; DROP INDEX tiger.idx_tiger_county_snd_name; DROP INDEX tiger.idx_tiger_county_the_geom_gist; DROP INDEX tiger.idx_tiger_countysub_lookup_snd_name; DROP INDEX tiger.idx_tiger_cousub_countyfp; DROP INDEX tiger.idx_tiger_cousub_cousubfp; DROP INDEX tiger.idx_tiger_cousub_lower_name; DROP INDEX tiger.idx_tiger_cousub_snd_name; DROP INDEX tiger.idx_tiger_cousub_the_geom_gist; DROP INDEX tiger_data.idx_tiger_data_ma_addr_least_address; DROP INDEX tiger_data.idx_tiger_data_ma_addr_tlid; DROP INDEX tiger_data.idx_tiger_data_ma_addr_zip; DROP INDEX tiger_data.idx_tiger_data_ma_county_countyfp; DROP INDEX tiger_data.idx_tiger_data_ma_county_lookup_lower_name; DROP INDEX tiger_data.idx_tiger_data_ma_county_lookup_snd_name; DROP INDEX tiger_data.idx_tiger_data_ma_county_lower_name; DROP INDEX tiger_data.idx_tiger_data_ma_county_snd_name; : :
Drop_Nation_Tables_Generate_Script — Створює скрипт, який видаляє всі таблиці у вказаній схемі, що починаються з county_all, state_all або коду штату, за яким слідує county або state.
text Drop_Nation_Tables_Generate_Script(text param_schema=tiger_data);
Створює скрипт, який видаляє всі таблиці у вказаній схемі, що починаються з county_all, state_all або коду штату, за яким слідує county або state. Це потрібно, якщо ви оновлюєте дані з tiger_2010 до tiger_2011.
Доступність: 2.1.0
SELECT drop_nation_tables_generate_script(); DROP TABLE tiger_data.county_all; DROP TABLE tiger_data.county_all_lookup; DROP TABLE tiger_data.state_all; DROP TABLE tiger_data.ma_county; DROP TABLE tiger_data.ma_state;
Drop_State_Tables_Generate_Script — Створює скрипт, який видаляє всі таблиці у вказаній схемі, що мають префікс у вигляді абревіатури стану. Якщо схема не вказана, за замовчуванням використовується схема tiger_data.
text Drop_State_Tables_Generate_Script(text param_state, text param_schema=tiger_data);
Створює скрипт, який видаляє всі таблиці у вказаній схемі, що мають префікс з абревіатурою стану. Якщо схема не вказана, за замовчуванням використовується схема tiger_data. Ця функція корисна для видалення таблиць стану безпосередньо перед перезавантаженням стану на випадок, якщо під час попереднього завантаження сталася помилка.
Доступність: 2.0.0
SELECT drop_state_tables_generate_script('PA');
DROP TABLE tiger_data.pa_addr;
DROP TABLE tiger_data.pa_county;
DROP TABLE tiger_data.pa_county_lookup;
DROP TABLE tiger_data.pa_cousub;
DROP TABLE tiger_data.pa_edges;
DROP TABLE tiger_data.pa_faces;
DROP TABLE tiger_data.pa_featnames;
DROP TABLE tiger_data.pa_place;
DROP TABLE tiger_data.pa_state;
DROP TABLE tiger_data.pa_zip_lookup_base;
DROP TABLE tiger_data.pa_zip_state;
DROP TABLE tiger_data.pa_zip_state_loc;
Geocode — Приймає адресу у вигляді рядка (або іншої нормалізованої адреси) і виводить набір можливих місць, що включають геометрію точки в NAD 83 long lat, нормалізовану адресу для кожного з них та рейтинг. Чим нижчий рейтинг, тим більша ймовірність збігу. Результати сортуються за найнижчим рейтингом. Можна додатково передати максимальну кількість результатів (за замовчуванням 10) та обмежити регіон (за замовчуванням NULL)
setof record geocode(varchar address, integer max_results=10, geometry restrict_region=NULL, norm_addy OUT addy, geometry OUT geomout, integer OUT rating);
setof record geocode(norm_addy in_addy, integer max_results=10, geometry restrict_region=NULL, norm_addy OUT addy, geometry OUT geomout, integer OUT rating);
Приймає адресу у вигляді рядка (або вже нормалізовану адресу) і виводить набір можливих місць, що включають геометрію точки в NAD 83 long lat, normalized_address (addy) для кожного з них та рейтинг. Чим нижчий рейтинг, тим більша ймовірність збігу. Результати сортуються за найнижчим рейтингом. Використовує дані Tiger (краї, грані, адреси), нечітке зіставлення рядків PostgreSQL (soundex, levenshtein) та функції інтерполяції ліній PostGIS для інтерполяції адреси вздовж країв Tiger. Чим вищий рейтинг, тим менша ймовірність правильності геокоду. Геокодована точка за замовчуванням зміщена на 10 метрів від центральної лінії в бік (L/R) від адреси вулиці, на якій вона розташована.
Покращено: 2.0.0 для підтримки структурованих даних Tiger 2010 та переглянуто деякі логічні алгоритми для підвищення швидкості, точності геокодування та зміщення точки від центральної лінії до сторони вулиці, на якій розташована адреса. Новий параметр max_results корисний для вказання кількості найкращих результатів або для повернення лише найкращого результату.
Наведені нижче приклади часу виконання були отримані на однопроцесорному комп'ютері з частотою 3,0 ГГц, операційною системою Windows 7, 2 ГБ оперативної пам'яті та встановленим програмним забезпеченням PostgreSQL 9.1rc1/PostGIS 2.0, завантаженим усіма даними про штати Массачусетс, Міннесота, Каліфорнія та Род-Айленд, отриманими з Tiger.
Точні збіги обчислюються швидше (61 мс)
SELECT g.rating, ST_X(g.geomout) As lon, ST_Y(g.geomout) As lat,
(addy).address As stno, (addy).streetname As street,
(addy).streettypeabbrev As styp, (addy).location As city, (addy).stateabbrev As st,(addy).zip
FROM geocode('75 State Street, Boston MA 02109', 1) As g;
rating | lon | lat | stno | street | styp | city | st | zip
--------+-------------------+----------------+------+--------+------+--------+----+-------
0 | -71.0557505845646 | 42.35897920691 | 75 | State | St | Boston | MA | 02109
Навіть якщо zip-код не передається, геокодер може вгадати (займає близько 122-150 мс)
SELECT g.rating, ST_AsText(ST_SnapToGrid(g.geomout,0.00001)) As wktlonlat,
(addy).address As stno, (addy).streetname As street,
(addy).streettypeabbrev As styp, (addy).location As city, (addy).stateabbrev As st,(addy).zip
FROM geocode('226 Hanover Street, Boston, MA',1) As g;
rating | wktlonlat | stno | street | styp | city | st | zip
--------+---------------------------+------+---------+------+--------+----+-------
1 | POINT(-71.05528 42.36316) | 226 | Hanover | St | Boston | MA | 02113
Може обробляти орфографічні помилки та надає кілька можливих рішень з оцінками, але працює довше (500 мс).
SELECT g.rating, ST_AsText(ST_SnapToGrid(g.geomout,0.00001)) As wktlonlat,
(addy).address As stno, (addy).streetname As street,
(addy).streettypeabbrev As styp, (addy).location As city, (addy).stateabbrev As st,(addy).zip
FROM geocode('31 - 37 Stewart Street, Boston, MA 02116',1) As g;
rating | wktlonlat | stno | street | styp | city | st | zip
--------+---------------------------+------+--------+------+--------+----+-------
70 | POINT(-71.06466 42.35114) | 31 | Stuart | St | Boston | MA | 02116
Використовується для пакетного геокодування адрес. Найпростіше встановити max_results=1. Обробляються тільки ті, що ще не геокодовані (не мають рейтингу).
CREATE TABLE addresses_to_geocode(addid serial PRIMARY KEY, address text,
lon numeric, lat numeric, new_address text, rating integer);
INSERT INTO addresses_to_geocode(address)
VALUES ('529 Main Street, Boston MA, 02129'),
('77 Massachusetts Avenue, Cambridge, MA 02139'),
('25 Wizard of Oz, Walaford, KS 99912323'),
('26 Capen Street, Medford, MA'),
('124 Mount Auburn St, Cambridge, Massachusetts 02138'),
('950 Main Street, Worcester, MA 01610');
-- only update the first 3 addresses (323-704 ms - there are caching and shared memory effects so first geocode you do is always slower) --
-- for large numbers of addresses you don't want to update all at once
-- since the whole geocode must commit at once
-- For this example we rejoin with LEFT JOIN
-- and set to rating to -1 rating if no match
-- to ensure we don't regeocode a bad address
UPDATE addresses_to_geocode
SET (rating, new_address, lon, lat)
= ( COALESCE(g.rating,-1), pprint_addy(g.addy),
ST_X(g.geomout)::numeric(8,5), ST_Y(g.geomout)::numeric(8,5) )
FROM (SELECT addid, address
FROM addresses_to_geocode
WHERE rating IS NULL ORDER BY addid LIMIT 3) As a
LEFT JOIN LATERAL geocode(a.address,1) As g ON true
WHERE a.addid = addresses_to_geocode.addid;
result
-----
Query returned successfully: 3 rows affected, 480 ms execution time.
SELECT * FROM addresses_to_geocode WHERE rating is not null;
addid | address | lon | lat | new_address | rating
-------+----------------------------------------------+-----------+----------+-------------------------------------------+--------
1 | 529 Main Street, Boston MA, 02129 | -71.07177 | 42.38357 | 529 Main St, Boston, MA 02129 | 0
2 | 77 Massachusetts Avenue, Cambridge, MA 02139 | -71.09396 | 42.35961 | 77 Massachusetts Ave, Cambridge, MA 02139 | 0
3 | 25 Wizard of Oz, Walaford, KS 99912323 | -97.92913 | 38.12717 | Willowbrook, KS 67502 | 108
(3 rows)SELECT g.rating, ST_AsText(ST_SnapToGrid(g.geomout,0.00001)) As wktlonlat,
(addy).address As stno, (addy).streetname As street,
(addy).streettypeabbrev As styp,
(addy).location As city, (addy).stateabbrev As st,(addy).zip
FROM geocode('100 Federal Street, MA',
3,
(SELECT ST_Union(the_geom)
FROM place WHERE statefp = '25' AND name = 'Lynn')::geometry
) As g;
rating | wktlonlat | stno | street | styp | city | st | zip
--------+---------------------------+------+---------+------+------+----+-------
7 | POINT(-70.96796 42.4659) | 100 | Federal | St | Lynn | MA | 01905
16 | POINT(-70.96786 42.46853) | NULL | Federal | St | Lynn | MA | 01905
(2 rows)
Time: 622.939 ms
Normalize_Address, Pprint_Addy, ST_AsText, ST_SnapToGrid, ST_X, ST_Y
Geocode_Intersection — Приймає 2 перехресні вулиці, штат, місто, поштовий індекс і видає набір можливих місць на першій перехресній вулиці, що знаходиться на перехресті, а також включає геокоординати як точку розташування в NAD 83 long lat, normalized_address (адреса) для кожного місця та рейтинг. Чим нижчий рейтинг, тим більша ймовірність збігу. Результати сортуються за найнижчим рейтингом. Можна вказати максимальну кількість результатів, за замовчуванням — 10. Використовує дані Tiger (краї, грані, адреси), нечітке зіставлення рядків PostgreSQL (soundex, levenshtein).
setof record geocode_intersection(text roadway1, text roadway2, text in_state, text in_city, text in_zip, integer max_results=10, norm_addy OUT addy, geometry OUT geomout, integer OUT rating);
Приймає 2 перехресні вулиці, штат, місто, поштовий індекс і виводить набір можливих місць на першій перехресній вулиці, що знаходиться на перехресті, а також включає геометрію точки в NAD 83 long lat, нормалізовану адресу для кожного місця та рейтинг. Чим нижчий рейтинг, тим більша ймовірність збігу. Результати сортуються за найнижчим рейтингом. Можна опціонально передати максимальну кількість результатів, за замовчуванням 10. Повертає normalized_address (addy) для кожного, geomout як точку розташування в NAD 83 long lat та рейтинг. Чим нижчий рейтинг, тим більша ймовірність збігу. Результати сортуються за найнижчим рейтингом. Використовує дані Tiger (краї, грані, адреси), нечітке зіставлення рядків PostgreSQL (soundex, levenshtein)
Доступність: 2.0.0
Наведені нижче приклади часу виконання отримані на однопроцесорному комп'ютері з частотою 3,0 ГГц, ОС Windows 7, 2 ГБ оперативної пам'яті, PostgreSQL 9.0/PostGIS 1.5 та всіма даними про тигрів штату Массачусетс. Наразі трохи повільно (3000 мс)
Тестування на Windows 2003 64-біт 8 ГБ на PostGIS 2.0 PostgreSQL 64-біт Tiger 2011 дані завантажено -- (41 мс)
SELECT pprint_addy(addy), st_astext(geomout),rating
FROM geocode_intersection( 'Haverford St','Germania St', 'MA', 'Boston', '02130',1);
pprint_addy | st_astext | rating
----------------------------------+----------------------------+--------
98 Haverford St, Boston, MA 02130 | POINT(-71.101375 42.31376) | 0
Навіть якщо zip не передається, геокодер може вгадати (на комп'ютері з Windows 7 це зайняло близько 3500 мс), на Windows 2003 64-біт — 741 мс
SELECT pprint_addy(addy), st_astext(geomout),rating
FROM geocode_intersection('Weld', 'School', 'MA', 'Boston');
pprint_addy | st_astext | rating
-------------------------------+--------------------------+--------
98 Weld Ave, Boston, MA 02119 | POINT(-71.099 42.314234) | 3
99 Weld Ave, Boston, MA 02119 | POINT(-71.099 42.314234) | 3
Get_Geocode_Setting — Повертає значення конкретного параметра, збереженого в таблиці tiger.geocode_settings.
text Get_Geocode_Setting(text setting_name);
Повертає значення конкретного параметра, збереженого в таблиці tiger.geocode_settings. Параметри дозволяють вмикати та вимикати налагодження функцій. У майбутньому планується контролювати рейтинг за допомогою параметрів. Поточний список параметрів такий:
name | setting | unit | category | short_desc
--------------------------------+---------+---------+-----------+------------------------------------------------------------------------------------------------------------------------------
debug_geocode_address | false | boolean | debug | outputs debug information in notice log such as queries when geocode_address is called if true
debug_geocode_intersection | false | boolean | debug | outputs debug information in notice log such as queries when geocode_intersection is called if true
debug_normalize_address | false | boolean | debug | outputs debug information in notice log such as queries and intermediate expressions when normalize_address is called if true
debug_reverse_geocode | false | boolean | debug | if true, outputs debug information in notice log such as queries and intermediate expressions when reverse_geocode
reverse_geocode_numbered_roads | 0 | integer | rating | For state and county highways, 0 - no preference in name,
1 - prefer the numbered highway name, 2 - prefer local state/county name
use_pagc_address_parser | false | boolean | normalize | If set to true, will try to use the address_standardizer extension (via pagc_normalize_address)
instead of tiger normalize_address built one Змінено: 2.2.0: стандартні налаштування тепер зберігаються в таблиці під назвою geocode_settings_default. Налаштування, що були змінені користувачем, зберігаються в geocode_settings і містять лише ті налаштування, які були встановлені користувачем.
Доступність: 2.1.0
SELECT get_geocode_setting('debug_geocode_address) As result;
result
---------
false
Get_Tract — Повертає переписний район або поле з таблиці районів, де розташована геометрія. За замовчуванням повертається коротка назва району.
text get_tract(geometry loc_geom, text output_field=name);
За заданою геометрією поверне місце розташування переписної ділянки цієї геометрії. Якщо просторова система координат не вказана, використовується NAD 83 (довгота, широта).
![]() | |
Ця функція використовує перепис Якщо ви ще не завантажили дані про свій штат і хочете завантажити ці додаткові таблиці, виконайте наступні дії UPDATE tiger.loader_lookuptables SET load = true WHERE load = false AND lookup_name IN('tract', 'bg', 'tabblock');тоді вони будуть включені за допомогою Loader_Generate_Script. |
Доступність: 2.0.0
SELECT get_tract(ST_Point(-71.101375, 42.31376) ) As tract_name;
tract_name
---------
1203.01
--this one returns the tiger geoid SELECT get_tract(ST_Point(-71.101375, 42.31376), 'tract_id' ) As tract_id; tract_id --------- 25025120301
Install_Missing_Indexes — Знаходить усі таблиці з ключовими стовпцями, що використовуються в з'єднаннях геокодера та умовах фільтрації, в яких відсутні використовувані індекси для цих стовпців, і додає їх.
boolean Install_Missing_Indexes();
Знаходить усі таблиці в схемах tiger та tiger_data із ключовими стовпцями, що використовуються в з'єднаннях та фільтрах геокодера, для яких відсутні індекси в цих стовпцях, і виводить SQL DDL для визначення індексу для цих таблиць, а потім виконує згенерований скрипт. Це допоміжна функція, яка додає нові індекси, необхідні для пришвидшення запитів, які могли бути відсутні під час процесу завантаження. Ця функція є доповненням до Missing_Indexes_Generate_Script, яка, крім створення скрипту для створення індексу, також виконує його. Вона викликається як частина скрипту оновлення update_geocode.sql.
Доступність: 2.0.0
SELECT install_missing_indexes();
install_missing_indexes
-------------------------
t
Loader_Generate_Census_Script — Створює скрипт оболонки для вказаної платформи для вказаних штатів, який завантажить таблиці даних Tiger census state tract, bg та tabblocks, підготує та завантажить їх у схему tiger_data. Кожен скрипт штату повертається як окремий запис.
setof text loader_generate_census_script(text[] param_states, text os);
Створює скрипт оболонки для вказаної платформи для вказаних станів, який завантажить дані перепису Tiger tract, групи блоків bg та таблиці даних tabblocks, розмістить їх у схемі tiger_data та завантажить. Кожен скрипт стану повертається як окремий запис.
Для завантаження використовується програма unzip в Linux (7-zip в Windows за замовчуванням) та wget. Для завантаження даних використовується Section 4.7.2, “Using the Shapefile Loader”. Зверніть увагу, що найменша одиниця, яку обробляє програма, — це цілий штат. Програма обробляє лише файли в папках staging та temp.
Для управління процесом і різними варіантами синтаксису оболонки ОС використовуються наступні таблиці управління.
loader_variables відстежує різні змінні, такі як місце перепису, рік, дані та схеми підготовки
loader_platform профілі різних платформ і розташування різних виконуваних файлів. Поставляється з Windows і Linux. Можна додати інші.
loader_lookuptables кожен запис визначає тип таблиці (штат, округ), чи обробляти записи в ній і як їх завантажувати. Визначає кроки для імпорту даних, підготовки даних, додавання, видалення стовпців, індексів та обмежень для кожного з них. Кожна таблиця має префікс із зазначенням стану та успадковує таблицю зі схеми tiger. Наприклад, створюється tiger_data.ma_faces, яка успадковує tiger.faces
Доступність: 2.0.0
![]() | |
Loader_Generate_Script включає цю логіку, але якщо ви встановили tiger geocoder до PostGIS 2.0.0 alpha5, вам потрібно буде запустити це на штатах, які ви вже обробили, щоб отримати ці додаткові таблиці. |
Створити скрипт для завантаження даних для вибраних штатів у форматі скрипту оболонки Windows.
SELECT loader_generate_census_script(ARRAY['MA'], 'windows');
-- result --
set STATEDIR="\gisdata\www2.census.gov\geo\pvs\tiger2010st\25_Massachusetts"
set TMPDIR=\gisdata\temp\
set UNZIPTOOL="C:\Program Files\7-Zip\7z.exe"
set WGETTOOL="C:\wget\wget.exe"
set PGBIN=C:\projects\pg\pg91win\bin\
set PGPORT=5432
set PGHOST=localhost
set PGUSER=postgres
set PGPASSWORD=yourpasswordhere
set PGDATABASE=tiger_postgis20
set PSQL="%PGBIN%psql"
set SHP2PGSQL="%PGBIN%shp2pgsql"
cd \gisdata
%WGETTOOL% http://www2.census.gov/geo/pvs/tiger2010st/25_Massachusetts/25/ --no-parent --relative --accept=*bg10.zip,*tract10.zip,*tabblock10.zip --mirror --reject=html
del %TMPDIR%\*.* /Q
%PSQL% -c "DROP SCHEMA tiger_staging CASCADE;"
%PSQL% -c "CREATE SCHEMA tiger_staging;"
cd %STATEDIR%
for /r %%z in (*.zip) do %UNZIPTOOL% e %%z -o%TMPDIR%
cd %TMPDIR%
%PSQL% -c "CREATE TABLE tiger_data.MA_tract(CONSTRAINT pk_MA_tract PRIMARY KEY (tract_id) ) INHERITS(tiger.tract); "
%SHP2PGSQL% -c -s 4269 -g the_geom -W "latin1" tl_2010_25_tract10.dbf tiger_staging.ma_tract10 | %PSQL%
%PSQL% -c "ALTER TABLE tiger_staging.MA_tract10 RENAME geoid10 TO tract_id; SELECT loader_load_staged_data(lower('MA_tract10'), lower('MA_tract')); "
%PSQL% -c "CREATE INDEX tiger_data_MA_tract_the_geom_gist ON tiger_data.MA_tract USING gist(the_geom);"
%PSQL% -c "VACUUM ANALYZE tiger_data.MA_tract;"
%PSQL% -c "ALTER TABLE tiger_data.MA_tract ADD CONSTRAINT chk_statefp CHECK (statefp = '25');"
: Створити скрипт sh
STATEDIR="/gisdata/www2.census.gov/geo/pvs/tiger2010st/25_Massachusetts"
TMPDIR="/gisdata/temp/"
UNZIPTOOL=unzip
WGETTOOL="/usr/bin/wget"
export PGBIN=/usr/pgsql-9.0/bin
export PGPORT=5432
export PGHOST=localhost
export PGUSER=postgres
export PGPASSWORD=yourpasswordhere
export PGDATABASE=geocoder
PSQL=${PGBIN}/psql
SHP2PGSQL=${PGBIN}/shp2pgsql
cd /gisdata
wget http://www2.census.gov/geo/pvs/tiger2010st/25_Massachusetts/25/ --no-parent --relative --accept=*bg10.zip,*tract10.zip,*tabblock10.zip --mirror --reject=html
rm -f ${TMPDIR}/*.*
${PSQL} -c "DROP SCHEMA tiger_staging CASCADE;"
${PSQL} -c "CREATE SCHEMA tiger_staging;"
cd $STATEDIR
for z in *.zip; do $UNZIPTOOL -o -d $TMPDIR $z; done
:
: Loader_Generate_Script — Створює скрипт оболонки для вказаної платформи для вказаних станів, який завантажить дані Tiger, підготує та завантажить у схему tiger_data. Кожен скрипт стану повертається як окремий запис. Остання версія підтримує структурні зміни Tiger 2010, а також завантажує таблиці перепису, групи блоків та блоки.
setof text loader_generate_script(text[] param_states, text os);
Створює скрипт оболонки для вказаної платформи для вказаних станів, який завантажить дані Tiger, підготує та завантажить у схему tiger_data. Кожен скрипт стану повертається як окремий запис.
Для завантаження використовується програма unzip в Linux (7-zip в Windows за замовчуванням) та wget. Для завантаження даних використовується Section 4.7.2, “Using the Shapefile Loader”. Зверніть увагу, що найменша одиниця, яку обробляє програма, — це весь штат, але ви можете замінити це, завантаживши файли самостійно. Програма обробляє лише файли в папках staging та temp.
Для управління процесом і різними варіантами синтаксису оболонки ОС використовуються наступні таблиці управління.
loader_variables відстежує різні змінні, такі як місце перепису, рік, дані та схеми підготовки
loader_platform профілі різних платформ і розташування різних виконуваних файлів. Поставляється з Windows і Linux. Можна додати інші.
loader_lookuptables кожен запис визначає тип таблиці (штат, округ), чи обробляти записи в ній і як їх завантажувати. Визначає кроки для імпорту даних, підготовки даних, додавання, видалення стовпців, індексів та обмежень для кожного з них. Кожна таблиця має префікс із зазначенням стану та успадковує таблицю зі схеми tiger. Наприклад, створюється tiger_data.ma_faces, яка успадковує tiger.faces
Доступність: 2.0.0 для підтримки структурованих даних Tiger 2010 та завантаження таблиць перепису населення (tract), груп кварталів (bg) та кварталів (tabblocks).
![]() | |
Якщо ви використовуєте pgAdmin 3, майте на увазі, що за замовчуванням pgAdmin 3 обрізає довгий текст. Щоб виправити це, змініть Файл -> Параметри -> Інструмент запитів -> Редактор запитів - >Макс. кількість символів у стовпці на значення, більше 50000 символів. |
Використовуючи psql, де gistest — ваша база даних, а /gisdata/data_load.sh — файл, який потрібно створити за допомогою команд оболонки, що виконуються.
psql -U postgres -h localhost -d gistest -A -t \ -c "SELECT Loader_Generate_Script(ARRAY['MA'], 'gistest')" > /gisdata/data_load.sh;
Створити скрипт для завантаження даних для 2 штатів у форматі скрипту оболонки Windows.
SELECT loader_generate_script(ARRAY['MA','RI'], 'windows') AS result; -- result -- set TMPDIR=\gisdata\temp\ set UNZIPTOOL="C:\Program Files\7-Zip\7z.exe" set WGETTOOL="C:\wget\wget.exe" set PGBIN=C:\Program Files\PostgreSQL\9.4\bin\ set PGPORT=5432 set PGHOST=localhost set PGUSER=postgres set PGPASSWORD=yourpasswordhere set PGDATABASE=geocoder set PSQL="%PGBIN%psql" set SHP2PGSQL="%PGBIN%shp2pgsql" cd \gisdata cd \gisdata %WGETTOOL% ftp://ftp2.census.gov/geo/tiger/TIGER2015/PLACE/tl_*_25_* --no-parent --relative --recursive --level=2 --accept=zip --mirror --reject=html cd \gisdata/ftp2.census.gov/geo/tiger/TIGER2015/PLACE : :
Створити скрипт sh
SELECT loader_generate_script(ARRAY['MA','RI'], 'sh') AS result;
-- result --
TMPDIR="/gisdata/temp/"
UNZIPTOOL=unzip
WGETTOOL="/usr/bin/wget"
export PGBIN=/usr/lib/postgresql/9.4/bin
-- variables used by psql: https://www.postgresql.org/docs/current/static/libpq-envars.html
export PGPORT=5432
export PGHOST=localhost
export PGUSER=postgres
export PGPASSWORD=yourpasswordhere
export PGDATABASE=geocoder
PSQL=${PGBIN}/psql
SHP2PGSQL=${PGBIN}/shp2pgsql
cd /gisdata
cd /gisdata
wget ftp://ftp2.census.gov/geo/tiger/TIGER2015/PLACE/tl_*_25_* --no-parent --relative --recursive --level=2 --accept=zip --mirror --reject=html
cd /gisdata/ftp2.census.gov/geo/tiger/TIGER2015/PLACE
rm -f ${TMPDIR}/*.*
:
:Loader_Generate_Nation_Script — Створює скрипт оболонки для вказаної платформи, який завантажує таблиці пошуку округів та штатів.
text loader_generate_nation_script(text os);
Створює скрипт оболонки для вказаної платформи, який завантажує таблиці county_all, county_all_lookup, state_all у схему tiger_data. Вони успадковуються відповідно від таблиць county, county_lookup, state у схемі tiger.
Для завантаження використовується програма unzip в Linux (7-zip в Windows за замовчуванням) та wget. Для завантаження даних використовується Section 4.7.2, “Using the Shapefile Loader”.
Він використовує наступні таблиці керування tiger.loader_platform, tiger.loader_variables та tiger.loader_lookuptables для керування процесом та різними варіаціями синтаксису оболонки ОС.
loader_variables відстежує різні змінні, такі як місце перепису, рік, дані та схеми підготовки
loader_platform профілі різних платформ та розташування різних виконуваних файлів. Поставляється з Windows та Linux/Unix. Можна додати більше.
loader_lookuptables кожен запис визначає тип таблиці (штат, округ), чи обробляти записи в ній і як їх завантажувати. Визначає кроки для імпорту даних, підготовки даних, додавання, видалення стовпців, індексів та обмежень для кожного з них. Кожна таблиця має префікс із зазначенням стану та успадковує таблицю зі схеми tiger. Наприклад, створюється tiger_data.ma_faces, яка успадковує tiger.faces
Покращено: 2.4.1 виправлено завантаження кроку табуляції поштового індексу 5 (zcta5) і, коли ця опція увімкнена, дані zcta5 завантажуються як одна таблиця під назвою zcta5_all у складі завантаження скрипту країни.
Доступність: 2.1.0
![]() | |
Якщо ви хочете, щоб область табуляції поштового індексу 5 (zcta5) була включена в завантаження скрипту вашої країни, виконайте наступні дії: UPDATE tiger.loader_lookuptables SET load = true WHERE table_name = 'zcta510'; |
![]() | |
Якщо ви використовували версію |
Створити скрипт для завантаження національних даних Windows.
SELECT loader_generate_nation_script('windows'); Створити скрипт для завантаження даних для систем Linux/Unix.
SELECT loader_generate_nation_script('sh'); Missing_Indexes_Generate_Script — Знаходить усі таблиці з ключовими стовпцями, що використовуються в з'єднаннях геокодера, в яких відсутні індекси для цих стовпців, і виводить SQL DDL для визначення індексу для цих таблиць.
text Missing_Indexes_Generate_Script();
Знаходить усі таблиці в схемах tiger та tiger_data із ключовими стовпцями, що використовуються в з'єднаннях геокодера, для яких відсутні індекси в цих стовпцях, і виводить SQL DDL для визначення індексу для цих таблиць. Це допоміжна функція, яка додає нові індекси, необхідні для прискорення запитів, які могли бути відсутні під час процесу завантаження. У міру вдосконалення геокодера ця функція буде оновлюватися для врахування нових індексів, що використовуються. Якщо ця функція не виводить нічого, це означає, що всі ваші таблиці вже мають, на нашу думку, необхідні ключові індекси.
Доступність: 2.0.0
SELECT missing_indexes_generate_script();
-- output: This was run on a database that was created before many corrections were made to the loading script ---
CREATE INDEX idx_tiger_county_countyfp ON tiger.county USING btree(countyfp);
CREATE INDEX idx_tiger_cousub_countyfp ON tiger.cousub USING btree(countyfp);
CREATE INDEX idx_tiger_edges_tfidr ON tiger.edges USING btree(tfidr);
CREATE INDEX idx_tiger_edges_tfidl ON tiger.edges USING btree(tfidl);
CREATE INDEX idx_tiger_zip_lookup_all_zip ON tiger.zip_lookup_all USING btree(zip);
CREATE INDEX idx_tiger_data_ma_county_countyfp ON tiger_data.ma_county USING btree(countyfp);
CREATE INDEX idx_tiger_data_ma_cousub_countyfp ON tiger_data.ma_cousub USING btree(countyfp);
CREATE INDEX idx_tiger_data_ma_edges_countyfp ON tiger_data.ma_edges USING btree(countyfp);
CREATE INDEX idx_tiger_data_ma_faces_countyfp ON tiger_data.ma_faces USING btree(countyfp);
Normalize_Address — За заданою текстовою адресою повертає комбінований тип norm_addy, що містить стандартизовані суфікс, префікс і тип дороги, вулицю, назву вулиці тощо, розділені на окремі поля. Ця функція працює лише з даними пошуку, що містяться в пакеті tiger_geocoder (дані перепису населення tiger не потрібні).
norm_addy normalize_address(varchar in_address);
За заданою текстовою адресою повертає комбінований тип norm_addy, що містить стандартизовані суфікси, префікси та типи доріг, вулиці, назви вулиць тощо, розділені на окремі поля. Це перший крок у процесі геокодування, що дозволяє перетворити всі адреси у стандартизований поштовий формат. Крім даних, що містяться в пакеті геокодера, ніякі інші дані не потрібні.
Ця функція просто використовує різні таблиці пошуку напрямків/станів/суфіксів, попередньо завантажені за допомогою tiger_geocoder і розташовані в схемі tiger, тому для її використання не потрібно завантажувати дані перепису tiger або будь-які інші додаткові дані. Можливо, вам знадобиться додати більше скорочень або альтернативних назв до різних таблиць пошуку в схемі tiger.
Він використовує різні таблиці контролю, розташовані в схемі tiger, для нормалізації вхідної адреси.
Поля в об'єкті типу norm_addy, що повертається цією функцією в такому порядку, де () позначає поле, необхідне для геокодера, [] позначає необов'язкове поле:
(address) [predirAbbrev] (streetName) [streetTypeAbbrev] [postdirAbbrev] [internal] [location] [stateAbbrev] [zip] [parsed] [zip4] [address_alphanumeric]
Покращено: об'єкт norm_addy версії 2.4.0 містить додаткові поля zip4 та address_alphanumeric.
address є цілим числом: номер будинку
predirAbbrev є varchar: напрямний префікс дороги, такий як N, S, E, W тощо. Вони контролюються за допомогою таблиці direction_lookup.
streetName varchar
streetTypeAbbrev varchar скорочена версія типу вулиці: наприклад, St, Ave, Cir. Вони контролюються за допомогою таблиці street_type_lookup.
postdirAbbrev varchar скорочений напрямний суфікс дороги N, S, E, W тощо. Вони контролюються за допомогою таблиці direction_lookup.
internal varchar внутрішня адреса, така як номер квартири або номер кімнати.
location varchar зазвичай місто або адміністративна область.
stateAbbrev varchar два символи, штат США. Наприклад, MA, NY, MI. Вони контролюються таблицею state_lookup.
zip varchar 5-значний поштовий індекс. Наприклад, 02109.
parsed boolean - позначає, чи адреса була сформована в результаті процесу нормалізації. Функція normalize_address встановлює це значення на true перед поверненням адреси.
zip4 останні 4 цифри 9-значного поштового індексу. Доступність: PostGIS 2.4.0.
address_alphanumeric Повний номер вулиці, навіть якщо він містить літери, наприклад 17R. Розбір цього краще виконувати за допомогою функції Pagc_Normalize_Address. Доступність: PostGIS 2.4.0.
Поля вибору виводу. Використовуйте Pprint_Addy, якщо хочете отримати гарний текстовий вивід.
SELECT address As orig, (g.na).streetname, (g.na).streettypeabbrev
FROM (SELECT address, normalize_address(address) As na
FROM addresses_to_geocode) As g;
orig | streetname | streettypeabbrev
-----------------------------------------------------+---------------+------------------
28 Capen Street, Medford, MA | Capen | St
124 Mount Auburn St, Cambridge, Massachusetts 02138 | Mount Auburn | St
950 Main Street, Worcester, MA 01610 | Main | St
529 Main Street, Boston MA, 02129 | Main | St
77 Massachusetts Avenue, Cambridge, MA 02139 | Massachusetts | Ave
25 Wizard of Oz, Walaford, KS 99912323 | Wizard of Oz |
Pagc_Normalize_Address — За заданою текстовою адресою повертає комбінований тип norm_addy, що містить стандартизовані суфікс, префікс і тип дороги, вулицю, назву вулиці тощо, розділені на окремі поля. Ця функція працює лише з даними пошуку, що містяться в пакеті tiger_geocoder (дані перепису населення tiger не потрібні). Потрібне розширення address_standardizer.
norm_addy pagc_normalize_address(varchar in_address);
За заданою текстовою адресою повертає комбінований тип norm_addy, що містить стандартизовані суфікси, префікси та типи доріг, вулиці, назви вулиць тощо, розділені на окремі поля. Це перший крок у процесі геокодування, що дозволяє перетворити всі адреси у стандартизований поштовий формат. Крім даних, що містяться в пакеті геокодера, ніякі інші дані не потрібні.
Ця функція використовує різні таблиці пошуку pagc_*, попередньо завантажені за допомогою tiger_geocoder і розташовані в схемі tiger, тому для її використання не потрібно завантажувати дані перепису tiger або будь-які інші додаткові дані. Можливо, вам знадобиться додати більше скорочень або альтернативних назв до різних таблиць пошуку в схемі tiger.
Він використовує різні таблиці контролю, розташовані в схемі tiger, для нормалізації вхідної адреси.
Поля в об'єкті типу norm_addy, що повертається цією функцією в такому порядку, де () позначає поле, необхідне для геокодера, [] позначає необов'язкове поле:
Існують незначні відмінності в оформленні та форматуванні посилання Normalize_Address.
Доступність: 2.1.0
This method needs address_standardizer extension.
(address) [predirAbbrev] (streetName) [streetTypeAbbrev] [postdirAbbrev] [internal] [location] [stateAbbrev] [zip]
На даний момент стандартний формат standardaddr розширення address_standardizer є дещо багатшим за norm_addy, оскільки він розроблений для підтримки міжнародних адрес (включно з країною). Еквівалентними полями standardaddr є:
house_num,predir, name, suftype, sufdir, unit, city, state, postcode
Покращено: об'єкт norm_addy версії 2.4.0 містить додаткові поля zip4 та address_alphanumeric.
address є цілим числом: номер будинку
predirAbbrev є varchar: напрямний префікс дороги, такий як N, S, E, W тощо. Вони контролюються за допомогою таблиці direction_lookup.
streetName varchar
streetTypeAbbrev varchar скорочена версія типу вулиці: наприклад, St, Ave, Cir. Вони контролюються за допомогою таблиці street_type_lookup.
postdirAbbrev varchar скорочений напрямний суфікс дороги N, S, E, W тощо. Вони контролюються за допомогою таблиці direction_lookup.
internal varchar внутрішня адреса, така як номер квартири або номер кімнати.
location varchar зазвичай місто або адміністративна область.
stateAbbrev varchar два символи, штат США. Наприклад, MA, NY, MI. Вони контролюються таблицею state_lookup.
zip varchar 5-значний поштовий індекс. Наприклад, 02109.
parsed boolean - позначає, чи адреса була сформована в результаті процесу нормалізації. Функція normalize_address встановлює це значення на true перед поверненням адреси.
zip4 останні 4 цифри 9-значного поштового індексу. Доступність: PostGIS 2.4.0.
address_alphanumeric Повний номер вулиці, навіть якщо він містить літери, наприклад 17R. Розбір цього краще виконувати за допомогою функції Pagc_Normalize_Address. Доступність: PostGIS 2.4.0.
Приклад одного виклику
SELECT addy.*
FROM pagc_normalize_address('9000 E ROO ST STE 999, Springfield, CO') AS addy;
address | predirabbrev | streetname | streettypeabbrev | postdirabbrev | internal | location | stateabbrev | zip | parsed
---------+--------------+------------+------------------+---------------+-----------+-------------+-------------+-----+--------
9000 | E | ROO | ST | | SUITE 999 | SPRINGFIELD | CO | | tПакетний виклик. Наразі існують проблеми зі швидкістю роботи postgis_tiger_geocoder при обробці address_standardizer. Сподіваємося, що ці проблеми будуть вирішені в наступних версіях. Щоб обійти ці проблеми, якщо вам потрібна швидкість для пакетного геокодування, щоб викликати normaddy в пакетному режимі, рекомендуємо безпосередньо викликати функцію standardize_address address_standardizer, як показано нижче, що схоже на те, що ми робили в Normalize_Address, яке використовує дані, створені в Geocode.
WITH g AS (SELECT address, ROW((sa).house_num, (sa).predir, (sa).name
, (sa).suftype, (sa).sufdir, (sa).unit , (sa).city, (sa).state, (sa).postcode, true)::norm_addy As na
FROM (SELECT address, standardize_address('tiger.pagc_lex'
, 'tiger.pagc_gaz'
, 'tiger.pagc_rules', address) As sa
FROM addresses_to_geocode) As g)
SELECT address As orig, (g.na).streetname, (g.na).streettypeabbrev
FROM g;
orig | streetname | streettypeabbrev
-----------------------------------------------------+---------------+------------------
529 Main Street, Boston MA, 02129 | MAIN | ST
77 Massachusetts Avenue, Cambridge, MA 02139 | MASSACHUSETTS | AVE
25 Wizard of Oz, Walaford, KS 99912323 | WIZARD OF |
26 Capen Street, Medford, MA | CAPEN | ST
124 Mount Auburn St, Cambridge, Massachusetts 02138 | MOUNT AUBURN | ST
950 Main Street, Worcester, MA 01610 | MAIN | STPprint_Addy — За заданого об'єкта складеного типу norm_addy повертає його представлення у вигляді зручного для друку формату. Зазвичай використовується разом із нормалізацією адреси.
varchar pprint_addy(norm_addy in_addy);
За заданого об'єкта складеного типу norm_addy повертає його представлення у вигляді зручного для друку формату. Крім даних, що містяться в геокодері, ніякі інші дані не потрібні.
Зазвичай використовується разом з Normalize_Address.
Красивий вивід однієї адреси
SELECT pprint_addy(normalize_address('202 East Fremont Street, Las Vegas, Nevada 89101')) As pretty_address;
pretty_address
---------------------------------------
202 E Fremont St, Las Vegas, NV 89101
Красивий вивід таблиці адрес
SELECT address As orig, pprint_addy(normalize_address(address)) As pretty_address
FROM addresses_to_geocode;
orig | pretty_address
-----------------------------------------------------+-------------------------------------------
529 Main Street, Boston MA, 02129 | 529 Main St, Boston MA, 02129
77 Massachusetts Avenue, Cambridge, MA 02139 | 77 Massachusetts Ave, Cambridge, MA 02139
28 Capen Street, Medford, MA | 28 Capen St, Medford, MA
124 Mount Auburn St, Cambridge, Massachusetts 02138 | 124 Mount Auburn St, Cambridge, MA 02138
950 Main Street, Worcester, MA 01610 | 950 Main St, Worcester, MA 01610Reverse_Geocode — Бере геометричну точку в відомій просторовій системі координат і повертає запис, що містить масив теоретично можливих адрес і масив перехресних вулиць. Якщо include_strnum_range = true, включає діапазон вулиць у перехресні вулиці.
record Reverse_Geocode(geometry pt, boolean include_strnum_range=false, geometry[] OUT intpt, norm_addy[] OUT addy, varchar[] OUT street);
Бере геометричну точку в відомій просторовій системі координат і повертає запис, що містить масив теоретично можливих адрес і масив перехресних вулиць. Якщо include_strnum_range = true, включає діапазон вулиць у перехресні вулиці. include_strnum_range за замовчуванням має значення false, якщо не передано. Адреси сортуються залежно від того, до якої дороги точка найближча, тому перша адреса, найімовірніше, є правильною.
Чому ми говоримо "теоретичні", а не "фактичні адреси"? Дані Tiger не містять реальних адрес, а лише діапазони вулиць. Таким чином, теоретична адреса є інтерпольованою адресою, що базується на діапазонах вулиць. Наприклад, інтерполяція однієї з моїх адрес дає результат 26 Court St. і 26 Court Sq., хоча такого місця як 26 Court Sq. не існує. Це відбувається тому, що точка може знаходитися на розі двох вулиць, і тому логіка інтерполює вздовж обох вулиць. Логіка також передбачає, що адреси розташовані на рівній відстані вздовж вулиці, що, звичайно, є неправильним, оскільки муніципальна будівля може займати значну частину вулиці, а решта будівель скупчені в кінці.
Примітка: Ця функція використовує дані Tiger. Якщо ви не завантажили дані, що охоплюють регіон цієї точки, ви отримаєте запис, заповнений нульовими значеннями.
Повернені елементи запису мають такий вигляд:
intpt — масив точок: це точки центральної лінії вулиці, найближчі до вхідної точки. Кількість точок дорівнює кількості адрес.
addy — масив norm_addy (нормалізованих адрес): це масив можливих адрес, які відповідають вхідній точці. Перша в масиві — найімовірніша. Зазвичай має бути тільки одна, за винятком випадків, коли точка знаходиться на розі 2 або 3 вулиць, або точка знаходиться десь на дорозі, а не збоку.
street масив varchar: це перехресні вулиці (або вулиця) (вулиці, що перетинаються або є вулицею, на яку проектується точка).
Покращено: 2.4.1 якщо завантажено опціональний набір даних zcta5, функція reverse_geocode може визначити штат і поштовий індекс, навіть якщо дані про конкретний штат не завантажено. Докладніші відомості про завантаження даних zcta5 див. у Loader_Generate_Nation_Script.
Доступність: 2.0.0
Приклад точки на розі двох вулиць, але найближчої до однієї з них. Це приблизне місцезнаходження MIT: 77 Massachusetts Ave, Cambridge, MA 02139 Зверніть увагу, що хоча у нас немає 3 вулиць, PostgreSQL просто поверне null для записів, що перевищують нашу верхню межу, тому використовувати це безпечно. Сюди входять діапазони вулиць
SELECT pprint_addy(r.addy[1]) As st1, pprint_addy(r.addy[2]) As st2, pprint_addy(r.addy[3]) As st3,
array_to_string(r.street, ',') As cross_streets
FROM reverse_geocode(ST_GeomFromText('POINT(-71.093902 42.359446)',4269),true) As r;
result
------
st1 | st2 | st3 | cross_streets
-------------------------------------------+-----+-----+----------------------------------------------
67 Massachusetts Ave, Cambridge, MA 02139 | | | 67 - 127 Massachusetts Ave,32 - 88 Vassar StТут ми вирішили не вказувати діапазони адрес для перехресних вулиць і вибрали місце, яке знаходиться дуже близько до перехрестя двох вулиць, тому його можна знайти за двома різними адресами.
SELECT pprint_addy(r.addy[1]) As st1, pprint_addy(r.addy[2]) As st2,
pprint_addy(r.addy[3]) As st3, array_to_string(r.street, ',') As cross_str
FROM reverse_geocode(ST_GeomFromText('POINT(-71.06941 42.34225)',4269)) As r;
result
--------
st1 | st2 | st3 | cross_str
---------------------------------+---------------------------------+-----+------------------------
5 Bradford St, Boston, MA 02118 | 49 Waltham St, Boston, MA 02118 | | Waltham St
Для цього ми повторно використовуємо наш геокодований приклад з Geocode і нам потрібна тільки основна адреса і максимум 2 перехресні вулиці.
SELECT actual_addr, lon, lat, pprint_addy((rg).addy[1]) As int_addr1,
(rg).street[1] As cross1, (rg).street[2] As cross2
FROM (SELECT address As actual_addr, lon, lat,
reverse_geocode( ST_SetSRID(ST_Point(lon,lat),4326) ) As rg
FROM addresses_to_geocode WHERE rating
> -1) As foo;
actual_addr | lon | lat | int_addr1 | cross1 | cross2
-----------------------------------------------------+-----------+----------+-------------------------------------------+-----------------+------------
529 Main Street, Boston MA, 02129 | -71.07181 | 42.38359 | 527 Main St, Boston, MA 02129 | Medford St |
77 Massachusetts Avenue, Cambridge, MA 02139 | -71.09428 | 42.35988 | 77 Massachusetts Ave, Cambridge, MA 02139 | Vassar St |
26 Capen Street, Medford, MA | -71.12377 | 42.41101 | 9 Edison Ave, Medford, MA 02155 | Capen St | Tesla Ave
124 Mount Auburn St, Cambridge, Massachusetts 02138 | -71.12304 | 42.37328 | 3 University Rd, Cambridge, MA 02138 | Mount Auburn St |
950 Main Street, Worcester, MA 01610 | -71.82368 | 42.24956 | 3 Maywood St, Worcester, MA 01603 | Main St | Maywood Pl
Topology_Load_Tiger — Завантажує визначену область tiger даних у топологію PostGIS, перетворює tiger дані на просторові посилання топології та прив'язує їх до допусків точності топології.
text Topology_Load_Tiger(varchar topo_name, varchar region_type, varchar region_id);
Завантажує визначену область даних Tiger у топологію PostGIS. Поверхні, вузли та ребра перетворюються у просторову систему координат цільової топології, а точки прив'язуються до допусків цільової топології. Створені поверхні, вузли та ребра зберігають ті самі ідентифікатори, що й оригінальні поверхні, вузли та ребра даних Tiger, щоб у майбутньому набори даних можна було легше узгодити з даними Tiger. Повертає зведену інформацію про процес.
Це може бути корисно, наприклад, для перерозподілу даних, коли потрібно, щоб новостворені полігони відповідали центральним лініям вулиць і не перекривали один одного.
![]() | |
Ця функція використовує дані Tiger, а також вимагає встановлення модуля топології PostGIS. Для отримання додаткової інформації див. Chapter 9, Топологія та Section 2.2.3, “Конфігурація збірки”. Якщо ви не завантажили дані, що охоплюють область, яка вас цікавить, записи топології не будуть створені. Ця функція також не працюватиме, якщо ви не створили топологію за допомогою функцій топології. |
![]() | |
Більшість помилок перевірки топології є наслідком проблем з толерантністю, коли після перетворення точки країв не збігаються або перекриваються. Щоб виправити ситуацію, можна збільшити або зменшити точність, якщо виникають помилки перевірки топології. |
Необхідні аргументи:
topo_name Назва існуючої топології PostGIS, в яку потрібно завантажити дані.
region_type Тип обмежувальної області. Наразі підтримуються лише place та county. Планується додати ще кілька. Ця таблиця використовується для визначення меж регіону. Наприклад, tiger.place, tiger.county
region_id Це те, що TIGER називає геоїдом. Це унікальний ідентифікатор регіону в таблиці. Для місця це стовпець plcidfp у таблиці tiger.place. Для округу це стовпець cntyidfp у таблиці tiger.county
Доступність: 2.0.0
Створіть топологію для Бостона, штат Массачусетс, у системі Mass State Plane Feet (2249) з допуском 0,25 футів, а потім завантажте грані, ребра та вузли міста Бостон у форматі Tiger.
SELECT topology.CreateTopology('topo_boston', 2249, 0.25);
createtopology
--------------
15
-- 60,902 ms ~ 1 minute on windows 7 desktop running 9.1 (with 5 states tiger data loaded)
SELECT tiger.topology_load_tiger('topo_boston', 'place', '2507000');
-- topology_loader_tiger --
29722 edges holding in temporary. 11108 faces added. 1875 edges of faces added. 20576 nodes added.
19962 nodes contained in a face. 0 edge start end corrected. 31597 edges added.
-- 41 ms --
SELECT topology.TopologySummary('topo_boston');
-- topologysummary--
Topology topo_boston (15), SRID 2249, precision 0.25
20576 nodes, 31597 edges, 11109 faces, 0 topogeoms in 0 layers
-- 28,797 ms to validate yeh returned no errors --
SELECT * FROM
topology.ValidateTopology('topo_boston');
error | id1 | id2
-------------------+----------+-----------
Створіть топологію для Суффолка, штат Массачусетс, в системі координат Mass State Plane Meters (26986) з похибкою 0,25 метра, а потім завантажте грані, ребра та вузли тигрової моделі округу Суффолк.
SELECT topology.CreateTopology('topo_suffolk', 26986, 0.25);
-- this took 56,275 ms ~ 1 minute on Windows 7 32-bit with 5 states of tiger loaded
-- must have been warmed up after loading boston
SELECT tiger.topology_load_tiger('topo_suffolk', 'county', '25025');
-- topology_loader_tiger --
36003 edges holding in temporary. 13518 faces added. 2172 edges of faces added.
24761 nodes added. 24075 nodes contained in a face. 0 edge start end corrected. 38175 edges added.
-- 31 ms --
SELECT topology.TopologySummary('topo_suffolk');
-- topologysummary--
Topology topo_suffolk (14), SRID 26986, precision 0.25
24761 nodes, 38175 edges, 13519 faces, 0 topogeoms in 0 layers
-- 33,606 ms to validate --
SELECT * FROM
topology.ValidateTopology('topo_suffolk');
error | id1 | id2
-------------------+----------+-----------
coincident nodes | 81045651 | 81064553
edge crosses node | 81045651 | 85737793
edge crosses node | 81045651 | 85742215
edge crosses node | 81045651 | 620628939
edge crosses node | 81064553 | 85697815
edge crosses node | 81064553 | 85728168
edge crosses node | 81064553 | 85733413
CreateTopology, CreateTopoGeom, TopologySummary, ValidateTopology
Set_Geocode_Setting — Встановлює налаштування, що впливає на поведінку функцій геокодера.
text Set_Geocode_Setting(text setting_name, text setting_value);
Встановлює значення конкретного параметра, збереженого в таблиці tiger.geocode_settings. Параметри дозволяють вмикати та вимикати налагодження функцій. У майбутньому планується контролювати рейтинг за допомогою параметрів. Поточний список параметрів наведено в Get_Geocode_Setting.
Доступність: 2.1.0
Якщо ви запустите Geocode, коли ця функція має значення true, у журналі NOTICE буде виведено час виконання та запити.
SELECT set_geocode_setting('debug_geocode_address', 'true') As result;
result
---------
trueНижче наведено просторові агрегатні функції, які використовуються так само, як і агрегатні функції SQL, такі як sum та average.
Наведені нижче функції є віконними просторовими функціями, які використовуються так само, як і віконні функції SQL, такі як row_number(), lead() та lag(). За ними має слідувати оператор OVER().
Наведені нижче функції є функціями PostGIS, які відповідають стандарту SQL/MM 3
Наведені нижче функції та оператори є функціями/операторами PostGIS, які приймають як вхідні дані або повертають як вихідні дані об'єкт типу даних geography.
![]() | |
Функції з (T) не є вбудованими геодезичними функціями і використовують виклик ST_Transform до та з геометрії для виконання операції. Як результат, вони можуть поводитися не так, як очікується, при перетині лінії зміни дати, полюсів, а також для великих геометрій або пар геометрій, що охоплюють більше однієї зони UTM. Базове перетворення - (віддаючи перевагу UTM, азимутальному проектуванню Ламберта (північ/південь) і, в гіршому випадку, проектуванню Меркатора) |
Наведені нижче функції та оператори є функціями/операторами PostGIS, які приймають як вхідні дані або повертають як вихідні дані об'єкт типу даних raster. Перелічені в алфавітному порядку.
Наведені нижче функції є функціями PostGIS, які приймають як вхідні дані або повертають як вихідні дані набір або окремий об'єкт типу даних geometry_dump або geomval.
Наведені нижче функції є функціями PostGIS, які приймають як вхідні дані або повертають як вихідні дані сімейство просторових типів PostGIS box*. Сімейство типів box складається з box2d та box3d
Наведені нижче функції є функціями PostGIS, які не відкидають Z-індекс.
Наведені нижче функції є функціями PostGIS, які можуть використовувати CIRCULARSTRING, CURVEPOLYGON та інші типи кривої геометрії
Наведені нижче функції є функціями PostGIS, які можуть використовувати геометрії POLYHEDRALSURFACE, POLYHEDRALSURFACEM
Нижче наведено алфавітний перелік просторових функцій у PostGIS та типи просторових даних, з якими вони працюють, або відповідність стандартам OGC/SQL, яких вони намагаються дотримуватися.
означає, що функція працює з типом або підтипом вбудовано.
означає, що це працює, але з вбудованим перетворенням за допомогою cast to geometry, перетворенням у просторове посилання "best srid", а потім зворотним перетворенням. Результати можуть не відповідати очікуваним для великих областей або областей на полюсах і можуть накопичувати сміття з плаваючою комою.
означає, що функція працює з типом завдяки автоматичному перетворенню в інший тип, наприклад box3d, а не завдяки прямій підтримці типу.
означає, що функція доступна тільки якщо PostGIS скомпільовано з підтримкою SFCGAL.
The functions given below are PostGIS functions that were added or enhanced.
Functions new in PostGIS 3.6
The functions given below are PostGIS functions that were added or enhanced.
Functions new in PostGIS 3.5
Functions enhanced in PostGIS 3.5
Functions changed in PostGIS 3.5
The functions given below are PostGIS functions that were added or enhanced.
Functions new in PostGIS 3.4
Functions enhanced in PostGIS 3.4
Functions changed in PostGIS 3.4
The functions given below are PostGIS functions that were added or enhanced.
Functions new in PostGIS 3.3
Functions enhanced in PostGIS 3.3
Functions changed in PostGIS 3.3
The functions given below are PostGIS functions that were added or enhanced.
Functions new in PostGIS 3.2
Functions enhanced in PostGIS 3.2
Functions changed in PostGIS 3.2
The functions given below are PostGIS functions that were added or enhanced.
Functions new in PostGIS 3.1
Functions enhanced in PostGIS 3.1
Functions changed in PostGIS 3.1
The functions given below are PostGIS functions that were added or enhanced.
Functions new in PostGIS 3.0
Functions enhanced in PostGIS 3.0
Functions changed in PostGIS 3.0
The functions given below are PostGIS functions that were added or enhanced.
Functions new in PostGIS 2.5
Functions enhanced in PostGIS 2.5
Functions changed in PostGIS 2.5
The functions given below are PostGIS functions that were added or enhanced.
Functions new in PostGIS 2.4
Functions enhanced in PostGIS 2.4
Functions changed in PostGIS 2.4
The functions given below are PostGIS functions that were added or enhanced.
Functions new in PostGIS 2.3
Functions enhanced in PostGIS 2.3
Functions changed in PostGIS 2.3
The functions given below are PostGIS functions that were added or enhanced.
Functions new in PostGIS 2.2
Functions enhanced in PostGIS 2.2
Functions changed in PostGIS 2.2
The functions given below are PostGIS functions that were added or enhanced.
Functions new in PostGIS 2.1
Functions enhanced in PostGIS 2.1
Functions changed in PostGIS 2.1
The functions given below are PostGIS functions that were added or enhanced.
Functions new in PostGIS 2.0
Functions enhanced in PostGIS 2.0
Functions changed in PostGIS 2.0
The functions given below are PostGIS functions that were added or enhanced.
Functions new in PostGIS 1.5
The functions given below are PostGIS functions that were added or enhanced.
Functions new in PostGIS 1.4
The functions given below are PostGIS functions that were added or enhanced.
Functions new in PostGIS 1.3
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.
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):
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
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.
Make a patch file containing the differences from the master copy of the documentation. On Unix, type:
git diff doc/postgis.xml > doc.patch
Attach the patch to a new issue in bug tracker.
2026/04/14
6055, Remove rare extension priv escalation case. Reported by Sven Klemm (Tiger Data), Allistair Ishmael Hakim (allistair.sh) and Daniel Bakker
GH-850, Use quote_identifier to build tables in pgis_tablefromflatgeobuf (Ariel Mashraki)
6058, Use Pg composite_to_json() function in 19+ (Paul Ramsey)
6060, fully quality calls to helper functions (Paul Ramsey)
6026, KNN failure in rare IEEE double rounding case (Paul Ramsey)
6061, WKT parser produces incorrect error locations (Paul Ramsey)
6069, Build warnings / CI failures on K&R style, fallthroughs (Paul Ramsey)
2026/02/09
If you are upgrading postgis_topology and have topogeometry columns, make sure to run after the upgrade to fix topogeometry corruption: SELECT topology.FixCorruptTopoGeometryColumn(schema_name, table_name, feature_column) FROM topology.layer
6023, Fix robustness issue in ptarray_contains_point (Sandro Santilli)
6027, Fix RemoveUnusedPrimitives without topology in search_path (Sandro Santilli)
6019, make clean does not remove cunit generated files (Bas Couwenberg)
6020, schema qualify call in ST_MPointFromText (Paul Ramsey)
6028, crash indexing malformed empty polygon (Paul Ramsey)
GH-841, small memory leak in address_standardizer (Maxim Korotkov)
5853, Issue with topology and tiger geocoder upgrade scripts (Regina Obe, Spencer Bryson)
6032, Fix postgis_tiger_geocoder upgrade for PostgreSQL < 16 (Regina Obe)
2025/11/13
If you are upgrading postgis_topology and have topogeometry columns, make sure to run after the upgrade to fix topogeometry corruption: SELECT topology.FixCorruptTopoGeometryColumn(schema_name, table_name, feature_column) FROM topology.layer
#5978, geometry_columns needs to still parse table constraints (Paul Ramsey)
#5987, ST_GeometryN fails for non-collections (Paul Ramsey)
#5991, CircularString distance error (Paul Ramsey)
#5994, Null pointer in ST_AsGeoJsonRow (Alexander Kukushkin)
#5998, ST_Distance error on CurvePolygon (Paul Ramsey)
#5962, Consistent clipping of MULTI/POINT (Paul Ramsey)
#5998, [tiger_geocoder] [security] CVE-2022-2625, make sure tables requires by extension are owned by extension authored: Andrey Borodin (Yandex), reported by Sergey Bobrov (Kaspersky)
#5754, ST_ForcePolygonCCW reverses lines (Paul Ramsey)
#5959, #5984, Prevent histogram target overflow when analysing massive tables (Darafei Praliaskouski)
#6012, Remove memory leak from lwcircstring_from_lwpointarray (Paul Ramsey)
#6013, [tiger_geocoder] Load Tiger 2025 data (Regina Obe)
#5983, [topology] topology.FixCorruptTopoGeometryColumn to fix corruption caused by 3.6.0 upgrade (Regina Obe, Francois Bonzon)
2025/09/01
This version requires PostgreSQL 12-18beta3, GEOS 3.8 or higher, and Proj 6.1+. To take advantage of all features, GEOS 3.14+ is needed. To take advantage of all SFCGAL features, SFCGAL 2.2+ is needed.
Many thanks to our translation teams, in particular:
Teramoto Ikuhiro (Japanese Team)
Daniel Nylander (Swedish Team)
Dapeng Wang, Zuo Chenwei from HighGo (Chinese Team)
Denys Kovshun (Ukrainian Team)
#5799, make ST_TileEnvelope clips envelopes to tile plane extent (Paul Ramsey)
#5829, remove constraint checking from geometry_columns view (Paul Ramsey)
#3373, GT-255, [topology] Support for upgrading domains (Ayo Adesugba, U.S. Census Bureau)
GT-252, ST_NumGeometries/ST_GeometryN treat TIN and PolyhedralSurface as unitary geometries, use ST_NumPatches/ST_PatchN for patch access (Loïc Bartoletti)
#3110, GT-242, [topology] Support for bigint (Ayo Adesugba, U.S. Census Bureau)
#5359, #5897, GT-260 [tiger_geocoder] Use @extschema:extension@ for PG >= 16 to schema qualify dependent extensions, switch to use typmod for tiger tables (Regina Obe)
#3110, GT-242, [topology] Support for bigint (Ayo Adesugba, U.S. Census Bureau)
#5498 Drop st_approxquantile(raster, double precision), wasn't usable as it triggered is not unique error when used (Regina Obe)
GH-803, [sfcgal] ADD CG_Simplify function (Loïc Bartoletti)
GH-805, [sfcgal] Add M support for SFCGAL >= 1.5.0 (Loïc Bartoletti)
GH-801, [sfcgal] ADD CG_3DAlphaWrapping function (Jean Felder)
#5894, [topology] TotalTopologySize (Sandro Santilli)
#5890, [topology] ValidateTopologyPrecision, MakeTopologyPrecise (Sandro Santilli)
#5861, [topology] Add --drop-topology switch to pgtopo_import (Sandro Santilli)
#1247, [raster] ST_AsRasterAgg (Sandro Santilli)
#5784, GT-223 Export circ_tree_distance_tree_internal for mobilitydb use (Maxime Schoemans)
GT-228 [sfcgal] Add new functions (Scale, Translate, Rotate, Buffer 3D and Straight Skeleton Partition) from SFCGAL 2 (Loïc Bartoletti)
[raster] New GUC postgis.gdal_cpl_debug, enables GDAL debugging messages and routes them into the PostgreSQL logging system. (Paul Ramsey)
#5841, Change interrupt handling to remove use of pqsignal to support PG 18 (Paul Ramsey)
Add ST_CoverageClean to edge match and gap remove polygonal coverages (Paul Ramsey) from GEOS 3.14 (Martin Davis)
#3110, GT-242 [topology] Support for bigint (Ayo Adesugba, U.S. Census Bureau)
[raster] Add ST_ReclassExact to quickly remap values in raster (Paul Ramsey)
#5971, [tiger] Option to build --without-tiger (Regina Obe)