Manuale di PostGIS 3.6.0dev

DEV (Thu 03 Oct 2024 08:35:42 AM UTC rev. 4fcfd0f )

Il gruppo di sviluppo di PostGIS

Abstract

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.6.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.


Table of Contents

Chapter 1. Introduzione

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à.

Il gruppo di sviluppo di PostGIS pianifica l e migliorie di necessarie a supportare meglio importanti funzionalita' GIS nelle aree degli standard spaziali OGC e SQL/MM, costrutti topologici avanzati (coperture, superfici, reti), sorgenti di dati per le interfacce utente da scrivania per visualizzare e modificare i dati GIS, e sistemi di accesso via web.

1.1. Comitato di Coordinamento del Progetto

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.

Raúl Marín Rodríguez

Supporto di MVT, risoluzione bachi, migliorie nelle performance e nella stabilità, cura di GitHub, allineamento di PostGIS con i rilasci di PostgreSQL

Regina Obe

CI and website maintenance, Windows production and experimental builds, documentation, alignment of PostGIS with PostgreSQL releases, X3D support, TIGER geocoder support, management functions.

Darafei Praliaskouski

Index improvements, bug fixing and geometry/geography function improvements, SFCGAL, raster, GitHub curation, and ci maintenance.

Paul Ramsey (Coordinatore)

Co-fondatore del progetto PostGIS. Correzione di bug generali, supporto della geografia, supporto degli indici geografici e geometrici (2D, 3D, indice nD e qualsiasi indice spaziale), strutture interne della geometria sottostante, integrazione delle funzionalità GEOS e allineamento con le release GEOS, allineamento di PostGIS con le release PostgreSQL, loader/dumper e loader GUI Shapefile.

Sandro Santilli

Bug fixes and maintenance, ci maintenance, git mirror management, management functions, integration of new GEOS functionality and alignment with GEOS releases, topology support, and raster framework and low level API functions.

1.2. Principali collaboratori attuali

Nicklas Avén

Miglioramenti e aggiunte alle funzioni di distanza (comprese le funzioni di distanza e relazione 3D), formato di output Tiny WKB (TWKB) e supporto generale agli utenti.

Loïc Bartoletti

SFCGAL enhancements and maintenance and ci support

Dan Baston

Aggiunte di funzioni di clustering geometrico, miglioramenti di altri algoritmi geometrici, miglioramenti di GEOS e supporto generale agli utenti.

Martin Davis

Miglioramenti e documentazione GEOS

Björn Harrtell

MapBox Vector Tile, GeoBuf, and Flatgeobuf functions. Gitea testing and GitLab experimentation.

Aliaksandr Kalenik

Elaborazione della geometria, gist PostgreSQL, correzione di bug generali

1.3. Principali collaboratori passati

Bborie Park

Precedente membro del PSC. Sviluppo di raster, integrazione con GDAL, caricatore di raster, supporto agli utenti, correzione di bug generali, test su vari sistemi operativi (Slackware, Mac, Windows e altri).

Mark Cave-Ayland

Precedente membro del PSC. Ha coordinato la correzione di bug e la manutenzione, la selettività e il binding degli indici spaziali, il caricatore/dumper e il caricatore di GUI Shapefile, l'integrazione di nuovi miglioramenti e nuove funzioni.

Jorge Arévalo

Sviluppo raster, supporto per il driver GDAL, loader

Olivier Courtin

Funzioni di input e ouput XML (KML,GML)/GeoJSON, supporto 3D e correzione di bug.

Chris Hodgson

Ex-membro del comitato di coordinamento. Sviluppo generale, manutenzione del sito e del buildbot, gestione dell'incubazione OSGeo

Mateusz Loskot

Supporto CMake per PostGIS, ha sviluppato il loader raster originale in python e le funzioni API raster di basso livello.

Kevin Neufeld

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.

Dave Blasby

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.

Jeff Lounsbury

Sviluppo iniziale del loader/dumper per gli Shapefile. Attualmente rappresentante di Project Owner di PostGIS.

Mark Leslie

Continuo sviluppo e manutenzione delle funzioni di base. Supporto avanzanto per le curve. Interfaccia grafica per il loader di Shapefile.

Pierre Racine

Architetto dell'implementazione raster di PostGIS. Architettura generale dei raster, prototipazione, supporto alla programmazione.

David Zwarg

Sviluppo raster (principalmente funzioni analitiche di map algebra)

1.4. Altri collaboratori

Collaboratori individuali

Alex BodnaruGino LucreziMaxime Guillaud
Alex MayrhoferGreg TroxelMaxime van Noppen
Andrea PeriGuillaume LelargeMaxime Schoemans
Andreas Forø TollefsenGiuseppe BroccoloMichael Fuhr
Andreas NeumannHan WangMike Toews
Andrew GierthHans LemuetNathan Wagner
Anne GhislaHaribabu KommiNathaniel Clay
Antoine BajoletHavard TveiteNikita Shulga
Arthur LesuisseIIDA TetsushiNorman Vine
Artur ZakirovIngvild NystuenPatricia Tozer
Barbara PhillipotJackie LengRafal Magda
Ben JubbJames AddisonRalph Mason
Bernhard ReiterJames MarcaRémi Cura
Björn EsserJan KatinsRichard Greenwood
Brian HamlinJan TojnarRobert Coup
Bruce RindahlJason SmithRoger Crew
Bruno Wolff IIIJeff AdamsRon Mayer
Bryce L. NordgrenJelte FennemaSam Peters
Carl AndersonJim JonesSebastiaan Couwenberg
Charlie SavageJoe ConwaySergei Shoulbakov
Chris MayoJonne SavolainenSergey Fedoseev
Christian SchroederJose Carlos Martinez LlariShinichi Sugiyama
Christoph BergJörg HabenichtShoaib Burq
Christoph Moench-TegederJulien RouhaudSilvio Grosso
Dane SpringmeyerKashif RasulStefan Corneliu Petrea
Dapeng WangKlaus FoersterSteffen Macke
Daryl HerzmannKris JurkaStepan Kuzmin
Dave FuhryLaurenz AlbeStephen Frost
David GarnierLars RoessigerSteven Ottens
David SkeaLeo HsuTalha Rizwan
David TecherLoic DacharyTeramoto Ikuhiro
Dian M FayLuca S. PercichTom Glancy
Dmitry VasilyevLucas C. Villa RealTom van Tilburg
Eduin CarrilloMaria Arias de ReynaVictor Collod
Esteban ZimanyiMarc DucobuVincent Bre
Eugene AntimirovMark SondheimVincent Mora
Even RouaultMarkus SchaberVincent Picavet
Florian WeimerMarkus WannerVolf Tomáš
Frank WarmerdamMatt AmosZuo Chenwei
George SilvaMatt Bretl 
Gerald FenoyMatthias Bay 

Sponsor aziendali

Queste sono realtà aziendali o altre istituzioni che hanno contribuito al progetto PostGIS sotto forma di tempo sviluppatore, hosting o finanziamento economico

Campagne di finanziamento diffuso

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.

Librerie di supporto importanti

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.

La libreria di proiezioni cartografiche PROJ

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.

Chapter 2. Installazione PostGIS

Questo capitolo elenca i passi necessari all'installazione di PostGIS.

2.1. Versione sintetica

Per compilare, assumendo di avere tutte le dipendenze nel percorso di ricerca:

tar -xvzf postgis-3.6.0dev.tar.gz
cd postgis-3.6.0dev
./configure
make
make install

Una volta installato PostGIS, bisogna abilitarlo (Section 3.3, “Creazione di database spaziali”) o aggiornarlo (Section 3.4, “Aggiornamento dei database spaziali”) individualmente nei database in cui si vuole usare.

2.2. Compilazione e installazione da sorgente

[Note]

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.

Questa sezione include istruzioni generali per la compilazione; se si sta compilando per Windows o altri sistemi operativi, si può trovare un aiuto più dettagliato in Guide di compilazione fornite dagli utenti di PostGIS e PostGIS Dev Wiki.

I pacchetti precostruiti per vari sistemi operativi sono elencati in Pacchetti precostruiti PostGIS

Se siete utenti di Windows, potete ottenere le build stabili tramite Stackbuilder o il sito di download di PostGIS Windows Abbiamo anche c build sperimentali di Windows molto all'avanguardia che vengono create di solito una o due volte alla settimana o ogni volta che succede qualcosa di interessante. È possibile utilizzarle per sperimentare le versioni in corso di PostGIS

Il modulo PostGIS è un'estensione del server backend PostgreSQL. Come tale, PostGIS 3.6.0dev richiede l'accesso completo alle intestazioni del server PostgreSQL per essere compilato. Può essere compilato con le versioni di PostgreSQL 12 - 17. Le versioni precedenti di PostgreSQL non sono supportate.

Se non avete ancora installato PostgreSQL, consultate le guide all'installazione di PostgreSQL. https://www.postgresql.org .

[Note]

Per le funzionalità legate a GEOS, quando installate PostgreSQL è possibile che dobbiate esplicitamente linkare PostgreSQL con la libreria C++ standard:

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

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.

2.2.1. Reperire il codice sorgente

Recuperare l'archivio sorgente di PostGIS dal sito web dei download https://postgis.net/stuff/postgis-3.6.0dev.tar.gz

wget https://postgis.net/stuff/postgis-3.6.0dev.tar.gz
tar -xvzf postgis-3.6.0dev.tar.gz
cd postgis-3.6.0dev

Questo passaggio creerà una cartella denominata postgis-3.6.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
    

Passare alla cartella postgis appena creata per continuare l'installazione.

./configure

2.2.2. Requisiti di installazione

PostGIS necessita dei seguenti requisiti per la compilazione e l'utilizzo:

Necessari

  • PostgreSQL 12 - 17. È necessaria un'installazione completa di PostgreSQL (comprese le intestazioni del server). PostgreSQL è disponibile presso https://www.postgresql.org .

    Per una matrice di supporto completa di PostgreSQL / PostGIS e per la matrice di supporto di PostGIS/GEOS, consultare 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.

  • Libreria di riproiezione Proj. È necessario Proj 6.1 o superiore. La libreria Proj viene utilizzata per fornire il supporto alla riproiezione delle coordinate all'interno di PostGIS. Proj è disponibile per il download da https://proj.org/ .

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

  • LibXML2, versione 2.5.x o superiore. LibXML2 è attualmente utilizzato in alcune funzioni di importazione (ST_GeomFromGML e ST_GeomFromKML). LibXML2 è disponibile per il download da https://gitlab.gnome.org/GNOME/libxml2/-/releases.

  • JSON-C, versione 0.9 o superiore. JSON-C viene attualmente utilizzato per importare GeoJSON tramite la funzione ST_GeomFromGeoJson. JSON-C è disponibile per il download da https://github.com/json-c/json-c/releases/.

  • GDAL, version 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-opzionale) solo se non si vuole il raster si può omettere. Assicurarsi inoltre di abilitare i driver che si desidera utilizzare come descritto 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, 1.4.1 or higher is required and 1.5.0+ is needed to be able to use all functionality. SFCGAL can be used to provide additional 2D and 3D advanced analysis functions to PostGIS cf Chapter 8, SFCGAL Functions Reference. 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://sfcgal.org) https://gitlab.com/sfcgal/SFCGAL/.

  • Per costruire Section 12.1, “Standardizzatore di indirizzi” è necessario anche PCRE http://www.pcre.org (che generalmente è già installato sui sistemi nix). Section 12.1, “Standardizzatore di indirizzi” sarà costruito automaticamente se rileva una libreria PCRE o se si passa un --with-pcre-dir=/path/to/pcre valido durante la configurazione.

  • Per abilitare ST_AsMVT sono necessari la libreria protobuf-c 1.1.0 o superiore (per l'uso) e il compilatore protoc-c (per la costruzione). Inoltre, è necessario pkg-config per verificare la versione minima corretta di protobuf-c. Vedere protobuf-c. Per impostazione predefinita, Postgis utilizza Wagyu per convalidare più velocemente i poligoni MVT, che richiede un compilatore c++11. Utilizzerà CXXFLAGS e lo stesso compilatore dell'installazione di PostgreSQL. Per disabilitare questa funzione e utilizzare invece GEOS, utilizzare l'opzione --without-wagyu durante la fase di configurazione.

  • 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/ .

2.2.3. Configurazione della compilazione

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.

--with-library-minor-version

A partire da PostGIS 3.0, i file di libreria generati per impostazione predefinita non avranno più la versione minore come parte del nome del file. Questo significa che tutte le librerie di PostGIS 3 finiranno con postgis-3. Questo è stato fatto per rendere più semplice l'aggiornamento di pg_upgrade, con l'inconveniente di poter installare una sola versione di PostGIS 3 nel proprio server. Per ottenere il vecchio comportamento dei file che includono la versione minore: per esempio postgis-3.0 aggiungere questo switch alla dichiarazione configure.

--prefix=PREFIX

Questa è la posizione in cui verranno installati gli eseguibili del caricatore PostGIS e le librerie condivise. Per impostazione predefinita, questo percorso è lo stesso dell'installazione di PostgreSQL rilevata.

[Caution]

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.

--with-pgconfig=FILE

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.

--with-gdalconfig=FILE

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.

--with-geosconfig=FILE

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.

--with-xml2config=FILE

LibXML è la libreria necessaria per eseguire processi GeomFromKML/GML. Normalmente si trova se è installata libxml, ma se non lo è o se si vuole utilizzare una versione specifica, è necessario indicare a PostGIS uno specifico file xml2-config confi per consentire alle installazioni software di individuare la directory di installazione di LibXML. Usare questo parametro (>--with-xml2config=/path/to/xml2-config) per specificare manualmente una particolare installazione di LibXML su cui PostGIS si baserà.

--with-projdir=DIR

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.

--with-libiconv=DIR

Cartella di installazione di iconv.

--with-jsondir=DIR

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.

--with-pcredir=DIR

PCRE è una libreria di espressioni regolari compatibile con Perl con licenza BSD, richiesta dall'estensione address_standardizer. Usare questo parametro (--with-pcredir=/path/to/pcredir) per specificare manualmente una particolare directory di installazione di PCRE che PostGIS compilerà.

--with-gui

Compilare l'interfaccia grafica per l'importazione di dati (richiede GTK+2.0). Questo passaggio creerà shp2pgsql-gui, interfaccia grafica per shp2pgsql.

--without-raster

Compilazione senza supporto raster.

--without-topology

Disabilita il supporto per la topologia. Non esiste una libreria corrispondente, poiché tutta la logica necessaria per la topologia si trova nella libreria postgis-3.6.0dev.

--with-gettext=no

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.

--with-sfcgal=PATH

Per impostazione predefinita, PostGIS non si installa con il supporto di sfcgal senza questo interruttore. PATH è un argomento opzionale che consente di specificare un PATH alternativo a sfcgal-config.

--without-phony-revision

Disabilita l'aggiornamento di postgis_revision.h per adattarlo all'HEAD corrente del repository git.

[Note]

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.

2.2.4. Compilazione

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."

A partire da PostGIS v1.4.0, tutte le funzioni hanno commenti generati dalla documentazione. Se si desidera installare questi commenti nei database spaziali in un secondo momento, eseguire il comando che richiede docbook. Il file postgis_comments.sql e gli altri file di commento del pacchetto raster_comments.sql, topology_comments.sql sono anch'essi contenuti nella distribuzione tar.gz nella cartella doc, quindi non è necessario creare commenti se si installa dal tar. I commenti sono inclusi anche nell'installazione di CREATE EXTENSION.

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

2.2.5. Compilazione e installazione delle estensioni PostGIS

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.

Le estensioni dovrebbero essere create automaticamente come parte del processo di installazione di make. Se necessario, si possono creare dalle cartelle delle estensioni o copiare i file se servono 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
[Note]

make check usa psql per eseguire i test e come tale può usare variabili d'ambiente psql. Quelle comuni utili da sovrascrivere sono PGUSER, PGPORT e PGHOST. Fare riferimento a variabili d'ambiente psql

I file di estensione saranno sempre gli stessi per la stessa versione di PostGIS e PostgreSQL, indipendentemente dal sistema operativo, quindi è possibile copiare i file di estensione da un sistema operativo all'altro, purché i binari di PostGIS siano già installati sui 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 fatto ciò, si dovrebbe vedere postgis, postgis_topology come estensioni disponibili in PgAdmin -> estensioni.

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.6.0dev         | 3.6.0dev
 address_standardizer_data_us | 3.6.0dev         | 3.6.0dev
 postgis                      | 3.6.0dev         | 3.6.0dev
 postgis_raster               | 3.6.0dev         | 3.6.0dev
 postgis_sfcgal               | 3.6.0dev         |
 postgis_tiger_geocoder       | 3.6.0dev         | 3.6.0dev
 postgis_topology             | 3.6.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 è possibile vedere quali versioni sono installate e anche quali schemi sono installati.

\connect mygisdb
\x
\dx postgis*
List of installed extensions
-[ RECORD 1 ]-------------------------------------------------
Name        | postgis
Version     | 3.6.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.6.0dev
Schema      | tiger
Description | PostGIS tiger geocoder and reverse geocoder
-[ RECORD 4 ]-------------------------------------------------
Name        | postgis_topology
Version     | 3.6.0dev
Schema      | topology
Description | PostGIS topology spatial types and functions
[Warning]

Per le tabelle delle estensioni spatial_ref_sys, layer e topology non è possibile eseguire un backup esplicito. Il backup può essere eseguito solo quando viene fatto il backup delle corrispondenti estensioni postgis o postgis_topology, il che pare avvenga solamente quando eseguite un backup dell'intero database. Alla versione 2.0.1, quando viene eseguito il backup del database, gli unici oggetti di cui viene fatta copia sono i record srid non facenti parte di PostGIS. Pertanto non modificare gli SRID facenti parte dell'installazione, aspettandovi poi di trovare le vostre modiche nel backup. Se ci sono problemi, aprite un ticket. Neanche delle strutture delle tabelle delle estensioni viene eseguito un backup, dato che sono create con CREATE EXTENSION, e si presume che siano le stesse per una data versione dell'estensione. Questo comportamento è inserito nell'attuale modello delle estensioni, per cui non c'è molto che l'utente può fare.

Se avete installato 3.6.0dev, senza usare il nostro meraviglioso sistema di estensioni, potete cambiarlo in un sistema basato sulle estensioni eseguendo i comandi seguenti per impacchettare le funzioni nelle rispettive estensioni. L'installazione con `unpackaged` è stata rimossa in PostgreSQL 13, quindi si consiglia di passare a una compilazione con estensione prima di aggiornare a 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;

2.2.6. Test

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.

[Note]

Se avete configurato PostGIS utilizzando percorsi non standard per PostgreSQL, GEOS o Proj, potreste dover aggiungere il percorso di queste librerie nella variabile di ambiente LD_LIBRARY_PATH.

[Caution]

Attualmente il comando make check fa riferimento alle variabili di ambiente PATH e PGPORT nello svolgimento dei controlli - e non utilizza la versione PostgreSQL che può essere stata specificata nella configurazione con il parametro --with-pgconfig. Perciò assicuratevi che la vostra variabile PATH corrisponda all'installazione di PostgreSQL rilevata durante al configurazione, o preparatevi ad affrontare una serie di grattacapi.

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

Le estensioni postgis_tiger_geocoder e address_standardizer attualmente supportano solo l'installcheck standard di PostgreSQL. Per testarle, usare il seguente comando. Nota: il make install non è necessario se si è già eseguito il make install nella cartella principale del codice di PostGIS.

Per address_standardizer:

cd extensions/address_standardizer
make install
make installcheck
          

L'output dovrebbe essere simile a:

============== 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.
=====================

Per il geocoder tiger, assicurarsi di avere le estensioni postgis e fuzzystrmatch disponibili nella propria istanza PostgreSQL. I test di address_standardizer verranno eseguiti anche se si è costruito postgis con il supporto di address_standardizer:

cd extensions/postgis_tiger_geocoder
make install
make installcheck
          

L'output dovrebbe essere simile a:

============== 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.
=====================

2.2.7. Installazione

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

[Note]

postgis_comments.sql, raster_comments.sql, e topology_comments.sql sono separati dai tipici obiettivi per il build e per l'installazione, dato che hanno una ulteriore dipendenza da xsltproc.

2.3. Installazione e utilizzo dello standardizzatore di indirizzi

L'estensione address_standardizer era un pacchetto separato che doveva essere scaricato separatamente. A partire da PostGIS 2.2, è ora inclusa nel pacchetto. Per ulteriori informazioni su address_standardize, su cosa fa e su come configurarlo per le proprie esigenze, fare riferimento a Section 12.1, “Standardizzatore di indirizzi”.

Questo standardizzatore può essere usato in combinazione con l'estensione del geocodificatore PostGIS packaged tiger, in sostituzione di Normalize_Address, di cui si è parlato. Per utilizzarlo come sostituto, fare riferimento a Section 2.4.2, “Utilizzo dell'estensione Address Standardizer con il geocoder Tiger”. È anche possibile utilizzarlo come elemento costitutivo per il proprio geocoder o per standardizzare gli indirizzi per facilitarne il confronto.

Lo standardizzatore di indirizzi si basa su PCRE, che di solito è già installato su molti sistemi Nix, ma si può scaricare l'ultimo all'indirizzo: http://www.pcre.org. Se durante Section 2.2.3, “Configurazione della compilazione” viene trovato PCRE, l'estensione address standardizer verrà automaticamente compilata. Se invece si vuole usare un'installazione personalizzata di pcre, passare a configurare --with-pcredir=/path/to/pcre, dove /path/to/pcre è la cartella principale per le directory include e lib di pcre.

Per gli utenti di Windows, il bundle PostGIS 2.1+ è già confezionato con address_standardizer, quindi non è necessario compilare e si può passare direttamente al passo CREATE EXTENSION.

Una volta effettuata l'installazione, è possibile collegarsi al database ed eseguire l'SQL:

CREATE EXTENSION address_standardizer;

Il seguente test non richiede regole, gaz o tabelle lex

SELECT num, street, city, state, zip
 FROM parse_address('1 Devonshire Place PH301, Boston, MA 02109');

L'uscita dovrebbe essere

num |         street         |  city  | state |  zip
-----+------------------------+--------+-------+-------
 1   | Devonshire Place PH301 | Boston | MA    | 02109

2.4. Installazione, aggiornamento di Tiger Geocoder e caricamento dei dati

Extra come Tiger geocoder potrebbero non essere presenti nella distribuzione di PostGIS. Se manca l'estensione tiger geocoder o se si desidera una versione più recente di quella in dotazione, utilizzare i file share/extension/postgis_tiger_geocoder.* dai pacchetti della sezione Windows Unreleased Versions per la propria versione di PostgreSQL. Sebbene questi pacchetti siano per Windows, i file di estensione postgis_tiger_geocoder funzionano su qualsiasi sistema operativo, poiché l'estensione è solo SQL/plpgsql.

2.4.1. Tiger Geocoder Abilitazione del database PostGIS

  1. Queste indicazioni presuppongono che l'installazione di PostgreSQL abbia già installato l'estensione postgis_tiger_geocoder.

  2. Collegarsi al database tramite psql o pgAdmin o un altro strumento ed eseguire i seguenti comandi SQL. Si noti che se si sta installando in un database che ha già postgis, non è necessario eseguire il primo passo. Se l'estensione fuzzystrmatch è già installata, non è necessario eseguire nemmeno il secondo passaggio.

    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;

    Se avete già installato l'estensione postgis_tiger_geocoder e volete solo aggiornare all'ultima versione:

    ALTER EXTENSION postgis UPDATE;
    ALTER EXTENSION postgis_tiger_geocoder UPDATE;

    Se sono state apportate voci o modifiche personalizzate a tiger.loader_platform e tiger.loader_variables, potrebbe essere necessario aggiornarle.

  3. Per confermare che l'installazione funziona correttamente, eseguire questo sql nel database:

    SELECT na.address, na.streetname,na.streettypeabbrev, na.zip
            FROM normalize_address('1 Devonshire Place, Boston, MA 02109') AS na;

    Che dovrebbe produrre

    address | streetname | streettypeabbrev |  zip
    ---------+------------+------------------+-------
               1 | Devonshire | Pl               | 02109
  4. Creare un nuovo record nella tabella tiger.loader_platform con i percorsi degli eseguibili e del server.

    Quindi, per esempio, per creare un profilo chiamato debbie che segue la convenzione sh. Si dovrebbe fare:

    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';

    Quindi modificare i percorsi nella colonna declare_sect in modo da adattarli ai percorsi di pg, unzip, shp2pgsql, psql, ecc. di Debbie.

    Se non si modifica la tabella loader_platform, essa conterrà solo le posizioni comuni degli elementi e si dovrà modificare lo script generato dopo che è stato generato.

  5. A partire da PostGIS 2.4.1, la fase di caricamento dell'area di tabulazione del codice Zip a 5 cifre zcta5 è stata rivista per caricare i dati zcta5 correnti e fa parte di Loader_Generate_Nation_Script quando è abilitata. È disattivato per impostazione predefinita perché richiede molto tempo per essere caricato (da 20 a 60 minuti), occupa molto spazio su disco e non viene usato spesso.

    Per attivarla, procedere come segue:

    UPDATE tiger.loader_lookuptables SET load = true WHERE table_name = 'zcta520';

    Se presente, la funzione Geocode può utilizzarla se viene aggiunto un filtro di delimitazione per limitare gli zip a quel confine. La funzione Reverse_Geocode lo utilizza se l'indirizzo restituito manca di un CAP, cosa che spesso accade con la geocodifica inversa delle autostrade.

  6. Creare una cartella chiamata gisdata nella root del server o sul pc locale se si dispone di una connessione di rete veloce al server. In questa cartella verranno scaricati ed elaborati i file tigre. Se non si è soddisfatti di avere la cartella nella radice del server o semplicemente si vuole cambiare la cartella di staging, modificare il campo staging_fold nella tabella tiger.loader_variables.

  7. Creare una cartella denominata temp nella cartella gisdata o dove è stata designata la cartella staging_fold. Questa sarà la cartella in cui il caricatore estrarrà i dati della tigre scaricati.

  8. Eseguire quindi la funzione Loader_Generate_Nation_Script SQL assicurandosi di utilizzare il nome del profilo personalizzato e copiare lo script in un file .sh o .bat. Quindi, per esempio, per costruire il carico della nazione:

    psql -c "SELECT Loader_Generate_Nation_Script('debbie')" -d geocoder -tA > /gisdata/nation_script_load.sh
  9. Eseguire gli script da riga di comando generati per il caricamento della nazione.

    cd /gisdata
    sh nation_script_load.sh
  10. Dopo aver eseguito lo script nazionale, si dovrebbero avere tre tabelle nello schema tiger_data e dovrebbero essere riempite di dati. Per confermarlo, eseguire le seguenti query da psql o pgAdmin

    SELECT count(*) FROM tiger_data.county_all;
    count
    -------
      3235
    (1 row)
    SELECT count(*) FROM tiger_data.state_all;
    count
    -------
        56
    (1 row)
    

    This will only have data if you marked zcta5 to be loaded

    SELECT count(*) FROM tiger_data.zcta5_all;
    count
    -------
      33931
    (1 row)
    
  11. Per impostazione predefinita, le tabelle corrispondenti a bg, tract, tabblock20 non vengono caricate. Queste tabelle non sono utilizzate dal geocodificatore, ma sono usate da molti per le statistiche sulla popolazione. Se si desidera caricarle come parte dei carichi di stato, eseguire la seguente istruzione per abilitarle.

    UPDATE tiger.loader_lookuptables SET load = true WHERE load = false AND lookup_name IN('tract', 'bg', 'tabblock20');

    In alternativa, è possibile caricare solo queste tabelle dopo aver caricato i dati di stato utilizzando il metodo Loader_Generate_Census_Script

  12. Per ogni stato per cui si desidera caricare i dati, generare uno script di stato Loader_Generate_Script.

    [Warning]

    NON generare lo script dello stato prima di aver caricato i dati della nazione, perché lo script dello stato utilizza l'elenco delle contee caricato dallo script della nazione.

  13. psql -c "SELECT Loader_Generate_Script(ARRAY['MA'], 'debbie')" -d geocoder -tA > /gisdata/ma_load.sh
  14. Eseguire gli script da riga di comando generati.

    cd /gisdata
    sh ma_load.sh
  15. Una volta terminato il caricamento di tutti i dati o in un punto di arresto, è buona norma analizzare tutte le tabelle delle tigri per aggiornare le statistiche (includere le statistiche ereditate)

    SELECT install_missing_indexes();
    vacuum (analyze, verbose) tiger.addr;
    vacuum (analyze, verbose) tiger.edges;
    vacuum (analyze, verbose) tiger.faces;
    vacuum (analyze, verbose) tiger.featnames;
    vacuum (analyze, verbose) tiger.place;
    vacuum (analyze, verbose) tiger.cousub;
    vacuum (analyze, verbose) tiger.county;
    vacuum (analyze, verbose) tiger.state;
    vacuum (analyze, verbose) tiger.zcta5;
    vacuum (analyze, verbose) tiger.zip_lookup_base;
    vacuum (analyze, verbose) tiger.zip_state;
    vacuum (analyze, verbose) tiger.zip_state_loc;

2.4.2. Utilizzo dell'estensione Address Standardizer con il geocoder Tiger

Una delle tante lamentele degli utenti è la funzione di normalizzazione degli indirizzi Normalize_Address che normalizza un indirizzo per la preparazione prima della geocodifica. Il normalizzatore è tutt'altro che perfetto e cercare di correggere le sue imperfezioni richiede una grande quantità di risorse. Per questo motivo ci siamo integrati con un altro progetto che ha un motore di normalizzazione degli indirizzi molto migliore. Per usare questo nuovo address_standardizer, si deve compilare l'estensione come descritto in Section 2.3, “Installazione e utilizzo dello standardizzatore di indirizzi” e installarla come estensione nel database.

Una volta installata questa estensione nello stesso database in cui è stato installato postgis_tiger_geocoder, è possibile utilizzare Pagc_Normalize_Address al posto di Normalize_Address. Questa estensione è agnostica rispetto a tiger, quindi può essere utilizzata con altre fonti di dati come gli indirizzi internazionali. L'estensione tiger geocoder viene fornita con le sue versioni personalizzate di rules table ( tiger.pagc_rules), gaz table (tiger.pagc_gaz) e lex table (tiger.pagc_lex). Queste possono essere aggiunte e aggiornate per migliorare l'esperienza di standardizzazione in base alle proprie esigenze.

2.4.3. Strumenti necessari per il caricamento dei dati Tiger

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

Se si effettua l'aggiornamento da tiger_2010, è necessario generare ed eseguire prima Drop_Nation_Tables_Generate_Script. Prima di caricare i dati degli stati, è necessario caricare i dati dell'intera nazione, cosa che si fa con Loader_Generate_Nation_Script. Loader_Generate_Nation_Script è un'operazione che va eseguita una sola volta per l'aggiornamento (dai dati del censimento di tiger dell'anno precedente) e per le nuove installazioni.

Per caricare i dati degli stati, fare riferimento a Loader_Generate_Script per generare uno script di caricamento dei dati per la propria piattaforma per gli stati desiderati. Si noti che è possibile installare questi script in modo frammentario. Non è necessario caricare tutti gli stati desiderati in una volta sola. È possibile caricarli man mano che se ne ha bisogno.

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

2.4.4. Aggiornamento dell'installazione e dei dati di Tiger Geocoder

Per prima cosa aggiornare l'estensione postgis_tiger_geocoder come segue:

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');

Fare riferimento a Section 2.4.1, “Tiger Geocoder Abilitazione del database PostGIS” per le istruzioni su come eseguire lo script di generazione. Questa operazione deve essere eseguita una sola volta.

[Note]

È possibile avere un mix di tabelle di stato di anni diversi e aggiornare ogni stato separatamente. Prima di aggiornare uno stato, è necessario eliminare le tabelle di stato dell'anno precedente per quello stato utilizzando Drop_State_Tables_Generate_Script.

2.5. Problemi comuni durante l'installazione

Quando l'installazione o l'aggiornamento non vanno come previsto, diverse cose vanno controllate.

  1. 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

  2. Se l'aggiornamento non funziona, assicuratevi di eseguire il ripristino in un database che abbia già PostGIS installato.

    SELECT postgis_full_version();

Verificare anche che configure abbia rilevato correttamente la posizione e la versione di PostgreSQL, della libreria Proj e della libreria GEOS.

  1. 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.

Chapter 3. Amministrazione di PostGIS

3.1. Messa a punto delle prestazioni

La messa a punto delle prestazioni di PostGIS è simile a quella di qualsiasi altro carico di lavoro di PostgreSQL. L'unica considerazione aggiuntiva è che le geometrie e i raster sono solitamente di grandi dimensioni, quindi le ottimizzazioni relative alla memoria hanno generalmente un impatto maggiore su PostGIS rispetto ad altri tipi di query PostgreSQL.

Per informazioni generali sull'ottimizzazione di PostgreSQL, consultare Tuning your PostgreSQL Server.

Per PostgreSQL 9.4+ la configurazione può essere impostata a livello di server senza toccare postgresql.conf o postgresql.auto.conf usando il comando ALTER SYSTEM.

ALTER SYSTEM SET work_mem = '256MB';
-- this forces non-startup configs to take effect for new connections
SELECT pg_reload_conf();
-- show current setting value
-- use SHOW ALL to see all settings
SHOW work_mem;

Oltre alle impostazioni di Postgres, PostGIS ha alcune impostazioni personalizzate che sono elencate in Section 7.22, “Grand Unified Custom Variables (GUCs)”.

3.1.1. Avviamento

Queste impostazioni sono configurate in postgresql.conf:

constraint_exclusion

  • Predefinito: partition

  • Questo è generalmente usato per il partizionamento delle tabelle. L'impostazione predefinita è "partition", ideale per PostgreSQL 8.4 e successivi, in quanto costringe il pianificatore ad analizzare le tabelle per la considerazione dei vincoli solo se si trovano in una gerarchia ereditata, senza penalizzare il pianificatore in caso contrario.

shared_buffers

  • Predefinito: ~128MB in PostgreSQL 9.6

  • Impostate circa il 25%-40% della RAM disponibile. Su Windows potrebbe non essere possibile impostare un valore così alto.

max_worker_processes Questa impostazione è disponibile solo per PostgreSQL 9.4+. Per PostgreSQL 9.6+ questa impostazione ha un'importanza aggiuntiva in quanto controlla il numero massimo di processi che si possono avere per le query parallele.

  • Predefinito: 8

  • Imposta il numero massimo di processi in background che il sistema può supportare. Questo parametro può essere impostato solo all'avvio del server.

3.1.2. Tempo di esecuzione

work_mem - imposta la dimensione della memoria utilizzata per le operazioni di ordinamento e le query complesse

  • Predefinito: 1-4MB

  • Aumentate per database di grandi dimensioni, query complesse, molta RAM

  • Riducete in caso di molti utenti contemporanei o di poca RAM.

  • Se avete molta RAM e pochi sviluppatori:

    SET work_mem TO '256MB';

maintenance_work_mem - la dimensione della memoria utilizzata per VACUUM, CREATE INDEX, ecc.

  • Predefinito: 16-64MB

  • Generalmente troppo basso - blocca l'I/O, blocca gli oggetti durante lo swapping della memoria

  • Consigliamo da 32 MB a 1 GB sui server di produzione con molta RAM, ma dipende dal numero di utenti contemporanei. Se avete molta RAM e pochi sviluppatori:

    SET maintenance_work_mem TO '1GB';

max_parallel_workers_per_gather

Questa impostazione è disponibile solo per PostgreSQL 9.6+ e influisce solo su PostGIS 2.3+, poiché solo PostGIS 2.3+ supporta le query parallele. Se impostata su un valore superiore a 0, alcune query, ad esempio quelle che coinvolgono funzioni di relazione come ST_Intersects, possono utilizzare più processi ed essere eseguite a una velocità più che doppia. Se si hanno molti processori a disposizione, si dovrebbe modificare il valore di questo parametro in base al numero di processori di cui si dispone. Assicuratevi anche di aumentare max_worker_processes almeno fino a questo numero.

  • Predefinito: 0

  • Imposta il numero massimo di worker che possono essere avviati da un singolo nodo Gather. I lavoratori paralleli vengono presi dal pool di processi stabilito da max_worker_processes. Si noti che il numero di lavoratori richiesto potrebbe non essere effettivamente disponibile al momento dell'esecuzione. In questo caso, il piano verrà eseguito con un numero di lavoratori inferiore a quello previsto, il che potrebbe essere inefficiente. Impostando questo valore a 0, che è quello predefinito, si disabilita l'esecuzione parallela delle query.

3.2. Configurare il supporto raster

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 7.22, “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"
[Note]

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/10/main/environment dove 10 si riferisce alla versione di PostgreSQL e main si riferisce al nome del cluster.

Su Windows, se si esegue come servizio, è possibile impostare le variabili di sistema che, per Windows 7, si ottengono facendo clic con il pulsante destro del mouse su Computer->Proprietà Impostazioni di sistema avanzate o, in explorer, navigando su Pannello di controllo\Tutte le voci del pannello di controllo\Sistema. Quindi fare clic su Impostazioni di sistema avanzate ->Avanzate->Variabili d'ambiente e aggiungere nuove variabili di sistema.

Dopo aver settato le variabili ambientali, affinché le modifiche abbiano effetto dovrai far ripartire il servizio PostgreSQL.

3.3. Creazione di database spaziali

3.3.1. Abilitazione spaziale di database usando il metodo EXTENSION

Se usi PostgreSQL 9.1+ e hai compilato ed installato le estensioni postgis, puoi attivare il supporto spaziale in un database usando il meccanismo delle EXTENSION.

L'estensione principale di postgis include geometria, geografia, spatial_ref_sys e tutte le funzioni e i commenti. Raster e topologia sono confezionati come estensione separata.

Lancia il seguente codice SQL nel database in cui vuoi abilitare il supporto spaziale:

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

3.3.2. Abilitare il database spazialmente senza usare l'ESTENSIONE (sconsigliato)

[Note]

Questo è generalmente necessario solo se non si può o non si vuole installare PostGIS nella directory delle estensioni di PostgreSQL (ad esempio durante i test, lo sviluppo o in un ambiente limitato).

L'aggiunta degli oggetti e delle definizioni delle funzioni di PostGIS nel database avviene caricando i vari file sql che si trovano in [prefisso]/share/contrib come specificato durante la fase di compilazione.

Gli oggetti PostGIS di base (tipi di geometria e geografia e relative funzioni di supporto) si trovano nello script postgis.sql. Gli oggetti raster si trovano nello script rtpostgis.sql. Gli oggetti topologici si trovano nello script topology.sql.

Per un insieme completo di identificatori di definizione di sistemi di coordinate EPSG, è possibile anche caricare il file di definizioni spatial_ref_sys.sql e popolare la tabella spatial_ref_sys. In questo modo è possibile eseguire operazioni ST_Transform() sulle geometrie.

Se si desidera aggiungere commenti alle funzioni di PostGIS, è possibile trovarli nello script postgis_comments.sql. I commenti possono essere visualizzati semplicemente digitando \dd [nome_funzione] da una finestra di terminale psql.

Eseguire i seguenti comandi di Shell nel terminale:

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

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

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

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

3.4. Aggiornamento dei database spaziali

L'aggiornamento dei database spaziali esistenti può essere complicato perché richiede la sostituzione o l'introduzione di nuove definizioni di oggetti PostGIS.

Purtroppo non tutte le definizioni possono essere facilmente sostituite in un database attivo, quindi a volte la cosa migliore è un processo di dump/reload.

PostGIS prevede una procedura di SOFT UPGRADE per i rilasci minori o di bugfix e una procedura di HARD UPGRADE per i rilasci maggiori.

Prima di tentare un aggiornamento di PostGIS, è sempre opportuno eseguire un backup dei dati. Se si usa il flag -Fc per pg_dump, si potrà sempre ripristinare il dump con un HARD UPGRADE.

3.4.1. Aggiornamento soft

Se il database è stato installato utilizzando le estensioni, è necessario effettuare anche l'aggiornamento nello stesso modo. Se l'installazione è stata eseguita con il vecchio metodo degli script sql, si consiglia di passare alle estensioni perché il metodo degli script non è più supportato.

3.4.1.1. Soft Upgrade 9.1+ utilizzando le estensioni

Se originariamente PostGIS è stato installato con le estensioni, è necessario effettuare anche l'aggiornamento utilizzando le estensioni. L'aggiornamento minore con le estensioni è abbastanza indolore.

Se si utilizza PostGIS 3 o superiore, è necessario utilizzare la funzione PostGIS_Extensions_Upgrade per aggiornare all'ultima versione installata.

SELECT postgis_extensions_upgrade();

Se si utilizza PostGIS 2.5 o inferiore, procedere come segue:

ALTER EXTENSION postgis UPDATE;
SELECT postgis_extensions_upgrade();
-- This second call is needed to rebundle postgis_raster extension
SELECT postgis_extensions_upgrade();

Se sono installate più versioni di PostGIS e non si vuole aggiornare alla più recente, è possibile specificare esplicitamente la versione come segue:

ALTER EXTENSION postgis UPDATE TO "3.6.0dev";
ALTER EXTENSION postgis_topology UPDATE TO "3.6.0dev";

Se si ottiene un avviso di errore, qualcosa di simile a:

No migration path defined for … to 3.6.0dev

È quindi necessario eseguire un backup del database, crearne uno nuovo come descritto in Section 3.3.1, “Abilitazione spaziale di database usando il metodo EXTENSION” e quindi ripristinare il backup su questo nuovo database.

Se viene visualizzato un messaggio di avviso del tipo:

Version "3.6.0dev" of extension "postgis" is already installed

Allora tutto è già aggiornato e si può tranquillamente ignorare. A MENO CHE non si stia cercando di passare da una versione di sviluppo alla successiva (che non riceve un nuovo numero di versione); in questo caso si può aggiungere "next" alla stringa della versione e la prossima volta si dovrà eliminare il suffisso "next":

ALTER EXTENSION postgis UPDATE TO "3.6.0devnext";
ALTER EXTENSION postgis_topology UPDATE TO "3.6.0devnext";
[Note]

Se PostGIS è stato installato originariamente senza una versione specificata, spesso è possibile saltare la reinstallazione dell'estensione postgis prima del ripristino, poiché il backup ha solo CREATE EXTENSION postgis e quindi preleva la versione più recente durante il ripristino.

[Note]

Se si aggiorna l'estensione di PostGIS da una versione precedente alla 3.0.0, si avrà una nuova estensione postgis_raster che si può tranquillamente abbandonare, se non si ha bisogno del supporto raster. Si può abbandonare come segue:

DROP EXTENSION postgis_raster;

3.4.1.2. Aggiornamento soft Pre 9.1+ o senza estensioni

Questa sezione si applica solo a chi ha installato PostGIS senza utilizzare le estensioni. Se si dispone di estensioni e si tenta di eseguire l'aggiornamento con questo approccio, si otterranno messaggi come:

can't drop … because postgis extension depends on it

NOTA: se si sta passando da PostGIS 1.* a PostGIS 2.* o da PostGIS 2.* precedente a r7409, non è possibile utilizzare questa procedura, ma è necessario eseguire un HARD UPGRADE.

Dopo la compilazione e l'installazione (make install) si dovrebbe trovare un insieme di file *_upgrade.sql nelle cartelle di installazione. È possibile elencarli tutti con:

ls `pg_config --sharedir`/contrib/postgis-3.6.0dev/*_upgrade.sql

Caricarli tutti in successione, a partire da postgis_upgrade.sql.

psql -f postgis_upgrade.sql -d your_spatial_database

La stessa procedura si applica alle estensioni raster, topology e sfcgal, con file di aggiornamento denominati rispettivamente rtpostgis_upgrade.sql, topology_upgrade.sql e sfcgal_upgrade.sql. Se ne avete bisogno:

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

Si consiglia di passare a un'installazione basata sulle estensioni eseguendo

psql -c "SELECT postgis_extensions_upgrade();"
[Note]

Se non si riesce a trovare il file postgis_upgrade.sql specifico per l'aggiornamento della propria versione, si sta utilizzando una versione troppo precoce per un aggiornamento soft e si deve eseguire un HARD UPGRADE.

La funzione PostGIS_Full_Version dovrebbe informare della necessità di eseguire questo tipo di aggiornamento con un messaggio "procs need upgrade".

3.4.2. Aggiornamento hard

Per HARD UPGRADE si intende il dump/reload completo dei database abilitati a PostGIS. È necessario un HARD UPGRADE quando la memoria interna degli oggetti PostGIS cambia o quando non è possibile effettuare un SOFT UPGRADE. L'appendice Release Notes riporta per ogni versione se è necessario un dump/reload (HARD UPGRADE) per l'aggiornamento.

Il processo di dump/reload è assistito dallo script postgis_restore che si occupa di saltare dal dump tutte le definizioni che appartengono a PostGIS (comprese quelle vecchie), consentendo di ripristinare gli schemi e i dati in un database con PostGIS installato senza incorrere in errori di simboli duplicati o di portare avanti oggetti deprecati.

Le istruzioni supplementari per gli utenti di Windows sono disponibili all'indirizzo Windows Hard upgrade.

La procedura è la seguente:

  1. Creare un dump in formato personalizzato del database che si vuole aggiornare (chiamiamolo olddb), includendo l'output binario (-b) e verboso (-v). L'utente può essere il proprietario del database, non è necessario che sia il super account di postgres.

    pg_dump -h localhost -p 5432 -U postgres -Fc -b -v -f "/somepath/olddb.backup" olddb
  2. Eseguire una nuova installazione di PostGIS in un nuovo database -- ci riferiremo a questo database come newdb. Per le istruzioni su come fare, fare riferimento a Section 3.3.2, “Abilitare il database spazialmente senza usare l'ESTENSIONE (sconsigliato)” e Section 3.3.1, “Abilitazione spaziale di database usando il metodo EXTENSION”.

    Le voci di spatial_ref_sys trovate nel dump verranno ripristinate, ma non sovrascriveranno quelle esistenti in spatial_ref_sys. Questo per garantire che le correzioni del set ufficiale vengano propagate correttamente ai database ripristinati. Se per qualche motivo si desidera sovrascrivere le voci standard, è sufficiente non caricare il file spatial_ref_sys.sql durante la creazione del nuovo database.

    Se il vostro database è molto vecchio o sapete di aver usato funzioni deprecate da tempo nelle vostre viste e funzioni, potreste aver bisogno di caricare legacy.sql affinché tutte le vostre funzioni, viste ecc. tornino correttamente. Fatelo solo se è veramente necessario. Se possibile, si consiglia di aggiornare le viste e le funzioni prima di eseguire il dump. Le funzioni deprecate possono essere rimosse in seguito caricando uninstall_legacy.sql.

  3. Ripristinare il backup nel nuovo database newdb utilizzando postgis_restore. Eventuali errori imprevisti saranno stampati da psql nel flusso di errore standard. Conservare un registro di questi errori.

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

Gli errori possono verificarsi nei seguenti casi:

  1. Alcune viste o funzioni fanno uso di oggetti PostGIS deprecati. Per risolvere questo problema si può provare a caricare lo script legacy.sql prima del ripristino, oppure si dovrà ripristinare una versione di PostGIS che contiene ancora questi oggetti e riprovare la migrazione dopo aver eseguito il porting del codice. Se il metodo legacy.sql funziona, non dimenticate di correggere il codice per smettere di usare le funzioni deprecate e di eliminarle caricando uninstall_legacy.sql.

  2. Alcuni record personalizzati di spatial_ref_sys nel file di dump hanno un valore SRID non valido. I valori SRID validi sono maggiori di 0 e minori di 999000. I valori nell'intervallo 999000.999999 sono riservati per uso interno, mentre i valori > 999999 non possono essere utilizzati. Tutti i record personalizzati con SRID non validi verranno mantenuti, con quelli > 999999 spostati nell'intervallo riservato, ma la tabella spatial_ref_sys perderà un vincolo di controllo che garantisce il mantenimento dell'invariante e forse anche la sua chiave primaria (quando più SRID non validi vengono convertiti nello stesso valore SRID riservato).

    Per risolvere il problema è necessario copiare l'SRS personalizzato in un SRID con un valore valido (forse nell'intervallo 910000...910999), convertire tutte le tabelle nel nuovo SRS (vedere UpdateGeometrySRID), eliminare la voce non valida da spatial_ref_sys e ricostruire i controlli con:

    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));
        

    Se state aggiornando un vecchio database contenente la cartografia francese IGN , probabilmente i SRID sono fuori range e vedrete, quando importate il database, problemi come questo:

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

    In questo caso, si può provare a procedere come segue: per prima cosa eliminare completamente l'IGN dallo sql risultante da postgis_restore. Quindi, dopo aver eseguito :

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

    eseguire questo comando :

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

    Creare quindi il proprio newdb, attivare le estensioni Postgis richieste e inserire correttamente l'IGN del sistema francese con: questo script Dopo queste operazioni, importare i dati:

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

Chapter 4. Data Management

4.1. Spatial Data Model

4.1.1. OGC Geometry

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

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

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

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

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”

4.1.1.1. Punto

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)

4.1.1.2. LineString

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

LINESTRING (1 2, 3 4, 5 6)

4.1.1.3. LinearRing

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

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

4.1.1.4. Poligono

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))

4.1.1.5. MultiPoint

A MultiPoint is a collection of Points.

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

4.1.1.6. MultiLineString

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

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

4.1.1.7. MultiPolygon

A MultiPolygon is a collection of non-overlapping, non-adjacent Polygons. Polygons in the collection may touch only at a finite number of points.

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

4.1.1.8. GeometryCollection

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

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

4.1.1.9. PolyhedralSurface

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

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

4.1.1.10. Triangle

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

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

4.1.1.11. TIN

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

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

4.1.2. SQL/MM Part 3 - Curves

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.

[Note]

All floating point comparisons within the SQL-MM implementation are performed to a specified tolerance, currently 1E-8.

4.1.2.1. CircularString

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)

4.1.2.2. CompoundCurve

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))

4.1.2.3. CurvePolygon

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) )

4.1.2.4. MultiCurve

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))

4.1.2.5. MultiSurface

A MultiSurface is a collection of surfaces, which can be (linear) Polygons or CurvePolygons.

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

4.1.3. WKT and WKB

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');

4.2. Geometry Data Type

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

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

[Note]

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.

4.2.1. PostGIS EWKB and EWKT

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)

[Caution]

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' )

4.3. Geography Data Type

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.

4.3.1. Creating Geography Tables

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 );

4.3.2. Using Geography Tables

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

4.3.3. When to use the Geography data type

The geography data type allows you to store data in longitude/latitude coordinates, but at a cost: there are fewer functions defined on GEOGRAPHY than there are on GEOMETRY; those functions that are defined take more CPU time to execute.

The data type you choose should be determined by the expected working area of the application you are building. Will your data span the globe or a large continental area, or is it local to a state, county or municipality?

  • If your data is contained in a small area, you might find that choosing an appropriate projection and using GEOMETRY is the best solution, in terms of performance and functionality available.

  • If your data is global or covers a continental region, you may find that GEOGRAPHY allows you to build a system without having to worry about projection details. You store your data in longitude/latitude, and use the functions that have been defined on GEOGRAPHY.

  • If you don't understand projections, and you don't want to learn about them, and you're prepared to accept the limitations in functionality available in GEOGRAPHY, then it might be easier for you to use GEOGRAPHY than GEOMETRY. Simply load your data up as longitude/latitude and go from there.

Refer to Section 13.11, “Matrice di supporto alle funzioni PostGIS” for compare between what is supported for Geography vs. Geometry. For a brief listing and description of Geography functions, refer to Section 13.4, “Funzioni di supporto alla geografia PostGIS”

4.3.4. Geography Advanced FAQ

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*.

4.4. Geometry Validation

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

4.4.1. Simple Geometry

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

A POINT is inherently simple as a 0-dimensional geometry object.

MULTIPOINTs are simple if no two coordinates (POINTs) are equal (have identical coordinate values).

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

(a) and (c) are simple LINESTRINGs. (b) and (d) are not simple. (c) is a closed Linear Ring.

(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 MULTILINESTRINGs. (g) is not simple.

(e)

(f)

(g)

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

To test if a geometry is simple use the ST_IsSimple function:

SELECT
   ST_IsSimple('LINESTRING(0 0, 100 100)') AS straight,
   ST_IsSimple('LINESTRING(0 0, 100 100, 100 0, 0 100)') AS crossing;

 straight | crossing
----------+----------
 t        | f

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

4.4.2. Valid Geometry

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

A POLYGON is valid if:

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

  2. boundary rings do not cross

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

  4. interior rings are contained in the exterior ring

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

(h) and (i) are valid POLYGONs. (j-m) are invalid. (j) can be represented as a valid MULTIPOLYGON.

(h)

(i)

(j)

(k)

(l)

(m)

A MULTIPOLYGON is valid if:

  1. its element POLYGONs are valid

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

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

(n) is a valid MULTIPOLYGON. (o) and (p) are invalid.

(n)

(o)

(p)

These rules mean that valid polygonal geometry is also simple.

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

SELECT
   ST_IsValid('LINESTRING(0 0, 1 1)') AS len_nonzero,
   ST_IsValid('LINESTRING(0 0, 0 0, 0 0)') AS len_zero,
   ST_IsValid('LINESTRING(10 10, 150 150, 180 50, 20 130)') AS self_int;

 len_nonzero | len_zero | self_int
-------------+----------+----------
 t           | f        | t

POINT and MULTIPOINT geometries have no validity rules.

4.4.3. Managing Validity

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

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

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

[Note]

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));

4.5. Spatial Reference Systems

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

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

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

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

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

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

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

4.5.1. SPATIAL_REF_SYS Table

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

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:

srid

An integer code that uniquely identifies the Spatial Reference System (SRS) within the database.

auth_name

The name of the standard or standards body that is being cited for this reference system. For example, "EPSG" is a valid auth_name.

auth_srid

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

srtext

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.

proj4text

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.

4.5.2. User-Defined Spatial Reference Systems

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'
);

4.6. Spatial Tables

4.6.1. Creating a Spatial Table

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);

4.6.2. GEOMETRY_COLUMNS View

The OGC Simple Features Specification for SQL defines the GEOMETRY_COLUMNS metadata table to describe geometry table structure. In PostGIS geometry_columns is a view reading from database system catalog tables. This ensures that the spatial metadata information is always consistent with the currently defined tables and views. The view structure is:

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

The columns are:

f_table_catalog, f_table_schema, f_table_name

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).

f_geometry_column

The name of the geometry column in the feature table.

coord_dimension

The coordinate dimension (2, 3 or 4) of the column.

srid

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”).

type

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.

4.6.3. Manually Registering Geometry Columns

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

4.7. Loading Spatial Data

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.

4.7.1. Using SQL to Load Data

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

4.7.2. Using the Shapefile Loader

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.

(c|a|d|p) sono opzioni che is escludono una con l'altra:

-c

Creates a new table and populates it from the Shapefile. This is the default mode.

-a

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.

-d

Drops the database table before creating a new table with the data in the Shapefile.

-p

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.

-D

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.

-s [<FROM_SRID>:]<SRID>

Creates and populates the geometry tables with the specified SRID. Optionally specifies that the input shapefile uses the given FROM_SRID, in which case the geometries will be reprojected to the target SRID.

-k

Keep identifiers' case (column, schema and attributes). Note that attributes in Shapefile are all UPPERCASE.

-i

Coerce all integers to standard 32-bit integers, do not create 64-bit bigints, even if the DBF header signature appears to warrant it.

-I

Create a GiST index on the geometry column.

-m

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

COLUMNNAME DBFFIELD1
AVERYLONGCOLUMNNAME DBFFIELD2

-S

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).

-t <dimensionality>

Force the output geometry to have the specified dimensionality. Use the following strings to indicate the dimensionality: 2D, 3DZ, 3DM, 4D.

If the input has fewer dimensions that specified, the output will have those dimensions filled in with zeroes. If the input has more dimensions that specified, the unwanted dimensions will be stripped.

-w

Output WKT format, instead of WKB. Note that this can introduce coordinate drifts due to loss of precision.

-e

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.

-W <encoding>

Specify encoding of the input data (dbf file). When used, all attributes of the dbf are converted from the specified encoding to UTF8. The resulting SQL output will contain a SET CLIENT_ENCODING to UTF8 command, so that the backend will be able to reconvert from UTF8 to whatever encoding the database is configured to use internally.

-N <policy>

NULL geometries handling policy (insert*,skip,abort)

-n

-n Only import DBF file. If your data has no corresponding shapefile, it will automatically switch to this mode and load just the dbf. So setting this flag is only needed if you have a full shapefile set, and you only want the attribute data and no geometry.

-G

Use geography type instead of geometry (requires lon/lat data) in WGS84 long lat (SRID=4326)

-T <tablespace>

Specify the tablespace for the new table. Indexes will still use the default tablespace unless the -X parameter is also used. The PostgreSQL documentation has a good description on when to use custom tablespaces.

-X <tablespace>

Specify the tablespace for the new table's indexes. This applies to the primary key index, and the GIST spatial index if -I is also used.

-Z

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

4.8. Extracting Spatial Data

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.

4.8.1. Using SQL to Extract Data

The most straightforward way of extracting spatial data out of the database is to use a SQL SELECT query to define the data set to be extracted and dump the resulting columns into a parsable text file:

db=# SELECT road_id, ST_AsText(road_geom) AS geom, road_name FROM roads;

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

There will be times when some kind of restriction is necessary to cut down the number of records returned. In the case of attribute-based restrictions, use the same SQL syntax as used with a non-spatial table. In the case of spatial restrictions, the following functions are useful:

ST_Intersects

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.

4.8.2. Using the Shapefile Dumper

The pgsql2shp table dumper connects to the database and converts a table (possibly defined by a query) into a shape file. The basic syntax is:

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

The commandline options are:

-f <filename>

Write the output to a particular filename.

-h <host>

The database host to connect to.

-p <port>

The port to connect to on the database host.

-P <password>

The password to use when connecting to the database.

-u <user>

The username to use when connecting to the database.

-g <geometry column>

In the case of tables with multiple geometry columns, the geometry column to use when writing the shape file.

-b

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.

-r

Raw mode. Do not drop the gid field, or escape column names.

-m 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.

4.9. Spatial Indexes

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.

4.9.1. GiST Indexes

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)];

4.9.2. BRIN Indexes

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.

4.9.3. SP-GiST Indexes

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.

4.9.4. Tuning Index Usage

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.

Chapter 5. Spatial Queries

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

5.1. Determining Spatial Relationships

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

5.1.1. Dimensionally Extended 9-Intersection Model

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

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

Boundary

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

Interior

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

Exterior

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

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

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

  • 0 => point

  • 1 => line

  • 2 => area

  • F => empty set

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

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

Visually, for two overlapping polygonal geometries, this looks like:

 
 InteriorBoundaryExterior
Interior

dim( I(a) ∩ I(b) ) = 2

dim( I(a) ∩ B(b) = 1

dim( I(a) ∩ E(b) ) = 2

Boundary

dim( B(a) ∩ I(b) ) = 1

dim( B(a) ∩ B(b) ) = 0

dim( B(a) ∩ E(b) ) = 1

Exterior

dim( E(a) ∩ I(b) ) = 2

dim( E(a) ∩ B(b) ) = 1

dim( E(a) ∩ E(b) = 2

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

For more information, refer to:

5.1.2. Named Spatial Relationships

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

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

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

For more details and illustrations, see the PostGIS Workshop.

5.1.3. General Spatial Relationships

In some cases the named spatial relationships are insufficient to provide a desired spatial filter condition.

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 true only where they cross at a point.

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 'LINESTRING' (properly dealing with cases that return GEOMETRYCOLLECTIONs of [MULTI]POINTs, [MULTI]LINESTRINGs, etc.).

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');

5.2. Using Spatial Indexes

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

Spatial operators include the bounding box operators (of which the most commonly used is &&; see Section 7.10.1, “Bounding Box Operators” for the full list) and the distance operators used in nearest-neighbor queries (the most common being <->; see Section 7.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.

5.3. Examples of Spatial SQL

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

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

The definition of the bc_municipality table is:

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

5.3.1.

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

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

SELECT sum(ST_Length(geom))/1000 AS km_roads FROM bc_roads;

km_roads
------------------
70842.1243039643

5.3.2.

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

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

SELECT
  ST_Area(geom)/10000 AS hectares
FROM bc_municipality
WHERE name = 'PRINCE GEORGE';

hectares
------------------
32657.9103824927

5.3.3.

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

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

SELECT
  name,
  ST_Area(geom)/10000 AS hectares
FROM bc_municipality
ORDER BY hectares DESC
LIMIT 1;

name           | hectares
---------------+-----------------
TUMBLER RIDGE  | 155020.02556131

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

5.3.4.

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

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

SELECT
  m.name,
  sum(ST_Length(r.geom))/1000 as roads_km
FROM bc_roads AS r
JOIN bc_municipality AS m
  ON ST_Contains(m.geom, r.geom)
GROUP BY m.name
ORDER BY roads_km;

name                        | roads_km
----------------------------+------------------
SURREY                      | 1539.47553551242
VANCOUVER                   | 1450.33093486576
LANGLEY DISTRICT            | 833.793392535662
BURNABY                     | 773.769091404338
PRINCE GEORGE               | 694.37554369147
...

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

5.3.5.

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

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

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

5.3.6.

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

SELECT
  sum(ST_Length(r.geom))/1000 AS kilometers
FROM bc_roads r
JOIN bc_municipality m
  ON ST_Intersects(m.geom, r.geom
WHERE
  r.name = 'Douglas St'
  AND m.name = 'VICTORIA';

kilometers
------------------
4.89151904172838

5.3.7.

What is the largest municipality polygon that has a hole?

SELECT gid, name, ST_Area(geom) AS area
FROM bc_municipality
WHERE ST_NRings(geom) 
> 1
ORDER BY area DESC LIMIT 1;

gid  | name         | area
-----+--------------+------------------
12   | SPALLUMCHEEN | 257374619.430216

Chapter 6. Suggerimenti per le prestazioni

6.1. Piccole tabelle contenenti geometrie di grandi dimensioni

6.1.1. Descrizione del problema

Le versioni attuali di PostgreSQL (compresa la 9.6) soffrono di una debolezza dell'ottimizzatore di query per quanto riguarda le tabelle TOAST. Le tabelle TOAST sono una sorta di "stanza di estensione" utilizzata per memorizzare valori di grandi dimensioni (nel senso della dimensione dei dati) che non si adattano alle normali pagine di dati (come testi lunghi, immagini o geometrie complesse con molti vertici), si veda la documentazione PostgreSQL per TOAST per maggiori informazioni).

Il problema si presenta se si ha una tabella con geometrie piuttosto grandi, ma non troppe righe (come una tabella contenente i confini di tutti i paesi europei in alta risoluzione). In questo caso, la tabella stessa è piccola, ma utilizza molto spazio TOAST. Nel nostro caso di esempio, la tabella stessa aveva circa 80 righe e utilizzava solo 3 pagine di dati, ma la tabella TOAST utilizzava 8225 pagine.

Ora si lanci una query che usi l'operatore && e che trovi solo poche righe. L'ottimizzatore di query ora vede che la tabella ha solo 3 pagine e 80 record. Stima che una scansione sequenziale su una tabella cosi' piccola e' molto piu' veloce rispetto all'uso di un indice, e quindi decide di ignorare l'indice GiST. Normalmente questa stima e' corretta, ma nel nostro caso l'operatorore && deve estrarre ogni geometria dal disco per confrontare i bounding box finendo con il leggere anche tutte le pagine TOAST.

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

e una discussione più recente su PostGIS https://lists.osgeo.org/pipermail/postgis-devel/2017-June/026209.html

6.1.2. Possibili soluzioni

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_Force2D(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.

6.2. CLUSTERing di indici geometrici

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 "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 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à.

6.3. Evitare la conversione della dimensione

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 geom = ST_Force2D(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 tabelle di grandi dimensioni, può essere opportuno dividere l'UPDATE in porzioni più piccole, vincolando l'UPDATE a una parte della tabella tramite una clausola WHERE e la chiave primaria o un altro criterio fattibile ed eseguendo un semplice "VACUUM;" tra gli UPDATE. In questo modo si riduce drasticamente la necessità di spazio temporaneo su disco. Inoltre, se si hanno geometrie di dimensioni miste, limitando l'AGGIORNAMENTO con "WHERE dimension(geom)>2" si evita di riscrivere le geometrie che sono già in 2D.

Chapter 7. Guida a PostGIS

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.

[Note]

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.

7.1. Tipi di dati PostGIS Geometria/Geografia/Box

Abstract

Questa sezione elenca i tipi di dati PostgreSQL personalizzati installati da PostGIS per rappresentare i dati spaziali.

Ogni tipo di dati descrive il suo comportamento di conversione di tipo. Un cast di tipo converte i valori di un tipo di dati in un altro tipo. PostgreSQL consente di definire il comportamento di conversione per i tipi personalizzati, insieme alle funzioni utilizzate per convertire i valori del tipo. I cast possono avere un comportamento automatico, che consente la conversione automatica di un argomento di funzione in un tipo supportato dalla funzione.

Alcuni cast hanno un comportamento esplicito, il che significa che il cast deve essere specificato usando la sintassi CAST(myval As sometype) o myval::sometype. Il casting esplicito evita il problema dei cast ambigui, che possono verificarsi quando si utilizza una funzione sovraccaricata che non supporta un determinato tipo. Ad esempio, una funzione può accettare un box2d o un box3d, ma non una geometria. Poiché la geometria ha un cast automatico per entrambi i tipi di box, questo produce un errore di "funzione ambigua". Per evitare l'errore, utilizzare un cast esplicito al tipo di box desiderato.

Tutti i tipi di dati possono essere convertiti in text, quindi non è necessario specificarlo esplicitamente.

  • box2d — The type representing a 2-dimensional bounding box.
  • box3d — The type representing a 3-dimensional bounding box.
  • geometry — geography è un tipo spaziale usato per rappresentare un'entità in un sistema di coordinate sferico valido per l'intero pianeta.
  • geometry_dump — A composite type used to describe the parts of complex geometry.
  • geography — The type representing spatial features with geodetic (ellipsoidal) coordinate systems.

Name

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

Descrizione

box2d è un tipo di dato spaziale usato per rappresentare il rettangolo contente una geometria o un insieme di geometrie. La funzione aggregata ST_Extent, ad esempio, restituisce un oggetto box2d.

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).

Comportamento in caso di CAST

Questa sezione illustra le modalità di CAST - automatici e espliciti - permessi per questo tipo di dato

Cast versoComportamento
box3dautomatico
geometryautomatico

Name

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

Descrizione

box3d è un tipo di dato spaziale di PostGIS usato per rappresentare il parallelepipedo contente una geometria o un insieme di geometrie. La funzione aggregata ST_3DExtent, ad esempio, ritorna un oggetto box3d.

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

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

Comportamento in caso di CAST

Questa sezione illustra le modalità di CAST - automatici e espliciti - permessi per questo tipo di dato

Cast versoComportamento
boxautomatico
box2dautomatico
geometryautomatico

Name

geometry — geography è un tipo spaziale usato per rappresentare un'entità in un sistema di coordinate sferico valido per l'intero pianeta.

Descrizione

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.

Comportamento in caso di CAST

Questa sezione illustra le modalità di CAST - automatici e espliciti - permessi per questo tipo di dato

Cast versoComportamento
boxautomatico
box2dautomatico
box3dautomatico
byteaautomatico
geographyautomatico
textautomatico

Name

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

Descrizione

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.


Name

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

Descrizione

geography è un tipo spaziale usato per rappresentare un'entità in un sistema di coordinate geodetico. I sistemi di coordinate geodetici utilizzano un modello ellipsoidale per il pianeta terra.

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

Comportamento in caso di CAST

Questa sezione illustra le modalità di CAST - automatici e espliciti - permessi per questo tipo di dato

Cast versoComportamento
geometryEsplicito

7.2. Funzioni di gestione delle tabelle

Abstract

Queste funzioni aiutano a definire tabelle contenenti colonne geometriche.

  • AddGeometryColumn — Aggiunge una colonna geometrica a una tabella esistente.
  • DropGeometryColumn — Rimuove una colonna geometry da una tabella spaziale
  • DropGeometryTable — Rimuove una tabella e tutte le sue referenze da geometry_columns
  • Find_SRID — Restituisce lo SRID di una colonna di tipo geometrico.
  • Populate_Geometry_Columns — Garantisce che le colonne di tipo geometrico siano definite con dei modificatori di tipo o abbiano dei vincoli spaziali appropriati.
  • UpdateGeometrySRID — Aggiorna lo SRID e di tutte le geometrie nella colonna specificata e i metadati di tabella.

Name

AddGeometryColumn — Aggiunge una colonna geometrica a una tabella esistente.

Synopsis

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);

Descrizione

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.

[Note]

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:ALTER TABLE some_table ADD COLUMN geom geometry(Point,4326);

Cambiamento nella versione 2.0.0: il vecchio funzionamento con i vincoli può essere attivato passando alla funzione l'argomento use_typmod impostato su false.

[Note]

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 dell'output della funzione verrà definito esplicitamente con la funzione CAST come typmod geometry. Si veda Section 4.6.3, “Manually Registering Geometry Columns”.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1.

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo supporta le Curve e le Circular String.

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.

Esempi

-- Create schema to hold data
CREATE SCHEMA my_schema;
-- Create a new simple PostgreSQL table
CREATE TABLE my_schema.my_spatial_table (id serial);

-- Describing the table shows a simple table with a single "id" column.
postgis=# \d my_schema.my_spatial_table
                                                         Table "my_schema.my_spatial_table"
 Column |  Type   |                                Modifiers
--------+---------+-------------------------------------------------------------------------
 id     | integer | not null default nextval('my_schema.my_spatial_table_id_seq'::regclass)

-- Add a spatial column to the table
SELECT AddGeometryColumn ('my_schema','my_spatial_table','geom',4326,'POINT',2);

-- Add a point using the old constraint based behavior
SELECT AddGeometryColumn ('my_schema','my_spatial_table','geom_c',4326,'POINT',2, false);

--Add a curvepolygon using old constraint behavior
SELECT AddGeometryColumn ('my_schema','my_spatial_table','geomcp_c',4326,'CURVEPOLYGON',2, false);

-- Describe the table again reveals the addition of a new geometry columns.
\d my_schema.my_spatial_table
                            addgeometrycolumn
-------------------------------------------------------------------------
 my_schema.my_spatial_table.geomcp_c SRID:4326 TYPE:CURVEPOLYGON DIMS:2
(1 row)

                                    Table "my_schema.my_spatial_table"
  Column  |         Type         |                                Modifiers
----------+----------------------+-------------------------------------------------------------------------
 id       | integer              | not null default nextval('my_schema.my_spatial_table_id_seq'::regclass)
 geom     | geometry(Point,4326) |
 geom_c   | geometry             |
 geomcp_c | geometry             |
Check constraints:
    "enforce_dims_geom_c" CHECK (st_ndims(geom_c) = 2)
    "enforce_dims_geomcp_c" CHECK (st_ndims(geomcp_c) = 2)
    "enforce_geotype_geom_c" CHECK (geometrytype(geom_c) = 'POINT'::text OR geom_c IS NULL)
    "enforce_geotype_geomcp_c" CHECK (geometrytype(geomcp_c) = 'CURVEPOLYGON'::text OR geomcp_c IS NULL)
    "enforce_srid_geom_c" CHECK (st_srid(geom_c) = 4326)
    "enforce_srid_geomcp_c" CHECK (st_srid(geomcp_c) = 4326)

-- geometry_columns view also registers the new columns --
SELECT f_geometry_column As col_name, type, srid, coord_dimension As ndims
    FROM geometry_columns
    WHERE f_table_name = 'my_spatial_table' AND f_table_schema = 'my_schema';

 col_name |     type     | srid | ndims
----------+--------------+------+-------
 geom     | Point        | 4326 |     2
 geom_c   | Point        | 4326 |     2
 geomcp_c | CurvePolygon | 4326 |     2

Name

DropGeometryColumn — Rimuove una colonna geometry da una tabella spaziale

Synopsis

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);

Descrizione

Rimuove una colonna geometry da una tabella spaziale. Il campo schema_name deve corrispondere al campo f_table_schema in geometry_columns.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1.

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo supporta le Curve e le Circular String.

[Note]

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 ALTER TABLE

Esempi

SELECT DropGeometryColumn ('my_schema','my_spatial_table','geom');
                        ----RESULT output ---
                                          dropgeometrycolumn
------------------------------------------------------
 my_schema.my_spatial_table.geom effectively removed.

-- In PostGIS 2.0+ the above is also equivalent to the standard
-- the standard alter table.  Both will deregister from geometry_columns
ALTER TABLE my_schema.my_spatial_table DROP column geom;
                

Name

DropGeometryTable — Rimuove una tabella e tutte le sue referenze da geometry_columns

Synopsis

boolean DropGeometryTable(varchar table_name);

boolean DropGeometryTable(varchar schema_name, varchar table_name);

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

Descrizione

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.

[Note]

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 DROP TABLE

Esempi

SELECT DropGeometryTable ('my_schema','my_spatial_table');
----RESULT output ---
my_schema.my_spatial_table dropped.

-- The above is now equivalent to --
DROP TABLE my_schema.my_spatial_table;
                

Name

Find_SRID — Restituisce lo SRID di una colonna di tipo geometrico.

Synopsis

integer Find_SRID(varchar a_schema_name, varchar a_table_name, varchar a_geomfield_name);

Descrizione

Restituisce lo SRID (un intero) della colonna geometrica specificata cercandolo nella tabella GEOMETRY_COLUMNS. Se la colonna geometrica non e' stata aggiunta correttamente (ad esempio con la funzione AddGeometryColumn), questa chiamata non funzionera'.

Esempi

SELECT Find_SRID('public', 'tiger_us_state_2007', 'geom_4269');
find_srid
----------
4269

Si veda anche

ST_SRID


Name

Populate_Geometry_Columns — Garantisce che le colonne di tipo geometrico siano definite con dei modificatori di tipo o abbiano dei vincoli spaziali appropriati.

Synopsis

text Populate_Geometry_Columns(boolean use_typmod=true);

int Populate_Geometry_Columns(oid relation_oid, boolean use_typmod=true);

Descrizione

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 retrocompatibilita' e per necessita' spaziali come l'ereditarieta' tabellare, in cui ogni tabella figlia puo' avere tipi geometrici differenti, il vecchio comportamento basato sui vincoli e' ancora sopportato. Se ti serve il vecchio comportamento puoi passare l'argomento opzionale use_typmod=false. In questo modo la colonna geometrica verra' creata senza modificatore di tipo ma avra' 3 vincoli definiti. In particolare questo vuol dire che ogni colonna geometrica appartenente ad una tabella avra' al meno tre vincoli:

  • enforce_dims_geom - assicura che ogni geometria abbia la stessa dimensione (vedere 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.

Esempi

CREATE TABLE public.myspatial_table(gid serial, geom geometry);
INSERT INTO myspatial_table(geom) VALUES(ST_GeomFromText('LINESTRING(1 2, 3 4)',4326) );
-- This will now use typ modifiers.  For this to work, there must exist data
SELECT Populate_Geometry_Columns('public.myspatial_table'::regclass);

populate_geometry_columns
--------------------------
                        1


\d myspatial_table

                                   Table "public.myspatial_table"
 Column |           Type            |                           Modifiers
--------+---------------------------+---------------------------------------------------------------
 gid    | integer                   | not null default nextval('myspatial_table_gid_seq'::regclass)
 geom   | geometry(LineString,4326) |
-- This will change the geometry columns to use constraints if they are not typmod or have constraints already.
--For this to work, there must exist data
CREATE TABLE public.myspatial_table_cs(gid serial, geom geometry);
INSERT INTO myspatial_table_cs(geom) VALUES(ST_GeomFromText('LINESTRING(1 2, 3 4)',4326) );
SELECT Populate_Geometry_Columns('public.myspatial_table_cs'::regclass, false);
populate_geometry_columns
--------------------------
                        1
\d myspatial_table_cs

                          Table "public.myspatial_table_cs"
 Column |   Type   |                            Modifiers
--------+----------+------------------------------------------------------------------
 gid    | integer  | not null default nextval('myspatial_table_cs_gid_seq'::regclass)
 geom   | geometry |
Check constraints:
    "enforce_dims_geom" CHECK (st_ndims(geom) = 2)
    "enforce_geotype_geom" CHECK (geometrytype(geom) = 'LINESTRING'::text OR geom IS NULL)
    "enforce_srid_geom" CHECK (st_srid(geom) = 4326)

Name

UpdateGeometrySRID — Aggiorna lo SRID e di tutte le geometrie nella colonna specificata e i metadati di tabella.

Synopsis

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);

Descrizione

Aggiorna lo SRID di tutti i record in una colonna geometry, aggiornando anche geometry_columns e il vincolo SRID della colonna. Se la colonna era vincolata da una defininizione di tipo, tale definizione verrà cambiata. Nota: usa la funzione current_schema() se lo schema non è passato come argomento.

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo supporta le Curve e le Circular String.

Esempi

Insertisce geometrie nella tabella delle strade con uno SRID già specificato usando il formato EWKT:

COPY roads (geom) FROM STDIN;
SRID=4326;LINESTRING(0 0, 10 10)
SRID=4326;LINESTRING(10 10, 15 0)
\.
                

Cambierà lo SRID della tabella delle strade a 4326 da qualunque valore abbia avuto prima:

SELECT UpdateGeometrySRID('roads','geom',4326);

L'esempio precedente è equivalente a questa dichiarazione DDL:

ALTER TABLE roads
  ALTER COLUMN geom TYPE geometry(MULTILINESTRING, 4326)
    USING ST_SetSRID(geom,4326);

Se si è sbagliata la proiezione (o la si è inserita come sconosciuta) nel caricamento e si vuole trasformare in web mercator in un colpo solo, è possibile farlo con il DDL, ma non esiste una funzione equivalente di gestione di PostGIS per farlo in un colpo solo.

ALTER TABLE roads
 ALTER COLUMN geom TYPE geometry(MULTILINESTRING, 3857) USING ST_Transform(ST_SetSRID(geom,4326),3857) ;

7.3. Costruttori geometrici.

  • ST_Collect — Creates a GeometryCollection or Multi* geometry from a set of geometries.
  • ST_LineFromMultiPoint — Crea una LineString da una geometria MultiPoint.
  • ST_MakeEnvelope — Creates a rectangular Polygon from minimum and maximum coordinates.
  • ST_MakeLine — Crea una LineString da una geometria Point, MultiPoint o un set di LineString
  • ST_MakePoint — Creates a 2D, 3DZ or 4D Point.
  • ST_MakePointM — Creates a Point from X, Y and M values.
  • ST_MakePolygon — Creates a Polygon from a shell and optional list of holes.
  • ST_Point — Creates a Point with X, Y and SRID values.
  • ST_PointZ — Creates a Point with X, Y, Z and SRID values.
  • ST_PointM — Creates a Point with X, Y, M and SRID values.
  • ST_PointZM — Creates a Point with X, Y, Z, M and SRID values.
  • ST_Polygon — Creates a Polygon from a LineString with a specified SRID.
  • ST_TileEnvelope — Creates a rectangular Polygon in Web Mercator (SRID:3857) using the XYZ tile system.
  • ST_HexagonGrid — Returns a set of hexagons and cell indices that completely cover the bounds of the geometry argument.
  • ST_Hexagon — Returns a single hexagon, using the provided edge size and cell coordinate within the hexagon grid space.
  • ST_SquareGrid — Returns a set of grid squares and cell indices that completely cover the bounds of the geometry argument.
  • ST_Square — Returns a single square, using the provided edge size and cell coordinate within the square grid space.
  • ST_Letters — Returns the input letters rendered as geometry with a default start position at the origin and default text height of 100.

Name

ST_Collect — Creates a GeometryCollection or Multi* geometry from a set of geometries.

Synopsis

geometry ST_Collect(geometry g1, geometry g2);

geometry ST_Collect(geometry[] g1_array);

geometry ST_Collect(geometry set g1field);

Descrizione

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.

[Note]

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).

[Note]

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.

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo supporta le Curve e le Circular String.

Esempi - uso di XLink

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))

Esempi - superficie poliedrica

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))

Examples - Aggregate variant

Creating multiple collections by grouping geometries in a table.

SELECT stusps, ST_Collect(f.geom) as geom
         FROM (SELECT stusps, (ST_Dump(geom)).geom As geom
                                FROM
                                somestatetable ) As f
        GROUP BY stusps

Si veda anche

ST_Dump, ST_AsBinary


Name

ST_LineFromMultiPoint — Crea una LineString da una geometria MultiPoint.

Synopsis

geometry ST_LineFromMultiPoint(geometry aMultiPoint);

Descrizione

Crea una LineString da una geometria MultiPoint.

Use ST_MakeLine to create lines from Point or LineString inputs.

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

Crea una LineString 3D da una geometria MultiPoint 3D.

SELECT ST_AsEWKT(  ST_LineFromMultiPoint('MULTIPOINT(1 2 3, 4 5 6, 7 8 9)')  ));

--result--
LINESTRING(1 2 3,4 5 6,7 8 9)

Si veda anche

ST_AsEWKT, ST_AsKML


Name

ST_MakeEnvelope — Creates a rectangular Polygon from minimum and maximum coordinates.

Synopsis

geometry ST_MakeEnvelope(float xmin, float ymin, float xmax, float ymax, integer srid=unknown);

Descrizione

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.

Example: Building a bounding box polygon

SELECT ST_AsText( ST_MakeEnvelope(10, 10, 11, 11, 4326) );

st_asewkt
-----------
POLYGON((10 10, 10 11, 11 11, 11 10, 10 10))

Name

ST_MakeLine — Crea una LineString da una geometria Point, MultiPoint o un set di LineString

Synopsis

geometry ST_MakeLine(geometry geom1, geometry geom2);

geometry ST_MakeLine(geometry[] geoms_array);

geometry ST_MakeLine(geometry set geoms);

Descrizione

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.

Questa funzione supporta il 3d e non distrugge gli 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.

Examples: Two-input variant

Create a line composed of two points.

SELECT ST_AsText( ST_MakeLine(ST_Point(1,2), ST_Point(3,4)) );

          st_astext
---------------------
 LINESTRING(1 2,3 4)

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)

Examples: Array variant

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_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)

Examples: Aggregate variant

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;

Name

ST_MakePoint — Creates a 2D, 3DZ or 4D Point.

Synopsis

geometry ST_MakePoint(float x, float y);

geometry ST_MakePoint(float x, float y, float z);

geometry ST_MakePoint(float x, float y, float z, float m);

Descrizione

Creates a 2D XY, 3D XYZ or 4D XYZM Point geometry. Use ST_MakePointM to make points with XYM coordinates.

Use ST_SetSRID to specify a SRID for the created point.

While not OGC-compliant, ST_MakePoint is faster and more precise than ST_GeomFromText and ST_PointFromText. It is also easier to use for numeric coordinate values.

[Note]

For geodetic coordinates, X is longitude and Y is latitude

[Note]

The functions ST_Point, ST_PointZ, ST_PointM, and ST_PointZM can be used to create points with a given SRID.

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

-- Create a point with unknown SRID
SELECT ST_MakePoint(-71.1043443253471, 42.3150676015829);

-- Create a point in the WGS 84 geodetic CRS
SELECT ST_SetSRID(ST_MakePoint(-71.1043443253471, 42.3150676015829),4326);

-- Create a 3D point (e.g. has altitude)
SELECT ST_MakePoint(1, 2,1.5);

-- Get z of point
SELECT ST_Z(ST_MakePoint(1, 2,1.5));
result
-------
1.5

Name

ST_MakePointM — Creates a Point from X, Y and M values.

Synopsis

geometry ST_MakePointM(float x, float y, float m);

Descrizione

Creates a point with X, Y and M (measure) ordinates. Use ST_MakePoint to make points with XY, XYZ, or XYZM coordinates.

Use ST_SetSRID to specify a SRID for the created point.

[Note]

For geodetic coordinates, X is longitude and Y is latitude

[Note]

The functions ST_PointM, and ST_PointZM can be used to create points with an M value and a given SRID.

Esempi

[Note]

ST_AsEWKT is used for text output because ST_AsText does not support M values.

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

Name

ST_MakePolygon — Creates a Polygon from a shell and optional list of holes.

Synopsis

geometry ST_MakePolygon(geometry linestring);

geometry ST_MakePolygon(geometry outerlinestring, geometry[] interiorlinestrings);

Descrizione

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.

[Note]

This function does not accept MultiLineStrings. Use ST_LineMerge to generate a LineString, or ST_Dump to extract LineStrings.

Questa funzione supporta il 3d e non distrugge gli z-index.

Examples: Single input variant

Create a Polygon from a 2D LineString.

SELECT ST_MakePolygon( ST_GeomFromText('LINESTRING(75 29,77 29,77 29, 75 29)'));

Create a Polygon from an open LineString, using ST_StartPoint and ST_AddPoint to close it.

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))

Examples: Outer shell with inner holes variant

Create a donut Polygon with an extra hole

SELECT ST_MakePolygon( ST_ExteriorRing( ST_Buffer(ring.line,10)),
        ARRAY[  ST_Translate(ring.line, 1, 1),
                ST_ExteriorRing(ST_Buffer(ST_Point(20,20),1)) ]
        )
FROM (SELECT ST_ExteriorRing(
        ST_Buffer(ST_Point(10,10),10,10)) AS line ) AS ring;

Create a set of province boundaries with holes representing lakes. The input is a table of province Polygons/MultiPolygons and a table of water linestrings. Lines forming lakes are determined by using ST_IsClosed. The province linework is extracted by using ST_Boundary. As required by ST_MakePolygon, the boundary is forced to be a single LineString by using ST_LineMerge. (However, note that if a province has more than one region or has islands this will produce an invalid polygon.) Using a LEFT JOIN ensures all provinces are included even if they have no lakes.

[Note]

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 EXISTS( SELECT w.geom
        FROM waterlines w
        WHERE ST_Within(w.geom, p.geom)
        AND ST_IsClosed(w.geom))
    THEN ST_MakePolygon(
        ST_LineMerge(ST_Boundary(p.geom)),
        ARRAY( SELECT w.geom
            FROM waterlines w
            WHERE ST_Within(w.geom, p.geom)
            AND ST_IsClosed(w.geom)))
    ELSE p.geom
    END AS geom
FROM provinces p;

Si veda anche

ST_BuildArea ST_Polygon


Name

ST_Point — Creates a Point with X, Y and SRID values.

Synopsis

geometry ST_Point(float x, float y);

geometry ST_Point(float x, float y, integer srid=unknown);

Descrizione

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.

[Note]

For geodetic coordinates, X is longitude and Y is latitude

Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID to mark the srid on the geometry.

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 6.1.2

Examples: Geometry

SELECT ST_Point( -71.104, 42.315);

Creating a point with SRID specified:

SELECT ST_Point( -71.104, 42.315, 4326);

Alternative way of specifying SRID:

SELECT ST_SetSRID( ST_Point( -71.104, 42.315), 4326);

Examples: Geography

Create geography points using the :: cast syntax:

SELECT ST_Point( -71.104, 42.315, 4326)::geography;

Pre-PostGIS 3.2 code, using CAST:

SELECT CAST( ST_SetSRID(ST_Point( -71.104, 42.315), 4326) AS geography);

If the point coordinates are not in a geodetic coordinate system (such as WGS84), then they must be reprojected before casting to a geography. In this example a point in Pennsylvania State Plane feet (SRID 2273) is projected to WGS84 (SRID 4326).

SELECT ST_Transform( ST_Point( 3637510, 3014852, 2273), 4326)::geography;

Name

ST_PointZ — Creates a Point with X, Y, Z and SRID values.

Synopsis

geometry ST_PointZ(float x, float y, float z, integer srid=unknown);

Descrizione

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.

Esempi

SELECT ST_PointZ(-71.104, 42.315, 3.4, 4326)
SELECT ST_PointZ(-71.104, 42.315, 3.4, srid => 4326)
SELECT ST_PointZ(-71.104, 42.315, 3.4)

Name

ST_PointM — Creates a Point with X, Y, M and SRID values.

Synopsis

geometry ST_PointM(float x, float y, float m, integer srid=unknown);

Descrizione

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.

Esempi

SELECT ST_PointM(-71.104, 42.315, 3.4, 4326)
SELECT ST_PointM(-71.104, 42.315, 3.4, srid => 4326)
SELECT ST_PointM(-71.104, 42.315, 3.4)

Name

ST_PointZM — Creates a Point with X, Y, Z, M and SRID values.

Synopsis

geometry ST_PointZM(float x, float y, float z, float m, integer srid=unknown);

Descrizione

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.

Esempi

SELECT ST_PointZM(-71.104, 42.315, 3.4, 4.5, 4326)
SELECT ST_PointZM(-71.104, 42.315, 3.4, 4.5, srid => 4326)
SELECT ST_PointZM(-71.104, 42.315, 3.4, 4.5)

Name

ST_Polygon — Creates a Polygon from a LineString with a specified SRID.

Synopsis

geometry ST_Polygon(geometry lineString, integer srid);

Descrizione

Returns a polygon built from the given LineString and sets the spatial reference system from the srid.

ST_Polygon is similar to ST_MakePolygon Variant 1 with the addition of setting the SRID.

, ST_MakePoint, ST_SetSRID

[Note]

This function does not accept MultiLineStrings. Use ST_LineMerge to generate a LineString, or ST_Dump to extract LineStrings.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1.

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 8.3.2

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

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))

Name

ST_TileEnvelope — Creates a rectangular Polygon in Web Mercator (SRID:3857) using the XYZ tile system.

Synopsis

geometry ST_TileEnvelope(integer tileZoom, integer tileX, integer tileY, geometry bounds=SRID=3857;LINESTRING(-20037508.342789 -20037508.342789,20037508.342789 20037508.342789), float margin=0.0);

Descrizione

Creates a rectangular Polygon giving the extent of a tile in the XYZ tile system. The tile is specified by the zoom level Z and the XY index of the tile in the grid at that level. Can be used to define the tile bounds required by ST_AsMVTGeom to convert geometry into the MVT tile coordinate space.

By default, the tile envelope is in the Web Mercator coordinate system (SRID:3857) using the standard range of the Web Mercator system (-20037508.342789, 20037508.342789). This is the most common coordinate system used for MVT tiles. The optional bounds parameter can be used to generate tiles in any coordinate system. It is a geometry that has the SRID and extent of the "Zoom Level zero" square within which the XYZ tile system is inscribed.

The optional margin parameter can be used to expand a tile by the given percentage. E.g. margin=0.125 expands the tile by 12.5%, which is equivalent to buffer=512 when the tile extent size is 4096, as used in ST_AsMVTGeom. This is useful to create a tile buffer to include data lying outside of the tile's visible area, but whose existence affects the tile rendering. For example, a city name (a point) could be near an edge of a tile, so its label should be rendered on two tiles, even though the point is located in the visible area of just one tile. Using expanded tiles in a query will include the city point in both tiles. Use a negative value to shrink the tile instead. Values less than -0.5 are prohibited because that would eliminate the tile completely. Do not specify a margin when using with ST_AsMVTGeom. See the example for ST_AsMVT.

Miglioramento nella versione: 2.0.0 introdotto opzionale parametro SRID.

Disponibilità: dalla versione 1.5.

Example: Building a tile envelope

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))

Si veda anche

ST_MakeEnvelope


Name

ST_HexagonGrid — Returns a set of hexagons and cell indices that completely cover the bounds of the geometry argument.

Synopsis

setof record ST_HexagonGrid(float8 size, geometry bounds);

Descrizione

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.

Example: Counting points in hexagons

To do a point summary against a hexagonal tiling, generate a hexagon grid using the extent of the points as the bounds, then spatially join to that grid.

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;

Example: Generating hex coverage of polygons

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.

[Note]

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)

Name

ST_Hexagon — Returns a single hexagon, using the provided edge size and cell coordinate within the hexagon grid space.

Synopsis

geometry ST_Hexagon(float8 size, integer cell_i, integer cell_j, geometry origin);

Descrizione

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.

Example: Creating a hexagon at the origin

SELECT ST_AsText(ST_SetSRID(ST_Hexagon(1.0, 0, 0), 3857));

POLYGON((-1 0,-0.5
         -0.866025403784439,0.5
         -0.866025403784439,1
         0,0.5
         0.866025403784439,-0.5
         0.866025403784439,-1 0)) 

Name

ST_SquareGrid — Returns a set of grid squares and cell indices that completely cover the bounds of the geometry argument.

Synopsis

setof record ST_SquareGrid(float8 size, geometry bounds);

Descrizione

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.

Example: Generating a 1 degree grid for a country

The grid will fill the whole bounds of the country, so if you want just squares that touch the country you will have to filter afterwards with ST_Intersects.

WITH grid AS (
SELECT (ST_SquareGrid(1, ST_Transform(geom,4326))).*
FROM admin0 WHERE name = 'Canada'
)
  SELEcT ST_AsText(geom)
  FROM grid

Example: Counting points in squares (using single chopped grid)

To do a point summary against a square tiling, generate a square grid using the extent of the points as the bounds, then spatially join to that grid. Note the estimated extent might be off from actual extent, so be cautious and at very least make sure you've analyzed your table.

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

Example: Counting points in squares using set of grid per point

This yields the same result as the first example but will be slower for a large number of points

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

Name

ST_Square — Returns a single square, using the provided edge size and cell coordinate within the square grid space.

Synopsis

geometry ST_Square(float8 size, integer cell_i, integer cell_j, geometry origin);

Descrizione

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.

Example: Creating a square at the origin

SELECT ST_AsText(ST_SetSRID(ST_Square(1.0, 0, 0), 3857));

 POLYGON((0 0,0 1,1 1,1 0,0 0))

Name

ST_Letters — Returns the input letters rendered as geometry with a default start position at the origin and default text height of 100.

Synopsis

geometry ST_Letters(text letters, json font);

Descrizione

Uses a built-in font to render out a string as a multipolygon geometry. The default text height is 100.0, the distance from the bottom of a descender to the top of a capital. The default start position places the start of the baseline at the origin. Over-riding the font involves passing in a json map, with a character as the key, and base64 encoded TWKB for the font shape, with the fonts having a height of 1000 units from the bottom of the descenders to the tops of the capitals.

The text is generated at the origin by default, so to reposition and resize the text, first apply the ST_Scale function and then apply the ST_Translate function.

Availability: 3.3.0

Example: Generating the word 'Yo'

SELECT ST_AsText(ST_Letters('Yo'), 1);

Letters generated by ST_Letters

Example: Scaling and moving words

SELECT ST_Translate(ST_Scale(ST_Letters('Yo'), 10, 10), 100,100);

7.4. Accessori alla geometria

  • GeometryType — Restituisce il tipo di geometria come testo.
  • ST_Boundary — Restituisce il confine di una geometria.
  • ST_BoundingDiagonal — Restituisce la diagonale del rettangolo di confine di una geometria.
  • ST_CoordDim — Restituisce la dimensione delle coordinate di una geometrie.
  • ST_Dimension — Restituisce la dimensione topologica di una geometria.
  • ST_Dump — Returns a set of geometry_dump rows for the components of a geometry.
  • ST_DumpPoints — Returns a set of geometry_dump rows for the coordinates in a geometry.
  • ST_DumpSegments — Returns a set of geometry_dump rows for the segments in a geometry.
  • ST_DumpRings — Returns a set of geometry_dump rows for the exterior and interior rings of a Polygon.
  • ST_EndPoint — Returns the last point of a LineString or CircularLineString.
  • ST_Envelope — Returns a geometry representing the bounding box of a geometry.
  • ST_ExteriorRing — Returns a LineString representing the exterior ring of a Polygon.
  • ST_GeometryN — Restituisce il tipo di geometria per il valore ST_Geometry.
  • ST_GeometryType — Restituisce il tipo di geometria per il valore ST_Geometry.
  • ST_HasArc — Tests if a geometry contains a circular arc
  • ST_InteriorRingN — Returns the Nth interior ring (hole) of a Polygon.
  • ST_NumCurves — Return the number of component curves in a CompoundCurve.
  • ST_CurveN — Returns the Nth component curve geometry of a CompoundCurve.
  • ST_IsClosed — Restituisce TRUE se il punto iniziale e quello finale di LINESTRING coincidono. Per le superfici poliedriche indica una superficie chiusa (volumetrica).
  • ST_IsCollection — Restituisce TRUE se la geometria è una geometrycollection, un poligono o un punto vuoto, ecc.
  • ST_IsEmpty — Tests if a geometry is empty.
  • ST_IsPolygonCCW — Tests if Polygons have exterior rings oriented counter-clockwise and interior rings oriented clockwise.
  • ST_IsPolygonCW — Tests if Polygons have exterior rings oriented clockwise and interior rings oriented counter-clockwise.
  • ST_IsRing — Tests if a LineString is closed and simple.
  • ST_IsSimple — Tests if a geometry has no points of self-intersection or self-tangency.
  • ST_M — Returns the M coordinate of a Point.
  • ST_MemSize — Restituisce il tipo di geometria per il valore ST_Geometry.
  • ST_NDims — Restituisce la dimensione delle coordinate di una geometria.
  • ST_NPoints — Returns the number of points (vertices) in a geometry.
  • ST_NRings — Returns the number of rings in a polygonal geometry.
  • ST_NumGeometries — Restituisce TRUE se la geometria è una geometrycollection, un poligono o un punto vuoto, ecc.
  • ST_NumInteriorRings — Returns the number of interior rings (holes) of a Polygon.
  • ST_NumInteriorRing — Returns the number of interior rings (holes) of a Polygon. Aias for ST_NumInteriorRings
  • ST_NumPatches — Return the number of faces on a Polyhedral Surface. Will return null for non-polyhedral geometries.
  • ST_NumPoints — Returns the number of points in a LineString or CircularString.
  • ST_PatchN — Restituisce il tipo di geometria per il valore ST_Geometry.
  • ST_PointN — Returns the Nth point in the first LineString or circular LineString in a geometry.
  • ST_Points — Restituisce un MultiPoint contenente le coordinate di una geometria.
  • ST_StartPoint — Returns the first point of a LineString.
  • ST_Summary — Returns a text summary of the contents of a geometry.
  • ST_X — Returns the X coordinate of a Point.
  • ST_Y — Returns the Y coordinate of a Point.
  • ST_Z — Returns the Z coordinate of a Point.
  • ST_Zmflag — Restituisce un codice indicante le dimensioni ZM di una geometria.
  • ST_HasZ — Checks if a geometry has a Z dimension.
  • ST_HasM — Checks if a geometry has an M (measure) dimension.

Name

GeometryType — Restituisce il tipo di geometria come testo.

Synopsis

text GeometryType(geometry geomA);

Descrizione

Restituisce il tipo di geometria come stringa. Ad esempio: 'LINESTRING', 'POLYGON', 'MULTIPOINT', ecc.

OGC SPEC s2.1.1.1 - Restituisce il nome del sottotipo istanziabile di Geometry di cui questa istanza di Geometry è membro. Il nome del sottotipo istanziabile di Geometry viene restituito come stringa.

[Note]

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.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1.

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta il 3d e non distrugge gli z-index.

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta i Triangoli e le Triangulated Irregular Network Surfaces (TIN).

Esempi

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    

Si veda anche

ST_GeometryType


Name

ST_Boundary — Restituisce il confine di una geometria.

Synopsis

geometry ST_Boundary(geometry geomA);

Descrizione

Restituisce la chiusura del confine combinatorio di questa geometria. Il confine combinatorio è definito come descritto nella sezione 3.12.3.2 di OGC SPEC. Poiché il risultato di questa funzione è una chiusura, e quindi topologicamente chiusa, il confine risultante può essere rappresentato utilizzando le primitive della geometria rappresentativa descritte nella sezione 3.12.2 di OGC SPEC.

Eseguito dal modulo GEOS

[Note]

Prma della 2.0.0, questa funzione dava un'eccezione se usata con GEOMETRYCOLLECTION. A partire dalla 2.0.0 in poi, restituirà invece NULL (input non supportato).

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1. OGC SPEC s2.1.1.1

Questo metodo implementa la specifica SQL/MM. SQL-MM IEC 13249-3: 5.1.17

Questa funzione supporta il 3d e non distrugge gli z-index.

Miglioramento: nella versione 2.1.0 è stato introdotto il supporto per Triangle

Modificato: dalla versione 3.2.0 supporta TIN, non usa geos, non linearizza le curve

Esempi

Linestring con sovrapposizione dei punti di confine

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))

buchi di poligoni con confini 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))

Name

ST_BoundingDiagonal — Restituisce la diagonale del rettangolo di confine di una geometria.

Synopsis

geometry ST_BoundingDiagonal(geometry geom, boolean fits=false);

Descrizione

Restituisce la diagonale del rettangolo di selezione della geometria fornita come una LineString. La diagonale è una LineString a 2 punti con i valori minimi di ciascuna dimensione nel punto iniziale e i valori massimi nel punto finale. Se la geometria di input è vuota, la diagonale è una LINESTRING EMPTY.

Il parametro opzionale fits specifica se è necessario il miglior adattamento. Se false, può essere accettata la diagonale di un rettangolo di selezione un po' più grande (che è più veloce da calcolare per geometrie con molti vertici). In entrambi i casi, il rettangolo di selezione della linea diagonale restituita copre sempre la geometria in ingresso.

La geometria restituita conserva il SRID e la dimensionalità (presenza di Z e M) della geometria di input.

[Note]

Nei casi degenerati (cioè con un solo vertice in ingresso) la linestring restituita sarà formalmente non valida (nessun interno). Il risultato è comunque topologicamente valido.

Disponibilità: 2.2.0

Questa funzione supporta il 3d e non distrugge gli z-index.

Questa funzione supporta le coordinate M.

Esempi

-- Get the minimum X in a buffer around a point
SELECT ST_X(ST_StartPoint(ST_BoundingDiagonal(
  ST_Buffer(ST_Point(0,0),10)
)));
 st_x
------
  -10
                

Name

ST_CoordDim — Restituisce la dimensione delle coordinate di una geometrie.

Synopsis

integer ST_CoordDim(geometry geomA);

Descrizione

Restituisce la dimensione delle coordinate del valore della ST_Geometry.

Questo è il nome dell'alias conforme a MM per ST_NDims

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1.

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 5.1.3

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta il 3d e non distrugge gli z-index.

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta i Triangoli e le Triangulated Irregular Network Surfaces (TIN).

Esempi

SELECT ST_CoordDim('CIRCULARSTRING(1 2 3, 1 3 4, 5 6 7, 8 9 10, 11 12 13)');
                        ---result--
                                3

                                SELECT ST_CoordDim(ST_Point(1,2));
                        --result--
                                2

                

Si veda anche

ST_NDims


Name

ST_Dimension — Restituisce la dimensione topologica di una geometria.

Synopsis

integer ST_Dimension(geometry g);

Descrizione

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 (ad esempio per una GEOMETRYCOLLECTION vuota), viene restituito il valore 0.

Questo metodo implementa la specifica SQL/MM. 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.

[Note]

Prima della 2.0.0, questa funzione dava un'eccezione se usata con una geometria vuota.

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta i Triangoli e le Triangulated Irregular Network Surfaces (TIN).

Esempi

SELECT ST_Dimension('GEOMETRYCOLLECTION(LINESTRING(1 1,0 0),POINT(0 0))');
ST_Dimension
-----------
1

Si veda anche

ST_NDims


Name

ST_Dump — Returns a set of geometry_dump rows for the components of a geometry.

Synopsis

geometry_dump[] ST_Dump(geometry g1);

Descrizione

A set-returning function (SRF) that extracts the components of a geometry. It returns a set of geometry_dump rows, each containing a geometry (geom field) and an array of integers (path field).

For an atomic geometry type (POINT,LINESTRING,POLYGON) a single record is returned with an empty path array and the input geometry as geom. For a collection or multi-geometry a record is returned for each of the collection components, and the path denotes the position of the component inside the collection.

ST_Dump is useful for expanding geometries. It is the inverse of a ST_Collect / GROUP BY, in that it creates new rows. For example it can be use to expand MULTIPOLYGONS into POLYGONS.

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.

[Note]

Prior to 1.3.4, this function crashes if used with geometries that contain CURVES. This is fixed in 1.3.4+

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta i Triangoli e le Triangulated Irregular Network Surfaces (TIN).

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi standard

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)

Esempi con superfici poliedriche, TIN e triangoli

-- 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))

Name

ST_DumpPoints — Returns a set of geometry_dump rows for the coordinates in a geometry.

Synopsis

geometry_dump[] ST_DumpPoints(geometry geom);

Descrizione

A set-returning function (SRF) that extracts the coordinates (vertices) of a geometry. It returns a set of geometry_dump rows, each containing a geometry (geom field) and an array of integers (path field).

  • the geom field POINTs represent the coordinates of the supplied geometry.

  • the path field (an integer[]) is an index enumerating the coordinate positions in the elements of the supplied geometry. The indices are 1-based. For example, for a LINESTRING the paths are {i} where i is the nth coordinate in the LINESTRING. For a POLYGON the paths are {i,j} where i is the ring number (1 is outer; inner rings follow) and j is the coordinate position in the ring.

To obtain a single geometry containing the coordinates use ST_Points.

Enhanced: 2.1.0 Faster speed. Reimplemented as native-C.

Migliorato: Nella 2.0.0 è stato introdotto il supporto per le superfici poliedriche, i triangoli e i TIN.

Disponibilità: 1.5.0

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta i Triangoli e le Triangulated Irregular Network Surfaces (TIN).

Questa funzione supporta il 3d e non distrugge gli z-index.

Classic Explode a Table of LineStrings into nodes

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)

Esempi standard

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)

Esempi con superfici poliedriche, TIN e triangoli

-- 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)

Name

ST_DumpSegments — Returns a set of geometry_dump rows for the segments in a geometry.

Synopsis

geometry_dump[] ST_DumpSegments(geometry geom);

Descrizione

A set-returning function (SRF) that extracts the segments of a geometry. It returns a set of geometry_dump rows, each containing a geometry (geom field) and an array of integers (path field).

  • the geom field LINESTRINGs represent the linear segments of the supplied geometry, while the CIRCULARSTRINGs represent the arc segments.

  • the path field (an integer[]) is an index enumerating the segment start point positions in the elements of the supplied geometry. The indices are 1-based. For example, for a LINESTRING the paths are {i} where i is the nth segment start point in the LINESTRING. For a POLYGON the paths are {i,j} where i is the ring number (1 is outer; inner rings follow) and j is the segment start point position in the ring.

Disponibilità: 3.2.0

Questa funzione supporta i Triangoli e le Triangulated Irregular Network Surfaces (TIN).

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi standard

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)

Esempi con superfici poliedriche, TIN e triangoli

-- 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)

Name

ST_DumpRings — Returns a set of geometry_dump rows for the exterior and interior rings of a Polygon.

Synopsis

geometry_dump[] ST_DumpRings(geometry a_polygon);

Descrizione

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.

[Note]

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.

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

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))

Name

ST_EndPoint — Returns the last point of a LineString or CircularLineString.

Synopsis

geometry ST_EndPoint(geometry g);

Descrizione

Restituisce l'ultimo punto di una geometria LINESTRING o CIRCULARLINESTRING come un POINT. Restituisce NULL se il parametro di input non è una LINESTRING o CIRCULARLINESTRING.

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 7.1.4

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo supporta le Curve e le Circular String.

[Note]

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.

Esempi

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)

Si veda anche

ST_PointN, ST_StartPoint


Name

ST_Envelope — Returns a geometry representing the bounding box of a geometry.

Synopsis

geometry ST_Envelope(geometry g1);

Descrizione

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

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.1

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 5.1.19

Esempi

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))

Name

ST_ExteriorRing — Returns a LineString representing the exterior ring of a Polygon.

Synopsis

geometry ST_ExteriorRing(geometry a_polygon);

Descrizione

Restituisce una LINESTRING che rappresenta l'anello esterno per una geometria POLYGON. Restituisce NULL se la geometria non è un poligono. Non funziona con MULTIPOLYGON

[Note]

Non funzionerà per i MULTIPOLYGON. Da utilizzare assieme a ST_GeometryN o ST_Dump per i MULTIPOLYGON

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1. 2.1.5.1

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 8.2.3, 8.3.3

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

--If you have a table of polygons
SELECT gid, ST_ExteriorRing(geom) AS ering
FROM sometable;

--If you have a table of MULTIPOLYGONs
--and want to return a MULTILINESTRING composed of the exterior rings of each polygon
SELECT gid, ST_Collect(ST_ExteriorRing(geom)) AS erings
        FROM (SELECT gid, (ST_Dump(geom)).geom As geom
                        FROM sometable) As foo
GROUP BY gid;

--3d Example
SELECT ST_AsEWKT(
        ST_ExteriorRing(
        ST_GeomFromEWKT('POLYGON((0 0 1, 1 1 1, 1 2 1, 1 1 1, 0 0 1))')
        )
);

st_asewkt
---------
LINESTRING(0 0 1,1 1 1,1 2 1,1 1 1,0 0 1)

Name

ST_GeometryN — Restituisce il tipo di geometria per il valore ST_Geometry.

Synopsis

geometry ST_GeometryN(geometry geomA, integer n);

Descrizione

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.

[Note]

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.

[Note]

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.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1.

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 9.1.5

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta i Triangoli e le Triangulated Irregular Network Surfaces (TIN).

Esempi standard

--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);

Esempi con superfici poliedriche, TIN e triangoli

-- 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))

Name

ST_GeometryType — Restituisce il tipo di geometria per il valore ST_Geometry.

Synopsis

text ST_GeometryType(geometry g1);

Descrizione

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.

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 5.1.4

Questa funzione supporta il 3d e non distrugge gli z-index.

Questa funzione supporta le Polyhedral Surface.

Esempi

SELECT ST_GeometryType(ST_GeomFromText('LINESTRING(77.29 29.07,77.42 29.26,77.27 29.31,77.29 29.07)'));
                        --result
                        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    

Si veda anche

GeometryType


Name

ST_HasArc — Tests if a geometry contains a circular arc

Synopsis

boolean ST_HasArc(geometry geomA);

Descrizione

Restituisce TRUE se la geometria è una geometrycollection, un poligono o un punto vuoto, ecc.

Disponibilità: 2.0

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo supporta le Curve e le Circular String.

Esempi

SELECT ST_HasArc(ST_Collect('LINESTRING(1 2, 3 4, 5 6)', 'CIRCULARSTRING(1 1, 2 3, 4 5, 6 7, 5 6)'));
                st_hasarc
                --------
                t
                

Name

ST_InteriorRingN — Returns the Nth interior ring (hole) of a Polygon.

Synopsis

geometry ST_InteriorRingN(geometry a_polygon, integer n);

Descrizione

Restituisce una LINESTRING che rappresenta l'anello esterno per una geometria POLYGON. Restituisce NULL se la geometria non è un poligono. Non funziona con MULTIPOLYGON

[Note]

Non funzionerà per i MULTIPOLYGON. Da utilizzare assieme a ST_GeometryN o ST_Dump per i MULTIPOLYGON

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1.

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 8.2.6, 8.3.5

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

SELECT ST_AsText(ST_InteriorRingN(geom, 1)) As geom
FROM (SELECT ST_BuildArea(
                ST_Collect(ST_Buffer(ST_Point(1,2), 20,3),
                        ST_Buffer(ST_Point(1, 2), 10,3))) As geom
                )  as foo;
                

Name

ST_NumCurves — Return the number of component curves in a CompoundCurve.

Synopsis

integer ST_NumCurves(geometry a_compoundcurve);

Descrizione

Return the number of component curves in a CompoundCurve, zero for an empty CompoundCurve, or NULL for a non-CompoundCurve input.

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 8.2.6, 8.3.5

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

-- Returns 3
SELECT ST_NumCurves('COMPOUNDCURVE(
    (2 2, 2.5 2.5),
    CIRCULARSTRING(2.5 2.5, 4.5 2.5, 3.5 3.5),
    (3.5 3.5, 2.5 4.5, 3 5, 2 2)
  )');

-- Returns 0
SELECT ST_NumCurves('COMPOUNDCURVE EMPTY');
        

Name

ST_CurveN — Returns the Nth component curve geometry of a CompoundCurve.

Synopsis

geometry ST_CurveN(geometry a_compoundcurve, integer index);

Descrizione

Returns the Nth component curve geometry of a CompoundCurve. The index starts at 1. Returns NULL if the geometry is not a CompoundCurve or the index is out of range.

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 8.2.6, 8.3.5

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

SELECT ST_AsText(ST_CurveN('COMPOUNDCURVE(
    (2 2, 2.5 2.5),
    CIRCULARSTRING(2.5 2.5, 4.5 2.5, 3.5 3.5),
    (3.5 3.5, 2.5 4.5, 3 5, 2 2)
  )', 1));
        

Name

ST_IsClosed — Restituisce TRUE se il punto iniziale e quello finale di LINESTRING coincidono. Per le superfici poliedriche indica una superficie chiusa (volumetrica).

Synopsis

boolean ST_IsClosed(geometry g);

Descrizione

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).

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1.

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 7.1.5, 9.3.3

[Note]

SQL-MM defines the result of ST_IsClosed(NULL) to be 0, while PostGIS returns NULL.

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo supporta le Curve e le Circular String.

Miglioramento: nella versione 2.0.0 è stato introdotto il supporto per le superfici poliedriche.

Questa funzione supporta le Polyhedral Surface.

Esempi con Stringhe di linee e punti

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)

Esempi con superfici poliedriche

-- 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

Si veda anche

ST_IsRing


Name

ST_IsCollection — Restituisce TRUE se la geometria è una geometrycollection, un poligono o un punto vuoto, ecc.

Synopsis

boolean ST_IsCollection(geometry g);

Descrizione

Restituisce TRUE se il tipo di geometria è uno tra:

  • GEOMETRYCOLLECTION

  • MULTI{POINT,POLYGON,LINESTRING,CURVE,SURFACE}

  • COMPOUNDCURVE

[Note]

Questa funzione analizza il tipo di geometria. Significa che restituirà TRUE sulle collezioni che sono vuote o contengono un singolo elemento.

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo supporta le Curve e le Circular String.

Esempi

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)

Si veda anche

ST_NumGeometries


Name

ST_IsEmpty — Tests if a geometry is empty.

Synopsis

boolean ST_IsEmpty(geometry geomA);

Descrizione

Restituisce TRUE se la Geometry è una geometria vuota. Se è TRUE, allora questa Geometry rappresenta una geometria vuota (una collezione, un poligono, un punto, ecc.)

[Note]

SQL-MM definisce il risultato di ST_IsEmpty(NULL) come 0, mentre PostGIS restituisce NULL.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.1

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 5.1.7

Questo metodo supporta le Curve e le Circular String.

[Warning]

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

Esempi

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)


                

Name

ST_IsPolygonCCW — Tests if Polygons have exterior rings oriented counter-clockwise and interior rings oriented clockwise.

Synopsis

boolean ST_IsPolygonCCW ( geometry geom );

Descrizione

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.

[Note]

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.

[Note]

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.4.0

Questa funzione supporta il 3d e non distrugge gli z-index.

Questa funzione supporta le coordinate M.


Name

ST_IsPolygonCW — Tests if Polygons have exterior rings oriented clockwise and interior rings oriented counter-clockwise.

Synopsis

boolean ST_IsPolygonCW ( geometry geom );

Descrizione

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.

[Note]

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.

[Note]

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.4.0

Questa funzione supporta il 3d e non distrugge gli z-index.

Questa funzione supporta le coordinate M.


Name

ST_IsRing — Tests if a LineString is closed and simple.

Synopsis

boolean ST_IsRing(geometry g);

Descrizione

Returns TRUE if this LINESTRING is both ST_IsClosed (ST_StartPoint(g) ~= ST_Endpoint(g)) and ST_IsSimple (does not self intersect).

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1. 2.1.5.1

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 7.1.6

[Note]

SQL-MM defines the result of ST_IsRing(NULL) to be 0, while PostGIS returns NULL.

Esempi

SELECT ST_IsRing(geom), ST_IsClosed(geom), ST_IsSimple(geom)
FROM (SELECT 'LINESTRING(0 0, 0 1, 1 1, 1 0, 0 0)'::geometry AS geom) AS foo;
 st_isring | st_isclosed | st_issimple
-----------+-------------+-------------
 t         | t           | t
(1 row)

SELECT ST_IsRing(geom), ST_IsClosed(geom), ST_IsSimple(geom)
FROM (SELECT 'LINESTRING(0 0, 0 1, 1 0, 1 1, 0 0)'::geometry AS geom) AS foo;
 st_isring | st_isclosed | st_issimple
-----------+-------------+-------------
 f         | t           | f
(1 row)

Name

ST_IsSimple — Tests if a geometry has no points of self-intersection or self-tangency.

Synopsis

boolean ST_IsSimple(geometry geomA);

Descrizione

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 compliance of geometries"

[Note]

SQL-MM defines the result of ST_IsSimple(NULL) to be 0, while PostGIS returns NULL.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.1

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 5.1.8

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

SELECT ST_IsSimple(ST_GeomFromText('POLYGON((1 2, 3 4, 5 6, 1 2))'));
 st_issimple
-------------
 f
(1 row)

 SELECT ST_IsSimple(ST_GeomFromText('LINESTRING(1 1,2 2,2 3.5,1 3,1 2,2 1)'));
 st_issimple
-------------
 f
(1 row)

Si veda anche

ST_IsValid


Name

ST_M — Returns the M coordinate of a Point.

Synopsis

float ST_M(geometry a_point);

Descrizione

Restituisce la coordinata M del punto, o NULL se non disponibile. L'input deve essere un punto.

[Note]

This is not (yet) part of the OGC spec, but is listed here to complete the point coordinate extractor function list.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1.

Questo metodo implementa la specifica SQL/MM.

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

SELECT ST_M(ST_GeomFromEWKT('POINT(1 2 3 4)'));
 st_m
------
        4
(1 row)

                

Si veda anche

ST_GeomFromEWKT, ST_X, ST_Y, ST_Z


Name

ST_MemSize — Restituisce il tipo di geometria per il valore ST_Geometry.

Synopsis

integer ST_MemSize(geometry geomA);

Descrizione

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.

[Note]

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

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta i Triangoli e le Triangulated Irregular Network Surfaces (TIN).

Changed: 2.2.0 name changed to ST_MemSize to follow naming convention.

Esempi

--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
        

Name

ST_NDims — Restituisce la dimensione delle coordinate di una geometria.

Synopsis

integer ST_NDims(geometry g1);

Descrizione

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

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

SELECT ST_NDims(ST_GeomFromText('POINT(1 1)')) As d2point,
        ST_NDims(ST_GeomFromEWKT('POINT(1 1 2)')) As d3point,
        ST_NDims(ST_GeomFromEWKT('POINTM(1 1 0.5)')) As d2pointm;

         d2point | d3point | d2pointm
---------+---------+----------
           2 |       3 |        3
                        

Name

ST_NPoints — Returns the number of points (vertices) in a geometry.

Synopsis

integer ST_NPoints(geometry g1);

Descrizione

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.

[Note]

Prior to 1.3.4, this function crashes if used with geometries that contain CURVES. This is fixed in 1.3.4+

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Esempi

SELECT ST_NPoints(ST_GeomFromText('LINESTRING(77.29 29.07,77.42 29.26,77.27 29.31,77.29 29.07)'));
--result
4

--Polygon in 3D space
SELECT ST_NPoints(ST_GeomFromEWKT('LINESTRING(77.29 29.07 1,77.42 29.26 0,77.27 29.31 -1,77.29 29.07 3)'))
--result
4

Si veda anche

ST_NumPoints


Name

ST_NRings — Returns the number of rings in a polygonal geometry.

Synopsis

integer ST_NRings(geometry geomA);

Descrizione

If the geometry is a polygon or multi-polygon returns the number of rings. Unlike NumInteriorRings, it counts the outer rings as well.

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo supporta le Curve e le Circular String.

Esempi

SELECT ST_NRings(geom) As Nrings, ST_NumInteriorRings(geom) As ninterrings
                                        FROM (SELECT ST_GeomFromText('POLYGON((1 2, 3 4, 5 6, 1 2))') As geom) As foo;
         nrings | ninterrings
--------+-------------
          1 |           0
(1 row)

Si veda anche

ST_NumInteriorRings


Name

ST_NumGeometries — Restituisce TRUE se la geometria è una geometrycollection, un poligono o un punto vuoto, ecc.

Synopsis

integer ST_NumGeometries(geometry geom);

Descrizione

Returns the number of elements in a geometry collection (GEOMETRYCOLLECTION or MULTI*). For non-empty atomic geometries returns 1. For empty geometries returns 0.

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.

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 9.1.4

Questa funzione supporta il 3d e non distrugge gli z-index.

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta i Triangoli e le Triangulated Irregular Network Surfaces (TIN).

Esempi

--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

Si veda anche

ST_GeometryN, ST_Multi


Name

ST_NumInteriorRings — Returns the number of interior rings (holes) of a Polygon.

Synopsis

integer ST_NumInteriorRings(geometry a_polygon);

Descrizione

Return the number of interior rings of a polygon geometry. Return NULL if the geometry is not a polygon.

Questo metodo implementa la specifica SQL/MM. 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.

Esempi

--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;
                        

Name

ST_NumInteriorRing — Returns the number of interior rings (holes) of a Polygon. Aias for ST_NumInteriorRings

Synopsis

integer ST_NumInteriorRing(geometry a_polygon);


Name

ST_NumPatches — Return the number of faces on a Polyhedral Surface. Will return null for non-polyhedral geometries.

Synopsis

integer ST_NumPatches(geometry g1);

Descrizione

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

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1.

Questo metodo implementa la specifica SQL/MM. SQL-MM ISO/IEC 13249-3: 8.5

Questa funzione supporta le Polyhedral Surface.

Esempi

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
                

Name

ST_NumPoints — Returns the number of points in a LineString or CircularString.

Synopsis

integer ST_NumPoints(geometry g1);

Descrizione

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 vertices for not just linestrings. Consider using ST_NPoints instead which is multi-purpose and works with many geometry types.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1.

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 7.2.4

Esempi

SELECT ST_NumPoints(ST_GeomFromText('LINESTRING(77.29 29.07,77.42 29.26,77.27 29.31,77.29 29.07)'));
                --result
                4
                

Si veda anche

ST_NPoints


Name

ST_PatchN — Restituisce il tipo di geometria per il valore ST_Geometry.

Synopsis

geometry ST_PatchN(geometry geomA, integer n);

Descrizione

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.

[Note]

L'indice parte da 1.

[Note]

Se volete estrarre tutte le geometria, ST_Dump è più efficiente e funziona anche nel caso di geometrie singole.

Disponibilità: 2.0.0

Questo metodo implementa la specifica SQL/MM. SQL-MM ISO/IEC 13249-3: 8.5

Questa funzione supporta il 3d e non distrugge gli z-index.

Questa funzione supporta le Polyhedral Surface.

Esempi

--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))

Name

ST_PointN — Returns the Nth point in the first LineString or circular LineString in a geometry.

Synopsis

geometry ST_PointN(geometry a_linestring, integer n);

Descrizione

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.

[Note]

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.

[Note]

If you want to get the Nth point of each LineString in a MultiLineString, use in conjunction with ST_Dump

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1.

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 7.2.5, 7.3.5

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo supporta le Curve e le Circular String.

[Note]

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)

Esempi

-- 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)

Si veda anche

ST_NPoints


Name

ST_Points — Restituisce un MultiPoint contenente le coordinate di una geometria.

Synopsis

geometry ST_Points( geometry geom );

Descrizione

Returns a MultiPoint containing all the coordinates of a geometry. Duplicate points are preserved, including the start and end points of ring geometries. (If desired, duplicate points can be removed by calling ST_RemoveRepeatedPoints on the result).

To obtain information about the position of each coordinate in the parent geometry use ST_DumpPoints.

M and Z coordinates are preserved if present.

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta il 3d e non distrugge gli z-index.

Availability: 2.3.0

Esempi

SELECT ST_AsText(ST_Points('POLYGON Z ((30 10 4,10 30 5,40 40 6, 30 10))'));

--result
MULTIPOINT Z ((30 10 4),(10 30 5),(40 40 6),(30 10 4))
                        

Name

ST_StartPoint — Returns the first point of a LineString.

Synopsis

geometry ST_StartPoint(geometry geomA);

Descrizione

Returns the first point of a LINESTRING or CIRCULARLINESTRING geometry as a POINT. Returns NULL if the input is not a LINESTRING or CIRCULARLINESTRING.

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 7.1.3

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo supporta le Curve e le Circular String.

[Note]

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.

Esempi

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)

Si veda anche

ST_EndPoint, ST_PointN


Name

ST_Summary — Returns a text summary of the contents of a geometry.

Synopsis

text ST_Summary(geometry g);

text ST_Summary(geography g);

Descrizione

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

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta i Triangoli e le 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

Esempi

=# 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)


Name

ST_X — Returns the X coordinate of a Point.

Synopsis

float ST_X(geometry a_point);

Descrizione

Restituisce la coordinata X del punto, o NULL se non disponibile. L'input deve essere un punto.

[Note]

To get the minimum and maximum X value of geometry coordinates use the functions ST_XMin and ST_XMax.

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 6.1.3

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

SELECT ST_X(ST_GeomFromEWKT('POINT(1 2 3 4)'));
 st_x
------
        1
(1 row)

SELECT ST_Y(ST_Centroid(ST_GeomFromEWKT('LINESTRING(1 2 3 4, 1 1 1 1)')));
 st_y
------
  1.5
(1 row)

                

Name

ST_Y — Returns the Y coordinate of a Point.

Synopsis

float ST_Y(geometry a_point);

Descrizione

Restituisce la coordinata Y del punto, o NULL se non disponibile. L'input deve essere un punto.

[Note]

To get the minimum and maximum Y value of geometry coordinates use the functions ST_YMin and ST_YMax.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1.

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 6.1.4

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

SELECT ST_Y(ST_GeomFromEWKT('POINT(1 2 3 4)'));
 st_y
------
        2
(1 row)

SELECT ST_Y(ST_Centroid(ST_GeomFromEWKT('LINESTRING(1 2 3 4, 1 1 1 1)')));
 st_y
------
  1.5
(1 row)


                

Name

ST_Z — Returns the Z coordinate of a Point.

Synopsis

float ST_Z(geometry a_point);

Descrizione

Restituisce la coordinata Z del punto, o NULL se non disponibile. L'input deve essere un punto.

[Note]

To get the minimum and maximum Z value of geometry coordinates use the functions ST_ZMin and ST_ZMax.

Questo metodo implementa la specifica SQL/MM.

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

SELECT ST_Z(ST_GeomFromEWKT('POINT(1 2 3 4)'));
 st_z
------
        3
(1 row)

                

Name

ST_Zmflag — Restituisce un codice indicante le dimensioni ZM di una geometria.

Synopsis

smallint ST_Zmflag(geometry geomA);

Descrizione

Restituisce un codice indicante le dimensioni ZM di una geometria.

Values are: 0 = 2D, 1 = 3D-M, 2 = 3D-Z, 3 = 4D.

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo supporta le Curve e le Circular String.

Esempi

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

Name

ST_HasZ — Checks if a geometry has a Z dimension.

Synopsis

boolean ST_HasZ(geometry geom);

Descrizione

Checks if the input geometry has a Z dimension and returns a boolean value. If the geometry has a Z dimension, it returns true; otherwise, it returns false.

Geometry objects with a Z dimension typically represent three-dimensional (3D) geometries, while those without it are two-dimensional (2D) geometries.

This function is useful for determining if a geometry has elevation or height information.

Availability: 3.5.0

Questa funzione supporta il 3d e non distrugge gli z-index.

Questa funzione supporta le coordinate M.

Esempi

SELECT ST_HasZ(ST_GeomFromText('POINT(1 2 3)'));
 --result
 true
SELECT ST_HasZ(ST_GeomFromText('LINESTRING(0 0, 1 1)'));
 --result
 false

Si veda anche

ST_Zmflag

ST_HasM


Name

ST_HasM — Checks if a geometry has an M (measure) dimension.

Synopsis

boolean ST_HasM(geometry geom);

Descrizione

Checks if the input geometry has an M (measure) dimension and returns a boolean value. If the geometry has an M dimension, it returns true; otherwise, it returns false.

Geometry objects with an M dimension typically represent measurements or additional data associated with spatial features.

This function is useful for determining if a geometry includes measure information.

Availability: 3.5.0

Questa funzione supporta il 3d e non distrugge gli z-index.

Questa funzione supporta le coordinate M.

Esempi

SELECT ST_HasM(ST_GeomFromText('POINTM(1 2 3)'));
 --result
 true
SELECT ST_HasM(ST_GeomFromText('LINESTRING(0 0, 1 1)'));
 --result
 false

Si veda anche

ST_Zmflag

ST_HasZ

7.5. Editori di geometria

Abstract

Queste funzioni creano geometrie modificate cambiando tipo, struttura o vertici.

  • ST_AddPoint — Aggiunge un punto a una stringa di linee.
  • ST_CollectionExtract — Given a geometry collection, returns a multi-geometry containing only elements of a specified type.
  • ST_CollectionHomogenize — Returns the simplest representation of a geometry collection.
  • ST_CurveToLine — Converts a geometry containing curves to a linear geometry.
  • ST_Scroll — Change start point of a closed LineString.
  • ST_FlipCoordinates — Returns a version of a geometry with X and Y axis flipped.
  • ST_Force2D — Force the geometries into a "2-dimensional mode".
  • ST_Force3D — Force the geometries into XYZ mode. This is an alias for ST_Force3DZ.
  • ST_Force3DZ — Force the geometries into XYZ mode.
  • ST_Force3DM — Force the geometries into XYM mode.
  • ST_Force4D — Force the geometries into XYZM mode.
  • ST_ForceCollection — Convert the geometry into a GEOMETRYCOLLECTION.
  • ST_ForceCurve — Upcast a geometry into its curved type, if applicable.
  • ST_ForcePolygonCCW — Orients all exterior rings counter-clockwise and all interior rings clockwise.
  • ST_ForcePolygonCW — Orients all exterior rings clockwise and all interior rings counter-clockwise.
  • ST_ForceSFS — Force the geometries to use SFS 1.1 geometry types only.
  • ST_ForceRHR — Force the orientation of the vertices in a polygon to follow the Right-Hand-Rule.
  • ST_LineExtend — Returns a line extended forwards and backwards by specified distances.
  • ST_LineToCurve — Converts a linear geometry to a curved geometry.
  • ST_Multi — Return the geometry as a MULTI* geometry.
  • ST_Normalize — Return the geometry in its canonical form.
  • ST_Project — Returns a point projected from a start point by a distance and bearing (azimuth).
  • ST_QuantizeCoordinates — Sets least significant bits of coordinates to zero
  • ST_RemovePoint — Remove a point from a linestring.
  • ST_RemoveRepeatedPoints — Returns a version of a geometry with duplicate points removed.
  • ST_RemoveIrrelevantPointsForView — Removes points that are irrelevant for rendering a specific rectangluar view of a geometry.
  • ST_RemoveSmallParts — Removes small parts (polygon rings or linestrings) of a geometry.
  • ST_Reverse — Return the geometry with vertex order reversed.
  • ST_Segmentize — Returns a modified geometry/geography having no segment longer than a given distance.
  • ST_SetPoint — Replace point of a linestring with a given point.
  • ST_ShiftLongitude — Shifts the longitude coordinates of a geometry between -180..180 and 0..360.
  • ST_WrapX — Wrap a geometry around an X value.
  • ST_SnapToGrid — Snap all points of the input geometry to a regular grid.
  • ST_Snap — Snap segments and vertices of input geometry to vertices of a reference geometry.
  • ST_SwapOrdinates — Returns a version of the given geometry with given ordinate values swapped.

Name

ST_AddPoint — Aggiunge un punto a una stringa di linee.

Synopsis

geometry ST_AddPoint(geometry linestring, geometry point);

geometry ST_AddPoint(geometry linestring, geometry point, integer position = -1);

Descrizione

Aggiunge un punto a una stringa di linee prima dell'indice position (utilizzando un indice basato su 0). Se il parametro position è omesso o è -1, il punto viene aggiunto alla fine della stringa di linee.

Disponibilità: 1.1.0

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

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;

Name

ST_CollectionExtract — Given a geometry collection, returns a multi-geometry containing only elements of a specified type.

Synopsis

geometry ST_CollectionExtract(geometry collection);

geometry ST_CollectionExtract(geometry collection, integer type);

Descrizione

Given a geometry collection, returns a homogeneous multi-geometry.

Se il tipo non è specificato, restituisce una multigeometria contenente solo geometrie della dimensione più alta. Quindi i poligoni sono preferiti alle linee, che sono preferite ai punti.

Se è specificato il tipo , restituisce una multigeometria contenente solo quel tipo. Se non ci sono sottogeometrie del tipo giusto, viene restituita una geometria VUOTA. Sono supportati solo punti, linee e poligoni. I numeri di tipo sono:

  • 1 == POINT

  • 2 == LINESTRING

  • 3 == POLYGON

For atomic geometry inputs, the geometry is returned unchanged if the input type matches the requested type. Otherwise, the result is an EMPTY geometry of the specified type. If required, these can be converted to multi-geometries using ST_Multi.

[Warning]

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

[Note]

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.

Esempi

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))

Name

ST_CollectionHomogenize — Returns the simplest representation of a geometry collection.

Synopsis

geometry ST_CollectionHomogenize(geometry collection);

Descrizione

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.

[Warning]

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

Esempi

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)))

Name

ST_CurveToLine — Converts a geometry containing curves to a linear geometry.

Synopsis

geometry ST_CurveToLine(geometry curveGeom, float tolerance, integer tolerance_type, integer flags);

Descrizione

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.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1.

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 7.1.7

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo supporta le Curve e le Circular String.

Esempi

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)


        

Si veda anche

ST_LineToCurve


Name

ST_Scroll — Change start point of a closed LineString.

Synopsis

geometry ST_Scroll(geometry linestring, geometry point);

Descrizione

Changes the start/end point of a closed LineString to the given vertex point.

Disponibilità: 3.2.0

Questa funzione supporta il 3d e non distrugge gli z-index.

Questa funzione supporta le coordinate M.

Esempi

Make e closed line start at its 3rd vertex

SELECT ST_AsEWKT(ST_Scroll('SRID=4326;LINESTRING(0 0 0 1, 10 0 2 0, 5 5 4 2,0 0 0 1)', 'POINT(5 5 4 2)'));

st_asewkt
----------
SRID=4326;LINESTRING(5 5 4 2,0 0 0 1,10 0 2 0,5 5 4 2)

Si veda anche

ST_Normalize


Name

ST_FlipCoordinates — Returns a version of a geometry with X and Y axis flipped.

Synopsis

geometry ST_FlipCoordinates(geometry geom);

Descrizione

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

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta il 3d e non distrugge gli z-index.

Questa funzione supporta le coordinate M.

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta i Triangoli e le Triangulated Irregular Network Surfaces (TIN).

Esempio

SELECT ST_AsEWKT(ST_FlipCoordinates(GeomFromEWKT('POINT(1 2)')));
 st_asewkt
------------
POINT(2 1)
         

Si veda anche

ST_SwapOrdinates


Name

ST_Force2D — Force the geometries into a "2-dimensional mode".

Synopsis

geometry ST_Force2D(geometry geomA);

Descrizione

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.

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

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))

                

Si veda anche

ST_Force3D


Name

ST_Force3D — Force the geometries into XYZ mode. This is an alias for ST_Force3DZ.

Synopsis

geometry ST_Force3D(geometry geomA, float Zvalue = 0.0);

Descrizione

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.

Questa funzione supporta le Polyhedral Surface.

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

--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))
                

Name

ST_Force3DZ — Force the geometries into XYZ mode.

Synopsis

geometry ST_Force3DZ(geometry geomA, float Zvalue = 0.0);

Descrizione

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.

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo supporta le Curve e le Circular String.

Esempi

--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))
                

Name

ST_Force3DM — Force the geometries into XYM mode.

Synopsis

geometry ST_Force3DM(geometry geomA, float Mvalue = 0.0);

Descrizione

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.

Questo metodo supporta le Curve e le Circular String.

Esempi

--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))

                

Name

ST_Force4D — Force the geometries into XYZM mode.

Synopsis

geometry ST_Force4D(geometry geomA, float Zvalue = 0.0, float Mvalue = 0.0);

Descrizione

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.

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo supporta le Curve e le Circular String.

Esempi

--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))

                

Name

ST_ForceCollection — Convert the geometry into a GEOMETRYCOLLECTION.

Synopsis

geometry ST_ForceCollection(geometry geomA);

Descrizione

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.

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo supporta le Curve e le Circular String.

Esempi

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))
)
                

Name

ST_ForceCurve — Upcast a geometry into its curved type, if applicable.

Synopsis

geometry ST_ForceCurve(geometry g);

Descrizione

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

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo supporta le Curve e le Circular String.

Esempi

SELECT ST_AsText(
  ST_ForceCurve(
        'POLYGON((0 0 2, 5 0 2, 0 5 2, 0 0 2),(1 1 2, 1 3 2, 3 1 2, 1 1 2))'::geometry
  )
);
                              st_astext
----------------------------------------------------------------------
 CURVEPOLYGON Z ((0 0 2,5 0 2,0 5 2,0 0 2),(1 1 2,1 3 2,3 1 2,1 1 2))
(1 row)

Si veda anche

ST_LineToCurve


Name

ST_ForcePolygonCCW — Orients all exterior rings counter-clockwise and all interior rings clockwise.

Synopsis

geometry ST_ForcePolygonCCW ( geometry geom );

Descrizione

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.

Disponibilità: 2.4.0

Questa funzione supporta il 3d e non distrugge gli z-index.

Questa funzione supporta le coordinate M.


Name

ST_ForcePolygonCW — Orients all exterior rings clockwise and all interior rings counter-clockwise.

Synopsis

geometry ST_ForcePolygonCW ( geometry geom );

Descrizione

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.

Disponibilità: 2.4.0

Questa funzione supporta il 3d e non distrugge gli z-index.

Questa funzione supporta le coordinate M.


Name

ST_ForceSFS — Force the geometries to use SFS 1.1 geometry types only.

Synopsis

geometry ST_ForceSFS(geometry geomA);

geometry ST_ForceSFS(geometry geomA, text version);

Descrizione

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta i Triangoli e le Triangulated Irregular Network Surfaces (TIN).

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta il 3d e non distrugge gli z-index.


Name

ST_ForceRHR — Force the orientation of the vertices in a polygon to follow the Right-Hand-Rule.

Synopsis

geometry ST_ForceRHR(geometry g);

Descrizione

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

[Note]

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.

Questa funzione supporta il 3d e non distrugge gli z-index.

Questa funzione supporta le Polyhedral Surface.

Esempi

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)

Name

ST_LineExtend — Returns a line extended forwards and backwards by specified distances.

Synopsis

geometry ST_LineExtend(geometry line, float distance_forward, float distance_backward=0.0);

Descrizione

Returns a line extended forwards and backwards by adding new start (and end) points at the given distance(s). A distance of zero does not add a point. Only non-negative distances are allowed. The direction(s) of the added point(s) is determined by the first (and last) two distinct points of the line. Duplicate points are ignored.

Availability: 3.4.0

Example: Extends a line 5 units forward and 6 units backward

SELECT ST_AsText(ST_LineExtend('LINESTRING(0 0, 0 10)'::geometry, 5, 6));
--------------------------------------------
LINESTRING(0 -6,0 0,0 10,0 15)

Name

ST_LineToCurve — Converts a linear geometry to a curved geometry.

Synopsis

geometry ST_LineToCurve(geometry geomANoncircular);

Descrizione

Converts plain LINESTRING/POLYGON to CIRCULAR STRINGs and Curved Polygons. Note much fewer points are needed to describe the curved equivalent.

[Note]

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

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo supporta le Curve e le Circular String.

Esempi

-- 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)

Si veda anche

ST_CurveToLine


Name

ST_Multi — Return the geometry as a MULTI* geometry.

Synopsis

geometry ST_Multi(geometry geom);

Descrizione

Returns the geometry as a MULTI* geometry collection. If the geometry is already a collection, it is returned unchanged.

Esempi

SELECT ST_AsText(ST_Multi('POLYGON ((10 30, 30 30, 30 10, 10 10, 10 30))'));
                    st_astext
    -------------------------------------------------
    MULTIPOLYGON(((10 30,30 30,30 10,10 10,10 30)))

Si veda anche

ST_AsText


Name

ST_Normalize — Return the geometry in its canonical form.

Synopsis

geometry ST_Normalize(geometry geom);

Descrizione

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

Esempi

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)
                        

Si veda anche

ST_Equals,


Name

ST_Project — Returns a point projected from a start point by a distance and bearing (azimuth).

Synopsis

geometry ST_Project(geometry g1, float distance, float azimuth);

geometry ST_Project(geometry g1, geometry g2, float distance);

geography ST_Project(geography g1, float distance, float azimuth);

geography ST_Project(geography g1, geography g2, float distance);

Descrizione

Returns a point projected from a point along a geodesic using a given distance and azimuth (bearing). This is known as the direct geodesic problem.

The two-point version uses the path from the first to the second point to implicitly define the azimuth and uses the distance as before.

The distance is given in meters. Negative values are supported.

The azimuth (also known as heading or bearing) is given in radians. It is measured clockwise from true north.

  • North is azimuth zero (0 degrees)

  • East is azimuth π/2 (90 degrees)

  • South is azimuth π (180 degrees)

  • West is azimuth 3π/2 (270 degrees)

Negative azimuth values and values greater than 2π (360 degrees) are supported.

Disponibilità: 2.0.0

Enhanced: 2.4.0 Allow negative distance and non-normalized azimuth.

Enhanced: 3.4.0 Allow geometry arguments and two-point form omitting azimuth.

Example: Projected point at 100,000 meters and bearing 45 degrees

SELECT ST_AsText(ST_Project('POINT(0 0)'::geography, 100000, radians(45.0)));
--------------------------------------------
 POINT(0.635231029125537 0.639472334729198)

Name

ST_QuantizeCoordinates — Sets least significant bits of coordinates to zero

Synopsis

geometry ST_QuantizeCoordinates ( geometry g , int prec_x , int prec_y , int prec_z , int prec_m );

Descrizione

ST_QuantizeCoordinates determines the number of bits (N) required to represent a coordinate value with a specified number of digits after the decimal point, and then sets all but the N most significant bits to zero. The resulting coordinate value will still round to the original value, but will have improved compressiblity. This can result in a significant disk usage reduction provided that the geometry column is using a compressible storage type. The function allows specification of a different number of digits after the decimal point in each dimension; unspecified dimensions are assumed to have the precision of the x dimension. Negative digits are interpreted to refer digits to the left of the decimal point, (i.e., prec_x=-2 will preserve coordinate values to the nearest 100.

The coordinates produced by ST_QuantizeCoordinates are independent of the geometry that contains those coordinates and the relative position of those coordinates within the geometry. As a result, existing topological relationships between geometries are unaffected by use of this function. The function may produce invalid geometry when it is called with a number of digits lower than the intrinsic precision of the geometry.

Availability: 2.5.0

Technical Background

PostGIS stores all coordinate values as double-precision floating point integers, which can reliably represent 15 significant digits. However, PostGIS may be used to manage data that intrinsically has fewer than 15 significant digits. An example is TIGER data, which is provided as geographic coordinates with six digits of precision after the decimal point (thus requiring only nine significant digits of longitude and eight significant digits of latitude.)

When 15 significant digits are available, there are many possible representations of a number with 9 significant digits. A double precision floating point number uses 52 explicit bits to represent the significand (mantissa) of the coordinate. Only 30 bits are needed to represent a mantissa with 9 significant digits, leaving 22 insignificant bits; we can set their value to anything we like and still end up with a number that rounds to our input value. For example, the value 100.123456 can be represented by the floating point numbers closest to 100.123456000000, 100.123456000001, and 100.123456432199. All are equally valid, in that ST_AsText(geom, 6) will return the same result with any of these inputs. As we can set these bits to any value, ST_QuantizeCoordinates sets the 22 insignificant bits to zero. For a long coordinate sequence this creates a pattern of blocks of consecutive zeros that is compressed by PostgreSQL more efficiently.

[Note]

Only the on-disk size of the geometry is potentially affected by ST_QuantizeCoordinates. ST_MemSize, which reports the in-memory usage of the geometry, will return the the same value regardless of the disk space used by a geometry.

Esempi

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)

Si veda anche

ST_SnapToGrid


Name

ST_RemovePoint — Remove a point from a linestring.

Synopsis

geometry ST_RemovePoint(geometry linestring, integer offset);

Descrizione

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

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

Guarantees no lines are closed by removing the end point of closed lines (rings). Assumes geom is of type LINESTRING

UPDATE sometable
        SET geom = ST_RemovePoint(geom, ST_NPoints(geom) - 1)
        FROM sometable
        WHERE ST_IsClosed(geom);

Name

ST_RemoveRepeatedPoints — Returns a version of a geometry with duplicate points removed.

Synopsis

geometry ST_RemoveRepeatedPoints(geometry geom, float8 tolerance);

Descrizione

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

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

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)

Si veda anche

ST_Simplify


Name

ST_RemoveIrrelevantPointsForView — Removes points that are irrelevant for rendering a specific rectangluar view of a geometry.

Synopsis

geometry ST_RemoveIrrelevantPointsForView(geometry geom, box2d bounds, boolean cartesian_hint = false);

Descrizione

Returns a geometry without points being irrelevant for rendering the geometry within a given rectangluar view.

This function can be used to quickly preprocess geometries that should be rendered only within certain bounds.

Only geometries of type (MULTI)POLYGON and (MULTI)LINESTRING are evaluated. Other geometries keep unchanged.

In contrast to ST_ClipByBox2D() this function

  • sorts out points without computing new intersection points which avoids rounding errors and usually increases performance,

  • returns a geometry with equal or similar point number,

  • leads to the same rendering result within the specified view, and

  • may introduce self-intersections which would make the resulting geometry invalid (see example below).

If cartesian_hint is set to true, the algorithm applies additional optimizations involving cartesian math to further reduce the resulting point number. Please note that using this option might introduce rendering artifacts if the resulting coordinates are projected into another (non-cartesian) coordinate system before rendering.

[Warning]

For polygons, this function does currently not ensure that the result is valid. This situation can be checked with ST_IsValid and repaired with ST_MakeValid.

Example: ST_RemoveIrrelevantPointsForView() applied to a polygon. Blue points remain, the rendering result (light-blue area) within the grey view box remains as well.

Example: Due to the fact that points are just sorted out and no new points are computed, the result of ST_RemoveIrrelevantPointsForView() may contain self-intersections.

Availability: 3.5.0

Esempi

SELECT ST_AsText(
                        ST_RemoveIrrelevantPointsForView(
                        ST_GeomFromText('MULTIPOLYGON(((10 10, 20 10, 30 10, 40 10, 20 20, 10 20, 10 10)),((10 10, 20 10, 20 20, 10 20, 10 10)))'),
                        ST_MakeEnvelope(12,12,18,18), true));
                
                st_astext
                ---------
                    MULTIPOLYGON(((10 10,40 10,20 20,10 20,10 10)),((10 10,20 10,20 20,10 20,10 10)))
                
SELECT ST_AsText(
                        ST_RemoveIrrelevantPointsForView(
                        ST_GeomFromText('MULTILINESTRING((0 0, 10 0,20 0,30 0), (0 15, 5 15, 10 15, 15 15, 20 15, 25 15, 30 15, 40 15), (13 13,15 15,17 17))'),
                        ST_MakeEnvelope(12,12,18,18), true));
                
                st_astext
                ---------
                        MULTILINESTRING((10 15,15 15,20 15),(13 13,15 15,17 17))
                
SELECT ST_AsText(
                        ST_RemoveIrrelevantPointsForView(
                        ST_GeomFromText('LINESTRING(0 0, 10 0,20 0,30 0)'),
                        ST_MakeEnvelope(12,12,18,18), true));
                
                st_astext
                ---------
                    LINESTRING EMPTY
                
SELECT ST_AsText(
                        ST_RemoveIrrelevantPointsForView(
                        ST_GeomFromText('POLYGON((0 30, 15 30, 30 30, 30 0, 0 0, 0 30))'),
                        ST_MakeEnvelope(12,12,18,18), true));
                
                st_astext
                ---------
                    POLYGON((15 30,30 0,0 0,15 30))
                
SELECT ST_AsText(
                        ST_RemoveIrrelevantPointsForView(
                        ST_GeomFromText('POLYGON((0 30, 15 30, 30 30, 30 0, 0 0, 0 30))'),
                        ST_MakeEnvelope(12,12,18,18)));
                
                st_astext
                ---------
                    POLYGON((0 30,30 30,30 0,0 0,0 30))
                

Name

ST_RemoveSmallParts — Removes small parts (polygon rings or linestrings) of a geometry.

Synopsis

geometry ST_RemoveSmallParts(geometry geom, double precision minSizeX, double precision minSizeY);

Descrizione

Returns a geometry without small parts (exterior or interior polygon rings, or linestrings).

This function can be used as preprocessing step for creating simplified maps, e. g. to remove small islands or holes.

It evaluates only geometries of type (MULTI)POLYGON and (MULTI)LINESTRING. Other geometries remain unchanged.

If minSizeX is greater than 0, parts are sorted out if their width is smaller than minSizeX.

If minSizeY is greater than 0, parts are sorted out if their height is smaller than minSizeY.

Both minSizeX and minSizeY are measured in coordinate system units of the geometry.

For polygon types, evaluation is done separately for each ring which can lead to one of the following results:

  • the original geometry,

  • a POLYGON with all rings with less vertices,

  • a POLYGON with a reduced number of interior rings (having possibly less vertices),

  • a POLYGON EMPTY, or

  • a MULTIPOLYGON with a reduced number of polygons (having possibly less interior rings or vertices), or

  • a MULTIPOLYGON EMPTY.

For linestring types, evaluation is done for each linestring which can lead to one of the following results:

  • the original geometry,

  • a LINESTRING with a reduced number of vertices,

  • a LINESTRING EMPTY,

  • a MULTILINESTRING with a reduced number of linestrings (having possibly less vertices), or

  • a MULTILINESTRING EMPTY.

Example: ST_RemoveSmallParts() applied to a multi-polygon. Blue parts remain.

Availability: 3.5.0

Esempi

SELECT ST_AsText(
                        ST_RemoveSmallParts(
                        ST_GeomFromText('MULTIPOLYGON(
                                ((60 160, 120 160, 120 220, 60 220, 60 160), (70 170, 70 210, 110 210, 110 170, 70 170)),
                                ((85 75, 155 75, 155 145, 85 145, 85 75)),
                                ((50 110, 70 110, 70 130, 50 130, 50 110)))'),
                                50, 50));
                
                st_astext
                ---------
                        MULTIPOLYGON(((60 160,120 160,120 220,60 220,60 160)),((85 75,155 75,155 145,85 145,85 75)))
                
SELECT ST_AsText(
                        ST_RemoveSmallParts(
                        ST_GeomFromText('LINESTRING(10 10, 20 20)'),
                                50, 50));
                
                st_astext
                ---------
                        LINESTRING EMPTY
                

Name

ST_Reverse — Return the geometry with vertex order reversed.

Synopsis

geometry ST_Reverse(geometry g1);

Descrizione

Can be used on any geometry and reverses the order of the vertices.

Enhanced: 2.4.0 support for curves was introduced.

Questa funzione supporta il 3d e non distrugge gli z-index.

Questa funzione supporta le Polyhedral Surface.

Esempi

SELECT ST_AsText(geom) as line, ST_AsText(ST_Reverse(geom)) As reverseline
FROM
(SELECT ST_MakeLine(ST_Point(1,2),
                ST_Point(1,10)) As geom) as foo;
--result
                line         |     reverseline
---------------------+----------------------
LINESTRING(1 2,1 10) | LINESTRING(1 10,1 2)

Name

ST_Segmentize — Returns a modified geometry/geography having no segment longer than a given distance.

Synopsis

geometry ST_Segmentize(geometry geom, float max_segment_length);

geography ST_Segmentize(geography geog, float max_segment_length);

Descrizione

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.

[Note]

This only shortens long segments. It does not lengthen segments shorter than the maximum length.

[Warning]

For inputs containing long segments, specifying a relatively short max_segment_length can cause a very large number of vertices to be added. This can happen unintentionally if the argument is specified accidentally as a number of segments, rather than a maximum length.

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) )

Esempi

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

Si veda anche

ST_LineSubstring


Name

ST_SetPoint — Replace point of a linestring with a given point.

Synopsis

geometry ST_SetPoint(geometry linestring, integer zerobasedposition, geometry point);

Descrizione

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

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

--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)

                        

Name

ST_ShiftLongitude — Shifts the longitude coordinates of a geometry between -180..180 and 0..360.

Synopsis

geometry ST_ShiftLongitude(geometry geom);

Descrizione

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.

[Note]

This is only useful for data with coordinates in longitude/latitude; e.g. SRID 4326 (WGS 84 geographic)

[Warning]

Pre-1.3.4 bug prevented this from working for MULTIPOINT. 1.3.4+ works with MULTIPOINT as well.

Questa funzione supporta il 3d e non distrugge gli z-index.

Miglioramento nella version 2.0.0: introdotto il supporto per superfici poliedriche e TIN.

NOTE: this function was renamed from "ST_Shift_Longitude" in 2.2.0

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta i Triangoli e le Triangulated Irregular Network Surfaces (TIN).

Esempi

--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)
        

Si veda anche

ST_WrapX


Name

ST_WrapX — Wrap a geometry around an X value.

Synopsis

geometry ST_WrapX(geometry geom, float8 wrap, float8 move);

Descrizione

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.

[Note]

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

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

-- Move all components of the given geometries whose bounding box
-- falls completely on the left of x=0 to +360
select ST_WrapX(geom, 0, 360);

-- Move all components of the given geometries whose bounding box
-- falls completely on the left of x=-30 to +360
select ST_WrapX(geom, -30, 360);
        

Si veda anche

ST_ShiftLongitude


Name

ST_SnapToGrid — Snap all points of the input geometry to a regular grid.

Synopsis

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);

Descrizione

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.

[Note]

The returned geometry might lose its simplicity (see ST_IsSimple).

[Note]

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

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

--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)

                

Name

ST_Snap — Snap segments and vertices of input geometry to vertices of a reference geometry.

Synopsis

geometry ST_Snap(geometry input, geometry reference, float tolerance);

Descrizione

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.

[Note]

The returned geometry might lose its simplicity (see ST_IsSimple) and validity (see ST_IsValid).

Eseguito dal modulo GEOS.

Disponibilità: 2.0.0

Esempi

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)
                                

Si veda anche

ST_SnapToGrid


Name

ST_SwapOrdinates — Returns a version of the given geometry with given ordinate values swapped.

Synopsis

geometry ST_SwapOrdinates(geometry geom, cstring ords);

Descrizione

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

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta il 3d e non distrugge gli z-index.

Questa funzione supporta le coordinate M.

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta i Triangoli e le Triangulated Irregular Network Surfaces (TIN).

Esempio

-- Scale M value by 2
SELECT ST_AsText(
  ST_SwapOrdinates(
    ST_Scale(
      ST_SwapOrdinates(g,'xm'),
      2, 1
    ),
  'xm')
) FROM ( SELECT 'POINT ZM (0 0 0 2)'::geometry g ) foo;
     st_astext
--------------------
 POINT ZM (0 0 0 4)
                 

Si veda anche

ST_FlipCoordinates

7.6. Geometry Validation

Abstract

These functions test whether geometries are valid according to the OGC SFS standard. They also provide information about the nature and location of invalidity. There is also a function to create a valid geometry out of an invalid one.

  • ST_IsValid — Tests if a geometry is well-formed in 2D.
  • ST_IsValidDetail — Returns a valid_detail row stating if a geometry is valid or if not a reason and a location.
  • ST_IsValidReason — Returns text stating if a geometry is valid, or a reason for invalidity.
  • ST_MakeValid — Attempts to make an invalid geometry valid without losing vertices.

Name

ST_IsValid — Tests if a geometry is well-formed in 2D.

Synopsis

boolean ST_IsValid(geometry g);

boolean ST_IsValid(geometry g, integer flags);

Descrizione

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”

[Note]

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.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1.

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 5.1.9

[Note]

Neither OGC-SFS nor SQL-MM specifications include a flag argument for ST_IsValid. The flag is a PostGIS extension.

Esempi

SELECT ST_IsValid(ST_GeomFromText('LINESTRING(0 0, 1 1)')) As good_line,
        ST_IsValid(ST_GeomFromText('POLYGON((0 0, 1 1, 1 2, 1 1, 0 0))')) As bad_poly
--results
NOTICE:  Self-intersection at or near point 0 0
 good_line | bad_poly
-----------+----------
 t         | f

Name

ST_IsValidDetail — Returns a valid_detail row stating if a geometry is valid or if not a reason and a location.

Synopsis

valid_detail ST_IsValidDetail(geometry geom, integer flags);

Descrizione

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

Esempi


--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     |        |



Name

ST_IsValidReason — Returns text stating if a geometry is valid, or a reason for invalidity.

Synopsis

text ST_IsValidReason(geometry geomA);

text ST_IsValidReason(geometry geomA, integer flags);

Descrizione

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.

Esempi

-- 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


Si veda anche

ST_IsValid, ST_Summary


Name

ST_MakeValid — Attempts to make an invalid geometry valid without losing vertices.

Synopsis

geometry ST_MakeValid(geometry input);

geometry ST_MakeValid(geometry input, text params);

Descrizione

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.

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

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;

Esempi

SELECT ST_AsText(ST_MakeValid(
    'LINESTRING(0 0, 0 0)',
    'method=structure keepcollapsed=true'
    ));

 st_astext
------------
 POINT(0 0)


SELECT ST_AsText(ST_MakeValid(
    'LINESTRING(0 0, 0 0)',
    'method=structure keepcollapsed=false'
    ));

    st_astext
------------------
 LINESTRING EMPTY

7.7. Spatial Reference System Functions

Abstract

These functions work with the Spatial Reference System of geometries as defined in the spatial_ref_sys table.

  • ST_InverseTransformPipeline — Return a new geometry with coordinates transformed to a different spatial reference system using the inverse of a defined coordinate transformation pipeline.
  • ST_SetSRID — Set the SRID on a geometry.
  • ST_SRID — Returns the spatial reference identifier for a geometry.
  • ST_Transform — Return a new geometry with coordinates transformed to a different spatial reference system.
  • ST_TransformPipeline — Return a new geometry with coordinates transformed to a different spatial reference system using a defined coordinate transformation pipeline.
  • postgis_srs_codes — Return the list of SRS codes associated with the given authority.
  • postgis_srs — Return a metadata record for the requested authority and srid.
  • postgis_srs_all — Return metadata records for every spatial reference system in the underlying Proj database.
  • postgis_srs_search — Return metadata records for projected coordinate systems that have areas of usage that fully contain the bounds parameter.

Name

ST_InverseTransformPipeline — Return a new geometry with coordinates transformed to a different spatial reference system using the inverse of a defined coordinate transformation pipeline.

Synopsis

geometry ST_InverseTransformPipeline(geometry geom, text pipeline, integer to_srid);

Descrizione

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.

Esempi

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)
    

Name

ST_SetSRID — Set the SRID on a geometry.

Synopsis

geometry ST_SetSRID(geometry geom, integer srid);

Descrizione

Sets the SRID on a geometry to a particular integer value. Useful in constructing bounding boxes for queries.

[Note]

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.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1.

Questo metodo supporta le Curve e le Circular String.

Esempi

-- 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)
      

Name

ST_SRID — Returns the spatial reference identifier for a geometry.

Synopsis

integer ST_SRID(geometry g1);

Descrizione

Returns the spatial reference identifier for the ST_Geometry as defined in spatial_ref_sys table. Section 4.5, “Spatial Reference Systems”

[Note]

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.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.1

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 5.1.5

Questo metodo supporta le Curve e le Circular String.

Esempi

SELECT ST_SRID(ST_GeomFromText('POINT(-71.1043 42.315)',4326));
    --result
    4326
    

Name

ST_Transform — Return a new geometry with coordinates transformed to a different spatial reference system.

Synopsis

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);

Descrizione

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.

[Note]

Requires PostGIS be compiled with PROJ support. Use PostGIS_Full_Version to confirm you have PROJ support compiled in.

[Note]

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.

[Note]

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.

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 5.1.6

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Esempi

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))
    

Configuring transformation behavior

Sometimes coordinate transformation involving a grid-shift can fail, for example if PROJ.4 has not been built with grid-shift files or the coordinate does not lie within the range for which the grid shift is defined. By default, PostGIS will throw an error if a grid shift file is not present, but this behavior can be configured on a per-SRID basis either by testing different to_proj values of PROJ.4 text, or altering the proj4text value within the spatial_ref_sys table.

For example, the proj4text parameter +datum=NAD87 is a shorthand form for the following +nadgrids parameter:

+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;

Name

ST_TransformPipeline — Return a new geometry with coordinates transformed to a different spatial reference system using a defined coordinate transformation pipeline.

Synopsis

geometry ST_TransformPipeline(geometry g1, text pipeline, integer to_srid);

Descrizione

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.

Esempi

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)
    

Name

postgis_srs_codes — Return the list of SRS codes associated with the given authority.

Synopsis

setof text postgis_srs_codes(text auth_name);

Descrizione

Returns a set of all auth_srid for the given auth_name.

Availability: 3.4.0

Proj version 6+

Esempi

List the first ten codes associated with the EPSG authority.

SELECT * FROM postgis_srs_codes('EPSG') LIMIT 10;

 postgis_srs_codes
-------------------
 2000
 20004
 20005
 20006
 20007
 20008
 20009
 2001
 20010
 20011
    

Name

postgis_srs — Return a metadata record for the requested authority and srid.

Synopsis

setof record postgis_srs(text auth_name, text auth_srid);

Descrizione

Returns a metadata record for the requested auth_srid for the given auth_name. The record will have the auth_name, auth_srid, srname, srtext, proj4text, and the corners of the area of usage, point_sw and point_ne.

Availability: 3.4.0

Proj version 6+

Esempi

Get the metadata for EPSG:3005.

SELECT * FROM postgis_srs('EPSG', '3005');

auth_name | EPSG
auth_srid | 3005
srname    | NAD83 / BC Albers
srtext    | PROJCS["NAD83 / BC Albers", ... ]]
proj4text | +proj=aea +lat_0=45 +lon_0=-126 +lat_1=50 +lat_2=58.5 +x_0=1000000 +y_0=0 +datum=NAD83 +units=m +no_defs +type=crs
point_sw  | 0101000020E6100000E17A14AE476161C00000000000204840
point_ne  | 0101000020E610000085EB51B81E855CC0E17A14AE47014E40
    

Name

postgis_srs_all — Return metadata records for every spatial reference system in the underlying Proj database.

Synopsis

setof record postgis_srs_all(void);

Descrizione

Returns a set of all metadata records in the underlying Proj database. The records will have the auth_name, auth_srid, srname, srtext, proj4text, and the corners of the area of usage, point_sw and point_ne.

Availability: 3.4.0

Proj version 6+

Esempi

Get the first 10 metadata records from the Proj database.

SELECT auth_name, auth_srid, srname FROM postgis_srs_all() LIMIT 10;

 auth_name | auth_srid |                  srname
-----------+-----------+------------------------------------------
 EPSG      | 2000      | Anguilla 1957 / British West Indies Grid
 EPSG      | 20004     | Pulkovo 1995 / Gauss-Kruger zone 4
 EPSG      | 20005     | Pulkovo 1995 / Gauss-Kruger zone 5
 EPSG      | 20006     | Pulkovo 1995 / Gauss-Kruger zone 6
 EPSG      | 20007     | Pulkovo 1995 / Gauss-Kruger zone 7
 EPSG      | 20008     | Pulkovo 1995 / Gauss-Kruger zone 8
 EPSG      | 20009     | Pulkovo 1995 / Gauss-Kruger zone 9
 EPSG      | 2001      | Antigua 1943 / British West Indies Grid
 EPSG      | 20010     | Pulkovo 1995 / Gauss-Kruger zone 10
 EPSG      | 20011     | Pulkovo 1995 / Gauss-Kruger zone 11    

7.8. Ingresso geometria

Abstract

Queste funzioni creano oggetti geometrici da vari formati testuali o binari.

7.8.1. Well-Known Text (WKT)

  • ST_BdPolyFromText — Costruisce un poligono an partire da una collezione arbitraria di linee chiuse in forma di multilinee rappresentate come testo Well-Known
  • ST_BdMPolyFromText — Costruisce un MultiPolygon a partire da una collezione arbitraria di linee chiuse sotto forma di MultiLineString in formato Well-Known-Text.
  • ST_GeogFromText — Ritorna un valore geography sotto forma di Well-Know-Text (WKT) oppure di Extended-Well-Know-Text (EWKT)
  • ST_GeographyFromText — Ritorna un valore geography sotto forma di Well-Know-Text (WKT) oppure di Extended-Well-Know-Text (EWKT)
  • ST_GeomCollFromText — Crea una collezione Geometria dalla collezione WKT con il SRID indicato. Se SRID non è indicato, il valore predefinito è 0.
  • ST_GeomFromEWKT — Ritorna un valore ST_Geometry a partire da una rappresentazione Extended Well-Known Text (EWKT).
  • ST_GeomFromMARC21 — Prende in input i dati geografici MARC21/XML e restituisce un oggetto geometrico PostGIS.
  • ST_GeometryFromText — Restituisce un valore ST_Geometry a partire da Well-Known-Text (WKT). È un alias per ST_GeomFromText
  • ST_GeomFromText — Restituisce un valore ST_Geometry a partire da una rappresentazione Well-Known-Text (WKT)
  • ST_LineFromText — Crea una geometria dalla rappresentazione WKT con il SRID indicato. Se SRID non viene indicato, il valore predefinito è 0.
  • ST_MLineFromText — Restituisce un valore ST_MultiLineString specificato dalla rappresentazione WKT.
  • ST_MPointFromText — Crea una geometria da WKT con il SRID indicato. Se SRID non viene indicato, il valore predefinito è 0.
  • ST_MPolyFromText — Crea una geometria multipoligono da WKT con il SRID indicato. Se SRID non è indicato, l'impostazione predefinita è 0.
  • ST_PointFromText — Crea una geometria di punti da WKT con il SRID indicato. Se SRID non è indicato, il valore predefinito è sconosciuto.
  • ST_PolygonFromText — Crea una geometria da WKT con il SRID indicato. Se SRID non viene indicato, il valore predefinito è 0.
  • ST_WKTToSQL — Restituisce un valore ST_Geometry a partire da Well-Known-Text (WKT). È un alias per ST_GeomFromText

Name

ST_BdPolyFromText — Costruisce un poligono an partire da una collezione arbitraria di linee chiuse in forma di multilinee rappresentate come testo Well-Known

Synopsis

geometry ST_BdPolyFromText(text WKT, integer srid);

Descrizione

Costruisce un poligono an partire da una collezione arbitraria di linee chiuse in forma di multilinee rappresentate come testo Well-Known

[Note]

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.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2

Eseguito dal modulo GEOS.

Disponibilità: 1.1.0


Name

ST_BdMPolyFromText — Costruisce un MultiPolygon a partire da una collezione arbitraria di linee chiuse sotto forma di MultiLineString in formato Well-Known-Text.

Synopsis

geometry ST_BdMPolyFromText(text WKT, integer srid);

Descrizione

Costruisse un poligono a partire da una collezione arbitraria di linee chiuse, poligoni e MultiLineString in formato Well-Known-Text.

[Note]

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.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2

Eseguito dal modulo GEOS.

Disponibilità: 1.1.0


Name

ST_GeogFromText — Ritorna un valore geography sotto forma di Well-Know-Text (WKT) oppure di Extended-Well-Know-Text (EWKT)

Synopsis

geography ST_GeogFromText(text EWKT);

Descrizione

Restituisce un oggetto geografico dal testo noto o dalla rappresentazione nota estesa. Se non specificato, viene assunto il codice SRID 4326. Si tratta di un alias di ST_GeographyFromText. I punti sono sempre espressi in long lat.

Esempi

--- 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)'));
                        

Name

ST_GeographyFromText — Ritorna un valore geography sotto forma di Well-Know-Text (WKT) oppure di Extended-Well-Know-Text (EWKT)

Synopsis

geography ST_GeographyFromText(text EWKT);

Descrizione

Restituisce un oggetto geografico dalla rappresentazione testuale nota. Se non specificato, si assume il codice SRID 4326.


Name

ST_GeomCollFromText — Crea una collezione Geometria dalla collezione WKT con il SRID indicato. Se SRID non è indicato, il valore predefinito è 0.

Synopsis

geometry ST_GeomCollFromText(text WKT, integer srid);

geometry ST_GeomCollFromText(text WKT);

Descrizione

Crea una collezione di geometrie dalla rappresentazione Well-Known-Text (WKT) con il SRID indicato. Se SRID non è indicato, il valore predefinito è 0.

OGC SPEC 3.2.6.2 - option SRID is from the conformance suite

Ritorna null se il WKT in input non è una GEOMETRYCOLLECTION

[Note]

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.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2

Questo metodo implementa la specifica SQL/MM.

Esempi

SELECT ST_GeomCollFromText('GEOMETRYCOLLECTION(POINT(1 2),LINESTRING(1 2, 3 4))');

Si veda anche

ST_GeomFromText, ST_SRID


Name

ST_GeomFromEWKT — Ritorna un valore ST_Geometry a partire da una rappresentazione Extended Well-Known Text (EWKT).

Synopsis

geometry ST_GeomFromEWKT(text EWKT);

Descrizione

Costruisce un oggetto PostGIS ST_Geometry a partire da una rappresentazione OGC Extended Well-Known Text (EWKT).

[Note]

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.0: introdotto il supporto per superfici poliedriche e TIN.

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta i Triangoli e le Triangulated Irregular Network Surfaces (TIN).

Esempi

SELECT ST_GeomFromEWKT('SRID=4269;LINESTRING(-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932)');
SELECT ST_GeomFromEWKT('SRID=4269;MULTILINESTRING((-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932))');

SELECT ST_GeomFromEWKT('SRID=4269;POINT(-71.064544 42.28787)');

SELECT ST_GeomFromEWKT('SRID=4269;POLYGON((-71.1776585052917 42.3902909739571,-71.1776820268866 42.3903701743239,
-71.1776063012595 42.3903825660754,-71.1775826583081 42.3903033653531,-71.1776585052917 42.3902909739571))');

SELECT ST_GeomFromEWKT('SRID=4269;MULTIPOLYGON(((-71.1031880899493 42.3152774590236,
-71.1031627617667 42.3152960829043,-71.102923838298 42.3149156848307,
-71.1023097974109 42.3151969047397,-71.1019285062273 42.3147384934248,
-71.102505233663 42.3144722937587,-71.10277487471 42.3141658254797,
-71.103113945163 42.3142739188902,-71.10324876416 42.31402489987,
-71.1033002961013 42.3140393340215,-71.1033488797549 42.3139495090772,
-71.103396240451 42.3138632439557,-71.1041521907712 42.3141153348029,
-71.1041411411543 42.3141545014533,-71.1041287795912 42.3142114839058,
-71.1041188134329 42.3142693656241,-71.1041112482575 42.3143272556118,
-71.1041072845732 42.3143851580048,-71.1041057218871 42.3144430686681,
-71.1041065602059 42.3145009876017,-71.1041097995362 42.3145589148055,
-71.1041166403905 42.3146168544148,-71.1041258822717 42.3146748022936,
-71.1041375307579 42.3147318674446,-71.1041492906949 42.3147711126569,
-71.1041598612795 42.314808571739,-71.1042515013869 42.3151287620809,
-71.1041173835118 42.3150739481917,-71.1040809891419 42.3151344119048,
-71.1040438678912 42.3151191367447,-71.1040194562988 42.3151832057859,
-71.1038734225584 42.3151140942995,-71.1038446938243 42.3151006300338,
-71.1038315271889 42.315094347535,-71.1037393329282 42.315054824985,
-71.1035447555574 42.3152608696313,-71.1033436658644 42.3151648370544,
-71.1032580383161 42.3152269126061,-71.103223066939 42.3152517403219,
-71.1031880899493 42.3152774590236)),
((-71.1043632495873 42.315113108546,-71.1043583974082 42.3151211109857,
-71.1043443253471 42.3150676015829,-71.1043850704575 42.3150793250568,-71.1043632495873 42.315113108546)))');
--3d circular string
SELECT ST_GeomFromEWKT('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)');
--Polyhedral Surface example
SELECT ST_GeomFromEWKT('POLYHEDRALSURFACE(
        ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)),
        ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)),
        ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)),
        ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)),
        ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)),
        ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1))
)');

Name

ST_GeomFromMARC21 — Prende in input i dati geografici MARC21/XML e restituisce un oggetto geometrico PostGIS.

Synopsis

geometry ST_GeomFromMARC21 ( text marcxml );

Descrizione

Questa funzione crea una geometria PostGIS da un record MARC21/XML, che può contenere un POINT o un POLYGON. In caso di più voci di dati geografici nello stesso record MARC21/XML, verrà restituito un MULTIPOINT o MULTIPOLYGON. Se il record contiene tipi di geometria misti, viene restituito un GEOMETRYCOLLECTION. Se il record MARC21/XML non contiene dati geografici, restituisce NULL (campo dati:034).

Versioni LOC MARC21/XML supportate:

Disponibilità: 3.3.0, richiede libxml2 2.6+

[Note]

I dati cartografici matematici codificati MARC21/XML non forniscono attualmente alcun mezzo per descrivere il sistema di riferimento spaziale delle coordinate codificate, pertanto questa funzione restituirà sempre una geometria con SRID 0.

[Note]

Le geometrie POLIGON restituite saranno sempre orientate in senso orario.

Esempi

Conversione di dati geografici MARC21/XML contenenti un singolo POINT codificato come 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)

            

Conversione di dati geografici MARC21/XML contenenti un singolo POLYGON codificato come 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)

            

Conversione di dati geografici MARC21/XML contenenti un POLIGON e un 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)
            

Si veda anche

ST_AsMARC21


Name

ST_GeometryFromText — Restituisce un valore ST_Geometry a partire da Well-Known-Text (WKT). È un alias per ST_GeomFromText

Synopsis

geometry ST_GeometryFromText(text WKT);

geometry ST_GeometryFromText(text WKT, integer srid);

Descrizione

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1.

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 5.1.40

Si veda anche

ST_GeomFromText


Name

ST_GeomFromText — Restituisce un valore ST_Geometry a partire da una rappresentazione Well-Known-Text (WKT)

Synopsis

geometry ST_GeomFromText(text WKT);

geometry ST_GeomFromText(text WKT, integer srid);

Descrizione

Costruisce un oggetto PostGIS ST_Geometry a partire da geometria in formato OGC Well-Known-Text

[Note]

Esistono due varianti della funzione ST_GeomFromText. La prima non accetta alcun SRID e restituisce una geometria senza sistema di riferimento spaziale definito (SRID=0). La seconda accetta un SRID come secondo argomento e restituisce una geometria che include questo SRID come parte dei suoi metadati.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2 - l'opzione SRID proviene dalla suite di conformità.

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 5.1.40

Questo metodo supporta le Curve e le Circular String.

[Note]

Pur non essendo conforme a OGC, ST_MakePoint è più veloce di ST_GeomFromText e ST_PointFromText. È anche più facile da usare per i valori delle coordinate numeriche. ST_Point è un'altra opzione simile per velocità a ST_MakePoint ed è conforme a OGC, ma non supporta altro che i punti 2D.

[Warning]

Modificato: 2.0.0 Nelle versioni precedenti di PostGIS era consentito ST_GeomFromText('GEOMETRYCOLLECTION(EMPTY)'). Questo è ora illegale in PostGIS 2.0.0 per conformarsi meglio agli standard SQL/MM. Ora si dovrebbe scrivere ST_GeomFromText('GEOMETRYCOLLECTION EMPTY')

Esempi

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)');
        

Name

ST_LineFromText — Crea una geometria dalla rappresentazione WKT con il SRID indicato. Se SRID non viene indicato, il valore predefinito è 0.

Synopsis

geometry ST_LineFromText(text WKT);

geometry ST_LineFromText(text WKT, integer srid);

Descrizione

Crea una geometria da WKT con il SRID indicato. Se SRID non è indicato, il valore predefinito è 0. Se WKT passato non è una LINESTRING, viene restituito null.

[Note]

OGC SPEC 3.2.6.2 - l'opzione SRID proviene dalla suite di conformità.

[Note]

Se si sa che tutte le geometrie sono LINESTRINGS, è più efficiente usare ST_GeomFromText. Questo richiama semplicemente ST_GeomFromText e aggiunge un'ulteriore convalida che restituisce una stringa di linee.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 7.2.8

Esempi

SELECT ST_LineFromText('LINESTRING(1 2, 3 4)') AS aline, ST_LineFromText('POINT(1 2)') AS null_return;
aline                            | null_return
------------------------------------------------
010200000002000000000000000000F ... | t
                

Si veda anche

ST_GeomFromText


Name

ST_MLineFromText — Restituisce un valore ST_MultiLineString specificato dalla rappresentazione WKT.

Synopsis

geometry ST_MLineFromText(text WKT, integer srid);

geometry ST_MLineFromText(text WKT);

Descrizione

Crea una geometria dal Well-Known-Text (WKT) con il SRID indicato. Se SRID non è indicato, l'impostazione predefinita è 0.

OGC SPEC 3.2.6.2 - option SRID is from the conformance suite

Restituisce null se il WKT non è un MULTILINESTRING

[Note]

Se si è assolutamente certi che tutte le geometrie WKT siano punti, non utilizzare questa funzione. È più lenta di ST_GeomFromText poiché aggiunge un ulteriore passaggio di convalida.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 9.4.4

Esempi

SELECT ST_MLineFromText('MULTILINESTRING((1 2, 3 4), (4 5, 6 7))');

Si veda anche

ST_GeomFromText


Name

ST_MPointFromText — Crea una geometria da WKT con il SRID indicato. Se SRID non viene indicato, il valore predefinito è 0.

Synopsis

geometry ST_MPointFromText(text WKT, integer srid);

geometry ST_MPointFromText(text WKT);

Descrizione

Crea una geometria da WKT con il SRID indicato. Se SRID non viene indicato, il valore predefinito è 0.

OGC SPEC 3.2.6.2 - option SRID is from the conformance suite

Restituisce null se il WKT non è un MULTIPOINT

[Note]

Se si è assolutamente certi che tutte le geometrie WKT siano punti, non utilizzare questa funzione. È più lenta di ST_GeomFromText poiché aggiunge un ulteriore passaggio di convalida.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1. 3.2.6.2

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 9.2.4

Esempi

SELECT ST_MPointFromText('MULTIPOINT((1 2),(3 4))');
SELECT ST_MPointFromText('MULTIPOINT((-70.9590 42.1180),(-70.9611 42.1223))', 4326);

Si veda anche

ST_GeomFromText


Name

ST_MPolyFromText — Crea una geometria multipoligono da WKT con il SRID indicato. Se SRID non è indicato, l'impostazione predefinita è 0.

Synopsis

geometry ST_MPolyFromText(text WKT, integer srid);

geometry ST_MPolyFromText(text WKT);

Descrizione

Crea un multipoligono da WKT con il SRID indicato. Se SRID non viene indicato, il valore predefinito è 0.

OGC SPEC 3.2.6.2 - option SRID is from the conformance suite

Lancia un errore se il WKT non è un MULTIPOLIGONO

[Note]

Se si è assolutamente certi che tutte le geometrie WKT siano multipoligoni, non utilizzare questa funzione. È più lenta di ST_GeomFromText perché aggiunge un ulteriore passaggio di convalida.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 9.6.4

Esempi

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);

Si veda anche

ST_GeomFromText, ST_SRID


Name

ST_PointFromText — Crea una geometria di punti da WKT con il SRID indicato. Se SRID non è indicato, il valore predefinito è sconosciuto.

Synopsis

geometry ST_PointFromText(text WKT);

geometry ST_PointFromText(text WKT, integer srid);

Descrizione

Costruisce un oggetto punto PostGIS ST_Geometry dalla rappresentazione testuale OGC Well-Known. Se SRID non è indicato, il valore predefinito è sconosciuto (attualmente 0). Se la geometria non è una rappresentazione di punto WKT, restituisce null. Se la WKT non è completamente valida, viene lanciato un errore.

[Note]

Esistono due varianti della funzione ST_PointFromText: la prima non accetta alcun SRID e restituisce una geometria senza sistema di riferimento spaziale definito. La seconda accetta un id di riferimento spaziale come secondo argomento e restituisce una ST_Geometry che include questo srid come parte dei suoi meta-dati. Il sistema di riferimento spaziale deve essere definito nella tabella spatial_ref_sys.

[Note]

Se si è assolutamente certi che tutte le geometrie WKT siano punti, non utilizzare questa funzione. È più lenta di ST_GeomFromText poiché aggiunge un'ulteriore fase di convalida. Se si costruiscono punti da coordinate long lat e si è più attenti alle prestazioni e all'accuratezza che alla conformità OGC, utilizzare ST_MakePoint o l'alias conforme a OGC ST_Point.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2 - l'opzione SRID proviene dalla suite di conformità.

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 6.1.8

Esempi

SELECT ST_PointFromText('POINT(-71.064544 42.28787)');
SELECT ST_PointFromText('POINT(-71.064544 42.28787)', 4326);
        

Name

ST_PolygonFromText — Crea una geometria da WKT con il SRID indicato. Se SRID non viene indicato, il valore predefinito è 0.

Synopsis

geometry ST_PolygonFromText(text WKT);

geometry ST_PolygonFromText(text WKT, integer srid);

Descrizione

Crea una geometria da WKT con il SRID indicato. Se SRID non è indicato, il valore predefinito è 0. Restituisce null se WKT non è un poligono.

OGC SPEC 3.2.6.2 - option SRID is from the conformance suite

[Note]

Se si è assolutamente certi che tutte le geometrie WKT siano poligoni, non utilizzare questa funzione. È più lenta di ST_GeomFromText poiché aggiunge un ulteriore passaggio di convalida.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 8.3.6

Esempi

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

Si veda anche

ST_GeomFromText


Name

ST_WKTToSQL — Restituisce un valore ST_Geometry a partire da Well-Known-Text (WKT). È un alias per ST_GeomFromText

Synopsis

geometry ST_WKTToSQL(text WKT);

Descrizione

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 5.1.34

Si veda anche

ST_GeomFromText

7.8.2. Well-Known Binary (WKB)

  • ST_GeogFromWKB — Crea un oggetto geography a partire da una geometria in Well-Known Binary (WKB) oppure Extended Well-Known Binary (EWKB).
  • ST_GeomFromEWKB — Ritorna un valore ST_Geometry a partire da Extended Well-Known Binary (EWKB).
  • ST_GeomFromWKB — Crea un'istanza di geometria da una rappresentazione geometrica Well-Known Binary (WKB) e da un SRID opzionale.
  • ST_LineFromWKB — Crea un LINESTRING da WKB con il SRID indicato
  • ST_LinestringFromWKB — Crea una geometria da WKB con il SRID indicato.
  • ST_PointFromWKB — Crea una geometria da WKB con il SRID indicato
  • ST_WKBToSQL — Restituisce un valore ST_Geometry specificato dalla rappresentazione Well-Known Binary (WKB). Si tratta di un nome alias per ST_GeomFromWKB che non accetta srid

Name

ST_GeogFromWKB — Crea un oggetto geography a partire da una geometria in Well-Known Binary (WKB) oppure Extended Well-Known Binary (EWKB).

Synopsis

geography ST_GeogFromWKB(bytea wkb);

Descrizione

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).

Questo metodo supporta le Curve e le Circular String.

Esempi

--Although bytea rep contains single \, these need to be escaped when inserting into a table
SELECT ST_AsText(
ST_GeogFromWKB(E'\\001\\002\\000\\000\\000\\002\\000\\000\\000\\037\\205\\353Q\\270~\\\\\\300\\323Mb\\020X\\231C@\\020X9\\264\\310~\\\\\\300)\\\\\\217\\302\\365\\230C@')
);
                                          st_astext
------------------------------------------------------
 LINESTRING(-113.98 39.198,-113.981 39.195)
(1 row)


Name

ST_GeomFromEWKB — Ritorna un valore ST_Geometry a partire da Extended Well-Known Binary (EWKB).

Synopsis

geometry ST_GeomFromEWKB(bytea EWKB);

Descrizione

Costruisce una ST_Geometry PostGIS a partire da OGC Extended Well-Known Binary (EWKT).

[Note]

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.0: introdotto il supporto per superfici poliedriche e TIN.

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta i Triangoli e le Triangulated Irregular Network Surfaces (TIN).

Esempi

Rappresentazione binaria di LINESTRING(-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932) in NAD 83 long lat (4269).

[Note]

NOTA: Anche se gli array di byte sono delimitati con \ e possono avere ', è necessario eseguire l'escape di entrambi con \ e '' se standard_conforming_strings è disattivato. Quindi non appare esattamente come la sua rappresentazione AsEWKB.

SELECT ST_GeomFromEWKB(E'\\001\\002\\000\\000 \\255\\020\\000\\000\\003\\000\\000\\000\\344J=
\\013B\\312Q\\300n\\303(\\010\\036!E@''\\277E''K
\\312Q\\300\\366{b\\235*!E@\\225|\\354.P\\312Q
\\300p\\231\\323e1!E@');
[Note]

In PostgreSQL 9.1+ - standard_conforming_strings è impostato su on per impostazione predefinita, mentre nelle versioni precedenti era impostato su off. È possibile modificare i valori predefiniti a seconda delle necessità per una singola query o a livello di database o di server. Di seguito viene illustrata la procedura da seguire con standard_conforming_strings = on. In questo caso si esegue l'escape di ' con lo standard ansi ', ma non si esegue l'escape degli slash

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')

Name

ST_GeomFromWKB — Crea un'istanza di geometria da una rappresentazione geometrica Well-Known Binary (WKB) e da un SRID opzionale.

Synopsis

geometry ST_GeomFromWKB(bytea geom);

geometry ST_GeomFromWKB(bytea geom, integer srid);

Descrizione

La funzione ST_GeomFromWKB prende una rappresentazione binaria nota di una geometria e un ID del sistema di riferimento spaziale (SRID) e crea un'istanza del tipo di geometria appropriato. Questa funzione svolge il ruolo di Geometry Factory in SQL. È un nome alternativo per ST_WKBToSQL.

Se SRID non è specificato, il valore predefinito è 0 (Sconosciuto).

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1. s3.2.7.2 - l'SRID opzionale proviene dalla suite di conformità

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 5.1.41

Questo metodo supporta le Curve e le Circular String.

Esempi

--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)

Name

ST_LineFromWKB — Crea un LINESTRING da WKB con il SRID indicato

Synopsis

geometry ST_LineFromWKB(bytea WKB);

geometry ST_LineFromWKB(bytea WKB, integer srid);

Descrizione

La funzione ST_LineFromWKB prende una rappresentazione binaria nota della geometria e un ID del sistema di riferimento spaziale (SRID) e crea un'istanza del tipo di geometria appropriato, in questo caso una geometria LINESTRING. Questa funzione svolge il ruolo di Geometry Factory in SQL.

Se non viene specificato un SRID, il valore predefinito è 0. NULL viene restituito se il bytea di ingresso non rappresenta un LINESTRING.

[Note]

OGC SPEC 3.2.6.2 - l'opzione SRID proviene dalla suite di conformità.

[Note]

Se si sa che tutte le geometrie sono LINESTRINGs, è più efficiente usare solo ST_GeomFromWKB. Questa funzione richiama semplicemente ST_GeomFromWKB e aggiunge un'ulteriore convalida che restituisce una stringa di linee.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 7.2.9

Esempi

SELECT ST_LineFromWKB(ST_AsBinary(ST_GeomFromText('LINESTRING(1 2, 3 4)'))) AS aline,
                ST_LineFromWKB(ST_AsBinary(ST_GeomFromText('POINT(1 2)'))) IS NULL AS null_return;
aline                            | null_return
------------------------------------------------
010200000002000000000000000000F ... | t
                

Name

ST_LinestringFromWKB — Crea una geometria da WKB con il SRID indicato.

Synopsis

geometry ST_LinestringFromWKB(bytea WKB);

geometry ST_LinestringFromWKB(bytea WKB, integer srid);

Descrizione

La funzione ST_LinestringFromWKB prende una rappresentazione binaria ben nota della geometria e un ID del sistema di riferimento spaziale (SRID) e crea un'istanza del tipo di geometria appropriato, in questo caso una geometria LINESTRING. Questa funzione svolge il ruolo di Geometry Factory in SQL.

Se non viene specificato un SRID, il valore predefinito è 0. NULL viene restituito se il bytea di ingresso non rappresenta una geometria LINESTRING. È un alias di ST_LineFromWKB.

[Note]

OGC SPEC 3.2.6.2 - il SRID opzionale proviene dalla suite di conformità.

[Note]

Se si sa che tutte le geometrie sono LINESTRING, è più efficiente usare solo ST_GeomFromWKB. Questa funzione richiama semplicemente ST_GeomFromWKB e aggiunge un'ulteriore convalida che restituisce una LINESTRING.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1. s3.2.6.2

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 7.2.9

Esempi

SELECT
  ST_LineStringFromWKB(
        ST_AsBinary(ST_GeomFromText('LINESTRING(1 2, 3 4)'))
  ) AS aline,
  ST_LinestringFromWKB(
        ST_AsBinary(ST_GeomFromText('POINT(1 2)'))
  ) IS NULL AS null_return;
   aline                            | null_return
------------------------------------------------
010200000002000000000000000000F ... | t

Name

ST_PointFromWKB — Crea una geometria da WKB con il SRID indicato

Synopsis

geometry ST_GeomFromWKB(bytea geom);

geometry ST_GeomFromWKB(bytea geom, integer srid);

Descrizione

La funzione ST_PointFromWKB prende una rappresentazione binaria nota della geometria e un ID del sistema di riferimento spaziale (SRID) e crea un'istanza del tipo di geometria appropriato, in questo caso una geometria POINT. Questa funzione svolge il ruolo di Geometry Factory in SQL.

Se non viene specificato un SRID, il valore predefinito è 0. NULL viene restituito se il bytea di ingresso non rappresenta una geometria POINT.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1. s3.2.7.2

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 6.1.9

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo supporta le Curve e le Circular String.

Esempi

SELECT
  ST_AsText(
        ST_PointFromWKB(
          ST_AsEWKB('POINT(2 5)'::geometry)
        )
  );
 st_astext
------------
 POINT(2 5)
(1 row)

SELECT
  ST_AsText(
        ST_PointFromWKB(
          ST_AsEWKB('LINESTRING(2 5, 2 6)'::geometry)
        )
  );
 st_astext
-----------

(1 row)

Name

ST_WKBToSQL — Restituisce un valore ST_Geometry specificato dalla rappresentazione Well-Known Binary (WKB). Si tratta di un nome alias per ST_GeomFromWKB che non accetta srid

Synopsis

geometry ST_WKBToSQL(bytea WKB);

Descrizione

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 5.1.36

Si veda anche

ST_GeomFromWKB

7.8.3. Altri formati

  • ST_Box2dFromGeoHash — Restituisce un BOX2D da una stringa GeoHash.
  • ST_GeomFromGeoHash — Restituisce una geometria da una stringa GeoHash.
  • ST_GeomFromGML — Accetta una geometria in formato GML come input e restituisce un oggetto PostGIS geometry
  • ST_GeomFromGeoJSON — Accetta come input la rappresentazione geojson di una geometria e restituisce una geometria PostGIS
  • ST_GeomFromKML — Accetta come input una geometria in formato KML e restituisce una geometria PostGIS.
  • ST_GeomFromTWKB — Crea un'istanza di geometria da una rappresentazione geometrica TWKB ("Tiny Well Known Binary").
  • ST_GMLToSQL — Restituisce un valore ST_Geometry a partire da una rappresentazione GML. Questo è solo un alias per la funzione ST_GeomFromGML.
  • ST_LineFromEncodedPolyline — Crea una stringa di linee da una polilinea codificata.
  • ST_PointFromGeoHash — Restituisce un punto da una stringa GeoHash.
  • ST_FromFlatGeobufToTable — Crea una tabella basata sulla struttura dei dati di FlatGeobuf.
  • ST_FromFlatGeobuf — Legge i dati di FlatGeobuf.

Name

ST_Box2dFromGeoHash — Restituisce un BOX2D da una stringa GeoHash.

Synopsis

box2d ST_Box2dFromGeoHash(text geohash, integer precision=full_precision_of_geohash);

Descrizione

Restituisce un BOX2D da una stringa GeoHash.

Se non viene specificata la precisione ST_Box2dFromGeoHash restituisce un BOX2D basato sulla precisione completa della stringa GeoHash in ingresso.

Se viene specificata la precisione ST_Box2dFromGeoHash utilizzerà il numero di caratteri del GeoHash per creare il BOX2D. Valori di precisione più bassi producono BOX2D più grandi e valori più grandi aumentano la precisione.

Disponibilità: 2.1.0

Esempi

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)

                

Name

ST_GeomFromGeoHash — Restituisce una geometria da una stringa GeoHash.

Synopsis

geometry ST_GeomFromGeoHash(text geohash, integer precision=full_precision_of_geohash);

Descrizione

Restituisce una geometria da una stringa GeoHash. La geometria sarà un poligono che rappresenta i limiti di GeoHash.

Se non viene specificata la precisione ST_GeomFromGeoHash restituisce un poligono basato sulla precisione completa della stringa GeoHash in ingresso.

Se viene specificata la precisione ST_GeomFromGeoHash utilizzerà il numero di caratteri del GeoHash per creare il poligono.

Disponibilità: 2.1.0

Esempi

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))

                

Name

ST_GeomFromGML — Accetta una geometria in formato GML come input e restituisce un oggetto PostGIS geometry

Synopsis

geometry ST_GeomFromGML(text geomgml);

geometry ST_GeomFromGML(text geomgml, integer srid);

Descrizione

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.0: introdotto il supporto per superfici poliedriche e TIN.

Miglioramento nella versione: 2.0.0 introdotto opzionale parametro SRID.

Questa funzione supporta il 3d e non distrugge gli z-index.

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta i Triangoli e le 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.

[Note]

ST_GeomFromGML non supporta geometrie curve SQL/MM.

Esempi - Una singola geometria con srsName

SELECT ST_GeomFromGML($$
    <gml:LineString xmlns:gml="http://www.opengis.net/gml"
                        srsName="EPSG:4269">
        <gml:coordinates>
            -71.16028,42.258729 -71.160837,42.259112 -71.161143,42.25932
        </gml:coordinates>
    </gml:LineString>
$$);

                

Esempi - uso di XLink

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>
$$);

                

Esempi - superficie poliedrica

SELECT ST_AsEWKT(ST_GeomFromGML('
<gml:PolyhedralSurface xmlns:gml="http://www.opengis.net/gml">
<gml:polygonPatches>
  <gml:PolygonPatch>
    <gml:exterior>
      <gml:LinearRing
><gml:posList srsDimension="3"
>0 0 0 0 0 1 0 1 1 0 1 0 0 0 0</gml:posList
></gml:LinearRing>
    </gml:exterior>
  </gml:PolygonPatch>
  <gml:PolygonPatch>
    <gml:exterior>
        <gml:LinearRing
><gml:posList srsDimension="3"
>0 0 0 0 1 0 1 1 0 1 0 0 0 0 0</gml:posList
></gml:LinearRing>
    </gml:exterior>
  </gml:PolygonPatch>
  <gml:PolygonPatch>
    <gml:exterior>
        <gml:LinearRing
><gml:posList srsDimension="3"
>0 0 0 1 0 0 1 0 1 0 0 1 0 0 0</gml:posList
></gml:LinearRing>
    </gml:exterior>
  </gml:PolygonPatch>
  <gml:PolygonPatch>
    <gml:exterior>
        <gml:LinearRing
><gml:posList srsDimension="3"
>1 1 0 1 1 1 1 0 1 1 0 0 1 1 0</gml:posList
></gml:LinearRing>
    </gml:exterior>
  </gml:PolygonPatch>
  <gml:PolygonPatch>
    <gml:exterior>
        <gml:LinearRing
><gml:posList srsDimension="3"
>0 1 0 0 1 1 1 1 1 1 1 0 0 1 0</gml:posList
></gml:LinearRing>
    </gml:exterior>
  </gml:PolygonPatch>
  <gml:PolygonPatch>
    <gml:exterior>
        <gml:LinearRing
><gml:posList srsDimension="3"
>0 0 1 1 0 1 1 1 1 0 1 1 0 0 1</gml:posList
></gml:LinearRing>
    </gml:exterior>
  </gml:PolygonPatch>
</gml:polygonPatches>
</gml:PolyhedralSurface
>'));

-- result --
 POLYHEDRALSURFACE(((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)),
 ((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)),
 ((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)),
 ((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)),
 ((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)),
 ((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1)))
                

Name

ST_GeomFromGeoJSON — Accetta come input la rappresentazione geojson di una geometria e restituisce una geometria PostGIS

Synopsis

geometry ST_GeomFromGeoJSON(text geomjson);

geometry ST_GeomFromGeoJSON(json geomjson);

geometry ST_GeomFromGeoJSON(jsonb geomjson);

Descrizione

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.

Migliorato: 3.0.0 la geometria analizzata viene impostata come predefinita su SRID=4326 se non specificato altrimenti.

Miglioramento: 2.5.0 può ora accettare json e jsonb come input.

Disponibilità: 2.0.0. Richiede - JSON-C >= 0.9

[Note]

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 della compilazione” per dettagli.

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

SELECT ST_AsText(ST_GeomFromGeoJSON('{"type":"Point","coordinates":[-48.23456,20.12345]}')) As wkt;
wkt
------
POINT(-48.23456 20.12345)
-- a 3D linestring
SELECT ST_AsText(ST_GeomFromGeoJSON('{"type":"LineString","coordinates":[[1,2,3],[4,5,6],[7,8,9]]}')) As wkt;

wkt
-------------------
LINESTRING(1 2,4 5,7 8)

Name

ST_GeomFromKML — Accetta come input una geometria in formato KML e restituisce una geometria PostGIS.

Synopsis

geometry ST_GeomFromKML(text geomkml);

Descrizione

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:

Disponibilità: 1.5, richiede libxml2 2.6+

Questa funzione supporta il 3d e non distrugge gli z-index.

[Note]

La funzione ST_GeomFromKML non supporta geometrie curve SQL/MM.

Esempi - Una singola geometria con srsName

SELECT ST_GeomFromKML($$
    <LineString>
        <coordinates
>-71.1663,42.2614
            -71.1667,42.2616</coordinates>
    </LineString>
$$);

        

Name

ST_GeomFromTWKB — Crea un'istanza di geometria da una rappresentazione geometrica TWKB ("Tiny Well Known Binary").

Synopsis

geometry ST_GeomFromTWKB(bytea twkb);

Descrizione

La funzione ST_GeomFromTWKB prende una rappresentazione geometrica TWKB ("Tiny Well-Known Binary") e crea un'istanza del tipo di geometria appropriato.

Esempi

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)

Si veda anche

ST_AsTWKB


Name

ST_GMLToSQL — Restituisce un valore ST_Geometry a partire da una rappresentazione GML. Questo è solo un alias per la funzione ST_GeomFromGML.

Synopsis

geometry ST_GMLToSQL(text geomgml);

geometry ST_GMLToSQL(text geomgml, integer srid);

Descrizione

Questo metodo implementa la specifica SQL/MM. 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.0: introdotto il supporto per superfici poliedriche e TIN.

Miglioramento nella versione: 2.0.0 introdotto opzionale parametro SRID.


Name

ST_LineFromEncodedPolyline — Crea una stringa di linee da una polilinea codificata.

Synopsis

geometry ST_LineFromEncodedPolyline(text polyline, integer precision=5);

Descrizione

Crea una stringa di linea da una stringa di polilinea codificata.

Opzionale precision specifica quante cifre decimali saranno conservate nella polilinea codificata. Il valore deve essere lo stesso nella codifica e nella decodifica, altrimenti le coordinate non saranno corrette.

Vedere http://developers.google.com/maps/documentation/utilities/polylinealgorithm

Disponibilità: 2.2.0

Esempi

-- 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)

    

Name

ST_PointFromGeoHash — Restituisce un punto da una stringa GeoHash.

Synopsis

point ST_PointFromGeoHash(text geohash, integer precision=full_precision_of_geohash);

Descrizione

Restituisce un punto da una stringa GeoHash. Il punto rappresenta il punto centrale del GeoHash.

Se non viene specificata la precisione ST_PointFromGeoHash restituisce un punto basato sulla precisione completa della stringa GeoHash in ingresso.

Se viene specificata la precisione ST_PointFromGeoHash utilizzerà il numero di caratteri del GeoHash per creare il punto.

Disponibilità: 2.1.0

Esempi

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)

                

Name

ST_FromFlatGeobufToTable — Crea una tabella basata sulla struttura dei dati di FlatGeobuf.

Synopsis

void ST_FromFlatGeobufToTable(text schemaname, text tablename, bytea FlatGeobuf input data);

Descrizione

Crea una tabella basata sulla struttura dei dati di FlatGeobuf. (http://flatgeobuf.org).

schema Nome dello schema.

table Nome della tabella.

dati Dati FlatGeobuf in ingresso.

Disponibilità: 3.2.0


Name

ST_FromFlatGeobuf — Legge i dati di FlatGeobuf.

Synopsis

setof anyelement ST_FromFlatGeobuf(anyelement Table reference, bytea FlatGeobuf input data);

Descrizione

Legge i dati FlatGeobuf (http://flatgeobuf.org). NOTA: i bytea di PostgreSQL non possono superare 1 GB.

tabletype riferimento a un tipo di tabella.

data dati FlatGeobuf in ingresso.

Disponibilità: 3.2.0

7.9. Geometry Output

Abstract

Queste funzioni convertono gli oggetti geometrici in vari formati testuali o binari.

7.9.1. Well-Known Text (WKT)

  • ST_AsEWKT — Ritorna la rappresentazione Well-Known Text (WKT) della geometria con incluso lo SRID.
  • ST_AsText — Return the Well-Known Text (WKT) representation of the geometry/geography without SRID metadata.

Name

ST_AsEWKT — Ritorna la rappresentazione Well-Known Text (WKT) della geometria con incluso lo SRID.

Synopsis

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);

Descrizione

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.

[Warning]

Using the maxdecimaldigits parameter can cause output geometry to become invalid. To avoid this use ST_ReducePrecision with a suitable gridsize first.

[Note]

The WKT spec does not include the SRID. To get the OGC WKT format use ST_AsText.

[Warning]

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.

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta i Triangoli e le Triangulated Irregular Network Surfaces (TIN).

Esempi

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)

Name

ST_AsText — Return the Well-Known Text (WKT) representation of the geometry/geography without SRID metadata.

Synopsis

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);

Descrizione

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.

[Note]

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

[Warning]

The textual representation of numbers in WKT may not maintain full floating-point precision. To ensure full accuracy for data storage or transport it is best to use Well-Known Binary (WKB) format (see ST_AsBinary and maxdecimaldigits).

[Warning]

Using the maxdecimaldigits parameter can cause output geometry to become invalid. To avoid this use ST_ReducePrecision with a suitable gridsize first.

Availability: 1.5 - support for geography was introduced.

Enhanced: 2.5 - optional parameter precision introduced.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.1

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 5.1.25

Questo metodo supporta le Curve e le Circular String.

Esempi

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)

7.9.2. Well-Known Binary (WKB)

  • ST_AsBinary — Return the OGC/ISO Well-Known Binary (WKB) representation of the geometry/geography without SRID meta data.
  • ST_AsEWKB — Return the Extended Well-Known Binary (EWKB) representation of the geometry with SRID meta data.
  • ST_AsHEXEWKB — Returns a Geometry in HEXEWKB format (as text) using either little-endian (NDR) or big-endian (XDR) encoding.

Name

ST_AsBinary — Return the OGC/ISO Well-Known Binary (WKB) representation of the geometry/geography without SRID meta data.

Synopsis

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);

Descrizione

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.

[Note]

The OGC/ISO WKB format does not include the SRID. To get the EWKB format which does include the SRID use ST_AsEWKB

[Note]

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.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.1

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 5.1.37

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta i Triangoli e le Triangulated Irregular Network Surfaces (TIN).

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

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

Name

ST_AsEWKB — Return the Extended Well-Known Binary (EWKB) representation of the geometry with SRID meta data.

Synopsis

bytea ST_AsEWKB(geometry g1);

bytea ST_AsEWKB(geometry g1, text NDR_or_XDR);

Descrizione

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.

[Note]

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.

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta i Triangoli e le Triangulated Irregular Network Surfaces (TIN).

Esempi

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
                

Name

ST_AsHEXEWKB — Returns a Geometry in HEXEWKB format (as text) using either little-endian (NDR) or big-endian (XDR) encoding.

Synopsis

text ST_AsHEXEWKB(geometry g1, text NDRorXDR);

text ST_AsHEXEWKB(geometry g1);

Descrizione

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.

[Note]

Availability: 1.2.2

Questa funzione supporta il 3d e non distrugge gli z-index.

Questo metodo supporta le Curve e le Circular String.

Esempi

SELECT ST_AsHEXEWKB(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326));
                which gives same answer as

                SELECT ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326)::text;

                st_ashexewkb
                --------
                0103000020E6100000010000000500
                00000000000000000000000000000000
                00000000000000000000000000000000F03F
                000000000000F03F000000000000F03F000000000000F03
                F000000000000000000000000000000000000000000000000

7.9.3. Altri formati

  • ST_AsEncodedPolyline — Returns an Encoded Polyline from a LineString geometry.
  • ST_AsFlatGeobuf — Return a FlatGeobuf representation of a set of rows.
  • ST_AsGeobuf — Return a Geobuf representation of a set of rows.
  • ST_AsGeoJSON — Return a geometry or feature in GeoJSON format.
  • ST_AsGML — Return the geometry as a GML version 2 or 3 element.
  • ST_AsKML — Return the geometry as a KML element.
  • ST_AsLatLonText — Return the Degrees, Minutes, Seconds representation of the given point.
  • ST_AsMARC21 — Returns geometry as a MARC21/XML record with a geographic datafield (034).
  • ST_AsMVTGeom — Transforms a geometry into the coordinate space of a MVT tile.
  • ST_AsMVT — Aggregate function returning a MVT representation of a set of rows.
  • ST_AsSVG — Returns SVG path data for a geometry.
  • ST_AsTWKB — Returns the geometry as TWKB, aka "Tiny Well-Known Binary"
  • ST_AsX3D — Returns a Geometry in X3D xml node element format: ISO-IEC-19776-1.2-X3DEncodings-XML
  • ST_GeoHash — Return a GeoHash representation of the geometry.

Name

ST_AsEncodedPolyline — Returns an Encoded Polyline from a LineString geometry.

Synopsis

text ST_AsEncodedPolyline(geometry geom, integer precision=5);

Descrizione

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.

Opzionale precision specifica quante cifre decimali saranno conservate nella polilinea codificata. Il valore deve essere lo stesso nella codifica e nella decodifica, altrimenti le coordinate non saranno corrette.

Disponibilità: 2.2.0

Esempi

Di base

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>


Name

ST_AsFlatGeobuf — Return a FlatGeobuf representation of a set of rows.

Synopsis

bytea ST_AsFlatGeobuf(anyelement set row);

bytea ST_AsFlatGeobuf(anyelement row, bool index);

bytea ST_AsFlatGeobuf(anyelement row, bool index, text geom_name);

Descrizione

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.

Disponibilità: 3.2.0


Name

ST_AsGeobuf — Return a Geobuf representation of a set of rows.

Synopsis

bytea ST_AsGeobuf(anyelement set row);

bytea ST_AsGeobuf(anyelement row, text geom_name);

Descrizione

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.

Disponibilità: 2.4.0

Esempi

SELECT encode(ST_AsGeobuf(q, 'geom'), 'base64')
    FROM (SELECT ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))') AS geom) AS q;
 st_asgeobuf
----------------------------------
 GAAiEAoOCgwIBBoIAAAAAgIAAAE=


                

Name

ST_AsGeoJSON — Return a geometry or feature in GeoJSON format.

Synopsis

text ST_AsGeoJSON(record feature, text geom_column="", integer maxdecimaldigits=9, boolean pretty_bool=false, text id_column='');

text ST_AsGeoJSON(geometry geom, integer maxdecimaldigits=9, integer options=8);

text ST_AsGeoJSON(geography geog, integer maxdecimaldigits=9, integer options=0);

Descrizione

Returns a geometry as a GeoJSON "geometry" object, or a row as a GeoJSON "feature" object.

The resulting GeoJSON geometry and feature representations conform with the GeoJSON specifications RFC 7946, except when the parsed geometries are referenced with a CRS other than WGS84 longitude and latitude (EPSG:4326, urn:ogc:def:crs:OGC::CRS84); the GeoJSON geometry object will then have a short CRS SRID identifier attached by default. 2D and 3D Geometries are both supported. GeoJSON only supports SFS 1.1 geometry types (no curve support for example).

The geom_column parameter is used to distinguish between multiple geometry columns. If omitted, the first geometry column in the record will be determined. Conversely, passing the parameter will save column type lookups.

The maxdecimaldigits argument may be used to reduce the maximum number of decimal places used in output (defaults to 9). If you are using EPSG:4326 and are outputting the geometry only for display, maxdecimaldigits=6 can be a good choice for many maps.

[Warning]

Using the maxdecimaldigits parameter can cause output geometry to become invalid. To avoid this use ST_ReducePrecision with a suitable gridsize first.

The options argument can be used to add BBOX or CRS in GeoJSON output:

  • 0: means no option

  • 1: GeoJSON BBOX

  • 2: GeoJSON Short CRS (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 id_column parameter is used to set the "id" member of the returned GeoJSON features. As per GeoJSON RFC, this SHOULD be used whenever a feature has a commonly used identifier, such as a primary key. When not specified, the produced features will not get an "id" member and any columns other than the geometry, including any potential keys, will just end up inside the feature’s "properties" member.

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.

Changed: 3.5.0 allow specifying the column containing the feature id

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

Generate a FeatureCollection:

SELECT json_build_object(
    'type', 'FeatureCollection',
    'features', json_agg(ST_AsGeoJSON(t.*, id_column =
> 'id')::json)
    )
FROM ( VALUES (1, 'one', 'POINT(1 1)'::geometry),
              (2, 'two', 'POINT(2 2)'),
              (3, 'three', 'POINT(3 3)')
     ) as t(id, name, geom);
{"type" : "FeatureCollection", "features" : [{"type": "Feature", "geometry": {"type":"Point","coordinates":[1,1]}, "id": 1, "properties": {"name": "one"}}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[2,2]}, "id": 2, "properties": {"name": "two"}}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[3,3]}, "id": 3, "properties": {"name": "three"}}]}

Generate a Feature:

SELECT ST_AsGeoJSON(t.*, id_column =
> 'id')
FROM (VALUES (1, 'one', 'POINT(1 1)'::geometry)) AS t(id, name, geom);
st_asgeojson
-----------------------------------------------------------------------------------------------------------------
 {"type": "Feature", "geometry": {"type":"Point","coordinates":[1,1]}, "id": 1, "properties": {"name": "one"}}

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]]}

Options argument can be used to add BBOX and CRS in GeoJSON output:

SELECT ST_AsGeoJSON(ST_SetSRID('POINT(1 1)'::geometry, 4326), 9, 4|1);
{"type":"Point","crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:EPSG::4326"}},"bbox":[1.000000000,1.000000000,1.000000000,1.000000000],"coordinates":[1,1]}

Name

ST_AsGML — Return the geometry as a GML version 2 or 3 element.

Synopsis

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);

Descrizione

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).

[Warning]

Using the maxdecimaldigits parameter can cause output geometry to become invalid. To avoid this use ST_ReducePrecision with a suitable gridsize first.

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 data 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.

[Note]

Only version 3+ of ST_AsGML supports Polyhedral Surfaces and TINS.

Questo metodo implementa la specifica SQL/MM. SQL-MM IEC 13249-3: 17.2

Questa funzione supporta il 3d e non distrugge gli z-index.

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta i Triangoli e le Triangulated Irregular Network Surfaces (TIN).

Examples: Version 2

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>

Esempi: Versione 3

-- 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>

Si veda anche

ST_GeomFromGML


Name

ST_AsKML — Return the geometry as a KML element.

Synopsis

text ST_AsKML(geometry geom, integer maxdecimaldigits=15, text nprefix=NULL);

text ST_AsKML(geography geog, integer maxdecimaldigits=15, text nprefix=NULL);

Descrizione

Return the geometry as a Keyhole Markup Language (KML) element. default maximum number of decimal places is 15, default namespace is no prefix.

[Warning]

Using the maxdecimaldigits parameter can cause output geometry to become invalid. To avoid this use ST_ReducePrecision with a suitable gridsize first.

[Note]

Requires PostGIS be compiled with Proj support. Use PostGIS_Full_Version to confirm you have proj support compiled in.

[Note]

Availability: 1.2.2 - later variants that include version param came in 1.3.2

[Note]

Enhanced: 2.0.0 - Add prefix namespace, use default and named args

[Note]

Changed: 3.0.0 - Removed the "versioned" variant signature

[Note]

AsKML output will not work with geometries that do not have an SRID

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

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>


Si veda anche

ST_AsSVG, ST_AsGML


Name

ST_AsLatLonText — Return the Degrees, Minutes, Seconds representation of the given point.

Synopsis

text ST_AsLatLonText(geometry pt, text format='');

Descrizione

Returns the Degrees, Minutes, Seconds representation of the point.

[Note]

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

Esempi

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

Name

ST_AsMARC21 — Returns geometry as a MARC21/XML record with a geographic datafield (034).

Synopsis

text ST_AsMARC21 ( geometry geom , text format='hdddmmss' );

Descrizione

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.

Versioni LOC MARC21/XML supportate:

Availability: 3.3.0

[Note]

This function does not support non lon/lat geometries, as they are not supported by the MARC21/XML standard (Coded Cartographic Mathematical Data).

[Note]

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.

Esempi

Converting a POINT to MARC21/XML formatted 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 formatted 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 formatted 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>



Si veda anche

ST_GeomFromMARC21


Name

ST_AsMVTGeom — Transforms a geometry into the coordinate space of a MVT tile.

Synopsis

geometry ST_AsMVTGeom(geometry geom, box2d bounds, integer extent=4096, integer buffer=256, boolean clip_geom=true);

Descrizione

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_TileEnvelope.

This function is used to convert geometry into the tile coordinate space required by ST_AsMVT.

geom is the geometry to transform, in the coordinate system of the target map.

bounds is the rectangular bounds of the tile in map coordinate space, with no buffer.

extent is the tile extent size in tile coordinate space as defined by the MVT specification. Defaults to 4096.

buffer is the buffer size in tile coordinate space for geometry clippig. Defaults to 256.

clip_geom is a boolean to control if geometries are clipped or encoded as-is. Defaults to true.

Disponibilità: 2.4.0

[Note]

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.

Esempi

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))



Name

ST_AsMVT — Aggregate function returning a MVT representation of a set of rows.

Synopsis

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);

Descrizione

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.

[Important]

Do not call with a GEOMETRYCOLLECTION as an element in the row. However you can use ST_AsMVTGeom to prepare a geometry collection for inclusion.

row row data with at least a geometry column.

name is the name of the layer. Default is the string "default".

extent is the tile extent in screen space as defined by the specification. Default is 4096.

geom_name is the name of the geometry column in the row data. Default is the first geometry column. Note that PostgreSQL by default automatically folds unquoted identifiers to lower case, which means that unless the geometry column is quoted, e.g. "MyMVTGeom", this parameter must be provided as lowercase.

feature_id_name is the name of the Feature ID column in the row data. If NULL or negative the Feature ID is not set. The first column matching name and valid type (smallint, integer, bigint) will be used as Feature ID, and any subsequent column will be added as a property. JSON properties are not supported.

Enhanced: 3.0 - added support for Feature ID.

Enhanced: 2.5.0 - added support parallel query.

Disponibilità: 2.4.0

Esempi

WITH mvtgeom AS
(
  SELECT ST_AsMVTGeom(geom, ST_TileEnvelope(12, 513, 412), extent =
> 4096, buffer =
> 64) AS geom, name, description
  FROM points_of_interest
  WHERE geom && ST_TileEnvelope(12, 513, 412, margin =
> (64.0 / 4096))
)
SELECT ST_AsMVT(mvtgeom.*)
FROM mvtgeom;


        

Name

ST_AsSVG — Returns SVG path data for a geometry.

Synopsis

text ST_AsSVG(geometry geom, integer rel=0, integer maxdecimaldigits=15);

text ST_AsSVG(geography geog, integer rel=0, integer maxdecimaldigits=15);

Descrizione

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 (";").

For working with PostGIS SVG graphics, checkout pg_svg library which provides plpgsql functions for working with outputs from ST_AsSVG.

Enhanced: 3.4.0 to support all curve types

Changed: 2.0.0 to use default args and support named args

[Note]

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

Questo metodo supporta le Curve e le Circular String.

Esempi

SELECT ST_AsSVG('POLYGON((0 0,0 1,1 1,1 0,0 0))'::geometry);

st_assvg
--------
M 0 0 L 0 -1 1 -1 1 0 Z

Circular string

SELECT ST_AsSVG( ST_GeomFromText('CIRCULARSTRING(-2 0,0 2,2 0,0 2,2 4)') );

st_assvg
--------
M -2 0 A 2 2 0 0 1 2 0 A 2 2 0 0 1 2 -4

Multi-curve

SELECT ST_AsSVG('MULTICURVE((5 5,3 5,3 3,0 3),
 CIRCULARSTRING(0 0,2 1,2 2))'::geometry, 0, 0);
 st_assvg
------------------------------------------------
 M 5 -5 L 3 -5 3 -3 0 -3 M 0 0 A 2 2 0 0 0 2 -2
 

Multi-surface

SELECT ST_AsSVG('MULTISURFACE(
CURVEPOLYGON(CIRCULARSTRING(-2 0,-1 -1,0 0,1 -1,2 0,0 2,-2 0),
    (-1 0,0 0.5,1 0,0 1,-1 0)),
((7 8,10 10,6 14,4 11,7 8)))'::geometry, 0, 2);

st_assvg
---------------------------------------------------------
M -2 0 A 1 1 0 0 0 0 0 A 1 1 0 0 0 2 0 A 2 2 0 0 0 -2 0 Z
M -1 0 L 0 -0.5 1 0 0 -1 -1 0 Z
M 7 -8 L 10 -10 6 -14 4 -11 Z
 

Name

ST_AsTWKB — Returns the geometry as TWKB, aka "Tiny Well-Known Binary"

Synopsis

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);

Descrizione

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.

[Note]

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

Esempi

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

Name

ST_AsX3D — Returns a Geometry in X3D xml node element format: ISO-IEC-19776-1.2-X3DEncodings-XML

Synopsis

text ST_AsX3D(geometry g1, integer maxdecimaldigits=15, integer options=0);

Descrizione

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.

[Note]

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 Type2D X3D Type3D X3D Type
LINESTRINGnot yet implemented - will be PolyLine2DLineSet
MULTILINESTRINGnot yet implemented - will be PolyLine2DIndexedLineSet
MULTIPOINTPolypoint2DPointSet
POINToutputs the space delimited coordinatesoutputs the space delimited coordinates
(MULTI) POLYGON, POLYHEDRALSURFACEInvalid X3D markupIndexedFaceSet (inner rings currently output as another faceset)
TINTriangleSet2D (Not Yet Implemented)IndexedTriangleSet
[Note]

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.

Questa funzione supporta il 3d e non distrugge gli z-index.

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta i Triangoli e le Triangulated Irregular Network Surfaces (TIN).

Example: Create a fully functional X3D document - This will generate a cube that is viewable in FreeWrl and other X3D viewers.

SELECT '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE X3D PUBLIC "ISO//Web3D//DTD X3D 3.0//EN" "http://www.web3d.org/specifications/x3d-3.0.dtd">
<X3D>
  <Scene>
    <Transform>
      <Shape>
       <Appearance>
            <Material emissiveColor=''0 0 1''/>
       </Appearance
> ' ||
       ST_AsX3D( ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)),
((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)),
((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)),
((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )')) ||
      '</Shape>
    </Transform>
  </Scene>
</X3D
>' As x3ddoc;

                x3ddoc
                --------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE X3D PUBLIC "ISO//Web3D//DTD X3D 3.0//EN" "http://www.web3d.org/specifications/x3d-3.0.dtd">
<X3D>
  <Scene>
    <Transform>
      <Shape>
       <Appearance>
            <Material emissiveColor='0 0 1'/>
       </Appearance>
       <IndexedFaceSet  coordIndex='0 1 2 3 -1 4 5 6 7 -1 8 9 10 11 -1 12 13 14 15 -1 16 17 18 19 -1 20 21 22 23'>
            <Coordinate point='0 0 0 0 0 1 0 1 1 0 1 0 0 0 0 0 1 0 1 1 0 1 0 0 0 0 0 1 0 0 1 0 1 0 0 1 1 1 0 1 1 1 1 0 1 1 0 0 0 1 0 0 1 1 1 1 1 1 1 0 0 0 1 1 0 1 1 1 1 0 1 1' />
      </IndexedFaceSet>
      </Shape>
    </Transform>
  </Scene>
</X3D>

PostGIS buildings

Copy and paste the output of this query to x3d scene viewer and click Show

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

Example: An Octagon elevated 3 Units and decimal precision of 6

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>

Esempio: TIN

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>

Example: Closed multilinestring (the boundary of a polygon with holes)

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>

Name

ST_GeoHash — Return a GeoHash representation of the geometry.

Synopsis

text ST_GeoHash(geometry geom, integer maxchars=full_precision_of_point);

Descrizione

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

[Note]

ST_GeoHash requires input geometry to be in geographic (lon/lat) coordinates.

Questo metodo supporta le Curve e le Circular String.

Esempi

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

                

7.10. Operatori

7.10.1. Bounding Box Operators

  • && — Returns TRUE if A's 2D bounding box intersects B's 2D bounding box.
  • &&(geometry,box2df) — Returns TRUE if a geometry's (cached) 2D bounding box intersects a 2D float precision bounding box (BOX2DF).
  • &&(box2df,geometry) — Returns TRUE if a 2D float precision bounding box (BOX2DF) intersects a geometry's (cached) 2D bounding box.
  • &&(box2df,box2df) — Returns TRUE if two 2D float precision bounding boxes (BOX2DF) intersect each other.
  • &&& — Returns TRUE if A's n-D bounding box intersects B's n-D bounding box.
  • &&&(geometry,gidx) — Returns TRUE if a geometry's (cached) n-D bounding box intersects a n-D float precision bounding box (GIDX).
  • &&&(gidx,geometry) — Returns TRUE if a n-D float precision bounding box (GIDX) intersects a geometry's (cached) n-D bounding box.
  • &&&(gidx,gidx) — Returns TRUE if two n-D float precision bounding boxes (GIDX) intersect each other.
  • &< — Returns TRUE if A's bounding box overlaps or is to the left of B's.
  • &<| — Returns TRUE if A's bounding box overlaps or is below B's.
  • &> — Returns TRUE if A' bounding box overlaps or is to the right of B's.
  • << — Returns TRUE if A's bounding box is strictly to the left of B's.
  • <<| — Returns TRUE if A's bounding box is strictly below B's.
  • = — Returns TRUE if the coordinates and coordinate order geometry/geography A are the same as the coordinates and coordinate order of geometry/geography B.
  • >> — Returns TRUE if A's bounding box is strictly to the right of B's.
  • @ — Returns TRUE if A's bounding box is contained by B's.
  • @(geometry,box2df) — Returns TRUE if a geometry's 2D bounding box is contained into a 2D float precision bounding box (BOX2DF).
  • @(box2df,geometry) — Returns TRUE if a 2D float precision bounding box (BOX2DF) is contained into a geometry's 2D bounding box.
  • @(box2df,box2df) — Returns TRUE if a 2D float precision bounding box (BOX2DF) is contained into another 2D float precision bounding box.
  • |&> — Returns TRUE if A's bounding box overlaps or is above B's.
  • |>> — Returns TRUE if A's bounding box is strictly above B's.
  • ~ — Returns TRUE if A's bounding box contains B's.
  • ~(geometry,box2df) — Returns TRUE if a geometry's 2D bonding box contains a 2D float precision bounding box (GIDX).
  • ~(box2df,geometry) — Returns TRUE if a 2D float precision bounding box (BOX2DF) contains a geometry's 2D bonding box.
  • ~(box2df,box2df) — Returns TRUE if a 2D float precision bounding box (BOX2DF) contains another 2D float precision bounding box (BOX2DF).
  • ~= — Returns TRUE if A's bounding box is the same as B's.

Name

&& — Returns TRUE if A's 2D bounding box intersects B's 2D bounding box.

Synopsis

boolean &&( geometry A , geometry B );

boolean &&( geography A , geography B );

Descrizione

The && operator returns TRUE if the 2D bounding box of geometry A intersects the 2D bounding box of geometry B.

[Note]

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.

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Esempi

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)

Si veda anche

ST_Intersects, ST_Extent, |&>, &>, &<|, &<, ~, @


Name

&&(geometry,box2df) — Returns TRUE if a geometry's (cached) 2D bounding box intersects a 2D float precision bounding box (BOX2DF).

Synopsis

boolean &&( geometry A , box2df B );

Descrizione

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)

[Note]

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+.

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Esempi

SELECT ST_Point(1,1) && ST_MakeBox2D(ST_Point(0,0), ST_Point(2,2)) AS overlaps;

 overlaps
----------
 t
(1 row)

Name

&&(box2df,geometry) — Returns TRUE if a 2D float precision bounding box (BOX2DF) intersects a geometry's (cached) 2D bounding box.

Synopsis

boolean &&( box2df A , geometry B );

Descrizione

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)

[Note]

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+.

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Esempi

SELECT ST_MakeBox2D(ST_Point(0,0), ST_Point(2,2)) && ST_Point(1,1) AS overlaps;

 overlaps
----------
 t
(1 row)

Name

&&(box2df,box2df) — Returns TRUE if two 2D float precision bounding boxes (BOX2DF) intersect each other.

Synopsis

boolean &&( box2df A , box2df B );

Descrizione

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)

[Note]

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+.

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Esempi

SELECT ST_MakeBox2D(ST_Point(0,0), ST_Point(2,2)) && ST_MakeBox2D(ST_Point(1,1), ST_Point(3,3)) AS overlaps;

 overlaps
----------
 t
(1 row)

Name

&&& — Returns TRUE if A's n-D bounding box intersects B's n-D bounding box.

Synopsis

boolean &&&( geometry A , geometry B );

Descrizione

The &&& operator returns TRUE if the n-D bounding box of geometry A intersects the n-D bounding box of geometry B.

[Note]

This operand will make use of any indexes that may be available on the geometries.

Disponibilità: 2.0.0

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta i Triangoli e le Triangulated Irregular Network Surfaces (TIN).

Questa funzione supporta il 3d e non distrugge gli z-index.

Examples: 3D LineStrings

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

Examples: 3M LineStrings

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

Si veda anche

&&


Name

&&&(geometry,gidx) — Returns TRUE if a geometry's (cached) n-D bounding box intersects a n-D float precision bounding box (GIDX).

Synopsis

boolean &&&( geometry A , gidx B );

Descrizione

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)

[Note]

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+.

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta i Triangoli e le Triangulated Irregular Network Surfaces (TIN).

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

SELECT ST_MakePoint(1,1,1) &&& ST_3DMakeBox(ST_MakePoint(0,0,0), ST_MakePoint(2,2,2)) AS overlaps;

 overlaps
----------
 t
(1 row)

Si veda anche

&&&(gidx,geometry), &&


Name

&&&(gidx,geometry) — Returns TRUE if a n-D float precision bounding box (GIDX) intersects a geometry's (cached) n-D bounding box.

Synopsis

boolean &&&( gidx A , geometry B );

Descrizione

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)

[Note]

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+.

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta i Triangoli e le Triangulated Irregular Network Surfaces (TIN).

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

SELECT ST_3DMakeBox(ST_MakePoint(0,0,0), ST_MakePoint(2,2,2)) &&& ST_MakePoint(1,1,1) AS overlaps;

 overlaps
----------
 t
(1 row)

Si veda anche

&&&(geometry,gidx), &&


Name

&&&(gidx,gidx) — Returns TRUE if two n-D float precision bounding boxes (GIDX) intersect each other.

Synopsis

boolean &&&( gidx A , gidx B );

Descrizione

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)

[Note]

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+.

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta i Triangoli e le Triangulated Irregular Network Surfaces (TIN).

Questa funzione supporta il 3d e non distrugge gli z-index.

Esempi

SELECT ST_3DMakeBox(ST_MakePoint(0,0,0), ST_MakePoint(2,2,2)) &&& ST_3DMakeBox(ST_MakePoint(1,1,1), ST_MakePoint(3,3,3)) AS overlaps;

 overlaps
----------
 t
(1 row)

Si veda anche

&&&(geometry,gidx), &&


Name

&< — Returns TRUE if A's bounding box overlaps or is to the left of B's.

Synopsis

boolean &<( geometry A , geometry B );

Descrizione

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.

[Note]

This operand will make use of any indexes that may be available on the geometries.

Esempi

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)

Si veda anche

&&, |&>, &>, &<|


Name

&<| — Returns TRUE if A's bounding box overlaps or is below B's.

Synopsis

boolean &<|( geometry A , geometry B );

Descrizione

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.

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

[Note]

This operand will make use of any indexes that may be available on the geometries.

Esempi

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)

Si veda anche

&&, |&>, &>, &<


Name

&> — Returns TRUE if A' bounding box overlaps or is to the right of B's.

Synopsis

boolean &>( geometry A , geometry B );

Descrizione

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.

[Note]

This operand will make use of any indexes that may be available on the geometries.

Esempi

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)

Si veda anche

&&, |&>, &<|, &<


Name

<< — Returns TRUE if A's bounding box is strictly to the left of B's.

Synopsis

boolean <<( geometry A , geometry B );

Descrizione

The << operator returns TRUE if the bounding box of geometry A is strictly to the left of the bounding box of geometry B.

[Note]

This operand will make use of any indexes that may be available on the geometries.

Esempi

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)

Si veda anche

>>, |>>, <<|


Name

<<| — Returns TRUE if A's bounding box is strictly below B's.

Synopsis

boolean <<|( geometry A , geometry B );

Descrizione

The <<| operator returns TRUE if the bounding box of geometry A is strictly below the bounding box of geometry B.

[Note]

This operand will make use of any indexes that may be available on the geometries.

Esempi

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)

Si veda anche

<<, >>, |>>


Name

= — Returns TRUE if the coordinates and coordinate order geometry/geography A are the same as the coordinates and coordinate order of geometry/geography B.

Synopsis

boolean =( geometry A , geometry B );

boolean =( geography A , geography B );

Descrizione

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).

[Note]

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

[Caution]

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.

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Esempi

SELECT 'LINESTRING(0 0, 0 1, 1 0)'::geometry = 'LINESTRING(1 1, 0 0)'::geometry;
 ?column?
----------
 f
(1 row)

SELECT ST_AsText(column1)
FROM ( VALUES
        ('LINESTRING(0 0, 1 1)'::geometry),
        ('LINESTRING(1 1, 0 0)'::geometry)) AS foo;
          st_astext
---------------------
 LINESTRING(0 0,1 1)
 LINESTRING(1 1,0 0)
(2 rows)

-- Note: the GROUP BY uses the "=" to compare for geometry equivalency.
SELECT ST_AsText(column1)
FROM ( VALUES
        ('LINESTRING(0 0, 1 1)'::geometry),
        ('LINESTRING(1 1, 0 0)'::geometry)) AS foo
GROUP BY column1;
      st_astext
---------------------
 LINESTRING(0 0,1 1)
 LINESTRING(1 1,0 0)
(2 rows)

-- In versions prior to 2.0, this used to return true --
 SELECT ST_GeomFromText('POINT(1707296.37 4820536.77)') =
        ST_GeomFromText('POINT(1707296.27 4820536.87)') As pt_intersect;

--pt_intersect --
f

Si veda anche

ST_Equals, ST_OrderingEquals, =


Name

>> — Returns TRUE if A's bounding box is strictly to the right of B's.

Synopsis

boolean >>( geometry A , geometry B );

Descrizione

The >> operator returns TRUE if the bounding box of geometry A is strictly to the right of the bounding box of geometry B.

[Note]

This operand will make use of any indexes that may be available on the geometries.

Esempi

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)

Si veda anche

<<, |>>, <<|


Name

@ — Returns TRUE if A's bounding box is contained by B's.

Synopsis

boolean @( geometry A , geometry B );

Descrizione

The @ operator returns TRUE if the bounding box of geometry A is completely contained by the bounding box of geometry B.

[Note]

This operand will make use of any indexes that may be available on the geometries.

Esempi

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)

Si veda anche

~, &&


Name

@(geometry,box2df) — Returns TRUE if a geometry's 2D bounding box is contained into a 2D float precision bounding box (BOX2DF).

Synopsis

boolean @( geometry A , box2df B );

Descrizione

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)

[Note]

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+.

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Esempi

SELECT ST_Buffer(ST_GeomFromText('POINT(2 2)'), 1) @ ST_MakeBox2D(ST_Point(0,0), ST_Point(5,5)) AS is_contained;

 is_contained
--------------
 t
(1 row)

Name

@(box2df,geometry) — Returns TRUE if a 2D float precision bounding box (BOX2DF) is contained into a geometry's 2D bounding box.

Synopsis

boolean @( box2df A , geometry B );

Descrizione

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)

[Note]

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+.

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Esempi

SELECT ST_MakeBox2D(ST_Point(2,2), ST_Point(3,3)) @ ST_Buffer(ST_GeomFromText('POINT(1 1)'), 10) AS is_contained;

 is_contained
--------------
 t
(1 row)

Name

@(box2df,box2df) — Returns TRUE if a 2D float precision bounding box (BOX2DF) is contained into another 2D float precision bounding box.

Synopsis

boolean @( box2df A , box2df B );

Descrizione

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)

[Note]

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+.

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Esempi

SELECT ST_MakeBox2D(ST_Point(2,2), ST_Point(3,3)) @ ST_MakeBox2D(ST_Point(0,0), ST_Point(5,5)) AS is_contained;

 is_contained
--------------
 t
(1 row)

Name

|&> — Returns TRUE if A's bounding box overlaps or is above B's.

Synopsis

boolean |&>( geometry A , geometry B );

Descrizione

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.

[Note]

This operand will make use of any indexes that may be available on the geometries.

Esempi

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)

Si veda anche

&&, &>, &<|, &<


Name

|>> — Returns TRUE if A's bounding box is strictly above B's.

Synopsis

boolean |>>( geometry A , geometry B );

Descrizione

The |>> operator returns TRUE if the bounding box of geometry A is strictly above the bounding box of geometry B.

[Note]

This operand will make use of any indexes that may be available on the geometries.

Esempi

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)

Si veda anche

<<, >>, <<|


Name

~ — Returns TRUE if A's bounding box contains B's.

Synopsis

boolean ~( geometry A , geometry B );

Descrizione

The ~ operator returns TRUE if the bounding box of geometry A completely contains the bounding box of geometry B.

[Note]

This operand will make use of any indexes that may be available on the geometries.

Esempi

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)

Si veda anche

@, &&


Name

~(geometry,box2df) — Returns TRUE if a geometry's 2D bonding box contains a 2D float precision bounding box (GIDX).

Synopsis

boolean ~( geometry A , box2df B );

Descrizione

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)

[Note]

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+.

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Esempi

SELECT ST_Buffer(ST_GeomFromText('POINT(1 1)'), 10) ~ ST_MakeBox2D(ST_Point(0,0), ST_Point(2,2)) AS contains;

 contains
----------
 t
(1 row)

Name

~(box2df,geometry) — Returns TRUE if a 2D float precision bounding box (BOX2DF) contains a geometry's 2D bonding box.

Synopsis

boolean ~( box2df A , geometry B );

Descrizione

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)

[Note]

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+.

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Esempi

SELECT ST_MakeBox2D(ST_Point(0,0), ST_Point(5,5)) ~ ST_Buffer(ST_GeomFromText('POINT(2 2)'), 1) AS contains;

 contains
----------
 t
(1 row)

Name

~(box2df,box2df) — Returns TRUE if a 2D float precision bounding box (BOX2DF) contains another 2D float precision bounding box (BOX2DF).

Synopsis

boolean ~( box2df A , box2df B );

Descrizione

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)

[Note]

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+.

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta le Polyhedral Surface.

Esempi

SELECT ST_MakeBox2D(ST_Point(0,0), ST_Point(5,5)) ~ ST_MakeBox2D(ST_Point(2,2), ST_Point(3,3)) AS contains;

 contains
----------
 t
(1 row)

Name

~= — Returns TRUE if A's bounding box is the same as B's.

Synopsis

boolean ~=( geometry A , geometry B );

Descrizione

The ~= operator returns TRUE if the bounding box of geometry/geography A is the same as the bounding box of geometry/geography B.

[Note]

This operand will make use of any indexes that may be available on the geometries.

Availability: 1.5.0 changed behavior

Questa funzione supporta le Polyhedral Surface.

[Warning]

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.

Esempi

select 'LINESTRING(0 0, 1 1)'::geometry ~= 'LINESTRING(0 1, 1 0)'::geometry as equality;
 equality   |
-----------------+
          t    |
                        

7.10.2. Operatori

  • <-> — Returns the 2D distance between A and B.
  • |=| — Returns the distance between A and B trajectories at their closest point of approach.
  • <#> — Returns the 2D distance between A and B bounding boxes.
  • <<->> — Returns the n-D distance between the A and B geometries or bounding boxes

Name

<-> — Returns the 2D distance between A and B.

Synopsis

double precision <->( geometry A , geometry B );

double precision <->( geography A , geography B );

Descrizione

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.

[Note]

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.

[Note]

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+

Esempi

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 geom <-> 'SRID=3005;POINT(1011102 450541)'::geometry limit 10;

        d         | edabbr | vaabbr
------------------+--------+--------
                0 | ALQ    | 128
 5541.57712511724 | ALQ    | 129A
 5579.67450712005 | ALQ    | 001
  6083.4207708641 | ALQ    | 131
  7691.2205404848 | ALQ    | 003
 7900.75451037313 | ALQ    | 122
 8694.20710669982 | ALQ    | 129B
 9564.24289057111 | ALQ    | 130
  12089.665931705 | ALQ    | 127
 18472.5531479404 | ALQ    | 002
(10 rows)

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)


Si veda anche

ST_DWithin, ST_Distance, <#>


Name

|=| — Returns the distance between A and B trajectories at their closest point of approach.

Synopsis

double precision |=|( geometry A , geometry B );

Descrizione

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).

[Note]

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.

[Note]

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+

Esempi

-- 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)

Name

<#> — Returns the 2D distance between A and B bounding boxes.

Synopsis

double precision <#>( geometry A , geometry B );

Descrizione

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.

[Note]

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.

[Note]

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+

Esempi

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)

Si veda anche

ST_DWithin, ST_Distance, <->


Name

<<->> — Returns the n-D distance between the A and B geometries or bounding boxes

Synopsis

double precision <<->>( geometry A , geometry B );

Descrizione

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.

[Note]

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.

[Note]

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+

Si veda anche

<->

7.11. Relazioni Spaziali

Abstract

Queste funzioni determinano la relazione spaziale tra due geometrie.

7.11.1. Relazioni Topologiche

  • ST_3DIntersects — Tests if two geometries spatially intersect in 3D - only for points, linestrings, polygons, polyhedral surface (area)
  • ST_Contains — Tests if every point of B lies in A, and their interiors have a point in common
  • ST_ContainsProperly — Tests if every point of B lies in the interior of A
  • ST_CoveredBy — Tests if every point of A lies in B
  • ST_Covers — Tests if every point of B lies in A
  • ST_Crosses — Tests if two geometries have some, but not all, interior points in common
  • ST_Disjoint — Tests if two geometries have no points in common
  • ST_Equals — Tests if two geometries include the same set of points
  • ST_Intersects — Tests if two geometries intersect (they have at least one point in common)
  • ST_LineCrossingDirection — Returns a number indicating the crossing behavior of two LineStrings
  • ST_OrderingEquals — Tests if two geometries represent the same geometry and have points in the same directional order
  • ST_Overlaps — Tests if two geometries have the same dimension and intersect, but each has at least one point not in the other
  • ST_Relate — Tests if two geometries have a topological relationship matching an Intersection Matrix pattern, or computes their Intersection Matrix
  • ST_RelateMatch — Tests if a DE-9IM Intersection Matrix matches an Intersection Matrix pattern
  • ST_Touches — Tests if two geometries have at least one point in common, but their interiors do not intersect
  • ST_Within — Tests if every point of A lies in B, and their interiors have a point in common

Name

ST_3DIntersects — Tests if two geometries spatially intersect in 3D - only for points, linestrings, polygons, polyhedral surface (area)

Synopsis

boolean ST_3DIntersects( geometry geomA , geometry geomB );

Descrizione

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.

[Note]

Questa funzione incorpora l'uso di una comparazione tra i bounding box in modo da usare qualunque indice spaziale disponibile sulle geometrie.

[Note]

Because of floating robustness failures, geometries don't always intersect as you'd expect them to after geometric processing. For example the closest point on a linestring to a geometry may not lie on the linestring. For these kind of issues where a distance of a centimeter you want to just consider as intersecting, use ST_3DDWithin.

Changed: 3.0.0 SFCGAL backend removed, GEOS backend supports TINs.

Disponibilità: 2.0.0

Questa funzione supporta il 3d e non distrugge gli z-index.

Questa funzione supporta le Polyhedral Surface.

Questa funzione supporta i Triangoli e le Triangulated Irregular Network Surfaces (TIN).

Questo metodo implementa la specifica SQL/MM. SQL-MM IEC 13249-3: 5.1

Geometry Examples

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)
    

TIN Examples

SELECT ST_3DIntersects('TIN(((0 0 0,1 0 0,0 1 0,0 0 0)))'::geometry, 'POINT(.1 .1 0)'::geometry);
 st_3dintersects
-----------------
 t

Name

ST_Contains — Tests if every point of B lies in A, and their interiors have a point in common

Synopsis

boolean ST_Contains(geometry geomA, geometry geomB);

Descrizione

Returns TRUE if geometry A contains geometry B. A contains B if and only if all points of B lie inside (i.e. in the interior or boundary of) A (or equivalently, no points of B lie in the exterior of A), and the interiors of A and B have at least one point in common.

In mathematical terms: ST_Contains(A, B) ⇔ (A ⋂ B = B) ∧ (Int(A) ⋂ Int(B) ≠ ∅)

The contains relationship is reflexive: every geometry contains itself. (In contrast, in the ST_ContainsProperly predicate a geometry does not properly contain itself.) The relationship is antisymmetric: if ST_Contains(A,B) = true and ST_Contains(B,A) = true, then the two geometries must be topologically equal (ST_Equals(A,B) = true).

ST_Contains is the converse of ST_Within. So, ST_Contains(A,B) = ST_Within(B,A).

[Note]

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.

[Note]

Questa funzione incorpora l'uso di una comparazione tra i bounding box in modo da usare qualunque indice spaziale disponibile sulle geometrie. To avoid index use, use the function _ST_Contains.

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.

[Important]

Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION

[Important]

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.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.2 // s2.1.13.3 - same as within(geometry B, geometry A)

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 5.1.31

Esempi

ST_Contains returns TRUE in the following situations:

LINESTRING / MULTIPOINT

POLYGON / POINT

POLYGON / LINESTRING

POLYGON / POLYGON

ST_Contains returns FALSE in the following situations:

POLYGON / MULTIPOINT

POLYGON / LINESTRING

Due to the interior intersection condition ST_Contains returns FALSE in the following situations (whereas ST_Covers returns TRUE):

LINESTRING / POINT

POLYGON / LINESTRING

-- 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

 

Name

ST_ContainsProperly — Tests if every point of B lies in the interior of A

Synopsis

boolean ST_ContainsProperly(geometry geomA, geometry geomB);

Descrizione

Returns true if every point of B lies in the interior of A (or equivalently, no point of B lies in the the boundary or exterior of A).

In mathematical terms: ST_ContainsProperly(A, B) ⇔ Int(A) ⋂ B = B

A contains B properly if the DE-9IM Intersection Matrix for the two geometries matches [T**FF*FF*]

A does not properly contain itself, but does contain itself.

A use for this predicate is computing the intersections of a set of geometries with a large polygonal geometry. Since intersection is a fairly slow operation, it can be more efficient to use containsProperly to filter out test geometries which lie fully inside the area. In these cases the intersection is known a priori to be exactly the original test geometry.

[Note]

Questa funzione incorpora l'uso di una comparazione tra i bounding box in modo da usare qualunque indice spaziale disponibile sulle geometrie. To avoid index use, use the function _ST_ContainsProperly.

[Note]

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.

Disponibilità: 1.4.0

[Important]

Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION

[Important]

Do not use this function with invalid geometries. You will get unexpected results.

Esempi

--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
 

Name

ST_CoveredBy — Tests if every point of A lies in B

Synopsis

boolean ST_CoveredBy(geometry geomA, geometry geomB);

boolean ST_CoveredBy(geography geogA, geography geogB);

Descrizione

Returns true if every point in Geometry/Geography A lies inside (i.e. intersects the interior or boundary of) Geometry/Geography B. Equivalently, tests that no point of A lies outside (in the exterior of) B.

In mathematical terms: ST_CoveredBy(A, B) ⇔ A ⋂ B = A

ST_CoveredBy is the converse of ST_Covers. So, ST_CoveredBy(A,B) = ST_Covers(B,A).

Generally this function should be used instead of ST_Within, since it has a simpler definition which does not have the quirk that "boundaries are not within their geometry".

[Note]

Questa funzione incorpora l'uso di una comparazione tra i bounding box in modo da usare qualunque indice spaziale disponibile sulle geometrie. To avoid index use, use the function _ST_CoveredBy.

[Important]

Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION

[Important]

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.

Esempi

--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) 

Name

ST_Covers — Tests if every point of B lies in A

Synopsis

boolean ST_Covers(geometry geomA, geometry geomB);

boolean ST_Covers(geography geogpolyA, geography geogpointB);

Descrizione

Returns true if every point in Geometry/Geography B lies inside (i.e. intersects the interior or boundary of) Geometry/Geography A. Equivalently, tests that no point of B lies outside (in the exterior of) A.

In mathematical terms: ST_Covers(A, B) ⇔ A ⋂ B = B

ST_Covers is the converse of ST_CoveredBy. So, ST_Covers(A,B) = ST_CoveredBy(B,A).

Generally this function should be used instead of ST_Contains, since it has a simpler definition which does not have the quirk that "geometries do not contain their boundary".

[Note]

Questa funzione incorpora l'uso di una comparazione tra i bounding box in modo da usare qualunque indice spaziale disponibile sulle geometrie. To avoid index use, use the function _ST_Covers.

[Important]

Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION

[Important]

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.

Esempi

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
    

Name

ST_Crosses — Tests if two geometries have some, but not all, interior points in common

Synopsis

boolean ST_Crosses(geometry g1, geometry g2);

Descrizione

Compares two geometry objects and returns true if their intersection "spatially crosses"; that is, the geometries have some, but not all interior points in common. The intersection of the interiors of the geometries must be non-empty and must have dimension less than the maximum dimension of the two input geometries, and the intersection of the two geometries must not equal either geometry. Otherwise, it returns false. The crosses relation is symmetric and irreflexive.

In mathematical terms: ST_Crosses(A, B) ⇔ (dim( Int(A) ⋂ Int(B) ) < max( dim( Int(A) ), dim( Int(B) ) )) ∧ (A ⋂ B ≠ A) ∧ (A ⋂ B ≠ B)

Geometries cross if their DE-9IM Intersection Matrix matches:

  • T*T****** for Point/Line, Point/Area, and Line/Area situations

  • T*****T** for Line/Point, Area/Point, and Area/Line situations

  • 0******** for Line/Line situations

  • the result is false for Point/Point and Area/Area situations

[Note]

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.

[Note]

Questa funzione incorpora l'uso di una comparazione tra i bounding box in modo da usare qualunque indice spaziale disponibile sulle geometrie.

[Important]

Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1. s2.1.13.3

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 5.1.29

Esempi

The following situations all return true.

MULTIPOINT / LINESTRING

MULTIPOINT / POLYGON

LINESTRING / POLYGON

LINESTRING / LINESTRING

Consider a situation where a user has two tables: a table of roads and a table of highways.

CREATE TABLE roads (
  id serial NOT NULL,
  geom geometry,
  CONSTRAINT roads_pkey PRIMARY KEY (road_id)
);

CREATE TABLE highways (
  id serial NOT NULL,
  the_gem geometry,
  CONSTRAINT roads_pkey PRIMARY KEY (road_id)
);

To determine a list of roads that cross a highway, use a query similar to:

SELECT roads.id
FROM roads, highways
WHERE ST_Crosses(roads.geom, highways.geom);

Si veda anche

ST_Contains, ST_Overlaps


Name

ST_Disjoint — Tests if two geometries have no points in common

Synopsis

boolean ST_Disjoint( geometry A , geometry B );

Descrizione

Returns true if two geometries are disjoint. Geometries are disjoint if they have no point in common.

If any other spatial relationship is true for a pair of geometries, they are not disjoint. Disjoint implies that ST_Intersects is false.

In mathematical terms: ST_Disjoint(A, B) ⇔ A ⋂ B = ∅

[Important]

Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION

Eseguito dal modulo GEOS

[Note]

This function call does not use indexes. A negated ST_Intersects predicate can be used as a more performant alternative that uses indexes: ST_Disjoint(A,B) = NOT ST_Intersects(A,B)

[Note]

NOTE: this is the "allowable" version that returns a boolean, not an integer.

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.2 //s2.1.13.3 - a.Relate(b, 'FF*FF****')

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 5.1.26

Esempi

SELECT ST_Disjoint('POINT(0 0)'::geometry, 'LINESTRING ( 2 0, 0 2 )'::geometry);
 st_disjoint
---------------
 t
(1 row)
SELECT ST_Disjoint('POINT(0 0)'::geometry, 'LINESTRING ( 0 0, 0 2 )'::geometry);
 st_disjoint
---------------
 f
(1 row)
    

Si veda anche

ST_Intersects


Name

ST_Equals — Tests if two geometries include the same set of points

Synopsis

boolean ST_Equals(geometry A, geometry B);

Descrizione

Returns true if the given geometries are "topologically equal". Use this for a 'better' answer than '='. Topological equality means that the geometries have the same dimension, and their point-sets occupy the same space. This means that the order of vertices may be different in topologically equal geometries. To verify the order of points is consistent use ST_OrderingEquals (it must be noted ST_OrderingEquals is a little more stringent than simply verifying order of points are the same).

In mathematical terms: ST_Equals(A, B) ⇔ A = B

The following relation holds: ST_Equals(A, B) ⇔ ST_Within(A,B) ∧ ST_Within(B,A)

[Important]

Enhanced: 3.0.0 enabled support for GEOMETRYCOLLECTION

Questo metodo implementa le OGC Simple Features Implementation Specification for SQL 1.1. s2.1.1.2

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 5.1.24

Changed: 2.2.0 Returns true even for invalid geometries if they are binary equal

Esempi

SELECT ST_Equals(ST_GeomFromText('LINESTRING(0 0, 10 10)'),
    ST_GeomFromText('LINESTRING(0 0, 5 5, 10 10)'));
 st_equals
-----------
 t
(1 row)

SELECT ST_Equals(ST_Reverse(ST_GeomFromText('LINESTRING(0 0, 10 10)')),
    ST_GeomFromText('LINESTRING(0 0, 5 5, 10 10)'));
 st_equals
-----------
 t
(1 row)

Name

ST_Intersects — Tests if two geometries intersect (they have at least one point in common)

Synopsis

boolean ST_Intersects( geometry geomA , geometry geomB );

boolean ST_Intersects( geography geogA , geography geogB );

Descrizione

Returns true if two geometries intersect. Geometries intersect if they have any point in common.

For geography, a distance tolerance of 0.00001 meters is used (so points that are very close are considered to intersect).

In mathematical terms: ST_Intersects(A, B) ⇔ A ⋂ B ≠ ∅

Geometries intersect if their DE-9IM Intersection Matrix matches one of:

  • T********

  • *T*******

  • ***T*****

  • ****T****

Spatial intersection is implied by all the other spatial relationship tests, except ST_Disjoint, which tests that geometries do NOT intersect.

[Note]

Questa funzione incorpora l'uso di una comparazione tra i bounding box in modo da usare qualunque indice spaziale disponibile sulle geometrie.

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.

[Note]

For geography, this function has a distance tolerance of about 0.00001 meters and uses the sphere rather than spheroid calculation.

[Note]

NOTE: this is the "allowable" version that returns a boolean, not an integer.

Questo metodo implementa le 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 ))

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 5.1.27

Questo metodo supporta le Curve e le Circular String.

Questa funzione supporta i Triangoli e le Triangulated Irregular Network Surfaces (TIN).

Geometry Examples

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)

Geography Examples

SELECT ST_Intersects(
    'SRID=4326;LINESTRING(-43.23456 72.4567,-43.23456 72.4568)'::geography,
    'SRID=4326;POINT(-43.23456 72.4567772)'::geography
    );

 st_intersects
---------------
t

Name

ST_LineCrossingDirection — Returns a number indicating the crossing behavior of two LineStrings

Synopsis

integer ST_LineCrossingDirection(geometry linestringA, geometry linestringB);

Descrizione

Given two linestrings returns an integer between -3 and 3 indicating what kind of crossing behavior exists between them. 0 indicates no crossing. This is only supported for LINESTRINGs.

The crossing number has the following meaning:

  • 0: LINE NO CROSS

  • -1: LINE CROSS LEFT

  • 1: LINE CROSS RIGHT

  • -2: LINE MULTICROSS END LEFT

  • 2: LINE MULTICROSS END RIGHT

  • -3: LINE MULTICROSS END SAME FIRST LEFT

  • 3: LINE MULTICROSS END SAME FIRST RIGHT

Availability: 1.4

Esempi

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;

Si veda anche

ST_Crosses


Name

ST_OrderingEquals — Tests if two geometries represent the same geometry and have points in the same directional order

Synopsis

boolean ST_OrderingEquals(geometry A, geometry B);

Descrizione

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).

[Note]

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

Questo metodo implementa la specifica SQL/MM. SQL-MM 3: 5.1.43

Esempi

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)

Si veda anche

&&, ST_Equals, ST_Reverse


Name

ST_Overlaps — Tests if two geometries have the same dimension and intersect, but each has at least one point not in the other

Synopsis

boolean ST_Overlaps(geometry A, geometry B);

Descrizione

Returns TRUE if geometry A and B "spatially overlap". Two geometries overlap if they have the same dimension, their interiors intersect in that dimension. and each has at least one point inside the other (or equivalently, neither one covers the other). The overlaps relation is symmetric and irreflexive.