PostGIS è un'estensione del database object-relational PostgreSQL che consente l'archiviazione di oggetti GIS (Geographic Information Systems). PostGIS comprende il supporto per gli indici spaziali R-Tree basati su GiST, e funzioni per l'analisi e l'elaborazione di oggetti GIS.
Questo è il manuale per la versione 3.4.0dev
Questa opera è rilasciata con una licenza Creative Commons Attribution-Share Alike 3.0 License. Siete liberi di utilizzare questo materiale come volete, ma vi chiediamo di citare il progetto PostGIS come fonte e, ove possibile, di inserire un link a http://postgis.net.
PostGIS è un'estensione spaziale per il database relazionale PostgreSQL creata da Refractions Research Inc. come progetto di ricerca tecnologica sui database spaziali. Refractions è una società di consulenza su GIS e basi di dati con base a Victoria, in British Columbia, Canada, specializzata nell'integrazione dei dati e nello sviluppo di software.
PostGIS ora è un progetto della OSGeo Foundation ed è sviluppato e finanziato da molti sviluppatori ed organizzazioni FOSS4G da tutto il mondo che beneficiano in modo significativo dalla sua funzionalità.
The PostGIS project development group plans on supporting and enhancing PostGIS to better support a range of important GIS functionality in the areas of OGC and SQL/MM spatial standards, advanced topological constructs (coverages, surfaces, networks), data source for desktop user interface tools for viewing and editing GIS data, and web-based access tools.
Il comitato di coordinamento del progetto (in inglese Project Steering Commitee o PSC) coordina la direzione generale, i cicli di rilascio, la documentazione e le iniziative di divulgazione del progetto PostGIS. Inoltre il comitato fornisce supporto agli utenti, accetta e approva patch dalla comunità generale PostGIS e vota su questioni varie che coinvolgono PostGIS come l'accesso di commit per gli sviluppatori, i nuovi membri del comitato e modifiche della API.
Supporto di MVT, risoluzione bachi, migliorie nelle performance e nella stabilità, cura di GitHub, allineamento di PostGIS con i rilasci di PostgreSQL
Buildbot Maintenance, Windows production and experimental builds, documentation, alignment of PostGIS with PostgreSQL releases, X3D support, TIGER geocoder support, management functions.
Index improvements, bug fixing and geometry/geography function improvements, SFCGAL, raster, GitHub curation, and bot maintenance.
Co-founder of PostGIS project. General bug fixing, geography support, geography and geometry index support (2D, 3D, nD index and anything spatial index), underlying geometry internal structures, GEOS functionality integration and alignment with GEOS releases, alignment of PostGIS with PostgreSQL releases, loader/dumper, and Shapefile GUI loader.
Bug fixes and maintenance, buildbot maintenance, git mirror management, management functions, integration of new GEOS functionality and alignment with GEOS releases, topology support, and raster framework and low level API functions.
Miglioramenti e aggiunte alla funzione di distanza (comprese le funzioni di distanza e di relazione 3D), formato di output Tiny WKB (TWKB) (in sviluppo) e supporto generale agli utenti
Geometry clustering function additions, other geometry algorithm enhancements, GEOS enhancements and general user support
GEOS enhancements and documentation
MapBox Vector Tile and GeoBuf functions. Gogs testing and GitLab experimentation.
Geometry Processing, PostgreSQL gist, general bug fixing
Prior PSC Member. Raster development, integration with GDAL, raster loader, user support, general bug fixing, testing on various OS (Slackware, Mac, Windows, and more)
Prior PSC Member. Coordinated bug fixing and maintenance effort, spatial index selectivity and binding, loader/dumper, and Shapefile GUI Loader, integration of new and new function enhancements.
Sviluppo raster, supporto per il driver GDAL, loader
Funzioni di input e ouput XML (KML,GML)/GeoJSON, supporto 3D e correzione di bug.
Ex-membro del comitato di coordinamento. Sviluppo generale, manutenzione del sito e del buildbot, gestione dell'incubazione OSGeo
Supporto CMake per PostGIS, ha sviluppato il loader raster originale in python e le funzioni API raster di basso livello.
Ex-membro del comitato di coordinamento. Documentazione e strumenti di supporto alla documentazione, manutenzione dei buildbot, supporto avanzato per gli utenti nel newsgroup PostGIS, miglioramenti alle funzioni di manutenzione PostGIS.
Lo sviluppatore iniziale e uno dei cofondatori di PostGIS. Dave ha scritto il codice per gli oggetti lato server, il binding degli indici e molte delle funzioni analitiche lato server.
Sviluppo iniziale del loader/dumper per gli Shapefile. Attualmente rappresentante di Project Owner di PostGIS.
Continuo sviluppo e manutenzione delle funzioni di base. Supporto avanzanto per le curve. Interfaccia grafica per il loader di Shapefile.
Architect of PostGIS raster implementation. Raster overall architecture, prototyping, programming support
Sviluppo raster (principalmente funzioni analitiche di map algebra)
Alex Bodnaru | Gino Lucrezi | Matt Bretl |
Alex Mayrhofer | Greg Troxel | Matthias Bay |
Andrea Peri | Guillaume Lelarge | Maxime Guillaud |
Andreas Forø Tollefsen | Giuseppe Broccolo | Maxime van Noppen |
Andreas Neumann | Han Wang | Michael Fuhr |
Andrew Gierth | Haribabu Kommi | Mike Toews |
Anne Ghisla | Havard Tveite | Nathan Wagner |
Antoine Bajolet | IIDA Tetsushi | Nathaniel Clay |
Arthur Lesuisse | Ingvild Nystuen | Nikita Shulga |
Artur Zakirov | Jackie Leng | Norman Vine |
Barbara Phillipot | James Marca | Patricia Tozer |
Ben Jubb | Jan Katins | Rafal Magda |
Bernhard Reiter | Jason Smith | Ralph Mason |
Björn Esser | Jeff Adams | Rémi Cura |
Brian Hamlin | Jim Jones | Richard Greenwood |
Bruce Rindahl | Joe Conway | Robert Coup |
Bruno Wolff III | Jonne Savolainen | Roger Crew |
Bryce L. Nordgren | Jose Carlos Martinez Llari | Ron Mayer |
Carl Anderson | Jörg Habenicht | Sebastiaan Couwenberg |
Charlie Savage | Julien Rouhaud | Sergei Shoulbakov |
Christian Schroeder | Kashif Rasul | Sergey Fedoseev |
Christoph Berg | Klaus Foerster | Shinichi Sugiyama |
Christoph Moench-Tegeder | Kris Jurka | Shoaib Burq |
Dane Springmeyer | Laurenz Albe | Silvio Grosso |
Daryl Herzmann | Lars Roessiger | Stefan Corneliu Petrea |
Dave Fuhry | Leo Hsu | Steffen Macke |
David Garnier | Loïc Bartoletti | Stepan Kuzmin |
David Skea | Loic Dachary | Stephen Frost |
David Techer | Luca S. Percich | Steven Ottens |
Dmitry Vasilyev | Lucas C. Villa Real | Talha Rizwan |
Eduin Carrillo | Maria Arias de Reyna | Tom Glancy |
Eugene Antimirov | Marc Ducobu | Tom van Tilburg |
Even Rouault | Mark Sondheim | Vincent Mora |
Frank Warmerdam | Markus Schaber | Vincent Picavet |
George Silva | Markus Wanner | Volf Tomáš |
Gerald Fenoy | Matt Amos |
Queste sono realtà aziendali o altre istituzioni che hanno contribuito al progetto PostGIS sotto forma di tempo sviluppatore, hosting o finanziamento economico
Crowd funding campaigns are campaigns we run to get badly wanted features funded that can service a large number of people. Each campaign is specifically focused on a particular feature or set of features. Each sponsor chips in a small fraction of the needed funding and with enough people/organizations contributing, we have the funds to pay for the work that will help many. If you have an idea for a feature you think many others would be willing to co-fund, please post to the PostGIS newsgroup your thoughts and together we can make it happen.
PostGIS 2.0.0 è stata la prima release con cui abbiamo tentato questa strategia. Abbiamo utilizzato PledgeBank, realizzando due campagne di successo.
postgistopology - Oltre 10 sponsor hanno contribuito con 250 USD ciascuno per realizzare la funzione TopoGeometry e per migliorare il supporto della topologia nella versione 2.0.0. E' successo.
postgis64windows - 20 e passa sponsor hanno contribuito con 100 USD ciascuno per retribuire il lavoro necessario per risolvere varie problematiche su PostGIS per Windows a 64 bit. E' successo. Ora abbiamo una versione per PostGIS 2.0.1 disponibile con lo stack builder PostgreSQL.
The GEOS geometry operations library
The GDAL Geospatial Data Abstraction Library used to power much of the raster functionality introduced in PostGIS 2. In kind, improvements needed in GDAL to support PostGIS are contributed back to the GDAL project.
The PROJ cartographic projection library
Ultimo, ma non ultimo, il database PostgreSQL, il gigante sulle cui spalle sta PostGIS. Molta della velolcità e flessibilità di PostGIS non sarebbe possibile senza l'estensibilità, il grande query planner, l'indice GIST, e la varietà di caratteristiche SQL rese disponibili da PostgreSQL.
Questo capitolo elenca i passi necessari all'installazione di PostGIS.
Per compilare, assumendo di avere tutte le dipendenze nel percorso di ricerca:
tar xvfz postgis-3.4.0dev.tar.gz cd postgis-3.4.0dev ./configure make make install
Una volta installato PostGIS, bisogna abilitarlo individualmente nei database in cui si vuole usare.
![]() | |
Ormai molti sistemi operativi contengono pacchetti precompilati per PostgreSQL/PostGIS. In molti casi la compilazione è necessaria solamente se volete l'ultimissima versione o se siete uno dei manutentori dei pacchetti. This section includes general compilation instructions, if you are compiling for Windows etc or another OS, you may find additional more detailed help at PostGIS User contributed compile guides and PostGIS Dev Wiki. Pre-Built Packages for various OS are listed in PostGIS Pre-built Packages Se siete un utente Windows, potete reperire le versioni stabili tramite Stackbuilder o la pagina PostGIS Windows download. Inoltre potete scaricare le ultimissime versioni sperimentati per Windows, che vengono create una o due volte alla settimana, quando ci sono aggiornamenti interessanti. Potete utilizzare queste versioni per fare prove con le versioni in via di sviluppo di PostGIS |
The PostGIS module is an extension to the PostgreSQL backend server. As such, PostGIS 3.4.0dev requires full PostgreSQL server headers access in order to compile. It can be built against PostgreSQL versions 12 - 16. Earlier versions of PostgreSQL are not supported.
Refer to the PostgreSQL installation guides if you haven't already installed PostgreSQL. https://www.postgresql.org .
![]() | |
Per le funzionalità legate a GEOS, quando installate PostgresSQL è possibile che dobbiate esplicitamente linkare PostgreSQL con la libreria C++ standard: LDFLAGS=-lstdc++ ./configure [INSERITE QUI LE VOSTRE OPZIONI] Questa è una soluzione alla buona per l'interazione con finte eccezioni C++ con gli strumenti di sviluppo più datati. Se riscontrate problemi anomali (chiusura inattesa del server o casi simili), provate questo trucco. Ciò richiederà ovviamente di ricompilare PostgreSQL da zero. |
I passaggi seguenti ripercorrono la procedura per configurare e compilare il sorgente di PostGIS. Sono scritti per utenti Linux e non funzioneranno su Windows o Mac.
Retrieve the PostGIS source archive from the downloads website http://postgis.net/stuff/postgis-3.4.0dev.tar.gz
wget http://postgis.net/stuff/postgis-3.4.0dev.tar.gz tar -xvzf postgis-3.4.0dev.tar.gz cd postgis-3.4.0dev
Questo passaggio creerà una cartella denominata postgis-3.4.0dev
nella cartella di lavoro attuale.
In alternativa, potete ottenere una copia del sorgente dalla repository git https://git.osgeo.org/gitea/postgis/postgis/ .
git clone https://git.osgeo.org/gitea/postgis/postgis.git postgis cd postgis sh autogen.sh
Entrate nella cartella appena creata, postgis-3.4.0dev
, per proseguire con l'installazione.
./configure
PostGIS necessita dei seguenti requisiti per la compilazione e l'utilizzo:
Necessari
PostgreSQL 12 - 16. A complete installation of PostgreSQL (including server headers) is required. PostgreSQL is available from http://www.postgresql.org .
For a full PostgreSQL / PostGIS support matrix and PostGIS/GEOS support matrix refer to https://trac.osgeo.org/postgis/wiki/UsersWikiPostgreSQLPostGIS
Compilatore GNU C (gcc
). Per la compilazione possono essere utilizzati anche altri compilatori ANSI C, ma abbiamo riscontrato molti meno problemi nella compilazione con gcc
.
GNU Make (gmake
or make
). Per molti sistem, GNU make
è la versione di default di make. Potete controllare la versione tramite il comando make -v
. Altre versioni di make
potrebbero non elaborare il Makefile
di PostGIS in modo corretto.
Proj reprojection library. Proj 6.1 or above is required. The Proj library is used to provide coordinate reprojection support within PostGIS. Proj is available for download from https://proj.org/ .
GEOS geometry library, version 3.6 or greater, but GEOS 3.11+ is required to take full advantage of all the new functions and features. GEOS is available for download from https://libgeos.org .
LibXML2, version 2.5.x or higher. LibXML2 is currently used in some imports functions (ST_GeomFromGML and ST_GeomFromKML). LibXML2 is available for download from https://gitlab.gnome.org/GNOME/libxml2/-/releases.
JSON-C, version 0.9 or higher. JSON-C is currently used to import GeoJSON via the function ST_GeomFromGeoJson. JSON-C is available for download from https://github.com/json-c/json-c/releases/.
GDAL, version 2+ is required 3+ is preferred. This is required for raster support. https://gdal.org/download.html.
Se si compila con PostgreSQL+JIT, e' necessaria una versione di LLVM >=6 https://trac.osgeo.org/postgis/ticket/4125.
Opzionali
GDAL (pseudo optional) only if you don't want raster you can leave it out. Also make sure to enable the drivers you want to use as described in Section 3.2, “Configurare il supporto raster”.
GTK (è necessario GTK+2.0, 2.8+) serve per compilare il loader shp2pgsql-gui shape. http://www.gtk.org/ .
SFCGAL, version 1.3.1 (or higher), 1.4.1 or higher is recommended and required to be able to use all functionality. SFCGAL can be used to provide additional 2D and 3D advanced analysis functions to PostGIS cf Section 8.20, “SFCGAL Functions”. And also allow to use SFCGAL rather than GEOS for some 2D functions provided by both backends (like ST_Intersection or ST_Area, for instance). A PostgreSQL configuration variable postgis.backend
allow end user to control which backend he want to use if SFCGAL is installed (GEOS by default). Nota: SFCGAL 1.2 require at least CGAL 4.3 and Boost 1.54 (cf: https://oslandia.gitlab.io/SFCGAL/dev.html) https://gitlab.com/Oslandia/SFCGAL/.
In order to build the Section 14.1, “Address Standardizer” you will also need PCRE http://www.pcre.org (which generally is already installed on nix systems). Regex::Assemble
perl CPAN package is only needed if you want to rebuild the data encoded in parseaddress-stcities.h
. Section 14.1, “Address Standardizer” will automatically be built if it detects a PCRE library, or you pass in a valid --with-pcre-dir=/path/to/pcre
during configure.
To enable ST_AsMVT protobuf-c library 1.1.0 or higher (for usage) and the protoc-c compiler (for building) are required. Also, pkg-config is required to verify the correct minimum version of protobuf-c. See protobuf-c. By default, Postgis will use Wagyu to validate MVT polygons faster which requires a c++11 compiler. It will use CXXFLAGS and the same compiler as the PostgreSQL installation. To disable this and use GEOS instead use the --without-wagyu
during the configure step.
CUnit (CUnit
). Serve per i collaudi di regressione. http://cunit.sourceforge.net/
DocBook (xsltproc
) è necessario per creare la documentazione. Docbook è disponibile sul sito http://www.docbook.org/ .
DBLatex (dblatex
) è necessario per creare la documentazione in formato PDF. DBLatex è disponibile dal sito http://dblatex.sourceforge.net/ .
ImageMagick (convert
) viene utilizzato per generare le immagini utilizzate nella documentazione. ImageMagick è disponibile sul sito http://www.imagemagick.org/ .
Come in molte installazioni Linux, il primo passo consiste nel generare il Makefile che sarà poi utilizzato che compilare il codice sorgente. Per questo si esegue lo script da shell
./configure
Se non si specificano parametri aggiuntivi, questo comando cercherà di individuare automaticamente le componenti e le librerie necessarie per compilare il codice sorgente PostGIS sul vostro sistema. Benché questa sia la modalità di utilizzo più comune per ./configure, lo script accetta vari parametri per coloro che tengono le librerie e i programmi necessari in percorsi non standard.
La lista seguente riporta solamente i parametri usati più di frequente. Per una lista completa, utilizzate i parametri --help o --help=short.
Starting with PostGIS 3.0, the library files generated by default will no longer have the minor version as part of the file name. This means all PostGIS 3 libs will end in postgis-3
. This was done to make pg_upgrade easier, with downside that you can only install one version PostGIS 3 series in your server. To get the old behavior of file including the minor version: e.g. postgis-3.0
add this switch to your configure statement.
Questo è il percorso in cui saranno installate le librerie PostGIS e gli script SQL. Come default, questo percorso coincide con quello rilevato per l'installazione di PostgreSQL.
![]() | |
Attualmente questo parametro non funzione, dato che il pacchetto si installerà solamente nella cartella di installazione di PostgreSQL. Potete visitare la pagina http://trac.osgeo.org/postgis/ticket/635 per seguire l'evoluzione di questo bug. |
PostgreSQL fornisce una utility chiamata pg_config per consentire a estensioni quali PostGIS di individuare la cartella di installazione di PostgreSQL. Utilizzate questo parametro (--with-pgconfig=/path/to/pg_config) per specificare manualmente una particolare installazione di PostgreSQL per la quale PostGIS sarà compilato.
GDAL è una libreria necessaria per il supporto raster. Utilizzare il comando gdal-config per consentire all'installazione di individuare la cartella di installazione di GDAL, oppure utilizzare il parametro --with-gdalconfig=/path/to/gdal-config per indicare manualmente specifica installazione di GDAL con cui compilare PostGIS.
GEOS, una libreria necessaria per gestire le geometrie, fornisce una utility chiamata geos-config per consentire alla procedura di installazione di individuare la cartella di installazione di GEOS. E' possibile utilizzare questo parametro (--with-geosconfig=/path/to/geos-config) per indicare manualmente una specifica installazione di GEO da utilizzare per la compilazione.
LibXML è la libreria richiesta dai comandi GeomFromKML/GML. Se la libreria è installata, viene normalmente localizzata automaticamente, ma se non è installata, o se volete utilizzare una versione specifica, dovete rimandare PostGIS a uno specifico file di configurazione xml2-config
per consentire all'installazione di localizzare la cartella di installazione di LibXML. Utilizzate questo parametro (
>--with-xml2config=/path/to/xml2-config) per indicare manualmente il riferimento a una specifica installazione di LibXML per la compilazione di PostGIS.
Proj4 è una libreria di riproiezione richiesta da PostGIS. Utilizzate questo parametro (--with-projdir=/path/to/projdir) per indicare manualmente una specifica cartella di installazione di Proj4 per la compilazione di PostGIS.
Cartella di installazione di iconv.
JSON-C è una libreria JSON con licenza MIR utilizzata da PostGIS per supportare ST_GeomFromJSON. Utilizzare questo parametro (--with-jsondir=/path/to/jsondir) per indicare manualmente una specifica cartella di installazione che PostGIS userà per la compilazione.
PCRE is an BSD-licensed Perl Compatible Regular Expression library required by address_standardizer extension. Use this parameter (--with-pcredir=/path/to/pcredir) to manually specify a particular PCRE installation directory that PostGIS will build against.
Compilare l'interfaccia grafica per l'importazione di dati (richiede GTK+2.0). Questo passaggio creerà shp2pgsql-gui, interfaccia grafica per shp2pgsql.
Installazione del supporto raster
Disable topology support. There is no corresponding library as all logic needed for topology is in postgis-3.4.0dev library.
Normalmente PostGIS cercherà di rilevare il supporto per gettext e di utilizzarlo nella compilazione. Tuttavia, se risocontrate problemi di compatibilità che determinano interruzioni del loader, potete disabilitare il supporto con questo comando. Potete fare riferimento al ticket http://trac.osgeo.org/postgis/ticket/748 per un esempio di un caso risolto utilizzando questa particolare configurazione. NOTA: disattivanto questa opzione non vi perdete molto, dato che è utilizzata per il supporto internazionale o per le etichette nel loader, che non sono ancora ben documentate e in forma sperimentale.
By default PostGIS will not install with sfcgal support without this switch. PATH
is an optional argument that allows to specify an alternate PATH to sfcgal-config.
Disable updating postgis_revision.h to match current HEAD of the git repository.
![]() | |
Se avete ottenuto PostGIS dalla code repository , il primo passo consiste nell'eseguire lo script ./autogen.sh Questo script genererà lo script configure, che a sua volta viente utilizzato per personalizzare l'installazione di PostGIS. Se invece avete ottenuto PostGIS come file tar, non sarà necessario eseguire ./autogen.sh, dato che configure sarà già stato generato. |
Una volta creato il Makefile, compilare PostGIS è semplice come eseguire
make
L'ultima linea dei messaggi in uscita dovrebbe essere "PostGIS was built successfully. Ready to install.
"
As of PostGIS v1.4.0, all the functions have comments generated from the documentation. If you wish to install these comments into your spatial databases later, run the command which requires docbook. The postgis_comments.sql and other package comments files raster_comments.sql, topology_comments.sql are also packaged in the tar.gz distribution in the doc folder so no need to make comments if installing from the tar ball. Comments are also included as part of the CREATE EXTENSION install.
make comments
Introdotto in PostGIS 2.0. Questa opzione genera degli opuscoli riassuntivi in formato HTML, utili come riferimento speditivo o per distribuzione agli studenti. Richiede xsltproc e genererà 4 file della cartella doc: topology_cheatsheet.html
, tiger_geocoder_cheatsheet.html
, raster_cheatsheet.html
, postgis_cheatsheet.html
Ne potete scaricare alcuni già pronti sia in formato HTML che PDF dalla pagina PostGIS / PostgreSQL Study Guides
make cheatsheets
Le estensioni di PostGIS vengono compilate e installate automaticamente se state utilizzando PostgreSQL 9.1+.
Se state compilando a partire dalla repository del sorgente, dovete prima compilare le descrizioni delle funzioni. Queste vengono create se avete docbook installato. Potete anche eseguire la compilazione manualmente tramite il comando:
make comments
Creare i file dei commenti non è necessario se state compilando a partire dal file tar, dato che questi file sono inclusi nel file tar stesso.
Se state compilando per PostgreSQL 9.1, le estensioni dovrebbero essere create automaticamente nel corso del processo di make install. Se serve, potete eseguire la compilazione a partire dalle cartelle delle estensioni, o potete copiare i file se ne avete bisogno su un altro server.
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
![]() | |
|
I file delle estensioni sono sempre gli stessi a pari versione di PostGIS, a prescindere dal sistema operativo, per cui non ci sono problemi a copiare i file delle estensioni da un sistema operativo a un altro, fintanto che i file binari di PostGIS sono già installati sui vostri server.
Se volete installare le estensioni manualmente su un server separato, diverso da quello di sviluppo, dovete copiare i seguenti file dalla cartella delle estensioni nella cartella PostgreSQL / share / extension
della vostra installazione PostgreSQL, così come i file binari per la versione normale di PostGIS, se questi già non sono presenti sul server.
Questi sono i file di controllo che indicano informazioni come la versione dell'estensione da installare, se non specificata. postgis.control, postgis_topology.control
.
Tutti i file nella cartella /sql di ciascuna estensione. Da notare che quesi devono essere copiati nella cartella principale delle estensioni di PostgreSQL, share/extension extensions/postgis/sql/*.sql
, extensions/postgis_topology/sql/*.sql
Una volta eseguita questa operazione, dovreste vedere postgis
, postgis_topology
come estensioni disponibili in PgAdmin -> extensions.
Se state utilizzando psql, potete verificare l'avvenuta installazione delle estensioni tramite questa query:
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.4.0dev | 3.4.0dev address_standardizer_data_us | 3.4.0dev | 3.4.0dev postgis | 3.4.0dev | 3.4.0dev postgis_raster | 3.4.0dev | 3.4.0dev postgis_sfcgal | 3.4.0dev | postgis_tiger_geocoder | 3.4.0dev | 3.4.0dev postgis_topology | 3.4.0dev | (6 rows)
Se avete le estensioni installate nel database che state interrogando, vedrete questo fatto menzionato nella colonna installed_version
. Se non vengono riportari record nel risultato, significa che non avete alcuna estensione installata sul server. PgAdmin III 1.14+ fornirà inoltre questa informazione nella sezione extensions
dell'albero di navigazione del database e consentirà anche l'aggiornamento o la disinstallazione tramite clic del tasto destro del mouse.
Se le estensioni sono disponibili, potete installare l'estensione postgis nel database da voi scelto utilizzando l'interfaccia pgAdmin per le estensioni o eseguendo i seguenti comandi 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;
In psql you can use to see what versions you have installed and also what schema they are installed.
\connect mygisdb \x \dx postgis*
List of installed extensions -[ RECORD 1 ]------------------------------------------------- Name | postgis Version | 3.4.0dev 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.4.0dev Schema | tiger Description | PostGIS tiger geocoder and reverse geocoder -[ RECORD 4 ]------------------------------------------------- Name | postgis_topology Version | 3.4.0dev Schema | topology Description | PostGIS topology spatial types and functions
![]() | |
Per le tabelle delle estensioni |
If you installed 3.4.0dev, without using our wonderful extension system, you can change it to be extension based by running the below commands to package the functions in their respective extension. Installing using `unpackaged` was removed in PostgreSQL 13, so you are advised to switch to an extension build before upgrading to 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;
Se volete eseguire un test sul PostGIS compilato, eseguite
make check
Il comando di cui sopra eseguirà vari controlli e collaudi di regressione, utilizzando la libreria generata per un database PostgreSQL effettivo.
![]() | |
Se avete configurato PostGIS utilizzando percorsi non standard per PostgreSQL, GEOS o Proj4, potreste dover aggiungere il percorso di queste librerie nella variabile di ambiente LD_LIBRARY_PATH |
![]() | |
Attualmente il comando make check fa riferimento alle variabili di ambiente |
Se il test è positivo, l'uscita conterrà il risultato di molti test la schermata dovrebbe essere simile alla seguente (molte linee sono omesse):
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
The postgis_tiger_geocoder
and address_standardizer
extensions, currently only support the standard PostgreSQL installcheck. To test these use the below. Note: the make install is not necessary if you already did make install at root of PostGIS code folder.
For address_standardizer:
cd extensions/address_standardizer make install make installcheck
Output should look like:
============== 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. =====================
For tiger geocoder, make sure you have postgis and fuzzystrmatch extensions available in your PostgreSQL instance. The address_standardizer tests will also kick in if you built postgis with address_standardizer support:
cd extensions/postgis_tiger_geocoder make install make installcheck
output should look like:
============== 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. =====================
Per installare PostGIS, digitate
make install
Questo comando copierà i file per l'installazione di PostGIS nelle cartelle appropriate, specificate tramite il parametro di configurazione --prefix. In particolare:
I file binari del loader e del dumper vengono installati in [prefix]/bin
.
I file SQL, quali postgis.sql
, vengono installati in [prefix]/share/contrib
.
Le librerie PostGIS vengono installate in [prefix]/lib
.
Se avete eseguito il comando make comments per generare i file postgis_comments.sql
e raster_comments.sql
, installate i file SQL eseguendo
make comments-install
![]() | |
|
The address_standardizer
extension used to be a separate package that required separate download. From PostGIS 2.2 on, it is now bundled in. For more information about the address_standardize, what it does, and how to configure it for your needs, refer to Section 14.1, “Address Standardizer”.
This standardizer can be used in conjunction with the PostGIS packaged tiger geocoder extension as a replacement for the Normalize_Address discussed. To use as replacement refer to Section 2.4.2, “Using Address Standardizer Extension with Tiger geocoder”. You can also use it as a building block for your own geocoder or use it to standardize your addresses for easier compare of addresses.
The address standardizer relies on PCRE which is usually already installed on many Nix systems, but you can download the latest at: http://www.pcre.org. If during Section 2.2.3, “Configurazione”, PCRE is found, then the address standardizer extension will automatically be built. If you have a custom pcre install you want to use instead, pass to configure --with-pcredir=/path/to/pcre
where /path/to/pcre
is the root folder for your pcre include and lib directories.
For Windows users, the PostGIS 2.1+ bundle is packaged with the address_standardizer already so no need to compile and can move straight to CREATE EXTENSION
step.
Once you have installed, you can connect to your database and run the SQL:
CREATE EXTENSION address_standardizer;
The following test requires no rules, gaz, or lex tables
SELECT num, street, city, state, zip FROM parse_address('1 Devonshire Place PH301, Boston, MA 02109');
Output should be
num | street | city | state | zip -----+------------------------+--------+-------+------- 1 | Devonshire Place PH301 | Boston | MA | 02109
Perl Regex:Assemble is no longer needed for compiling address_standardizer extension since the files it generates are part of the source tree. However if you need to edit the usps-st-city-orig.txt
or usps-st-city-orig.txt usps-st-city-adds.tx
, you need to rebuild parseaddress-stcities.h
which does require Regex:Assemble.
cpan Regexp::Assemble
or if you are on Ubuntu / Debian you might need to do
sudo perl -MCPAN -e "install Regexp::Assemble"
Extras like Tiger geocoder may not be packaged in your PostGIS distribution. If you are missing the tiger geocoder extension or want a newer version than what your install comes with, then use the share/extension/postgis_tiger_geocoder.*
files from the packages in Windows Unreleased Versions section for your version of PostgreSQL. Although these packages are for windows, the postgis_tiger_geocoder extension files will work on any OS since the extension is an SQL/plpgsql only extension.
First get binaries for PostGIS 2.1+ or compile and install as usual. This should install the necessary extension files as well for tiger geocoder.
Connect to your database via psql or pgAdmin or some other tool and run the following SQL commands. Note that if you are installing in a database that already has postgis, you don't need to do the first step. If you have fuzzystrmatch
extension already installed, you don't need to do the second step either.
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;
If you already have postgis_tiger_geocoder extension installed, and just want to update to the latest run:
ALTER EXTENSION postgis UPDATE; ALTER EXTENSION postgis_tiger_geocoder UPDATE;
If you made custom entries or changes to tiger.loader_platform
and tiger.loader_variables
you may need to update these.
To confirm your install is working correctly, run this sql in your database:
SELECT na.address, na.streetname,na.streettypeabbrev, na.zip FROM normalize_address('1 Devonshire Place, Boston, MA 02109') AS na;
Which should output
address | streetname | streettypeabbrev | zip ---------+------------+------------------+------- 1 | Devonshire | Pl | 02109
Create a new record in tiger.loader_platform
table with the paths of your executables and server.
So for example to create a profile called debbie that follows sh
convention. You would do:
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';
And then edit the paths in the declare_sect column to those that fit Debbie's pg, unzip,shp2pgsql, psql, etc path locations.
If you don't edit this loader_platform
table, it will just contain common case locations of items and you'll have to edit the generated script after the script is generated.
As of PostGIS 2.4.1 the Zip code-5 digit tabulation area zcta5
load step was revised to load current zcta5 data and is part of the Loader_Generate_Nation_Script when enabled. It is turned off by default because it takes quite a bit of time to load (20 to 60 minutes), takes up quite a bit of disk space, and is not used that often.
To enable it, do the following:
UPDATE tiger.loader_lookuptables SET load = true WHERE table_name = 'zcta520';
If present the Geocode function can use it if a boundary filter is added to limit to just zips in that boundary. The Reverse_Geocode function uses it if the returned address is missing a zip, which often happens with highway reverse geocoding.
Create a folder called gisdata
on root of server or your local pc if you have a fast network connection to the server. This folder is where the tiger files will be downloaded to and processed. If you are not happy with having the folder on the root of the server, or simply want to change to a different folder for staging, then edit the field staging_fold
in the tiger.loader_variables
table.
Create a folder called temp in the gisdata
folder or wherever you designated the staging_fold
to be. This will be the folder where the loader extracts the downloaded tiger data.
Then run the Loader_Generate_Nation_Script SQL function make sure to use the name of your custom profile and copy the script to a .sh or .bat file. So for example to build the nation load:
psql -c "SELECT Loader_Generate_Nation_Script('debbie')" -d geocoder -tA > /gisdata/nation_script_load.sh
Run the generated nation load commandline scripts.
cd /gisdata sh nation_script_load.sh
After you are done running the nation script, you should have three tables in your tiger_data
schema and they should be filled with data. Confirm you do by doing the following queries from psql or pgAdmin
SELECT count(*) FROM tiger_data.county_all;
count ------- 3233 (1 row)
SELECT count(*) FROM tiger_data.state_all;
count ------- 56 (1 row)
By default the tables corresponding to bg
, tract
, tabblock20
are not loaded. These tables are not used by the geocoder but are used by folks for population statistics. If you wish to load them as part of your state loads, run the following statement to enable them.
UPDATE tiger.loader_lookuptables SET load = true WHERE load = false AND lookup_name IN('tract', 'bg', 'tabblock20');
Alternatively you can load just these tables after loading state data using the Loader_Generate_Census_Script
For each state you want to load data for, generate a state script Loader_Generate_Script.
![]() | |
DO NOT Generate the state script until you have already loaded the nation data, because the state script utilizes county list loaded by nation script. |
psql -c "SELECT Loader_Generate_Script(ARRAY['MA'], 'debbie')" -d geocoder -tA > /gisdata/ma_load.sh
Run the generated commandline scripts.
cd /gisdata sh ma_load.sh
After you are done loading all data or at a stopping point, it's a good idea to analyze all the tiger tables to update the stats (include inherited stats)
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.zip_lookup_base; vacuum (analyze, verbose) tiger.zip_state; vacuum (analyze, verbose) tiger.zip_state_loc;
One of the many complaints of folks is the address normalizer function Normalize_Address function that normalizes an address for prepping before geocoding. The normalizer is far from perfect and trying to patch its imperfectness takes a vast amount of resources. As such we have integrated with another project that has a much better address standardizer engine. To use this new address_standardizer, you compile the extension as described in Section 2.3, “Installing and Using the address standardizer” and install as an extension in your database.
Once you install this extension in the same database as you have installed postgis_tiger_geocoder
, then the Pagc_Normalize_Address can be used instead of Normalize_Address. This extension is tiger agnostic, so can be used with other data sources such as international addresses. The tiger geocoder extension does come packaged with its own custom versions of rules table ( tiger.pagc_rules
) , gaz table (tiger.pagc_gaz
), and lex table (tiger.pagc_lex
). These you can add and update to improve your standardizing experience for your own needs.
Il processo di caricamento scarica i dati per ciascuno stato richiesto dal sito del censimento, estrare i file, e li carica nelle rispettive tabelle. La tabella di ogni stato eredita le proprietà dalle tabelle definite nello schema tiger
, per cui è sufficiente eseguire le interrogazioni su queste tabelle per accedere a tutti i dati. E' altresì possibile cancellare le tabelle per un dato stato tramite lo script Drop_State_Tables_Generate_Script, qualora aveste necessità di ricaricare uno stato o se questo non vi serve più.
Per caricare i dati avrete bisogno dei seguenti strumenti:
Uno strumento per decomprimere i file zip dal sito web dei censimenti.
Per sistemi tipo Unix: l'eseguibile unzip
è di soiito già installato.
Per Windows, 7-zip è uno strumento libero di compressione/decompressione, che può essere scaricato dal sito http://www.7-zip.org/
Il programam da riga di comando shp2pgsql
, che viene installato di base quando nistallate PostGIS.
wget
è uno strumento per la copia di file da web, solitamente installato nella maggior parte dei sistemi Unix/Linux.
Se siete su Windows, potete reperire i file binari precompilati da http://gnuwin32.sourceforge.net/packages/wget.htm
If you are upgrading from tiger_2010, you'll need to first generate and run Drop_Nation_Tables_Generate_Script. Before you load any state data, you need to load the nation wide data which you do with Loader_Generate_Nation_Script. Which will generate a loader script for you. Loader_Generate_Nation_Script is a one-time step that should be done for upgrading (from a prior year tiger census data) and for new installs.
To load state data refer to Loader_Generate_Script to generate a data load script for your platform for the states you desire. Note that you can install these piecemeal. You don't have to load all the states you want all at once. You can load them as you need them.
Dopo aver caricato i dati per gli stati cui siete interessati, assicuratevi di eseguire:
SELECT install_missing_indexes();
come descritto in Install_Missing_Indexes.
Per vedere se le cose funzionano come dovrebbero, provate a eseguire la geocodifica di un indirizzo nel vostro stato utilizzando Geocode
First upgrade your postgis_tiger_geocoder extension as follows:
ALTER EXTENSION postgis_tiger_geocoder UPDATE;
Poi cancellate tutte le tabelle delle nazioni e caricate quelle nuove. Potete generare uno script per la cancellazione con il codice SQL illustrato in Drop_Nation_Tables_Generate_Script
SELECT drop_nation_tables_generate_script();
Eseguite i comandi SQL DROP che vengono generati.
Generate uno script per il caricamento di uno stato con l'istruzione SELECT come illustrato in Loader_Generate_Nation_Script
Per Windows
SELECT loader_generate_nation_script('windows');
Per unix/linux
SELECT loader_generate_nation_script('sh');
Fate riferimento a 4 per istruzioni su come eseguire lo script generato. Questo passaggio deve essere eseguito solo una volta.
![]() | |
You can have a mix of different year state tables and can upgrade each state separately. Before you upgrade a state you first need to drop the prior year state tables for that state using Drop_State_Tables_Generate_Script. |
Quando l'installazione o l'aggiornamento non vanno come previsto, diverse cose vanno controllate.
Controllate di aver installato PostgreSQL 12 o più recente, e che state compilando con il sorgente PostgreSQL nella versione corrispondente alla versione di PostgreSQL che sta girando. Si possono verificare casi di confusione quando la vostra distribuzione (Linux) ha PostgreSQL già installao, o quando avete installato PostgreSQL in precedenza e ve ne siete dimenticati. PostGIS funzionerà solo con PostgreSQL 12 o più recente, e si potrebbero ricevere messaggi di errore strani o inattesi se utilizzate una versione più vecchia. Per verificare quale versione di PostgreSQL sta girando, collegatevi al database utilizzando psql ed eseguite la seguente query:
SELECT version();
Se state utilizzando una distribuzione basata su RPM, potete verificare la presenza di pacchetti preinstallati utilizzando il comando rpm con la seguente sintassi: rpm -qa | grep postgresql
Se l'aggiornamento non funziona, assicuratevi di eseguire il ripristino in un database che abbia già PostGIS installato.
SELECT postgis_full_version();
Inoltre, verificate che configure abbia correttamente individuato il percorso e la versione di PostgreSQL, della libreria Proj4 e della libreria GEOS.
L'uscita da configure viene utilizzata per generare il file postgis_config.h
. Controllate che le variabili POSTGIS_PGSQL_VERSION
, POSTGIS_PROJ_VERSION
e POSTGIS_GEOS_VERSION
siano assegnate correttamente.
Tuning for PostGIS performance is much like tuning for any PostgreSQL workload. The only additional consideration is that geometries and rasters are usually large, so memory-related optimizations generally have more of an impact on PostGIS than other types of PostgreSQL queries.
For general details about optimizing PostgreSQL, refer to Tuning your PostgreSQL Server.
For PostgreSQL 9.4+ configuration can be set at the server level without touching postgresql.conf
or postgresql.auto.conf
by using the ALTER SYSTEM
command.
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;
In addition to the Postgres settings, PostGIS has some custom settings which are listed in Section 8.23, “Grand Unified Custom Variables (GUCs)”.
These settings are configured in postgresql.conf
:
Default: partition
This is generally used for table partitioning. The default for this is set to "partition" which is ideal for PostgreSQL 8.4 and above since it will force the planner to only analyze tables for constraint consideration if they are in an inherited hierarchy and not pay the planner penalty otherwise.
Default: ~128MB in PostgreSQL 9.6
Set to about 25% to 40% of available RAM. On windows you may not be able to set as high.
max_worker_processes This setting is only available for PostgreSQL 9.4+. For PostgreSQL 9.6+ this setting has additional importance in that it controls the max number of processes you can have for parallel queries.
Default: 8
Sets the maximum number of background processes that the system can support. This parameter can only be set at server start.
work_mem - sets the size of memory used for sort operations and complex queries
Default: 1-4MB
Adjust up for large dbs, complex queries, lots of RAM
Adjust down for many concurrent users or low RAM.
If you have lots of RAM and few developers:
SET work_mem TO '256MB';
maintenance_work_mem - the memory size used for VACUUM, CREATE INDEX, etc.
Default: 16-64MB
Generally too low - ties up I/O, locks objects while swapping memory
Recommend 32MB to 1GB on production servers w/lots of RAM, but depends on the # of concurrent users. If you have lots of RAM and few developers:
SET maintenance_work_mem TO '1GB';
max_parallel_workers_per_gather
This setting is only available for PostgreSQL 9.6+ and will only affect PostGIS 2.3+, since only PostGIS 2.3+ supports parallel queries. If set to higher than 0, then some queries such as those involving relation functions like ST_Intersects
can use multiple processes and can run more than twice as fast when doing so. If you have a lot of processors to spare, you should change the value of this to as many processors as you have. Also make sure to bump up max_worker_processes
to at least as high as this number.
Default: 0
Sets the maximum number of workers that can be started by a single Gather
node. Parallel workers are taken from the pool of processes established by max_worker_processes
. Note that the requested number of workers may not actually be available at run time. If this occurs, the plan will run with fewer workers than expected, which may be inefficient. Setting this value to 0, which is the default, disables parallel query execution.
Se hai abilitato il supporto per i raster vorrai leggere la prossima sezione per configurarlo correttamente.
A partire da PostGIS 2.1.3, per default sono disabilitati tutti i raster driver ed il supporto per i raster offline. Per ri-abilitarli, puoi dare un valore alle seguenti variabili ambientali (nell'ambiente del server): POSTGIS_GDAL_ENABLED_DRIVERS
e POSTGIS_ENABLE_OUTDB_RASTERS
.A partire da PostGIS 2.2, puoi usare l'approccio più combatibile tra varie piattaforme usando le Section 8.23, “Grand Unified Custom Variables (GUCs)” corrispondenti.
Se vuoi abilitare il supporto per i raster offline:
POSTGIS_ENABLE_OUTDB_RASTERS=1
Qualunque altro valore, o l'assenza di valore, disabilita il supporto per i raster offline (out-of-db).
Per abilitare tutti i driver GDAL disponibili nella tua installazione, valorizza la seguente variabile come segue
POSTGIS_GDAL_ENABLED_DRIVERS=ENABLE_ALL
Se vuoi abilitare solo degli specifici driver, valorizza la variabile cosí:
POSTGIS_GDAL_ENABLED_DRIVERS="GTiff PNG JPEG GIF XYZ"
![]() | |
Su Windows, non usare le virgolette |
Come settare variabili ambientali dipende dal sistema operativo. Se postgreSQL è stato installato su Ubuntu o Debian via apt-postgresql, il metodo preferito è modificare /etc/postgresql/
dove 10 si riferisce alla versione di PostgreSQL e main si riferisce al nome del cluster.10
/main
/environment
On windows, if you are running as a service, you can set via System variables which for Windows 7 you can get to by right-clicking on Computer->Properties Advanced System Settings or in explorer navigating to Control Panel\All Control Panel Items\System
. Then clicking Advanced System Settings ->Advanced->Environment Variables and adding new system variables.
Dopo aver settato le variabili ambientali, affinché le modifiche abbiano effetto dovrai far ripartire il servizio PostgreSQL.
If you are using PostgreSQL 9.1+ and have compiled and installed the extensions/postgis modules, you can turn a database into a spatial one using the EXTENSION mechanism.
Core postgis extension includes geometry, geography, spatial_ref_sys and all the functions and comments. Raster and topology are packaged as a separate extension.
Run the following SQL snippet in the database you want to enable spatially:
CREATE EXTENSION IF NOT EXISTS plpgsql; CREATE EXTENSION postgis; CREATE EXTENSION postgis_raster; -- OPTIONAL CREATE EXTENSION postgis_topology; -- OPTIONAL
![]() | |
This is generally only needed if you cannot or don't want to get PostGIS installed in the PostgreSQL extension directory (for example during testing, development or in a restricted environment). |
Adding PostGIS objects and function definitions into your database is done by loading the various sql files located in [prefix]/share/contrib
as specified during the build phase.
The core PostGIS objects (geometry and geography types, and their support functions) are in the postgis.sql
script. Raster objects are in the rtpostgis.sql
script. Topology objects are in the topology.sql
script.
For a complete set of EPSG coordinate system definition identifiers, you can also load the spatial_ref_sys.sql
definitions file and populate the spatial_ref_sys
table. This will permit you to perform ST_Transform() operations on geometries.
If you wish to add comments to the PostGIS functions, you can find them in the postgis_comments.sql
script. Comments can be viewed by simply typing \dd [function_name] from a psql terminal window.
Run the following Shell commands in your terminal:
DB=[yourdatabase] SCRIPTSDIR=`pg_config --sharedir`/contrib/postgis-3.3/ # 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
Some packaged distributions of PostGIS (in particular the Win32 installers for PostGIS >= 1.1.5) load the PostGIS functions into a template database called template_postgis
. If the template_postgis
database exists in your PostgreSQL installation then it is possible for users and/or applications to create spatially-enabled databases using a single command. Note that in both cases, the database user must have been granted the privilege to create new databases.
From the shell:
# createdb -T template_postgis my_spatial_db
From SQL:
postgres=# CREATE DATABASE my_spatial_db TEMPLATE=template_postgis
Upgrading existing spatial databases can be tricky as it requires replacement or introduction of new PostGIS object definitions.
Unfortunately not all definitions can be easily replaced in a live database, so sometimes your best bet is a dump/reload process.
PostGIS provides a SOFT UPGRADE procedure for minor or bugfix releases, and a HARD UPGRADE procedure for major releases.
Before attempting to upgrade PostGIS, it is always worth to backup your data. If you use the -Fc flag to pg_dump you will always be able to restore the dump with a HARD UPGRADE.
If you installed your database using extensions, you'll need to upgrade using the extension model as well. If you installed using the old sql script way, you are advised to switch your install to extensions because the script way is no longer supported.
If you originally installed PostGIS with extensions, then you need to upgrade using extensions as well. Doing a minor upgrade with extensions, is fairly painless.
If you are running PostGIS 3 or above, then you should use the PostGIS_Extensions_Upgrade function to upgrade to the latest version you have installed.
SELECT postgis_extensions_upgrade();
If you are running PostGIS 2.5 or lower, then do the following:
ALTER EXTENSION postgis UPDATE; SELECT postgis_extensions_upgrade(); -- This second call is needed to rebundle postgis_raster extension SELECT postgis_extensions_upgrade();
If you have multiple versions of PostGIS installed, and you don't want to upgrade to the latest, you can explicitly specify the version as follows:
ALTER EXTENSION postgis UPDATE TO "3.4.0dev"; ALTER EXTENSION postgis_topology UPDATE TO "3.4.0dev";
If you get an error notice something like:
No migration path defined for … to 3.4.0dev
Then you'll need to backup your database, create a fresh one as described in Section 3.3.1, “Spatially enable database using EXTENSION” and then restore your backup on top of this new database.
If you get a notice message like:
Version "3.4.0dev" of extension "postgis" is already installed
Then everything is already up to date and you can safely ignore it. UNLESS you're attempting to upgrade from an development version to the next (which doesn't get a new version number); in that case you can append "next" to the version string, and next time you'll need to drop the "next" suffix again:
ALTER EXTENSION postgis UPDATE TO "3.4.0devnext"; ALTER EXTENSION postgis_topology UPDATE TO "3.4.0devnext";
![]() | |
If you installed PostGIS originally without a version specified, you can often skip the reinstallation of postgis extension before restoring since the backup just has |
![]() | |
If you are upgrading PostGIS extension from a version prior to 3.0.0, you will have a new extension postgis_raster which you can safely drop, if you don't need raster support. You can drop as follows: DROP EXTENSION postgis_raster; |
This section applies only to those who installed PostGIS not using extensions. If you have extensions and try to upgrade with this approach you'll get messages like:
can't drop … because postgis extension depends on it
NOTE: if you are moving from PostGIS 1.* to PostGIS 2.* or from PostGIS 2.* prior to r7409, you cannot use this procedure but would rather need to do a HARD UPGRADE.
After compiling and installing (make install) you should find a set of *_upgrade.sql
files in the installation folders. You can list them all with:
ls `pg_config --sharedir`/contrib/postgis-3.4.0dev/*_upgrade.sql
Load them all in turn, starting from postgis_upgrade.sql
.
psql -f postgis_upgrade.sql -d your_spatial_database
The same procedure applies to raster, topology and sfcgal extensions, with upgrade files named rtpostgis_upgrade.sql
, topology_upgrade.sql
and sfcgal_upgrade.sql
respectively. If you need them:
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
You are advised to switch to an extension based install by running
psql -c "SELECT postgis_extensions_upgrade();"
![]() | |
If you can't find the |
The PostGIS_Full_Version function should inform you about the need to run this kind of upgrade using a "procs need upgrade" message.
By HARD UPGRADE we mean full dump/reload of postgis-enabled databases. You need a HARD UPGRADE when PostGIS objects' internal storage changes or when SOFT UPGRADE is not possible. The Release Notes appendix reports for each version whether you need a dump/reload (HARD UPGRADE) to upgrade.
The dump/reload process is assisted by the postgis_restore.pl script which takes care of skipping from the dump all definitions which belong to PostGIS (including old ones), allowing you to restore your schemas and data into a database with PostGIS installed without getting duplicate symbol errors or bringing forward deprecated objects.
Supplementary instructions for windows users are available at Windows Hard upgrade.
The Procedure is as follows:
Create a "custom-format" dump of the database you want to upgrade (let's call it olddb
) include binary blobs (-b) and verbose (-v) output. The user can be the owner of the db, need not be postgres super account.
pg_dump -h localhost -p 5432 -U postgres -Fc -b -v -f "/somepath/olddb.backup" olddb
Do a fresh install of PostGIS in a new database -- we'll refer to this database as newdb
. Please refer to Section 3.3.2, “Spatially enable database without using EXTENSION (discouraged)” and Section 3.3.1, “Spatially enable database using EXTENSION” for instructions on how to do this.
The spatial_ref_sys entries found in your dump will be restored, but they will not override existing ones in spatial_ref_sys. This is to ensure that fixes in the official set will be properly propagated to restored databases. If for any reason you really want your own overrides of standard entries just don't load the spatial_ref_sys.sql file when creating the new db.
If your database is really old or you know you've been using long deprecated functions in your views and functions, you might need to load legacy.sql
for all your functions and views etc. to properly come back. Only do this if _really_ needed. Consider upgrading your views and functions before dumping instead, if possible. The deprecated functions can be later removed by loading uninstall_legacy.sql
.
Restore your backup into your fresh newdb
database using postgis_restore.pl. Unexpected errors, if any, will be printed to the standard error stream by psql. Keep a log of those.
perl utils/postgis_restore.pl "/somepath/olddb.backup" | psql -h localhost -p 5432 -U postgres newdb 2> errors.txt
Errors may arise in the following cases:
Some of your views or functions make use of deprecated PostGIS objects. In order to fix this you may try loading legacy.sql
script prior to restore or you'll have to restore to a version of PostGIS which still contains those objects and try a migration again after porting your code. If the legacy.sql
way works for you, don't forget to fix your code to stop using deprecated functions and drop them loading uninstall_legacy.sql
.
Some custom records of spatial_ref_sys in dump file have an invalid SRID value. Valid SRID values are bigger than 0 and smaller than 999000. Values in the 999000.999999 range are reserved for internal use while values > 999999 can't be used at all. All your custom records with invalid SRIDs will be retained, with those > 999999 moved into the reserved range, but the spatial_ref_sys table would lose a check constraint guarding for that invariant to hold and possibly also its primary key ( when multiple invalid SRIDS get converted to the same reserved SRID value ).
In order to fix this you should copy your custom SRS to a SRID with a valid value (maybe in the 910000..910999 range), convert all your tables to the new srid (see UpdateGeometrySRID), delete the invalid entry from spatial_ref_sys and re-construct the check(s) with:
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));
If you are upgrading an old database containing french IGN cartography, you will have probably SRIDs out of range and you will see, when importing your database, issues like this :
WARNING: SRID 310642222 converted to 999175 (in reserved zone)
In this case, you can try following steps : first throw out completely the IGN from the sql which is resulting from postgis_restore.pl. So, after having run :
perl utils/postgis_restore.pl "/somepath/olddb.backup" > olddb.sql
run this command :
grep -v IGNF olddb.sql > olddb-without-IGN.sql
Create then your newdb, activate the required Postgis extensions, and insert properly the french system IGN with : this script After these operations, import your data :
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 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))
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 8, Guida a 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.23815667
The 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 15.11, “PostGIS Function Support Matrix” for compare between what is supported for Geography vs. Geometry. For a brief listing and description of Geography functions, refer to Section 15.4, “PostGIS Geography Support Functions”
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.
MULTIPOINT
s are simple if no two coordinates (POINT
s) 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) |
POLYGON
s 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 (POLYGON
s and MULTIPOLYGON
s) . 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 cannnot 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 POLYGON
s 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 LINESTRING
s 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:
An integer code that uniquely identifies the Spatial Reference System (SRS) within the database.
The name of the standard or standards body that is being cited for this reference system. For example, "EPSG" is a valid auth_name
.
The ID of the Spatial Reference System as defined by the Authority cited in the auth_name
. In the case of EPSG, this is the EPSG code.
The 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.
PostGIS 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:
The 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).
The name of the geometry column in the feature table.
The coordinate dimension (2, 3 or 4) of the column.
The 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”).
The 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.
Creates a new table and populates it from the Shapefile. This is the default mode.
Appends 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.
Drops the database table before creating a new table with the data in the Shapefile.
Only 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.
Use 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.
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.
Keep identifiers' case (column, schema and attributes). Note that attributes in Shapefile are all UPPERCASE.
Coerce all integers to standard 32-bit integers, do not create 64-bit bigints, even if the DBF header signature appears to warrant it.
Create a GiST index on the geometry column.
-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
Generate 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).
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.
Output WKT format, instead of WKB. Note that this can introduce coordinate drifts due to loss of precision.
Execute 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.
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.
NULL geometries handling policy (insert*,skip,abort)
-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.
Use geography type instead of geometry (requires lon/lat data) in WGS84 long lat (SRID=4326)
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.
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.
When 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:
This 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:
Write the output to a particular filename.
The database host to connect to.
The port to connect to on the database host.
The password to use when connecting to the database.
The username to use when connecting to the database.
In the case of tables with multiple geometry columns, the geometry column to use when writing the shape file.
Use 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.
Raw mode. Do not drop the gid
field, or escape column names.
filename
Remap 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 POINT
s, which have a dimension of 0, the boundary is the empty set. The boundary of a LINESTRING
is the two endpoints. For POLYGON
s, 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 POINT
s, the interior is the point itself. The interior of a LINESTRING
is the set of points between the endpoints. For POLYGON
s, 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 8.10.1, “Bounding Box Operators” for the full list) and the distance operators used in nearest-neighbor queries (the most common being <->; see Section 8.10.2, “Operatori” 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)
Le attuali versioni di PostgreSQL (compresa la versione 8.0) sono affette da un difetto del query optimizer riguardante le tabelle TOAST. Le tabelle TOAST sono una sorta di "spazio aggiuntivo" usato per memorizzare valori di grandi dimensioni (nel senso di dimensioni dei dati) che non possono essere salvati in normali pagine (per esempio lunghi testi, immagini o geometrie con molti vertici). Vedi la documentazione PostgreSQL sulle tabelle TOAST per maggiori informazioni).
Il problema si presenta nel caso di tabelle contenenti geometrie di grandi dimensioni ma poche righe (per esempio una tabella contenente i confini di tutti gli stati europei ad alta risoluzione). In questo caso infatti la tabella in se è di piccole dimensioni ma usa molto spazio TOAST. Nel nostro esempio la tabella conteneva circa 80 righe e utilizzava solo 3 pagine di dati, ma la tabella TOAST ne utilizzava 8225.
Ora si lanci una query che usi l'operatore && e che [MATCHES] solo poche righe. Il
Per controllare se i propri dati sono interessati da questo bug, si può usare il comando PostgreSQL "EXPLAIN ANALYZE". Per maggiori informazioni e dettagli tecnici consultare il corrispondente thread sulla mailing list di PostgreSQL: http://archives.postgresql.org/pgsql-performance/2005-02/msg00030.php
and newer thread on PostGIS https://lists.osgeo.org/pipermail/postgis-devel/2017-June/026209.html
Gli sviluppatori di PostgreSQL stanno cercando di risolvere il problema rendendo la valutazione della query indipendente dalla tabella TOAST. Per ora ci sono due possibili soluzioni alternative:
La è forzare il query planner ad usare l'indice spaziale usando il comando "SET enable_seqscan TO off;" prima di lanciare la query. Questo comando impedisce al query planner di usare lo scan sequenziale della tabella se possibile e lo forza quindi ad usare l'indice GIST. Tuttavia il comando deve essere lanciato ad ogni connessione e, per evitare di confondere il query planner in altri casi, il parametro deve essere resettato dopo l'esecuzione della query interessata con il comando "SET enable_seqscan TO on;" .
Il secondo metodo è rendere lo scan sequenziale così veloce come il query planner si aspetta che sia. Questo può essere raggiunto aggiungendo una colonna addizionale in cui salvare la bounding box di ogni geometria. Nel nostro esempio i comandi sarebbero:
SELECT AddGeometryColumn('myschema','mytable','bbox','4326','GEOMETRY','2'); UPDATE mytable SET bbox = ST_Envelope(ST_Force_2d(the_geom));
Ora la query deve essere modificata in modo da usare l'operatore && con la colonna bbox piuttosto che con la colonna geom_column:
SELECT geom_column FROM mytable WHERE bbox && ST_SetSRID('BOX3D(0 0,1 1)'::box3d,4326);
Ovviamente la colonna bbox deve essere mantenuta attuale quando si modificano o si aggiungono geometrie. La via più semplice per fare questo sarebbe con un trigger, oppure l'applicazione può essere modificata in modo da attualizzare anche la colonna bbox oppure si può lanciare l'UPDATE precedente dopo ogni modifica.
Per tabelle che vengono per lo più solo lette, e dove un singolo indice è usato dalla maggior parte delle query, PostgreSQL offre il comando CLUSTER. Questo comando riordina fisicamente le righe in modo che l'ordine corrisponda a quello dell'indice. Con questo metodo si migliorano le prestazioni per due motivi: primo, il numero delle ricerche nella tabella dei dati è ridotto drasticamente. Secondo, se i dati interessati dalla query sono concentrati in un piccolo intervallo sull'indice, il processo di mettere in cache sarà più efficiente perché le righe saranno distribuite all'interno di poche pagine. (si invita a leggere la documentazione di PostgreSQL riguardante il comando CLUSTER).
Attualmente però, PostgreSQL non permette di usare il clustering con indici GIST, perché gli indici GIST ignorano i valori nulli:
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 "the_geom" NOT NULL.
Come suggerito dal messaggio di errore, è possibile aggirare il problema aggiungendo un vincolo "NOT NULL" alla tabella:
lwgeom=# ALTER TABLE my_table ALTER COLUMN the_geom SET not null; ALTER TABLE
Ovviamente questo non funzionerà se la colonna the_geom già contiene valori nulli. Inoltre il vincolo dev'essere definito usando il comando precedente. Usare un vincolo CHECK del tipo "ALTER TABLE blubb ADD CHECK (geometry is not null);" non funzionerà.
A volte può accadere di avere dati in 3D o 4D, ma di accederli sempre usando funzioni che danno in output solo geometrie 2D come ST_AsText() oppure ST_AsBinary(). Queste funzioni processano internamente le geometrie eseguendo ST_Force2D() e questo può risultare in un peggioramento delle prestazioni significativo nel caso di geometrie di grandi dimensioni. Per evitare questo problema è consigliabile eliminare le dimensioni non utilizzate una volte e per sempre:
UPDATE mytable SET the_geom = ST_Force_2d(the_geom); VACUUM FULL ANALYZE mytable;
Se la colonna di tipo geometry è stata aggiunta usando la funzione AddGeometryColumn(), verrà creato anche un vincolo dimensionale sulla geometria. Per aggirare il vincolo sarà necessario cancellarlo. Ricorda di attualizzare il record nella tabella geometry_columns e di ricreare il vincolo successivamente.
Nel caso di grandi tabelle può essere sensato dividere l'UPDATE in porzioni più piccole, usando la clausola WHERE con la chiave primaria o un altro criterio flessibile per attualizzare solo una parte della tabella , ed eseguendo un semplice "VACUUM;" tra gli UPDATE. Questo accorgimento ridurrà drasticamente il bisogno lo spazio temporaneo sul disco. Inoltre, se la colonna geometrica contiene geometrie con diverse dimensioni, si può limitare l'UPDATE con "WHERE dimension(the_geom)>2", evitando così di riscrivere le geometrie che sono già in 2D.
The Minnesota MapServer is an internet web-mapping server which conforms to the OpenGIS Web Map Service specification.
The MapServer homepage is at http://mapserver.org.
The OpenGIS Web Map Service specification is at http://www.opengeospatial.org/standards/wms.
To use PostGIS with MapServer, you need to know how to configure MapServer, which is beyond the scope of this documentation. This section covers specific PostGIS issues and configuration details.
To use PostGIS with MapServer, you will need:
Version 0.6 or newer of PostGIS.
Version 3.5 or newer of MapServer.
MapServer accesses PostGIS/PostgreSQL data like any other PostgreSQL client, using the libpq
interface. This means that MapServer can be installed on any machine with network access to the PostGIS server, and use PostGIS as a source of data. The faster the connection between the systems, the better.
Compile and install MapServer, with whatever options you desire, including the "--with-postgis" configuration option.
In your MapServer map file, add a PostGIS layer. For example:
LAYER CONNECTIONTYPE postgis NAME "widehighways" # Connect to a remote spatial database CONNECTION "user=dbuser dbname=gisdatabase host=bigserver" PROCESSING "CLOSE_CONNECTION=DEFER" # Get the lines from the 'geom' column of the 'roads' table DATA "geom from roads using srid=4326 using unique gid" STATUS ON TYPE LINE # Of the lines in the extents, only render the wide highways FILTER "type = 'highway' and numlanes >= 4" CLASS # Make the superhighways brighter and 2 pixels wide EXPRESSION ([numlanes] >= 6) STYLE COLOR 255 22 22 WIDTH 2 END END CLASS # All the rest are darker and only 1 pixel wide EXPRESSION ([numlanes] < 6) STYLE COLOR 205 92 82 END END END
In the example above, the PostGIS-specific directives are as follows:
For PostGIS layers, this is always "postgis".
The database connection is governed by the a 'connection string' which is a standard set of keys and values like this (with the default values in <>):
user=<username> password=<password> dbname=<username> hostname=<server> port=<5432>
An empty connection string is still valid, and any of the key/value pairs can be omitted. At a minimum you will generally supply the database name and username to connect with.
The form of this parameter is "<geocolumn> from <tablename> using srid=<srid> using unique <primary key>" where the column is the spatial column to be rendered to the map, the SRID is SRID used by the column and the primary key is the table primary key (or any other uniquely-valued column with an index).
You can omit the "using srid" and "using unique" clauses and MapServer will automatically determine the correct values if possible, but at the cost of running a few extra queries on the server for each map draw.
Putting in a CLOSE_CONNECTION=DEFER if you have multiple layers reuses existing connections instead of closing them. This improves speed. Refer to for MapServer PostGIS Performance Tips for a more detailed explanation.
The filter must be a valid SQL string corresponding to the logic normally following the "WHERE" keyword in a SQL query. So, for example, to render only roads with 6 or more lanes, use a filter of "num_lanes >= 6".
In your spatial database, ensure you have spatial (GiST) indexes built for any the layers you will be drawing.
CREATE INDEX [indexname] ON [tablename] USING GIST ( [geometrycolumn] );
If you will be querying your layers using MapServer you will also need to use the "using unique" clause in your DATA statement.
MapServer requires unique identifiers for each spatial record when doing queries, and the PostGIS module of MapServer uses the unique value you specify in order to provide these unique identifiers. Using the table primary key is the best practice.
The USING
pseudo-SQL clause is used to add some information to help mapserver understand the results of more complex queries. More specifically, when either a view or a subselect is used as the source table (the thing to the right of "FROM" in a DATA
definition) it is more difficult for mapserver to automatically determine a unique identifier for each row and also the SRID for the table. The USING
clause can provide mapserver with these two pieces of information as follows:
DATA "geom FROM ( SELECT table1.geom AS geom, table1.gid AS gid, table2.data AS data FROM table1 LEFT JOIN table2 ON table1.id = table2.id ) AS new_table USING UNIQUE gid USING SRID=4326"
MapServer requires a unique id for each row in order to identify the row when doing map queries. Normally it identifies the primary key from the system tables. However, views and subselects don't automatically have an known unique column. If you want to use MapServer's query functionality, you need to ensure your view or subselect includes a uniquely valued column, and declare it with USING UNIQUE
. For example, you could explicitly select nee of the table's primary key values for this purpose, or any other column which is guaranteed to be unique for the result set.
![]() | |
"Querying a Map" is the action of clicking on a map to ask for information about the map features in that location. Don't confuse "map queries" with the SQL query in a |
PostGIS needs to know which spatial referencing system is being used by the geometries in order to return the correct data back to MapServer. Normally it is possible to find this information in the "geometry_columns" table in the PostGIS database, however, this is not possible for tables which are created on the fly such as subselects and views. So the USING SRID=
option allows the correct SRID to be specified in the DATA
definition.
Lets start with a simple example and work our way up. Consider the following MapServer layer definition:
LAYER CONNECTIONTYPE postgis NAME "roads" CONNECTION "user=theuser password=thepass dbname=thedb host=theserver" DATA "geom from roads" STATUS ON TYPE LINE CLASS STYLE COLOR 0 0 0 END END END
This layer will display all the road geometries in the roads table as black lines.
Now lets say we want to show only the highways until we get zoomed in to at least a 1:100000 scale - the next two layers will achieve this effect:
LAYER CONNECTIONTYPE postgis CONNECTION "user=theuser password=thepass dbname=thedb host=theserver" PROCESSING "CLOSE_CONNECTION=DEFER" DATA "geom from roads" MINSCALE 100000 STATUS ON TYPE LINE FILTER "road_type = 'highway'" CLASS COLOR 0 0 0 END END LAYER CONNECTIONTYPE postgis CONNECTION "user=theuser password=thepass dbname=thedb host=theserver" PROCESSING "CLOSE_CONNECTION=DEFER" DATA "geom from roads" MAXSCALE 100000 STATUS ON TYPE LINE CLASSITEM road_type CLASS EXPRESSION "highway" STYLE WIDTH 2 COLOR 255 0 0 END END CLASS STYLE COLOR 0 0 0 END END END
The first layer is used when the scale is greater than 1:100000, and displays only the roads of type "highway" as black lines. The FILTER
option causes only roads of type "highway" to be displayed.
The second layer is used when the scale is less than 1:100000, and will display highways as double-thick red lines, and other roads as regular black lines.
So, we have done a couple of interesting things using only MapServer functionality, but our DATA
SQL statement has remained simple. Suppose that the name of the road is stored in another table (for whatever reason) and we need to do a join to get it and label our roads.
LAYER CONNECTIONTYPE postgis CONNECTION "user=theuser password=thepass dbname=thedb host=theserver" DATA "geom FROM (SELECT roads.gid AS gid, roads.geom AS geom, road_names.name as name FROM roads LEFT JOIN road_names ON roads.road_name_id = road_names.road_name_id) AS named_roads USING UNIQUE gid USING SRID=4326" MAXSCALE 20000 STATUS ON TYPE ANNOTATION LABELITEM name CLASS LABEL ANGLE auto SIZE 8 COLOR 0 192 0 TYPE truetype FONT arial END END END
This annotation layer adds green labels to all the roads when the scale gets down to 1:20000 or less. It also demonstrates how to use an SQL join in a DATA
definition.
Java clients can access PostGIS "geometry" objects in the PostgreSQL database either directly as text representations or using the JDBC extension objects bundled with PostGIS. In order to use the extension objects, the "postgis.jar" file must be in your CLASSPATH along with the "postgresql.jar" JDBC driver package.
import java.sql.*; import java.util.*; import java.lang.*; import org.postgis.*; public class JavaGIS { public static void main(String[] args) { java.sql.Connection conn; try { /* * Load the JDBC driver and establish a connection. */ Class.forName("org.postgresql.Driver"); String url = "jdbc:postgresql://localhost:5432/database"; conn = DriverManager.getConnection(url, "postgres", ""); /* * Add the geometry types to the connection. Note that you * must cast the connection to the pgsql-specific connection * implementation before calling the addDataType() method. */ ((org.postgresql.PGConnection)conn).addDataType("geometry",Class.forName("org.postgis.PGgeometry")); ((org.postgresql.PGConnection)conn).addDataType("box3d",Class.forName("org.postgis.PGbox3d")); /* * Create a statement and execute a select query. */ Statement s = conn.createStatement(); ResultSet r = s.executeQuery("select geom,id from geomtable"); while( r.next() ) { /* * Retrieve the geometry as an object then cast it to the geometry type. * Print things out. */ PGgeometry geom = (PGgeometry)r.getObject(1); int id = r.getInt(2); System.out.println("Row " + id + ":"); System.out.println(geom.toString()); } s.close(); conn.close(); } catch( Exception e ) { e.printStackTrace(); } } }
The "PGgeometry" object is a wrapper object which contains a specific topological geometry object (subclasses of the abstract class "Geometry") depending on the type: Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon.
PGgeometry geom = (PGgeometry)r.getObject(1); if( geom.getType() == Geometry.POLYGON ) { Polygon pl = (Polygon)geom.getGeometry(); for( int r = 0; r < pl.numRings(); r++) { LinearRing rng = pl.getRing(r); System.out.println("Ring: " + r); for( int p = 0; p < rng.numPoints(); p++ ) { Point pt = rng.getPoint(p); System.out.println("Point: " + p); System.out.println(pt.toString()); } } }
The JavaDoc for the extension objects provides a reference for the various data accessor functions in the geometric objects.
...
Le funzioni elencate sotto sono quelle di cui un utente PostGIS avrà più probabilmente bisogno. Ci sono altre funzioni, di supporto agli oggetti PostGIS, che non sono utili all'utente comune.
![]() | |
PostGIS ha iniziato una transizione dalla namin convention esistente a una convenzione SQL-MM-centrica. Di conseguenza, molte funzioni di uso comune sono state rinominate usando il prefisso standard "spatial type" (ST). Le funzioni precedenti sono tuttora disponibili, anche se non elencate nel presente documento. Al loro posto sono presenti le funzioni aggiornate corrispondenti. Le funzioni non ST_ che mancano in questo documento sono deprecate e verranno eliminate in una futura release, quindi NON VANNO PIÙ USATE. |
Questa sezione illustra i tipi di dati di PostgreSQL che vengono installati da Postgis. Vengono illustrati anche i metodi per eseguire il cast tra diversi tipi, cosa particolarmente importante per la realizzazione di funzioni proprie.
Each data type describes its type casting behavior. A type cast converts values of one data type into another type. PostgreSQL allows defining casting behavior for custom types, along with the functions used to convert type values. Casts can have automatic behavior, which allows automatic conversion of a function argument to a type supported by the function.
Some casts have explicit behavior, which means the cast must be specified using the syntax CAST(myval As sometype)
or myval::sometype
. Explicit casting avoids the issue of ambiguous casts, which can occur when using an overloaded function which does not support a given type. For example, a function may accept a box2d or a box3d, but not a geometry. Since geometry has an automatic cast to both box types, this produces an "ambiguous function" error. To prevent the error use an explicit cast to the desired box type.
All data types can be cast to text
, so this does not need to be specified explicitly.
box2d — The type representing a 2-dimensional bounding box.
box3d è un tipo spaziale di Postgis usato per rappresentare il parallelepipedo contente una geometria o un insieme di geometrie. La funzione ST_3DExtent ritorna un oggetto box3d.
The representation contains the values xmin, ymin, xmax, ymax
. These are the minimum and maximum values of the X and Y extents.
box2d
objects have a text representation which looks like BOX(1 2,5 6)
.
box3d — The type representing a 3-dimensional bounding box.
box3d è un tipo spaziale di Postgis usato per rappresentare il parallelepipedo contente una geometria o un insieme di geometrie. La funzione ST_3DExtent ritorna un oggetto box3d.
The representation contains the values xmin, ymin, zmin, xmax, ymax, zmax
. These are the minimum and maxium values of the X, Y and Z extents.
box3d
objects have a text representation which looks like BOX3D(1 2 3,5 6 5)
.
geometry — geography è un tipo spaziale usato per rappresentare un'entità in un sistema di coordinate sferico valido per l'intero pianeta.
Il tipo di dato "geometry" è un fondamentale tipo spaziale di Postgis usato per rappresentare una entità in un sistema di coordinate euclideo.
All spatial operations on geometry use the units of the Spatial Reference System the geometry is in.
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 è un tipo spaziale usato per rappresentare un'entità in un sistema di coordinate sferico valido per l'intero pianeta.
Spatial operations on the geography type provide more accurate results by taking the ellipsoidal model into account.
AddGeometryColumn — Rimuove una colonna geometry da una tabella spaziale
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)
;
Aggiunge una colonna di tipo geometry ad una tabella già esistente. schema_name
è il nome dello schema contenente la tabella. srid
deve essere un numero intero che si riferisce a un record presente nella tabella SPATIAL_REF_SYS. type
deve essere una stringa corrispondente al tipo di geometria, per esempio 'POLYGON' oppure 'MULTILINESTRING'. La funzione produce un errore se lo schema non esiste (oppure non è visibile nel search_path attual), o la SRID specificata, il tipo di geometria o la dimensione sono invalidi.
![]() | |
Cambiamento nella versione 2.0.0: questa funzione non aggiorna più geometry_columns perché geometry_columns non è più una tabella ma una vista che estrae automaticamente le informazioni necessarie dal system catalog. Inoltre per default la funzione non crea vincoli ma usa il modificatore di tipi integrato in PostgreSQL. Per esempio: creare una colonna con tipo POINT e con SRID 4326 con questa funzione, ora è equivalente a: Cambiamento nella versione 2.0.0: il vecchio funzionamento con i vincoli può essere attivato passando alla funzione l'argomento |
![]() | |
Cambiamento in versione 2.0.0: le viste non possono più essere registrate in geometry_columns, a meno che le colonne geometry a cui fanno riferimento non siano state generate con typmod e usate senza funzioni wrapper. In questo caso la vista sarà registrata correttamente in geometry_columns perché eredita il typmod dalla colonna geometry originale. Le viste che usano funzioni che ritornano geometrie verranno registrate correttamente se il tipo delll'output della funzione verrà definito esplicitamente con la funzione CAST come typmod geometry. |
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
Miglioramento nella version 2.0.0: introdotto il parametro use_typmod. Se settato su true (o se omesso) la funzione genererà una colonna geometry basata su typmod. Se settato su "false", la funzione genererà una colonna geometry con basata su vincoli geometrici.
-- Creiamo uno schema in sui salvare i dati CREATE SCHEMA my_schema; -- Creiamo una Semplice tabella CREATE TABLE my_schema.my_spatial_table (id serial); -- La descrizione mostra una semplice tabella con un'unica colonna "id" 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) -- Aggiungiamo una colonna geometry SELECT AddGeometryColumn ('my_schema','my_spatial_table','geom',4326,'POINT',2); -- Aggiungiamo un'altra colonna geometry settando il parametro use_typmod = false, -- generando quindo una colonna geometry basata su vincoli SELECT AddGeometryColumn ('my_schema','my_spatial_table','geom_c',4326,'POINT',2, false); --Di nuovo aggiungiamo un'altra colonna geometry usando il vecchio meccanismo con vincoli Add a curvepolygon using old constraint behavior SELECT AddGeometryColumn ('my_schema','my_spatial_table','geomcp_c',4326,'CURVEPOLYGON',2, false); -- Descriviamo di nuovo la tabella con le nuove 3 colonne geometry \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) -- Le colonne geometry sono automaticamante registrate in geometry_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 — Rimuove una colonna geometry da una tabella spaziale
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)
;
Rimuove una colonna geometry da una tabella spaziale. Il campo schema_name deve corrispondere al campo f_table_schema in 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
![]() | |
Cambiamento nella versione 2.0.0: questa funzione è mantenuta per retrocompatibilità. Attualmente, essendo geometry_columns una vista basata sul system catalog, una colonna geometry può essere rimossa come qualsiasi altra colonna con |
SELECT DropGeometryColumn ('my_schema','my_spatial_table','geom'); ----RESULT output --- dropgeometrycolumn ------------------------------------------------------ my_schema.my_spatial_table.geom effectively removed. -- In PostGIS 2.0+ questo comando è equivalente al comando standard -- alter table. Ambedue i comandi rimuoveranno la colonna da geometry_columns ALTER TABLE my_schema.my_spatial_table DROP column geom;
DropGeometryTable — Rimuove una tabella e tutte le sue referenze da 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)
;
Rimuove una tabella spaziale e tutte le sue referenze da geometry_columns. Nota: utilizza la funzione PostgreSQL current_schema() se lo schema non è passato come argomento.
![]() | |
Cambiamento nella versione 2.0.0: questa funzione è mantenuta per retrocompatibilità. Attualmente, essendo geometry_columns una vista basata sul system catalog, una tabella spaziale può essere rimossa come qualsiasi altra tabella con |
Find_SRID — Returns the SRID defined for a geometry column.
integer Find_SRID(
varchar a_schema_name, varchar a_table_name, varchar a_geomfield_name)
;
Returns the integer SRID of the specified geometry column by searching through the GEOMETRY_COLUMNS table. If the geometry column has not been properly added (e.g. with the AddGeometryColumn function), this function will not work.
Populate_Geometry_Columns — Ensures geometry columns are defined with type modifiers or have appropriate spatial constraints.
text Populate_Geometry_Columns(
boolean use_typmod=true)
;
int Populate_Geometry_Columns(
oid relation_oid, boolean use_typmod=true)
;
Si accerta che le colonne geometry siano definite con typemod oppure abbiano gli appropriati vincoli spaziali e conseguentemente siano correttamente registrate nella vista geometry_columns
. Per default la funzione converte tutte le colonne geometry definite senza typemod in geometry con typemod. Per ottenere il vecchio meccanismo con i vincoli spaziali si può settare la variabile use_typmod=false
For backwards compatibility and for spatial needs such as table inheritance where each child table may have different geometry type, the old check constraint behavior is still supported. If you need the old behavior, you need to pass in the new optional argument as false use_typmod=false
. When this is done geometry columns will be created with no type modifiers but will have 3 constraints defined. In particular, this means that every geometry column belonging to a table has at least three constraints:
enforce_dims_the_geom
- assicura che tutte le geometrie hanno la stessa dimensione (vedi ST_NDims)
enforce_geotype_the_geom
- assicura che tutte le geometrie sono dello stesso tipo (vedi GeometryType)
enforce_srid_the_geom
- - assicura che tutte le geometrie hanno la stessa proiezione (vedi ST_SRID)
Se alla funzione viene passato l' oid
di una tabella, questa cerca di determinare srid, dimensione e tipo della geometria di tutte le colonne geometry della tabella, aggiungendo i vincoli se necessario. In caso di successo, una riga viene inserita nella tabella geometry_columns, altrimenti viene lanciata un'eccezione con un messaggio che descrive il problema.
Se alla funzione viene passato l'oid
di una vista, questa cerca di determinare srid, dimensione e tipo della geometria di tutte le colonne geometry della vista, inserendo le appropriate righe nella tabella geometry_columns. I vincoli spaziali non vengono controllati né definiti.
La variante senza parametri è un semplice wrapper per la variante parametrizzata, che prima svuota e poi riempie la tabella geometry_columns per ogni vista e tabella spaziale nel database, aggiungendo gli appropriate vincoli spaziali. La funzione ritorna un sommario con il numero delle colonne geometry trovate e di quelle inserite in geometry_columns
. La versione parametrizzata ritorna semplicemente il numero di righe inserite nella tabella geometry_columns
.
Disponibilità: 1.4.0
Cambiamento nella versione 2.0.0: Per default la funzione utilizza ora type modifier invece di controllare i vincoli spaziali. il meccanismo con i vincoli può essere comunque attivato passando il parametro use_typmod
e settandolo come false.
Miglioramento nelle version 2.0.0: Il parametro opzionale use_typmod
è stato introdotto per permettere di controllare se le colonne devono essere create con typmodifier oppure con i vincoli spaziali.
CREATE TABLE public.myspatial_table(gid serial, geom geometry); INSERT INTO myspatial_table(geom) VALUES(ST_GeomFromText('LINESTRING(1 2, 3 4)',4326) ); -- Il comando seguente usa typ modifiers. Per poter funzionare devono essere presenti dati nella tabella. 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) |
-- Il comando seguente modificherà le colonne geometry usando i vincoli spaziali se non sono state definite con typmod oppure non hanno già i vincoli spaziali. --Per poter funzionare devono essere presenti dati nella tabella. 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 — Updates the SRID of all features in a geometry column, and the table metadata.
text UpdateGeometrySRID(
varchar table_name, varchar column_name, integer srid)
;
text UpdateGeometrySRID(
varchar schema_name, varchar table_name, varchar column_name, integer srid)
;
text UpdateGeometrySRID(
varchar catalog_name, varchar schema_name, varchar table_name, varchar column_name, integer srid)
;
Aggiorna lo SRID di tutti i record in una colonna geometry, aggiornando anche geometry_columns e il vincolo SRID della colonna. Usa la funzione current_schema() se lo schema non è passato come argomento.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
Insert geometries into roads table with a SRID set already using EWKT format:
COPY roads (geom) FROM STDIN; SRID=4326;LINESTRING(0 0, 10 10) SRID=4326;LINESTRING(10 10, 15 0) \.
This will change the srid of the roads table to 4326 from whatever it was before:
SELECT UpdateGeometrySRID('roads','geom',4326);
The prior example is equivalent to this DDL statement:
ALTER TABLE roads ALTER COLUMN geom TYPE geometry(MULTILINESTRING, 4326) USING ST_SetSRID(geom,4326);
If you got the projection wrong (or brought it in as unknown) in load and you wanted to transform to web mercator all in one shot you can do this with DDL but there is no equivalent PostGIS management function to do so in one go.
ALTER TABLE roads ALTER COLUMN geom TYPE geometry(MULTILINESTRING, 3857) USING ST_Transform(ST_SetSRID(geom,4326),3857) ;
ST_GeomCollFromText — Creates a GeometryCollection or Multi* geometry from a set of geometries.
geometry ST_MakeLine(
geometry set geoms)
;
geometry ST_MakeLine(
geometry geom1, geometry geom2)
;
geometry ST_MakeLine(
geometry[] geoms_array)
;
Collects geometries into a geometry collection. The result is either a Multi* or a GeometryCollection, depending on whether the input geometries have the same or different types (homogeneous or heterogeneous). The input geometries are left unchanged within the collection.
Variant 1: accepts two input geometries
Variant 2: accepts an array of geometries
Variant 3: aggregate function accepting a rowset of geometries.
![]() | |
If any of the input geometries are collections (Multi* or GeometryCollection) ST_Collect returns a GeometryCollection (since that is the only type which can contain nested collections). To prevent this, use ST_Dump in a subquery to expand the input collections to their atomic elements (see example below). |
![]() | |
ST_Collect and ST_Union appear similar, but in fact operate quite differently. ST_Collect aggregates geometries into a collection without changing them in any way. ST_Union geometrically merges geometries where they overlap, and splits linestrings at intersections. It may return single geometries when it dissolves boundaries. |
Availability: 1.4.0 - ST_Collect(geomarray) was introduced. ST_Collect was enhanced to handle more geometries faster.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
Collect 2D points.
SELECT ST_AsText( ST_Collect( ST_GeomFromText('POINT(1 2)'), ST_GeomFromText('POINT(-2 3)') )); st_astext ---------- MULTIPOINT((1 2),(-2 3))
Collect 3D points.
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)
Collect curves.
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))
Using an array constructor for a subquery.
SELECT ST_Collect( ARRAY( SELECT geom FROM sometable ) );
Using an array constructor for values.
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))
ST_LineFromMultiPoint — Crea una LineString da una geometria MultiPoint.
geometry ST_LineFromMultiPoint(
geometry aMultiPoint)
;
Crea una LineString da una geometria MultiPoint.
Use ST_MakeLine to create lines from Point or LineString inputs.
This function supports 3d and will not drop the z-index.
ST_MakeEnvelope — Creates a rectangular Polygon from minimum and maximum coordinates.
geometry ST_MakeEnvelope(
double precision xmin, double precision ymin, double precision xmax, double precision ymax, integer srid=unknown)
;
Creates a rectangular Polygon from the minimum and maximum values for X and Y. Input values must be in the spatial reference system specified by the SRID. If no SRID is specified the unknown spatial reference system (SRID 0) is used.
Disponibilità: dalla versione 1.5.
Enhanced: 2.0: Ability to specify an envelope without specifying an SRID was introduced.
ST_MakeLine — Crea una LineString da una geometria Point, MultiPoint o un set di LineString
geometry ST_MakeLine(
geometry set geoms)
;
geometry ST_MakeLine(
geometry geom1, geometry geom2)
;
geometry ST_MakeLine(
geometry[] geoms_array)
;
Creates a LineString containing the points of Point, MultiPoint, or LineString geometries. Other geometry types cause an error.
Variant 1: accepts two input geometries
Variant 2: accepts an array of geometries
Variant 3: aggregate function accepting a rowset of geometries. To ensure the order of the input geometries use ORDER BY
in the function call, or a subquery with an ORDER BY
clause.
Repeated nodes at the beginning of input LineStrings are collapsed to a single point. Repeated points in Point and MultiPoint inputs are not collapsed. ST_RemoveRepeatedPoints can be used to collapse repeated points from the output LineString.
This function supports 3d and will not drop the z-index.
Availability: 2.3.0 - Support for MultiPoint input elements was introduced
Availability: 2.0.0 - Support for LineString input elements was introduced
Availability: 1.4.0 - ST_MakeLine(geomarray) was introduced. ST_MakeLine aggregate functions was enhanced to handle more points faster.
Create a line composed of two points.
SELECT ST_MakeLine(ARRAY(SELECT ST_Centroid(the_geom) FROM visit_locations ORDER BY visit_time)); --Making a 3d line with 3 3-d points 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)
Crea una BOX3D definita dalle geometrie dei punti 3d dati.
SELECT ST_AsEWKT( ST_MakeLine(ST_MakePoint(1,2,3), ST_MakePoint(3,4,5) )); st_asewkt ------------------------- LINESTRING(1 2 3,3 4 5)
Create a line from two disjoint 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)
Create a line from an array formed by a subquery with ordering.
SELECT ST_MakeLine( ARRAY( SELECT ST_Centroid(geom) FROM visit_locations ORDER BY visit_time) );
Create a 3D line from an array of 3D points
SELECT ST_MakeLine(ARRAY(SELECT ST_Centroid(the_geom) FROM visit_locations ORDER BY visit_time)); --Making a 3d line with 3 3-d points 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)
This example queries time-based sequences of GPS points from a set of tracks and creates one record for each track. The result geometries are LineStrings composed of the GPS track points in the order of travel.
Using aggregate ORDER BY
provides a correctly-ordered LineString.
SELECT gps.track_id, ST_MakeLine(gps.geom ORDER BY gps_time) As geom FROM gps_points As gps GROUP BY track_id;
Prior to PostgreSQL 9, ordering in a subquery can be used. However, sometimes the query plan may not respect the order of the subquery.
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_MakePoint — Creates a 2D, 3DZ or 4D Point.
geometry ST_Point(
float x_lon, float y_lat)
;
geometry ST_MakePointM(
float x, float y, float m)
;
geometry ST_MakePoint(
double precision x, double precision y, double precision z, double precision m)
;
Crea una BOX2D definita dalle geometrie dei punti dati.
Use ST_MakePointM to make points with XYM coordinates.
While not OGC-compliant, ST_MakePoint
is faster and more precise than ST_GeomFromText and ST_PointFromText. It is also easier to use for numeric coordinate values.
![]() | |
For geodetic coordinates, |
This function supports 3d and will not drop the z-index.
--Return point with unknown SRID SELECT ST_MakePoint(-71.1043443253471, 42.3150676015829); --Return point marked as WGS 84 long lat SELECT ST_SetSRID(ST_MakePoint(-71.1043443253471, 42.3150676015829),4326); --Return 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_MakePointM — Creates a Point from X, Y and M values.
geometry ST_MakePointM(
float x, float y, float m)
;
Creates a point with X, Y and M (measure) coordinates.
Use ST_MakePoint to make points with XY, XYZ, or XYZM coordinates.
![]() | |
For geodetic coordinates, |
Create point with unknown SRID.
SELECT ST_AsEWKT( ST_MakePointM(-71.1043443253471, 42.3150676015829, 10) ); st_asewkt ----------------------------------------------- POINTM(-71.1043443253471 42.3150676015829 10)
Create point with a measure in the WGS 84 geodetic coordinate system.
SELECT ST_AsEWKT( ST_SetSRID( ST_MakePointM(-71.104, 42.315, 10), 4326)); st_asewkt --------------------------------------------------------- SRID=4326;POINTM(-71.104 42.315 10)
Get measure of created point.
SELECT ST_M( ST_MakePointM(-71.104, 42.315, 10) ); result ------- 10
ST_MakePolygon — Creates a Polygon from a shell and optional list of holes.
geometry ST_MakePolygon(
geometry linestring)
;
geometry ST_MakePolygon(
geometry outerlinestring, geometry[] interiorlinestrings)
;
Creates a Polygon formed by the given shell and optional array of holes. Input geometries must be closed LineStrings (rings).
Variant 1: Accepts one shell LineString.
Variant 2: Accepts a shell LineString and an array of inner (hole) LineStrings. A geometry array can be constructed using the PostgreSQL array_agg(), ARRAY[] or ARRAY() constructs.
![]() | |
This function does not accept MultiLineStrings. Use ST_LineMerge to generate a LineString, or ST_Dump to extract LineStrings. |
This function supports 3d and will not drop the z-index.
Create a Polygon from a 2D LineString.
SELECT ST_MLineFromText('MULTILINESTRING((1 2, 3 4), (4 5, 6 7))');
Create a Polygon from an open LineString, using ST_StartPoint and ST_AddPoint to close it.
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;
Create a Polygon from a 3D LineString
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))
Create a Polygon from a LineString with measures
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))
Create a donut Polygon with an extra hole
SELECT ST_MakePolygon( ST_ExteriorRing(ST_Buffer(foo.line,10)), ARRAY[ST_Translate(foo.line,1,1), ST_ExteriorRing(ST_Buffer(ST_MakePoint(20,20),1)) ] ) FROM (SELECT ST_ExteriorRing(ST_Buffer(ST_MakePoint(10,10),10,10)) As line ) As foo;
Create a set of province boundaries with holes representing lakes. The input is a table of province Polygons/MultiPolygons and a table of water linestrings. Lines forming lakes are determined by using ST_IsClosed. The province linework is extracted by using ST_Boundary. As required by ST_MakePolygon
, the boundary is forced to be a single LineString by using ST_LineMerge. (However, note that if a province has more than one region or has islands this will produce an invalid polygon.) Using a LEFT JOIN ensures all provinces are included even if they have no lakes.
![]() | |
The CASE construct is used because passing a null array into ST_MakePolygon results in a NULL return value. |
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;
Another technique is to utilize a correlated subquery and the ARRAY() constructor that converts a row set to an array.
SELECT p.gid, p.province_name, CASE WHEN ST_Accum(w.the_geom) IS NULL THEN p.the_geom ELSE ST_MakePolygon(ST_LineMerge(ST_Boundary(p.the_geom)), ST_Accum(w.the_geom)) END FROM provinces p LEFT JOIN waterlines w ON (ST_Within(w.the_geom, p.the_geom) AND ST_IsClosed(w.the_geom)) GROUP BY p.gid, p.province_name, p.the_geom; -- Stesso esempio di cui sopra, ma con una sottoquery correlata -- e la funzione PostgreSQL ARRAY() che converte il set di record in un vettore SELECT p.gid, p.province_name, CASE WHEN EXISTS(SELECT w.the_geom FROM waterlines w WHERE ST_Within(w.the_geom, p.the_geom) AND ST_IsClosed(w.the_geom)) THEN ST_MakePolygon(ST_LineMerge(ST_Boundary(p.the_geom)), ARRAY(SELECT w.the_geom FROM waterlines w WHERE ST_Within(w.the_geom, p.the_geom) AND ST_IsClosed(w.the_geom))) ELSE p.the_geom END As the_geom FROM provinces p;
ST_Point — Creates a Point with X, Y and SRID values.
geometry ST_Point(
float x_lon, float y_lat)
;
geometry ST_MakePointM(
float x, float y, float m)
;
Returns a Point with the given X and Y coordinate values. This is the SQL-MM equivalent for ST_MakePoint that takes just X and Y.
![]() | |
For geodetic coordinates, |
Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID to mark the srid on the geometry.
This method implements the SQL/MM specification. SQL-MM 3: 6.1.2
SELECT ST_Point( -71.104, 42.315);
SELECT ST_SetSRID(ST_Point( -71.104, 42.315),4326);
New in 3.2.0: With SRID specified
SELECT ST_Point( -71.104, 42.315, 4326);
Pre-PostGIS 3.2 syntax
SELECT CAST( ST_SetSRID(ST_Point( -71.104, 42.315), 4326) AS geography);
3.2 and on you can include the srid
SELECT CAST( ST_Point( -71.104, 42.315, 4326) AS geography);
PostgreSQL also provides the ::
short-hand for casting
SELECT ST_Point( -71.104, 42.315, 4326)::geography;
If the point coordinates are not in a geodetic coordinate system (such as WGS84), then they must be reprojected before casting to a geography. In this example a point in Pennsylvania State Plane feet (SRID 2273) is projected to WGS84 (SRID 4326).
SELECT CAST(ST_SetSRID(ST_Point(-71.1043443253471, 42.3150676015829),4326) As geography);
ST_Point — Creates a Point with X, Y, Z and SRID values.
geometry ST_MakePoint(
double precision x, double precision y, double precision z, double precision m)
;
Returns an Point with the given X, Y and Z coordinate values, and optionally an SRID number.
Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID to mark the srid on the geometry.
ST_Point — Creates a Point with X, Y, M and SRID values.
geometry ST_PointM(
float x, float y, float m, integer srid=unknown)
;
Returns an Point with the given X, Y and M coordinate values, and optionally an SRID number.
Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID to mark the srid on the geometry.
ST_Point — Creates a Point with X, Y, Z, M and SRID values.
geometry ST_MakeEnvelope(
double precision xmin, double precision ymin, double precision xmax, double precision ymax, integer srid=unknown)
;
Returns an Point with the given X, Y, Z and M coordinate values, and optionally an SRID number.
Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID to mark the srid on the geometry.
ST_Polygon — Creates a Polygon from a LineString with a specified SRID.
geometry ST_Polygon(
geometry aLineString, integer srid)
;
Returns a polygon built from the given LineString and sets the spatial reference system from the srid
.
ST_Polygon is similar to ST_MakePolygon Variant 1 with the addition of setting the SRID.
![]() | |
This function does not accept MultiLineStrings. Use ST_LineMerge to generate a LineString, or ST_Dump to extract 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.
Create a 2D polygon.
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))
Create a 3D polygon.
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_MakeEnvelope — Creates a rectangular Polygon in Web Mercator (SRID:3857) using the XYZ tile system.
geometry ST_MakePoint(
double precision x, double precision y, double precision z, double precision m)
;
Creates a rectangular Polygon giving the extent of a tile in the XYZ tile system. The tile is specifed by the zoom level Z and the XY index of the tile in the grid at that level. Can be used to define the tile bounds required by ST_AsMVTGeom to convert geometry into the MVT tile coordinate space.
By default, the tile envelope is in the Web Mercator coordinate system (SRID:3857) using the standard range of the Web Mercator system (-20037508.342789, 20037508.342789). This is the most common coordinate system used for MVT tiles. The optional bounds
parameter can be used to generate tiles in any coordinate system. It is a geometry that has the SRID and extent of the "Zoom Level zero" square within which the XYZ tile system is inscribed.
The optional margin
parameter can be used to expand a tile by the given percentage. E.g. margin=0.125
expands the tile by 12.5%, which is equivalent to buffer=512 when the tile extent size is 4096, as used in ST_AsMVTGeom. This is useful to create a tile buffer to include data lying outside of the tile's visible area, but whose existence affects the tile rendering. For example, a city name (a point) could be near an edge of a tile, so its label should be rendered on two tiles, even though the point is located in the visible area of just one tile. Using expanded tiles in a query will include the city point in both tiles. Use a negative value to shrink the tile instead. Values less than -0.5 are prohibited because that would eliminate the tile completely. Do not specify a margin when using with ST_AsMVTGeom
. See the example for ST_AsMVT.
Miglioramento nella versione: 2.0.0 introdotto opzionale parametro SRID.
Disponibilità: dalla versione 1.5.
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 — Returns a set of hexagons and cell indices that completely cover the bounds of the geometry argument.
geometry ST_Point(
float x_lon, float y_lat)
;
Starts with the concept of a hexagon tiling of the plane. (Not a hexagon tiling of the globe, this is not the H3 tiling scheme.) For a given planar SRS, and a given edge size, starting at the origin of the SRS, there is one unique hexagonal tiling of the plane, Tiling(SRS, Size). This function answers the question: what hexagons in a given Tiling(SRS, Size) overlap with a given bounds.
The SRS for the output hexagons is the SRS provided by the bounds geometry.
Doubling or tripling the edge size of the hexagon generates a new parent tiling that fits with the origin tiling. Unfortunately, it is not possible to generate parent hexagon tilings that the child tiles perfectly fit inside.
Disponibilità: dalla versione 1.5.
To do a point summary against a hexagonal tiling, generate a hexagon grid using the extent of the points as the bounds, then spatially join to that grid.
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;
If we generate a set of hexagons for each polygon boundary and filter out those that do not intersect their hexagons, we end up with a tiling for each polygon.
Tiling states results in a hexagon coverage of each state, and multiple hexagons overlapping at the borders between states.
![]() | |
The LATERAL keyword is implied for set-returning functions when referring to a prior table in the FROM list. So CROSS JOIN LATERAL, CROSS JOIN, or just plain , are equivalent constructs for this example. |
SELECT admin1.gid, hex.geom FROM admin1 CROSS JOIN ST_HexagonGrid(100000, admin1.geom) AS hex WHERE adm0_a3 = 'USA' AND ST_Intersects(admin1.geom, hex.geom)
ST_Hexagon — Returns a single hexagon, using the provided edge size and cell coordinate within the hexagon grid space.
geometry ST_MakePoint(
double precision x, double precision y, double precision z, double precision m)
;
Uses the same hexagon tiling concept as ST_HexagonGrid, but generates just one hexagon at the desired cell coordinate. Optionally, can adjust origin coordinate of the tiling, the default origin is at 0,0.
Hexagons are generated with no SRID set, so use ST_SetSRID to set the SRID to the one you expect.
Disponibilità: dalla versione 1.5.
ST_SquareGrid — Returns a set of grid squares and cell indices that completely cover the bounds of the geometry argument.
geometry ST_Point(
float x_lon, float y_lat)
;
Starts with the concept of a square tiling of the plane. For a given planar SRS, and a given edge size, starting at the origin of the SRS, there is one unique square tiling of the plane, Tiling(SRS, Size). This function answers the question: what grids in a given Tiling(SRS, Size) overlap with a given bounds.
The SRS for the output squares is the SRS provided by the bounds geometry.
Doubling or edge size of the square generates a new parent tiling that perfectly fits with the original tiling. Standard web map tilings in mercator are just powers-of-two square grids in the mercator plane.
Disponibilità: dalla versione 1.5.
The grid will fill the whole bounds of the country, so if you want just squares that touch the country you will have to filter afterwards with ST_Intersects.
WITH grid AS ( SELECT (ST_SquareGrid(1, ST_Transform(geom,4326))).* FROM admin0 WHERE name = 'Canada' ) SELEcT ST_AsText(geom) FROM grid
To do a point summary against a square tiling, generate a square grid using the extent of the points as the bounds, then spatially join to that grid. Note the estimated extent might be off from actual extent, so be cautious and at very least make sure you've analyzed your table.
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
This yields the same result as the first example but will be slower for a large number of points
SELECT COUNT(*), squares.geom FROM pointtable AS pts INNER JOIN ST_SquareGrid( 1000, pts.geom ) AS squares ON ST_Intersects(pts.geom, squares.geom) GROUP BY squares.geom
ST_Square — Returns a single square, using the provided edge size and cell coordinate within the square grid space.
geometry ST_MakePoint(
double precision x, double precision y, double precision z, double precision m)
;
Uses the same square tiling concept as ST_SquareGrid, but generates just one square at the desired cell coordinate. Optionally, can adjust origin coordinate of the tiling, the default origin is at 0,0.
Squares are generated with no SRID set, so use ST_SetSRID to set the SRID to the one you expect.
Disponibilità: dalla versione 1.5.
ST_Letters — Returns the input letters rendered as geometry with a default start position at the origin and default text height of 100.
geometry ST_Letters(
text letters, json font)
;
Uses a built-in font to render out a string as a multipolygon geometry. The default text height is 100.0, the distance from the bottom of a descender to the top of a capital. The default start position places the start of the baseline at the origin. Over-riding the font involves passing in a json map, with a character as the key, and base64 encoded TWKB for the font shape, with the fonts having a height of 1000 units from the bottom of the descenders to the tops of the capitals.
The text is generated at the origin by default, so to reposition and resize the text, first apply the ST_Scale
function and then apply the ST_Translate
function.
Disponibilità: dalla versione 1.5.
geometry_dump
rows for the components of a geometry.geometry_dump
rows for the coordinates in a geometry.geometry_dump
rows for the segments in a geometry.geometry_dump
rows for the exterior and interior rings of a Polygon.TRUE
se il punto iniziale e quello finale di LINESTRING
coincidono. Per le superfici poliedriche indica una superficie chiusa (volumetrica). GeometryType — Restituisce il tipo di geometria per il valore ST_Geometry.
text GeometryType(
geometry geomA)
;
Restituisce il tipo di geometria come stringa. Per esempio: 'LINESTRING', 'POLYGON', 'MULTIPOINT', ecc.
OGC SPEC s2.1.1.1 - Returns the name of the instantiable subtype of Geometry of which this Geometry instance is a member. The name of the instantiable subtype of Geometry is returned as a string.
![]() | |
Questa funzione indica anche se la geometria è misurata, restituendo una stringa nella forma 'POINTM'. |
Migliorato: Nella 2.0.0 è stato introdotto il supporto per le superfici poliedriche, i triangoli e i 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 — Restituisce il tipo di geometria per il valore ST_Geometry.
geometry ST_Boundary(
geometry geomA)
;
Returns the closure of the combinatorial boundary of this Geometry. The combinatorial boundary is defined as described in section 3.12.3.2 of the OGC SPEC. Because the result of this function is a closure, and hence topologically closed, the resulting boundary can be represented using representational geometry primitives as discussed in the OGC SPEC, section 3.12.2.
Eseguito dal modulo GEOS
![]() | |
Prma della 2.0.0, questa funzione dava un'eccezione se usata con |
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.
Enhanced: 2.1.0 support for Triangle was introduced
Changed: 3.2.0 support for TIN, does not use geos, does not linearize curves
![]() Linestring with boundary points overlaid
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))
| ![]() polygon holes with boundary multilinestring
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 — Returns the diagonal of a geometry's bounding box.
geometry ST_BoundingDiagonal(
geometry geom, boolean fits=false)
;
Returns the diagonal of the supplied geometry's bounding box as a LineString. The diagonal is a 2-point LineString with the minimum values of each dimension in its start point and the maximum values in its end point. If the input geometry is empty, the diagonal line is a LINESTRING EMPTY.
The optional fits
parameter specifies if the best fit is needed. If false, the diagonal of a somewhat larger bounding box can be accepted (which is faster to compute for geometries with many vertices). In either case, the bounding box of the returned diagonal line always covers the input geometry.
The returned geometry retains the SRID and dimensionality (Z and M presence) of the input geometry.
![]() | |
In degenerate cases (i.e. a single vertex in input) the returned linestring will be formally invalid (no interior). The result is still topologically valid. |
Disponibilità: 2.2.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_CoordDim — Restituisce la dimensione delle coordinate di una geometrie.
integer ST_CoordDim(
geometry geomA)
;
Restituisce la dimensione delle coordinate del valore della ST_Geometry.
This is the MM compliant alias name for 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).
ST_Dimension — Restituisce la dimensione topologica di una geometria.
integer ST_Dimension(
geometry g)
;
La dimensione inerente a questo oggetto Geometry, che deve essere minore o uguale alla dimensione delle coordinate. La specifica OGC s2.1.1.1 restituisce 0 per POINT
, 1 per LINESTRING
, 2 per POLYGON
, e la maggiore fra le dimensioni dei componenti di una GEOMETRYCOLLECTION
. Se la geometria è sconosciuta (vuota), viene restituito il valore NULL.
This method implements the SQL/MM specification. SQL-MM 3: 5.1.2
Miglioramento: nella versione 2.0.0 è stato introdotto il supporto per le superfici poliedriche e i TIN. Non viene più generata un'eccezione se viene data una geometria vuota.
![]() | |
Prima della 2.0.0, questa funzione dava un'eccezione se usata con una geometria vuota. |
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
ST_Dump — Returns a set of geometry_dump
rows for the components of a geometry.
geometry ST_Envelope(
geometry g1)
;
A set-returning function (SRF) that extracts the components of a geometry. It returns a set of geometry_dump rows, each containing a geometry (geom
field) and an array of integers (path
field).
For an atomic geometry type (POINT,LINESTRING,POLYGON) a single record is returned with an empty path
array and the input geometry as geom
. For a collection or multi-geometry a record is returned for each of the collection components, and the path
denotes the position of the component inside the collection.
ST_Dump is useful for expanding geometries. It is the inverse of a ST_GeomCollFromText / GROUP BY, in that it creates new rows. For example it can be use to expand MULTIPOLYGONS into POLYGONS.
Migliorato: Nella 2.0.0 è stato introdotto il supporto per le superfici poliedriche, i triangoli e i TIN.
Availability: PostGIS 1.0.0RC1. Requires PostgreSQL 7.3 or higher.
![]() | |
Prior to 1.3.4, this function crashes if used with geometries that contain CURVES. This is fixed in 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_NumPoints — Returns a set of geometry_dump
rows for the coordinates in a geometry.
geometry ST_StartPoint(
geometry geomA)
;
A set-returning function (SRF) that extracts the coordinates (vertices) of a geometry. It returns a set of geometry_dump rows, each containing a geometry (geom
field) and an array of integers (path
field).
the geom
field POINT
s represent the coordinates of the supplied geometry.
the path
field (an integer[]
) is an index enumerating the coordinate positions in the elements of the supplied geometry. The indices are 1-based. For example, for a LINESTRING
the paths are {i}
where i
is the nth
coordinate in the LINESTRING
. For a POLYGON
the paths are {i,j}
where i
is the ring number (1 is outer; inner rings follow) and j
is the coordinate position in the ring.
To obtain a single geometry containing the coordinates use ST_Points.
Enhanced: 2.1.0 Faster speed. Reimplemented as native-C.
Migliorato: Nella 2.0.0 è stato introdotto il supporto per le superfici poliedriche, i triangoli e i TIN.
Disponibilità: 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_NumPoints — Returns a set of geometry_dump
rows for the segments in a geometry.
geometry ST_StartPoint(
geometry geomA)
;
A set-returning function (SRF) that extracts the segments of a geometry. It returns a set of geometry_dump rows, each containing a geometry (geom
field) and an array of integers (path
field).
the geom
field LINESTRING
s represent the segments of the supplied geometry.
the path
field (an integer[]
) is an index enumerating the segment start point positions in the elements of the supplied geometry. The indices are 1-based. For example, for a LINESTRING
the paths are {i}
where i
is the nth
segment start point in the LINESTRING
. For a POLYGON
the paths are {i,j}
where i
is the ring number (1 is outer; inner rings follow) and j
is the segment start point position in the ring.
Disponibilità: 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_NRings — Returns a set of geometry_dump
rows for the exterior and interior rings of a Polygon.
geometry ST_ExteriorRing(
geometry a_polygon)
;
A set-returning function (SRF) that extracts the rings of a polygon. It returns a set of geometry_dump rows, each containing a geometry (geom
field) and an array of integers (path
field).
The geom
field contains each ring as a POLYGON. The path
field is an integer array of length 1 containing the polygon ring index. The exterior ring (shell) has index 0. The interior rings (holes) have indices of 1 and higher.
![]() | |
Non funzionerà per i MULTIPOLYGON. Da utilizzare assieme a ST_Dump per i MULTIPOLYGON |
Availability: PostGIS 1.1.3. Requires PostgreSQL 7.3 or higher.
This function supports 3d and will not drop the z-index.
General form of query.
SELECT polyTable.field1, polyTable.field1, (ST_DumpRings(polyTable.geom)).geom As geom FROM polyTable;
A polygon with a single hole.
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 — Returns the last point of a LineString or CircularLineString.
geometry ST_Envelope(
geometry g1)
;
Restituisce l'ultimo punto di una geometria LINESTRING
come POINT
o NULL
se il parametro di input non è una LINESTRING
.
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
![]() | |
Modifica: La versione 2.0.0 non funziona più con geometrie singole di stringhe multilinea. Nelle versioni precedenti di PostGIS una stringa multilinea con una sola linea avrebbe funzionato tranquillamente con questa funzione, restituendo il punto di inizio. Nella versione 2.0.0 la funzione restituisce NULL come per qualsiasi altra stringa multilinea. Il comportamento precedente non era documentato, ma le persone che presumevano di avere i dati memorizzati come LINESTRING potrebbero trovare che questi ora restituiscono il valore NULL. |
End point of a LineString
postgis=# SELECT ST_AsText(ST_EndPoint('LINESTRING(1 1, 2 2, 3 3)'::geometry)); st_astext ------------ POINT(3 3)
End point of a non-LineString is NULL
SELECT ST_EndPoint('POINT(1 1)'::geometry) IS NULL AS is_null; is_null ---------- t
End point of a 3D LineString
--3d endpoint SELECT ST_AsEWKT(ST_EndPoint('LINESTRING(1 1 2, 1 2 3, 0 0 5)')); st_asewkt -------------- POINT(0 0 5)
End point of a 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 — Returns a geometry representing the bounding box of a geometry.
geometry ST_Envelope(
geometry g1)
;
Returns the double-precision (float8) minimum bounding box for the supplied geometry, as a geometry. The polygon is defined by the corner points of the bounding box ((MINX
, MINY
), (MINX
, MAXY
), (MAXX
, MAXY
), (MAXX
, MINY
), (MINX
, MINY
)). (PostGIS will add a ZMIN
/ZMAX
coordinate as well).
I casi degeneri (linee verticali, punti) restituiranno una geometria di dimensione inferiore al POLYGON
, cioè POINT
o LINESTRING
.
Disponibilità: il comportamento nella 1.5.0 è stato cambiato per dare in uscita numeri in precisione doppia anziche 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;
Envelope of a point and linestring.
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 — Returns a LineString representing the exterior ring of a Polygon.
geometry ST_ExteriorRing(
geometry a_polygon)
;
Restituisce una LINESTRING che rappresenta l'anello esterno per una geometria POLYGON
. Restituisce NULL se la geometria non è un poligono. Non funziona con MULTIPOLYGON
![]() | |
Non funzionerà per i MULTIPOLYGON. Da utilizzare assieme a ST_Dump per i MULTIPOLYGON |
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.
--Se avete una tabella di poligoni: SELECT gid, ST_ExteriorRing(the_geom) AS ering FROM sometable; --Se avete una tabella MULTIPOLYGON --e volete riottenere un MULTILINESTRING composto dagli anelli esteriori mposed of the exterior rings of each polygon SELECT gid, ST_Collect(ST_ExteriorRing(the_geom)) AS erings FROM (SELECT gid, (ST_Dump(the_geom)).geom As the_geom FROM sometable) As foo GROUP BY gid; --Esempio 3d 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 — Restituisce il tipo di geometria per il valore ST_Geometry.
geometry ST_GeometryN(
geometry geomA, integer n)
;
Restituisce la geometria numero N (a partire da 1) se la geometria è una GEOMETRYCOLLECTION, (MULTI)POINT, (MULTI)LINESTRING, MULTICURVE o (MULTI)POLYGON, POLYHEDRALSURFACE. Altrimenti restituisce il valore NULL.
![]() | |
L'indice parte da 1, come per le specifiche OGC a partire dalla versione 0.8.0. Le precedenti versioni invece implementavano un indice a partire da zero. |
![]() | |
Se volete estrarre tutte le geometria, ST_Dump è più efficiente e funziona anche nel caso di geometrie singole. |
Migliorato: Nella 2.0.0 è stato introdotto il supporto per le superfici poliedriche, i triangoli e i TIN.
Changed: 2.0.0 Prior versions would return NULL for singular geometries. This was changed to return the geometry for ST_GeometryN(..,1) case.
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 — Restituisce il tipo di geometria per il valore ST_Geometry.
text ST_GeometryType(
geometry g1)
;
Restituisce il tipo di geometria come stringa. P. es.: 'ST_LineString', 'ST_Polygon','ST_MultiPolygon' ecc. Questa funzione differisce da GeometryType(geometry) per il prefisso ST che viene restituito, così come per il fatto che non indica se la geometria è misurata.
Miglioramento: nella versione 2.0.0 è stato introdotto il supporto per le superfici poliedriche.
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)')); --risultato ST_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 ST_PolyhedralSurface
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 ST_PolyhedralSurface
SELECT 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 — Tests if a geometry contains a circular arc
boolean ST_IsEmpty(
geometry geomA)
;
Restituisce TRUE se la geometria è una geometrycollection, un poligono o un punto vuoto, ecc.
Disponibilità: 2.0
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
ST_InteriorRingN — Returns the Nth interior ring (hole) of a Polygon.
geometry ST_InteriorRingN(
geometry a_polygon, integer n)
;
Restituisce una LINESTRING che rappresenta l'anello esterno per una geometria POLYGON
. Restituisce NULL se la geometria non è un poligono. Non funziona con MULTIPOLYGON
![]() | |
Non funzionerà per i MULTIPOLYGON. Da utilizzare assieme a ST_Dump per i MULTIPOLYGON |
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.
ST_IsClosed — Restituisce TRUE
se il punto iniziale e quello finale di LINESTRING
coincidono. Per le superfici poliedriche indica una superficie chiusa (volumetrica).
boolean ST_IsClosed(
geometry g)
;
Restituisce TRUE
se il punto iniziale e quello finale di LINESTRING
coincidono. Per le superfici poliedriche indicase la superficie è un'area (aperta) o un volume (chiusa).
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 definisce il risultato di |
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
Miglioramento: nella versione 2.0.0 è stato introdotto il supporto per le superfici poliedriche.
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 — Restituisce TRUE se la geometria è una geometrycollection, un poligono o un punto vuoto, ecc.
boolean ST_IsCollection(
geometry g)
;
Restituisce TRUE
se il tipo di geometria è uno tra:
GEOMETRYCOLLECTION
MULTI{POINT,POLYGON,LINESTRING,CURVE,SURFACE}
COMPOUNDCURVE
![]() | |
Questa funzione analizza il tipo di geometria. Significa che restituirà |
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 — Tests if a geometry is empty.
boolean ST_IsEmpty(
geometry geomA)
;
Restituisce TRUE se la Geometry è una geometria vuota. Se è TRUE, allora questa Geometry rappresenta una geometria vuota (una collezione, un poligono, un punto, ecc.)
![]() | |
SQL-MM definisce il risultato di ST_IsEmpty(NULL) come 0, mentre PostGIS restituisce 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
![]() | |
Changed: 2.0.0 In prior versions of PostGIS ST_GeomFromText('GEOMETRYCOLLECTION(EMPTY)') was allowed. This is now illegal in PostGIS 2.0.0 to better conform with SQL/MM standards |
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 — Tests if Polygons have exterior rings oriented counter-clockwise and interior rings oriented clockwise.
boolean ST_IsPolygonCCW (
geometry geom )
;
Returns true if all polygonal components of the input geometry use a counter-clockwise orientation for their exterior ring, and a clockwise direction for all interior rings.
Returns true if the geometry has no polygonal components.
![]() | |
Closed linestrings are not considered polygonal components, so you would still get a true return by passing a single closed linestring no matter its orientation. |
![]() | |
If a polygonal geometry does not use reversed orientation for interior rings (i.e., if one or more interior rings are oriented in the same direction as an exterior ring) then both ST_IsPolygonCW and ST_IsPolygonCCW will return false. |
Disponibilità: 2.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_IsPolygonCW — Tests if Polygons have exterior rings oriented clockwise and interior rings oriented counter-clockwise.
boolean ST_IsPolygonCW (
geometry geom )
;
Returns true if all polygonal components of the input geometry use a clockwise orientation for their exterior ring, and a counter-clockwise direction for all interior rings.
Returns true if the geometry has no polygonal components.
![]() | |
Closed linestrings are not considered polygonal components, so you would still get a true return by passing a single closed linestring no matter its orientation. |
![]() | |
If a polygonal geometry does not use reversed orientation for interior rings (i.e., if one or more interior rings are oriented in the same direction as an exterior ring) then both ST_IsPolygonCW and ST_IsPolygonCCW will return false. |
Disponibilità: 2.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_IsRing — Tests if a LineString is closed and simple.
boolean ST_IsRing(
geometry g)
;
Restituisce TRUE
se questa LINESTRING
è sia ST_IsClosed (ST_StartPoint(
g
)~=
ST_Endpoint(
) che ST_IsSimple (non interseca se stessa).g
)
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. 2.1.5.1
This method implements the SQL/MM specification. SQL-MM 3: 7.1.6
![]() | |
SQL-MM defines the result of |
SELECT ST_IsRing(the_geom), ST_IsClosed(the_geom), ST_IsSimple(the_geom) FROM (SELECT 'LINESTRING(0 0, 0 1, 1 1, 1 0, 0 0)'::geometry AS the_geom) AS foo; st_isring | st_isclosed | st_issimple -----------+-------------+------------- t | t | t (1 row) SELECT ST_IsRing(the_geom), ST_IsClosed(the_geom), ST_IsSimple(the_geom) FROM (SELECT 'LINESTRING(0 0, 0 1, 1 0, 1 1, 0 0)'::geometry AS the_geom) AS foo; st_isring | st_isclosed | st_issimple -----------+-------------+------------- f | t | f (1 row)
ST_IsSimple — Tests if a geometry has no points of self-intersection or self-tangency.
boolean ST_IsSimple(
geometry geomA)
;
Returns true if this Geometry has no anomalous geometric points, such as self-intersection or self-tangency. For more information on the OGC's definition of geometry simplicity and validity, refer to "Ensuring OpenGIS compliancy of geometries"
![]() | |
SQL-MM defines the result of ST_IsSimple(NULL) to be 0, while PostGIS returns 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.
ST_M — Returns the M coordinate of a Point.
float ST_M(
geometry a_point)
;
Restituisce la coordinata M del punto, o NULL se non disponibile. L'input deve essere un punto.
![]() | |
This is not (yet) part of the OGC spec, but is listed here to complete the point coordinate extractor function list. |
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.
ST_MemSize — Restituisce il tipo di geometria per il valore ST_Geometry.
integer ST_NRings(
geometry geomA)
;
Restituisce il tipo di geometria per il valore ST_Geometry.
This complements the PostgreSQL built-in database object functions pg_column_size, pg_size_pretty, pg_relation_size, pg_total_relation_size.
![]() | |
pg_relation_size which gives the byte size of a table may return byte size lower than ST_MemSize. This is because pg_relation_size does not add toasted table contribution and large geometries are stored in TOAST tables. pg_total_relation_size - includes, the table, the toasted tables, and the indexes. pg_column_size returns how much space a geometry would take in a column considering compression, so may be lower than ST_MemSize |
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Changed: 2.2.0 name changed to ST_MemSize to follow naming convention.
--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 — Restituisce la dimensione delle coordinate di una geometria.
integer ST_NDims(
geometry g1)
;
Returns the coordinate dimension of the geometry. PostGIS supports 2 - (x,y) , 3 - (x,y,z) or 2D with measure - x,y,m, and 4 - 3D with measure space x,y,z,m
This function supports 3d and will not drop the z-index.
ST_NPoints — Returns the number of points (vertices) in a geometry.
integer ST_NPoints(
geometry g1)
;
Return the number of points in a geometry. Works for all geometries.
Miglioramento: nella versione 2.0.0 è stato introdotto il supporto per le superfici poliedriche.
![]() | |
Prior to 1.3.4, this function crashes if used with geometries that contain CURVES. This is fixed in 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.
ST_NRings — Returns the number of rings in a polygonal geometry.
integer ST_NRings(
geometry geomA)
;
If the geometry is a polygon or multi-polygon returns the number of rings. Unlike NumInteriorRings, it counts the outer rings as well.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
ST_NumGeometries — Restituisce TRUE se la geometria è una geometrycollection, un poligono o un punto vuoto, ecc.
integer ST_NumGeometries(
geometry geom)
;
Returns the number of Geometries. If geometry is a GEOMETRYCOLLECTION (or MULTI*) return the number of geometries, for single geometries will return 1, otherwise return NULL.
Migliorato: Nella 2.0.0 è stato introdotto il supporto per le superfici poliedriche, i triangoli e i TIN.
Changed: 2.0.0 In prior versions this would return NULL if the geometry was not a collection/MULTI type. 2.0.0+ now returns 1 for single geometries e.g 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 — Returns the number of interior rings (holes) of a Polygon.
integer ST_NumInteriorRings(
geometry a_polygon)
;
Return the number of interior rings of a polygon geometry. Return NULL if the geometry is not a polygon.
This method implements the SQL/MM specification. SQL-MM 3: 8.2.5
Changed: 2.0.0 - in prior versions it would allow passing a MULTIPOLYGON, returning the number of interior rings of first 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 — Returns the number of interior rings (holes) of a Polygon. Aias for ST_NumInteriorRings
integer ST_NumInteriorRing(
geometry a_polygon)
;
ST_NumPatches — Return the number of faces on a Polyhedral Surface. Will return null for non-polyhedral geometries.
integer ST_NumPatches(
geometry g1)
;
Return the number of faces on a Polyhedral Surface. Will return null for non-polyhedral geometries. This is an alias for ST_NumGeometries to support MM naming. Faster to use ST_NumGeometries if you don't care about MM convention.
Disponibilità: 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 — Returns the number of points in a LineString or CircularString.
integer ST_NumPoints(
geometry g1)
;
Return the number of points in an ST_LineString or ST_CircularString value. Prior to 1.4 only works with linestrings as the specs state. From 1.4 forward this is an alias for ST_NPoints which returns number of vertexes for not just linestrings. Consider using ST_NPoints instead which is multi-purpose and works with many geometry types.
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
ST_PatchN — Restituisce il tipo di geometria per il valore ST_Geometry.
geometry ST_PatchN(
geometry geomA, integer n)
;
Returns the 1-based Nth geometry (face) if the geometry is a POLYHEDRALSURFACE or POLYHEDRALSURFACEM. Otherwise, returns NULL. This returns the same answer as ST_GeometryN for PolyhedralSurfaces. Using ST_GeometryN is faster.
![]() | |
L'indice parte da 1. |
![]() | |
Se volete estrarre tutte le geometria, ST_Dump è più efficiente e funziona anche nel caso di geometrie singole. |
Disponibilità: 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_PointN — Returns the Nth point in the first LineString or circular LineString in a geometry.
geometry ST_PointN(
geometry a_linestring, integer n)
;
Return the Nth point in a single linestring or circular linestring in the geometry. Negative values are counted backwards from the end of the LineString, so that -1 is the last point. Returns NULL if there is no linestring in the geometry.
![]() | |
Index is 1-based as for OGC specs since version 0.8.0. Backward indexing (negative index) is not in OGC Previous versions implemented this as 0-based instead. |
![]() | |
If you want to get the Nth point of each LineString in a MultiLineString, use in conjunction with 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
![]() | |
Changed: 2.0.0 no longer works with single geometry multilinestrings. In older versions of PostGIS -- a single line multilinestring would work happily with this function and return the start point. In 2.0.0 it just returns NULL like any other multilinestring. Changed: 2.3.0 : negative indexing available (-1 is last point) |
-- 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 — Restituisce un MultiPoint contenente le coordinate di una geometria.
geometry ST_Points(
geometry geom )
;
Returns a MultiPoint containing all the coordinates of a geometry. Duplicate points are preserved, including the start and end points of ring geometries. (If desired, duplicate points can be removed by calling ST_RemoveRepeatedPoints on the result).
To obtain information about the position of each coordinate in the parent geometry use ST_NumPoints.
M and Z coordinates are preserved if present.
This method supports Circular Strings and Curves
This function supports 3d and will not drop the z-index.
Availability: 2.3.0
ST_StartPoint — Returns the first point of a LineString.
geometry ST_StartPoint(
geometry geomA)
;
Returns the first point of a LINESTRING
or CIRCULARLINESTRING
geometry as a POINT
. Returns NULL
if the input is not a LINESTRING
or 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
![]() | |
Enhanced: 3.2.0 returns a point for all geometries. Prior behavior returns NULLs if input was not a LineString. Modifica: La versione 2.0.0 non funziona più con geometrie singole di stringhe multilinea. Nelle versioni precedenti di PostGIS una stringa multilinea con una sola linea avrebbe funzionato tranquillamente con questa funzione, restituendo il punto di inizio. Nella versione 2.0.0 la funzione restituisce NULL come per qualsiasi altra stringa multilinea. Il comportamento precedente non era documentato, ma le persone che presumevano di avere i dati memorizzati come LINESTRING potrebbero trovare che questi ora restituiscono il valore NULL. |
Start point of a LineString
SELECT ST_AsText(ST_StartPoint('LINESTRING(0 1, 0 2)'::geometry)); st_astext ------------ POINT(0 1)
Start point of a non-LineString is NULL
SELECT ST_StartPoint('POINT(0 1)'::geometry) IS NULL AS is_null; is_null ---------- t
Start point of a 3D LineString
SELECT ST_AsEWKT(ST_StartPoint('LINESTRING(0 1 1, 0 2 2)'::geometry)); st_asewkt ------------ POINT(0 1 1)
Start point of a 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 — Returns a text summary of the contents of a geometry.
text ST_Summary(
geometry g)
;
text ST_Summary(
geography g)
;
Restituisce il tipo di geometria per il valore ST_Geometry.
Flags shown square brackets after the geometry type have the following meaning:
M: has M coordinate
Z: has Z coordinate
B: has a cached bounding box
G: is geodetic (geography)
S: has spatial reference system
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Availability: 1.2.2
Enhanced: 2.0.0 added support for geography
Enhanced: 2.1.0 S flag to denote if has a known spatial reference system
Enhanced: 2.2.0 Added support for TIN and Curves
=# 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 — Returns the X coordinate of a Point.
float ST_X(
geometry a_point)
;
Restituisce la coordinata X del punto, o NULL se non disponibile. L'input deve essere un punto.
![]() | |
To get the minimum and maximum X value of geometry coordinates use the functions ST_XMin and ST_XMax. |
This method implements the SQL/MM specification. SQL-MM 3: 6.1.3
This function supports 3d and will not drop the z-index.
ST_Y — Returns the Y coordinate of a Point.
float ST_Y(
geometry a_point)
;
Restituisce la coordinata Y del punto, o NULL se non disponibile. L'input deve essere un punto.
![]() | |
To get the minimum and maximum Y value of geometry coordinates use the functions ST_YMin and ST_YMax. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3: 6.1.4
This function supports 3d and will not drop the z-index.
ST_Z — Returns the Z coordinate of a Point.
float ST_Z(
geometry a_point)
;
Restituisce la coordinata Z del punto, o NULL se non disponibile. L'input deve essere un punto.
![]() | |
To get the minimum and maximum Z value of geometry coordinates use the functions ST_ZMin and ST_ZMax. |
This method implements the SQL/MM specification.
This function supports 3d and will not drop the z-index.
ST_Zmflag — Restituisce un codice indicante le dimensioni ZM di una geometria.
smallint ST_Zmflag(
geometry geomA)
;
Restituisce un codice indicante le dimensioni ZM di una geometria.
Values are: 0 = 2D, 1 = 3D-M, 2 = 3D-Z, 3 = 4D.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
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_AddPoint — Add a point to a LineString.
geometry ST_AddPoint(
geometry linestring, geometry point)
;
geometry ST_AddPoint(
geometry linestring, geometry point, integer position = -1)
;
Adds a point to a LineString before the index position
(using a 0-based index). If the position
parameter is omitted or is -1 the point is appended to the end of the LineString.
Disponibilità: 1.1.0
This function supports 3d and will not drop the z-index.
Add a point to the end of a 3D line
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)
Guarantee all lines in a table are closed by adding the start point of each line to the end of the line only for those that are not closed.
UPDATE sometable SET geom = ST_AddPoint(geom, ST_StartPoint(geom)) FROM sometable WHERE ST_IsClosed(geom) = false;
ST_CollectionExtract — Given a geometry collection, returns a multi-geometry containing only elements of a specified type.
geometry ST_CollectionExtract(
geometry collection)
;
geometry ST_CollectionExtract(
geometry collection, integer type)
;
Given a geometry collection, returns a homogeneous multi-geometry.
If the type
is not specified, returns a multi-geometry containing only geometries of the highest dimension. So polygons are preferred over lines, which are preferred over points.
If the type
is specified, returns a multi-geometry containing only that type. If there are no sub-geometries of the right type, an EMPTY geometry is returned. Only points, lines and polygons are supported. The type numbers are:
1 == POINT
2 == LINESTRING
3 == POLYGON
For atomic geometry inputs, the geometry is retured unchanged if the input type matches the requested type. Otherwise, the result is an EMPTY geometry of the specified type. If required, these can be converted to multi-geometries using ST_Multi.
![]() | |
MultiPolygon results are not checked for validity. If the polygon components are adjacent or overlapping the result will be invalid. (For example, this can occur when applying this function to an ST_Split result.) This situation can be checked with ST_IsValid and repaired with ST_MakeValid. |
Disponibilità: 1.5.0
![]() | |
Prior to 1.5.3 this function returned atomic inputs unchanged, no matter type. In 1.5.3 non-matching single geometries returned a NULL result. In 2.0.0 non-matching single geometries return an EMPTY result of the requested type. |
Extract highest-dimension type:
SELECT ST_AsText(ST_CollectionExtract( 'GEOMETRYCOLLECTION( POINT(0 0), LINESTRING(1 1, 2 2) )')); st_astext --------------- MULTILINESTRING((1 1, 2 2))
Extract points (type 1 == POINT):
SELECT ST_AsText(ST_CollectionExtract( 'GEOMETRYCOLLECTION(GEOMETRYCOLLECTION(POINT(0 0)))', 1 )); st_astext --------------- MULTIPOINT((0 0))
Extract lines (type 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 — Returns the simplest representation of a geometry collection.
geometry ST_CollectionHomogenize(
geometry collection)
;
Given a geometry collection, returns the "simplest" representation of the contents.
Homogeneous (uniform) collections are returned as the appropriate multi-geometry.
Heterogeneous (mixed) collections are flattened into a single GeometryCollection.
Collections containing a single atomic element are returned as that element.
Atomic geometries are returned unchanged. If required, these can be converted to a multi-geometry using ST_Multi.
![]() | |
This function does not ensure that the result is valid. In particular, a collection containing adjacent or overlapping Polygons will create an invalid MultiPolygon. This situation can be checked with ST_IsValid and repaired with ST_MakeValid. |
Disponibilità: 2.0.0
Single-element collection converted to an atomic geometry
SELECT ST_AsText(ST_CollectionHomogenize('GEOMETRYCOLLECTION(POINT(0 0))')); st_astext ------------ POINT(0 0)
Nested single-element collection converted to an atomic geometry:
SELECT ST_AsText(ST_CollectionHomogenize('GEOMETRYCOLLECTION(MULTIPOINT((0 0)))')); st_astext ------------ POINT(0 0)
Collection converted to a multi-geometry:
SELECT ST_AsText(ST_CollectionHomogenize('GEOMETRYCOLLECTION(POINT(0 0),POINT(1 1))')); st_astext --------------------- MULTIPOINT((0 0),(1 1))
Nested heterogeneous collection flattened to a 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))
Collection of Polygons converted to an (invalid) 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 — Converts a geometry containing curves to a linear geometry.
geometry ST_CurveToLine(
geometry curveGeom, float tolerance, integer tolerance_type, integer flags)
;
Converts a CIRCULAR STRING to regular LINESTRING or CURVEPOLYGON to POLYGON or MULTISURFACE to MULTIPOLYGON. Useful for outputting to devices that can't support CIRCULARSTRING geometry types
Converts a given geometry to a linear geometry. Each curved geometry or segment is converted into a linear approximation using the given `tolerance` and options (32 segments per quadrant and no options by default).
The 'tolerance_type' argument determines interpretation of the `tolerance` argument. It can take the following values:
0 (default): Tolerance is max segments per quadrant.
1: Tolerance is max-deviation of line from curve, in source units.
2: Tolerance is max-angle, in radians, between generating radii.
The 'flags' argument is a bitfield. 0 by default. Supported bits are:
1: Symmetric (orientation idependent) output.
2: Retain angle, avoids reducing angles (segment lengths) when producing symmetric output. Has no effect when Symmetric flag is off.
Availability: 1.3.0
Enhanced: 2.4.0 added support for max-deviation and max-angle tolerance, and for symmetric output.
Enhanced: 3.0.0 implemented a minimum number of segments per linearized arc to prevent topological collapse.
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3: 7.1.7
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
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 — Change start point of a closed LineString.
geometry ST_Scroll(
geometry linestring, geometry point)
;
Changes the start/end point of a closed LineString to the given vertex point
.
Availability: 3.2.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_FlipCoordinates — Returns a version of a geometry with X and Y axis flipped.
geometry ST_FlipCoordinates(
geometry geom)
;
Returns a version of the given geometry with X and Y axis flipped. Useful for fixing geometries which contain coordinates expressed as latitude/longitude (Y,X).
Disponibilità: 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).
ST_Force2D — Force the geometries into a "2-dimensional mode".
geometry ST_Force2D(
geometry geomA)
;
Forces the geometries into a "2-dimensional mode" so that all output representations will only have the X and Y coordinates. This is useful for force OGC-compliant output (since OGC only specifies 2-D geometries).
Miglioramento: nella versione 2.0.0 è stato introdotto il supporto per le superfici poliedriche.
Changed: 2.1.0. Up to 2.0.x this was called 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 — Force the geometries into XYZ mode. This is an alias for ST_Force3DZ.
geometry ST_Force3D(
geometry geomA, float Zvalue = 0.0)
;
Forces the geometries into XYZ mode. This is an alias for ST_Force3DZ. If a geometry has no Z component, then a Zvalue
Z coordinate is tacked on.
Miglioramento: nella versione 2.0.0 è stato introdotto il supporto per le superfici poliedriche.
Changed: 2.1.0. Up to 2.0.x this was called ST_Force_3D.
Changed: 3.1.0. Added support for supplying a non-zero Z value.
This function supports Polyhedral surfaces.
This method supports Circular Strings and Curves
This function supports 3d and will not drop the z-index.
--Nothing happens to an already 3D geometry 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 — Force the geometries into XYZ mode.
geometry ST_Force3DZ(
geometry geomA, float Zvalue = 0.0)
;
Forces the geometries into XYZ mode. If a geometry has no Z component, then a Zvalue
Z coordinate is tacked on.
Miglioramento: nella versione 2.0.0 è stato introdotto il supporto per le superfici poliedriche.
Changed: 2.1.0. Up to 2.0.x this was called ST_Force_3DZ.
Changed: 3.1.0. Added support for supplying a non-zero Z value.
This function supports Polyhedral surfaces.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
--Nothing happens to an already 3D geometry 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 — Force the geometries into XYM mode.
geometry ST_Force3DM(
geometry geomA, float Mvalue = 0.0)
;
Forces the geometries into XYM mode. If a geometry has no M component, then a Mvalue
M coordinate is tacked on. If it has a Z component, then Z is removed
Changed: 2.1.0. Up to 2.0.x this was called ST_Force_3DM.
Changed: 3.1.0. Added support for supplying a non-zero M value.
This method supports Circular Strings and Curves
--Nothing happens to an already 3D geometry 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_Force4D — Force the geometries into XYZM mode.
geometry ST_Force4D(
geometry geomA, float Zvalue = 0.0, float Mvalue = 0.0)
;
Forces the geometries into XYZM mode. Zvalue
and Mvalue
is tacked on for missing Z and M dimensions, respectively.
Changed: 2.1.0. Up to 2.0.x this was called ST_Force_4D.
Changed: 3.1.0. Added support for supplying non-zero Z and M values.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
--Nothing happens to an already 3D geometry 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_ForcePolygonCCW — Orients all exterior rings counter-clockwise and all interior rings clockwise.
geometry ST_ForcePolygonCCW (
geometry geom )
;
Forces (Multi)Polygons to use a counter-clockwise orientation for their exterior ring, and a clockwise orientation for their interior rings. Non-polygonal geometries are returned unchanged.
Availability: 2.4.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_ForceCollection — Convert the geometry into a GEOMETRYCOLLECTION.
geometry ST_ForceCollection(
geometry geomA)
;
Converts the geometry into a GEOMETRYCOLLECTION. This is useful for simplifying the WKB representation.
Miglioramento: nella versione 2.0.0 è stato introdotto il supporto per le superfici poliedriche.
Availability: 1.2.2, prior to 1.3.4 this function will crash with Curves. This is fixed in 1.3.4+
Changed: 2.1.0. Up to 2.0.x this was called 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_ForcePolygonCW — Orients all exterior rings clockwise and all interior rings counter-clockwise.
geometry ST_ForcePolygonCW (
geometry geom )
;
Forces (Multi)Polygons to use a clockwise orientation for their exterior ring, and a counter-clockwise orientation for their interior rings. Non-polygonal geometries are returned unchanged.
Availability: 2.4.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_ForceSFS — Force the geometries to use SFS 1.1 geometry types only.
geometry ST_ForceSFS(
geometry geomA)
;
geometry ST_ForceSFS(
geometry geomA, text version)
;
ST_ForceRHR — Force the orientation of the vertices in a polygon to follow the Right-Hand-Rule.
geometry ST_ForceRHR(
geometry g)
;
Forces the orientation of the vertices in a polygon to follow a Right-Hand-Rule, in which the area that is bounded by the polygon is to the right of the boundary. In particular, the exterior ring is orientated in a clockwise direction and the interior rings in a counter-clockwise direction. This function is a synonym for ST_ForcePolygonCW
![]() | |
The above definition of the Right-Hand-Rule conflicts with definitions used in other contexts. To avoid confusion, it is recommended to use ST_ForcePolygonCW. |
Miglioramento: nella versione 2.0.0 è stato introdotto il supporto per le superfici poliedriche.
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_ForceCurve — Upcast a geometry into its curved type, if applicable.
geometry ST_ForceCurve(
geometry g)
;
Turns a geometry into its curved representation, if applicable: lines become compoundcurves, multilines become multicurves polygons become curvepolygons multipolygons become multisurfaces. If the geometry input is already a curved representation returns back same as input.
Disponibilità: 2.2.0
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
ST_LineToCurve — Converts a linear geometry to a curved geometry.
geometry ST_LineToCurve(
geometry geomANoncircular)
;
Converts plain LINESTRING/POLYGON to CIRCULAR STRINGs and Curved Polygons. Note much fewer points are needed to describe the curved equivalent.
![]() | |
If the input LINESTRING/POLYGON is not curved enough to clearly represent a curve, the function will return the same input geometry. |
Availability: 1.3.0
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
-- 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 — Return the geometry as a MULTI* geometry.
geometry ST_Multi(
geometry geom)
;
Returns the geometry as a MULTI* geometry collection. If the geometry is already a collection, it is returned unchanged.
ST_Normalize — Return the geometry in its canonical form.
geometry ST_Normalize(
geometry geom)
;
Returns the geometry in its normalized/canonical form. May reorder vertices in polygon rings, rings in a polygon, elements in a multi-geometry complex.
Mostly only useful for testing purposes (comparing expected and obtained results).
Availability: 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_QuantizeCoordinates — Sets least significant bits of coordinates to zero
geometry ST_QuantizeCoordinates (
geometry g , int prec_x , int prec_y , int prec_z , int prec_m )
;
ST_QuantizeCoordinates
determines the number of bits (N
) required to represent a coordinate value with a specified number of digits after the decimal point, and then sets all but the N
most significant bits to zero. The resulting coordinate value will still round to the original value, but will have improved compressiblity. This can result in a significant disk usage reduction provided that the geometry column is using a compressible storage type. The function allows specification of a different number of digits after the decimal point in each dimension; unspecified dimensions are assumed to have the precision of the x
dimension. Negative digits are interpreted to refer digits to the left of the decimal point, (i.e., prec_x=-2
will preserve coordinate values to the nearest 100.
The coordinates produced by ST_QuantizeCoordinates
are independent of the geometry that contains those coordinates and the relative position of those coordinates within the geometry. As a result, existing topological relationships between geometries are unaffected by use of this function. The function may produce invalid geometry when it is called with a number of digits lower than the intrinsic precision of the geometry.
Availability: 2.5.0
PostGIS stores all coordinate values as double-precision floating point integers, which can reliably represent 15 significant digits. However, PostGIS may be used to manage data that intrinsically has fewer than 15 significant digits. An example is TIGER data, which is provided as geographic coordinates with six digits of precision after the decimal point (thus requiring only nine significant digits of longitude and eight significant digits of latitude.)
When 15 significant digits are available, there are many possible representations of a number with 9 significant digits. A double precision floating point number uses 52 explicit bits to represent the significand (mantissa) of the coordinate. Only 30 bits are needed to represent a mantissa with 9 significant digits, leaving 22 insignificant bits; we can set their value to anything we like and still end up with a number that rounds to our input value. For example, the value 100.123456 can be represented by the floating point numbers closest to 100.123456000000, 100.123456000001, and 100.123456432199. All are equally valid, in that ST_AsText(geom, 6)
will return the same result with any of these inputs. As we can set these bits to any value, ST_QuantizeCoordinates
sets the 22 insignificant bits to zero. For a long coordinate sequence this creates a pattern of blocks of consecutive zeros that is compressed by PostgreSQL more effeciently.
![]() | |
Only the on-disk size of the geometry is potentially affected by |
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 — Remove a point from a linestring.
geometry ST_RemovePoint(
geometry linestring, integer offset)
;
Removes a point from a LineString, given its index (0-based). Useful for turning a closed line (ring) into an open linestring.
Enhanced: 3.2.0
Disponibilità: 1.1.0
This function supports 3d and will not drop the z-index.
ST_RemoveRepeatedPoints — Returns a version of a geometry with duplicate points removed.
geometry ST_RemoveRepeatedPoints(
geometry geom, float8 tolerance)
;
Returns a version of the given geometry with duplicate consecutive points removed. The function processes only (Multi)LineStrings, (Multi)Polygons and MultiPoints but it can be called with any kind of geometry. Elements of GeometryCollections are processed individually. The endpoints of LineStrings are preserved.
If the tolerance
parameter is provided, vertices within the tolerance distance of one another are considered to be duplicates.
Enhanced: 3.2.0
Disponibilità: 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)
Example: Collection elements are processed individually.
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))
Example: Repeated point removal with a distance tolerance.
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_Reverse — Return the geometry with vertex order reversed.
geometry ST_Reverse(
geometry g1)
;
ST_Segmentize — Returns a modified geometry/geography having no segment longer than a given distance.
geometry ST_Segmentize(
geometry geom, float max_segment_length)
;
geography ST_Segmentize(
geography geog, float max_segment_length)
;
Returns a modified geometry/geography having no segment longer than max_segment_length
. Length is computed in 2D. Segments are always split into equal-length subsegments.
For geometry, the maximum length is in the units of the spatial reference system.
For geography, the maximum length is in meters. Distances are computed on the sphere. Added vertices are created along the spherical great-circle arcs defined by segment endpoints.
![]() | |
This only shortens long segments. It does not lengthen segments shorter than the maximum length. |
![]() | |
For inputs containing long segments, specifying a relatively short |
Availability: 1.2.2
Enhanced: 3.0.0 Segmentize geometry now produces equal-length subsegments
Enhanced: 2.3.0 Segmentize geography now produces equal-length subsegments
Enhanced: 2.1.0 support for geography was introduced.
Changed: 2.1.0 As a result of the introduction of geography support, the usage ST_Segmentize('LINESTRING(1 2, 3 4)', 0.5)
causes an ambiguous function error. The input needs to be properly typed as a geometry or geography. Use ST_GeomFromText, ST_GeogFromText or a cast to the required type (e.g. ST_Segmentize('LINESTRING(1 2, 3 4)'::geometry, 0.5) )
Segmentizing a line. Long segments are split evenly, and short segments are not split.
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))
Segmentizing a polygon:
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))
Segmentizing a geographic line, using a maximum segment length of 2000 kilometers. Vertices are added along the great-circle arc connecting the endpoints.
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)
A geographic line segmentized along a great circle arc
ST_SetPoint — Replace point of a linestring with a given point.
geometry ST_SetPoint(
geometry linestring, integer zerobasedposition, geometry point)
;
Replace point N of linestring with given point. Index is 0-based.Negative index are counted backwards, so that -1 is last point. This is especially useful in triggers when trying to maintain relationship of joints when one vertex moves.
Disponibilità: 1.1.0
Updated 2.3.0 : negative indexing
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_ShiftLongitude — Shifts the longitude coordinates of a geometry between -180..180 and 0..360.
geometry ST_ShiftLongitude(
geometry geom)
;
Reads every point/vertex in a geometry, and shifts its longitude coordinate from -180..0 to 180..360 and vice versa if between these ranges. This function is symmetrical so the result is a 0..360 representation of a -180..180 data and a -180..180 representation of a 0..360 data.
![]() | |
This is only useful for data with coordinates in longitude/latitude; e.g. SRID 4326 (WGS 84 geographic) |
![]() | |
Pre-1.3.4 bug prevented this from working for MULTIPOINT. 1.3.4+ works with MULTIPOINT as well. |
This function supports 3d and will not drop the z-index.
Miglioramento nella version 2.0.2: introdotto il supporto per superfici poliedriche e TIN.
NOTE: this function was renamed from "ST_Shift_Longitude" in 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 — Wrap a geometry around an X value.
geometry ST_WrapX(
geometry geom, float8 wrap, float8 move)
;
This function splits the input geometries and then moves every resulting component falling on the right (for negative 'move') or on the left (for positive 'move') of given 'wrap' line in the direction specified by the 'move' parameter, finally re-unioning the pieces together.
![]() | |
This is useful to "recenter" long-lat input to have features of interest not spawned from one side to the other. |
Availability: 2.3.0 requires GEOS
This function supports 3d and will not drop the z-index.
ST_SnapToGrid — Snap all points of the input geometry to a regular grid.
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)
;
Variant 1,2,3: Snap all points of the input geometry to the grid defined by its origin and cell size. Remove consecutive points falling on the same cell, eventually returning NULL if output points are not enough to define a geometry of the given type. Collapsed geometries in a collection are stripped from it. Useful for reducing precision.
Variant 4: Introduced 1.1.0 - Snap all points of the input geometry to the grid defined by its origin (the second argument, must be a point) and cell sizes. Specify 0 as size for any dimension you don't want to snap to a grid.
![]() | |
The returned geometry might lose its simplicity (see ST_IsSimple). |
![]() | |
Before release 1.1.0 this function always returned a 2d geometry. Starting at 1.1.0 the returned geometry will have same dimensionality as the input one with higher dimension values untouched. Use the version taking a second geometry argument to define all grid dimensions. |
Disponibilità: dalla versione 1.0.0RC1
Availability: 1.1.0 - Z and M support
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 — Snap segments and vertices of input geometry to vertices of a reference geometry.
geometry ST_Snap(
geometry input, geometry reference, float tolerance)
;
Snaps the vertices and segments of a geometry to another Geometry's vertices. A snap distance tolerance is used to control where snapping is performed. The result geometry is the input geometry with the vertices snapped. If no snapping occurs then the input geometry is returned unchanged.
Snapping one geometry to another can improve robustness for overlay operations by eliminating nearly-coincident edges (which cause problems during noding and intersection calculation).
Too much snapping can result in invalid topology being created, so the number and location of snapped vertices is decided using heuristics to determine when it is safe to snap. This can result in some potential snaps being omitted, however.
![]() | |
The returned geometry might lose its simplicity (see ST_IsSimple) and validity (see ST_IsValid). |
Eseguito dal modulo GEOS.
Disponibilità: 2.0.0
![]() A multipolygon shown with a linestring (before any snapping) | |
![]() A multipolygon snapped to linestring to tolerance: 1.01 of distance. The new multipolygon is shown with reference linestring
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))) | ![]() A multipolygon snapped to linestring to tolerance: 1.25 of distance. The new multipolygon is shown with reference linestring
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))) |
![]() The linestring snapped to the original multipolygon at tolerance 1.01 of distance. The new linestring is shown with reference multipolygon
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)
| ![]() The linestring snapped to the original multipolygon at tolerance 1.25 of distance. The new linestring is shown with reference multipolygon
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 — Returns a version of the given geometry with given ordinate values swapped.
geometry ST_SwapOrdinates(
geometry geom, cstring ords)
;
Returns a version of the given geometry with given ordinates swapped.
The ords
parameter is a 2-characters string naming the ordinates to swap. Valid names are: x,y,z and m.
Disponibilità: 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).
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. |
Eseguito dal modulo 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. |
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.
Eseguito dal modulo GEOS.
Disponibilità: 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.
Eseguito dal modulo 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.
Eseguito dal modulo GEOS.
Disponibilità: 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;
|
ST_InverseTransformPipeline — Return a new geometry with coordinates transformed to a different spatial reference system using the inverse of a defined coordinate transformation pipeline.
geometry ST_InverseTransformPipeline(
geometry geom, text pipeline, integer to_srid)
;
Return a new geometry with coordinates transformed to a different spatial reference system using a defined coordinate transformation pipeline to go in the inverse direction.
Refer to ST_TransformPipeline for details on writing a transformation pipeline.
Availability: 3.4.0
The SRID of the input geometry is ignored, and the SRID of the output geometry will be set to zero unless a value is provided via the optional to_srid
parameter. When using ST_TransformPipeline the pipeline is executed in a forward direction. Using `ST_InverseTransformPipeline()` the pipeline is executed in the inverse direction.
Transforms using pipelines are a specialised version of ST_Transform. In most cases `ST_Transform` will choose the correct operations to convert between coordinate systems, and should be preferred.
Change WGS 84 long lat to UTM 31N using the EPSG:16031 conversion
-- 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)
;
Returns the spatial reference identifier for the ST_Geometry as defined in spatial_ref_sys table. Section 4.5, “Spatial Reference Systems”
![]() | |
spatial_ref_sys table is a table that catalogs all spatial reference systems known to PostGIS and is used for transformations from one spatial reference system to another. So verifying you have the right spatial reference system identifier is important if you plan to ever transform your geometries. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s2.1.1.1
This method implements the SQL/MM specification. SQL-MM 3: 5.1.5
This method supports Circular Strings and Curves
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. |
![]() | |
Prior to 1.3.4, this function crashes if used with geometries that contain CURVES. This is fixed in 1.3.4+ |
Miglioramento: nella versione 2.0.0 è stato introdotto il supporto per le superfici poliedriche.
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
.
Availability: 3.4.0
The SRID of the input geometry is ignored, and the SRID of the output geometry will be set to zero unless a value is provided via the optional to_srid
parameter. When using `ST_TransformPipeline()` the pipeline is executed in a forward direction. Using ST_InverseTransformPipeline the pipeline is executed in the inverse direction.
Transforms using pipelines are a specialised version of ST_Transform. In most cases `ST_Transform` will choose the correct operations to convert between coordinate systems, and should be preferred.
Change WGS 84 long lat to UTM 31N using the EPSG:16031 conversion
-- 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)
ST_BdPolyFromText — Costruisce un poligono an partire da una collezione arbitraria di linee chiuse in forma di multilinee rappresentate come testo Well-Known
geometry ST_BdPolyFromText(
text WKT, integer srid)
;
Costruisce un poligono an partire da una collezione arbitraria di linee chiuse in forma di multilinee rappresentate come testo Well-Known
![]() | |
Ritorna un errore se il testo WKT non è una MULTILINESTRING oppure se l'output è un MULTIPOLYGON; in questo caso si può usare ST_BdMPolyFromText oppure ST_BuildArea() per un approccio specifica postgis. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.6.2
Eseguito dal modulo GEOS.
Disponibilità: 1.1.0
ST_BdMPolyFromText — Costruisce un MultiPolygon a partire da una collezione arbitraria di linee chiuse sotto forma di MultiLineString in formato Well-Known-Text.
geometry ST_BdMPolyFromText(
text WKT, integer srid)
;
Costruisse un poligono a partire da una collezione arbitraria di linee chiuse, poligoni e MultiLineString in formato Well-Known-Text.
![]() | |
Ritorna un errore se il WKT non è una MULTILINESTRING. L'output è MULTIPOLYGON anche se il risultato è un singolo poligono. Usare ST_BdPolyFromText se si è sicuri che il risultato è un singolo poligono oppure vedere ST_BuildArea() per un approccio specifico postgis. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.6.2
Eseguito dal modulo GEOS.
Disponibilità: 1.1.0
ST_GeogFromText — Ritorna un valore geography sotto forma di Well-Know-Text (WKT) oppure di Extended-Well-Know-Text (EWKT)
geography ST_GeogFromText(
text EWKT)
;
Returns a geography object from the well-known text or extended well-known representation. SRID 4326 is assumed if unspecified. This is an alias for ST_GeographyFromText. Points are always expressed in long lat form.
--- 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 — Ritorna un valore geography sotto forma di Well-Know-Text (WKT) oppure di Extended-Well-Know-Text (EWKT)
geography ST_GeographyFromText(
text EWKT)
;
ST_GeomCollFromText — Makes a collection Geometry from collection WKT with the given SRID. If SRID is not given, it defaults to 0.
geometry ST_GeomCollFromText(
text WKT, integer srid)
;
geometry ST_GeomCollFromText(
text WKT)
;
Makes a collection Geometry from the Well-Known-Text (WKT) representation with the given SRID. If SRID is not given, it defaults to 0.
OGC SPEC 3.2.6.2 - option SRID is from the conformance suite
Ritorna null se il WKT in input non è una GEOMETRYCOLLECTION
![]() | |
Se si è sicuri che tutti i WKT in input sono effettivamente GEOMETRYCOLLECTION, è sconsigliato usare questa funzione. È più lenta di ST_GeomFromText perché effettua anche una validazione della geometria. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.6.2
This method implements the SQL/MM specification.
ST_GeomFromEWKT — Ritorna un valore ST_Geometry a partire da una rappresentazione Extended Well-Known Text (EWKT).
geometry ST_GeomFromEWKT(
text EWKT)
;
Costruisce un oggetto PostGIS ST_Geometry a partire da una rappresentazione OGC Extended Well-Known Text (EWKT).
![]() | |
Il formato EWKT non è uno standard OGC ma un formato specifico di PostGIS che include il codice del sistema di riferimento spaziale (SRID). |
Miglioramento nella version 2.0.2: introdotto il supporto per superfici poliedriche e 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)))');
-- Linea curva 3d 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 — Takes MARC21/XML geographic data as input and returns a PostGIS geometry object.
geometry ST_GeomFromMARC21 (
text marcxml )
;
This function creates a PostGIS geometry from a MARC21/XML record, which can contain a POINT
or a POLYGON
. In case of multiple geographic data entries in the same MARC21/XML record, a MULTIPOINT
or MULTIPOLYGON
will be returned. If the record contains mixed geometry types, a GEOMETRYCOLLECTION
will be returned. It returns NULL if the MARC21/XML record does not contain any geographic data (datafield:034).
LOC MARC21/XML versions supported:
Availability: 3.3.0, requires libxml2 2.6+
![]() | |
The MARC21/XML Coded Cartographic Mathematical Data currently does not provide any means to describe the Spatial Reference System of the encoded coordinates, so this function will always return a geometry with |
![]() | |
Returned |
Converting MARC21/XML geographic data containing a single POINT
encoded as 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)
Converting MARC21/XML geographic data containing a single POLYGON
encoded as 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)
Converting MARC21/XML geographic data containing a POLYGON
and a 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 — Restituisce un valore ST_Geometry a partire da Well-Known-Text (WKT). È un alias per 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.40
ST_GeomFromText — Restituisce un valore ST_Geometry a partire da una rappresentazione Well-Known-Text (WKT)
geometry ST_GeomFromText(
text WKT)
;
geometry ST_GeomFromText(
text WKT, integer srid)
;
Costruisce un oggetto PostGIS ST_Geometry a partire da geometria in formato OGC Well-Known-Text
![]() | |
There are two variants of ST_GeomFromText function. The first takes no SRID and returns a geometry with no defined spatial reference system (SRID=0). The second takes a SRID as the second argument and returns a geometry that includes this SRID as part of its metadata. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.6.2 - option SRID is from the conformance suite.
This method implements the SQL/MM specification. SQL-MM 3: 5.1.40
This method supports Circular Strings and Curves
![]() | |
While not OGC-compliant, ST_MakePoint is faster than ST_GeomFromText and ST_PointFromText. It is also easier to use for numeric coordinate values. ST_Point is another option similar in speed to ST_MakePoint and is OGC-compliant, but doesn't support anything but 2D points. |
![]() | |
Changed: 2.0.0 In prior versions of PostGIS ST_GeomFromText('GEOMETRYCOLLECTION(EMPTY)') was allowed. This is now illegal in PostGIS 2.0.0 to better conform with SQL/MM standards. This should now be written as 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 — Makes a Geometry from WKT representation with the given SRID. If SRID is not given, it defaults to 0.
geometry ST_LineFromText(
text WKT)
;
geometry ST_LineFromText(
text WKT, integer srid)
;
Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0. If WKT passed in is not a LINESTRING, then null is returned.
![]() | |
OGC SPEC 3.2.6.2 - option SRID is from the conformance suite. |
![]() | |
If you know all your geometries are LINESTRINGS, its more efficient to just use ST_GeomFromText. This just calls ST_GeomFromText and adds additional validation that it returns a linestring. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.6.2
This method implements the SQL/MM specification. SQL-MM 3: 7.2.8
ST_MLineFromText — Return a specified ST_MultiLineString value from WKT representation.
geometry ST_MLineFromText(
text WKT, integer srid)
;
geometry ST_MLineFromText(
text WKT)
;
Makes a Geometry from Well-Known-Text (WKT) with the given SRID. If SRID is not given, it defaults to 0.
OGC SPEC 3.2.6.2 - option SRID is from the conformance suite
Returns null if the WKT is not a MULTILINESTRING
![]() | |
If you are absolutely sure all your WKT geometries are points, don't use this function. It is slower than ST_GeomFromText since it adds an additional validation step. |
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
ST_MPointFromText — Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.
geometry ST_MPointFromText(
text WKT, integer srid)
;
geometry ST_MPointFromText(
text WKT)
;
Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.
OGC SPEC 3.2.6.2 - option SRID is from the conformance suite
Returns null if the WKT is not a MULTIPOINT
![]() | |
If you are absolutely sure all your WKT geometries are points, don't use this function. It is slower than ST_GeomFromText since it adds an additional validation step. |
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
ST_MPolyFromText — Makes a MultiPolygon Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.
geometry ST_MPolyFromText(
text WKT, integer srid)
;
geometry ST_MPolyFromText(
text WKT)
;
Makes a MultiPolygon from WKT with the given SRID. If SRID is not given, it defaults to 0.
OGC SPEC 3.2.6.2 - option SRID is from the conformance suite
Throws an error if the WKT is not a MULTIPOLYGON
![]() | |
If you are absolutely sure all your WKT geometries are multipolygons, don't use this function. It is slower than ST_GeomFromText since it adds an additional validation step. |
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 — Makes a point Geometry from WKT with the given SRID. If SRID is not given, it defaults to unknown.
geometry ST_PointFromText(
text WKT)
;
geometry ST_PointFromText(
text WKT, integer srid)
;
Constructs a PostGIS ST_Geometry point object from the OGC Well-Known text representation. If SRID is not given, it defaults to unknown (currently 0). If geometry is not a WKT point representation, returns null. If completely invalid WKT, then throws an error.
![]() | |
There are 2 variants of ST_PointFromText function, the first takes no SRID and returns a geometry with no defined spatial reference system. The second takes a spatial reference id as the second argument and returns an ST_Geometry that includes this srid as part of its meta-data. The srid must be defined in the spatial_ref_sys table. |
![]() | |
If you are absolutely sure all your WKT geometries are points, don't use this function. It is slower than ST_GeomFromText since it adds an additional validation step. If you are building points from long lat coordinates and care more about performance and accuracy than OGC compliance, use ST_MakePoint or OGC compliant alias ST_Point. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.6.2 - option SRID is from the conformance suite.
This method implements the SQL/MM specification. SQL-MM 3: 6.1.8
ST_PolygonFromText — Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.
geometry ST_PolygonFromText(
text WKT)
;
geometry ST_PolygonFromText(
text WKT, integer srid)
;
Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0. Returns null if WKT is not a polygon.
OGC SPEC 3.2.6.2 - option SRID is from the conformance suite
![]() | |
If you are absolutely sure all your WKT geometries are polygons, don't use this function. It is slower than ST_GeomFromText since it adds an additional validation step. |
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
LINESTRING
from WKB with the given SRIDST_GeogFromWKB — Crea un oggetto geography a partire da una geometria in Well-Known Binary (WKB) oppure Extended Well-Known Binary (EWKB).
geography ST_GeogFromWKB(
bytea wkb)
;
La funzione ST_GeogFromWKB
accetta come argomento una geometria POstGIS in formato Well-Known-Binary (WKB) oppure Extended WKB a crea un oggetto dell'appropriato tipo geography. Questa funzione ha un ruolo nella Geometry Factory in SQL.
Se non specificato, lo SRID di default è 4326 (WGS 84 long lat).
This method supports Circular Strings and Curves
--Anche se bytea rep contiene singoli \, 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 — Ritorna un valore ST_Geometry a partire da Extended Well-Known Binary (EWKB).
geometry ST_GeomFromEWKB(
bytea EWKB)
;
Costruisce una ST_Geometry PostGIS a partire da OGC Extended Well-Known Binary (EWKT).
![]() | |
Il EWKB non è uno standard OGC ma uno specifico formato di Postgis che include il codice del sistema di riferimento spaziale (SRID). |
Miglioramento nella version 2.0.2: introdotto il supporto per superfici poliedriche e 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).
Rappresentazione binaria di LINESTRING(-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932) in NAD 83 long lat (4269).
![]() | |
NOTE: Even though byte arrays are delimited with \ and may have ', we need to escape both out with \ and '' if standard_conforming_strings is off. So it does not look exactly like its AsEWKB representation. |
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@');
![]() | |
In PostgreSQL 9.1+ - standard_conforming_strings is set to on by default, where as in past versions it was set to off. You can change defaults as needed for a single query or at the database or server level. Below is how you would do it with standard_conforming_strings = on. In this case we escape the ' with standard ansi ', but slashes are not escaped |
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 — Creates a geometry instance from a Well-Known Binary geometry representation (WKB) and optional SRID.
geometry ST_GeomFromWKB(
bytea geom)
;
geometry ST_GeomFromWKB(
bytea geom, integer srid)
;
The ST_GeomFromWKB
function, takes a well-known binary representation of a geometry and a Spatial Reference System ID (SRID
) and creates an instance of the appropriate geometry type. This function plays the role of the Geometry Factory in SQL. This is an alternate name for ST_WKBToSQL.
If SRID is not specified, it defaults to 0 (Unknown).
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.7.2 - the optional SRID is from the conformance suite
This method implements the SQL/MM specification. SQL-MM 3: 5.1.41
This method supports Circular Strings and Curves
--Although bytea rep contains single \, these need to be escaped when inserting into a table -- unless standard_conforming_strings is set to on. 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 — Makes a LINESTRING
from WKB with the given SRID
geometry ST_LineFromWKB(
bytea WKB)
;
geometry ST_LineFromWKB(
bytea WKB, integer srid)
;
The ST_LineFromWKB
function, takes a well-known binary representation of geometry and a Spatial Reference System ID (SRID
) and creates an instance of the appropriate geometry type - in this case, a LINESTRING
geometry. This function plays the role of the Geometry Factory in SQL.
If an SRID is not specified, it defaults to 0. NULL
is returned if the input bytea
does not represent a LINESTRING
.
![]() | |
OGC SPEC 3.2.6.2 - option SRID is from the conformance suite. |
![]() | |
If you know all your geometries are |
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
ST_LinestringFromWKB — Makes a geometry from WKB with the given SRID.
geometry ST_LinestringFromWKB(
bytea WKB)
;
geometry ST_LinestringFromWKB(
bytea WKB, integer srid)
;
The ST_LinestringFromWKB
function, takes a well-known binary representation of geometry and a Spatial Reference System ID (SRID
) and creates an instance of the appropriate geometry type - in this case, a LINESTRING
geometry. This function plays the role of the Geometry Factory in SQL.
If an SRID is not specified, it defaults to 0. NULL
is returned if the input bytea
does not represent a LINESTRING
geometry. This an alias for ST_LineFromWKB.
![]() | |
OGC SPEC 3.2.6.2 - optional SRID is from the conformance suite. |
![]() | |
If you know all your geometries are |
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
ST_PointFromWKB — Makes a geometry from WKB with the given SRID
geometry ST_GeomFromWKB(
bytea geom)
;
geometry ST_GeomFromWKB(
bytea geom, integer srid)
;
The ST_PointFromWKB
function, takes a well-known binary representation of geometry and a Spatial Reference System ID (SRID
) and creates an instance of the appropriate geometry type - in this case, a POINT
geometry. This function plays the role of the Geometry Factory in SQL.
If an SRID is not specified, it defaults to 0. NULL
is returned if the input bytea
does not represent a POINT
geometry.
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
ST_Box2dFromGeoHash — Return a BOX2D from a GeoHash string.
box2d ST_Box2dFromGeoHash(
text geohash, integer precision=full_precision_of_geohash)
;
Return a BOX2D from a GeoHash string.
If no precision
is specified ST_Box2dFromGeoHash returns a BOX2D based on full precision of the input GeoHash string.
If precision
is specified ST_Box2dFromGeoHash will use that many characters from the GeoHash to create the BOX2D. Lower precision values results in larger BOX2Ds and larger values increase the precision.
Availability: 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 — Return a geometry from a GeoHash string.
geometry ST_GeomFromGeoHash(
text geohash, integer precision=full_precision_of_geohash)
;
Return a geometry from a GeoHash string. The geometry will be a polygon representing the GeoHash bounds.
If no precision
is specified ST_GeomFromGeoHash returns a polygon based on full precision of the input GeoHash string.
If precision
is specified ST_GeomFromGeoHash will use that many characters from the GeoHash to create the polygon.
Availability: 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 — Accetta una geometria in formato GML come input e restituisce un oggetto PostGIS geometry
geometry ST_GeomFromGML(
text geomgml)
;
geometry ST_GeomFromGML(
text geomgml, integer srid)
;
Costruisce un oggetto PostGIS ST_Geometry a partire da una rappresentazione OGC GML
ST_GeomFromGML supporta solo singole geometrie in formato GML. Ritorna un errore se si cerca di usare l'intero documento GML.
Versioni di OGC GML supportate:
GML 3.2.1 Namespace
GML 3.1.1 Simple Features profile SF-2 (con retrocompatibilità GML 3.1.0 e 3.0.0)
GML 2.1.2
OGC GML standards, cf: http://www.opengeospatial.org/standards/gml:
Disponibilità: 1.5, richiede libxml2 1.6+
Miglioramento nella version 2.0.2: introdotto il supporto per superfici poliedriche e TIN.
Miglioramento nella versione: 2.0.0 introdotto opzionale parametro 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).
In formato GML permette di combinare diverse dimensioni (per esempio la stessa multigeometria può contenere elementi in 2D e 3D contemporaneamente). Siccome le geometrie PostGIS non supportano la combinazione di diverse dimensioni, la funzione ST_GeomFromGML converte l'intera geometria in 2D se almeno un elemento è in 2D.
Il formato GML supporta la combinazione di diversi SRID all'interno della stessa multigeometria. Siccome le geometrie PostGIS non supportano questa combinazione, la funzione ST_GeomFromGML riproietta tutte le sottogeometrie nello SRID del nodo root. Se il nodo root non contiene l'attributo srsName, la funzione restituisce un errore.
La funzione ST_GeomFromGML non richiede dell'indicazione esplicita di un namespace GML. Nell'uso comune una indicazione specifica. non è necessaria. Il namespace deve però essere indicato esplicitamente se si vuole usare la feature XLink all'interno di GML.
![]() | |
ST_GeomFromGML non supporta geometrie curve SQL/MM. |
SELECT ST_GeomFromGML(' <gml:LineString 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> <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 — Accetta come input la rappresentazione geojson di una geometria e restituisce una geometria PostGIS
geometry ST_GeomFromGeoJSON(
text geomjson)
;
geometry ST_GeomFromGeoJSON(
json geomjson)
;
geometry ST_GeomFromGeoJSON(
jsonb geomjson)
;
Costruisce una geometria PostGIS a partire a una rappresentazione GeoJson
ST_GeomFromGeoJSON funzione solo con frammenti di geometrie GeoJson. Ritorna un errore se si cerca di usare un completo documento json.
Enhanced: 3.0.0 parsed geometry defaults to SRID=4326 if not specified otherwise.
Enhanced: 2.5.0 can now accept json and jsonb as inputs.
Disponibilità: 2.0.0. Richiede - JSON-C >= 0.9
![]() | |
Se supporto JSON-C non è attivato, viene restituito un errore invece dell'output. Per attivare il supporto JSON-C, usare configure --with-jsondir=/path/to/json-c. Vedi Section 2.2.3, “Configurazione” per dettagli. |
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)
-- una linestring 3D 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 — Accetta come input una geometria in formato KML e restituisce una geometria PostGIS.
geometry ST_GeomFromKML(
text geomkml)
;
Costruisce un oggetto PostSIG ST_Geometry a partire da una geometria in formato OGC KML.
ST_GeomFromKML accetta solo frammenti di geometrie KML. Restituisce un errore se l'input consiste in un intero documento KML.
Versioni di OGC KML supportate:
KML 2.2.0 Namespace
OGC KML standards, cf: http://www.opengeospatial.org/standards/kml:
Availability: 1.5, requires libxml2 2.6+
This function supports 3d and will not drop the z-index.
![]() | |
La funzione ST_GeomFromKML non supporta geometrie curve SQL/MM. |
ST_GeomFromTWKB — Creates a geometry instance from a TWKB ("Tiny Well-Known Binary") geometry representation.
geometry ST_GeomFromTWKB(
bytea twkb)
;
The ST_GeomFromTWKB
function, takes a a TWKB ("Tiny Well-Known Binary") geometry representation (WKB) and creates an instance of the appropriate geometry type.
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 — Restituisce un valore ST_Geometry a partire da una rappresentazione GML. Questo è solo un alias per la funzione 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 (tranne che il supporto per le curve).
Disponibilità: 1.5, richiede libxml2 1.6+
Miglioramento nella version 2.0.2: introdotto il supporto per superfici poliedriche e TIN.
Miglioramento nella versione: 2.0.0 introdotto opzionale parametro SRID.
ST_LineFromEncodedPolyline — Creates a LineString from an Encoded Polyline.
geometry ST_LineFromEncodedPolyline(
text polyline, integer precision=5)
;
Creates a LineString from an Encoded Polyline string.
Optional precision
specifies how many decimal places will be preserved in Encoded Polyline. Value should be the same on encoding and decoding, or coordinates will be incorrect.
See http://developers.google.com/maps/documentation/utilities/polylinealgorithm
Disponibilità: 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 — Return a point from a GeoHash string.
point ST_PointFromGeoHash(
text geohash, integer precision=full_precision_of_geohash)
;
Return a point from a GeoHash string. The point represents the center point of the GeoHash.
If no precision
is specified ST_PointFromGeoHash returns a point based on full precision of the input GeoHash string.
If precision
is specified ST_PointFromGeoHash will use that many characters from the GeoHash to create the point.
Availability: 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 — Creates a table based on the structure of FlatGeobuf data.
geometry ST_BdPolyFromText(
text WKT, integer srid)
;
Creates a table based on the structure of FlatGeobuf data. (http://flatgeobuf.org).
schema
Schema name.
table
Table name.
data
Input FlatGeobuf data.
Availability: 3.2.0
ST_FromFlatGeobuf — Reads FlatGeobuf data.
setof anyelement ST_FromFlatGeobuf(
anyelement Table reference, bytea FlatGeobuf input data)
;
Reads FlatGeobuf data (http://flatgeobuf.org). NOTE: PostgreSQL bytea cannot exceed 1GB.
tabletype
reference to a table type.
data
input FlatGeobuf data.
Availability: 3.2.0
ST_AsEWKT — Return the Well-Known Text (WKT) representation of the geometry with SRID meta data.
text ST_AsEWKT(
geometry g1)
;
text ST_AsEWKT(
geometry g1, integer maxdecimaldigits=15)
;
text ST_AsEWKT(
geography g1)
;
text ST_AsEWKT(
geography g1, integer maxdecimaldigits=15)
;
Returns the Well-Known Text representation of the geometry prefixed with the SRID. The optional maxdecimaldigits
argument may be used to reduce the maximum number of decimal digits after floating point used in output (defaults to 15).
To perform the inverse conversion of EWKT representation to PostGIS geometry use ST_GeomFromEWKT.
![]() | |
Using the |
![]() | |
The WKT spec does not include the SRID. To get the OGC WKT format use ST_AsText. |
![]() | |
WKT format does not maintain precision so to prevent floating truncation, use ST_AsBinary or ST_AsEWKB format for transport. |
Enhanced: 3.1.0 support for optional precision parameter.
Enhanced: 2.0.0 support for Geography, Polyhedral surfaces, Triangles and TIN was introduced.
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 — Return the Well-Known Text (WKT) representation of the geometry/geography without SRID metadata.
text ST_AsText(
geometry g1)
;
text ST_AsText(
geometry g1, integer maxdecimaldigits = 15)
;
text ST_AsText(
geography g1)
;
text ST_AsText(
geography g1, integer maxdecimaldigits = 15)
;
Returns the OGC Well-Known Text (WKT) representation of the geometry/geography. The optional maxdecimaldigits
argument may be used to limit the number of digits after the decimal point in output ordinates (defaults to 15).
To perform the inverse conversion of WKT representation to PostGIS geometry use ST_GeomFromText.
![]() | |
The standard OGC WKT representation does not include the SRID. To include the SRID as part of the output representation, use the non-standard PostGIS function ST_AsEWKT |
![]() | |
The textual representation of numbers in WKT may not maintain full floating-point precision. To ensure full accuracy for data storage or transport it is best to use Well-Known Binary (WKB) format (see ST_AsBinary and |
![]() | |
Using the |
Availability: 1.5 - support for geography was introduced.
Enhanced: 2.5 - optional parameter precision introduced.
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s2.1.1.1
This method implements the SQL/MM specification. SQL-MM 3: 5.1.25
This method supports Circular Strings and Curves
SELECT ST_AsText('01030000000100000005000000000000000000 000000000000000000000000000000000000000000000000 F03F000000000000F03F000000000000F03F000000000000F03 F000000000000000000000000000000000000000000000000'); st_astext -------------------------------- POLYGON((0 0,0 1,1 1,1 0,0 0))
Full precision output is the default.
SELECT ST_AsText('POINT(111.1111111 1.1111111)')); st_astext ------------------------------ POINT(111.1111111 1.1111111)
The maxdecimaldigits
argument can be used to limit output precision.
SELECT ST_AsText('POINT(111.1111111 1.1111111)'), 2); st_astext -------------------- POINT(111.11 1.11)
ST_AsBinary — Return the OGC/ISO Well-Known Binary (WKB) representation of the geometry/geography without SRID meta data.
bytea ST_AsBinary(
geometry g1)
;
bytea ST_AsBinary(
geometry g1, text NDR_or_XDR)
;
bytea ST_AsBinary(
geography g1)
;
bytea ST_AsBinary(
geography g1, text NDR_or_XDR)
;
Returns the OGC/ISO Well-Known Binary (WKB) representation of the geometry. The first function variant defaults to encoding using server machine endian. The second function variant takes a text argument specifying the endian encoding, either little-endian ('NDR') or big-endian ('XDR').
WKB format is useful to read geometry data from the database and maintaining full numeric precision. This avoids the precision rounding that can happen with text formats such as WKT.
To perform the inverse conversion of WKB to PostGIS geometry use ST_GeomFromWKB.
![]() | |
The OGC/ISO WKB format does not include the SRID. To get the EWKB format which does include the SRID use ST_AsEWKB |
![]() | |
The default behavior in PostgreSQL 9.0 has been changed to output bytea in hex encoding. If your GUI tools require the old behavior, then SET bytea_output='escape' in your database. |
Migliorato: Nella 2.0.0 è stato introdotto il supporto per le superfici poliedriche, i triangoli e i TIN.
Enhanced: 2.0.0 support for higher coordinate dimensions was introduced.
Enhanced: 2.0.0 support for specifying endian with geography was introduced.
Availability: 1.5.0 geography support was introduced.
Changed: 2.0.0 Inputs to this function can not be unknown -- must be geometry. Constructs such as ST_AsBinary('POINT(1 2)')
are no longer valid and you will get an n st_asbinary(unknown) is not unique error
. Code like that needs to be changed to ST_AsBinary('POINT(1 2)'::geometry);
. If that is not possible, then install legacy.sql
.
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s2.1.1.1
This method implements the SQL/MM specification. SQL-MM 3: 5.1.37
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
This function supports 3d and will not drop the z-index.
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 — Return the Extended Well-Known Binary (EWKB) representation of the geometry with SRID meta data.
bytea ST_AsEWKB(
geometry g1)
;
bytea ST_AsEWKB(
geometry g1, text NDR_or_XDR)
;
Returns the Extended Well-Known Binary (EWKB) representation of the geometry with SRID metadata. The first function variant defaults to encoding using server machine endian. The second function variant takes a text argument specifying the endian encoding, either little-endian ('NDR') or big-endian ('XDR').
WKB format is useful to read geometry data from the database and maintaining full numeric precision. This avoids the precision rounding that can happen with text formats such as WKT.
To perform the inverse conversion of EWKB to PostGIS geometry use ST_GeomFromEWKB.
![]() | |
To get the OGC/ISO WKB format use ST_AsBinary. Note that OGC/ISO WKB format does not include the SRID. |
Migliorato: Nella 2.0.0 è stato introdotto il supporto per le superfici poliedriche, i triangoli e i 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 — Returns a Geometry in HEXEWKB format (as text) using either little-endian (NDR) or big-endian (XDR) encoding.
text ST_AsHEXEWKB(
geometry g1, text NDRorXDR)
;
text ST_AsHEXEWKB(
geometry g1)
;
Returns a Geometry in HEXEWKB format (as text) using either little-endian (NDR) or big-endian (XDR) encoding. If no encoding is specified, then NDR is used.
![]() | |
Availability: 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)); dà la stessa risposta di SELECT ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326)::text; st_ashexewkb -------- 0103000020E6100000010000000500 00000000000000000000000000000000 00000000000000000000000000000000F03F 000000000000F03F000000000000F03F000000000000F03 F000000000000000000000000000000000000000000000000
ST_AsEncodedPolyline — Returns an Encoded Polyline from a LineString geometry.
text ST_AsEncodedPolyline(
geometry geom, integer precision=5)
;
Returns the geometry as an Encoded Polyline. This format is used by Google Maps with precision=5 and by Open Source Routing Machine with precision=5 and 6.
Optional precision
specifies how many decimal places will be preserved in Encoded Polyline. Value should be the same on encoding and decoding, or coordinates will be incorrect.
Disponibilità: 2.2.0
Basic
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`@
Use in conjunction with geography linestring and geography segmentize, and put on google maps
-- 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 will look something like this where $ variable you replace with query result
<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 — Return a FlatGeobuf representation of a set of rows.
bytea ST_AsFlatGeobuf(
anyelement set row)
;
bytea ST_AsFlatGeobuf(
anyelement row, bool index)
;
bytea ST_AsFlatGeobuf(
anyelement row, bool index, text geom_name)
;
Return a FlatGeobuf representation (http://flatgeobuf.org) of a set of rows corresponding to a FeatureCollection. NOTE: PostgreSQL bytea cannot exceed 1GB.
row
row data with at least a geometry column.
index
toggle spatial index creation. Default is false.
geom_name
is the name of the geometry column in the row data. If NULL it will default to the first found geometry column.
Availability: 3.2.0
ST_AsGeobuf — Return a Geobuf representation of a set of rows.
bytea ST_AsGeobuf(
anyelement set row)
;
bytea ST_AsGeobuf(
anyelement row, text geom_name)
;
Return a Geobuf representation (https://github.com/mapbox/geobuf) of a set of rows corresponding to a FeatureCollection. Every input geometry is analyzed to determine maximum precision for optimal storage. Note that Geobuf in its current form cannot be streamed so the full output will be assembled in memory.
row
row data with at least a geometry column.
geom_name
is the name of the geometry column in the row data. If NULL it will default to the first found geometry column.
Availability: 2.4.0
ST_AsGeoJSON — Return a geometry as a GeoJSON element.
text ST_AsGeoJSON(
record feature, text geomcolumnname, integer maxdecimaldigits=9, boolean pretty_bool=false)
;
text ST_AsGeoJSON(
geometry geom, integer maxdecimaldigits=9, integer options=8)
;
text ST_AsGeoJSON(
geography geog, integer maxdecimaldigits=9, integer options=0)
;
Returns a geometry as a GeoJSON "geometry", or a row as a GeoJSON "feature". (See the GeoJSON specifications RFC 7946). 2D and 3D Geometries are both supported. GeoJSON only support SFS 1.1 geometry types (no curve support for example).
The maxdecimaldigits
argument may be used to reduce the maximum number of decimal places used in output (defaults to 9). If you are using EPSG:4326 and are outputting the geometry only for display, maxdecimaldigits
=6 can be a good choice for many maps.
![]() | |
Using the |
The options
argument can be used to add BBOX or CRS in GeoJSON output:
0: means no option
1: GeoJSON BBOX
2: GeoJSON Short CRS (e.g EPSG:4326)
4: GeoJSON Long CRS (e.g urn:ogc:def:crs:EPSG::4326)
8: GeoJSON Short CRS if not EPSG:4326 (default)
The GeoJSON specification states that polygons are oriented using the Right-Hand Rule, and some clients require this orientation. This can be ensured by using ST_ForcePolygonCCW . The specification also requires that geometry be in the WGS84 coordinate system (SRID = 4326). If necessary geometry can be projected into WGS84 using ST_Transform: ST_Transform( geom, 4326 )
.
GeoJSON can be tested and viewed online at geojson.io and geojsonlint.com. It is widely supported by web mapping frameworks:
Disponibilità: 1.3.4
Availability: 1.5.0 geography support was introduced.
Changed: 2.0.0 support default args and named args.
Changed: 3.0.0 support records as input
Changed: 3.0.0 output SRID if not EPSG:4326.
This function supports 3d and will not drop the z-index.
Generate a FeatureCollection:
SELECT json_build_object( 'type', 'FeatureCollection', 'features', json_agg(ST_AsGeoJSON(t.*)::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]}, "properties": {"id": 1, "name": "one"}}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[2,2]}, "properties": {"id": 2, "name": "two"}}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[3,3]}, "properties": {"id": 3, "name": "three"}}]}
Generate a Feature:
SELECT ST_AsGeoJSON(t.*) FROM (VALUES (1, 'one', 'POINT(1 1)'::geometry)) AS t(id, name, geom);
st_asgeojson ----------------------------------------------------------------------------------------------------------------- {"type": "Feature", "geometry": {"type":"Point","coordinates":[1,1]}, "properties": {"id": 1, "name": "one"}}
An alternate way to generate Features with an id
property is to use JSONB functions and operators:
SELECT jsonb_build_object( 'type', 'Feature', 'id', id, 'geometry', ST_AsGeoJSON(geom)::jsonb, 'properties', to_jsonb( t.* ) - 'id' - 'geom' ) AS json FROM (VALUES (1, 'one', 'POINT(1 1)'::geometry)) AS t(id, name, geom);
json ----------------------------------------------------------------------------------------------------------------- {"id": 1, "type": "Feature", "geometry": {"type": "Point", "coordinates": [1, 1]}, "properties": {"name": "one"}}
Don't forget to transform your data to WGS84 longitude, latitude to conform with the GeoJSON specification:
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 geometries are supported:
SELECT ST_AsGeoJSON('LINESTRING(1 2 3, 4 5 6)');
{"type":"LineString","coordinates":[[1,2,3],[4,5,6]]}
ST_AsGML — Return the geometry as a GML version 2 or 3 element.
text ST_AsGML(
geometry geom, integer maxdecimaldigits=15, integer options=0)
;
text ST_AsGML(
geography geog, integer maxdecimaldigits=15, integer options=0, text nprefix=null, text id=null)
;
text ST_AsGML(
integer version, geometry geom, integer maxdecimaldigits=15, integer options=0, text nprefix=null, text id=null)
;
text ST_AsGML(
integer version, geography geog, integer maxdecimaldigits=15, integer options=0, text nprefix=null, text id=null)
;
Return the geometry as a Geography Markup Language (GML) element. The version parameter, if specified, may be either 2 or 3. If no version parameter is specified then the default is assumed to be 2. The maxdecimaldigits
argument may be used to reduce the maximum number of decimal places used in output (defaults to 15).
![]() | |
Using the |
GML 2 refer to 2.1.2 version, GML 3 to 3.1.1 version
The 'options' argument is a bitfield. It could be used to define CRS output type in GML output, and to declare data as lat/lon:
0: GML Short CRS (e.g EPSG:4326), default value
1: GML Long CRS (e.g urn:ogc:def:crs:EPSG::4326)
2: For GML 3 only, remove srsDimension attribute from output.
4: For GML 3 only, use <LineString> rather than <Curve> tag for lines.
16: Declare that datas are lat/lon (e.g srid=4326). Default is to assume that data are planars. This option is useful for GML 3.1.1 output only, related to axis order. So if you set it, it will swap the coordinates so order is lat lon instead of database lon lat.
32: Output the box of the geometry (envelope).
The 'namespace prefix' argument may be used to specify a custom namespace prefix or no prefix (if empty). If null or omitted 'gml' prefix is used
Disponibilità: 1.3.2
Availability: 1.5.0 geography support was introduced.
Enhanced: 2.0.0 prefix support was introduced. Option 4 for GML3 was introduced to allow using LineString instead of Curve tag for lines. GML3 Support for Polyhedral surfaces and TINS was introduced. Option 32 was introduced to output the box.
Changed: 2.0.0 use default named args
Enhanced: 2.1.0 id support was introduced, for GML 3.
![]() | |
Only version 3+ of ST_AsGML supports Polyhedral Surfaces and 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 — Return the geometry as a KML element.
text ST_AsKML(
geometry geom, integer maxdecimaldigits=15, text nprefix=NULL)
;
text ST_AsKML(
geography geog, integer maxdecimaldigits=15, text nprefix=NULL)
;
Return the geometry as a Keyhole Markup Language (KML) element. default maximum number of decimal places is 15, default namespace is no prefix.
![]() | |
Using the |
![]() | |
Requires PostGIS be compiled with Proj support. Use PostGIS_Full_Version to confirm you have proj support compiled in. |
![]() | |
Availability: 1.2.2 - later variants that include version param came in 1.3.2 |
![]() | |
Enhanced: 2.0.0 - Add prefix namespace, use default and named args |
![]() | |
Changed: 3.0.0 - Removed the "versioned" variant signature |
![]() | |
AsKML output will not work with geometries that do not have an 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 — Return the Degrees, Minutes, Seconds representation of the given point.
text ST_AsLatLonText(
geometry pt, text format='')
;
Returns the Degrees, Minutes, Seconds representation of the point.
![]() | |
It is assumed the point is in a lat/lon projection. The X (lon) and Y (lat) coordinates are normalized in the output to the "normal" range (-180 to +180 for lon, -90 to +90 for lat). |
The text parameter is a format string containing the format for the resulting text, similar to a date format string. Valid tokens are "D" for degrees, "M" for minutes, "S" for seconds, and "C" for cardinal direction (NSEW). DMS tokens may be repeated to indicate desired width and precision ("SSS.SSSS" means " 1.0023").
"M", "S", and "C" are optional. If "C" is omitted, degrees are shown with a "-" sign if south or west. If "S" is omitted, minutes will be shown as decimal with as many digits of precision as you specify. If "M" is also omitted, degrees are shown as decimal with as many digits precision as you specify.
If the format string is omitted (or zero-length) a default format will be used.
Disponibilità: 2.0
Default format.
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)')); st_aslatlontext ---------------------------- 2°19'29.928"S 3°14'3.243"W
Providing a format (same as the default).
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
Characters other than D, M, S, C and . are just passed through.
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
Signed degrees instead of cardinal directions.
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)', 'D°M''S.SSS"')); st_aslatlontext ---------------------------- -2°19'29.928" -3°14'3.243"
Decimal degrees.
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)', 'D.DDDD degrees C')); st_aslatlontext ----------------------------------- 2.3250 degrees S 3.2342 degrees W
Excessively large values are normalized.
SELECT (ST_AsLatLonText('POINT (-302.2342342 -792.32498)')); st_aslatlontext ------------------------------- 72°19'29.928"S 57°45'56.757"E
ST_AsMARC21 — Returns geometry as a MARC21/XML record with a geographic datafield (034).
text ST_AsMARC21 (
geometry geom , text format='hdddmmss' )
;
This function returns a MARC21/XML record with Coded Cartographic Mathematical Data representing the bounding box of a given geometry. The format
parameter allows to encode the coordinates in subfields $d
,$e
,$f
and $g
in all formats supported by the MARC21/XML standard. Valid formats are:
cardinal direction, degrees, minutes and seconds (default): hdddmmss
decimal degrees with cardinal direction: hddd.dddddd
decimal degrees without cardinal direction: ddd.dddddd
decimal minutes with cardinal direction: hdddmm.mmmm
decimal minutes without cardinal direction: dddmm.mmmm
decimal seconds with cardinal direction: hdddmmss.sss
The decimal sign may be also a comma, e.g. hdddmm,mmmm
.
The precision of decimal formats can be limited by the number of characters after the decimal sign, e.g. hdddmm.mm
for decimal minutes with a precision of two decimals.
This function ignores the Z and M dimensions.
LOC MARC21/XML versions supported:
Availability: 3.3.0
![]() | |
This function does not support non lon/lat geometries, as they are not supported by the MARC21/XML standard (Coded Cartographic Mathematical Data). |
![]() | |
The MARC21/XML Standard does not provide any means to annotate the spatial reference system for Coded Cartographic Mathematical Data, which means that this information will be lost after conversion to MARC21/XML. |
Converting a POINT
to MARC21/XML formated as hdddmmss (default)
SELECT ST_AsMARC21('SRID=4326;POINT(-4.504289 54.253312)'::geometry); st_asmarc21 ------------------------------------------------- <record xmlns="http://www.loc.gov/MARC21/slim"> <datafield tag="034" ind1="1" ind2=" "> <subfield code="a">a</subfield> <subfield code="d">W0043015</subfield> <subfield code="e">W0043015</subfield> <subfield code="f">N0541512</subfield> <subfield code="g">N0541512</subfield> </datafield> </record>
Converting a POLYGON
to MARC21/XML formated in decimal degrees
SELECT ST_AsMARC21('SRID=4326;POLYGON((-4.5792388916015625 54.18172660239091,-4.56756591796875 54.196993557130355,-4.546623229980469 54.18313300502024,-4.5792388916015625 54.18172660239091))'::geometry,'hddd.dddd'); <record xmlns="http://www.loc.gov/MARC21/slim"> <datafield tag="034" ind1="1" ind2=" "> <subfield code="a">a</subfield> <subfield code="d">W004.5792</subfield> <subfield code="e">W004.5466</subfield> <subfield code="f">N054.1970</subfield> <subfield code="g">N054.1817</subfield> </datafield> </record>
Converting a GEOMETRYCOLLECTION
to MARC21/XML formated in decimal minutes. The geometries order in the MARC21/XML output correspond to their order in the collection.
SELECT ST_AsMARC21('SRID=4326;GEOMETRYCOLLECTION(POLYGON((13.1 52.65,13.516666666666667 52.65,13.516666666666667 52.38333333333333,13.1 52.38333333333333,13.1 52.65)),POINT(-4.5 54.25))'::geometry,'hdddmm.mmmm'); st_asmarc21 ------------------------------------------------- <record xmlns="http://www.loc.gov/MARC21/slim"> <datafield tag="034" ind1="1" ind2=" "> <subfield code="a">a</subfield> <subfield code="d">E01307.0000</subfield> <subfield code="e">E01331.0000</subfield> <subfield code="f">N05240.0000</subfield> <subfield code="g">N05224.0000</subfield> </datafield> <datafield tag="034" ind1="1" ind2=" "> <subfield code="a">a</subfield> <subfield code="d">W00430.0000</subfield> <subfield code="e">W00430.0000</subfield> <subfield code="f">N05415.0000</subfield> <subfield code="g">N05415.0000</subfield> </datafield> </record>
ST_AsMVTGeom — Transforms a geometry into the coordinate space of a MVT tile.
geometry ST_AsMVTGeom(
geometry geom, box2d bounds, integer extent=4096, integer buffer=256, boolean clip_geom=true)
;
Transforms a geometry into the coordinate space of a MVT (Mapbox Vector Tile) tile, clipping it to the tile bounds if required. The geometry must be in the coordinate system of the target map (using ST_Transform if needed). Commonly this is Web Mercator (SRID:3857).
The function attempts to preserve geometry validity, and corrects it if needed. This may cause the result geometry to collapse to a lower dimension.
The rectangular bounds of the tile in the target map coordinate space must be provided, so the geometry can be transformed, and clipped if required. The bounds can be generated using ST_MakeEnvelope.
This function is used to convert geometry into the tile coordinate space required by ST_AsMVT.
geom
is the geometry to transform, in the coordinate system of the target map.
bounds
is the rectangular bounds of the tile in map coordinate space, with no buffer.
extent
is the tile extent size in tile coordinate space as defined by the MVT specification. Defaults to 4096.
buffer
is the buffer size in tile coordinate space for geometry clippig. Defaults to 256.
clip_geom
is a boolean to control if geometries are clipped or encoded as-is. Defaults to true.
Availability: 2.4.0
![]() | |
From 3.0, Wagyu can be chosen at configure time to clip and validate MVT polygons. This library is faster and produces more correct results than the GEOS default, but it might drop small polygons. |
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)))
Canonical example for a Web Mercator tile using a computed tile bounds to query and clip geometry.
SELECT ST_AsMVTGeom( ST_Transform( geom, 3857 ), ST_TileEnvelope(12, 513, 412), extent => 4096, buffer => 64) AS geom FROM data WHERE geom && ST_TileEnvelope(12, 513, 412, margin => (64.0 / 4096))
ST_AsMVT — Aggregate function returning a MVT representation of a set of rows.
bytea ST_AsMVT(
anyelement set row)
;
bytea ST_AsMVT(
anyelement row, text name)
;
bytea ST_AsMVT(
anyelement row, text name, integer extent)
;
bytea ST_AsMVT(
anyelement row, text name, integer extent, text geom_name)
;
bytea ST_AsMVT(
anyelement row, text name, integer extent, text geom_name, text feature_id_name)
;
An aggregate function which returns a binary Mapbox Vector Tile representation of a set of rows corresponding to a tile layer. The rows must contain a geometry column which will be encoded as a feature geometry. The geometry must be in tile coordinate space and valid as per the MVT specification. ST_AsMVTGeom can be used to transform geometry into tile coordinate space. Other row columns are encoded as feature attributes.
The Mapbox Vector Tile format can store features with varying sets of attributes. To use this capability supply a JSONB column in the row data containing Json objects one level deep. The keys and values in the JSONB values will be encoded as feature attributes.
Tiles with multiple layers can be created by concatenating multiple calls to this function using ||
or STRING_AGG
.
![]() | |
Do not call with a |
row
row data with at least a geometry column.
name
is the name of the layer. Default is the string "default".
extent
is the tile extent in screen space as defined by the specification. Default is 4096.
geom_name
is the name of the geometry column in the row data. Default is the first geometry column. Note that PostgreSQL by default automatically folds unquoted identifiers to lower case, which means that unless the geometry column is quoted, e.g. "MyMVTGeom"
, this parameter must be provided as lowercase.
feature_id_name
is the name of the Feature ID column in the row data. If NULL or negative the Feature ID is not set. The first column matching name and valid type (smallint, integer, bigint) will be used as Feature ID, and any subsequent column will be added as a property. JSON properties are not supported.
Enhanced: 3.0 - added support for Feature ID.
Enhanced: 2.5.0 - added support parallel query.
Availability: 2.4.0
ST_AsSVG — Returns SVG path data for a geometry.
text ST_AsSVG(
geometry geom, integer rel=0, integer maxdecimaldigits=15)
;
text ST_AsSVG(
geography geog, integer rel=0, integer maxdecimaldigits=15)
;
Return the geometry as Scalar Vector Graphics (SVG) path data. Use 1 as second argument to have the path data implemented in terms of relative moves, the default (or 0) uses absolute moves. Third argument may be used to reduce the maximum number of decimal digits used in output (defaults to 15). Point geometries will be rendered as cx/cy when 'rel' arg is 0, x/y when 'rel' is 1. Multipoint geometries are delimited by commas (","), GeometryCollection geometries are delimited by semicolons (";").
![]() | |
Availability: 1.2.2. Availability: 1.4.0 Changed in PostGIS 1.4.0 to include L command in absolute path to conform to http://www.w3.org/TR/SVG/paths.html#PathDataBNF |
Changed: 2.0.0 to use default args and support named args
ST_AsTWKB — Returns the geometry as TWKB, aka "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)
;
Returns the geometry in TWKB (Tiny Well-Known Binary) format. TWKB is a compressed binary format with a focus on minimizing the size of the output.
The decimal digits parameters control how much precision is stored in the output. By default, values are rounded to the nearest unit before encoding. If you want to transfer more precision, increase the number. For example, a value of 1 implies that the first digit to the right of the decimal point will be preserved.
The sizes and bounding boxes parameters control whether optional information about the encoded length of the object and the bounds of the object are included in the output. By default they are not. Do not turn them on unless your client software has a use for them, as they just use up space (and saving space is the point of TWKB).
The array-input form of the function is used to convert a collection of geometries and unique identifiers into a TWKB collection that preserves the identifiers. This is useful for clients that expect to unpack a collection and then access further information about the objects inside. You can create the arrays using the array_agg function. The other parameters operate the same as for the simple form of the function.
![]() | |
The format specification is available online at https://github.com/TWKB/Specification, and code for building a JavaScript client can be found at https://github.com/TWKB/twkb.js. |
Enhanced: 2.4.0 memory and speed improvements.
Disponibilità: 2.2.0
SELECT ST_AsTWKB('LINESTRING(1 1,5 5)'::geometry); st_astwkb -------------------------------------------- \x02000202020808
To create an aggregate TWKB object including identifiers aggregate the desired geometries and objects first, using "array_agg()", then call the appropriate TWKB function.
SELECT ST_AsTWKB(array_agg(geom), array_agg(gid)) FROM mytable; st_astwkb -------------------------------------------- \x040402020400000202
ST_AsX3D — Returns a Geometry in X3D xml node element format: ISO-IEC-19776-1.2-X3DEncodings-XML
text ST_AsX3D(
geometry g1, integer maxdecimaldigits=15, integer options=0)
;
Returns a geometry as an X3D xml formatted node element http://www.web3d.org/standards/number/19776-1. If maxdecimaldigits
(precision) is not specified then defaults to 15.
![]() | |
There are various options for translating PostGIS geometries to X3D since X3D geometry types don't map directly to PostGIS geometry types and some newer X3D types that might be better mappings we have avoided since most rendering tools don't currently support them. These are the mappings we have settled on. Feel free to post a bug ticket if you have thoughts on the idea or ways we can allow people to denote their preferred mappings. Below is how we currently map PostGIS 2D/3D types to X3D types |
The 'options' argument is a bitfield. For PostGIS 2.2+, this is used to denote whether to represent coordinates with X3D GeoCoordinates Geospatial node and also whether to flip the x/y axis. By default, ST_AsX3D
outputs in database form (long,lat or X,Y), but X3D default of lat/lon, y/x may be preferred.
0: X/Y in database order (e.g. long/lat = X,Y is standard database order), default value, and non-spatial coordinates (just regular old Coordinate tag).
1: Flip X and Y. If used in conjunction with the GeoCoordinate option switch, then output will be default "latitude_first" and coordinates will be flipped as well.
2: Output coordinates in GeoSpatial GeoCoordinates. This option will throw an error if geometries are not in WGS 84 long lat (srid: 4326). This is currently the only GeoCoordinate type supported. Refer to X3D specs specifying a spatial reference system.. Default output will be GeoCoordinate geoSystem='"GD" "WE" "longitude_first"'
. If you prefer the X3D default of GeoCoordinate geoSystem='"GD" "WE" "latitude_first"'
use (2 + 1)
= 3
PostGIS Type | 2D X3D Type | 3D X3D Type |
---|---|---|
LINESTRING | not yet implemented - will be PolyLine2D | LineSet |
MULTILINESTRING | not yet implemented - will be PolyLine2D | IndexedLineSet |
MULTIPOINT | Polypoint2D | PointSet |
POINT | outputs the space delimited coordinates | outputs the space delimited coordinates |
(MULTI) POLYGON, POLYHEDRALSURFACE | Invalid X3D markup | IndexedFaceSet (inner rings currently output as another faceset) |
TIN | TriangleSet2D (Not Yet Implemented) | IndexedTriangleSet |
![]() | |
2D geometry support not yet complete. Inner rings currently just drawn as separate polygons. We are working on these. |
Lots of advancements happening in 3D space particularly with X3D Integration with HTML5
There is also a nice open source X3D viewer you can use to view rendered geometries. Free Wrl http://freewrl.sourceforge.net/ binaries available for Mac, Linux, and Windows. Use the FreeWRL_Launcher packaged to view the geometries.
Also check out PostGIS minimalist X3D viewer that utilizes this function and x3dDom html/js open source toolkit.
Availability: 2.0.0: ISO-IEC-19776-1.2-X3DEncodings-XML
Enhanced: 2.2.0: Support for GeoCoordinates and axis (x/y, long/lat) flipping. Look at options for details.
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>
Copy and paste the output of this query to x3d scene viewer and click 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);
Buildings formed by subdividing PostGIS and extrusion
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 — Return a GeoHash representation of the geometry.
text ST_GeoHash(
geometry geom, integer maxchars=full_precision_of_point)
;
Computes a GeoHash representation of a geometry. A GeoHash encodes a geographic Point into a text form that is sortable and searchable based on prefixing. A shorter GeoHash is a less precise representation of a point. It can be thought of as a box that contains the point.
Non-point geometry values with non-zero extent can also be mapped to GeoHash codes. The precision of the code depends on the geographic extent of the geometry.
If maxchars
is not specified, the returned GeoHash code is for the smallest cell containing the input geometry. Points return a GeoHash with 20 characters of precision (about enough to hold the full double precision of the input). Other geometric types may return a GeoHash with less precision, depending on the extent of the geometry. Larger geometries are represented with less precision, smaller ones with more precision. The box determined by the GeoHash code always contains the input feature.
If maxchars
is specified the returned GeoHash code has at most that many characters. It maps to a (possibly) lower precision representation of the input geometry. For non-points, the starting point of the calculation is the center of the bounding box of the geometry.
Disponibilità: 1.4.0
![]() | |
ST_GeoHash requires input geometry to be in geographic (lon/lat) coordinates. |
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
TRUE
if A's 2D bounding box intersects B's 2D bounding box.TRUE
if a geometry's (cached) 2D bounding box intersects a 2D float precision bounding box (BOX2DF).TRUE
if a 2D float precision bounding box (BOX2DF) intersects a geometry's (cached) 2D bounding box.TRUE
if two 2D float precision bounding boxes (BOX2DF) intersect each other.TRUE
if A's n-D bounding box intersects B's n-D bounding box.TRUE
if a geometry's (cached) n-D bounding box intersects a n-D float precision bounding box (GIDX).TRUE
if a n-D float precision bounding box (GIDX) intersects a geometry's (cached) n-D bounding box.TRUE
if two n-D float precision bounding boxes (GIDX) intersect each other.TRUE
if A's bounding box overlaps or is to the left of B's.TRUE
if A's bounding box overlaps or is below B's.TRUE
if A' bounding box overlaps or is to the right of B's.TRUE
if A's bounding box is strictly to the left of B's.TRUE
if A's bounding box is strictly below B's.TRUE
if the coordinates and coordinate order geometry/geography A are the same as the coordinates and coordinate order of geometry/geography B.TRUE
if A's bounding box is strictly to the right of B's.TRUE
if A's bounding box is contained by B's.TRUE
if a geometry's 2D bounding box is contained into a 2D float precision bounding box (BOX2DF).TRUE
if a 2D float precision bounding box (BOX2DF) is contained into a geometry's 2D bounding box.TRUE
if a 2D float precision bounding box (BOX2DF) is contained into another 2D float precision bounding box.TRUE
if A's bounding box overlaps or is above B's.TRUE
if A's bounding box is strictly above B's.TRUE
if A's bounding box contains B's.TRUE
if a geometry's 2D bonding box contains a 2D float precision bounding box (GIDX).TRUE
if a 2D float precision bounding box (BOX2DF) contains a geometry's 2D bonding box.TRUE
if a 2D float precision bounding box (BOX2DF) contains another 2D float precision bounding box (BOX2DF).TRUE
if A's bounding box is the same as B's.&& — Returns TRUE
if A's 2D bounding box intersects B's 2D bounding box.
boolean &&(
geometry A , geometry B )
;
boolean &&(
geography A , geography B )
;
The &&
operator returns TRUE
if the 2D bounding box of geometry A intersects the 2D bounding box of geometry B.
![]() | |
This operand will make use of any indexes that may be available on the geometries. |
Miglioramento: nella versione 2.0.0 è stato introdotto il supporto per le superfici poliedriche.
Availability: 1.5.0 support for geography was introduced.
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) — Returns TRUE
if a geometry's (cached) 2D bounding box intersects a 2D float precision bounding box (BOX2DF).
boolean &<(
geometry A , geometry B )
;
The &&
operator returns TRUE
if the cached 2D bounding box of geometry A intersects the 2D bounding box B, using float precision. This means that if B is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)
![]() | |
This operand is intended to be used internally by BRIN indexes, more than by users. |
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
&&(box2df,geometry) — Returns TRUE
if a 2D float precision bounding box (BOX2DF) intersects a geometry's (cached) 2D bounding box.
boolean &<(
geometry A , geometry B )
;
The &&
operator returns TRUE
if the 2D bounding box A intersects the cached 2D bounding box of geometry B, using float precision. This means that if A is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)
![]() | |
This operand is intended to be used internally by BRIN indexes, more than by users. |
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
&&(box2df,box2df) — Returns TRUE
if two 2D float precision bounding boxes (BOX2DF) intersect each other.
boolean &<(
geometry A , geometry B )
;
The &&
operator returns TRUE
if two 2D bounding boxes A and B intersect each other, using float precision. This means that if A (or B) is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)
![]() | |
This operator is intended to be used internally by BRIN indexes, more than by users. |
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
&&& — Returns TRUE
if A's n-D bounding box intersects B's n-D bounding box.
boolean &&&(
geometry A , geometry B )
;
The &&&
operator returns TRUE
if the n-D bounding box of geometry A intersects the n-D bounding box of geometry B.
![]() | |
This operand will make use of any indexes that may be available on the geometries. |
Disponibilità: 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
&&& — Returns TRUE
if a geometry's (cached) n-D bounding box intersects a n-D float precision bounding box (GIDX).
boolean &<(
geometry A , geometry B )
;
The &&&
operator returns TRUE
if the cached n-D bounding box of geometry A intersects the n-D bounding box B, using float precision. This means that if B is a (double precision) box3d, it will be internally converted to a float precision 3D bounding box (GIDX)
![]() | |
This operator is intended to be used internally by BRIN indexes, more than by users. |
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires 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.
&&& — Returns TRUE
if a n-D float precision bounding box (GIDX) intersects a geometry's (cached) n-D bounding box.
boolean &<(
geometry A , geometry B )
;
The &&&
operator returns TRUE
if the n-D bounding box A intersects the cached n-D bounding box of geometry B, using float precision. This means that if A is a (double precision) box3d, it will be internally converted to a float precision 3D bounding box (GIDX)
![]() | |
This operator is intended to be used internally by BRIN indexes, more than by users. |
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires 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.
&&& — Returns TRUE
if two n-D float precision bounding boxes (GIDX) intersect each other.
boolean &<(
geometry A , geometry B )
;
The &&&
operator returns TRUE
if two n-D bounding boxes A and B intersect each other, using float precision. This means that if A (or B) is a (double precision) box3d, it will be internally converted to a float precision 3D bounding box (GIDX)
![]() | |
This operator is intended to be used internally by BRIN indexes, more than by users. |
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires 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.
&< — Returns TRUE
if A's bounding box overlaps or is to the left of B's.
boolean &<(
geometry A , geometry B )
;
The &<
operator returns TRUE
if the bounding box of geometry A overlaps or is to the left of the bounding box of geometry B, or more accurately, overlaps or is NOT to the right of the bounding box of geometry B.
![]() | |
This operand will make use of any indexes that may be available on the geometries. |
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)
&<| — Returns TRUE
if A's bounding box overlaps or is below B's.
boolean &<|(
geometry A , geometry B )
;
The &<|
operator returns TRUE
if the bounding box of geometry A overlaps or is below of the bounding box of geometry B, or more accurately, overlaps or is NOT above the bounding box of geometry B.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
![]() | |
This operand will make use of any indexes that may be available on the geometries. |
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)
&> — Returns TRUE
if A' bounding box overlaps or is to the right of B's.
boolean &>(
geometry A , geometry B )
;
The &>
operator returns TRUE
if the bounding box of geometry A overlaps or is to the right of the bounding box of geometry B, or more accurately, overlaps or is NOT to the left of the bounding box of geometry B.
![]() | |
This operand will make use of any indexes that may be available on the geometries. |
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)
<< — Returns TRUE
if A's bounding box is strictly to the left of B's.
boolean <<(
geometry A , geometry B )
;
The <<
operator returns TRUE
if the bounding box of geometry A is strictly to the left of the bounding box of geometry B.
![]() | |
This operand will make use of any indexes that may be available on the geometries. |
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)
<<| — Returns TRUE
if A's bounding box is strictly below B's.
boolean <<|(
geometry A , geometry B )
;
The <<|
operator returns TRUE
if the bounding box of geometry A is strictly below the bounding box of geometry B.
![]() | |
This operand will make use of any indexes that may be available on the geometries. |
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)
= — Returns TRUE
if the coordinates and coordinate order geometry/geography A are the same as the coordinates and coordinate order of geometry/geography B.
boolean =(
geometry A , geometry B )
;
boolean =(
geography A , geography B )
;
The =
operator returns TRUE
if the coordinates and coordinate order geometry/geography A are the same as the coordinates and coordinate order of geometry/geography B. PostgreSQL uses the =, <, and > operators defined for geometries to perform internal orderings and comparison of geometries (ie. in a GROUP BY or ORDER BY clause).
![]() | |
Only geometry/geography that are exactly equal in all respects, with the same coordinates, in the same order, are considered equal by this operator. For "spatial equality", that ignores things like coordinate order, and can detect features that cover the same spatial area with different representations, use ST_OrderingEquals or ST_Equals |
![]() | |
This operand will NOT make use of any indexes that may be available on the geometries. For an index assisted exact equality test, combine = with &&. |
Changed: 2.4.0, in prior versions this was bounding box equality not a geometric equality. If you need bounding box equality, use ~= instead.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
SELECT 'LINESTRING(0 0, 0 1, 1 0)'::geometry = 'LINESTRING(1 1, 0 0)'::geometry; ?column? ---------- t (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) -- Nota: il GROUP BY usa lo "=" per confrontare l'equivalenza delle geometrie 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) (1 row) -- 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
>> — Returns TRUE
if A's bounding box is strictly to the right of B's.
boolean >>(
geometry A , geometry B )
;
The >>
operator returns TRUE
if the bounding box of geometry A is strictly to the right of the bounding box of geometry B.
![]() | |
This operand will make use of any indexes that may be available on the geometries. |
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)
@ — Returns TRUE
if A's bounding box is contained by B's.
boolean @(
geometry A , geometry B )
;
The @
operator returns TRUE
if the bounding box of geometry A is completely contained by the bounding box of geometry B.
![]() | |
This operand will make use of any indexes that may be available on the geometries. |
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) — Returns TRUE
if a geometry's 2D bounding box is contained into a 2D float precision bounding box (BOX2DF).
boolean @(
geometry A , geometry B )
;
The @
operator returns TRUE
if the A geometry's 2D bounding box is contained the 2D bounding box B, using float precision. This means that if B is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)
![]() | |
This operand is intended to be used internally by BRIN indexes, more than by users. |
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
@(box2df,geometry) — Returns TRUE
if a 2D float precision bounding box (BOX2DF) is contained into a geometry's 2D bounding box.
boolean @(
geometry A , geometry B )
;
The @
operator returns TRUE
if the 2D bounding box A is contained into the B geometry's 2D bounding box, using float precision. This means that if B is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)
![]() | |
This operand is intended to be used internally by BRIN indexes, more than by users. |
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
@(box2df,box2df) — Returns TRUE
if a 2D float precision bounding box (BOX2DF) is contained into another 2D float precision bounding box.
boolean @(
geometry A , geometry B )
;
The @
operator returns TRUE
if the 2D bounding box A is contained into the 2D bounding box B, using float precision. This means that if A (or B) is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)
![]() | |
This operand is intended to be used internally by BRIN indexes, more than by users. |
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
|&> — Returns TRUE
if A's bounding box overlaps or is above B's.
boolean |&>(
geometry A , geometry B )
;
The |&>
operator returns TRUE
if the bounding box of geometry A overlaps or is above the bounding box of geometry B, or more accurately, overlaps or is NOT below the bounding box of geometry B.
![]() | |
This operand will make use of any indexes that may be available on the geometries. |
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)
|>> — Returns TRUE
if A's bounding box is strictly above B's.
boolean |>>(
geometry A , geometry B )
;
The |>>
operator returns TRUE
if the bounding box of geometry A is strictly above the bounding box of geometry B.
![]() | |
This operand will make use of any indexes that may be available on the geometries. |
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)
~ — Returns TRUE
if A's bounding box contains B's.
boolean ~(
geometry A , geometry B )
;
The ~
operator returns TRUE
if the bounding box of geometry A completely contains the bounding box of geometry B.
![]() | |
This operand will make use of any indexes that may be available on the geometries. |
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) — Returns TRUE
if a geometry's 2D bonding box contains a 2D float precision bounding box (GIDX).
boolean ~(
geometry A , geometry B )
;
The ~
operator returns TRUE
if the 2D bounding box of a geometry A contains the 2D bounding box B, using float precision. This means that if B is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)
![]() | |
This operand is intended to be used internally by BRIN indexes, more than by users. |
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
~(box2df,geometry) — Returns TRUE
if a 2D float precision bounding box (BOX2DF) contains a geometry's 2D bonding box.
boolean ~(
geometry A , geometry B )
;
The ~
operator returns TRUE
if the 2D bounding box A contains the B geometry's bounding box, using float precision. This means that if A is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)
![]() | |
This operand is intended to be used internally by BRIN indexes, more than by users. |
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
~(box2df,box2df) — Returns TRUE
if a 2D float precision bounding box (BOX2DF) contains another 2D float precision bounding box (BOX2DF).
boolean ~(
geometry A , geometry B )
;
The ~
operator returns TRUE
if the 2D bounding box A contains the 2D bounding box B, using float precision. This means that if A is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)
![]() | |
This operand is intended to be used internally by BRIN indexes, more than by users. |
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
~= — Returns TRUE
if A's bounding box is the same as B's.
boolean ~=(
geometry A , geometry B )
;
The ~=
operator returns TRUE
if the bounding box of geometry/geography A is the same as the bounding box of geometry/geography B.
![]() | |
This operand will make use of any indexes that may be available on the geometries. |
Availability: 1.5.0 changed behavior
This function supports Polyhedral surfaces.
![]() | |
This operator has changed behavior in PostGIS 1.5 from testing for actual geometric equality to only checking for bounding box equality. To complicate things it also depends on if you have done a hard or soft upgrade which behavior your database has. To find out which behavior your database has you can run the query below. To check for true equality use ST_OrderingEquals or ST_Equals. |
<-> — Returns the 2D distance between A and B.
double precision <->(
geometry A , geometry B )
;
double precision <->(
geography A , geography B )
;
The <->
operator returns the 2D distance between two geometries. Used in the "ORDER BY" clause provides index-assisted nearest-neighbor result sets. For PostgreSQL below 9.5 only gives centroid distance of bounding boxes and for PostgreSQL 9.5+, does true KNN distance search giving true distance between geometries, and distance sphere for geographies.
![]() | |
This operand will make use of 2D GiST indexes that may be available on the geometries. It is different from other operators that use spatial indexes in that the spatial index is only used when the operator is in the ORDER BY clause. |
![]() | |
Index only kicks in if one of the geometries is a constant (not in a subquery/cte). e.g. 'SRID=3005;POINT(1011102 450541)'::geometry instead of a.geom |
Refer to PostGIS workshop: Nearest-Neighbor Searching for a detailed example.
Enhanced: 2.2.0 -- True KNN ("K nearest neighbor") behavior for geometry and geography for PostgreSQL 9.5+. Note for geography KNN is based on sphere rather than spheroid. For PostgreSQL 9.4 and below, geography support is new but only supports centroid box.
Changed: 2.2.0 -- For PostgreSQL 9.5 users, old Hybrid syntax may be slower, so you'll want to get rid of that hack if you are running your code only on PostGIS 2.2+ 9.5+. See examples below.
Availability: 2.0.0 -- Weak KNN provides nearest neighbors based on geometry centroid distances instead of true distances. Exact results for points, inexact for all other types. Available for 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)
Then the KNN raw answer:
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)
If you run "EXPLAIN ANALYZE" on the two queries you would see a performance improvement for the second.
For users running with PostgreSQL < 9.5, use a hybrid query to find the true nearest neighbors. First a CTE query using the index-assisted KNN, then an exact query to get correct ordering:
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)
|=| — Returns the distance between A and B trajectories at their closest point of approach.
double precision |=|(
geometry A , geometry B )
;
The |=|
operator returns the 3D distance between two trajectories (See ST_IsValidTrajectory). This is the same as ST_DistanceCPA but as an operator it can be used for doing nearest neighbor searches using an N-dimensional index (requires PostgreSQL 9.5.0 or higher).
![]() | |
This operand will make use of ND GiST indexes that may be available on the geometries. It is different from other operators that use spatial indexes in that the spatial index is only used when the operator is in the ORDER BY clause. |
![]() | |
Index only kicks in if one of the geometries is a constant (not in a subquery/cte). e.g. 'SRID=3005;LINESTRINGM(0 0 0,0 0 1)'::geometry instead of a.geom |
Availability: 2.2.0. Index-supported only available for 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)
<#> — Returns the 2D distance between A and B bounding boxes.
double precision <#>(
geometry A , geometry B )
;
The <#>
operator returns distance between two floating point bounding boxes, possibly reading them from a spatial index (PostgreSQL 9.1+ required). Useful for doing nearest neighbor approximate distance ordering.
![]() | |
This operand will make use of any indexes that may be available on the geometries. It is different from other operators that use spatial indexes in that the spatial index is only used when the operator is in the ORDER BY clause. |
![]() | |
Index only kicks in if one of the geometries is a constant e.g. ORDER BY (ST_GeomFromText('POINT(1 2)') <#> geom) instead of g1.geom <#>. |
Availability: 2.0.0 -- KNN only available for 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)
<<->> — Returns the n-D distance between the centroids of A and B bounding boxes.
double precision <<->>(
geometry A , geometry B )
;
The <<->>
operator returns the n-D (euclidean) distance between the centroids of the bounding boxes of two geometries. Useful for doing nearest neighbor approximate distance ordering.
![]() | |
This operand will make use of n-D GiST indexes that may be available on the geometries. It is different from other operators that use spatial indexes in that the spatial index is only used when the operator is in the ORDER BY clause. |
![]() | |
Index only kicks in if one of the geometries is a constant (not in a subquery/cte). e.g. 'SRID=3005;POINT(1011102 450541)'::geometry instead of a.geom |
Availability: 2.2.0 -- KNN only available for PostgreSQL 9.1+
<<#>> — Returns the n-D distance between A and B bounding boxes.
double precision <<#>>(
geometry A , geometry B )
;
The <<#>>
operator returns distance between two floating point bounding boxes, possibly reading them from a spatial index (PostgreSQL 9.1+ required). Useful for doing nearest neighbor approximate distance ordering.
![]() | |
This operand will make use of any indexes that may be available on the geometries. It is different from other operators that use spatial indexes in that the spatial index is only used when the operator is in the ORDER BY clause. |
![]() | |
Index only kicks in if one of the geometries is a constant e.g. ORDER BY (ST_GeomFromText('POINT(1 2)') <<#>> geom) instead of g1.geom <<#>>. |
Availability: 2.2.0 -- KNN only available for PostgreSQL 9.1+
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. |
Changed: 3.0.0 SFCGAL backend removed, GEOS backend supports TINs.
Disponibilità: 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)
ST_Contains — Tests if every point of B lies in A, and their interiors have a point in common
boolean ST_Contains(
geometry geomA, geometry geomB)
;
Returns TRUE if geometry A contains geometry B. A contains B if and only if all points of B lie inside (i.e. in the interior or boundary of) A (or equivalently, no points of B lie in the exterior of A), and the interiors of A and B have at least one point in common.
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 |
Eseguito dal modulo 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_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 inside A (or equivalently, no point of B lies in the the boundary or exterior of A).
A does not properly contain itself, but does contain itself.
Every point of the other geometry is a point of this geometry's interior. The DE-9IM Intersection Matrix for the two geometries matches [T**FF*FF*] used in ST_Relate
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. |
Eseguito dal modulo GEOS.
Availability: 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.
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. |
Eseguito dal modulo GEOS
Availability: 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.
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. |
Eseguito dal modulo 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.
Availability: 1.5 - support for geography was introduced.
Availability: 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 cross", 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. Additionally, the intersection of the two geometries must not equal either of the source geometries. Otherwise, it returns false
.
In mathematical terms, this is:
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
For Point/Point and Area/Area situations this predicate returns false
.
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 similiar 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 )
;
Overlaps, Touches, Within all imply geometries are not spatially disjoint. If any of the aforementioned returns true, then the geometries are not spatially disjoint. Disjoint implies false for spatial intersection.
![]() | |
Enhanced: 3.0.0 enabled support for |
Eseguito dal modulo 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
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 "spatially equal". Use this for a 'better' answer than '='. Note by spatially equal we mean ST_Within(A,B) = true and ST_Within(B,A) = true and also mean ordering of points can be different but represent the same geometry structure. 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).
![]() | |
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
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 )
;
Compares two geometries and returns true
if they 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).
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)
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 LINESTRING
s.
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(ST_GeomFromText('LINESTRING(0 0, 10 10)'), ST_GeomFromText('LINESTRING(0 0, 5 5, 10 10)')); st_orderingequals ----------- f (1 row) SELECT ST_OrderingEquals(ST_GeomFromText('LINESTRING(0 0, 10 10)'), ST_GeomFromText('LINESTRING(0 0, 0 0, 10 10)')); st_orderingequals ----------- t (1 row) SELECT ST_OrderingEquals(ST_Reverse(ST_GeomFromText('LINESTRING(0 0, 10 10)')), ST_GeomFromText('LINESTRING(0 0, 0 0, 10 10)')); st_orderingequals ----------- f (1 row)
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 relationship is symmetric and irreflexive.
![]() | |
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 |
Eseguito dal modulo 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 evalation. |
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
Eseguito dal modulo 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 dupl