OpenGIS - Soluzioni libere per l'analisi geospaziale
QuantumGIS e OpenJUMP - PostGIS
Master "Tecnologie OpenSource"
Argomenti della lezione
- PostGIS, OpenJUMP e QuantumGIS
- Preparazione dell’ambiente di lavoro
- Primi passi in QuantumGIS
- Caratteristiche di OpenJUMP
- Introduzione a PostGIS
- Operazioni comuni con PostGIS
- Analisi vettoriale in PostGIS
- Visualizzazione di dati in PostGIS su QGIS e OpenJUMP
PostGIS
PostGIS aggiunge il supporto a oggetti geografici al database relazioanle PostgreSQL. L’installazione di PostGIS permette di utilizzare PostgreSQL come backend dati nei sistemi GIS che lo supportano, implementandi un’architettura simile a ESRI SDE o Oracle Spatial Extensions.
PostGIS segue lo standard OGC Simple Features Specifications for SQL, ed è certificato come aderente alle specifiche Types and Functions.
PostGIS è stato sviluppato dalla “Refractions Research” ed è software libero, rilasciato in licenza GPL.
OpenJUMP
OpenJUMP è un GIS open source scritto in Java. È basato su JUMP GIS di Vivid Solutions.
È un GIS particolarmente orientato all’analisi vettoriale, con limitate funzionalità di gestione di dati raster. Essendo scritto in Java, è portabile su tutte le piattaforme per le quali sia disponibile una Java Virtual Machine (JVM).
Anche OpenJump è un software rilasciato in GPL.
QuantumGIS
Quantum GIS (QGIS) è un software GIS user friendly e Open Source, rilasciato in licenza GPL.
QGIS è un progetto ufficiale dell’Open Source Geospatial Foundation (OSGeo). È un software multipiattaforma che gira su Linux, Unix, Mac OSX, e Windows; supporta numerosi formati vettoriali e raster e offre meccanismi di connessione a database relazionali con estensioni geografiche.
Quantum GIS fornisce un numero sempre crescente di funzionalità (sia interne che in forma di plugins). Con QGIS è possibile gestire, visualizzare ed editare dati geografici, effettuare analisi dei data e comporre cartografia tematica.
Open Geospatial Consortium
Open Geospatial Consortium (OGC) è un’organizzazione no-profit che si occupa di produrre standard aperti per servizi di tipo geospaziale.
Attulmente il consorzio riunsce 382 entità, tra cui aziende, agenzie governative e università. Tra i molti documenti prodotti, si devono annoverare:
- GML (Geographic Markup Language)
- KML (Keyhole Markup Language): applicazione XML introdotta da google con i suoi servizi gMaps e gEarth
- WMS/WFS (Web Map/Features Service): API per l’implementazione di servizi Web services cartografici
Nota: OpenGIS è un marchio registrato di OGC.
Installazione di PostGIS in Ubuntu (1/3)
Ubuntu fornisce nei suoi repository (precisamente in universe) il pacchetto binario di PostGIS.
Per questo l’installazione base del programma si ottiene lanciando semplicemente il comando:
sudo apt-get install postgresql-8.3-postgis
Installazione di PostGIS in Ubuntu (2/3)
A questo punto è necessaria un po’ di post-configurazione:
- Creare un utente in PostgreSQL (qualora non ne sia presente già alcuno)
- Creare un database che rappresenterà il template per i DB Geo-enabled
- Creare il linuguaggio procedurale plpgsql (se non esiste)
- Caricare nel template alcuni dati necessari
createdb geotemplate
createlang plpgsql geotemplate
psql -d geotemplate -f /usr/share/postgresql-8.3-postgis/lwpostgis.sql
psql -d geotemplate -f /usr/share/postgresql-8.3-postgis/spatial_ref_sys.sql
Installazione di PostGIS in Ubuntu (3/3)
A questo punto si è in grado di creare un database con supporto geospaziale. Dal client psql digitare i seguenti comandi
CREATE DATABASE provagis TEMPLATE = geotemplate;
Per verificare invece che l’installazione sia andata a buon fine:
SELECT postgis_geos_version();
Installazione di QuantumGIS in Ubuntu (1/3)
Dalla versione 8.04 di Ubuntu QuantumGIS è stato rimosso dai repository Canonical. Per installare i binari del software sono dunque necessari i seguenti step:
Installazione di QuantumGIS in Ubuntu (2/3)
Dalla versione 8.10 di Ubuntu (Intrepid Ibex) Canonical ha aggiunto alle GNU libc il supporto a FORTIFY, un flag di compilazione che esegue check run-time del codice binario, allo scopo di eliminare eventuali problemi nella gestione della memoria (buffer overflows).
Tale funzionalità ha però introdotto un BUG nelle librerie gdal (librerie per il supporto a decine di formati raster georeferenziati), che provoca il crash di QuantumGIS in alcune situazioni.
Per ovviare a questo inconveniente al momento l’unica soluzione è ricompilare il pacchetto libgdal1-1.3.0, disabilitando tale flag.
Installazione di QuantumGIS in Ubuntu (3/3)
Installazione di OpenJUMP
L’installazione di OpenJump è un procedimento estremamente semplice, essendo il SW scritto in Java (quindi multipiattaforma).
In realtà è sufficiente scaricare lo zip contenente il programma e decomprimerlo nella propria home:
cd ~
mkdir OpenJump; cd OpenJump
wget http://jump-pilot.sourceforge.net/download/nightlybuild/openjump-core-1.3-20090423-bin.zip
unzip openjump-core-1.3-20090423-bin.zip
Per lanciare il programma invece, da terminale:
cd ~/OpenJump/bin
./openjump.sh&
Presentazione di QuantumGIS (1/2)
Con QGIS è possibile effettuare le seguenti operazioni:
- Visualizzare layer vettoriali e raster
- Modificare i tematismi vettoriali
- Modificare la sibologia (intervalli uguali, quantili…)
- Modificare la visualizzazione dei raster (agendo su bande e intervalli di valori)
- Visualizzare, selezionare e modificare attributi
- Definire azioni sugli attributi
- Digitalizzare mappe raster (vettorializzazione)
Presentazione di QuantumGIS (2/2)
Formati di file supportati:
- tutti i più comuni formati raster (georeferenziati e non)
- ESRI shp, Mapinfo (mif/tab), Spatial Data Transfer (cadt/ddf), GML
QuantumGIS supporta inoltre:
- il caricamento di dati da Database Goegrafico (in particolare PostGIS)
- il supporto a web services che esportino servizi WMS o WFS
Presentazione di OpenJump (1/3)
OpenJump offre le seguenti funzionalità di base:
- Visualizzazino layer vettoriali e raster
- Modifica dei tematismi vettoriali
- Modifica della sibologia (intervalli uguali, quantili…)
- Visualizzione, selezione e modifica degli attributi
- Digitalizzazione mappe raster (vettorializzazione)
- Esportazione delle carte in formati raster (png/jpeg) e vettoriali (svg)
Presentazione di OpenJump (2/3)
Sono inoltre fornite alcune funzioni avanzate:
- Creazione di query guidate sulla tabella attributi
- Creazione guidata di query spaziali (distanza, area, buffer..)
- Funzionalità di analisi vettoriale (unione, intersezione, sovrapposizione)
- Funzioni statistiche sugli attributi
- Risoluzione delle geometrie errate
- Generazione di buffer e inviluppo complesso
- Trasformazione di geometrie
Presentazione di OpenJump (3/3)
OpenJump supporta tutti i principali formati raster e vettoriali, il caricamento dati da web services WMS, e la connetività a PostGIS.
Attraverso quest’ultimo meccanismo mette a disposizione dell’utente tutte le caratteristiche di analisi vettoriali di PostGIS (è possibile inserire normali query SQL o PL/pgSQL attraverso una semplice interfaccia, in fase di aggiunta di un layer PostGIS).
Un’altra caratteristica degna di nota di OpenJump è la sua architettura a plug-ins, che permette di aggiungere nuove funzionalità in maniera estremamente semplice. Una lista delle estensioni supportate può essere reperita all’indirizzo:
http://www.openjump.org/wiki/show/Plugins
Presentazione di PostGIS
PostGIS aggiunge il supporto geospaziale al database relazionale ad oggetti PostgreSQL, attraverso una libreria (in C) che estende il linguaggio procedurale PL/pgSQL. Attualmente fornisce le seguenti funzionalità:
- Memorizzazione di dati vettoriali in formato testo e binario
- Supporto a geometrie di tipo point, line, polygon, multipoint, multiline, multipolygon, and geometrycollections
- Supporto a geometrie EWKB/EWKT (3dm,3dz,4d) e SRID (spatial referencing system identifier) embedded
- Supporto a funzionalità di analisi vettoriale
- Indicizzazione delle colonne geometriche, per ottimizzazioni in performance
- Riproiezione al volo dei layer vettoriali nei sistemi di riferimento supportati
- Query miste spaziali/quantitative
- Supporto alle tabelle geografiche standard OGC (geometry_columns e spatial_ref_sys)
Memorizzazione dei dati (1/2)
La specifica OpenGIS definisce due modalità standard per rappresentare gli oggetti geometrici:
- WKT (Well-known Text)
- WKB (Well-known Binary)
Entrambe le rappresentazioni includono informazioni relative a tipo dell’oggetto e coordinate.
Esempi di oggetti geometrici in WKT utilizzabili da PostGIS sono i seguenti:
- POINT (0 0)
- LINESTRING (0 0,1 1,1 2)
- 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)
Memorizzazione dei dati (2/2)
Lo stesso standard prevede che il formato interno di memorizzazione debba mantenere anche cognizione del sistema di riferimento in cui sono date le coordinate
PostGIS offre le seguenti interfacce per la manipolazione di oggetti geografici:
- bytea WKB = asBinary(geometry);
- text WKT = asText(geometry);
- geometry = GeomFromWKB(bytea WKB, SRID);
- geometry = GeometryFromText(text WKT, SRID);
L’inserimento di dati in una tabella geo-abilitata deve dunque essere effettuato nella seguente forma:
INSERT INTO geotable ( the_geom, the_name )
VALUES ( GeomFromText(‘POINT (-126.4 45.32)’, 312), ‘A Place’);
PostGIS e gli standard OGC
La specifica “Simple Features Specification for SQL” OGC definisce:
- tipi di oggetti GIS standard
- funzioni per la loro manipolazione
- un insime di tabelle per mantenere metadati
In riferimento all’ultimo punto, lo standard e PostGIS implementano:
- la tabella spatial_ref_sys, che contiene i sistemi di riferimento utilizzabili
- la tabella geometry_columns, che memorizza la lista delle tabelle e delle colonne di tipo geografico. Questa tabella è utilizzata dai GIS standard-compliant per listare i dati disponibili in un dato DB
Creazione di una tabella geospaziale
La creazione di una tabella geospaziale deve essere effettuata in due step:
- aggiunta di una colonna geometrica, mediante la funzione AddGeometryColumn(table_name, column_name, srid, type, dimension):
SELECT AddGeometryColumn(‘public’, ‘roads’, ‘geom’, 423, ‘LINESTRING’, 2);
Caricare dati in PostGIS
L’inserimento di dati in una tabella geospaziale può essere effettuata in due modi differenti:
- mediante normali query di inserimento, utilizzando la funzione PodtGIS GeomFromText(WKT_string)
INSERT INTO roads (road_id, roads_geom, road_name)
VALUES (1,GeomFromText (‘LINESTRING (191232 243118,191108 243242)’,-1),‘Jeff Rd’);
- utilizzando un’utility fornita insieme alla libreria, che converte shapefiles in listati SQL
L’utility shp2pgsql
L’utility shp2pgsql converte automaticamente file in formato ESRI shp in listati SQL compatibili con PostGIS/PostgrSQL. L’uso base del programma è il seguente:
shp2pgsql shapefile schema.tabella > listato.sql
psql -U utente -W -d database -f listato.sql
Segue la spiegazione delle opzioni d’utilizzo più comuni:
-d |
Cancella la tabella dal database prima di ricrearla e popolarla |
-a |
Aggiunge i nuovi dati ad una tabella preesistente |
-c |
Crea la tabella nel DB e la popola (comportamento di default) |
-p |
Crea solo la tabella, senza aggiungere i dati |
-D |
Utilizza il formato binario di dump di PostgreSQL |
-s |
Imposta il SRID della tabella |
Esportare dati da PostGIS
Anche l’esportazione dei dati prevede la doppia modalità:
- attraverso un’utility di dumping
L’utility pgsql2shp
pgsql2shp è un utility di dumping di tabelle geospaziali, che si connette direttamente al DBMS ed esporta i dati nel formato ESRI shp. La sintassi base del comando è la seguente:
pgsql2shp [<options>] <database> [<schema>.]<table>
pgsql2shp [<options>] <database> <query>
Segue una lista delle opzioni più comuni:
-f |
Definisce il nome dello shapefile da esportare |
-h |
Nome Host del server PostgreSQL |
-p |
Porta d’ascolto del server |
-u |
Utente per la connessione |
-p |
Password di connessione |
Ottimizzazioni mediante indici
Come per le normali tabelle, PostgreSQL permette di definire indici sulle colonne geografiche. Questa operazione è necessaria soprattutto nel caso si utilizzino tabelle con un numero molto elevato di tuple, e impatta in maniera significativa sulle performance in fase di interrogazione.
PostgreSQL inplementa i seguenti tipi di indici:
- B-Trees (Alberi binari)
- R-Trees (Alberi rettangolari)
- GiST (Generalized Search Trees)
…ma offre le migliori garanzie con la terza tipologia. La definizione di un indice avviene dunque con la seguente sintassi (SQL Standard):
CREATE INDEX [indexname] ON [tablename] USING GIST ( [geometryfield] );
Funzioni base di PostGIS
Segue una lista delle funzioni base di PostGIS, tra cui:
- Lettura delle geometrie in formato testo
- Valutazione di uguaglianza
- Valutazione di distanze
- Calcolo di lunghezze, aree, perimetri
- Calcolo di centroidi
- Generazione di buffers
- Gestione di SRID
- Riproiezione
WKT
La seguente query restituisce i dati geografici in formato WKT:
SELECT astext (the_geom) FROM geotable;
Uguaglianza
La funzione st_equals() valuta due geometrie e restituisce un true se le stesse sono uguali:
SELECT a.gid, b.gid, st_equals (a.the_geom, b.the_geom)
FROM province1 a, province2 b
WHERE a.gid=b.gid;
Distanza
Per effettuare il calcolo di una distanza tra due geometrie si utilizza invece la funzione st_distance():
SELECT a.gid, b.gid, st_distance (a.the_geom, b.the_geom)
FROM province a, fiumi b
WHERE a.gid=b.gid;
Centroide
PostGIS è in grado di calcolare il baricentro (o centroide) di un poligono mediante la funzione st_centroid():
SELECT st_centroid (the_geom) FROM province;
Area, perimetro, lunghezza
Per il calcolo di aree, perimetri e lunghezze PostGIS implementa le seguenti funzioni:
Buffer
Tra le funzioni di analisi spaziale, spicca la possibilità di creare al volo buffer fissi o variabili, mediante la funzione st_buffer():
Riproiezione al volo
Un’altra caratteristica estremamente utile di PostGIS, è la possibilità di riproiettare al volo un layer vettoriale. È sufficiente utilizzare la funzione st_transform():
SELECT ST_Transform(the_geom, nuovo_srid) from fiumi;
PostGIS reference
Segue una lista di tutte le principali funzioni di PostGIS:
- Funzioni standard OpenGIS:
- Funzioni di gestione
- Funzioni di calcolo delle relazioni tra geometrie
- Funzioni di elaborazione delle geometrie (analisi e processing)
- Funzioni di utilità
- Funzioni per costruire le geometrie
- Estensioni PostGIS:
- Funzioni di misura
- Funzioni di output
- Funzioni di editing delle geometrie
- Funzioni varie
- Operatori tra geometrie
Funzioni di gestione (1/2)
- AddGeometryColumn(varchar, varchar, varchar, integer, varchar, integer). Sintassi: AddGeometryColumn( schema_name, table_name, column_name, srid, type, dimension). Aggiunge una colonna geometrica ad una tabella esistente, e la registra nella tabella OGC geometry_columns. Nota: type è una costante stringa tutta maiuscola, del tipo ‘POLYGON’ o ‘MULTILINESTRING’
- DropGeometryColumn(varchar, varchar, varchar). Sintassi: DropGeometryColumn( schema_name, table_name, column_name). Rimuove una colonna geometrica da una tabella spaziale, e la derergistra dalla tabella OGC geometry_columns
Funzioni di gestione (2/2)
- Probe_Geometry_Columns(): effettua una scansione di tutte le tabelle spaziali del database e aggiunge le colonne geometriche trovate nella tabella OGC geometry_columns.
- ST_SetSRID(geometry, integer): setta il SRID su una geometria (estratta al volo). Utile nella costruzione di geometrie all’interno di query
Relazioni tra geometrie (1/3)
- ST_Distance(geometry, geometry):
Restituisce la distanza cartesiana tra due geometrie, nell’unità di misura della proiezione in uso. Nota: la funzione non fa uso di indici.
- ST_Equals(geometry, geometry):
Restituisce TRUE se le due geometrie passate come argomento sono uguali (a differenza dell’operatore =, che funziona sul box circoscritto, ST_Equals calcola l’eguaglianza su tutti i punti).
Relazioni tra geometrie (2/3)
- ST_Disjoint(geometry, geometry):
Restituisce TRUE se le due geometrie sono disgiunte.
Returns 1 (TRUE) if the Geometries are “spatially disjoint”.
- ST_Intersects(geometry, geometry):
Restituisce TRUE se le due geometrie in argomenrto si intersecano.
- ST_Touches(geometry, geometry):
Restituisce TRUE se le due geometrie in argomenrto si toccano in almeno un punto.
- ST_Crosses(geometry, geometry):
Restituisce TRUE se le due geometrie in argomenrto si intersecano
- ST_Within(geometry A, geometry B):
Restituisce TRUE se A è completamente contenuto in B.
Relazioni tra geometrie (3/3)
- ST_Overlaps(geometry, geometry):
Restituisce TRUE se le due geometrie in argomento sono sovrapposte.
- ST_Contains(geometry A, geometry B):
Restituisce TRUE se A contiene B.
- ST_Covers(geometry A, geometry B):
TRUE se nessun punto di B è all’esterno della geometria A.
- ST_CoveredBy(geometry A, geometry B):
TRUE se nessun punto di A è all’esterno della geometria B.
- ST_Intersects(geometry, geometry):
Ritorna TRUE se le due geometrie in argomento si intersecano.
Funzioni di elaborazione delle geometrie (1/3)
- ST_Centroid(geometry):
Restituisce un punto che rappresenta il centroide (o baricentro) della geometria passata in argomento.
- ST_Area(geometry):
Restituisce l’area della geometria passata, se si tratta di un poligono o multi-poligono, nel sistema di riferimento spaziale associato.
- ST_Length(geometry):
Restituisce la lunghezza della geometria passata, nel sistema di riferimento spaziale associato (sinonimo di lenght2d()).
- ST_PointOnSurface(geometry):
Ritorna un punto casuale appartenente alla superficie della geometria passata in argomento.
Funzioni di elaborazione delle geometrie (2/3)
- ST_Boundary(geometry):
Restituisce la geometria del perimetro (più correttamente i limiti combinatori, come definiti nella sezione 3.12.3.2 della specifica OGC) dell’argomento passato.
- ST_Buffer(geometry, double, [integer]):
Ritorna una geometria che rappresenta l’insieme dei punti per i quali la distanza dalla geometria passata nel primo argomento sia minore o uguale al secondo parametro (espresso nel sistema di riferimento spaziale associato). Il terzo parametro, opzionale, imposta il numero di segmenti usati per approssimare un quarto di circonferenza (di default 8).
- ST_ConvexHull(geometry):
Ritorna la copertura convessa (la geometria minima chiusa e convessa che ricopre interamente una data figura) della geometria in argomento.
- ST_Intersection(geometry, geometry):
Ritorna una geometria data dall’insieme dei punti di A (primo argomento) e B (secondo argomento)
Funzioni di elaborazione delle geometrie (3/3)
- ST_SymDifference(geometry A, geometry B):
Calcola la differenza simmetrica tra le due geometrie passate in argomento, cioè il luogo dei punti di A e B che non si intersecano. L’operazione è detta simmetrica perché ST_Difference(A,B)=ST_Difference(B,A).
- ST_Difference(geometry A, geometry B):
Calcola la differenta tra le due geometrie in argomento (il luogo dei punti di A che non intersecano B).
- ST_Union(geometry A, geometry B):
Restituisce una geometria data dall’insieme dei punti di A e di B.
- ST_Union(geometry set):
Restituisce una geometria data dall’unione di tutti i punti di tutte le geometrie dell’insieme (geometry set) passato in argomento.
- ST_MemUnion(geometry set):
Come la precendente, ma implementata con un algoritmo che limita l’uso della RAM (in generale richiede quindi maggiore tempo di computazione).
Funzioni di utilità (1/5):
- ST_AsText(geometry):
Ritorna la rappresentazione della geometria nel formato WKT.
- ST_AsBinary(geometry):
Ritorna la rappresentazione della geometria nel formato WKB.
- ST_SRID(geometry):
Restituisce l’SRID (Spatial Reference IDentifier) della geometria.
- ST_Dimension(geometry):
Ritorna le dimensioni della geometria in argomento, in generale un numero minore o uguale alle dimensioni del sistema di riferimento (2D, 3DZ, 3DM, 4D). Secondo la specifica OGC, restituisce 0 per punti, 1 per linee e 2 per poligoni, mentre nel caso di oggetti GEOMETRYCOLLECTION la dimensione massima dei componenti.
- ST_Envelope(geometry):
Restituisce una geometria valida (POINT, LINESTRING o POLYGON) che rappresenta il “bounding box” dell’argomento.
Funzioni di utilità (2/5):
- ST_IsEmpty(geometry):
Ritorna TRUE se l’argomento è una geometria vuota (insieme vuoto dei punti).
- ST_IsSimple(geometry):
Ritorna TRUE se la geometria in argomento non presenta anomalie, come auto-intersezioni o punti di tangenza.
- ST_IsClosed(geometry):
Restituisce TRUE se i punti di inizio e fine della geometria in argomento sono coincidenti.
- ST_IsRing(geometry):
Ritorna TRUE se l’argomento è una curva chiusa (StartPoint = EndPoint) e semplice (non passa da uno stesso punto più di una volta).
- ST_NumGeometries(geometry):
Se l’argomento è una GEOMETRYCOLLECTION restituisce il numero di oggetti, altrimenti ritorna NULL.
Funzioni di utilità (3/5):
- ST_GeometryN(geometry,int):
Restituisce l’n-ma geometria se l’argomento è un GEOMETRYCOLLECTION, MULTIPOINT, MULTILINESTRING or MULTIPOLYGON, altrimenti ritorna NULL.
- ST_NumPoints(geometry):
Calcola e restituisce il numero di punti della prima LINESTRING dell’argomento. Se non trova LINESTRING ritorna NULL.
- ST_PointN(geometry,integer):
Ritorna l’n-mo punto nella prima LINESTRING della geometria in argomento.
- ST_ExteriorRing(geometry):
Restituisce l’anello circoscritto (exterior ring) al poligono passato in argomento. Se il parametro non è un poligono ritorna NULL.
- ST_NumInteriorRings(geometry):
Restituisce il numero di anelli inscritti (interior ring) nel primo poligono della geometria.
Funzioni di utilità (4/5):
- ST_NumInteriorRing(geometry):
Sinonimo della precedente (la specifica presenta un’ambiguità, pertanto PostGIS le implementa entrambe).
- ST_InteriorRingN(geometry,integer):
Ritorna l’n-mo anello inscritto nella geometria in argomento (NULL se la stessa non è un poligono).
- ST_EndPoint(geometry):
Restituisce l’ultimo punto della geometria passata in argomento (se è una linestring).
- ST_StartPoint(geometry):
Restituisce il primo punto della geometria passata in argomento (se è una linestring).
- GeometryType(geometry)/ST_GeometryType(geometry):
Restituisce il tipo della geometria passata in argomento, come stringa (Es: ‘LINESTRING’, ‘POLYGON’, ‘MULTIPOINT’, etc.).
Funzioni di utilità (5/5):
- ST_X(geometry):
Ritorna la coordinata X del punto (l’argomento DEVE essere un POINT).
- ST_Y(geometry):
Ritorna la coordinata Y del punto (l’argomento DEVE essere un POINT).
- ST_Z(geometry):
Ritorna la coordinata Z del punto, o NULL se non disponibile (l’argomento DEVE essere un POINT).
- ST_M(geometry):
Ritorna la coordinata M del punto, o NULL se non disponibile (l’argomento DEVE essere un POINT).
Funzioni costruttori di geometrie (1/5)
- ST_GeomFromText(text,[]):
Makes a Geometry from WKT with the given SRID.
- ST_PointFromText(text,[]):
Makes a Geometry from WKT with the given SRID. If SRID is not give, it defaults to -1.
- ST_LineFromText(text,[]):
Makes a Geometry from WKT with the given SRID. If SRID is not give, it defaults to -1.
- ST_LinestringFromText(text,[]):
Makes a Geometry from WKT with the given SRID. If SRID is not give, it defaults to -1.
- ST_PolyFromText(text,[]):
Makes a Geometry from WKT with the given SRID. If SRID is not give, it defaults to -1.
Funzioni costruttori di geometrie (2/5)
- ST_PolygonFromText(text,[]):
Makes a Geometry from WKT with the given SRID. If SRID is not give, it defaults to -1.
- ST_MPointFromText(text,[]):
Makes a Geometry from WKT with the given SRID. If SRID is not give, it defaults to -1.
- ST_MLineFromText(text,[]):
Makes a Geometry from WKT with the given SRID. If SRID is not give, it defaults to -1.
- ST_MPolyFromText(text,[]):
Makes a Geometry from WKT with the given SRID. If SRID is not give, it defaults to -1.
- ST_GeomCollFromText(text,[]):
Makes a Geometry from WKT with the given SRID. If SRID is not give, it defaults to -1.
Funzioni costruttori di geometrie (3/5)
- ST_GeomFromWKB(bytea,[]):
Makes a Geometry from WKB with the given SRID. If SRID is not give, it defaults to -1.
- ST_GeometryFromWKB(bytea,[]):
Makes a Geometry from WKB with the given SRID. If SRID is not give, it defaults to -1.
- ST_PointFromWKB(bytea,[]):
Makes a Geometry from WKB with the given SRID. If SRID is not give, it defaults to -1.
- ST_LineFromWKB(bytea,[]):
Makes a Geometry from WKB with the given SRID. If SRID is not give, it defaults to -1.
- ST_LinestringFromWKB(bytea,[]):
Makes a Geometry from WKB with the given SRID. If SRID is not give, it defaults to -1.
Funzioni costruttori di geometrie (4/5)
- ST_PolyFromWKB(bytea,[]):
Makes a Geometry from WKB with the given SRID. If SRID is not give, it defaults to -1.
- ST_PolygonFromWKB(bytea,[]):
Makes a Geometry from WKB with the given SRID. If SRID is not give, it defaults to -1.
- ST_MPointFromWKB(bytea,[]):
Makes a Geometry from WKB with the given SRID. If SRID is not give, it defaults to -1.
- ST_MLineFromWKB(bytea,[]):
Makes a Geometry from WKB with the given SRID. If SRID is not give, it defaults to -1.
- ST_MPolyFromWKB(bytea,[]):
Makes a Geometry from WKB with the given SRID. If SRID is not give, it defaults to -1.
Funzioni costruttori di geometrie (5/5)
- T_GeomCollFromWKB(bytea,[]):
Makes a Geometry from WKB with the given SRID. If SRID is not give, it defaults to -1.
- ST_BdPolyFromText(text WKT, integer SRID):
Construct a Polygon given an arbitrary collection of closed linestrings as a MultiLineString text representation.
- ST_BdMPolyFromText(text WKT, integer SRID):
Construct a MultiPolygon given an arbitrary collection of closed linestrings as a MultiLineString text representation.
Funzioni di misura (1/3)
- ST_Area(geometry):
Returns the area of the geometry if it is a polygon or multi-polygon.
- ST_distance_sphere(point, point):
Returns linear distance in meters between two lat/lon points. Uses a spherical earth and radius of 6370986 meters. Faster than distance_spheroid(), but less accurate. Only implemented for points.
- ST_distance_spheroid(point, point, spheroid):
Returns linear distance between two lat/lon points given a particular spheroid. See the explanation of spheroids given for length_spheroid(). Currently only implemented for points.
- ST_length2d(geometry):
Returns the 2-dimensional length of the geometry if it is a linestring or multi-linestring.
- ST_length3d(geometry):
Returns the 3-dimensional length of the geometry if it is a linestring or multi-linestring.
Funzioni di misura (2/3)
- ST_length_spheroid(geometry,spheroid):
Calculates the length of of a geometry on an ellipsoid. This is useful if the coordinates of the geometry are in latitude/longitude and a length is desired without reprojection. The ellipsoid is a separate database type and can be constructed as follows:
SPHEROID [NAME,SEMI-MAJORAXIS>,INVERSE_FLATTENING]
-
Eg:
SPHEROID [“GRS_1980”,6378137,298.257222101]
-
An example calculation might look like this:
SELECT length_spheroid (geometry_column,‘SPHEROID[“GRS_1980”,6378137,298.257222101]’)
FROM geometry_table;
Funzioni di misura (3/3)
- ST_length3d_spheroid(geometry,spheroid):
Calculates the length of of a geometry on an ellipsoid, taking the elevation into account. This is just like length_spheroid except vertical coordinates (expressed in the same units as the spheroid axes) are used to calculate the extra distance vertical displacement adds.
- ST_distance(geometry, geometry):
Returns the smaller distance between two geometries.
- ST_max_distance(linestring,linestring):
Returns the largest distance between two line strings.
- ST_perimeter(geometry):
Returns the 2-dimensional perimeter of the geometry, if it is a polygon or multi-polygon.
- ST_perimeter2d(geometry):
Returns the 2-dimensional perimeter of the geometry, if it is a polygon or multi-polygon.
- ST_perimeter3d(geometry):
Returns the 3-dimensional perimeter of the geometry, if it is a polygon or multi-polygon.
- ST_azimuth(geometry, geometry):
Returns the azimuth of the segment defined by the given Point geometries, or NULL if the two points are coincident. Return value is in radians.
Funzioni di output (1/2)
- ST_AsBinary(geometry,{’NDR’|’XDR’}):
Returns the geometry in the OGC “well-known-binary” format as a bytea, using little-endian (NDR) or big-endian (XDR) encoding. This is useful in binary cursors to pull data out of the database without converting it to a string representation.
- ST_AsEWKT(geometry):
Returns a Geometry in EWKT format (as text).
- ST_AsEWKB(geometry, {’NDR’|’XDR’}):
Returns a Geometry in EWKB format (as bytea) using either little-endian (NDR) or big-endian (XDR) encoding.
- ST_AsHEXEWKB(geometry, {’NDR’|’XDR’}):
Returns a Geometry in HEXEWKB format (as text) using either little-endian (NDR) or big-endian (XDR) encoding.
- ST_AsSVG(geometry, [rel], [precision]):
Return the geometry as 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 (“;”).
Funzioni di output (2/2)
- ST_AsGML([version], geometry, [precision]):
Return the geometry as a 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 third argument may be used to reduce the maximum number of significant digits used in output (defaults to 15).
- ST_AsKML([version], geometry, [precision]):
Return the geometry as a KML element. Second argument may be used to reduce the maximum number of significant digits used in output (defaults to 15). Version defaults to 2
- ST_AsGeoJson([version], geometry, [precision], [options]):
Return the geometry as a GeoJson element. (Cf GeoJson specifications 1.0). 2D and 3D Geometries are both supported. GeoJson only support SFS 1.1 geometry type (no curve support for example).
The version parameter, if specified, must be 1.
The third argument may be used to reduce the maximum number of decimal places used in output (defaults to 15).
The last ‘options’ argument could be used to add Bbox or Crs in GeoJSON output:
- 0: means no option (default value)
- 1: GeoJson CRS
- 2: GeoJson Bbox
- 3: Both GeoJson Bbox and CRS
Funzioni di editing delle geometrie (1/6)
- ST_AddBBOX(geometry):
Add bounding box to the geometry. This would make bounding box based queries faster, but will increase the size of the geometry.
- ST_DropBBOX(geometry):
Drop the bounding box cache from the geometry. This reduces geometry size, but makes bounding-box based queries slower.
- ST_AddPoint(linestring, point, []):
Adds a point to a LineString before point (0-based index). Third parameter can be omitted or set to -1 for appending.
- ST_RemovePoint(linestring, offset):
Removes point from a linestring. Offset is 0-based.
- ST_SetPoint(linestring, N, point):
Replace point N of linestring with given point. Index is 0-based.
- ST_Force_collection(geometry):
Converts the geometry into a GEOMETRYCOLLECTION. This is useful for simplifying the WKB representation.
Funzioni di editing delle geometrie (2/6)
- ST_Force_2d(geometry):
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).
- ST_Force_3dz(geometry), ST_Force_3d(geometry):
Forces the geometries into XYZ mode.
- ST_Force_3dm(geometry):
Forces the geometries into XYM mode.
- ST_Force_4d(geometry):
Forces the geometries into XYZM mode.
- ST_Multi(geometry):
Returns the geometry as a MULTI* geometry. If the geometry is already a MULTI*, it is returned unchanged.
Funzioni di editing delle geometrie (3/6)
- ST_Transform(geometry,integer):
Returns a new geometry with its coordinates transformed to the SRID referenced by the integer parameter. The destination SRID must exist in the SPATIAL_REF_SYS table.
Funzioni di editing delle geometrie (4/6)
- ST_Affine(geometry, float8, float8, float8, float8, float8, float8):
Applies an 2d affine transformation to the geometry.
- ST_Translate(geometry, float8, float8, float8):
Translates the geometry to a new location using the numeric parameters as offsets. Ie: translate(geom, X, Y, Z).
- ST_Scale(geometry, float8, float8, float8):
scales the geometry to a new size by multiplying the ordinates with the parameters. Ie: scale(geom, Xfactor, Yfactor, Zfactor).
- ST_RotateZ(geometry, float8), ST_RotateX(geometry, float8), ST_RotateY(geometry, float8):
Rotate the geometry around the Z, X or Y axis by the given angle given in radians. Follows the right-hand rule.
- ST_TransScale(geometry, float8, float8, float8, float8):
First, translates the geometry using the first two floats, then scales it using the second two floats, working in 2D only. Using transscale(geom, X, Y, XFactor, YFactor) internally calls affine(geom, XFactor, 0, 0, 0, YFactor, 0, 0, 0, 1, X*XFactor, Y*YFactor, 0).
Funzioni di editing delle geometrie (5/6)
- ST_Reverse(geometry):
Returns the geometry with vertex order reversed.
- ST_ForceRHR(geometry):
Force polygons of the collection to obey Right-Hand-Rule.
- ST_Simplify(geometry, tolerance):
Returns a “simplified” version of the given geometry using the Douglas-Peuker algorithm. Will actually do something only with (multi)lines and (multi)polygons but you can safely call it with any kind of geometry. Since simplification occurs on a object-by-object basis you can also feed a GeometryCollection to this function. Note that returned geometry might loose its simplicity (see IsSimple)
- ST_SimplifyPreserveTopology(geometry, tolerance):
Returns a “simplified” version of the given geometry using the Douglas-Peuker algorithm. Will avoid creating derived geometries (polygons in particular) that are invalid.
- ST_SnapToGrid(geometry, originX, originY, sizeX, sizeY), ST_SnapToGrid(geometry, sizeX, sizeY), ST_SnapToGrid(geometry, size):
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.
Funzioni di editing delle geometrie (6/6)
- ST_SnapToGrid(geometry, geometry, sizeX, sizeY, sizeZ, sizeM):
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.
- ST_Segmentize(geometry, maxlength):
Return a modified geometry having no segment longer then the given distance. Interpolated points will have Z and M values (if needed) set to 0. Distance computation is performed in 2d only.
- ST_LineMerge(geometry):
Returns a (set of) LineString(s) formed by sewing together constituent linework of input.
Funzioni varie (1/4)
- ST_Summary(geometry):
Returns a text summary of the contents of the geometry.
- ST_box2d(geometry):
Returns a BOX2D representing the maximum extents of the geometry.
- ST_box3d(geometry):
Returns a BOX3D representing the maximum extents of the geometry.
- ST_extent(geometry set):
The extent() function is an “aggregate” function in the terminology of PostgreSQL. That means that it operators on lists of data, in the same way the sum() and mean() functions do. For example, “SELECT EXTENT FROM GEOMTABLE” will return a BOX3D giving the maximum extend of all features in the table. Similarly, “SELECT EXTENT FROM GEOMTABLE GROUP BY CATEGORY” will return one extent result for each category.
- ST_zmflag(geometry):
Returns ZM (dimension semantic) flag of the geometries as a small int. Values are: 0=2d, 1=3dm, 2=3dz, 3=4d.
Funzioni varie (2/4)
- ST_HasBBOX(geometry):
Returns TRUE if the bbox of this geometry is cached, FALSE otherwise. Use addBBOX() and dropBBOX() to control caching.
- ST_ndims(geometry):
Returns number of dimensions of the geometry as a small int. Values are: 2,3 or 4.
- ST_nrings(geometry):
If the geometry is a polygon or multi-polygon returns the number of rings.
- ST_npoints(geometry):
Returns the number of points in the geometry.
- ST_isvalid(geometry):
returns true if this geometry is valid.
Funzioni varie (3/4)
- ST_expand(geometry, float):
This function returns a bounding box expanded in all directions from the bounding box of the input geometry, by an amount specified in the second argument. Very useful for distance() queries, to add an index filter to the query.
- ST_estimated_extent([schema], table, geocolumn):
Return the ‘estimated’ extent of the given spatial table. The estimated is taken from the geometry column’s statistics. The current schema will be used if not specified.
- ST_find_srid(varchar,varchar,varchar):
The syntax is find_srid(<db/schema>,
, ) and the function returns the integer SRID of the specified column by searching through the GEOMETRY_COLUMNS table. If the geometry column has not been properly added with the AddGeometryColumns() function, this function will not work either.
- ST_mem_size(geometry):
Returns the amount of space (in bytes) the geometry takes.
- ST_point_inside_circle(geometry, float, float, float):
The syntax for this functions is point_inside_circle(,,,). Returns the true if the geometry is a point and is inside the circle. Returns false otherwise.
Funzioni varie (4/4)
- ST_XMin(box3d) ST_YMin(box3d) ST_ZMin(box3d):
Returns the requested minima of a bounding box.
- ST_XMax(box3d) ST_YMax(box3d) ST_ZMax(box3d):
Returns the requested maxima of a bounding box.
- ST_Accum(geometry set):
Aggregate. Constructs an array of geometries.
Operatori tra geometrie
A &< B |
The “&<” operator returns true if A’s bounding box overlaps or is to the left of B’s bounding box |
A &> B |
The “&>” operator returns true if A’s bounding box overlaps or is to the right of B’s bounding box |
A << B |
The “<<” operator returns true if A’s bounding box is strictly to the left of B’s bounding box |
A >> B |
The “>>” operator returns true if A’s bounding box is strictly to the right of B’s bounding box |
%A &< |
B% |
The "&< |
" operator returns true if A’s bounding box overlaps or is below B’s bounding box |
**A |
&> B** |
The " |
&>" operator returns true if A’s bounding box overlaps or is above B’s bounding box |
**A << |
B** |
The "<< |
" operator returns true if A’s bounding box is strictly below B’s bounding box |
**A |
>> B** |
The " |
>>" operator returns true if A’s bounding box is strictly above B’s bounding box |
| A ~= B |
The “~=” operator is the “same as” operator. It tests actual geometric equality of two features. So if A and B are the same feature, vertex-by-vertex, the operator returns true |
A @ B |
The “@” operator returns true if A’s bounding box is completely contained by B’s bounding box |
A ~ B |
The “~” operator returns true if A’s bounding box completely contains B’s bounding box |
A && B |
The “&&” operator is the “overlaps” operator. If A’s bounding box overlaps B’s bounding box the operator returns true |
Esercitazione con PostGIS
Note di licenza
Sitografia
Software presentati:
Altre risorse:
Copyright (C) 2008 - Alca Societa' Cooperativa
http://alca.le.it - info@alca.le.it
released under CreativeCommons 2.5 by-nc-sa
NOTA: le immagini dei software e dei device contenuti
nella presentazione sono proprieta' dei relativi detentori
del copyright e sono state riprodotte a scopo esclusivamente didattico.