Manuel PostGIS 2.4.0dev

The PostGIS Development Group

Abstract

PostGIS est une extension du système de base de données relationnel-objet qui permet de stocker des objets SIG (Système d'Information Géographique) dans la base. PostGIS comporte un support des index spatiaux R-Tree basé sur GiST et des fonctions d'analyse et de traitement des objets SIG.

Manuel de la version 2.4.0dev

This work is licensed under a Creative Commons Attribution-Share Alike 3.0 License. Feel free to use this material any way you like, but we ask that you attribute credit to the PostGIS Project and wherever possible, a link back to http://postgis.net.


Table of Contents

1. Introduction
1.1. Comité de direction du projet (Project Steering Committee)
1.2. Core Contributors Present
1.3. Core Contributors Past
1.4. Other Contributors
1.5. Plus d'information
2. Installation de PostGIS
2.1. Version courte
2.2. Install Requirements
2.3. Obtenir les Sources
2.4. Compiling and Install from Source: Detailed
2.4.1. Configuration
2.4.2. Compiler
2.4.3. Compiler les Extensions PostGIS et les déployer
2.4.4. Tests
2.4.5. Installation
2.5. Créer une base de données spatiale en utilisant EXTENSIONS
2.6. Créer une base de données spatiale à partir d'un modèle
2.7. Installing and Using the address standardizer
2.7.1. Installing Regex::Assemble
2.8. Installer, mettre à jour le Géocodeur Tiger et charger des données
2.8.1. Tiger Geocoder Enabling your PostGIS database: Using Extension
2.8.2. Tiger Geocoder Enabling your PostGIS database: Not Using Extensions
2.8.3. Using Address Standardizer Extension with Tiger geocoder
2.8.4. Chargement des données Tiger
2.8.5. Mise à jour de l'installation du Géocodeur Tiger
2.9. Créer une base de données spatiale à partir d'un modèle
2.10. Mise à jour
2.10.1. Mise à jour mineure
2.10.2. Mise à jour majeure
2.11. Common Problems during installation
2.12. Chargeur/Dumper
3. Foire Aux Questions PostGIS
4. Using PostGIS: Data Management and Queries
4.1. GIS Objects
4.1.1. OpenGIS WKB and WKT
4.1.2. PostGIS EWKB, EWKT and Canonical Forms
4.1.3. SQL-MM Part 3
4.2. PostGIS Geography Type
4.2.1. Geography Basics
4.2.2. When to use Geography Data type over Geometry data type
4.2.3. Geography Advanced FAQ
4.3. Using OpenGIS Standards
4.3.1. The SPATIAL_REF_SYS Table and Spatial Reference Systems
4.3.2. The GEOMETRY_COLUMNS VIEW
4.3.3. Creating a Spatial Table
4.3.4. Manually Registering Geometry Columns in geometry_columns
4.3.5. Ensuring OpenGIS compliancy of geometries
4.3.6. Dimensionally Extended 9 Intersection Model (DE-9IM)
4.4. Loading GIS (Vector) Data
4.4.1. Loading Data Using SQL
4.4.2. shp2pgsql: Using the ESRI Shapefile Loader
4.5. Retrieving GIS Data
4.5.1. Using SQL to Retrieve Data
4.5.2. Using the Dumper
4.6. Building Indexes
4.6.1. GiST Indexes
4.6.2. BRIN Indexes
4.6.3. Using Indexes
4.7. Complex Queries
4.7.1. Taking Advantage of Indexes
4.7.2. Examples of Spatial SQL
5. Raster Data Management, Queries, and Applications
5.1. Loading and Creating Rasters
5.1.1. Using raster2pgsql to load rasters
5.1.2. Creating rasters using PostGIS raster functions
5.2. Raster Catalogs
5.2.1. Raster Columns Catalog
5.2.2. Raster Overviews
5.3. Building Custom Applications with PostGIS Raster
5.3.1. PHP Example Outputting using ST_AsPNG in concert with other raster functions
5.3.2. ASP.NET C# Example Outputting using ST_AsPNG in concert with other raster functions
5.3.3. Java console app that outputs raster query as Image file
5.3.4. Use PLPython to dump out images via SQL
5.3.5. Outputting Rasters with PSQL
6. Using PostGIS Geometry: Building Applications
6.1. Utiliser MapServer
6.1.1. Utilisation basique
6.1.2. Questions les plus fréquemment posées
6.1.3. Usage avancé
6.1.4. Exemples
6.2. Clients Java (JDBC)
6.3. C Clients (libpq)
6.3.1. Text Cursors
6.3.2. Binary Cursors
7. Astuces de performances
7.1. Petites tables de grandes géométries
7.1.1. Description du problème
7.1.2. Solutions de contournement
7.2. CLUSTER d'index géométriques
7.3. Eviter les conversions de dimension
7.4. Réglage de votre configuration
7.4.1. Commencement
7.4.2. Runtime
8. Référence PostGIS
8.1. Les types Geometry/Geography/Box de PostgreSQL PostGIS
8.2. Variables PostGIS GUC ( Grand Unified Custom Variables )
8.3. Fonctions de gestion
8.4. Fonctions d'accès aux géométries
8.5. Geometry Editors
8.6. Geometry Outputs
8.7. Opérateurs
8.8. Relations spatiales et mesures
8.9. SFCGAL Functions
8.10. Geometry Processing
8.11. Référencement linéaire
8.12. Temporal Support
8.13. Support des transactions longues
8.14. Fonctions diverses
8.15. Fonctions particulières
9. Raster Reference
9.1. Raster Support Data types
9.2. Raster Management
9.3. Raster Constructors
9.4. Raster Accessors
9.5. Raster Band Accessors
9.6. Raster Pixel Accessors and Setters
9.7. Raster Editors
9.8. Raster Band Editors
9.9. Raster Band Statistics and Analytics
9.10. Raster Outputs
9.11. Raster Processing
9.11.1. Map Algebra
9.11.2. Built-in Map Algebra Callback Functions
9.11.3. DEM (Elevation)
9.11.4. Raster to Geometry
9.12. Raster Operators
9.13. Raster and Raster Band Spatial Relationships
10. Foire Aux Questions PostGIS Raster
11. Topologie
11.1. Les types associés à "Topology"
11.2. Topology Domains
11.3. Topology and TopoGeometry Management
11.4. Topology Constructors
11.5. Topology Editors
11.6. Topology Accessors
11.7. Topology Processing
11.8. TopoGeometry Constructors
11.9. TopoGeometry Editors
11.10. TopoGeometry Accessors
11.11. TopoGeometry Outputs
11.12. Topology Spatial Relationships
12. Address Standardizer
12.1. How the Parser Works
12.2. Address Standardizer Types
12.3. Address Standardizer Tables
12.4. Address Standardizer Functions
13. PostGIS Extras
13.1. Tiger Geocoder
14. PostGIS Special Functions Index
14.1. PostGIS Aggregate Functions
14.2. PostGIS Window Functions
14.3. PostGIS SQL-MM Compliant Functions
14.4. PostGIS Geography Support Functions
14.5. PostGIS Raster Support Functions
14.6. PostGIS Geometry / Geography / Raster Dump Functions
14.7. PostGIS Box Functions
14.8. PostGIS Functions that support 3D
14.9. PostGIS Curved Geometry Support Functions
14.10. PostGIS Polyhedral Surface Support Functions
14.11. PostGIS Function Support Matrix
14.12. New, Enhanced or changed PostGIS Functions
14.12.1. PostGIS Functions new or enhanced in 2.4
14.12.2. PostGIS Functions new or enhanced in 2.3
14.12.3. PostGIS Functions new or enhanced in 2.2
14.12.4. PostGIS functions breaking changes in 2.2
14.12.5. PostGIS Functions new or enhanced in 2.1
14.12.6. PostGIS functions breaking changes in 2.1
14.12.7. PostGIS Functions new, behavior changed, or enhanced in 2.0
14.12.8. PostGIS Functions changed behavior in 2.0
14.12.9. PostGIS Functions new, behavior changed, or enhanced in 1.5
14.12.10. PostGIS Functions new, behavior changed, or enhanced in 1.4
14.12.11. PostGIS Functions new in 1.3
15. Rapporter un problème
15.1. Rapporter un problème logiciel
15.2. Reporting Documentation Issues
A. Annexes
A.1. Version 2.0.1
A.2. Version 2.0.1
A.3. Version 2.0.1
A.4. Release 2.2.0
A.5. Version 2.0.1
A.6. Version 2.0.1
A.7. Version 2.0.1
A.8. Release 2.1.5
A.9. Release 2.1.4
A.10. Release 2.1.3
A.11. Release 2.1.2
A.12. Release 2.1.1
A.13. Release 2.1.0
A.14. Release 2.0.5
A.15. Release 2.0.4
A.16. Release 2.0.3
A.17. Release 2.0.2
A.18. Version 2.0.1
A.19. Release 2.0.0
A.20. Release 1.5.4
A.21. Release 1.5.3
A.22. Release 1.5.2
A.23. Release 1.5.1
A.24. Release 1.5.0
A.25. Release 1.4.0
A.26. Release 1.3.6
A.27. Release 1.3.5
A.28. Release 1.3.4
A.29. Release 1.3.3
A.30. Release 1.3.2
A.31. Release 1.3.1
A.32. Release 1.3.0
A.33. Release 1.2.1
A.34. Release 1.2.0
A.35. Release 1.1.6
A.36. Release 1.1.5
A.37. Release 1.1.4
A.38. Release 1.1.3
A.39. Release 1.1.2
A.40. Release 1.1.1
A.41. Release 1.1.0
A.42. Release 1.0.6
A.43. Release 1.0.5
A.44. Release 1.0.4
A.45. Release 1.0.3
A.46. Release 1.0.2
A.47. Release 1.0.1
A.48. Release 1.0.0
A.49. Release 1.0.0RC6
A.50. Release 1.0.0RC5
A.51. Release 1.0.0RC4
A.52. Release 1.0.0RC3
A.53. Release 1.0.0RC2
A.54. Release 1.0.0RC1

Chapter 1. Introduction

PostGIS a été développé par Refractions Research Inc, en tant que projet de recherche sur les technologies de bases de données spatiales. Refractions est une entreprise de conseil en SIG et bases de données à Victoria, Colombie Britannique, Canada. Elle est spécialisée en intégration de données et développement de logiciels spécifiques. Nous prévoyons de supporter et développer PostGIS pour satisfaire une large gamme de fonctionnalités SIG, tels que le support complet d'OpenGIS, des constructions topologiques avancées (couvertures, surfaces, réseaux), des outils bureautiques pour visualiser et éditer des données SIG, et des outils d'accès web.

PostGIS est un projet officiel de la fondation OSGeo. PostGIS est continuellement amélioré et financé par de nombreux développeurs de logiciels SIG libres, ainsi que par des organisations tout autour du monde qui profite largement de ses fonctionnalités et de sa souplesse d'utilisation.

1.1. Comité de direction du projet (Project Steering Committee)

Le comité de direction du projet (PSC) coordonne la direction générale, les cycles de publication, la documentation et les efforts spécifiques pour le projet PostGIS. De plus, le PSC fournit un support général aux utilisateurs, accepte et approuve les patches de la communauté PostGIS et vote sur divers points concernant PostGIS, tels que les accès commit pour les développeurs, les nouveaux membres du PSC ou les changements majeurs d'API.

Mark Cave-Ayland

Coordination de la correction des bugs et de l'effort de maintenance, alignement des sorties de PostGIS avec celles de PostgreSQL, sélectivité et liaisons des index spatiaux, outil de chargement/export, interface de chargement de shapefiles, intégration de nouvelles fonctions et améliorations de fonctions existantes.

Regina Obe

Maintenance des robots de build, création des builds expérimentaux et stables pour windows, documentation, support général aux utilisateurs sur les newsgroups PostGIS, support X3D, support du géocodeur Tiger, fonctions de gestion, tests des nouvelles fonctionnalités et des changements majeurs du code.

Bborie Park

Raster development, integration with GDAL, raster loader, user support, general bug fixing, testing on various OS (Slackware, Mac, Windows, and more)

Paul Ramsey (Directeur)

Co-founder of PostGIS project. General bug fixing, geography support, geography and geometry index support (2D, 3D, nD index and anything spatial index), underlying geometry internal structures, PointCloud (in development), GEOS functionality integration and alignment with GEOS releases, loader/dumper, and Shapefile GUI loader.

Sandro Santilli

Correction de bugs, mantenance et intégration de nouvelles fonctionnalités de GEOS et alignement de la publication avec les sorties de GEOS, support de la topologie, framework Raster et fonctions bas niveau de l'API.

1.2. Core Contributors Present

Jorge Arévalo

Développement Raster, support du driver GDAL, outil de chargement.

Nicklas Avén

Distance function enhancements (including 3D distance and relationship functions) and additions, Tiny WKB output format (TWKB) (in development) and general user support

Dan Baston

Geometry clustering function additions, other geometry algorithm enhancements, and general user support

Olivier Courtin

Fonctions d'entrée/sortie XML (KML,GML) et fonctions GeoJSON, support 3D et correction de bugs.

Björn Harrtell

MapBox Vector Tile and GeoBuf functions. Gogs testing.

Mateusz Loskot

CMake support for PostGIS, built original raster loader in python and low level raster api functions

Pierre Racine

Architecture générale des raster, prototypage, support à la programmation.

1.3. Core Contributors Past

Chris Hodgson

Ancien membre du PSC. Développement général, maintenance du site et du robot de build, gestion de l'incubation OSGeo.

Kevin Neufeld

Prior PSC Member. Documentation and documentation support tools, buildbot maintenance, advanced user support on PostGIS newsgroup, and PostGIS maintenance function enhancements.

Dave Blasby

Développeur original et co-fondateur de PostGIS. Dave a écrit les objets côté serveur, les liaisons des index, et de nombreuses fonctions d'analyse côté serveur.

Jeff Lounsbury

Développement originel de l'outil de chargement/export de shapefiles. Actuel représentant du projet PostGIS.

Mark Leslie

Maintenance générale et développement de fonctions du noyau PostGIS. Amélioration du support des courbes. Interface graphique de chargement des shapefiles.

David Zwarg

Raster development (mostly map algebra analytic functions)

1.4. Other Contributors

Individual Contributors

In alphabetical order: Alex Bodnaru, Alex Mayrhofer, Andrea Peri, Andreas Forø Tollefsen, Andreas Neumann, Anne Ghisla, Barbara Phillipot, Ben Jubb, Bernhard Reiter, Brian Hamlin, Bruce Rindahl, Bruno Wolff III, Bryce L. Nordgren, Carl Anderson, Charlie Savage, Dane Springmeyer, David Skea, David Techer, Eduin Carrillo, Even Rouault, Frank Warmerdam, George Silva, Gerald Fenoy, Gino Lucrezi, Guillaume Lelarge, IIDA Tetsushi, Ingvild Nystuen, Jason Smith, Jeff Adams, Jose Carlos Martinez Llari, Julien Rouhaud, Kashif Rasul, Klaus Foerster, Kris Jurka, Leo Hsu, Loic Dachary, Luca S. Percich, Maria Arias de Reyna, Mark Sondheim, Markus Schaber, Maxime Guillaud, Maxime van Noppen, Michael Fuhr, Mike Toews, Nathan Wagner, Nathaniel Clay, Nikita Shulga, Norman Vine, Rafal Magda, Ralph Mason, Rémi Cura, Richard Greenwood, Silvio Grosso, Steffen Macke, Stephen Frost, Tom van Tilburg, Vincent Mora, Vincent Picavet

Corporate Sponsors

Certaines organisations ont contribué du temps de développeur, de l'hébergement, ou du financement direct pour le projet PostGIS.

In alphabetical order: Arrival 3D, Associazione Italiana per l'Informazione Geografica Libera (GFOSS.it), AusVet, Avencia, Azavea, Cadcorp, CampToCamp, CartoDB, City of Boston (DND), Clever Elephant Solutions, Cooperativa Alveo, Deimos Space, Faunalia, Geographic Data BC, Hunter Systems Group, Lidwala Consulting Engineers, LisaSoft, Logical Tracking & Tracing International AG, Maponics, Michigan Tech Research Institute, Natural Resources Canada, Norwegian Forest and Landscape Institute, Boundless (former OpenGeo), OSGeo, Oslandia, Palantir Technologies, Paragon Corporation, R3 GIS, Refractions Research, Regione Toscana - SITA, Safe Software, Sirius Corporation plc, Stadt Uster, UC Davis Center for Vectorborne Diseases, University of Laval, U.S Department of State (HIU), Zonar Systems

Campagnes de financement participatif

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 a été la première version où cette stratégie a été testée. Nous avons utilisé PledgeBank et avons eu deux campagnes de financement réussies.

postgistopology - Plus de 10 sponsors ont contribué chacun 250USD pour créer la function toTopoGeometry et sortir le support de la topologie dans la version 2.0.0. Ce fut une réussite.

postgis64windows - 20 someodd sponsors each contributed $100 USD to pay for the work needed to work out PostGIS 64-bit issues on windows. It happened. We now have a 64-bit release for PostGIS 2.0.1 available on PostgreSQL stack builder.

Bibliothèques de base importantes

La bibliothèque d'opérations géométriques GEOS, et le travail algorithmique de Martin Davis pour faire fonctionner tout cela, la maintenance et le support de Mateusz Loskot, Sandro Santilli (strk), Paul Ramsey et d'autres.

La bibliothèque GDAL Geospatial Data Abstraction Library, par Frank Warmerdam et d'autres, est utilisée pour supporter nombre de fonctionnalités raster introduites dans PostGIS 2.0.0. Des améliorations nécessaires dans GDAL pour supporter PostGIS sont aussi remontées en retour dans le projet GDAL.

La bibliothèque Proj4 de gestion de projections cartographiques, travail de Gerald Evenden et Frank Warmerdam pour la créer et la maintenir.

Enfin, mais non des moindres, le projet de SGBD PostgreSQL, géant sur les épaules duquel PostGIS s'appuie. La rapidité et flexibilité de PostGIS serait impossible sans l'extensibilité, le plannificateur de requêtes, les index GiST et les nombreuses fonctionnalités SQL que fournit PostgreSQL.

1.5. Plus d'information

Chapter 2. Installation de PostGIS

Ce chapitre décrit les étapes nécessaires pour installer PostGIS

2.1. Version courte

Pour compiler, assurez-vous que toutes les dépendances soient dans votre chemin de recherche.

tar xvfz postgis-2.4.0dev.tar.gz
cd postgis-2.4.0dev
./configure
make
make install

Une fois PostGIS installé, il est disponible pour chacune des bases de données que vous utilisez.

[Note]

The raster support is currently optional, but installed by default. For enabling using the PostgreSQL 9.1+ extensions model raster is required. Using the extension enable process is preferred and more user-friendly. To spatially enable your database:

psql -d yourdatabase -c "CREATE EXTENSION postgis;"
psql -d yourdatabase -c "CREATE EXTENSION postgis_topology;"
-- if you built with sfcgal support --
psql -d yourdatabase -c "CREATE EXTENSION postgis_sfcgal;"

-- if you want to install tiger geocoder --
psql -d yourdatabase -c "CREATE EXTENSION fuzzystrmatch"
psql -d yourdatabase -c "CREATE EXTENSION postgis_tiger_geocoder;"

-- if you installed with pcre
-- you should have address standardizer extension as well
psql -d yourdatabase -c "CREATE EXTENSION address_standardizer;"

Please refer to Section 2.4.3, “Compiler les Extensions PostGIS et les déployer” for more details about querying installed/available extensions and upgrading extensions, or switching from a non-extension install to an extension install.

For those running who decided for some reason not to compile with raster support, or just are old-fashioned, here are longer more painful instructions for you:

All the .sql files once installed will be installed in share/contrib/postgis-2.3 folder of your PostgreSQL install

createdb yourdatabase
createlang plpgsql yourdatabase
psql -d yourdatabase -f postgis.sql
psql -d yourdatabase -f postgis_comments.sql
psql -d yourdatabase -f spatial_ref_sys.sql
psql -d yourdatabase -f topology.sql
psql -d yourdatabase -f topology_comments.sql

-- only if you compiled with raster (GDAL)
psql -d yourdatabase -f rtpostgis.sql
psql -d yourdatabase -f raster_comments.sql

--if you built with sfcgal support --
psql -d yourdatabase -f sfcgal.sql
psql -d yourdatabase -f sfcgal_comments.sql

La suite de ce chapitre détaille chacune des étapes d'installation présentées ci-avant

As of PostGIS 2.1.3, out-of-db rasters and all raster drivers are disabled by default. In order to re-enable these, you need to set the following environment variables POSTGIS_GDAL_ENABLED_DRIVERS and POSTGIS_ENABLE_OUTDB_RASTERS in the server environment. For PostGIS 2.2, you can use the more cross-platform approach of setting the corresponding Section 8.2, “Variables PostGIS GUC ( Grand Unified Custom Variables )”.

If you want to enable offline raster:

POSTGIS_ENABLE_OUTDB_RASTERS=1

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

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

POSTGIS_GDAL_ENABLED_DRIVERS=ENABLE_ALL

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

POSTGIS_GDAL_ENABLED_DRIVERS="GTiff PNG JPEG GIF XYZ"
[Note]

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

Setting environment variables varies depending on OS. For PostgreSQL installed on Ubuntu or Debian via apt-postgresql, the preferred way is to edit /etc/postgresql/9.3/main/environment where 9.3 refers to version of PostgreSQL and main refers to the cluster.

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

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

2.2. Install Requirements

La compilation et la manipulation de PostGIS requièrent les éléments suivant:

Obligatoire

  • PostgreSQL 9.3 ou supérieure. Une installation complete de PostgreSQL (incluant les fichiers header du serveur) nécessaire. PostgreSQL est disponible depuis le site http://www.postgresql.org .

    Pour la liste complète des exigences concernant PostgreSQL / PostGIS et PostGIS/GEOS, veuillez vous référer à http://trac.osgeo.org/postgis/wiki/UsersWikiPostgreSQLPostGIS

  • Un compilateur GNUC C (gcc). D'autres compilateurs ANSI C peuvent être utilisés, mais la compilation avec gcc est source de moins de problèmes

  • GNU Make (gmake ou make). Sur beaucoup de systemes, GNU make est la version par défaut de make. Vous pouvez vérifier la version de make avec la commande make -v. D'autres versions de make peuvent ne pas être compatibles avec le Makefile de PostGIS.

  • La bibliothèque de reprojection Proj4, version 4.6.0 ou supérieure. La bibliothèque Proj4 est utilisée pour le support des projections dans PostGIS. Pro4 est disponible depuis le site http://trac.osgeo.org/proj/

  • GEOS geometry library, version 3.3 or greater, but GEOS 3.5+ is recommended to take full advantage of all the new functions and features. Without GEOS 3.5, you will be missing some major enhancements such as ST_ClipByBox2D and ST_Subdivide. GEOS is available for download from http://trac.osgeo.org/geos/ and 3.4+ is backward-compatible with older versions so fairly safe to upgrade.

  • LibXML2, version 2.5.x ou supérieure. LibXML2 est utilisée dans certaines fonctions d'import (ST_GeomFromGML and ST_GeomFromKML). LibXML2 est disponible depuis http://xmlsoft.org/downloads.html.

  • JSON-C, version 0.9 or higher. JSON-C is currently used to import GeoJSON via the function ST_GeomFromGeoJson. JSON-C is available for download from https://github.com/json-c/json-c/releases/.

  • GDAL, version 1.8 or higher (1.9 or higher is strongly recommended since some things will not work well or behavior differently with lower versions). This is required for raster support and to be able to install with CREATE EXTENSION postgis so highly recommended for those running 9.1+. http://trac.osgeo.org/gdal/wiki/DownloadSource.

Optionnel

  • GDAL (pseudo optional) only if you don't want raster and don't care about installing with CREATE EXTENSION postgis can you leave it out. Keep in mind other extensions may have a requires postgis extension which will prevent you from installing them unless you install postgis as an extension. So it is highly recommended you compile with GDAL support.

    Also make sure to enable the drivers you want to use as described in Section 2.1, “Version courte”.

  • GTK (GTK+2.0, 2.8+) pour compiler le chargeur de shape file shp2pgsql-gui. http://www.gtk.org/ .

  • SFCGAL, version 1.1 (or higher) could be used to provide additional 2D and 3D advanced analysis functions to PostGIS cf Section 8.9, “SFCGAL Functions”. And also allow to use SFCGAL rather than GEOS for some 2D functions provided by both backends (like ST_Intersection or ST_Area, for instance). A PostgreSQL configuration variable postgis.backend allow end user to control which backend he want to use if SFCGAL is installed (GEOS by default). Nota: SFCGAL 1.2 require at least CGAL 4.3 and Boost 1.54 (cf: http://oslandia.github.io/SFCGAL/installation.html) https://github.com/Oslandia/SFCGAL.

  • In order to build the Chapter 12, Address Standardizer you will also need PCRE http://www.pcre.org (which generally is already installed on nix systems). Regex::Assemble perl CPAN package is only needed if you want to rebuild the data encoded in parseaddress-stcities.h. Chapter 12, Address Standardizer will automatically be built if it detects a PCRE library, or you pass in a valid --with-pcre-dir=/path/to/pcre during configure.

  • To enable ST_AsMVT protobuf-c library (for usage) and the protoc-c compiler (for building) are required. Also, pgk-config is required to verify the correct minimum version of protobuf-c. See protobuf-c.

  • CUnit (CUnit). Nécessaire pour les tests de régression. http://cunit.sourceforge.net/

  • DocBook (xsltproc) est nécessaire pour générer la documentation. Docbook est disponible depuis le site http://www.docbook.org/ .

  • DBLatex (dblatex) est nécessaire pour générer la documentation au format PDF. DBLatex est disponible depuis http://dblatex.sourceforge.net/ .

  • ImageMagick (convert) est nécessaire pour générer les images de la documentation. ImageMagick is available from http://www.imagemagick.org/ .

2.3. Obtenir les Sources

Les sources de PostGIS sont disponible depuis http://postgis.net/stuff/postgis-2.4.0dev.tar.gz

wget http://postgis.net/stuff/postgis-2.4.0dev.tar.gz
tar -xvzf postgis-2.4.0dev.tar.gz

Un répertoire appelé postgis-2.4.0dev sera créé dans le répertoire courant

Les sources peuvent également être obtenues depuis le dépôt svn http://svn.osgeo.org/postgis/trunk/ .

svn checkout http://svn.osgeo.org/postgis/trunk/ postgis-2.4.0dev

Se placer dans le nouveau répertoire créé postgis-2.4.0dev pour poursuivre l'installation

2.4. Compiling and Install from Source: Detailed

[Note]

La plupart des systèmes d'exploitation dispose de paquets pré-compilés de PostgreSQL/PostGIS. La compilation est réellement nécessaire uniquement pour disposer des toutes dernières fonctionnalités ou pour les responsables de paquets PostGIS

Cette section présente les instructions générales pour compiler PostGIS. Si la compilation s'effectue sous Windows ou un autre système d'exploitation, des informations complémentaires sont disponibles depuis PostGIS User contributed compile guides and PostGIS Dev Wiki.

Les paquets pré compilés pour différents systèmes d'exploitation sont listés dans PostGIS Pre-built Packages

Pour les utilisateurs Windows, des versions stables sont disponibles par Stackbuilder ou PostGIS Windows download site. Des compilations expérimentales incluant les dernières fonctionnalités sont disponibles depuis very bleeding-edge windows experimental builds. Ces compilations sont généralements mises à jour toutes les unes ou deux semaines, ou chaque fois qu'une nouvelle fonctionnalité intéressante est ajoutée. Vous pouvez les utiliser pour suivre l'avancée des versions de PostGIS

Le module PostGIS est une extension du serveur PostgreSQL. A ce titre, PostGIS 2.4.0dev nécessite l'accès complet aux en-têtes du serveur PostgreSQL afin de pouvoir compiler. Il peut être compilé à partir de la version versions 9.3 de PostgreSQL ou supérieure. Les versions plus anciennes de PostgreSQL ne sont pas supportées.

Référez-vous aux guides d'installation de PostgreSQL si vous n'avez pas déjà installé PostgreSQL. http://www.postgresql.org .

[Note]

Pour les fonctionnalités de de GEOS, quand vous installez PostgreSQL, vous aurez peut-être besoin de lier explicitement PostgreSQL avec la bibliothèque standard C++:

LDFLAGS=-lstdc++ ./configure [Vos options à la suite]

Ceci est une solution de contournement d'exceptions C++ d'interactions bugués dans des outils de développements plus ancien. Si vous tombez sur ce genre de problèmes (backend soudainement fermé ou des choses similaires) essayez cette astuce. Cela nécessite de recompiler votre PostgreSQL du début, bien sur.

Les étapes suivantes résument la configuration et la compilation des sources PostGIS. Elles ont été rédigées pour les utilisateurs sous Linux et ne fonctionneront pas pour Windows et Mac.

2.4.1. Configuration

Comme pour la plupart des installations linux, la première étape est de générer le Makefile qui sera utilisé pour compiler le code source. Ceci est réalisée en lançant le script shell

./configure

Sans paramètre supplémentaire, cette commande tentera de localiser automatiquement les composants requis et les bibliothèques nécessaires à la compilation de PostGIS. Bien que cela soit l'utilisation la plus commune de la commande ./configure, vous pouvez également ajouter différents paramètres à ce script. Par exemple, vous pouvez définir l'emplacement de bibliothèques ou de programmes si ceux-ci ne sont pas localisés à un emplacement standard.

La liste suivante présente les options les plus courantes. Pour consulter la liste complète utilisez l'option --help ou --help=short.

--prefix=PREFIX

Cela correspond à l'emplacement où les bibliothèques et les scripts SQL de PostGIS seront installés. Par défaut, cet emplacement est le même que celui de l'installation de PostgreSQL.

[Caution]

Ce paramètre est actuellement défectueux: le paquet s'installe uniquement dans le répertoire d'installation de PostgreSQL. Le suivu de ce bug est disponible depuis http://trac.osgeo.org/postgis/ticket/635

--with-pgconfig=FILE

PostgreSQL fournit l'utilitaire pg_config permettant aux extensions comme PostGIS de localiser le répertoire d'installation de PostgreSQL. Utiliser ce paramètre (--with-pgconfig=/path/to/pg_config) pour spécifier une installation particulière de PostgreSQL pour laquelle PostGIS doit être compilée.

--with-gdalconfig=FILE

GDAL, une des bibliothèques requises pour le support des rasters. gdal-config pour permettre au logiciel de localiser le répertoire d'installation de GDAL. Utiliser ce paramètre (--with-gdalconfig=/path/to/gdal-config) pour spécifier un répertoire d'installation particulier de GDAL qui sera utilisé pour compiler PostGIS.

--with-geosconfig=FILE

GEOS, une des bibliothèques requises, fournit un utilitaire appelé geos-config permettant aux logiciels de localiser le répertoire d'installation de GEOS. Utiliser ce paramètre (--with-geosconfig=/path/to/geos-config) pour spécifier le repertoire de GEOS qui sera utilisé pour la compilation de PostGIS.

--with-xml2config=FILE

LibXML est la bibliothèque requise pour les traitements GML/KML. Elle est normalement auto détectée en cas d'installation normale. Utiliser ce paramètre ( >--with-xml2config=/path/to/xml2-config) pour spécifier le repertoire de LibXML qui sera utilisé pour la compilation de PostGIS.

--with-projdir=DIR

Proj4 est la bibliothèque de reprojection nécessaire à PostGIS. Utiliser ce paramètre (--with-projdir=/path/to/projdir) pour spécifier le repertoire de LibXML qui sera utilisé pour la compilation de PostGIS.

--with-libiconv=DIR

Répertoire d'installation d'iconv

--with-jsondir=DIR

JSON-C est une bibliothèque sous licence MIT utilisée par PostGIS pour les traitements JSON (ST_GeomFromJSON par exemple). Utiliser ce paramètre (--with-jsondir=/path/to/jsondir) pour spécifier le répertoire de JSON-C qui sera utilisé pour la compilation de PostGIS.

--with-pcredir=DIR

PCRE is an BSD-licensed Perl Compatible Regular Expression library required by address_standardizer extension. Use this parameter (--with-pcredir=/path/to/pcredir) to manually specify a particular PCRE installation directory that PostGIS will build against.

--with-gui

Compile l'interface graphique d'import de données (nécessite GTK+2.0). Ceci créé l'interface graphique shp2pgsql-gui à shp2pgsql.

--with-raster

Compilation avec support des raster. Produit la bibliothèque rtpostgis-2.4.0dev et le fichier rtpostgis.sql. Les versions futures doivent à terme inclure le support des rasters par défaut.

--without-topology

Compilation avec support de la topologie. Produit le fichier topology.sql. Il n'y a pas de bibliothèque correspondante: toute la logique nécessaire à la topologie est incluse dans la bibliothèque postgis-2.4.0dev

--with-gettext=no

Par défaut PostGIS tentera de détecter la gestion de gettext et de reposer dessus pour la compilation, cependant si vous tombez sur des problèmes d'incompatibilités qui cause la cassure du chargeur, vous pouvez le désactiver entièrement avec cette commande. Référez vous au ticket http://trac.osgeo.org/postgis/ticket/748 pour un exemple de problème résolu par cette configuration. NOTE : que vous perdez beaucoup de chose en le désactivant. Cela est utilisé pour la gestion de l'aide et des labels internationaux dans le chargeur graphique qui n'est pas documenté et encore expérimental.

--with-sfcgal=PATH

By default PostGIS will not install with sfcgal support without this switch. PATH is an optional argument that allows to specify an alternate PATH to sfcgal-config.

[Note]

Si vous avez téléchargé PostGIS depuis le dépôt SVN , la première étape est d'exécuter le script.

./autogen.sh

Ce script générera le script configure qui est utilisé pour personnaliser votre installation de PostGIS.

Si vous avez obtenu PostGIS comme archive, lancer la commande ./autogen.sh n'est pas nécessaire puisque configure a déjà été généré.

2.4.2. Compiler

Une fois le Makefile généré, compiler PostGIS est aussi simple que lancer

make

La dernière ligne de la sortie doit être "PostGIS was built successfully. Ready to install."

À partir de PostGIS v1.4.0, toutes les fonctions ont des commentaires générés à partir de la documentation. Si vous désirez installer ces commentaires dans votre base de données spatiales plus tard, lancez la commande qui nécessite docbook. Le fichier postgis_comments.sql et les autres groupes de fichiers de commentaires raster_comments.sql, topology_comments.sql sont aussi packagés dans la distribution tar.gz dans le répertoire doc par conséquent pas besoin de créer les commentaires si vous installez à partir des archives.

make comments

Introduit dans PostGIS 2.0. Cela génère un mémo en html disponible pour une référence rapide ou pour les étudiants. La compilation nécessite xsltproc et génèrera 4 fichiers dans le répertoire doc topology_cheatsheet.html, tiger_geocoder_cheatsheet.html, raster_cheatsheet.html, postgis_cheatsheet.html

Vous pouvez télécharger des pré-compilations disponibles en HTML et PDF à partir de PostGIS / PostgreSQL Study Guides

make cheatsheets

2.4.3. Compiler les Extensions PostGIS et les déployer

Les extensions PostGIS sont compilées et installées automatiquement si vous utilisez PostgreSQL 9.1+

Si vous compilez à partir des dépôts des sources, vous devez compiler les descriptions de fonction d'abord. Ceci est compilé si vous avez docbook installé. Vous pouvez également compiler manuellement avec cette commande :

make comments

Compiler les commentaires n'est pas nécessaire si vous avez compilé à partir d'une release d'archive puisque ceux-ci sont des pré-compilations packagés avec le tar ball.

Si vous compilez avec PostgreSQL 9.1, les extensions doivent être automatiquement compilées comme part du processus make install. Vous pouvez, si nécessaire, compilé à partir des répertoires d'extensions ou copier les fichiers si vous en avez besoin sur un serveur différent.

cd extensions
cd postgis
make clean
make
make install
cd ..
cd postgis_topology
make clean
make
make install
cd ..
cd postgis_sfcgal
make clean
make
make install

cd ..
cd address_standardizer
make clean
make
make install
make installcheck

cd ..
cd postgis_tiger_geocoder
make clean
make
make install
make installcheck
          

Les fichiers extensions seront toujours les mêmes pour les mêmes version de PostGIS indépendamment de l'OS, par conséquent il n'y a pas de problème à copier les fichiers extensions d'un OS à un autre du moment que vous avez les binaires PostGIS déjà installés sur vos serveurs.

Si vous voulez installer les extensions manuellement sur un serveur différent séparé de votre développement, vous devez copier les fichiers suivants à partir du répertoire extension dans le répertoire PostgreSQL / share / extension de votre installation PostgreSQL ainsi que les binaires nécessaires pour une version correcte de PostGIS si vous ne les avez pas déjà sur le serveur.

  • Ceux-ci sont les fichiers de contrôle qui renvoie les informations telles que la version de l'extension à installer si non spécifié. postgis.control, postgis_topology.control.

  • Tous les fichiers dans le répertoire /sql de chaque extension. Notez que ceux-ci nécessitent d'être copiées à la racine du répertoire share/extension de PostgreSQL

Une fois fait, vous devez voir postgis, postgis_topology comme extensions disponibles dans PgAdmin -> extensions.

Si vous utilisez psql, vous pouvez vérifier que les extensions sont installées en lançant cette requête :

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         | 2.4.0dev         | 2.4.0dev
 address_standardizer_data_us | 2.4.0dev         | 2.4.0dev
 postgis                      | 2.4.0dev         | 2.4.0dev
 postgis_sfcgal               | 2.4.0dev         |
 postgis_tiger_geocoder       | 2.4.0dev         | 2.4.0dev
 postgis_topology             | 2.4.0dev         |
(6 rows)

Si vous avez l'extension installée dans la base de données que vous interrogez, vous verrez la mention dans la colonne installed_version. Si vous n'obtenez aucun enregistrement , cela signifie que vous n'avez pas d'extension postgis installés sur le serveur. PgAdmin III 1.14+ fournira aussi cette information dans la section extensions dans l'arbre de l'explorateur de la base de données et autorisera même la mise à jour ou la désinstallation par clic-droit.

Si vous avez les extensions disponibles, vous pouvez installer les extensions postgis dans votre base de données de votre choix soit en utilisant l'interface d'extension de PgAdmin ou lançant ces commandes SQL :

CREATE EXTENSION postgis;
CREATE EXTENSION postgis_sfcgal;
CREATE EXTENSION fuzzystrmatch; --needed for postgis_tiger_geocoder
--optional used by postgis_tiger_geocoder, or can be used standalone
CREATE EXTENSION address_standardizer;
CREATE EXTENSION address_standardizer_data_us;
CREATE EXTENSION postgis_tiger_geocoder;
CREATE EXTENSION postgis_topology;

In psql you can use to see what versions you have installed and also what schema they are installed.

\connect mygisdb
\x 
\dx postgis*
List of installed extensions
-[ RECORD 1 ]-------------------------------------------------
-
Name        | postgis
Version     | 2.4.0dev
Schema      | public
Description | PostGIS geometry, geography, and raster spat..
-[ RECORD 2 ]-------------------------------------------------
-
Name        | postgis_tiger_geocoder
Version     | 2.4.0dev
Schema      | tiger
Description | PostGIS tiger geocoder and reverse geocoder
-[ RECORD 3 ]-------------------------------------------------
-
Name        | postgis_topology
Version     | 2.4.0dev
Schema      | topology
Description | PostGIS topology spatial types and functions
[Warning]

Les tables d'extension spatial_ref_sys, layer, topology ne peuvent pas être explicitement sauvegardé. Elles peuvent être uniquement sauvegardées quand les extensions respectives postgis ou postgis_topology sont sauvegardées, ce qui semblent seulement arrivé quand vous sauvegardez l'ensemble de la base. À partir de PostGIS 2.0.1, seulement les enregistrements des srid non packagés avec PostGIS sont sauvegardés quand la base de données est sauvegardé par conséquent ne changez pas les srids que nous fournissons et attendre que vos modifications seront encore là. Créez un ticket si vous trouvez un problème. Les structures de la table d'extension ne sont jamais sauvegardées puisque créée avec CREATE EXTENSION et supposées être identique pour la même version de l'extension. Ce comportement fait partie du modèle actuel d'extensions de PostgreSQL, nous pouvons donc rien faire à ce sujet.

If you installed 2.4.0dev, without using our wonderful extension system, you can change it to be extension based by first upgrading to the latest micro version running the upgrade scripts: postgis_upgrade_22_minor.sql,raster_upgrade_22_minor.sql,topology_upgrade_22_minor.sql.

Si vous installez postgis sans la gestion du raster, vous aurez besoin d'installer la gestion du raster (en utilisant le script rtpostgis.sql complet

Puis vous pouvez lancer les commandes ci-dessous pour packager les fonctions dans leur extension respective.

CREATE EXTENSION postgis FROM unpackaged;
CREATE EXTENSION postgis_topology FROM unpackaged;
CREATE EXTENSION postgis_tiger_geocoder FROM unpackaged;

2.4.4. Tests

Si vous désirez tester la compilation de PostGIS, lancez

make check

La commande ci-dessus fonctionnera pour différentes tests de vérification et de régression en utilisant la bibliothèque générée selon la base de données actuelle.

[Note]

Si vous configurez PostGIS en utilisant une localisation non standard de PostgreSQL, GEOS, ou Proj4, vous pourrez avoir besoin d'ajouter la localisation des bibliothèques à la variable d'environnement LD_LIBRARY_PATH.

[Caution]

Pour le moment, make check repose sur les variables d'environnement PATH et PGPORT lors de la réalisation des vérifications - il n'utilise pas la version de PostgreSQL qui a pu être définie en utilisant la paramètre configuration --with-pgconfig. Assurez vous donc de modifier votre PATH pour correspondre l'installation de PostgreSQL détectée durant la configuration ou préparez vous à gérer des maux de tête inhérent.

Si fructueux; la sortie du test doit être similaire à ceci :

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


Suite: computational_geometry
  Test: test_lw_segment_side ...passed
  Test: test_lw_segment_intersects ...passed
  Test: test_lwline_crossing_short_lines ...passed
  Test: test_lwline_crossing_long_lines ...passed
  Test: test_lwline_crossing_bugs ...passed
  Test: test_lwpoint_set_ordinate ...passed
  Test: test_lwpoint_get_ordinate ...passed
  Test: test_point_interpolate ...passed
  Test: test_lwline_clip ...passed
  Test: test_lwline_clip_big ...passed
  Test: test_lwmline_clip ...passed
  Test: test_geohash_point ...passed
  Test: test_geohash_precision ...passed
  Test: test_geohash ...passed
  Test: test_geohash_point_as_int ...passed
  Test: test_isclosed ...passed
  Test: test_lwgeom_simplify ...passed
Suite: buildarea
  Test: buildarea1 ...passed
  Test: buildarea2 ...passed
  Test: buildarea3 ...passed
  Test: buildarea4 ...passed
  Test: buildarea4b ...passed
  Test: buildarea5 ...passed
  Test: buildarea6 ...passed
  Test: buildarea7 ...passed
Suite: geometry_clean
  Test: test_lwgeom_make_valid ...passed
Suite: clip_by_rectangle
  Test: test_lwgeom_clip_by_rect ...passed
Suite: force_sfs
  Test: test_sfs_11 ...passed
  Test: test_sfs_12 ...passed
  Test: test_sqlmm ...passed
Suite: geodetic
  Test: test_sphere_direction ...passed
  Test: test_sphere_project ...passed
  Test: test_lwgeom_area_sphere ...passed
  Test: test_signum ...passed
  Test: test_gbox_from_spherical_coordinates ...passed
  Test: test_gserialized_get_gbox_geocentric ...passed
  Test: test_clairaut ...passed
  Test: test_edge_intersection ...passed
  Test: test_edge_intersects ...passed
  Test: test_edge_distance_to_point ...passed
  Test: test_edge_distance_to_edge ...passed
  Test: test_lwgeom_distance_sphere ...passed
  Test: test_lwgeom_check_geodetic ...passed
  Test: test_gserialized_from_lwgeom ...passed
  Test: test_spheroid_distance ...passed
  Test: test_spheroid_area ...passed
  Test: test_lwpoly_covers_point2d ...passed
  Test: test_gbox_utils ...passed
  Test: test_vector_angle ...passed
  Test: test_vector_rotate ...passed
  Test: test_lwgeom_segmentize_sphere ...passed
  Test: test_ptarray_contains_point_sphere ...passed
  Test: test_ptarray_contains_point_sphere_iowa ...passed
Suite: GEOS
  Test: test_geos_noop ...passed
  Test: test_geos_subdivide ...passed
  Test: test_geos_linemerge ...passed
Suite: Clustering
  Test: basic_test ...passed
  Test: nonsequential_test ...passed
  Test: basic_distance_test ...passed
  Test: single_input_test ...passed
  Test: empty_inputs_test ...passed
Suite: Clustering Union-Find
  Test: test_unionfind_create ...passed
  Test: test_unionfind_union ...passed
  Test: test_unionfind_ordered_by_cluster ...passed
Suite: homogenize
  Test: test_coll_point ...passed
  Test: test_coll_line ...passed
  Test: test_coll_poly ...passed
  Test: test_coll_coll ...passed
  Test: test_geom ...passed
  Test: test_coll_curve ...passed
Suite: encoded_polyline_input
  Test: in_encoded_polyline_test_geoms ...passed
  Test: in_encoded_polyline_test_precision ...passed
Suite: geojson_input
  Test: in_geojson_test_srid ...passed
  Test: in_geojson_test_bbox ...passed
  Test: in_geojson_test_geoms ...passed
Suite: twkb_input
  Test: test_twkb_in_point ...passed
  Test: test_twkb_in_linestring ...passed
  Test: test_twkb_in_polygon ...passed
  Test: test_twkb_in_multipoint ...passed
  Test: test_twkb_in_multilinestring ...passed
  Test: test_twkb_in_multipolygon ...passed
  Test: test_twkb_in_collection ...passed
  Test: test_twkb_in_precision ...passed
Suite: serialization/deserialization
  Test: test_typmod_macros ...passed
  Test: test_flags_macros ...passed
  Test: test_serialized_srid ...passed
  Test: test_gserialized_from_lwgeom_size ...passed
  Test: test_gbox_serialized_size ...passed
  Test: test_lwgeom_from_gserialized ...passed
  Test: test_lwgeom_count_vertices ...passed
  Test: test_on_gser_lwgeom_count_vertices ...passed
  Test: test_geometry_type_from_string ...passed
  Test: test_lwcollection_extract ...passed
  Test: test_lwgeom_free ...passed
  Test: test_lwgeom_flip_coordinates ...passed
  Test: test_f2d ...passed
  Test: test_lwgeom_clone ...passed
  Test: test_lwgeom_force_clockwise ...passed
  Test: test_lwgeom_calculate_gbox ...passed
  Test: test_lwgeom_is_empty ...passed
  Test: test_lwgeom_same ...passed
  Test: test_lwline_from_lwmpoint ...passed
  Test: test_lwgeom_as_curve ...passed
  Test: test_lwgeom_scale ...passed
  Test: test_gserialized_is_empty ...passed
  Test: test_gbox_same_2d ...passed
Suite: measures
  Test: test_mindistance2d_tolerance ...passed
  Test: test_rect_tree_contains_point ...passed
  Test: test_rect_tree_intersects_tree ...passed
  Test: test_lwgeom_segmentize2d ...passed
  Test: test_lwgeom_locate_along ...passed
  Test: test_lw_dist2d_pt_arc ...passed
  Test: test_lw_dist2d_seg_arc ...passed
  Test: test_lw_dist2d_arc_arc ...passed
  Test: test_lw_arc_length ...passed
  Test: test_lw_dist2d_pt_ptarrayarc ...passed
  Test: test_lw_dist2d_ptarray_ptarrayarc ...passed
  Test: test_lwgeom_tcpa ...passed
  Test: test_lwgeom_is_trajectory ...passed
Suite: effectivearea
  Test: do_test_lwgeom_effectivearea_lines ...passed
  Test: do_test_lwgeom_effectivearea_polys ...passed
Suite: miscellaneous
  Test: test_misc_force_2d ...passed
  Test: test_misc_simplify ...passed
  Test: test_misc_count_vertices ...passed
  Test: test_misc_area ...passed
  Test: test_misc_wkb ...passed
  Test: test_grid ...passed
Suite: noding
  Test: test_lwgeom_node ...passed
Suite: encoded_polyline_output
  Test: out_encoded_polyline_test_geoms ...passed
  Test: out_encoded_polyline_test_srid ...passed
  Test: out_encoded_polyline_test_precision ...passed
Suite: geojson_output
  Test: out_geojson_test_precision ...passed
  Test: out_geojson_test_dims ...passed
  Test: out_geojson_test_srid ...passed
  Test: out_geojson_test_bbox ...passed
  Test: out_geojson_test_geoms ...passed
Suite: gml_output
  Test: out_gml_test_precision ...passed
  Test: out_gml_test_srid ...passed
  Test: out_gml_test_dims ...passed
  Test: out_gml_test_geodetic ...passed
  Test: out_gml_test_geoms ...passed
  Test: out_gml_test_geoms_prefix ...passed
  Test: out_gml_test_geoms_nodims ...passed
  Test: out_gml2_extent ...passed
  Test: out_gml3_extent ...passed
Suite: kml_output
  Test: out_kml_test_precision ...passed
  Test: out_kml_test_dims ...passed
  Test: out_kml_test_geoms ...passed
  Test: out_kml_test_prefix ...passed
Suite: svg_output
  Test: out_svg_test_precision ...passed
  Test: out_svg_test_dims ...passed
  Test: out_svg_test_relative ...passed
  Test: out_svg_test_geoms ...passed
  Test: out_svg_test_srid ...passed
Suite: x3d_output
  Test: out_x3d3_test_precision ...passed
  Test: out_x3d3_test_geoms ...passed
  Test: out_x3d3_test_option ...passed
Suite: ptarray
  Test: test_ptarray_append_point ...passed
  Test: test_ptarray_append_ptarray ...passed
  Test: test_ptarray_locate_point ...passed
  Test: test_ptarray_isccw ...passed
  Test: test_ptarray_signed_area ...passed
  Test: test_ptarray_unstroke ...passed
  Test: test_ptarray_insert_point ...passed
  Test: test_ptarray_contains_point ...passed
  Test: test_ptarrayarc_contains_point ...passed
  Test: test_ptarray_scale ...passed
Suite: printing
  Test: test_lwprint_default_format ...passed
  Test: test_lwprint_format_orders ...passed
  Test: test_lwprint_optional_format ...passed
  Test: test_lwprint_oddball_formats ...passed
  Test: test_lwprint_bad_formats ...passed
Suite: SFCGAL
  Test: test_sfcgal_noop ...passed
Suite: split
  Test: test_lwline_split_by_point_to ...passed
  Test: test_lwgeom_split ...passed
Suite: stringbuffer
  Test: test_stringbuffer_append ...passed
  Test: test_stringbuffer_aprintf ...passed
Suite: surface
  Test: triangle_parse ...passed
  Test: tin_parse ...passed
  Test: polyhedralsurface_parse ...passed
  Test: surface_dimension ...passed
Suite: Internal Spatial Trees
  Test: test_tree_circ_create ...passed
  Test: test_tree_circ_pip ...passed
  Test: test_tree_circ_pip2 ...passed
  Test: test_tree_circ_distance ...passed
  Test: test_tree_circ_distance_threshold ...passed
Suite: triangulate
  Test: test_lwgeom_delaunay_triangulation ...passed
Suite: twkb_output
  Test: test_twkb_out_point ...passed
  Test: test_twkb_out_linestring ...passed
  Test: test_twkb_out_polygon ...passed
  Test: test_twkb_out_multipoint ...passed
  Test: test_twkb_out_multilinestring ...passed
  Test: test_twkb_out_multipolygon ...passed
  Test: test_twkb_out_collection ...passed
  Test: test_twkb_out_idlist ...passed
Suite: varint
  Test: test_zigzag ...passed
  Test: test_varint ...passed
  Test: test_varint_roundtrip ...passed
Suite: wkb_input
  Test: test_wkb_in_point ...passed
  Test: test_wkb_in_linestring ...passed
  Test: test_wkb_in_polygon ...passed
  Test: test_wkb_in_multipoint ...passed
  Test: test_wkb_in_multilinestring ...passed
  Test: test_wkb_in_multipolygon ...passed
  Test: test_wkb_in_collection ...passed
  Test: test_wkb_in_circularstring ...passed
  Test: test_wkb_in_compoundcurve ...passed
  Test: test_wkb_in_curvpolygon ...passed
  Test: test_wkb_in_multicurve ...passed
  Test: test_wkb_in_multisurface ...passed
  Test: test_wkb_in_malformed ...passed
Suite: wkb_output
  Test: test_wkb_out_point ...passed
  Test: test_wkb_out_linestring ...passed
  Test: test_wkb_out_polygon ...passed
  Test: test_wkb_out_multipoint ...passed
  Test: test_wkb_out_multilinestring ...passed
  Test: test_wkb_out_multipolygon ...passed
  Test: test_wkb_out_collection ...passed
  Test: test_wkb_out_circularstring ...passed
  Test: test_wkb_out_compoundcurve ...passed
  Test: test_wkb_out_curvpolygon ...passed
  Test: test_wkb_out_multicurve ...passed
  Test: test_wkb_out_multisurface ...passed
  Test: test_wkb_out_polyhedralsurface ...passed
Suite: wkt_input
  Test: test_wkt_in_point ...passed
  Test: test_wkt_in_linestring ...passed
  Test: test_wkt_in_polygon ...passed
  Test: test_wkt_in_multipoint ...passed
  Test: test_wkt_in_multilinestring ...passed
  Test: test_wkt_in_multipolygon ...passed
  Test: test_wkt_in_collection ...passed
  Test: test_wkt_in_circularstring ...passed
  Test: test_wkt_in_compoundcurve ...passed
  Test: test_wkt_in_curvpolygon ...passed
  Test: test_wkt_in_multicurve ...passed
  Test: test_wkt_in_multisurface ...passed
  Test: test_wkt_in_tin ...passed
  Test: test_wkt_in_polyhedralsurface ...passed
  Test: test_wkt_in_errlocation ...passed
Suite: wkt_output
  Test: test_wkt_out_point ...passed
  Test: test_wkt_out_linestring ...passed
  Test: test_wkt_out_polygon ...passed
  Test: test_wkt_out_multipoint ...passed
  Test: test_wkt_out_multilinestring ...passed
  Test: test_wkt_out_multipolygon ...passed
  Test: test_wkt_out_collection ...passed
  Test: test_wkt_out_circularstring ...passed
  Test: test_wkt_out_compoundcurve ...passed
  Test: test_wkt_out_curvpolygon ...passed
  Test: test_wkt_out_multicurve ...passed
  Test: test_wkt_out_multisurface ...passed

Run Summary:    Type  Total    Ran Passed Failed Inactive
              suites     38     38    n/a      0        0
               tests    251    251    251      0        0
             asserts   2468   2468   2468      0      n/a

Elapsed time =    0.298 seconds

Creating database 'postgis_reg'
Loading PostGIS into 'postgis_reg'
  /projects/postgis/branches/2.2/regress/00-regress-install/share/contrib/postgis/postgis.sql
  /projects/postgis/branches/2.2/regress/00-regress-install/share/contrib/postgis/postgis_comments.sql
Loading SFCGAL into 'postgis_reg'
  /projects/postgis/branches/2.2/regress/00-regress-install/share/contrib/postgis/sfcgal.sql
  /projects/postgis/branches/2.2/regress/00-regress-install/share/contrib/postgis/sfcgal_comments.sql
PostgreSQL 9.4.4, compiled by Visual C++ build 1800, 32-bit
  Postgis 2.2.0dev - r13980 - 2015-08-23 06:13:07
  scripts 2.2.0dev r13980
  GEOS: 3.5.0-CAPI-1.9.0 r4088
  PROJ: Rel. 4.9.1, 04 March 2015
  SFCGAL: 1.1.0

Running tests

 loader/Point .............. ok
 loader/PointM .............. ok
 loader/PointZ .............. ok
 loader/MultiPoint .............. ok
 loader/MultiPointM .............. ok
 loader/MultiPointZ .............. ok
 loader/Arc .............. ok
 loader/ArcM .............. ok
 loader/ArcZ .............. ok
 loader/Polygon .............. ok
 loader/PolygonM .............. ok
 loader/PolygonZ .............. ok
 loader/TSTPolygon ......... ok
 loader/TSIPolygon ......... ok
 loader/TSTIPolygon ......... ok
 loader/PointWithSchema ..... ok
 loader/NoTransPoint ......... ok
 loader/NotReallyMultiPoint ......... ok
 loader/MultiToSinglePoint ......... ok
 loader/ReprojectPts ........ ok
 loader/ReprojectPtsGeog ........ ok
 loader/Latin1 .... ok
 loader/Latin1-implicit .... ok
 loader/mfile .... ok
 dumper/literalsrid ....... ok
 dumper/realtable ....... ok
 affine .. ok
 bestsrid .. ok
 binary .. ok
 boundary .. ok
 cluster .. ok
 concave_hull .. ok
 ctors .. ok
 dump .. ok
 dumppoints .. ok
 empty .. ok
 forcecurve .. ok
 geography .. ok
 in_geohash .. ok
 in_gml .. ok
 in_kml .. ok
 in_encodedpolyline .. ok
 iscollection .. ok
 legacy .. ok
 long_xact .. ok
 lwgeom_regress .. ok
 measures .. ok
 operators .. ok
 out_geometry .. ok
 out_geography .. ok
 polygonize .. ok
 polyhedralsurface .. ok
 postgis_type_name .. ok
 regress .. ok
 regress_bdpoly .. ok
 regress_index .. ok
 regress_index_nulls .. ok
 regress_management .. ok
 regress_selectivity .. ok
 regress_lrs .. ok
 regress_ogc .. ok
 regress_ogc_cover .. ok
 regress_ogc_prep .. ok
 regress_proj .. ok
 relate .. ok
 remove_repeated_points .. ok
 removepoint .. ok
 setpoint .. ok
 simplify .. ok
 simplifyvw .. ok
 size .. ok
 snaptogrid .. ok
 split .. ok
 sql-mm-serialize .. ok
 sql-mm-circularstring .. ok
 sql-mm-compoundcurve .. ok
 sql-mm-curvepoly .. ok
 sql-mm-general .. ok
 sql-mm-multicurve .. ok
 sql-mm-multisurface .. ok
 swapordinates .. ok
 summary .. ok
 temporal .. ok
 tickets .. ok
 twkb .. ok
 typmod .. ok
 wkb .. ok
 wkt .. ok
 wmsservers .. ok
 knn .. ok
 hausdorff .. ok
 regress_buffer_params .. ok
 offsetcurve .. ok
 relatematch .. ok
 isvaliddetail .. ok
 sharedpaths .. ok
 snap .. ok
 node .. ok
 unaryunion .. ok
 clean .. ok
 relate_bnr .. ok
 delaunaytriangles .. ok
 clipbybox2d .. ok
 subdivide .. ok
 in_geojson .. ok
 regress_sfcgal .. ok
 sfcgal/empty .. ok
 sfcgal/geography .. ok
 sfcgal/legacy .. ok
 sfcgal/measures .. ok
 sfcgal/regress_ogc_prep .. ok
 sfcgal/regress_ogc .. ok
 sfcgal/regress .. ok
 sfcgal/tickets .. ok
 sfcgal/concave_hull .. ok
 sfcgal/wmsservers .. ok
 sfcgal/approximatemedialaxis .. ok
 uninstall .  /projects/postgis/branches/2.2/regress/00-regress-install/share/contrib/postgis/uninstall_sfcgal.sql
  /projects/postgis/branches/2.2/regress/00-regress-install/share/contrib/postgis/uninstall_postgis.sql
. ok (4336)

Run tests: 118
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/


Suite: Shapefile Loader File shp2pgsql Test
  Test: test_ShpLoaderCreate() ...passed
  Test: test_ShpLoaderDestroy() ...passed
Suite: Shapefile Loader File pgsql2shp Test
  Test: test_ShpDumperCreate() ...passed
  Test: test_ShpDumperDestroy() ...passed

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

The postgis_tiger_geocoder and address_standardizer extensions, currenlty only support the standard PostgreSQL installcheck. To test these use the below. Note: the make install is not necessary if you already did make install at root of PostGIS code folder.

For address_standardizer:

cd extensions/address_standardizer
make install
make installcheck
          

Output should look like:

============== dropping database "contrib_regression" ==============
DROP DATABASE
============== creating database "contrib_regression" ==============
CREATE DATABASE
ALTER DATABASE
============== running regression test queries        ==============
test test-init-extensions     ... ok
test test-parseaddress        ... ok
test test-standardize_address_1 ... ok
test test-standardize_address_2 ... ok

=====================
 All 4 tests passed.
=====================

For tiger geocoder, make sure you have postgis and fuzzystrmatch extensions available in your PostgreSQL instance. The address_standardizer tests will also kick in if you built postgis with address_standardizer support:

cd extensions/postgis_tiger_geocoder
make install
make installcheck
          

output should look like:

============== dropping database "contrib_regression" ==============
DROP DATABASE
============== creating database "contrib_regression" ==============
CREATE DATABASE
ALTER DATABASE
============== installing fuzzystrmatch               ==============
CREATE EXTENSION
============== installing postgis                     ==============
CREATE EXTENSION
============== installing postgis_tiger_geocoder      ==============
CREATE EXTENSION
============== installing address_standardizer        ==============
CREATE EXTENSION
============== running regression test queries        ==============
test test-normalize_address   ... ok
test test-pagc_normalize_address ... ok

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

2.4.5. Installation

Pour installer PostGIS, entrez

make install

Ceci copiera les fichiers d'installation de PostGIS dans leur sous-répertoires appropriés définie par le paramètre de configuration --prefix. En particulier :

  • Les binaires du chargeur et du dumper sont installés dans [prefix]/bin.

  • Les fichiers SQL, tel que postgis.sql, sont installé dans [prefix]/share/contrib.

  • Les bibliothèques PostGIS sont installées dans [prefix]/lib.

Si vous avez déjà lancé la commande make comments pour générer les fichiers postgis_comments.sql, raster_comments.sql, installer le fichier sql en lançant

make comments-install

[Note]

postgis_comments.sql, raster_comments.sql, topology_comments.sql ont été séparés de la compilation initiale et des cibles de l'installation depuis qu'ils sont dépendant de xsltproc.

2.5. Créer une base de données spatiale en utilisant EXTENSIONS

Si vous utilisez PostgreSQL 9.1 et supérieur puis avez compilé et installé les modules extensions/ postgis, vous pouvez créer une base de données spatiales par la nouvelle manière.

createdb [yourdatabase]

L'extension du coeur de PostGIS installe geometry, geography, raster, spatial_ref_sys et toutes les fonctions et commentaires avec une simple commande :

CREATE EXTENSION postgis;

.

psql -d [yourdatabase] -c "CREATE EXTENSION postgis;"

La topologie est fournie comme extension séparée et installable avec la commande :

psql -d [yourdatabase] -c "CREATE EXTENSION postgis_topology;"

Si vous prévoyez de restaurer une vielle sauvegarde à partir d'une version antérieure dans la nouvelle base, lancez :

psql -d [yourdatabase] -f legacy.sql

Vous pouvez lancer uninstall_legacy.sql pour supprimer les fonctions dépréciées après avoir fait les opérations de restauration et de nettoyage.

2.6. Créer une base de données spatiale à partir d'un modèle

[Note]

This is generally only needed if you built-PostGIS without raster support. Since raster functions are part of the postgis extension, extension support is not enabled if PostGIS is built without raster.

La première étape dans la création d'une base de données PostGIS est de créer la base PostgreSQL.

createdb [yourdatabase]

Plusieurs fonctions PostGIS sont écrites en langage procédural PL/pgSQL. Par conséquent, l'étape suivante pour créer une base de données PostGIS est d'activer la langue PL/pgSQL dans votre base de données. Cela est réalisée par la commande ci-dessous. Pour les versions 8.4 et supérieure de PostgreSQL, celle-ci est généralement déjà installée.

createlang plpgsql [yourdatabase]

Maintenant chargez les définitions d'objet et de fonction PostGIS dans votre base de données en chargeant le fichier de définition postgis.sql (localisé dans [prefix]/share/contrib comme définie dans l'étape de configuration).

psql -d [yourdatabase] -f postgis.sql

Pour un ensemble complet d'identifiant de définition de système de coordonnées EPSG, vous pouvez également lancer le fichier de définitions spatial_ref_sys.sql et remplir la table spatial_ref_sys. Cela vous permet de réaliser des opérations ST_Transform() sur les géométries.

psql -d [yourdatabase] -f spatial_ref_sys.sql

Si vous désirez ajouter des commentaires aux fonctions PostGIS, l'étape finale est de charger postgis_comments.sql dans votre base spatiale. Les commentaires peuvent être vus en tapant simplement \dd [function_name] dans la console psql.

psql -d [yourdatabase] -f postgis_comments.sql

Installation de la gestion des raster

psql -d [yourdatabase] -f rtpostgis.sql

Installation des commentaires dans la gestion des raster. Cela fournira une aide rapide pour chaque fonction raster en utilisant psql ou PgAdmin ou n'importe quel outil PostgreSQL qui peut montrer les commentaires des fonctions.

psql -d [yourdatabase] -f raster_comments.sql

Installer la gestion de la topologie

psql -d [yourdatabase] -f topology/topology.sql

Installation des commentaires dans la gestion de la topologie. Cela fournira une aide rapide pour chaque fonction topologique en utilisant psql ou PgAdmin ou n'importe quel outil PostgreSQL qui peut montrer les commentaires des fonctions.

psql -d [yourdatabase] -f topology/topology_comments.sql

Si vous prévoyez de restaurer une vielle sauvegarde à partir d'une version antérieure dans la nouvelle base, lancez :

psql -d [yourdatabase] -f legacy.sql

[Note]

Il y a l'alternatif legacy_minimal.sql que vous pouvez lancer à la place et qui va installer les primitives nécessaires pour récupérer les tables et travailler avec des applications comme MapServer et GeoServer. Si vous avez des vues qui utilisent des choses comme distance / length etc, vous aurez besoin du fichier legacy.sql complet.

Vous pouvez lancer uninstall_legacy.sql pour supprimer les fonctions dépréciées après avoir fait les opérations de restauration et de nettoyage.

2.7. Installing and Using the address standardizer

The address_standardizer extension used to be a separate package that required separate download. From PostGIS 2.2 on, it is now bundled in. For more information about the address_standardize, what it does, and how to configure it for your needs, refer to Chapter 12, Address Standardizer.

This standardizer can be used in conjunction with the PostGIS packaged tiger geocoder extension as a replacement for the Normalize_Address discussed. To use as replacement refer to Section 2.8.3, “Using Address Standardizer Extension with Tiger geocoder”. You can also use it as a building block for your own geocoder or use it to standardize your addresses for easier compare of addresses.

The address standardizer relies on PCRE which is usually already installed on many Nix systems, but you can download the latest at: http://www.pcre.org. If during Section 2.4.1, “Configuration”, PCRE is found, then the address standardizer extension will automatically be built. If you have a custom pcre install you want to use instead, pass to configure --with-pcredir=/path/to/pcre where /path/to/pcre is the root folder for your pcre include and lib directories.

For Windows users, the PostGIS 2.1+ bundle is packaged with the address_standardizer already so no need to compile and can move straight to CREATE EXTENSION step.

Once you have installed, you can connect to your database and run the SQL:

CREATE EXTENSION address_standardizer;

The following test requires no rules, gaz, or lex tables

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

Output should be

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

2.7.1. Installing Regex::Assemble

Perl Regex:Assemble is no longer needed for compiling address_standardizer extension since the files it generates are part of the source tree. However if you need to edit the usps-st-city-orig.txt or usps-st-city-orig.txt usps-st-city-adds.tx, you need to rebuild parseaddress-stcities.h which does require Regex:Assemble.

cpan Regexp::Assemble

ou si vous êtes sur Ubuntu / Debian, vous devrez peut-être faire

sudo perl -MCPAN -e "install Regexp::Assemble"

2.8. Installer, mettre à jour le Géocodeur Tiger et charger des données

Extras like Tiger geocoder may not be packaged in your PostGIS distribution, but will always be available in the postgis-2.4.0dev.tar.gz file. The instructions provided here are also available in the extras/tiger_geocoder/README

Si vous êtes sous Windows et que vous n'avez pas tar installé, vous pouvez utiliser http://www.7-zip.org/ pour décompresser le tarball PostGIS.

2.8.1. Tiger Geocoder Enabling your PostGIS database: Using Extension

If you are using PostgreSQL 9.1+ and PostGIS 2.1+, you can take advantage of the new extension model for installing tiger geocoder. To do so:

  1. First get binaries for PostGIS 2.1+ or compile and install as usual. This should install the necessary extension files as well for tiger geocoder.

  2. Connect to your database via psql or pgAdmin or some other tool and run the following SQL commands. Note that if you are installing in a database that already has postgis, you don't need to do the first step. If you have fuzzystrmatch extension already installed, you don't need to do the second step either.

    CREATE EXTENSION postgis;
    CREATE EXTENSION fuzzystrmatch;
    --this one is optional if you want to use the rules based standardizer (pagc_normalize_address)
    CREATE EXTENSION address_standardizer;
    CREATE EXTENSION postgis_tiger_geocoder;

    If you already have postgis_tiger_geocoder extension installed, and just want to update to the latest run:

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

    If you made custom entries or changes to tiger.loader_platform and tiger.loader_variables you may need to update these.

  3. To confirm your install is working correctly, run this sql in your database:

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

    Which should output

    address | streetname | streettypeabbrev |  zip
    ---------+------------+------------------+-------
               1 | Devonshire | Pl               | 02109
  4. Create a new record in tiger.loader_platform table with the paths of your executables and server.

    So for example to create a profile called debbie that follows sh convention. You would do:

    INSERT INTO tiger.loader_platform(os, declare_sect, pgbin, wget, unzip_command, psql, path_sep,
                       loader, environ_set_command, county_process_command)
    SELECT 'debbie', declare_sect, pgbin, wget, unzip_command, psql, path_sep,
               loader, environ_set_command, county_process_command
      FROM tiger.loader_platform
      WHERE os = 'sh';

    And then edit the paths in the declare_sect column to those that fit Debbie's pg, unzip,shp2pgsql, psql, etc path locations.

    If you don't edit this loader_platform table, it will just contain common case locations of items and you'll have to edit the generated script after the script is generated.

  5. Create a folder called gisdata on root of server or your local pc if you have a fast network connection to the server. This folder is where the tiger files will be downloaded to and processed. If you are not happy with having the folder on the root of the server, or simply want to change to a different folder for staging, then edit the field staging_fold in the tiger.loader_variables table.

  6. Create a folder called temp in the gisdata folder or whereever you designated the staging_fold to be. This will be the folder where the loader extracts the downloaded tiger data.

  7. Then run the Loader_Generate_Nation_Script SQL function make sure to use the name of your custom profile and copy the script to a .sh or .bat file. So for example to build the nation load:

    psql -c "SELECT Loader_Generate_Nation_Script('debbie')" -d geocoder -tA > /gisdata/nation_script_load.sh
  8. Lancement des requêtes SQL de suppression générées.

    cd /gisdata
    sh nation_script_load.sh
  9. After you are done running the nation script, you should have three tables in your tiger_data schema and they should be filled with data. Confirm you do by doing the following queries from psql or pgAdmin

    SELECT count(*) FROM tiger_data.county_all;
    count
    -------
      3233
    (1 row)
    SELECT count(*) FROM tiger_data.state_all;
    count
    -------
        56
    (1 row)
    
  10. For each state you want to load data for, generate a state script Loader_Generate_Script. DO NOT Generate the state script until you have already loaded the nation data, because the state script utilizes county list loaded by nation script.

  11. psql -c "SELECT Loader_Generate_Script(ARRAY['MA'], 'debbie')" -d geocoder -tA > /gisdata/ma_load.sh
  12. Lancement des requêtes SQL de suppression générées.

    cd /gisdata
    sh ma_load.sh
  13. After you are done loading all data or at a stopping point, it's a good idea to analyze all the tiger tables to update the stats (include inherited stats)

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

2.8.1.1. Converting a Tiger Geocoder Regular Install to Extension Model

If you installed the tiger geocoder without using the extension model, you can convert to the extension model as follows:

  1. Follow instructions in Section 2.8.5, “Mise à jour de l'installation du Géocodeur Tiger” for the non-extension model upgrade.

  2. Connect to your database with psql or pgAdmin and run the following command:

    CREATE EXTENSION postgis_tiger_geocoder FROM unpackaged;

2.8.2. Tiger Geocoder Enabling your PostGIS database: Not Using Extensions

D'abord installez PostGIS en utilisant les instructions précédentes.

If you don't have an extras folder, download http://postgis.net/stuff/postgis-2.4.0dev.tar.gz

tar xvfz postgis-2.4.0dev.tar.gz

cd postgis-2.4.0dev/extras/tiger_geocoder

Edit the tiger_loader_2015.sql (or latest loader file you find, unless you want to load different year) to the paths of your executables server etc or alternatively you can update the loader_platform table once installed. If you don't edit this file or the loader_platform table, it will just contain common case locations of items and you'll have to edit the generated script after the fact when you run the Loader_Generate_Nation_Script and Loader_Generate_Script SQL functions.

If you are installing Tiger geocoder for the first time edit either the create_geocode.bat script If you are on windows or the create_geocode.sh if you are on Linux/Unix/Mac OSX with your PostgreSQL specific settings and run the corresponding script from the commandline.

Vérifiez que vous avez maintenant un schéma tiger dans votre base de données et qu'il fait partie de votre search_path. Si ce n'est pas le cas, ajoutez le avec une commande qui s'apparente à celle-ci :

ALTER DATABASE geocoder SET search_path=public, tiger;

La fonctionnalité de normalisation des adresses fonctionne plus ou moins sans données, sauf les adresses un peu complexe. Lancez ce test et vérifiez que les choses ressemblent à cela :

SELECT pprint_addy(normalize_address('202 East Fremont Street, Las Vegas, Nevada 89101')) As pretty_address;
pretty_address
---------------------------------------
202 E Fremont St, Las Vegas, NV 89101
                        

2.8.3. Using Address Standardizer Extension with Tiger geocoder

One of the many complaints of folks is the address normalizer function Normalize_Address function that normalizes an address for prepping before geocoding. The normalizer is far from perfect and trying to patch its imperfectness takes a vast amount of resources. As such we have integrated with another project that has a much better address standardizer engine. To use this new address_standardizer, you compile the extension as described in Section 2.7, “Installing and Using the address standardizer” and install as an extension in your database.

Once you install this extension in the same database as you have installed postgis_tiger_geocoder, then the Pagc_Normalize_Address can be used instead of Normalize_Address. This extension is tiger agnostic, so can be used with other data sources such as international addresses. The tiger geocoder extension does come packaged with its own custom versions of rules table ( tiger.pagc_rules) , gaz table (tiger.pagc_gaz), and lex table (tiger.pagc_lex). These you can add and update to improve your standardizing experience for your own needs.

2.8.4. Chargement des données Tiger

Les instructions pour charger les données sont disponibles sous forme plus détaillée dans extras/tiger_geocoder/tiger_2011/README. Ce chapitre indique juste les étapes générales.

Le processus de chargement télécharge les données du site web census pour respectivement les fichiers nation, état demandé, extrait les fichiers, puis charge chaque état dans son ensemble de tables état. Chaque table state hérite de la table définie dans le schéma tiger, il est suffisant d'interroger ces tables pour accéder à toutes les données et supprimer un ensemble de table state n'importe quand en utilisant Drop_State_Tables_Generate_Script si vous devez recharger un état ou si vous en avez plus besoin.

Dans l'objectif de charger des données vous avez besoin des outils suivants :

  • Un outils pour décompresser les fichiers zip du site web census.

    Pour les systèmes Unix-like : un exécutable unzip qui est habituellement installé sur la plupart des plateformes Unix-like.

    Pour Windows, 7-zip qui est un outils de compression/décompression libre, vous pouvez le récupérer à partir de http://www.7-zip.org/

  • La commande shp2pgsql qui est installé par défaut quand vous installez PostGIS.

  • wget qui est un outil de récupération de lien habituellement installé sur les systèmes Unix/Linux.

    Si vous êtes sous Windows, vous pouvez obtenir des binaires pré-compilés à partir de http://gnuwin32.sourceforge.net/packages/wget.htm

If you are upgrading from tiger_2010, you'll need to first generate and run Drop_Nation_Tables_Generate_Script. Before you load any state data, you need to load the nation wide data which you do with Loader_Generate_Nation_Script. Which will generate a loader script for you. Loader_Generate_Nation_Script is a one-time step that should be done for upgrading (from 2010) and for new installs.

To load state data refer to Loader_Generate_Script to generate a data load script for your platform for the states you desire. Note that you can install these piecemeal. You don't have to load all the states you want all at once. You can load them as you need them.

Après que les états que vous désirez aient été chargé, assurez vous de lancer la commande :

SELECT install_missing_indexes();

comme décrit dans Install_Missing_Indexes.

Pour tester que les choses fonctionnent comme elles le devraient, essayez de lancer un géocodage sur une adresse de votre état en utilisant Geocode

2.8.5. Mise à jour de l'installation du Géocodeur Tiger

If you have Tiger Geocoder packaged with 2.0+ already installed, you can upgrade the functions at any time even from an interim tar ball if there are fixes you badly need. This will only work for Tiger geocoder not installed with extensions.

If you don't have an extras folder, download http://postgis.net/stuff/postgis-2.4.0dev.tar.gz

tar xvfz postgis-2.4.0dev.tar.gz

cd postgis-2.4.0dev/extras/tiger_geocoder/tiger_2011

Locate the upgrade_geocoder.bat script If you are on windows or the upgrade_geocoder.sh if you are on Linux/Unix/Mac OSX. Edit the file to have your postgis database credentials.

If you are upgrading from 2010 or 2011, make sure to unremark out the loader script line so you get the latest script for loading 2012 data.

Then run th corresponding script from the commandline.

Puis supprimez toutes les tables nation et chargez les nouvelles. Générez un script de suppression avec la requête SQL comme détaillée dans Drop_Nation_Tables_Generate_Script

SELECT drop_nation_tables_generate_script();

Lancement des requêtes SQL de suppression générées.

Générez un script de chargement des pays avec la requête SELECT comme détaillé dans Loader_Generate_Nation_Script

Pour windows

SELECT loader_generate_nation_script('windows'); 

Pour unix/linux

SELECT loader_generate_nation_script('sh');

Référez vous à Section 2.8.4, “Chargement des données Tiger” pour les instructions sur la manière de lancer le script généré. Cela doit être fait qu'une fois.

[Note]

Vous pouvez avoir un mélange de tables d'état 2010/2011 et vous pouvez mettre à jour chaque état séparément. Avant la mise à jour d'un état vers 2011, vous devez d'abord supprimer les tables 2010 pour chaque état avec Drop_State_Tables_Generate_Script.

2.9. Créer une base de données spatiale à partir d'un modèle

Certaines distributions packagées de PostGIS (en particulier les installeurs Wins32 pour PostGIS >= 1.1.5) charge les fonctions PostGIS dans une base modèle appelée template_postgis. Si la base template_postgis existe dans votre installation PostgreSQL alors il est possible que les utilisateurs et les applications de créer des bases de données spatiales en utilisant une simple commande. Notez que dans les deux cas, l'utilisateur de la base de données doit avoir des privilèges de création de nouvelles bases.

À partir de la console :

# createdb -T template_postgis my_spatial_db

À partir du SQL :

postgres=# CREATE DATABASE my_spatial_db TEMPLATE=template_postgis

2.10. Mise à jour

La mise à jour de bases de données spatiales existant peut être complexe puisqu'elle nécessite le remplacement ou l'introduction de nouvelles définitions d'objet PostGIS.

Malheureusement seules certaines définitions peuvent être remplacées dans une base en cours d'utilisation, parfois votre meilleure stratégie est la procédure d'export/import.

PostGIS fourni une procédure de mise à jour mineure pour les releases mineures ou de correction de bug et une procédure de mise à jour majeure pour les releases mpajeures.

Avant de tenter la mise à jour de PostGIS, cela vaut toujours le coup de sauvegarder vos données. Si vous utilisez l'option -Fc à pg_dump vous aurez toujours la possibilité de restaurer le dump avec une mise à jour majeure.

2.10.1. Mise à jour mineure

Si vous avez installé votre base de données en utilisant les extensions, vous devrez mettre à jour le modèle d'extension également. Si vous l'avez installé en utilisant l'ancienne méthode du script, alors vous devez mettre à jour en utilisant la méthode du script. Référez vous à la méthode appropriée.

2.10.1.1. Mise à jour mineure avant la 9.1 ou sans les extensions

Cette section s'applique seulement à ceux qui ont installé PostGIS sans utiliser les extensions. Si vous avez les extensions et tentez de mettre à jour avec cette approche vous obtiendrez des messages comme :

can't drop ... because postgis extension depends on it

Après compilation et installation (make install) vous devrez trouvez plusieurs fichiers postgis_upgrade.sql et rtpostgis_upgrade.sql dans les dossiers d'installation. Par exemple /usr/share/postgresql/9.3/contrib/postgis_upgrade.sql. Installer postgis_upgrade.sql. Si vous avez installé la fonctionnalité raster, vous aurez aussi besoin d'installer le /usr/share/postgresql/9.3/contrib/postgis_upgrade.sql. Si vous migrez de PostGIS 1.* vers PostGIS 2.* ou de PostGIS 2.* avec la révision r7409, vous devez faire une mise à jour majeure.

psql -f postgis_upgrade.sql -d your_spatial_database

La même procédure s'applique aux extensions raster et topologie avec les fichiers de mises à jour nommés respectivement : rtpostgis_upgrade*.sql et topology_upgrade*.sql. Si vous en avez besoin :

psql -f rtpostgis_upgrade.sql -d your_spatial_database
psql -f topology_upgrade.sql -d your_spatial_database
[Note]

Si vous ne pouvez pas trouver de version spécifique de postgis_upgrade*.sql pour mettre à jour votre version, vous utilisez une version trop vielle pour une mise à jour mineure et devez faire une mise à jour majeure.

La fonction PostGIS_Full_Version doit vous informer sur le besoin de faire ce genre de mise à jour en utilisant le message "procs need upgrade".

2.10.1.2. Mise à jour mineure 9.1 et supérieure en utilisant les extensions

Si vous avez à l'origine installé PostGIS avec les extensions, alors vous devez faire la mise à jour en utilisant les extensions également. Réaliser une mise à jour mineure avec les extensions est sans difficulté.

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

Si vous obtenez un rapport d'erreur similaire à celui-ci:

No migration path defined for ... to 2.4.0dev

Then you'll need to backup your database, create a fresh one as described in Section 2.5, “Créer une base de données spatiale en utilisant EXTENSIONS” and then restore your backup ontop of this new database.

Si vous obtenez un message d'avertissement comme :

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

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

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

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

2.10.2. Mise à jour majeure

Par mise à jour majeure nous voulons dire export/import complet des bases PostGIS. Vous devez faire une mise à jour majeure lorsque le stockage interne des objets PostGIS change ou quand la mise à jour mineure n'est pas possible. L'annexe des Release Notes pour chaque version indique si vous avez besoin d'un export/import (mise à jour majeure) pour la mise à jour.

Le processus d'export/import est assisté par le script postgis_restore.pl qui s'assure de sauter dans le dump toutes les définitions qui appartiennent à PostGIS (dont les anciennes) vous permettant de restaurer vos schémas et données dans une base avec PostGIS installé sans avoir des erreurs de symboles dupliquées ou rapporter des objets dépréciés.

Des instructions supplémentaires pour les utilisateurs de Windows sont disponibles sur Mise à jour majeure pour Windows.

La procédure est la suivante :

  1. Créer un dump au format personnalisé de la base que vous voulez mettre à jour (appelons la olddb) en incluant les blobs binaire (-b) et une sortie verbeuse (-v). L'utilisateur peut être le propriétaire de la base, pas besoin d'être le super-utilisateur postgres.

    pg_dump -h localhost -p 5432 -U postgres -Fc -b -v -f "/somepath/olddb.backup" olddb
  2. Faîtes une installation fraîche de PostGIS dans une nouvelle base de données -- nous nous référons à cette base comme newdb. Référez vous s'il vous plaît aux instructions Section 2.6, “Créer une base de données spatiale à partir d'un modèle” et Section 2.5, “Créer une base de données spatiale en utilisant EXTENSIONS” sur comment faire cela.

    Les entrées de spatial_ref_sys trouvé dans le dump seront restaurées, mais ils n'écraseront pas ceux existant dans la table spatial_ref_sys. Cela pour s'assurer que les corrections dans l'ensemble officiel seront propagées correctement aux bases restaurées. Si pour une raison ou une autre vous souhaitez réellement que les vôtres écrasent les entrées standards ne chargez pas le fichier spatial_ref_sys.sql lors de la création de la nouvelle base.

    Si votre base de données est vraiment ancienne ou que vous avez utilisé des fonctions longtemps dépréciées dans vos vues et fonctions, vous pourrez avoir besoin de charger legacy.sql pour que toutes vos vues et fonctions, etc fonctionnent proprement. Faîtes cela uniquement si c'est _réellement_ nécessaire. Les fonctions dépréciées peuvent être supprimé plus tard en chargeant le script

  3. Restaurez votre sauvegarde dans votre nouvelle base de données newdb en utilisant le script postgis_restore.pl. Des erreurs inattendues seront éventuellement affichées dans le flux standards d'erreur par psql. Gardez un log de ceux-ci.

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

Des erreurs peuvent arriver dans les cas suivants :

  1. Certaines de vos vues ou fonctions utilisent des objets dépréciés de PostGIS. Dans le but de corriger cela vous pouvez essayer de charger le script legacy.sql avant de restaurer ou de restaurer une version de PostGIS qui contient toujours ces objets et tenter une migration après avoir modifié votre code. Si le fichier legacy.sql peut fonctionner pour vous, n'oubliez pas de corriger votre code pour arrêter d'utiliser des fonctions dépréciées et supprimer les en chargeant le script

  2. Certains enregistrement de spatial_ref_sys dans le fichier dump ont des valeurs de SRID invalides. Les valeurs de SRID valides sont supérieures à 0 et plus petites que 999000. Les valeurs dans le domaine 999000.999999 sont réservés pour un usage interne tandis que les valeurs > 999999 ne peut pas être utilisé du tout. Tous vos enregistrements personnalisés avec des SRID invalides seront gardés, ceux qui sont > 999999 déplacé dans le domaine réservé, mais la table spatial_ref_sys perdra une contrainte de vérification pour garder cela cohérent et probablement sa clé primaire (lorsque plusieurs SRID invalides sont converties à la même valeur réservé pour le SRID).

    Afin de corriger cela, vous pouvez copier vos SRS personnalisés vers un SRID avec une valeur valide (probablement dans le domaine 910000..910999), convertissez toutes vos tables vers le nouveau srid (lisez UpdateGeometrySRID), supprimez les entrées invalides de la table spatial_ref_sys et reconstruisez la ou les vérification(s) avec :

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

2.11. Common Problems during installation

Il y a plusieurs choses à vérifier quand votre installation ou mise à jour ne va pas dans la direction souhaitée.

  1. Vérifiez que vous avez installé PostgreSQL 9.3 ou plus récent et que vous êtes en train de compiler avec la même version du code source de PostgreSQL que la version qui fonctionne. Un mélange peut arriver lorsque votre distribution (Linux) a déjà une version de PostgreSQL installée ou que vous avez oublié que vous avez déjà installée une version. PostGIS fonctionnera uniquement avec PostgreSQL 9.3 ou plus récent, et des messages d'erreurs étranges et inhabituelles en résultera si vous utilisez une version plus ancienne. Pour vérifier la version de PostgreSQL qui fonctionne, connectez vous à la base en utilisant psql et lancez la requête :

    SELECT version();

    Si vous utilisez une distribution basé sur les RPM, vous pouvez vérifier l'existence de paquets pré-installés en utilisant la commande rpm comme suit : rpm -qa | grep postgresql

  2. Si votre mise à jour plante, assurez vous de la présence de PostGIS dans la nouvelle base de données.

    SELECT postgis_full_version();

Vérifiez également que le script configure a correctement détecté la localisation et la version de PostgreSQL, la bibliothèque Proj.4 et GEOS.

  1. La sortie du configure est utilisée pour générer le fichier postgis_config.h. Vérifiez que les variables POSTGIS_PGSQL_VERSION, POSTGIS_PROJ_VERSION et POSTGIS_GEOS_VERSION ont été définies correctement.

2.12. Chargeur/Dumper

Les outils d'import et d'export de données sont compilés et installés automatiquement dans le processus de compilation de PostGIS. Pour les compiler et les installer manuellement :

# cd postgis-2.4.0dev/loader
# make
# make install

L'outil d'import est appelé shp2pgsql et converti des fichiers ESRI Shape en SQL compatible pour être chargé dans PostGIS/PostgreSQL. L'outil d'export est appelé pgsql2shp et converti les tables PostGIS (ou des requêtes) en fichier ESRI Shape. Pour une documentation plus complète, lisez l'aide en ligne et les pages de manuel.

Chapter 3. Foire Aux Questions PostGIS

3.1. Où puis-je trouver des tutoriaux, des guides et des travaux pratiques pour travailler avec PostGIS
3.2. Mon application et mes outils fonctionnaient avec PostGIS 1.5, cependant ils ne marchent plus avec PostGIS 2.0. Comment réparer cela ?
3.3. Lorsque je charge des données OpenStreetMap avec osm2pgsql, je reçois une erreur : ERROR: operator class "gist_geometry_ops" does not exist for access method "gist" Error occurred. Tout marchait correctement avec PostGIS 1.5.
3.4. J'utilise PostgreSQL 9.0 et je ne peux plus accéder à la géométries de mes objets dans OpenJump, Safe FME ou tout autre logiciel
3.5. J'ai essayé d'utiliser PgAdmin pour visualiser mon champ géométrique mais elle est vide, qu'arrive-t-il ?
3.6. Quelles sont les objets géométriques que je peux sauvegarder ?
3.7. Je suis perdu. Dois-je utiliser un champs de type "geometry" ou "geography" ?
3.8. J'ai d'autres questions plus avancées sur le type geography, comme la taille d'une région géographique que je peux mettre dans une colonne geography pour continuer à avoir des requêtes performantes. Ou bien s'il y a des limitations, comme aux pôles, ou si toutes les données doivent tenir dans un hémisphère (comme dans SQL server 2008), ou bien sur la vitesse d'exécution, etc.
3.9. Comment est-ce que j'insère un objet SIG dans une base de données ?
3.10. Comment est-ce que je construis une requête spatiale ?
3.11. Comment est-ce que je peux accélérer les requêtes spatiales sur des grandes tables ?
3.12. Pourquoi est-ce que les indexes R-Tree PostgreSQL ne sont pas supportés ?
3.13. Pourquoi est-il mieux d'utiliser la fonction AddGeometryColumn() et toutes les autres fonctionnalités de PostGIS ?
3.14. Quelle est la meilleure méthode pour trouver les objets qui sont dans un certains rayons d'un autre objet ?
3.15. Comment procéder à de la reprojection de coordonnées dans une requête ?
3.16. J'ai fait un ST_AsEWKT et un ST_AsText sur de grandes géométries et j'ai obtenu une réponse vide. Qu'est-il arrivé ?
3.17. Quand je fais un ST_Intersects, il me répond que mes deux géométries ne s'intersectent pas alors que JE SAIS QUE C'EST LE CAS. Qu'arrive-t-il ?
3.18. Je vais sortir un logiciel qui utilise PostGIS, est-ce que cela veut dire que mon logiciel doit être sous licence GPL tel que PostGIS ? Vais-je devoir publier tout mon code source si j'utilise PostGIS ?

3.1.

Où puis-je trouver des tutoriaux, des guides et des travaux pratiques pour travailler avec PostGIS

OpenGeo a un tutoriel pas à pas sous forme d'atelier Introduction à PostGIS. Il comprend des jeux données ainsi que l'intro pour travailler avec OpenGeo Suite. C'est probablement le meilleur tutoriel sur PostGIS.

BostonGIS a aussi un Guide pour démarrer avec PostGIS pour les quasi-idiots. Ce dernier est plutôt orienté vers les utilisateurs Windows.

3.2.

Mon application et mes outils fonctionnaient avec PostGIS 1.5, cependant ils ne marchent plus avec PostGIS 2.0. Comment réparer cela ?

Beaucoup de fonctions obsolètes ont été supprimées du code de PostGIS dans PostGIS 2.0. Cela a affecté des applications en sus d'outils tiers comme GeoServer, MapServer, QuantumGIS et OpenJump pour n'en citer que quelques uns. Il y a plusieurs façons de résoudre ceci. Pour les applications tierces, vous pouvez essayer de passer aux dernières versions de celles qui ont vu beaucoup de ces problèmes résolus. Pour votre propre code, vous pouvez le modifier pour ne pas utiliser les fonctions supprimées. La plupart de ces fonctions ne sont pas des alias ST_ de ST_Union, ST_Length etc. et en dernier recours, installez la totalité de legacy.sql ou juste les parties de legacy.sql dont vous avez besoin.

Le fichier legacy.sql est situé dans le même répertoire que postgis.sql. Vous pouvez installer ce fichier après avoir installé postgis.sql et spatial_ref_sys.sql pour retrouver toutes les 200 et quelques anciennes fonctions que nous avons supprimées.

3.3.

Lorsque je charge des données OpenStreetMap avec osm2pgsql, je reçois une erreur : ERROR: operator class "gist_geometry_ops" does not exist for access method "gist" Error occurred. Tout marchait correctement avec PostGIS 1.5.

Dans PostGIS 2, la classe d'opérateur de geometry par défaut gist_geometry_ops a été changé en gist_geometry_ops_2d et gist_geometry_ops a été totalement supprimé. Cela a été fait car PostGIS 2 a aussi introduit les indexes Nd pour le support 3D et l'ancien nom a été considéré comme trompeur.

Certaines applications anciennes créant des tables et des indexes dans leur fonctionnement référençaient directement l'ancienne classe d'opérateur. Cela n'était pas nécessaire si vous vouliez l'index 2D par défaut. Donc si vous souhaitez faire les chose correctement, changer la création d'index de :

MAUVAIS :

CREATE INDEX idx_my_table_geom ON my_table USING gist(geom gist_geometry_ops);

vers la BONNE version :

CREATE INDEX idx_my_table_geom ON my_table USING gist(geom);

Le seul cas où vous DEVEZ spécifier la classe d'opérateur est si vous voulez un index spatial 3D comme dans l'exemple suivant :

CREATE INDEX idx_my_super3d_geom ON my_super3d USING gist(geom gist_geometry_ops_nd);

Si vous êtes assez malchanceux pour être coincé avec un code compilé que vous ne pouvez changer et qui a l'ancien gist_geometry_ops codé en dur, alors vous pouvez recréer l'ancienne classe en utilisant legacy_gist.sql fourni avec PostGIS 2.0.2+. Cependant si vous utilisez cette rustine, il est conseillé par la suite de supprimer l'index et de le recréer sans la classe d'opérateur. Cela vous évitera des soucis à l'avenir lorsque vous devrez refaire une mise à jour.

3.4.

J'utilise PostgreSQL 9.0 et je ne peux plus accéder à la géométries de mes objets dans OpenJump, Safe FME ou tout autre logiciel

Dans PostgreSQL 9.0+, l'encodage par défaut pour la donnée bytea a été changé vers l'hexadécimal et les anciens pilotes JDBC assument toujours l'ancien format avec échappement. Cela affecte certaines applications telles que les applications Java utilisant des anciens pilotes JDBC, ou des applications .NET qui utilisent le vieux pilote npgsql, qui attend l'ancien comportement de ST_AsBinary. Il y a deux approches pour rétablir un bon fonctionnement dans cette situation.

Vous pouvez mettre à jour votre pilote JDBC vers sa version PostgreSQL 9.0 que vous pouvez obtenir depuis http://jdbc.postgresql.org/download.html

Si vous faites tourner une application .NET, vous pouvez utiliser Npgsql 2.0.11 ou supérieure, que vous pouvez télécharger de http://pgfoundry.org/frs/?group_id=1000140, et voir la description donnée sur l'entrée de blog de Francisco Figueiredo sur NpgSQL 2.0.11

Si mettre à jour votre pilote PostgreSQL n'est pas une option, alors vous pouvez définir la valeur par défaut à l'ancien comportement avec la modification suivante :

ALTER DATABASE mypostgisdb SET bytea_output='escape';

3.5.

J'ai essayé d'utiliser PgAdmin pour visualiser mon champ géométrique mais elle est vide, qu'arrive-t-il ?

PgAdmin ne montre rien concernant les grandes géométries. Quelles sont les meilleurs solutions pour vérifier que mes champs géométriques contiennent des données ?

-- Cela ne devrait retourner aucun résultat si tous les champs geom sont renseignés dans
SELECT le_champ FROM ma_table WHERE geom IS NULL
-- Pour connaître la taille de votre géométrie faîtes une requête de ce type
-- qui vous indiquera le plus grand nombre de points vous avez dans vos géométries
SELECT MAX(ST_NPoints(geom)) FROM sometable;

3.6.

Quelles sont les objets géométriques que je peux sauvegarder ?

Vous pouvez stocker des géométries Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon et GeometryCollection. Dans PostGIS 2.0 et ultérieur, vous pouvez aussi stocker des TINS et des surfaces polyhédrales ( Polyhedral Surfaces ) dans le type de base geometry. Ces types sont spécifiés dans le format Open GIS Well Known Text ( avec les extensions Z, M et ZM). Il y a trois types de données actuellement supportés. Le type geometry standard OGC utilise un système de coordonnées planaire pour les valeurs. Le type geography utilise un système de coordonnées géodésique, avec les calculs sur une sphère ou un sphéroïde. Le membre le plus récent de la famille des types de données spatiales de PostGIS est le raster pour stocker et analyser des données raster. Raster possède sa propre FAQ. Voir Chapter 10, Foire Aux Questions PostGIS Raster et Chapter 9, Raster Reference pour plus de détails.

3.7.

Je suis perdu. Dois-je utiliser un champs de type "geometry" ou "geography" ?

Réponse courte : geography est un type de données récent qui supporte les calculs de distance sur de grandes étendues, mais la plupart des calculs l'utilisant sont plus lent que ceux avec le type geometry. Si vous utilisez geography, vous n'avez pas besoin de vous préoccuper de systèmes de coordonnées planaires. Geography est en général meilleur si tout ce qui vous importe est de mesurer des distances et des longueurs et que vous avez des données couvrant le monde entier. Le type de données geometry est plus ancien et a beaucoup plus de fonctions disponibles, un plus grand support des outils externes, et des calculs qui sont généralement plus rapide -- parfois jusqu'à 10 fois plus rapide pour de grosses géométries . Geometry est meilleur si vous connaissez les systèmes de référence spatiale ou si vous avez de la donnée locale qui tient toute dans un seul système de référence spatial ( SRID), ou que vous faites beaucoup de traitement spatiaux. Note : il est assez simple de faire des conversions entre les deux types pour bénéficier des avantages de chacun. Se référer à Section 14.11, “PostGIS Function Support Matrix” pour voir ce qui est actuellement supporté et ce qui ne l'est pas pour chaque type.

Réponse plus longue ; référez vous à notre longue discussion sur Section 4.2.2, “When to use Geography Data type over Geometry data type” et matrice de type de fonction.

3.8.

J'ai d'autres questions plus avancées sur le type geography, comme la taille d'une région géographique que je peux mettre dans une colonne geography pour continuer à avoir des requêtes performantes. Ou bien s'il y a des limitations, comme aux pôles, ou si toutes les données doivent tenir dans un hémisphère (comme dans SQL server 2008), ou bien sur la vitesse d'exécution, etc.

Vos questions sont trop complexes et trop importantes pour être suffisamment détaillées ici. Référez vous à notre Section 4.2.3, “Geography Advanced FAQ”.

3.9.

Comment est-ce que j'insère un objet SIG dans une base de données ?

D'abords, vous devez créer une table avec une colonne de type "geometry" ou "geography" pour stocker vos données SIG. Stocker des données de type géographique est un petit différent que stocker des géométries. Référez vous à la page Section 4.2.1, “Geography Basics” pour les détails sur le stockage géographique.

Pour les géométries : connectez vous à votre base de données avec psql et tentez la commande SQL suivante :

CREATE TABLE gtest ( gid serial primary key, name varchar(20)
        , geom geometry(LINESTRING) );

Si la définition d'une colonne de géométrie échoue, vous n'avez probablement pas chargé les fonctions et les objets de PostGIS dans la base de données, ou vous utilisez une version de PostGIS antérieure à la 2.0. Voir

Puis, vous pouvez insérer une géométrie dans la table en utilisant une requête SQL insert. L'objet SIG lui même est formaté en utilisant le format "well-known text" de l'OpenGIS Consortium.

INSERT INTO gtest (ID, NAME, GEOM)
VALUES (
  1,
  'First Geometry',
  ST_GeomFromText('LINESTRING(2 3,4 5,6 5,7 8)')
);

Pour plus d'information sur les objets SIG, lisez le chapitre object reference.

Pour voir vos données SIG dans la table :

SELECT id, name, ST_AsText(geom) AS geom FROM gtest;

La valeur retournée doit ressembler à çà :

id | name           | geom
----+----------------+-----------------------------
  1 | First Geometry | LINESTRING(2 3,4 5,6 5,7 8)
(1 row)

3.10.

Comment est-ce que je construis une requête spatiale ?

De la même manière vous construisez n'importe quelle requête de base de données, comme une combinaison SQL de valeurs retournées, fonctions et tests booléens.

Pour les requêtes spatiales, il y a deux problèmes qui sont important à garder à l'esprit lors de la construction de vos requêtes : y a t'il un index spatial que vous pouvez utiliser et faîtes vous des calculs couteux sur un grand nombre de géométries.

En général, vous voulez utiliser l'"opérateur intersects" (&&) qui test si la boîte englobante de l'entité intersecte. La raison de l'utilité de l'opérateur && est que si un index spatial est disponible pour accélérer le test, l'opérateur && l'utilisera. Cela rend les requêtes beaucoup plus rapide.

Vous allez aussi utiliser les fonctions spatiales telles que Distance(), ST_Intersects(), ST_Contains() et ST_Within(), entre autres, pour affiner les résultats de votre recherche. La plupart des requêtes spatiales incluent à la fois un test sur les indexes et un test de fonction spatiale. Le test d'index sert à limiter le nombre de tuples pour analyser uniquement les tuples qui pourraient satisfaire les conditions posées. Les fonctions spatiales sont ensuite utilisées pour tester la condition exacte.

SELECT id, the_geom
FROM thetable
WHERE
  ST_Contains(the_geom,'POLYGON((0 0, 0 10, 10 10, 10 0, 0 0))');

3.11.

Comment est-ce que je peux accélérer les requêtes spatiales sur des grandes tables ?

Les requêtes rapides sur de grosse table est la raison d'etre des bases de donnes spatiales (avec la gestion des transactions) donc avoir un bon index est important.

Pour créer un index spatial sur une table avec un champ geometry, utilisez la fonction "CREATE INDEX" comme ci-après :

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

L'option "USING GIST" dit au serveur d'utiliser un index GiST (Generalized Search Tree).

[Note]

Les indexes GiST sont supposés sans perte. Les indexes avec pertes utilisent un objet proxy (dans le cas du spatial, une boîte englobante) pour construire l'index.

Vous devriez vous assurer également que le planificateur PostgreSQL possède suffisamment d'information sur votre index pour prendre des décisions rationnelles sur son utilisation. Pour cela, il faudra "calculer les statistiques" sur vos tables géométriques.

Pour les versions de PostgreSQL 8.0.x et les versions supérieures, lancez simplement la commande VACUUM ANALYZE.

Pour PostgreSQL 7.4.x et antérieur, lancez la commande SELECT UPDATE_GEOMETRY_STATS()

3.12.

Pourquoi est-ce que les indexes R-Tree PostgreSQL ne sont pas supportés ?

Les versions précédentes de PostGIS utilisaient des index de type R-Tree. Néanmoins, ces index R-Trees ont été supprimés depuis la version 0.6 et l'indexation spatiale est maintenant réalisée par un R-Tree-over-GiST.

Nos tests ont montré que la vitesse de recherche des indexes R-Tree et GiST est comparable. Les R-Tree PostgreSQL ont deux limitations qui les rendent inintéressants pour une utilisation avec des objets SIG (notez que ces limitations sont dues à l'implémentation native des R-Tree dans PostgreSQL, pas au concept de R-Tree en général):

  • Dans PostgreSQL, les index R-Tree ne peuvent pas gérer des objets qui sont plus grands que 8K en taille. Les index GiST le peuvent, en utilisant le truc "approximatif" de substituer la boîte d'encombrement à l'objet lui-même.

  • Dans PostgreSQL, les index R-Tree ne sont pas "null safe", donc construire un index sur une colonne geometry qui contient des géométries nulles échouera.

3.13.

Pourquoi est-il mieux d'utiliser la fonction AddGeometryColumn() et toutes les autres fonctionnalités de PostGIS ?

SI vous ne souhaitez pas utiliser les fonctions de l'OpenGIS, vous n'avez pas à le faire. Dans ce cas, créez simplement vos tables comme cela se faisait auparavant en spécifiant votre colonne géométrique lors du processus de création (CREATE). Toutes vos géométries auront alors -1 pour SRID et la table de métadonnées OpenGIS ne sera pas remplie correctement. Néanmoins, cela entraînera des erreurs pour la plupart des applications utilisant PostGIS et il est généralement conseillé d'utiliser AddGeometryColumn() pour créer votre table géométrique.

MapServer est l'une des applications qui utilise les métadonnées de la table geometry_columns. Plus spécifiquement, MapServer peut utiliser le SRID spécifié dans la table géométrique afin d'effectuer des reprojections à la volée conforme à la projection de la carte.

3.14.

Quelle est la meilleure méthode pour trouver les objets qui sont dans un certains rayons d'un autre objet ?

Pour utiliser la base de données de la manière la plus efficace possible, il est préférable de faire des requêtes de plus proches voisins qui combinent le test de distance et un test sur une étendue ("bounding box") : la bounding box utilise l'indexation spatiale, donnant accès rapide à un sous-ensemble de données sur lequel le test de distance est ensuite appliqué.

La fonction ST_DWithin(geometry, geometry, distance) est un moyen pratique pour effectuer un recherche indexée sur une distance. Cela fonctionne en créant une recherche rectangulaire suffisamment large pour contenir le rayon de distance, pour ensuite effectuer une recherche par distance exacte portant sur un sous-ensemble de résultats indexés.

Par exemple, pour trouver tous les objets qui sont dans les 100 mètres du POINT(1000 1000), la requête suivante fonctionne très bien :

SELECT * FROM geotable
WHERE ST_DWithin(geocolumn, 'POINT(1000 1000)', 100.0);

3.15.

Comment procéder à de la reprojection de coordonnées dans une requête ?

Pour procéder à une reprojection, les systèmes de coordonnée source et destination doivent être définis dans la table SPATIAL_REF_SYS, et les géométries reprojetées doivent déjà posséder un SRID. Une fois ceci fait, une reprojection est aussi simple que de se référer au SRID de destination désiré. Ci-dessous on projette une géométrie vers long lat NAD 83. Ceci ne fonctionne que si le srid de the_geom n'est pas -1 (référence spatiale non définie)

SELECT ST_Transform(the_geom,4269) FROM geotable;

3.16.

J'ai fait un ST_AsEWKT et un ST_AsText sur de grandes géométries et j'ai obtenu une réponse vide. Qu'est-il arrivé ?

Vous utilisez probablement PgAdmin ou un autre outils qui ne supportent pas les réponses longues. Si votre géométrie est très grosse, elle ne s'affichera pas dans ces outils. Utilisez PSQL si vous devez la visualiser ou exporter la en WKT.

--Pour vérifier le nombre de géométries qui sont réellement vides
SELECT count(gid) FROM geotable WHERE the_geom IS NULL;

3.17.

Quand je fais un ST_Intersects, il me répond que mes deux géométries ne s'intersectent pas alors que JE SAIS QUE C'EST LE CAS. Qu'arrive-t-il ?

Cela arrive généralement dans deux configurations. Votre géométrie est invalide -- vérifier avec ST_IsValid ou vous pensez que vos géométries s'intersectent du fait que ST_AsText tronque les chiffres et vous avez après de nombreuses décimales qui ne sont pas affichées.

3.18.

Je vais sortir un logiciel qui utilise PostGIS, est-ce que cela veut dire que mon logiciel doit être sous licence GPL tel que PostGIS ? Vais-je devoir publier tout mon code source si j'utilise PostGIS ?

Bien sur que non. Comme exemple, prenons une base de données Oracle tournant sur Linux. Linux est sous licence GPL, Oracle non. Est-ce qu'Oracle tournant sous Linux doit être distribué sous GPL ? Non. Donc votre programme peut utiliser une base de données PostgreSQL/PostGIS autant que vous voulez et être sous la licence que vous souhaitez.

La seule exception est si vous faites des modifications au code source de PostGIS, et que vous distribuez cette version modifiée de PostGIS. Dans ce cas vous devrez partager le code source de votre PostGIS modifié (mais pas le code des applications l'utilisant). Même dans ce cas limité, vous n'auriez à distribuer le code source qu'aux gens à qui vous distribuez des binaires. La GPL n'oblige pas à publier votre code source, mais uniquement à le partager avec les personnes à qui vous donnez des binaires.

Chapter 4. Using PostGIS: Data Management and Queries

4.1. GIS Objects

The GIS objects supported by PostGIS are a superset of the "Simple Features" defined by the OpenGIS Consortium (OGC). As of version 0.9, PostGIS supports all the objects and functions specified in the OGC "Simple Features for SQL" specification.

PostGIS extends the standard with support for 3DZ,3DM and 4D coordinates.

4.1.1. OpenGIS WKB and WKT

The OpenGIS specification defines two standard ways of expressing spatial objects: the Well-Known Text (WKT) form and the Well-Known Binary (WKB) form. Both WKT and WKB include information about the type of the object and the coordinates which form the object.

Examples of the text representations (WKT) of the spatial objects of the features are as follows:

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

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

The OpenGIS specification also requires that the internal storage format of spatial objects include a spatial referencing system identifier (SRID). The SRID is required when creating spatial objects for insertion into the database.

Input/Output of these formats are available using the following interfaces:

bytea WKB = ST_AsBinary(geometry);
text WKT = ST_AsText(geometry);
geometry = ST_GeomFromWKB(bytea WKB, SRID);
geometry = ST_GeometryFromText(text WKT, SRID);

For example, a valid insert statement to create and insert an OGC spatial object would be:

INSERT INTO geotable ( the_geom, the_name )
  VALUES ( ST_GeomFromText('POINT(-126.4 45.32)', 312), 'A Place');

4.1.2. PostGIS EWKB, EWKT and Canonical Forms

OGC formats only support 2d geometries, and the associated SRID is *never* embedded in the input/output representations.

PostGIS extended formats are currently superset of OGC one (every valid WKB/WKT is a valid EWKB/EWKT) but this might vary in the future, specifically if OGC comes out with a new format conflicting with our extensions. Thus you SHOULD NOT rely on this feature!

PostGIS EWKB/EWKT add 3dm,3dz,4d coordinates support and embedded SRID information.

Examples of the text representations (EWKT) of the extended spatial objects of the features are as follows.

  • 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 9, 9 0, 0 0))

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

Input/Output of these formats are available using the following interfaces:

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

For example, a valid insert statement to create and insert a PostGIS spatial object would be:

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

The "canonical forms" of a PostgreSQL type are the representations you get with a simple query (without any function call) and the one which is guaranteed to be accepted with a simple insert, update or copy. For the postgis 'geometry' type these are:

- Output
  - binary: EWKB
        ascii: HEXEWKB (EWKB in hex form)
- Input
  - binary: EWKB
        ascii: HEXEWKB|EWKT 

For example this statement reads EWKT and returns HEXEWKB in the process of canonical ascii input/output:

=# SELECT 'SRID=4;POINT(0 0)'::geometry;

geometry
----------------------------------------------------
01010000200400000000000000000000000000000000000000
(1 row)

4.1.3. SQL-MM Part 3

The SQL Multimedia Applications Spatial specification extends the simple features for SQL spec by defining a number of circularly interpolated curves.

The SQL-MM definitions include 3dm, 3dz and 4d coordinates, but do not allow the embedding of SRID information.

The well-known text extensions are not yet fully supported. Examples of some simple curved geometries are shown below:

  • CIRCULARSTRING(0 0, 1 1, 1 0)

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

    The CIRCULARSTRING is the basic curve type, similar to a LINESTRING in the linear world. A single segment required three points, the start and end points (first and third) and any other point on the arc. The exception to this is for a closed circle, where the start and end points are the same. In this case the second point MUST be the center of the arc, ie the opposite side of the circle. To chain arcs together, the last point of the previous arc becomes the first point of the next arc, just like in LINESTRING. This means that a valid circular string must have an odd number of points greated than 1.

  • COMPOUNDCURVE(CIRCULARSTRING(0 0, 1 1, 1 0),(1 0, 0 1))

    A compound curve is a single, continuous curve that has both curved (circular) 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.

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

    Example compound curve in a curve polygon: CURVEPOLYGON(COMPOUNDCURVE(CIRCULARSTRING(0 0,2 0, 2 1, 2 3, 4 3),(4 3, 4 5, 1 4, 0 0)), CIRCULARSTRING(1.7 1, 1.4 0.4, 1.6 0.4, 1.6 0.5, 1.7 1) )

    A CURVEPOLYGON is just like a polygon, with an outer ring and zero or more inner rings. The difference is that a ring can take the form of a circular string, linear string or compound string.

    As of PostGIS 1.4 PostGIS supports compound curves in a curve polygon.

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

    The MULTICURVE is a collection of curves, which can include linear strings, circular strings or compound strings.

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

    This is a collection of surfaces, which can be (linear) polygons or curve polygons.

[Note]

PostGIS prior to 1.4 does not support compound curves in a curve polygon, but PostGIS 1.4 and above do support the use of Compound Curves in a Curve Polygon.

[Note]

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

4.2. PostGIS Geography Type

The geography 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 type is a plane. The shortest path between two points on the plane is a straight line. That means calculations on geometries (areas, distances, lengths, intersections, etc) can be calculated using cartesian mathematics and straight line vectors.

The basis for the PostGIS geographic type is a sphere. The shortest path between two points on the sphere is a great circle arc. That means that calculations on geographies (areas, distances, lengths, intersections, etc) must be calculated on the sphere, using more complicated mathematics. For more accurate measurements, the calculations must take the actual spheroidal shape of the world into account, and the mathematics becomes very complicated indeed.

Because the underlying mathematics is much 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.

One restriction is that it only supports WGS 84 long lat (SRID:4326). It uses a new data type called geography. None of the GEOS functions support this new type. As a workaround one can convert back and forth between geometry and geography types.

The new geography type uses the PostgreSQL 8.3+ typmod definition format so that a table with a geography field can be added in a single step. All the standard OGC formats except for curves are supported.

4.2.1. Geography Basics

The geography type only supports the simplest of simple features. Standard geometry type data will autocast to geography if it is of SRID 4326. You can also use the EWKT and EWKB conventions to insert data.

  • POINT: Creating a table with 2d point geometry:

    CREATE TABLE testgeog(gid serial PRIMARY KEY, the_geog geography(POINT,4326) );

    Creating a table with z coordinate point

    CREATE TABLE testgeog(gid serial PRIMARY KEY, the_geog geography(POINTZ,4326) );
  • LINESTRING

  • POLYGON

  • MULTIPOINT

  • MULTILINESTRING

  • MULTIPOLYGON

  • GEOMETRYCOLLECTION

The new geography fields don't get registered in the geometry_columns. They get registered in a new view called geography_columns which is a view against the system catalogs so is always automatically kept up to date without need for an AddGeom... like function.

Now, check the "geography_columns" view and see that your table is listed.

You can create a new table with a GEOGRAPHY column using the CREATE TABLE syntax. Unlike GEOMETRY, there is no need to run a separate AddGeometryColumns() process to register the column in metadata.

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

Note that the location column has type GEOGRAPHY and that geography type supports two optional modifier: a type modifier that restricts the kind of shapes and dimensions allowed in the column; an SRID modifier that restricts the coordinate reference identifier to a particular number.

Allowable values for the type modifier are: POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING, MULTIPOLYGON. The modifier also supports dimensionality restrictions through suffixes: Z, M and ZM. So, for example a modifier of 'LINESTRINGM' would only allow line strings with three dimensions in, and would treat the third dimension as a measure. Similarly, 'POINTZM' would expect four dimensional data.

The SRID modifier is currently of limited use: only 4326 (WGS84) is allowed as a value. If you do not specify an SRID, the a value 0 (undefined spheroid) will be used, and all calculations will proceed using WGS84 anyways.

In the future, alternate SRIDs will allow calculations on spheroids other than WGS84.

Once you have created your table, you can see it in the GEOGRAPHY_COLUMNS table:

-- See the contents of the metadata view
SELECT * FROM geography_columns;

You can insert data into the table the same as you would if it was using a GEOMETRY column:

-- Add some data into the test table
INSERT INTO global_points (name, location) VALUES ('Town', ST_GeographyFromText('SRID=4326;POINT(-110 30)') );
INSERT INTO global_points (name, location) VALUES ('Forest', ST_GeographyFromText('SRID=4326;POINT(-109 29)') );
INSERT INTO global_points (name, location) VALUES ('London', ST_GeographyFromText('SRID=4326;POINT(0 49)') );

Creating an index works the same as GEOMETRY. 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 );

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

-- Show a distance query and note, London is outside the 1000km tolerance
  SELECT name FROM global_points WHERE ST_DWithin(location, ST_GeographyFromText('SRID=4326;POINT(-110 29)'), 1000000);

You can see the power of GEOGRAPHY in action by calculating the how close a plane flying from Seattle to London (LINESTRING(-122.33 47.606, 0.0 51.5)) comes to Reykjavik (POINT(-21.96 64.15)).

-- Distance calculation using GEOGRAPHY (122.2km)
  SELECT ST_Distance('LINESTRING(-122.33 47.606, 0.0 51.5)'::geography, 'POINT(-21.96 64.15)':: geography);

-- Distance calculation using GEOMETRY (13.3 "degrees")
  SELECT ST_Distance('LINESTRING(-122.33 47.606, 0.0 51.5)'::geometry, 'POINT(-21.96 64.15)':: geometry);

The GEOGRAPHY type calculates the true shortest distance over the sphere between Reykjavik and the great circle flight path between Seattle and London.

Great Circle mapper 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 might be called "degrees", but the result doesn't correspond to any true angular difference between the points, so even calling them "degrees" is inaccurate.

4.2.2. When to use Geography Data type over Geometry data type

The new GEOGRAPHY 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 type you choose should be conditioned on 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 14.11, “PostGIS Function Support Matrix” for compare between what is supported for Geography vs. Geometry. For a brief listing and description of Geography functions, refer to Section 14.4, “PostGIS Geography Support Functions”

4.2.3. Geography Advanced FAQ

4.2.3.1. Do you calculate on the sphere or the spheroid?
4.2.3.2. What about the date-line and the poles?
4.2.3.3. What is the longest arc you can process?
4.2.3.4. Why is it so slow to calculate the area of Europe / Russia / insert big geographic region here ?

4.2.3.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.2.3.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.2.3.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.2.3.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. Just because you *can* store all of Europe in one polygon doesn't mean you *should*.

4.3. Using OpenGIS Standards

The OpenGIS "Simple Features Specification for SQL" defines standard GIS object types, the functions required to manipulate them, and a set of meta-data tables. In order to ensure that meta-data remain consistent, operations such as creating and removing a spatial column are carried out through special procedures defined by OpenGIS.

There are two OpenGIS meta-data tables: SPATIAL_REF_SYS and GEOMETRY_COLUMNS. The SPATIAL_REF_SYS table holds the numeric IDs and textual descriptions of coordinate systems used in the spatial database.

4.3.1. The SPATIAL_REF_SYS Table and Spatial Reference Systems

The spatial_ref_sys table is a PostGIS included and OGC compliant database table that lists over 3000 known spatial reference systems and details needed to transform/reproject between them.

Although the PostGIS spatial_ref_sys table contains over 3000 of the more commonly used spatial reference system definitions that can be handled by the proj library, it does not contain all known to man and you can even define your own custom projection if you are familiar with proj4 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.

An excellent resource for finding spatial reference systems not defined in the core set is http://spatialreference.org/

Some of the more 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, Spatial reference systems for each NAD 83, WGS 84 UTM zone - UTM zones are one of the most ideal for measurement, but only cover 6-degree regions.

Various US state plane spatial reference systems (meter or feet based) - usually one or 2 exists per US state. Most of the meter ones are in the core set, but many of the feet based ones or ESRI created ones you will need to pull from spatialreference.org.

For details on determining which UTM zone to use for your area of interest, check out the utmzone PostGIS plpgsql helper function.

The SPATIAL_REF_SYS table definition is as follows:

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 SPATIAL_REF_SYS columns are as follows:

SRID

An integer value that uniquely identifies the Spatial Referencing 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" would be 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 where the EPSG projection code would go.

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 listing of EPSG projection codes and their corresponding WKT representations, see http://www.opengeospatial.org/. For a discussion of WKT in general, see the OpenGIS "Coordinate Transformation Services Implementation Specification" at http://www.opengeospatial.org/standards. For information on the European Petroleum Survey Group (EPSG) and their database of spatial reference systems, see http://www.epsg.org.

PROJ4TEXT

PostGIS uses the Proj4 library to provide coordinate transformation capabilities. The PROJ4TEXT column contains the Proj4 coordinate definition string for a particular SRID. For example:

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

For more information about, see the Proj4 web site at http://trac.osgeo.org/proj/. The spatial_ref_sys.sql file contains both SRTEXT and PROJ4TEXT definitions for all EPSG projections.

4.3.2. The GEOMETRY_COLUMNS VIEW

In versions of PostGIS prior to 2.0.0, geometry_columns was a table that could be directly edited, and sometimes got out of synch with the actual definition of the geometry columns. In PostGIS 2.0.0, GEOMETRY_COLUMNS became a view with the same front-facing structure as prior versions, but reading from database system catalogs Its structure is as follows:

\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 column meanings have not changed from prior versions and are:

F_TABLE_CATALOG, F_TABLE_SCHEMA, F_TABLE_NAME

The fully qualified name of the feature table containing the geometry column. Note that the terms "catalog" and "schema" are Oracle-ish. There is not 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 spatial dimension (2, 3 or 4 dimensional) 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.

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.

[Note]

This attribute is (probably) not part of the OpenGIS specification, but is required for ensuring type homogeneity.

4.3.3. Creating a Spatial Table

Creating a table with spatial data, can be done in one step. As shown in the following example which creates a roads table with a 2D linestring geometry column in WGS84 long lat

CREATE TABLE ROADS ( ID int4
                , ROAD_NAME varchar(25), geom geometry(LINESTRING,4326) );

We can add additional columns using standard ALTER TABLE command as we do in this next example where we add a 3-D linestring.

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

For backwards compability, you can still create a spatial table in two stages using the management functions.

  • Create a normal non-spatial table.

    For example: CREATE TABLE ROADS ( ID int4, ROAD_NAME varchar(25) )

  • Add a spatial column to the table using the OpenGIS "AddGeometryColumn" function. Refer to AddGeometryColumn for more details.

    The syntax is:

    AddGeometryColumn(
      <schema_name>,
      <table_name>,
      <column_name>,
      <srid>,
      <type>,
      <dimension>
    )

    Or, using current schema:

    AddGeometryColumn(
      <table_name>,
      <column_name>,
      <srid>,
      <type>,
      <dimension>
    )

    Example1: SELECT AddGeometryColumn('public', 'roads', 'geom', 423, 'LINESTRING', 2)

    Example2: SELECT AddGeometryColumn( 'roads', 'geom', 423, 'LINESTRING', 2)

Here is an example of SQL used to create a table and add a spatial column (assuming that an SRID of 128 exists already):

CREATE TABLE parks (
  park_id    INTEGER,
  park_name  VARCHAR,
  park_date  DATE,
  park_type  VARCHAR
);
SELECT AddGeometryColumn('parks', 'park_geom', 128, 'MULTIPOLYGON', 2 );

Here is another example, using the generic "geometry" type and the undefined SRID value of 0:

CREATE TABLE roads (
  road_id INTEGER,
  road_name VARCHAR
);
SELECT AddGeometryColumn( 'roads', 'roads_geom', 0, 'GEOMETRY', 3 );

4.3.4. Manually Registering Geometry Columns in geometry_columns

The AddGeometryColumn() approach creates a geometry column of specified type. This type and dimension are queryable from the geometry_columns view. Starting with PostGIS 2.0, geometry_columns is no longer editable and all geometry columns are autoregistered.

If your geometry columns were created as generic in a table or view and no constraints applied, they will not have a dimension, type or srid in geometry_columns views, but will still be listed.

Two of the cases where this may happen, but you can't use AddGeometryColumn, is in 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 in PostGIS 2.0+ 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 in PostGIS 2.0+
-- 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
-- like so
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 that this approach will work for both PostGIS 2.0+ and PostGIS 1.4+
-- For PostGIS 2.0 it will also change the underlying structure of the table to
-- to make the column typmod based.
-- For PostGIS prior to 2.0, this technique can also be used to register views
SELECT populate_geometry_columns('myschema.my_special_pois'::regclass);

--If you are using PostGIS 2.0 and for whatever reason, you
-- you need the old constraint based definition behavior
-- (such as case of inherited tables where all children do not have the same type and srid)
-- set new 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 varchar(20)
   , 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, we 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.3.5. Ensuring OpenGIS compliancy of geometries

PostGIS is compliant with the Open Geospatial Consortium’s (OGC) OpenGIS Specifications. As such, many PostGIS methods require, or more accurately, assume that geometries that are operated on are both simple and 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.

According to the OGC Specifications, a simple geometry is one that has no anomalous geometric points, such as self intersection or self tangency and primarily refers to 0 or 1-dimensional geometries (i.e. [MULTI]POINT, [MULTI]LINESTRING). Geometry validity, on the other hand, primarily refers to 2-dimensional geometries (i.e. [MULTI]POLYGON) and defines the set of assertions that characterizes a valid polygon. The description of each geometric class includes specific conditions that further detail geometric simplicity and validity.

A POINT is inheritably 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, in which case it is referred to as a linear ring and additionally considered closed).

(a)

(b)

(c)

(d)

(a) and (c) are simple LINESTRINGs, (b) and (d) are not.

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)

(f)

(g)

(e) and (f) are simple MULTILINESTRINGs, (g) is not.

By definition, a POLYGON is always simple. It is valid if no two rings in the boundary (made up of an exterior ring and interior rings) cross. The boundary of a POLYGON may intersect at a POINT but only as a tangent (i.e. not on a line). A POLYGON may not have cut lines or spikes and the interior rings must be contained entirely within the exterior ring.

(h)

(i)

(j)

(k)

(l)

(m)

(h) and (i) are valid POLYGONs, (j-m) cannot be represented as single POLYGONs, but (j) and (m) could be represented as a valid MULTIPOLYGON.

A MULTIPOLYGON is valid if and only if all of its elements are valid and the interiors of no two elements intersect. The boundaries of any two elements may touch, but only at a finite number of POINTs.

(n)

(o)

(p)

(n) and (o) are not valid MULTIPOLYGONs. (p), however, is valid.

Most of the functions implemented by the GEOS library rely on the assumption that your geometries are valid as specified by the OpenGIS Simple Feature Specification. To check simplicity or validity of geometries you can use the ST_IsSimple() and ST_IsValid()

-- Typically, it doesn't make sense to check
-- for validity on linear features since it will always return TRUE.
-- But in this example, PostGIS extends the definition of the OGC IsValid
-- by returning false if a LineString has less than 2 *distinct* vertices.
gisdb=# SELECT
   ST_IsValid('LINESTRING(0 0, 1 1)'),
   ST_IsValid('LINESTRING(0 0, 0 0, 0 0)');

 st_isvalid | st_isvalid
------------+-----------
      t     |     f

By default, PostGIS does not apply this validity check on geometry input, because testing for validity needs lots of CPU time for complex geometries, especially polygons. If you do not trust your data sources, you can manually enforce such a check to your tables by adding a check constraint:

ALTER TABLE mytable
  ADD CONSTRAINT geometry_valid_check
        CHECK (ST_IsValid(the_geom));

If you encounter any strange error messages such as "GEOS Intersection() threw an error!" or "JTS Intersection() threw an error!" when calling PostGIS functions with valid input geometries, you likely found an error in either PostGIS or one of the libraries it uses, and you should contact the PostGIS developers. The same is true if a PostGIS function returns an invalid geometry for valid input.

[Note]

Strictly compliant OGC geometries cannot have Z or M values. The ST_IsValid() function won't consider higher dimensioned geometries invalid! Invocations of AddGeometryColumn() will add a constraint checking geometry dimensions, so it is enough to specify 2 there.

4.3.6. Dimensionally Extended 9 Intersection Model (DE-9IM)

It is sometimes the case that the typical spatial predicates (ST_Contains, ST_Crosses, ST_Intersects, ST_Touches, ...) are insufficient in and of themselves to adequately provide that desired spatial filter.

For example, consider a linear dataset representing a road network. It may be the task of a GIS analyst to identify all road segments that cross each other, not at a point, but on a line, perhaps invalidating some business rule. In this case, ST_Crosses does not adequately provide the necessary spatial filter since, for linear features, it returns true only where they cross at a point.

One two-step solution might be to first perform the actual intersection (ST_Intersection) of pairs of road segments that spatially intersect (ST_Intersects), and then compare the intersection's ST_GeometryType with 'LINESTRING' (properly dealing with cases that return GEOMETRYCOLLECTIONs of [MULTI]POINTs, [MULTI]LINESTRINGs, etc.).

A more elegant / faster solution may indeed be desirable.

A second [theoretical] example may be that of a GIS analyst trying to locate all wharfs or docks that intersect a lake's boundary on a line and where only one end of the wharf is up on shore. In other words, where a wharf is within, but not completely within a lake, intersecting the boundary of a lake on a line, and where the wharf's endpoints are both completely within and on the boundary of the lake. The analyst may need to use a combination of spatial predicates to isolate the sought after features:

So enters the Dimensionally Extended 9 Intersection Model, or DE-9IM for short.

4.3.6.1. Theory

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

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 are the two endpoints. For POLYGONs, the boundary is the linework that make up the exterior and interior rings.

Interior

The interior of a geometry are those points of a geometry that are left when the boundary is removed. For POINTs, the interior is the POINT itself. The interior of a LINESTRING are the set of real points between the endpoints. For POLYGONs, the interior is the areal surface inside the polygon.

Exterior

The exterior of a geometry is the universe, an areal surface, not on the interior or boundary of the geometry.

Given geometry a, where the I(a), B(a), and E(a) are the Interior, Boundary, and Exterior of a, the mathematical representation of the matrix 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) )

Where dim(a) is the dimension of a as specified by ST_Dimension but has the domain of {0,1,2,T,F,*}

  • 0 => point

  • 1 => line

  • 2 => area

  • T => {0,1,2}

  • F => empty set

  • * => don't care

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

 

 InteriorBoundaryExterior
Interior

dim(...) = 2

dim(...) = 1

dim(...) = 2

Boundary

dim(...) = 1

dim(...) = 0

dim(...) = 1

Exterior

dim(...) = 2

dim(...) = 1

dim(...) = 2

Read from left to right and from top to bottom, the dimensional matrix is represented, '212101212'.

A relate matrix that would therefore represent our first example of two lines that intersect on a line would be: '1*1***1**'

-- Identify road segments that cross on 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**');

A relate matrix that represents the second example of wharfs partly on the lake's shoreline would be '102101FF2'

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

For more information or reading, see:

4.4. Loading GIS (Vector) Data

Once you have created a spatial table, you are ready to upload GIS data to the database. Currently, there are two ways to get data into a PostGIS/PostgreSQL database: using formatted SQL statements or using the Shape file loader/dumper.

4.4.1. Loading Data Using SQL

If you can convert your data to a text representation, then using formatted SQL might be the easiest way to get your data into PostGIS. As with Oracle and other SQL databases, data can be bulk loaded by piping a large text file full of SQL "INSERT" statements into the SQL terminal monitor.

A data upload file (roads.sql for example) might look like this:

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

The data file can be piped into PostgreSQL very easily using the "psql" SQL terminal monitor:

psql -d [database] -f roads.sql

4.4.2. shp2pgsql: Using the ESRI Shapefile Loader

The shp2pgsql data loader converts ESRI Shape files into SQL suitable for insertion into a PostGIS/PostgreSQL database either in geometry or geography format. The loader has several operating modes distinguished by command line flags:

In addition to the shp2pgsql command-line loader, there is an shp2pgsql-gui graphical interface with most of the options as the command-line loader, but 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) These are mutually exclusive options:

-c

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

-a

Appends data from the Shape file 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 Shape file.

-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%gt;:]<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. FROM_SRID cannot be specified with -D.

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

An example session using the loader to create an input file and uploading 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 upload can be done all in one step using UNIX pipes:

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

4.5. Retrieving GIS Data

Data can be extracted from the database using either SQL or the Shape file loader/dumper. In the section on SQL we will discuss some of the operators available to do comparisons and queries on spatial tables.

4.5.1. Using SQL to Retrieve Data

The most straightforward means of pulling data out of the database is to use a SQL select query to reduce the number of RECORDS and COLUMNS returned 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)

However, there will be times when some kind of restriction is necessary to cut down the number of fields returned. In the case of attribute-based restrictions, just use the same SQL syntax as normal with a non-spatial table. In the case of spatial restrictions, the following operators are available/useful:

&&

This operator tells whether the bounding box of one geometry intersects the bounding box of another.

ST_OrderingEquals

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

=

This operator is a little more naive, it only tests whether the bounding boxes of two geometries are the same.

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 by using the "ST_GeomFromText()" function. The 312 is a fictitious spatial reference system that matches our data. So, for example:

SELECT road_id, road_name
  FROM roads
  WHERE ST_OrderingEquals(roads_geom , ST_GeomFromText('LINESTRING(191232 243118,191108 243242)',312) ) ;

The above query would return the single record from the "ROADS_GEOM" table in which the geometry was equal to that value.

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.

SELECT road_id, road_name
FROM roads
WHERE roads_geom && ST_GeomFromText('POLYGON((...))',312);

The above query will use the bounding box of the polygon for comparison purposes.

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. 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.5.2. Using the Dumper

The pgsql2shp table dumper connects directly 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.

-d

For backward compatibility: write a 3-dimensional shape file when dumping from old (pre-1.0.0) postgis databases (the default is to write a 2-dimensional shape file in that case). Starting from postgis-1.0.0+, dimensions are fully encoded.

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

Indexes are what make using a spatial database for large data sets possible. Without indexing, any search for a feature would require a "sequential scan" of every record in the database. Indexing speeds up searching by organizing the data into a search tree which can be quickly traversed to find a particular record. PostgreSQL supports three kinds of indexes by default: B-Tree indexes, R-Tree indexes, and GiST indexes.

  • B-Trees are used for data which can be sorted along one axis; for example, numbers, letters, dates. GIS data cannot be rationally sorted along one axis (which is greater, (0,0) or (0,1) or (1,0)?) so B-Tree indexing is of no use for us.

  • R-Trees break up data into rectangles, and sub-rectangles, and sub-sub rectangles, etc. R-Trees are used by some spatial databases to index GIS data, but the PostgreSQL R-Tree implementation is not as robust as the GiST implementation.

  • GiST (Generalized Search Trees) 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 GIS data.

4.6.1. GiST Indexes

GiST stands for "Generalized Search Tree" and is a generic form of indexing. In addition to GIS indexing, GiST is 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.

Once a GIS 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 supported in PostGIS 2.0+ 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: on tables of around 1 million rows, on a 300MHz Solaris machine, we have found building a GiST index takes about 1 hour. After building an index, it is important to force PostgreSQL to collect table statistics, which are used to optimize query plans:

VACUUM ANALYZE [table_name] [(column_name)];
-- This is only needed for PostgreSQL 7.4 installations and below
SELECT UPDATE_GEOMETRY_STATS([table_name], [column_name]);

GiST indexes have two advantages over R-Tree indexes in PostgreSQL. Firstly, GiST indexes are "null safe", meaning they can index columns which include null values. Secondly, GiST indexes support the concept of "lossiness" which is important when dealing with GIS objects larger than the PostgreSQL 8K page size. Lossiness allows PostgreSQL to store only the "important" part of an object in an index -- in the case of GIS objects, just the bounding box. GIS objects larger than 8K will cause R-Tree indexes to fail in the process of being built.

4.6.2. BRIN Indexes

BRIN stands for "Block Range Index" and is a generic form of indexing that has been introduced in PostgreSQL 9.5. BRIN is a lossy kind of index, and its main usage is to provide a compromise for both read and write performance. Its primary goal is to handle very large tables for which some of the columns have some natural correlation with their physical location within the table. In addition to GIS indexing, BRIN is used to speed up searches on various kinds of regular or irregular data structures (integer, arrays etc).

Once a GIS 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). GiST indexes are really 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 storage size, and the penalty in write workload. Otherwise, BRIN index can be considered as an alternative.

The idea of a BRIN index is to store only the bouding box englobing all the geometries contained in all the rows in a set of table blocks, called a range. Obviously, this indexing method will only be efficient if the data is physically ordered in a way where the resulting bouding boxes for block ranges will be mutually exclusive. The resulting index will be really small, but will be less efficient than a GiST index in many cases.

Building a BRIN index is way less intensive than building a GiST index. It's quite common to build a BRIN index in more than ten time less than a GiST index would have required. As a BRIN index only store one bouding box for one to many table blocks, it's pretty common to consume up to a thousand time less disk space for this kind of indexes.

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 help to get better performance.

The syntax for building a BRIN index on a "geometry" column is as follows:

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

The above syntax will always build a 2D-index. To get a 3d-dimensional index, you can create one using this syntax

CREATE INDEX [indexname] ON [tablename] USING BRIN ([geometryfield] 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 ([geometryfield] brin_geometry_inclusion_ops_4d);

These above syntaxes will use the default number or block in a range, which is 128. To specify the number of blocks you want to summarise in a range, you can create one using this syntax

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

Also, keep in mind that a BRIN index will only store one index value 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 drop of performance by choosing the operator class whith the least number of dimensions of the stored geometries

Also the "geography" datatype is supported for BRIN indexing. The syntax for building a BRIN index on a "geography" column is as follows:

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

The above syntax will always build a 2D-index for geospatial objetcs on the spheroid.

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

VACUUM ANALYZE [table_name] [(column_name)];
-- This is only needed for PostgreSQL 7.4 installations and below
SELECT UPDATE_GEOMETRY_STATS([table_name], [column_name]);

4.6.3. Using Indexes

Ordinarily, indexes invisibly speed up data access: once the index is built, the query planner transparently decides when to use index information to speed up a query plan. Unfortunately, the PostgreSQL query planner does not optimize the use of GiST indexes well, so sometimes searches which should use a spatial index instead default to a sequence scan of the whole table.

If you find your spatial indexes are not being used (or your attribute indexes, for that matter) there are a couple things you can do:

  • Firstly, 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. For PostgreSQL 7.4 installations and below this is done by running update_geometry_stats([table_name, column_name]) (compute distribution) and VACUUM ANALYZE [table_name] [column_name] (compute number of values). Starting with PostgreSQL 8.0 running VACUUM ANALYZE will do both operations. You should regularly vacuum your databases anyways -- many PostgreSQL DBAs have VACUUM run as an off-peak cron job on a regular basis.

  • If vacuuming does not work, you can force the planner to use the index information by using the SET ENABLE_SEQSCAN=OFF command. You should only use this command sparingly, and only on spatially indexed queries: generally speaking, the planner knows better than you do about when to use normal B-Tree indexes. Once you have run your query, you should consider setting ENABLE_SEQSCAN back on, so that other queries will utilize the planner as normal.

    [Note]

    As of version 0.6, it should not be necessary to force the planner to use the index with ENABLE_SEQSCAN.

  • If you find the planner wrong about the cost of sequential vs index scans try reducing the value of random_page_cost in postgresql.conf or using SET random_page_cost=#. Default value for the parameter is 4, try setting it to 1 or 2. Decrementing the value makes the planner more inclined of using Index scans.

4.7. Complex Queries

The raison d'etre of spatial database functionality is performing queries inside the database which would ordinarily require desktop GIS functionality. Using PostGIS effectively requires knowing what spatial functions are available, and ensuring that appropriate indexes are in place to provide good performance. The SRID of 312 used in these examples is purely for demonstration. You should be using a REAL SRID listed in the the spatial_ref_sys table and one that matches the projection of your data. If your data has no spatial reference system specified, you should be THINKING very thoughtfully why it doesn't and maybe it should. If your reason is because you are modeling something that doesn't have a geographic spatial reference system defined such as the internals of a molecule or a good location on Mars to transport the human race in the event of a nuclear holocaust, then simply leave out the SRID or make one up and insert it in the spatial_ref_sys table.

4.7.1. Taking Advantage of Indexes

When constructing a query it is important to remember that only the bounding-box-based operators such as && can take advantage of the GiST spatial index. Functions such as ST_Distance() cannot use the index to optimize their operation. For example, the following query would be quite slow on a large table:

SELECT the_geom
FROM geom_table
WHERE ST_Distance(the_geom, ST_GeomFromText('POINT(100000 200000)', 312)) < 100

This query is selecting 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 our specified point, ie. one ST_Distance() calculation for each row in the table. We can avoid this by using the && operator to reduce the number of distance calculations required:

SELECT the_geom
FROM geom_table
WHERE ST_DWithin(the_geom,  ST_MakeEnvelope(90900, 190900, 100100, 200100,312), 100)

This query selects the same geometries, but it does it in a more efficient way. Assuming there is a GiST index on the_geom, the query planner will recognize that it can use the index to reduce the number of rows before calculating the result of the ST_distance() function. Notice that the ST_MakeEnvelope geometry which is used in the && operation is a 200 unit square box centered on the original point - this is our "query box". The && operator uses the index to quickly reduce the result set down to only those geometries which have bounding boxes that overlap the "query box". Assuming that our query box is much smaller than the extents of the entire geometry table, this will drastically reduce the number of distance calculations that need to be done.

[Note]Change in Behavior

As of PostGIS 1.3.0, most of the Geometry Relationship Functions, with the notable exceptions of ST_Disjoint and ST_Relate, include implicit bounding box overlap operators.

4.7.2. Examples of Spatial SQL

The examples in this section will make use of two tables, a table of linear roads, and a table of polygonal municipality boundaries. The table definitions for the bc_roads table is:

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

The table definition for the bc_municipality table is:

Column     | Type              | Description
-----------+-------------------+-------------------
gid        | integer           | Unique ID
code       | integer           | Unique ID
name       | character varying | City / Town Name
the_geom   | geometry          | Location Geometry (Polygon)
4.7.2.1. What is the total length of all roads, expressed in kilometers?
4.7.2.2. How large is the city of Prince George, in hectares?
4.7.2.3. What is the largest municipality in the province, by area?
4.7.2.4. What is the length of roads fully contained within each municipality?
4.7.2.5. Create a new table with all the roads within the city of Prince George.
4.7.2.6. What is the length in kilometers of "Douglas St" in Victoria?
4.7.2.7. What is the largest municipality polygon that has a hole?

4.7.2.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(the_geom))/1000 AS km_roads FROM bc_roads;

km_roads
------------------
70842.1243039643
(1 row)

4.7.2.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 area):

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

hectares
------------------
32657.9103824927
(1 row)

4.7.2.3.

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

This query brings a spatial measurement into the query condition. There are several ways of approaching this problem, but the most efficient is below:

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

name           | hectares
---------------+-----------------
TUMBLER RIDGE  | 155020.02556131
(1 row)

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 we could separately index for performance. By ordering the results in a descending direction, and them using the PostgreSQL "LIMIT" command we can easily pick off the largest value without using an aggregate function like max().

4.7.2.4.

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

This is an example of a "spatial join", because we are bringing together data from two tables (doing a join) but using a spatial interaction condition ("contained") as the join condition rather than the usual relational approach of joining on a common key:

SELECT
  m.name,
  sum(ST_Length(r.the_geom))/1000 as roads_km
FROM
  bc_roads AS r,
  bc_municipality AS m
WHERE
  ST_Contains(m.the_geom,r.the_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 our particular example table). For smaller overlays (several thousand records on several hundred) the response can be very fast.

4.7.2.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 actually 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.the_geom, m.the_geom) AS intersection_geom,
  ST_Length(r.the_geom) AS rd_orig_length,
  r.*
FROM
  bc_roads AS r,
  bc_municipality AS m
WHERE  m.name = 'PRINCE GEORGE' AND ST_Intersects(r.the_geom, m.the_geom);

4.7.2.6.

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

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

kilometers
------------------
4.89151904172838
(1 row)

4.7.2.7.

What is the largest municipality polygon that has a hole?

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

gid  | name         | area
-----+--------------+------------------
12   | SPALLUMCHEEN | 257374619.430216
(1 row)

Chapter 5. Raster Data Management, Queries, and Applications

5.1. Loading and Creating Rasters

For most use cases, you will create PostGIS rasters by loading existing raster files using the packaged raster2pgsql raster loader.

5.1.1. Using raster2pgsql to load rasters

The raster2pgsql is a raster loader executable that loads GDAL supported raster formats into sql suitable for loading into a PostGIS raster table. It is capable of loading folders of raster files as well as creating overviews of rasters.

Since the raster2pgsql is compiled as part of PostGIS most often (unless you compile your own GDAL library), the raster types supported by the executable will be the same as those compiled in the GDAL dependency library. To get a list of raster types your particular raster2pgsql supports use the -G switch. These should be the same as those provided by your PostGIS install documented here ST_GDALDrivers if you are using the same gdal library for both.

[Note]

The older version of this tool was a python script. The executable has replaced the python script. If you still find the need for the Python script Examples of the python one can be found at GDAL PostGIS Raster Driver Usage. Please note that the raster2pgsql python script may not work with future versions of PostGIS raster and is no longer supported.

[Note]

When creating overviews of a specific factor from a set of rasters that are aligned, it is possible for the overviews to not align. Visit http://trac.osgeo.org/postgis/ticket/1764 for an example where the overviews do not align.

EXAMPLE USAGE:

raster2pgsql raster_options_go_here raster_file someschema.sometable > out.sql

-?

Display help screen. Help will also display if you don't pass in any arguments.

-G

Print the supported raster formats.

(c|a|d|p) These are mutually exclusive options:

-c

Create new table and populate it with raster(s), this is the default mode

-a

Append raster(s) to an existing table.

-d

Drop table, create new one and populate it with raster(s)

-p

Prepare mode, only create the table.

Raster processing: Applying constraints for proper registering in raster catalogs

-C

Apply raster constraints -- srid, pixelsize etc. to ensure raster is properly registered in raster_columns view.

-x

Disable setting the max extent constraint. Only applied if -C flag is also used.

-r

Set the constraints (spatially unique and coverage tile) for regular blocking. Only applied if -C flag is also used.

Raster processing: Optional parameters used to manipulate input raster dataset

-s <SRID>

Assign output raster with specified SRID. If not provided or is zero, raster's metadata will be checked to determine an appropriate SRID.

-b BAND

Index (1-based) of band to extract from raster. For more than one band index, separate with comma (,). If unspecified, all bands of raster will be extracted.

-t TILE_SIZE

Cut raster into tiles to be inserted one per table row. TILE_SIZE is expressed as WIDTHxHEIGHT or set to the value "auto" to allow the loader to compute an appropriate tile size using the first raster and applied to all rasters.

-P

Pad right-most and bottom-most tiles to guarantee that all tiles have the same width and height.

-R, --register

Register the raster as a filesystem (out-db) raster.

Only the metadata of the raster and path location to the raster is stored in the database (not the pixels).

-l OVERVIEW_FACTOR

Create overview of the raster. For more than one factor, separate with comma(,). Overview table name follows the pattern o_overview factor_table, where overview factor is a placeholder for numerical overview factor and table is replaced with the base table name. Created overview is stored in the database and is not affected by -R. Note that your generated sql file will contain both the main table and overview tables.

-N NODATA

NODATA value to use on bands without a NODATA value.

Optional parameters used to manipulate database objects

-q

Wrap PostgreSQL identifiers in quotes

-f COLUMN

Specify name of destination raster column, default is 'rast'

-F

Add a column with the name of the file

-n COLUMN

Specify the name of the filename column. Implies -F.

-q

Wrap PostgreSQL identifiers in quotes.

-I

Create a GiST index on the raster column.

-M

Vacuum analyze the raster table.

-k

Skip NODATA value checks for each raster band.

-T tablespace

Specify the tablespace for the new table. Note that indices (including the primary key) will still use the default tablespace unless the -X flag is also used.

-X tablespace

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

-Y

Use copy statements instead of insert statements.

-e

Execute each statement individually, do not use a transaction.

-E ENDIAN

Control endianness of generated binary output of raster; specify 0 for XDR and 1 for NDR (default); only NDR output is supported now

-V version

Specify version of output format. Default is 0. Only 0 is supported at this time.

An example session using the loader to create an input file and uploading it chunked in 100x100 tiles might look like this:

[Note]

You can leave the schema name out e.g demelevation instead of public.demelevation and the raster table will be created in the default schema of the database or user

raster2pgsql -s 4326 -I -C -M *.tif -F -t 100x100 public.demelevation 
> elev.sql
psql -d gisdb -f elev.sql

A conversion and upload can be done all in one step using UNIX pipes:

raster2pgsql -s 4326 -I -C -M *.tif -F -t 100x100 public.demelevation | psql -d gisdb

Load rasters Massachusetts state plane meters aerial tiles into a schema called aerial and create a full view, 2 and 4 level overview tables, use copy mode for inserting (no intermediary file just straight to db), and -e don't force everything in a transaction (good if you want to see data in tables right away without waiting). Break up the rasters into 128x128 pixel tiles and apply raster constraints. Use copy mode instead of table insert. (-F) Include a field called filename to hold the name of the file the tiles were cut from.

raster2pgsql -I -C -e -Y -F -s 26986 -t 128x128  -l 2,4 bostonaerials2008/*.jpg aerials.boston | psql -U postgres -d gisdb -h localhost -p 5432
--get a list of raster types supported:
raster2pgsql -G

The -G commands outputs a list something like

Available GDAL raster formats:
  Virtual Raster
  GeoTIFF
  National Imagery Transmission Format
  Raster Product Format TOC format
  ECRG TOC format
  Erdas Imagine Images (.img)
  CEOS SAR Image
  CEOS Image
  JAXA PALSAR Product Reader (Level 1.1/1.5)
  Ground-based SAR Applications Testbed File Format (.gff)
  ELAS
  Arc/Info Binary Grid
  Arc/Info ASCII Grid
  GRASS ASCII Grid
  SDTS Raster
  DTED Elevation Raster
  Portable Network Graphics
  JPEG JFIF
  In Memory Raster
  Japanese DEM (.mem)
  Graphics Interchange Format (.gif)
  Graphics Interchange Format (.gif)
  Envisat Image Format
  Maptech BSB Nautical Charts
  X11 PixMap Format
  MS Windows Device Independent Bitmap
  SPOT DIMAP
  AirSAR Polarimetric Image
  RadarSat 2 XML Product
  PCIDSK Database File
  PCRaster Raster File
  ILWIS Raster Map
  SGI Image File Format 1.0
  SRTMHGT File Format
  Leveller heightfield
  Terragen heightfield
  USGS Astrogeology ISIS cube (Version 3)
  USGS Astrogeology ISIS cube (Version 2)
  NASA Planetary Data System
  EarthWatch .TIL
  ERMapper .ers Labelled
  NOAA Polar Orbiter Level 1b Data Set
  FIT Image
  GRIdded Binary (.grb)
  Raster Matrix Format
  EUMETSAT Archive native (.nat)
  Idrisi Raster A.1
  Intergraph Raster
  Golden Software ASCII Grid (.grd)
  Golden Software Binary Grid (.grd)
  Golden Software 7 Binary Grid (.grd)
  COSAR Annotated Binary Matrix (TerraSAR-X)
  TerraSAR-X Product
  DRDC COASP SAR Processor Raster
  R Object Data Store
  Portable Pixmap Format (netpbm)
  USGS DOQ (Old Style)
  USGS DOQ (New Style)
  ENVI .hdr Labelled
  ESRI .hdr Labelled
  Generic Binary (.hdr Labelled)
  PCI .aux Labelled
  Vexcel MFF Raster
  Vexcel MFF2 (HKV) Raster
  Fuji BAS Scanner Image
  GSC Geogrid
  EOSAT FAST Format
  VTP .bt (Binary Terrain) 1.3 Format
  Erdas .LAN/.GIS
  Convair PolGASP
  Image Data and Analysis
  NLAPS Data Format
  Erdas Imagine Raw
  DIPEx
  FARSITE v.4 Landscape File (.lcp)
  NOAA Vertical Datum .GTX
  NADCON .los/.las Datum Grid Shift
  NTv2 Datum Grid Shift
  ACE2
  Snow Data Assimilation System
  Swedish Grid RIK (.rik)
  USGS Optional ASCII DEM (and CDED)
  GeoSoft Grid Exchange Format
  Northwood Numeric Grid Format .grd/.tab
  Northwood Classified Grid Format .grc/.tab
  ARC Digitized Raster Graphics
  Standard Raster Product (ASRP/USRP)
  Magellan topo (.blx)
  SAGA GIS Binary Grid (.sdat)
  Kml Super Overlay
  ASCII Gridded XYZ
  HF2/HFZ heightfield raster
  OziExplorer Image File
  USGS LULC Composite Theme Grid
  Arc/Info Export E00 GRID
  ZMap Plus Grid
  NOAA NGS Geoid Height Grids

5.1.2. Creating rasters using PostGIS raster functions

On many occasions, you'll want to create rasters and raster tables right in the database. There are a plethora of functions to do that. The general steps to follow.

  1. Create a table with a raster column to hold the new raster records which can be accomplished with:

    CREATE TABLE myrasters(rid serial primary key, rast raster);
  2. There are many functions to help with that goal. If you are creating rasters not as a derivative of other rasters, you will want to start with: ST_MakeEmptyRaster, followed by ST_AddBand

    You can also create rasters from geometries. To achieve that you'll want to use ST_AsRaster perhaps accompanied with other functions such as ST_Union or ST_MapAlgebraFct or any of the family of other map algebra functions.

    There are even many more options for creating new raster tables from existing tables. For example you can create a raster table in a different projection from an existing one using ST_Transform

  3. Once you are done populating your table initially, you'll want to create a spatial index on the raster column with something like:

    CREATE INDEX myrasters_rast_st_convexhull_idx ON myrasters USING gist( ST_ConvexHull(rast) );

    Note the use of ST_ConvexHull since most raster operators are based on the convex hull of the rasters.

    [Note]

    Pre-2.0 versions of PostGIS raster were based on the envelop rather than the convex hull. For the spatial indexes to work properly you'll need to drop those and replace with convex hull based index.

  4. Apply raster constraints using AddRasterConstraints

5.2. Raster Catalogs

There are two raster catalog views that come packaged with PostGIS. Both views utilize information embedded in the constraints of the raster tables. As a result the catalog views are always consistent with the raster data in the tables since the constraints are enforced.

  1. raster_columns this view catalogs all the raster table columns in your database.

  2. raster_overviews this view catalogs all the raster table columns in your database that serve as overviews for a finer grained table. Tables of this type are generated when you use the -l switch during load.

5.2.1. Raster Columns Catalog

The raster_columns is a catalog of all raster table columns in your database that are of type raster. It is a view utilizing the constraints on the tables so the information is always consistent even if you restore one raster table from a backup of another database. The following columns exist in the raster_columns catalog.

If you created your tables not with the loader or forgot to specify the -C flag during load, you can enforce the constraints after the fact using AddRasterConstraints so that the raster_columns catalog registers the common information about your raster tiles.

  • r_table_catalog The database the table is in. This will always read the current database.

  • r_table_schema The database schema the raster table belongs to.

  • r_table_name raster table

  • r_raster_column the column in the r_table_name table that is of type raster. There is nothing in PostGIS preventing you from having multiple raster columns per table so its possible to have a raster table listed multiple times with a different raster column for each.

  • srid The spatial reference identifier of the raster. Should be an entry in the Section 4.3.1, “The SPATIAL_REF_SYS Table and Spatial Reference Systems”.

  • scale_x The scaling between geometric spatial coordinates and pixel. This is only available if all tiles in the raster column have the same scale_x and this constraint is applied. Refer to ST_ScaleX for more details.

  • scale_y The scaling between geometric spatial coordinates and pixel. This is only available if all tiles in the raster column have the same scale_y and the scale_y constraint is applied. Refer to ST_ScaleY for more details.

  • blocksize_x The width (number of pixels across) of each raster tile . Refer to ST_Width for more details.

  • blocksize_y The width (number of pixels down) of each raster tile . Refer to ST_Height for more details.

  • same_alignment A boolean that is true if all the raster tiles have the same alignment . Refer to ST_SameAlignment for more details.

  • regular_blocking If the raster column has the spatially unique and coverage tile constraints, the value with be TRUE. Otherwise, it will be FALSE.

  • num_bands The number of bands in each tile of your raster set. This is the same information as what is provided by ST_NumBands

  • pixel_types An array defining the pixel type for each band. You will have the same number of elements in this array as you have number of bands. The pixel_types are one of the following defined in ST_BandPixelType.

  • nodata_values An array of double precision numbers denoting the nodata_value for each band. You will have the same number of elements in this array as you have number of bands. These numbers define the pixel value for each band that should be ignored for most operations. This is similar information provided by ST_BandNoDataValue.

  • out_db An array of boolean flags indicating if the raster bands data is maintained outside the database. You will have the same number of elements in this array as you have number of bands.

  • extent This is the extent of all the raster rows in your raster set. If you plan to load more data that will change the extent of the set, you'll want to run the DropRasterConstraints function before load and then reapply constraints with AddRasterConstraints after load.

  • spatial_index A boolean that is true if raster column has a spatial index.

5.2.2. Raster Overviews

raster_overviews catalogs information about raster table columns used for overviews and additional information about them that is useful to know when utilizing overviews. Overview tables are cataloged in both raster_columns and raster_overviews because they are rasters in their own right but also serve an additional special purpose of being a lower resolution caricature of a higher resolution table. These are generated along-side the main raster table when you use the -l switch in raster loading or can be generated manually using AddOverviewConstraints.

Overview tables contain the same constraints as other raster tables as well as additional informational only constraints specific to overviews.

[Note]

The information in raster_overviews does not duplicate the information in raster_columns. If you need the information about an overview table present in raster_columns you can join the raster_overviews and raster_columns together to get the full set of information you need.

Two main reasons for overviews are:

  1. Low resolution representation of the core tables commonly used for fast mapping zoom-out.

  2. Computations are generally faster to do on them than their higher resolution parents because there are fewer records and each pixel covers more territory. Though the computations are not as accurate as the high-res tables they support, they can be sufficient in many rule-of-thumb computations.

The raster_overviews catalog contains the following columns of information.

  • o_table_catalog The database the overview table is in. This will always read the current database.

  • o_table_schema The database schema the overview raster table belongs to.

  • o_table_name raster overview table name

  • o_raster_column the raster column in the overview table.

  • r_table_catalog The database the raster table that this overview services is in. This will always read the current database.

  • r_table_schema The database schema the raster table that this overview services belongs to.

  • r_table_name raster table that this overview services.

  • r_raster_column the raster column that this overview column services.

  • overview_factor - this is the pyramid level of the overview table. The higher the number the lower the resolution of the table. raster2pgsql if given a folder of images, will compute overview of each image file and load separately. Level 1 is assumed and always the original file. Level 2 is will have each tile represent 4 of the original. So for example if you have a folder of 5000x5000 pixel image files that you chose to chunk 125x125, for each image file your base table will have (5000*5000)/(125*125) records = 1600, your (l=2) o_2 table will have ceiling(1600/Power(2,2)) = 400 rows, your (l=3) o_3 will have ceiling(1600/Power(2,3) ) = 200 rows. If your pixels aren't divisible by the size of your tiles, you'll get some scrap tiles (tiles not completely filled). Note that each overview tile generated by raster2pgsql has the same number of pixels as its parent, but is of a lower resolution where each pixel of it represents (Power(2,overview_factor) pixels of the original).

5.3. Building Custom Applications with PostGIS Raster

The fact that PostGIS raster provides you with SQL functions to render rasters in known image formats gives you a lot of optoins for rendering them. For example you can use OpenOffice / LibreOffice for rendering as demonstrated in Rendering PostGIS Raster graphics with LibreOffice Base Reports. In addition you can use a wide variety of languages as demonstrated in this section.

5.3.1. PHP Example Outputting using ST_AsPNG in concert with other raster functions

In this section, we'll demonstrate how to use the PHP PostgreSQL driver and the ST_AsGDALRaster family of functions to output band 1,2,3 of a raster to a PHP request stream that can then be embedded in an img src html tag.

The sample query demonstrates how to combine a whole bunch of raster functions together to grab all tiles that intersect a particular wgs 84 bounding box and then unions with ST_Union the intersecting tiles together returning all bands, transforms to user specified projection using ST_Transform, and then outputs the results as a png using ST_AsPNG.

You would call the below using

http://mywebserver/test_raster.php?srid=2249

to get the raster image in Massachusetts state plane feet.

<?php
/** contents of test_raster.php **/
$conn_str ='dbname=mydb host=localhost port=5432 user=myuser password=mypwd';
$dbconn = pg_connect($conn_str);
header('Content-Type: image/png');
/**If a particular projection was requested use it otherwise use mass state plane meters **/
if (!empty( $_REQUEST['srid'] ) && is_numeric( $_REQUEST['srid']) ){
                $input_srid = intval($_REQUEST['srid']);
}
else { $input_srid = 26986; }
/** The set bytea_output may be needed for PostgreSQL 9.0+, but not for 8.4 **/
$sql = "set bytea_output='escape';
SELECT ST_AsPNG(ST_Transform(
                        ST_AddBand(ST_Union(rast,1), ARRAY[ST_Union(rast,2),ST_Union(rast,3)])
                                ,$input_srid) ) As new_rast
 FROM aerials.boston
        WHERE
         ST_Intersects(rast, ST_Transform(ST_MakeEnvelope(-71.1217, 42.227, -71.1210, 42.218,4326),26986) )";
$result = pg_query($sql);
$row = pg_fetch_row($result);
pg_free_result($result);
if ($row === false) return;
echo pg_unescape_bytea($row[0]);
?>

5.3.2. ASP.NET C# Example Outputting using ST_AsPNG in concert with other raster functions

In this section, we'll demonstrate how to use Npgsql PostgreSQL .NET driver and the ST_AsGDALRaster family of functions to output band 1,2,3 of a raster to a PHP request stream that can then be embedded in an img src html tag.

You will need the npgsql .NET PostgreSQL driver for this exercise which you can get the latest of from http://npgsql.projects.postgresql.org/. Just download the latest and drop into your ASP.NET bin folder and you'll be good to go.

The sample query demonstrates how to combine a whole bunch of raster functions together to grab all tiles that intersect a particular wgs 84 bounding box and then unions with ST_Union the intersecting tiles together returning all bands, transforms to user specified projection using ST_Transform, and then outputs the results as a png using ST_AsPNG.

This is same example as Section 5.3.1, “PHP Example Outputting using ST_AsPNG in concert with other raster functions” except implemented in C#.

You would call the below using

http://mywebserver/TestRaster.ashx?srid=2249

to get the raster image in Massachusetts state plane feet.

-- web.config connection string section --
<connectionStrings>
    <add name="DSN"
        connectionString="server=localhost;database=mydb;Port=5432;User Id=myuser;password=mypwd"/>
</connectionStrings>
// Code for TestRaster.ashx
<%@ WebHandler Language="C#" Class="TestRaster" %>
using System;
using System.Data;
using System.Web;
using Npgsql;

public class TestRaster : IHttpHandler
{
        public void ProcessRequest(HttpContext context)
        {

                context.Response.ContentType = "image/png";
                context.Response.BinaryWrite(GetResults(context));

        }

        public bool IsReusable {
                get { return false; }
        }

        public byte[] GetResults(HttpContext context)
        {
                byte[] result = null;
                NpgsqlCommand command;
                string sql = null;
                int input_srid = 26986;
        try {
                    using (NpgsqlConnection conn = new NpgsqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DSN"].ConnectionString)) {
                            conn.Open();

                if (context.Request["srid"] != null)
                {
                    input_srid = Convert.ToInt32(context.Request["srid"]);
                }
                sql = @"SELECT ST_AsPNG(
                            ST_Transform(
                                        ST_AddBand(
                                ST_Union(rast,1), ARRAY[ST_Union(rast,2),ST_Union(rast,3)])
                                                    ,:input_srid) ) As new_rast
                        FROM aerials.boston
                                WHERE
                                    ST_Intersects(rast,
                                    ST_Transform(ST_MakeEnvelope(-71.1217, 42.227, -71.1210, 42.218,4326),26986) )";
                            command = new NpgsqlCommand(sql, conn);
                command.Parameters.Add(new NpgsqlParameter("input_srid", input_srid));


                            result = (byte[]) command.ExecuteScalar();
                conn.Close();
                        }

                }
        catch (Exception ex)
        {
            result = null;
            context.Response.Write(ex.Message.Trim());
        }
                return result;
        }
}

5.3.3. Java console app that outputs raster query as Image file

This is a simple java console app that takes a query that returns one image and outputs to specified file.

You can download the latest PostgreSQL JDBC drivers from http://jdbc.postgresql.org/download.html

You can compile the following code using a command something like:

set env CLASSPATH .:..\postgresql-9.0-801.jdbc4.jar
javac SaveQueryImage.java
jar cfm SaveQueryImage.jar Manifest.txt *.class

And call it from the command-line with something like

java -jar SaveQueryImage.jar "SELECT ST_AsPNG(ST_AsRaster(ST_Buffer(ST_Point(1,5),10, 'quad_segs=2'),150, 150, '8BUI',100));" "test.png" 
-- Manifest.txt --
Class-Path: postgresql-9.0-801.jdbc4.jar
Main-Class: SaveQueryImage
// Code for SaveQueryImage.java
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.io.*;

public class SaveQueryImage {
  public static void main(String[] argv) {
      System.out.println("Checking if Driver is registered with DriverManager.");

      try {
        //java.sql.DriverManager.registerDriver (new org.postgresql.Driver());
        Class.forName("org.postgresql.Driver");
      }
      catch (ClassNotFoundException cnfe) {
        System.out.println("Couldn't find the driver!");
        cnfe.printStackTrace();
        System.exit(1);
      }

      Connection conn = null;

      try {
        conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/mydb","myuser", "mypwd");
        conn.setAutoCommit(false);

        PreparedStatement sGetImg = conn.prepareStatement(argv[0]);

        ResultSet rs = sGetImg.executeQuery();

                FileOutputStream fout;
                try
                {
                        rs.next();
                        /** Output to file name requested by user **/
                        fout = new FileOutputStream(new File(argv[1]) );
                        fout.write(rs.getBytes(1));
                        fout.close();
                }
                catch(Exception e)
                {
                        System.out.println("Can't create file");
                        e.printStackTrace();
                }

        rs.close();
                sGetImg.close();
        conn.close();
      }
      catch (SQLException se) {
        System.out.println("Couldn't connect: print out a stack trace and exit.");
        se.printStackTrace();
        System.exit(1);
      }
  }
}

5.3.4. Use PLPython to dump out images via SQL

This is a plpython stored function that creates a file in the server directory for each record. Requires you have plpython installed. Should work fine with both plpythonu and plpython3u.

CREATE OR REPLACE FUNCTION write_file (param_bytes bytea, param_filepath text)
RETURNS text
AS $$
f = open(param_filepath, 'wb+')
f.write(param_bytes)
return param_filepath
$$ LANGUAGE plpythonu;
--write out 5 images to the PostgreSQL server in varying sizes
-- note the postgresql daemon account needs to have write access to folder
-- this echos back the file names created;
 SELECT write_file(ST_AsPNG(
        ST_AsRaster(ST_Buffer(ST_Point(1,5),j*5, 'quad_segs=2'),150*j, 150*j, '8BUI',100)),
         'C:/temp/slices'|| j || '.png')
         FROM generate_series(1,5) As j;

     write_file
---------------------
 C:/temp/slices1.png
 C:/temp/slices2.png
 C:/temp/slices3.png
 C:/temp/slices4.png
 C:/temp/slices5.png

5.3.5. Outputting Rasters with PSQL

Sadly PSQL doesn't have easy to use built-in functionality for outputting binaries. This is a bit of a hack that piggy backs on PostgreSQL somewhat legacy large object support. To use first launch your psql commandline connected to your database.

Unlike the python approach, this approach creates the file on your local computer.

SELECT oid, lowrite(lo_open(oid, 131072), png) As num_bytes
 FROM
 ( VALUES (lo_create(0),
   ST_AsPNG( (SELECT rast FROM aerials.boston WHERE rid=1) )
  ) ) As v(oid,png);
-- you'll get an output something like --
   oid   | num_bytes
---------+-----------
 2630819 |     74860

-- next note the oid and do this replacing the c:/test.png to file path location
-- on your local computer
 \lo_export 2630819 'C:/temp/aerial_samp.png'

-- this deletes the file from large object storage on db
SELECT lo_unlink(2630819);
                        

Chapter 6. Using PostGIS Geometry: Building Applications

6.1. Utiliser MapServer

MapServer est un serveur cartographique web conforme aux spécifications définies par l'OpenGIS

6.1.1. Utilisation basique

Afin d'utiliser conjointement PostGIS et MapServer, il est nécessaire au préalable de savoir comment configurer MapServer ce qui est bien au-delà de l'objectif de cette documentation. Cette section portera spécifiquement sur les aspects relatifs à PostGIS.

Pour utiliser PostGIS avec MapServer, vous aurez besoin de :

  • La version 0.6 - ou plus récente - de PostGIS.

  • La version 3.5 - ou plus récente - de MapServer.

MapServer communique avec PostGIS/PostgreSQL en utilisant l'interface libpq comme n'importe quel autre client PostgreSQL. Cela signifie que pour utiliser PostGIS, MapServer peut être installé sur n'importe quelle machine disposant d'un accès internet au serveur PostGIS. Plus la connection entre les deux systèmes est rapide et meilleur seront les performances.

  1. Compile and install MapServer, with whatever options you desire, including the "--with-postgis" configuration option.

  2. Dans votre fichier MapFIle, ajoutez une couche PostGIS. Par exemple :

    LAYER
    CONNECTIONTYPE postgis
    NAME "widehighways" 
    # Connection à la base de données
    CONNECTION "user=dbuser dbname=gisdatabase host=bigserver"
    PROCESSING "CLOSE_CONNECTION=DEFER"
    # Récupère les informations géographiques de la colonne 'geom' de la table 'roads' 
    DATA "geom from roads using srid=4326 using unique gid" 
    STATUS ON
    TYPE LINE 
    # Seule les routes principales seront affichées 
    FILTER "type = 'highway' and numlanes >= 4" 
    CLASS 
    # Le trait représentant les routes importantes sera plus claires et large de 2 pixels
    EXPRESSION ([numlanes] >= 6) 
    STYLE
    COLOR 255 22 22 
    WIDTH 2 
    END
    END 
    CLASS 
    # Toute les autres seront dessinées en couleur sombre avec un trait d'1 pixel d'paisseur
    EXPRESSION ([numlanes] < 6) 
    STYLE
    COLOR 205 92 82
    END
    END 
    END

    In the example above, the PostGIS-specific directives are as follows:

    CONNECTIONTYPE

    Pour les couches de données PostGIS, cela sera toujours "postgis".

    CONNECTION

    The database connection is governed by the a 'connection string' which is a standard set of keys and values like this (with the default values in <>):

    user=<username> password=<password> dbname=<username> hostname=<server> port=<5432>

    An empty connection string is still valid, and any of the key/value pairs can be omitted. At a minimum you will generally supply the database name and username to connect with.

    DATA

    The form of this parameter is "<geocolumn> from <tablename> using srid=<srid> using unique <primary key>" where the column is the spatial column to be rendered to the map, the SRID is SRID used by the column and the primary key is the table primary key (or any other uniquely-valued column with an index).

    You can omit the "using srid" and "using unique" clauses and MapServer will automatically determine the correct values if possible, but at the cost of running a few extra queries on the server for each map draw.

    PROCESSING

    Putting in a CLOSE_CONNECTION=DEFER if you have multiple layers reuses existing connections instead of closing them. This improves speed. Refer to for MapServer PostGIS Performance Tips for a more detailed explanation.

    FILTER

    The filter must be a valid SQL string corresponding to the logic normally following the "WHERE" keyword in a SQL query. So, for example, to render only roads with 6 or more lanes, use a filter of "num_lanes >= 6".

  3. In your spatial database, ensure you have spatial (GiST) indexes built for any the layers you will be drawing.

    CREATE INDEX [indexname] ON [tablename] USING GIST ( [geometrycolumn] );
  4. If you will be querying your layers using MapServer you will also need to use the "using unique" clause in your DATA statement.

    MapServer requires unique identifiers for each spatial record when doing queries, and the PostGIS module of MapServer uses the unique value you specify in order to provide these unique identifiers. Using the table primary key is the best practice.

6.1.2. Questions les plus fréquemment posées

6.1.2.1. When I use an EXPRESSION in my map file, the condition never returns as true, even though I know the values exist in my table.
6.1.2.2. The FILTER I use for my Shape files is not working for my PostGIS table of the same data.
6.1.2.3. My PostGIS layer draws much slower than my Shape file layer, is this normal?
6.1.2.4. Mes couches de données PostGIS s'affichent correctement, mais les requêtes sont longues. Qu'est ce qui ne va pas ?
6.1.2.5. Est-il possible avec MapServer d'utiliser le type de données "geography" (nouveauté de la version 1.5 de PostGIS) comme couche de données ?

6.1.2.1.

When I use an EXPRESSION in my map file, the condition never returns as true, even though I know the values exist in my table.

Unlike shape files, PostGIS field names have to be referenced in EXPRESSIONS using lower case.

EXPRESSION ([numlanes] >= 6)

6.1.2.2.

The FILTER I use for my Shape files is not working for my PostGIS table of the same data.

Unlike shape files, filters for PostGIS layers use SQL syntax (they are appended to the SQL statement the PostGIS connector generates for drawing layers in MapServer).

FILTER "type = 'highway' and numlanes >= 4"

6.1.2.3.

My PostGIS layer draws much slower than my Shape file layer, is this normal?

In general, the more features you are drawing into a given map, the more likely it is that PostGIS will be slower than Shape files. For maps with relatively few features (100s), PostGIS will often be faster. For maps with high feature density (1000s), PostGIS will always be slower.

If you are finding substantial draw performance problems, it is possible that you have not built a spatial index on your table.

postgis# CREATE INDEX geotable_gix ON geotable USING GIST ( geocolumn );
postgis# VACUUM ANALYZE;

6.1.2.4.

Mes couches de données PostGIS s'affichent correctement, mais les requêtes sont longues. Qu'est ce qui ne va pas ?

Afin que vos requêtes s'exécutent rapidement, vos enregistrements doivent être identifiables par une clé unique, identifiant qui doit également avoir été indexé.

You can specify what unique key for mapserver to use with the USING UNIQUE clause in your DATA line:

DATA "geom FROM geotable USING UNIQUE gid"

6.1.2.5.

Est-il possible avec MapServer d'utiliser le type de données "geography" (nouveauté de la version 1.5 de PostGIS) comme couche de données ?

Yes! MapServer understands geography columns as being the same as geometry columns, but always using an SRID of 4326. Just make sure to include a "using srid=4326" clause in your DATA statement. Everything else works exactly the same as with geometry.

DATA "geog FROM geogtable USING SRID=4326 USING UNIQUE gid"

6.1.3. Usage avancé

The USING pseudo-SQL clause is used to add some information to help mapserver understand the results of more complex queries. More specifically, when either a view or a subselect is used as the source table (the thing to the right of "FROM" in a DATA definition) it is more difficult for mapserver to automatically determine a unique identifier for each row and also the SRID for the table. The USING clause can provide mapserver with these two pieces of information as follows:

DATA "geom FROM (
  SELECT
    table1.geom AS geom,
    table1.gid AS gid,
    table2.data AS data
  FROM table1
  LEFT JOIN table2
  ON table1.id = table2.id
) AS new_table USING UNIQUE gid USING SRID=4326"
USING UNIQUE <uniqueid>

MapServer requires a unique id for each row in order to identify the row when doing map queries. Normally it identifies the primary key from the system tables. However, views and subselects don't automatically have an known unique column. If you want to use MapServer's query functionality, you need to ensure your view or subselect includes a uniquely valued column, and declare it with USING UNIQUE. For example, you could explicitly select nee of the table's primary key values for this purpose, or any other column which is guaranteed to be unique for the result set.

[Note]

"Querying a Map" is the action of clicking on a map to ask for information about the map features in that location. Don't confuse "map queries" with the SQL query in a DATA definition.

USING SRID=<srid>

PostGIS needs to know which spatial referencing system is being used by the geometries in order to return the correct data back to MapServer. Normally it is possible to find this information in the "geometry_columns" table in the PostGIS database, however, this is not possible for tables which are created on the fly such as subselects and views. So the USING SRID= option allows the correct SRID to be specified in the DATA definition.

6.1.4. Exemples

Lets start with a simple example and work our way up. Consider the following MapServer layer definition:

LAYER
  CONNECTIONTYPE postgis
  NAME "roads"
  CONNECTION "user=theuser password=thepass dbname=thedb host=theserver"
  DATA "geom from roads"
  STATUS ON
  TYPE LINE
  CLASS
    STYLE
      COLOR 0 0 0
    END
  END
END

This layer will display all the road geometries in the roads table as black lines.

Now lets say we want to show only the highways until we get zoomed in to at least a 1:100000 scale - the next two layers will achieve this effect:

LAYER
  CONNECTIONTYPE postgis
  CONNECTION "user=theuser password=thepass dbname=thedb host=theserver"
  PROCESSING "CLOSE_CONNECTION=DEFER"
  DATA "geom from roads"
  MINSCALE 100000
  STATUS ON
  TYPE LINE
  FILTER "road_type = 'highway'"
  CLASS
    COLOR 0 0 0
  END
END
LAYER
  CONNECTIONTYPE postgis
  CONNECTION "user=theuser password=thepass dbname=thedb host=theserver"
  PROCESSING "CLOSE_CONNECTION=DEFER"
  DATA "geom from roads"
  MAXSCALE 100000
  STATUS ON
  TYPE LINE
  CLASSITEM road_type
  CLASS
    EXPRESSION "highway"
    STYLE
      WIDTH 2
      COLOR 255 0 0
    END
  END
  CLASS
    STYLE
      COLOR 0 0 0
    END
  END
END

The first layer is used when the scale is greater than 1:100000, and displays only the roads of type "highway" as black lines. The FILTER option causes only roads of type "highway" to be displayed.

The second layer is used when the scale is less than 1:100000, and will display highways as double-thick red lines, and other roads as regular black lines.

So, we have done a couple of interesting things using only MapServer functionality, but our DATA SQL statement has remained simple. Suppose that the name of the road is stored in another table (for whatever reason) and we need to do a join to get it and label our roads.

LAYER
  CONNECTIONTYPE postgis
  CONNECTION "user=theuser password=thepass dbname=thedb host=theserver"
  DATA "geom FROM (SELECT roads.gid AS gid, roads.geom AS geom,
        road_names.name as name FROM roads LEFT JOIN road_names ON
        roads.road_name_id = road_names.road_name_id)
        AS named_roads USING UNIQUE gid USING SRID=4326"
  MAXSCALE 20000
  STATUS ON
  TYPE ANNOTATION
  LABELITEM name
  CLASS
    LABEL
      ANGLE auto
      SIZE 8
      COLOR 0 192 0
      TYPE truetype
      FONT arial
    END
  END
END

This annotation layer adds green labels to all the roads when the scale gets down to 1:20000 or less. It also demonstrates how to use an SQL join in a DATA definition.

6.2. Clients Java (JDBC)

Java clients can access PostGIS "geometry" objects in the PostgreSQL database either directly as text representations or using the JDBC extension objects bundled with PostGIS. In order to use the extension objects, the "postgis.jar" file must be in your CLASSPATH along with the "postgresql.jar" JDBC driver package.

import java.sql.*;
import java.util.*;
import java.lang.*;
import org.postgis.*;

public class JavaGIS {

public static void main(String[] args) {

  java.sql.Connection conn;

  try {
    /*
    * Load the JDBC driver and establish a connection.
    */
    Class.forName("org.postgresql.Driver");
    String url = "jdbc:postgresql://localhost:5432/database";
    conn = DriverManager.getConnection(url, "postgres", "");
    /*
    * Add the geometry types to the connection. Note that you
    * must cast the connection to the pgsql-specific connection
    * implementation before calling the addDataType() method.
    */
    ((org.postgresql.PGConnection)conn).addDataType("geometry",Class.forName("org.postgis.PGgeometry"));
    ((org.postgresql.PGConnection)conn).addDataType("box3d",Class.forName("org.postgis.PGbox3d"));
    /*
    * Create a statement and execute a select query.
    */
    Statement s = conn.createStatement();
    ResultSet r = s.executeQuery("select geom,id from geomtable");
    while( r.next() ) {
      /*
      * Retrieve the geometry as an object then cast it to the geometry type.
      * Print things out.
      */
      PGgeometry geom = (PGgeometry)r.getObject(1);
      int id = r.getInt(2);
      System.out.println("Row " + id + ":");
      System.out.println(geom.toString());
    }
    s.close();
    conn.close();
  }
catch( Exception e ) {
  e.printStackTrace();
  }
}
}

The "PGgeometry" object is a wrapper object which contains a specific topological geometry object (subclasses of the abstract class "Geometry") depending on the type: Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon.

PGgeometry geom = (PGgeometry)r.getObject(1);
if( geom.getType() == Geometry.POLYGON ) {
  Polygon pl = (Polygon)geom.getGeometry();
  for( int r = 0; r < pl.numRings(); r++) {
    LinearRing rng = pl.getRing(r);
    System.out.println("Ring: " + r);
    for( int p = 0; p < rng.numPoints(); p++ ) {
      Point pt = rng.getPoint(p);
      System.out.println("Point: " + p);
      System.out.println(pt.toString());
    }
  }
}

The JavaDoc for the extension objects provides a reference for the various data accessor functions in the geometric objects.

6.3. C Clients (libpq)

...

6.3.1. Text Cursors

...

6.3.2. Binary Cursors

...

Chapter 7. Astuces de performances

7.1. Petites tables de grandes géométries

7.1.1. Description du problème

Les versions de PostgreSQL actuelles (y compris 8.0) souffrent d'une faiblesse optimiseur de requête relative les tables TOAST. Tables TOAST sont une sorte de «salle de l'extension" utilisé pour stocker de grandes valeurs (dans le sens de la taille des données) qui ne rentrent pas dans les pages de données normales (comme de longs textes, images ou des géométries complexes avec beaucoup de sommets), voir Documentation PostgreSQL pour TOAST pour plus d'informations).

Le problème apparaît s'il vous arrive d'avoir une table avec d'assez grandes géométries, mais pas beaucoup de lignes d'entre elles (comme un tableau contenant les frontières de tous les pays européens en haute résolution). Ensuite, le tableau lui-même est petit, mais il utilise beaucoup d'espace TOAST. Dans notre exemple, le cas, la table elle-même avait environ 80 lignes et seulement 3 pages de données utilisées, mais la table TOAST 8225 pages utilisé.

Maintenant émettre une requête en utilisant l'opérateur de géométrie && pour rechercher une boîte englobante qui correspond que très peu de ces lignes. Maintenant l'optimiseur de requêtes voit que la table n'a que 3 pages et 80 lignes. Il estime qu'une analyse séquentielle sur une telle petite table est beaucoup plus rapide que d'utiliser un index. Et alors il décide d'ignorer l'index GIST. Habituellement, cette estimation est correcte. Mais dans notre cas, l'opérateur && doit aller chercher chaque géométrie à partir du disque pour comparer les boîtes englobantes, et par conséquent la lecture de toutes les pages TOAST également.

Pour voir si votre souffrent de ce bogue, utilisez la commande "EXPLAIN ANALYZE" de postgresql. Pour plus d'informations et détails techniques, vous pouvez lire le fil sur la liste de diffusion des performances de postgres: http://archives.postgresql.org/pgsql-performance/2005-02/msg00030.php

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

7.1.2. Solutions de contournement

Les personnes de PostgreSQL essayent de résoudre ce problème en faisant l'estimation de la requête TOAST-courant. Pour l'instant, voici deux solutions:

La première solution consiste à forcer le planificateur de requêtes à utiliser l'index. Envoyer "SET enable_seqscan TO off;" au serveur avant d'émettre la requête. Cela force le planificateur de requêtes à éviter balayages séquentiels lorsque cela est possible. Donc, il utilise l'index GIST comme d'habitude. Mais cet indicateur doit être fixé à chaque connexion, et il provoque le planificateur de requêtes à faire des erreurs d'estimation dans les autres cas, vous devrez donc faire "SET POUR enable_seqscan sur;" après la requête.

La deuxième solution consiste à faire le balayage séquentielle aussi vite que le planificateur de requêtes pense. Ceci peut être réalisé en créant une colonne supplémentaire qui "cache" la bbox, et contre cette correspondance. Dans notre exemple, les commandes sont comme:

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

Maintenant changez votre requête pour utiliser l'opérateur && face à la bbox au lieu de la geom_column, comme:

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

Bien sûr, si vous changez ou ajoutez des lignes à mytable, vous devez garder la bbox "synchro". La façon la plus transparente pour ce faire serait des déclencheurs, mais vous pouvez également modifier votre application afin de maintenir la colonne bbox courante ou exécuter la requête UPDATE ci-dessus après chaque modification.

7.2. CLUSTER d'index géométriques

Pour les tables qui sont pour la plupart en lecture seule, et où un seul index est utilisé pour la majorité des requêtes, PostgreSQL offre la commande CLUSTER. Cette commande réorganise physiquement toutes les lignes de données dans le même ordre que les critères de l'index, ce qui donne deux avantages de performance: d'abord, pour des analyses d'intervalle de l'index, le nombre de recherche sur la table de données est considérablement réduit. Deuxièmement, si votre jeu de travail se concentre à quelques petits intervalles sur les index, vous avez une mise en cache plus efficace parce que les lignes de données sont dispersées sur moins de pages de données. (N'hésitez pas à lire la documentation de la commande CLUSTER du manuel PostgreSQL à ce stade)

Cependant, PostgreSQL ne permet actuellement pas le clustering sur les index GIST de PostGIS car les indices GIST ignorent les valeurs NULL, vous obtenez un message d'erreur comme:

lwgeom=# CLUSTER my_geom_index ON my_table; 
ERROR: cannot cluster when index access method does not handle null values
HINT: You may be able to work around this by marking column "the_geom" NOT NULL.

Comme le message d'ASTUCES vous le dit, on peut contourner cette lacune en ajoutant une contrainte "not null" à la table:

lwgeom=# ALTER TABLE my_table ALTER COLUMN the_geom SET not null; 
ALTER TABLE

Bien sûr, cela ne fonctionnera pas si vous avez besoin, dans les faits, de valeurs NULL dans la colonne de géométrie. En outre, vous devez utiliser la méthode ci-dessus pour ajouter la contrainte, en utilisant une contrainte CHECK comme "ALTER TABLE blubb ADD CHECK (geometry is not null)" ne fonctionnera pas.

7.3. Eviter les conversions de dimension

Sometimes, you happen to have 3D or 4D data in your table, but always access it using OpenGIS compliant ST_AsText() or ST_AsBinary() functions that only output 2D geometries. They do this by internally calling the ST_Force2D() function, which introduces a significant overhead for large geometries. To avoid this overhead, it may be feasible to pre-drop those additional dimensions once and forever:

UPDATE mytable SET the_geom = ST_Force2D(the_geom); 
VACUUM FULL ANALYZE mytable;

Notez que si vous avez ajouté votre colonne de géométrie à l'aide AddGeometryColumn (), il y aura une contrainte sur la dimension de la géométrie. Pour contourner vous devrez supprimer la contrainte. N'oubliez pas de mettre à jour l'entrée dans la table geometry_columns et recréer la contrainte par la suite.

En cas de grandes tables, il peut être judicieux de diviser cette mise à jour en petites portions en restreignant l'UPDATE à une partie de la table via une clause WHERE et votre clé primaire ou d'un autre critère, et exécutant un simple «VACUUM»; entre votre mises à jour. Cela réduit considérablement le besoin d'espace disque temporaire. En outre, si vous avez des données géométriques de dimension mixte, restreindre la mise à jour en "WHERE dimension(the_geom)>2" saute la ré-écriture des géométries qui sont déjà en 2D.

7.4. Réglage de votre configuration

Tuning for PostGIS is much like tuning for any PostgreSQL workload. The only additional note to keep in mind is that geometries and rasters are heavy so memory related optimizations generally have more of an impact on PostGIS than other types of PostgreSQL queries.

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

For PostgreSQL 9.4+ all these can be set at the server level without touching postgresql.conf or postgresql.auto.conf by using the ALTER SYSTEM.. command.

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

In addition to these settings, PostGIS also has some custom settings which you can find listed in Section 8.2, “Variables PostGIS GUC ( Grand Unified Custom Variables )”.

7.4.1. Commencement

Ces réglages sont configurés dans postgresql.conf:

constraint_exclusion

  • Par défaut : 1MB

  • Ceci est généralement utilisé pour le partitionnement de table. Si vous utilisez des versions de PostgreSQL inférieur à 8.4 , régler sur "on" pour s'assurer que le planificateur de requêtes optimisera comme désiré. Pour PostgreSQL 8.4, la valeur par défaut pour ce paramètre est réglé à "partition" qui est idéal pour PostgreSQL 8.4 et au-dessus, car il va forcer le planificateur à analyser uniquement les tables pour les contraintes, si elles sont dans une hiérarchie héritée et si elles ne vont pas pénaliser le planificateur d'un autre coté.

shared_buffers

  • Default: ~128MB in PostgreSQL 9.6

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

work_mem (la mémoire utilisé pour les opérations de tri et les requêtes complexes)

  • Par défaut : 1MB

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

7.4.2. Runtime

work_mem (la mémoire utilisé pour les opérations de tri et les requêtes complexes)

  • Par défaut : 1MB

  • Ajuster vers le haut pour de grandes bases de données, des requêtes complexes, beaucoup de RAM

  • Ajuster vers le bas pour beaucoup d'accès concurrents ou peu de RAM

  • Si vous avez beaucoup de RAM et peu de développeurs:

    SET work_mem TO 1200000;
                    

maintenance_work_mem (Utilisé pour VACUUM, CREATE INDEX, etc.)

  • Par défaut : 16MB

  • Généralement trop faible en I/O, objets verrouillés pendant les permutations de mémoire

  • 32MB à 256MB sont recommandé sur des serveur de production avec beaucoup de RAM, but cela dépend du nombre d'accès concurrents. Si vous avez beaucoup de RAM et peu de développeurs:

    SET maintenance_work_mem TO 1200000;
                    

max_parallel_workers_per_gather This setting is only available for PostgreSQL 9.6+ and will only affect PostGIS 2.3+, since only PostGIS 2.3+ supports parallel queries. If set to higher than 0, then some queries such as those involving relation functions like ST_Intersects can use multiple processes and can run more than twice as fast when doing so. If you have a lot of processors to spare, you should change the value of this to as many processors as you have. Also make sure to bump up max_worker_processes to at least as high as this number.

  • Par défaut : 1MB

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

Chapter 8. Référence PostGIS

Les fonctions suivantes sont celles dont un utilisateur normal de PostGIS peut avoir besoin. Il existe d'autres fonctions nécessaires au fonctionnement de PostGIS. Elles ne sont normalement pas destinées à un utilisateur standard.

[Note]

PostGIS a entamé une phase de transition concernant le nom des fonctions pour les faire correspondre à la norme SQL-MM. La plupart des fonctions ont été renommées en utilisant le préfixe des types spatiaux (ST, pour Spatial Type). Les anciennes fonctions, toujours disponibles, ne sont pas listées ci-après si leur équivalent est disponible. Les fonctions non préfixées par ST, qui ne sont pas listées dans cette documentation sont dépréciées et seront supprimées des prochaines version de PostGIS. IL NE FAUT PLUS LES UTILISER.

8.1. Les types Geometry/Geography/Box de PostgreSQL PostGIS

Abstract

Cette section liste les types de données PostgreSQL installés par PostGIS. Leurs méthodes de transtypage sont également décrites, ce qui est particulièrement important lors de la définition/création de nouvelles fonctions.

Un transtypage ou cast est l'opération visant à changer un type de données vers un autres type. PostgreSQL offre la fonctionnalité assez unique de pouvoir définir les comportements des types spécifiques lors du transtypage et les fonctions utilisées lors du transtypage. Un transtypage peut être défini comme automatique, auquel cas il n'est pas nécessaire d'utiliser la fonction CAST(myfoo As otherfootype) ou myfoo::otherfootype lors de l'appel d'une fonction supportant uniquement otherfootype: le transtypage sera automatique.

Le danger lors de l'utilisation d'un transtypage automatique peut survenir si, par exemple, il existe une fonction surchargée prenant en paramètre une box2d et une prenant une box3d, mais aucune acceptant une geometry. Dans ce cas, les deux fonctions peuvent être utilisées avec un type geometry sachant que ce type peut être transtypé automatiquement vers les deux types box2d et box3d. Une erreur survient alors indiquant que la fonction est ambigüe. Pour forcer PostgreSQL à utiliser la bonne fonction, il faut utiliser la fonction CAST(mygeom As box3d) ou mygeom::box3d.

A partir de PostgreSQL 8.3 - Tout peut être transtypé en texte (type text). Il n'est donc pas nécessaire de définir un opérateur de transtypage spécifique vers le type text..

box2d — Un rectangle composé des coordonnées xmin, ymin, xmax, ymax. Souvent utilisé pour renvoyer la boite 2d d'une géométrie.
box3d — Une boite composée des coordonnées xmin, ymin, zmin, xmax, ymax, zmax. Souvent utilisé pour renvoyer la boite 3d d'une géométrie ou d'une collection de géométries.
geometry — Type de données spatiales planaires
geometry_dump — Un type spatial comportant deux champs - geom (stockant un objet géométrique) et path[] (un tableau uni dimensionnel 1-d stockant la position de la géométrie dans la collection.)
geography — Type spatial ellipsoïdal

Name

box2d — Un rectangle composé des coordonnées xmin, ymin, xmax, ymax. Souvent utilisé pour renvoyer la boite 2d d'une géométrie.

Description

box2d est un type spatial utilisé pour représenter la boite englobante d'une géométrie ou d'un ensemble de géométries. Dans les versions de PostGIS antérieures à 1.4, la fonction ST_Extent renvoie une box2d.


Name

box3d — Une boite composée des coordonnées xmin, ymin, zmin, xmax, ymax, zmax. Souvent utilisé pour renvoyer la boite 3d d'une géométrie ou d'une collection de géométries.

Description

box3d est un type spatial utilisé pour représenter la boite englobante d'une géométrie ou d'un ensemble de géométries en 3 dimensions. La fonction ST_3DExtent renvoie une box3d.

Comportement du transtypage

Cette section liste les transtypages automatiques et explicites autorisés pour ce type de données

Transtypage versComportement
boxautomatique
box2dautomatique
geometryautomatique

Name

geometry — Type de données spatiales planaires

Description

Le type geometry est un type de données capital dans PostGIS, utilisé pour modéliser une entité dans un système de coordonées euclidien.

Comportement du transtypage

Cette section liste les transtypages automatiques et explicites autorisés pour ce type de données

Transtypage versComportement
boxautomatique
box2dautomatique
box3dautomatique
byteaautomatique
geographyautomatique
textautomatique

Name

geometry_dump — Un type spatial comportant deux champs - geom (stockant un objet géométrique) et path[] (un tableau uni dimensionnel 1-d stockant la position de la géométrie dans la collection.)

Description

geometry_dump est un type de données composite consistant en un objet géométrique référencé par le champ .geom et un tableau uni dimensionnel d'entiers référencé par le champ path[] donnant la position de chaque géométrie dans la collection (L'index du tableau démarre à 1. Par ex: path[1] pour obtenir le premier élément). Ce type utilisé par la famille de fonctions ST_Dump* comme type de retour pour exploser une géométrie complexe en ses parties élémentaires et les positions de ces parties.


Name

geography — Type spatial ellipsoïdal

Description

geography est un type de données spatiales utilisé pour représenter une entité dans les coordonnées sphériques de la terre.

Comportement du transtypage

Cette section liste les transtypages automatiques et explicites autorisés pour ce type de données

Transtypage versComportement
geometryexplicite

8.2. Variables PostGIS GUC ( Grand Unified Custom Variables )

Abstract

Cette section liste les variables globales spécifiques de PostGIS appelées GUC : Grand Unified Custom Variables. Elles peuvent être réglées globalement, par base de données, par session ou par transaction. Il est préférable de les régler au niveau global ou au niveau de la base de donnée.

postgis.backend — Le backend qui sera utilisé par les fonctions lorsque GEOS et SFCGAL se recouvrent. Options: geos ou sfcgal. Valeur par défaut geos.
postgis.gdal_datapath — Une option de configuration pour régler la valeur de l'option GDAL_DATA de GDAL. Si elle n'est pas assignée, la valeur de la variable d'environnement GDAL_DATA est utilisée.
postgis.gdal_enabled_drivers — A configuration option to set the enabled GDAL drivers in the PostGIS environment. Affects the GDAL configuration variable GDAL_SKIP.
postgis.enable_outdb_rasters — A boolean configuration option to enable access to out-db raster bands.

Name

postgis.backend — Le backend qui sera utilisé par les fonctions lorsque GEOS et SFCGAL se recouvrent. Options: geos ou sfcgal. Valeur par défaut geos.

Description

Cette GUC n'a de sens que si vous avez compilé PostGIS avec le support SFCGAL. Par défaut le backend geos est utilisé pour les fonctions proposées à la fois par GEOS et SFCGAL (même nom). Cette variable permet de surcharger la valeur par défaut et d'utiliser sfcgal comme backend pour effectuer la requête.

Disponibilité: 2.1.0

Exemples

Régler le backend juste pour le temps de la connexion

set postgis.backend = sfcgal;

Régler le backend pour les nouvelles connexions à une base de données

ALTER DATABASE mygisdb SET postgis.backend = sfcgal;

Name

postgis.gdal_datapath — Une option de configuration pour régler la valeur de l'option GDAL_DATA de GDAL. Si elle n'est pas assignée, la valeur de la variable d'environnement GDAL_DATA est utilisée.

Description

Une variable GUC PostgreSQL pour régler la valeur de l'option GDAL_DATA de GDAL. La valeur postgis.gdal_datapath devrait être le chemin physique complet vers les fichiers de données de GDAL.

Cette option de configuration est principalement destinée aux plateformes Windows où le chemin des fichiers de données de GDAL n'est pas codé en dur. Cette option devrait aussi être réglée lorsque les fichiers de données GDAL ne sont pas situés dans le chemin attendu par GDAL.

[Note]

Cette option peut être réglée dans le fichier de configuration postgresql.conf de PostgreSQL. Elle peut aussi être réglée par connexion ou par transaction.

Disponibilité : 2.2.0

[Note]

Des informations complémentaires sur GDAL_DATA sont disponibles dans la description des Options de configuration.

Exemples

Régler et remettre à la valeur par défaut postgis.gdal_datapath

SET postgis.gdal_datapath TO '/usr/local/share/gdal.hidden';
SET postgis.gdal_datapath TO default;
                                

Réglage pour une base de données spécifique, sous Windows

ALTER DATABASE gisdb
SET postgis.gdal_datapath = 'C:/Program Files/PostgreSQL/9.3/gdal-data';

Name

postgis.gdal_enabled_drivers — A configuration option to set the enabled GDAL drivers in the PostGIS environment. Affects the GDAL configuration variable GDAL_SKIP.

Description

A configuration option to set the enabled GDAL drivers in the PostGIS environment. Affects the GDAL configuration variable GDAL_SKIP. This option can be set in PostgreSQL's configuration file: postgresql.conf. It can also be set by connection or transaction.

The initial value of postgis.gdal_enabled_drivers may also be set by passing the environment variable POSTGIS_GDAL_ENABLED_DRIVERS with the list of enabled drivers to the process starting PostgreSQL.

Enabled GDAL specified drivers can be specified by the driver's short-name or code. Driver short-names or codes can be found at GDAL Raster Formats. Multiple drivers can be specified by putting a space between each driver.

[Note]

There are three special codes available for postgis.gdal_enabled_drivers. The codes are case-sensitive.

  • DISABLE_ALL disables all GDAL drivers. If present, DISABLE_ALL overrides all other values in postgis.gdal_enabled_drivers.

  • ENABLE_ALL enables all GDAL drivers.

  • VSICURL enables GDAL's /vsicurl/ virtual file system.

When postgis.gdal_enabled_drivers is set to DISABLE_ALL, attempts to use out-db rasters, ST_FromGDALRaster(), ST_AsGDALRaster(), ST_AsTIFF(), ST_AsJPEG() and ST_AsPNG() will result in error messages.

[Note]

In the standard PostGIS installation, postgis.gdal_enabled_drivers is set to DISABLE_ALL.

[Note]

Additional information about GDAL_SKIP is available at GDAL's Configuration Options.

Disponibilité : 2.2.0

Exemples

Set and reset postgis.gdal_enabled_drivers

Sets backend for all new connections to database

ALTER DATABASE mygisdb SET postgis.gdal_enabled_drivers TO 'GTiff PNG JPEG';

Sets default enabled drivers for all new connections to server. Requires super user access and PostgreSQL 9.4+. Also not that database, session, and user settings override this.

ALTER SYSTEM SET postgis.gdal_enabled_drivers TO 'GTiff PNG JPEG';
SELECT pg_reload_conf();
                                
SET postgis.gdal_enabled_drivers TO 'GTiff PNG JPEG';
SET postgis.gdal_enabled_drivers = default;
                                

Enable all GDAL Drivers

SET postgis.gdal_enabled_drivers = 'ENABLE_ALL';
                                

Disable all GDAL Drivers

SET postgis.gdal_enabled_drivers = 'DISABLE_ALL';
                                

Name

postgis.enable_outdb_rasters — A boolean configuration option to enable access to out-db raster bands.

Description

A boolean configuration option to enable access to out-db raster bands. This option can be set in PostgreSQL's configuration file: postgresql.conf. It can also be set by connection or transaction.

The initial value of postgis.enable_outdb_rasters may also be set by passing the environment variable POSTGIS_ENABLE_OUTDB_RASTERS with a non-zero value to the process starting PostgreSQL.

[Note]

Even if postgis.enable_outdb_rasters is True, the GUC postgis.enable_outdb_rasters determines the accessible raster formats.

[Note]

In the standard PostGIS installation, postgis.enable_outdb_rasters is set to False.

Disponibilité : 2.2.0

Exemples

Set and reset postgis.enable_outdb_rasters

SET postgis.enable_outdb_rasters TO True;
SET postgis.enable_outdb_rasters = default;
SET postgis.enable_outdb_rasters = True;
SET postgis.enable_outdb_rasters = False;
                                

8.3. Fonctions de gestion

AddGeometryColumn — Ajoute une colonne géométrique à une table attributaire existante. Utilise par défaut le modificateur de type lors de la définition de la géométrie, plutôt que des contraintes. Passer le paramètre use_typmod à false pour activer l'ancien mécanisme basé sur les contraintes.
DropGeometryColumn — Supprime une colonne géométrique d'une table spatiale.
DropGeometryTable — Supprime une table et toutes ces références dans geometry_columns.
PostGIS_Full_Version — Affiche la version complète de PostGIS et les informations de compilation.
PostGIS_GEOS_Version — Retourne le numéro de version de la bibliothèque GEOS
PostGIS_LibXML_Version — Retourne le numéro de version de la bibliothèque libxml2.
PostGIS_Lib_Build_Date — Retourne la date de compilation de la bibliotèque PostGIS.
PostGIS_Lib_Version — Retourne le numéro de version de la bibliothèque PostGIS.
PostGIS_PROJ_Version — Retourne le numéro de version de la bibliothèque PROJ4.
PostGIS_Scripts_Build_Date — Retourne la date de génération des scripts PostGIS.
PostGIS_Scripts_Installed — Retourne le numéro de version des scripts PostGIS installés dans cette base de données.
PostGIS_Scripts_Released — Retourne le numéro de version des scripts PostGIS livrés avec la bibliothèque PostGIS installée
PostGIS_Version — Retourne le numéro de version PostGIS et des options de compilation.
Populate_Geometry_Columns — S'assure que les colonnes géométriques sont définies avec un modificateur de type ou dispose des contraintes nécessaires. Garantit un enregistrement correct dans la vue geometry_columns. Par défaut, convertit toutes les colonnes géométriques sans modificateur de type en colonnes avec modificateurs. Pour conserver l'ancien mécanisme, mettre use_typmod=false
UpdateGeometrySRID — Updates the SRID of all features in a geometry column, geometry_columns metadata and srid. If it was enforced with constraints, the constraints will be updated with new srid constraint. If the old was enforced by type definition, the type definition will be changed.

Name

AddGeometryColumn — Ajoute une colonne géométrique à une table attributaire existante. Utilise par défaut le modificateur de type lors de la définition de la géométrie, plutôt que des contraintes. Passer le paramètre use_typmod à false pour activer l'ancien mécanisme basé sur les contraintes.

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

Description

Ajoute une colonne géométrique à une table attributaire existante. schema_name est le nom du schéma de la table. srid est un entier positif présent dans la table SPATIAL_REF_SYS. type est le type de géométrie en texte, par exemple 'POLYGON' ou 'MULTILINESTRING'. Une erreur est renvoyée si le schéma n'existe pas (ou n'est pas visible dans le search_path courant) ou si le SRID, type de géométrie ou dimension est invalide.

[Note]

Changement: 2.0.0 Cette fonction ne met plus à jour geometry_columns maintenant que geometry_columns est une vue basée sur le catalogue système. Par défaut, elle ne créée plus de contraintes mais utilise le modificateur de type de PostgreSQL. Ainsi, par exemple, créer une colonne de type POINT WGS84 est désormais équivalent à: ALTER TABLE some_table ADD COLUMN geom geometry(Point,4326);

Changement: 2.0.0 Si l'ancien mécanisme basé sur les contraintes est nécessaire, utiliser le paramètre use_typmod avec la valeur false.

[Note]

Changement: 2.0.0 Les vues ne peuvent plus être enregistrées dans geometry_columns. Cependant, les vues construites à partir de tables contenant des géométries définies avec le modificateur de type et n'utilisant pas de fonctions d'encapsulation seront enregistrées dans la vue geometry_columns car elles héritent du mécanisme des tables dont elles sont issues. Les vues utilisant des fonctions renvoyant d'autres géométries doivent être transtypées vers des géométries avec modificateur de type pour pouvoir être correctement référencées dans la vue geometry_columns. Cf. Section 4.3.4, “Manually Registering Geometry Columns in geometry_columns”.

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

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

This method supports Circular Strings and Curves

Amélioration: 2.0.0 introduction du paramètre use_typmod. Le comportement par défaut est de créer une colonne géométrique avec modificateur de type au lieu de contraintes sur la colonne.

Exemples

-- 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 — Supprime une colonne géométrique d'une table spatiale.

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

Description

Supprime une colonne géométrique d'une table spatiale. Note: schema_name doit correspondre au champ f_table_schema de la table geometry_columns.

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

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

This method supports Circular Strings and Curves

[Note]

Changement: 2.0.0 Function assurant la rétro compatibilité. Maintenant que geometry_columns est une vue basée sur les catalogues du système, la colonne géométrique peut etre supprimée d'une table comme tout autre colonne en utilisant ALTER TABLE

Exemples

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 — Supprime une table et toutes ces références dans 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);

Description

Supprime une table et toutes ces références dans geometry_columns. Note: utilise la fonction current_schema() sur les installations PostgreSQL le supportant, si le schéma n'est pas fourni.

[Note]

Changement: 2.0.0 Function assurant la rétro compatibilité. Maintenant que geometry_columns est une vue basée sur les catalogues du système, une table spatiale peut etre supprimée comme tout autre table en utilisant ALTER TABLE

Exemples

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

PostGIS_Full_Version — Affiche la version complète de PostGIS et les informations de compilation.

Synopsis

text PostGIS_Full_Version();

Description

Affiche la version complète de PostGIS et les informations de compilation. Donne également des informations sur la synchronisation entre les bibliothèques et les scripts en conseillant les mises à jour si besoin.

Exemples

SELECT PostGIS_Full_Version();
                                                           postgis_full_version
----------------------------------------------------------------------------------
POSTGIS="2.2.0dev r12699" GEOS="3.5.0dev-CAPI-1.9.0 r3989" SFCGAL="1.0.4" PROJ="Rel. 4.8.0, 6 March 2012" 
GDAL="GDAL 1.11.0, released 2014/04/16" LIBXML="2.7.8" LIBJSON="0.12" RASTER
(1 row)

Name

PostGIS_GEOS_Version — Retourne le numéro de version de la bibliothèque GEOS

Synopsis

text PostGIS_GEOS_Version();

Description

Retourne le numéro de version de la bibliothèque GEOS ou NULL si le support GEOS n'est pas activé

Exemples

SELECT PostGIS_GEOS_Version();
 postgis_geos_version
----------------------
 3.1.0-CAPI-1.5.0
(1 row)

Name

PostGIS_LibXML_Version — Retourne le numéro de version de la bibliothèque libxml2.

Synopsis

text PostGIS_LibXML_Version();

Description

Retourne le numéro de version de la bibliothèque libxml2.

Disponibilité: 1.5

Exemples

SELECT PostGIS_LibXML_Version();
 postgis_libxml_version
----------------------
 2.7.6
(1 row)

Name

PostGIS_Lib_Build_Date — Retourne la date de compilation de la bibliotèque PostGIS.

Synopsis

text PostGIS_Lib_Build_Date();

Description

Retourne la date de compilation de la bibliothèque PostGIS.

Exemples

SELECT PostGIS_Lib_Build_Date();
 postgis_lib_build_date
------------------------
 2008-06-21 17:53:21
(1 row)

Name

PostGIS_Lib_Version — Retourne le numéro de version de la bibliothèque PostGIS.

Synopsis

text PostGIS_Lib_Version();

Description

Retourne le numéro de version de la bibliothèque PostGIS.

Exemples

SELECT PostGIS_Lib_Version();
 postgis_lib_version
---------------------
 1.3.3
(1 row)

Name

PostGIS_PROJ_Version — Retourne le numéro de version de la bibliothèque PROJ4.

Synopsis

text PostGIS_PROJ_Version();

Description

Retourne le numéro de version de la bibliothèque PROJ4, ou NULL si PROJ4 n'est pas installée.

Exemples

SELECT PostGIS_PROJ_Version();
  postgis_proj_version
-------------------------
 Rel. 4.4.9, 29 Oct 2004
(1 row)

Name

PostGIS_Scripts_Build_Date — Retourne la date de génération des scripts PostGIS.

Synopsis

text PostGIS_Scripts_Build_Date();

Description

Retourne la date de génération des scripts PostGIS.

Disponibilité: 1.0.0RC1

Exemples

SELECT PostGIS_Scripts_Build_Date();
  postgis_scripts_build_date
-------------------------
 2007-08-18 09:09:26
(1 row)

Name

PostGIS_Scripts_Installed — Retourne le numéro de version des scripts PostGIS installés dans cette base de données.

Synopsis

text PostGIS_Scripts_Installed();

Description

Retourne le numéro de version des scripts PostGIS installés dans cette base de données

[Note]

Si la sortie de cette fonction ne correspond pas à la sortie de PostGIS_Scripts_Released cela veut probablement dire que la mise à jour de la base de données n'a pas fonctionné. Cf. section Upgrading pour plus d'information

Disponibilité: 0.9.0

Exemples

SELECT PostGIS_Scripts_Installed();
  postgis_scripts_installed
-------------------------
 1.5.0SVN
(1 row)

Name

PostGIS_Scripts_Released — Retourne le numéro de version des scripts PostGIS livrés avec la bibliothèque PostGIS installée

Synopsis

text PostGIS_Scripts_Released();

Description

Retourne le numéro de version des scripts PostGIS livrés avec la bibliothèque PostGIS installée.

[Note]

A partir de la version 1.1.0, cette fonction retourne la même valeur que PostGIS_Lib_Version. Conservée pour rétro compatibilité.

Disponibilité: 0.9.0

Exemples

SELECT PostGIS_Scripts_Released();
  postgis_scripts_released
-------------------------
 1.3.4SVN
(1 row)

Name

PostGIS_Version — Retourne le numéro de version PostGIS et des options de compilation.

Synopsis

text PostGIS_Version();

Description

Retourne le numéro de version PostGIS et des options de compilation.

Exemples

SELECT PostGIS_Version();
                        postgis_version
---------------------------------------
 1.3 USE_GEOS=1 USE_PROJ=1 USE_STATS=1
(1 row)

Name

Populate_Geometry_Columns — S'assure que les colonnes géométriques sont définies avec un modificateur de type ou dispose des contraintes nécessaires. Garantit un enregistrement correct dans la vue geometry_columns. Par défaut, convertit toutes les colonnes géométriques sans modificateur de type en colonnes avec modificateurs. Pour conserver l'ancien mécanisme, mettre use_typmod=false

Synopsis

text Populate_Geometry_Columns(boolean use_typmod=true);

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

Description

S'assure que les colonnes géométriques sont définies avec un modificateur de type ou dispose des contraintes nécessaires pour Garantir un enregistrement correct dans la vue geometry_columns.

For backwards compatibility and for spatial needs such as table inheritance where each child table may have different geometry type, the old check constraint behavior is still supported. If you need the old behavior, you need to pass in the new optional argument as false use_typmod=false. When this is done geometry columns will be created with no type modifiers but will have 3 constraints defined. In particular, this means that every geometry column belonging to a table has at least three constraints:

  • enforce_dims_the_geom - ensures every geometry has the same dimension (see ST_NDims)

  • enforce_geotype_the_geom - ensures every geometry is of the same type (see GeometryType)

  • enforce_srid_the_geom - s'assure que toutes les géométries sont dans la même projection (see ST_SRID)

Si un identifiant de table oid est fourni, cette fonction tente de déterminer le SRID, la dimension et le type géométrique de toutes les colonnes géométriques de la table, ajoutant des contraintes si nécessaire. En cas de succès, une ligne est insérée dans la table geometry_columns, sinon, une erreur est affichée indiquant le problème.

Si un identifiant de vue oid est fourni, comme pour un oid de table, cette fonction tente de déterminer le SRID, la dimension et le type géométrique de toutes les colonnes géométriques de la vue, insérant les informations correspondantes dans la table geometry_columns. Rien n'est fait concernant les contraintes.

La version sans paramètre est un raccourci pour la version avec paramètres. Elle vide puis remplit la table geometry_columns pour chaque table ou vue spatiale de la base, ajoutant les contraintes aux tables si besoin. Retourne un résumé montrant le nombre de colonnes géométriques identifiées dans la base et le nombre inséré dans la table geometry_columns. La version avec paramètres renvoie juste le nombre de lignes insérées dans la table geometry_columns

Disponibilité: 1.4.0

Changement: 2.0.0 Par défaut, utilise les modificateurs de type au lieu de contraintes de vérification pour contraindre les types géométriques. Le comportement basé sur les contraintes peut être activé en mettant le nouveau paramètre use_typmod à false.

Amélioration: 2.0.0 L'argument optionnel use_typmod a été introduit pour controler si les colonnes sont créés avec des modificateurs de type ou des contraintes de vérification.

Exemples

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 — Updates the SRID of all features in a geometry column, geometry_columns metadata and srid. If it was enforced with constraints, the constraints will be updated with new srid constraint. If the old was enforced by type definition, the type definition will be changed.

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

Description

Met à jour le SRID de tous les objets d'une colonne géométrique et met à jour les métadonnées de geometry_columns et la contrainte sur le SRID. Note: utilise la fonction current_schema() sur les installations PostgreSQL le supportant, si le schéma n'est pas fourni.

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

This method supports Circular Strings and Curves

Exemples

Cela va changer le srid de la table roads à 4326 quelle que soit sa valeur avant

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

The prior example is equivalent to this DDL statement

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

If you got the projection wrong (or brought it in as unknown) in load and you wanted to transform to web mercator all in one shot You can do this with DDL but there is no equivalent PostGIS management function to do so in one go.

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

8.4. Fonctions d'accès aux géométries

GeometryType — Retourne le type de la géométrie, par exemple: 'LINESTRING', 'POLYGON', 'MULTIPOINT', etc.
ST_Boundary — Renvoie l'ensemble formant la frontière finie de cette géométrie.
ST_CoordDim — Retourne la dimension des coordonnées de la ST_Geometry.
ST_Dimension — La dimension intrinsèque de l'objet Geometry, inférieure ou égale à la dimension des coordonnées
ST_EndPoint — Returns the last point of a LINESTRING or CIRCULARLINESTRING geometry as a POINT.
ST_Envelope — Renvoie une géométrie représentant la boite englobante de la géométrie donnée, sous forme de double precision (float8).
ST_BoundingDiagonal — Returns the diagonal of the supplied geometry's bounding box.
ST_ExteriorRing — Retourne une ligne représentant l'envelope extérieure du POLYGON. Renvoie NULL si la géométrie n'est pas un polygone. Ne marche pas avec un objet MULTIPOLYGON
ST_GeometryN — Retourne la nième géométrie, n commençant à 1, si la géométrie passée en paramètre est de type GEOMETRYCOLLECTION, (MULTI)POINT, (MULTI)LINESTRING, MULTICURVE ou (MULTI)POLYGON, POLYHEDRALSURFACE. Renvoie NULL dans les autres cas.
ST_GeometryType — Renvoie le type de la géométrie passée en paramètre.
ST_InteriorRingN — Retourne la nième ligne intérieure du polygone passé en paramètre. Renvoie NULL si la géométrie n'est pas un polygone ou si l'index ne correspond pas à un intérieur.
ST_IsCollection — Returns true if all exterior rings are oriented counter-clockwise and all interior rings are oriented clockwise.
ST_IsCollection — Returns true if all exterior rings are oriented clockwise and all interior rings are oriented counter-clockwise.
ST_IsClosed — Renvoie TRUE si les premier et dernier points de la LINESTRING sont identiques. Pour les surface polyhédriques, indique si la surface est surfacique (ouverte) ou volumétrique (fermée).
ST_IsCollection — Renvoie TRUE si le paramètre est une collection (MULTI*, GEOMETRYCOLLECTION, ...)
ST_IsEmpty — Renvoie vrai si la géométrie est une geometrycollection vide, un polygon, un point etc.
ST_IsRing — Renvoie TRUE si la LINESTRING est à la fois fermée et simple.
ST_IsSimple — Renvoie (TRUE) si cette géométrie ne présente pas d'anomalie comme une auto intersection ou des segments tangentiels.
ST_IsValid — Renvoie true si la ST_Geometry est correctement constituée.
ST_IsValidReason — Returns text stating if a geometry is valid or not and if not valid, a reason why.
ST_IsValidDetail — Returns a valid_detail (valid,reason,location) row stating if a geometry is valid or not and if not valid, a reason why and a location where.
ST_M — Retourne les coordonnées M d'un point, ou NULL si non disponible. L'entrée doit être un point.
ST_NDims — Returns coordinate dimension of the geometry as a small int. Values are: 2,3 or 4.
ST_NPoints — Retourne le nombre de points (vertex) d'un objet géométrique.
ST_NRings — Si la géométrie est un polygone ou un multi-polygone renvoi le nombre d'anneaux.
ST_NumGeometries — If geometry is a GEOMETRYCOLLECTION (or MULTI*) return the number of geometries, for single geometries will return 1, otherwise return NULL.
ST_NumInteriorRings — Retourne le nombre de points (vertex) d'un objet géométrique.
ST_NumInteriorRing — Return the number of interior rings of a polygon in the geometry. Synonym for ST_NumInteriorRings.
ST_NumPatches — Return the number of faces on a Polyhedral Surface. Will return null for non-polyhedral geometries.
ST_NumPoints — Retourne le nombre de points d'un objet géométrique dans une valeur ST_LineString ou ST_CircularString.
ST_PatchN — Return the 1-based Nth geometry (face) if the geometry is a POLYHEDRALSURFACE, POLYHEDRALSURFACEM. Otherwise, return NULL.
ST_PointN — Return the Nth point in the first LineString or circular LineString in the geometry. Negative values are counted backwards from the end of the LineString. Returns NULL if there is no linestring in the geometry.
ST_NPoints — Returns a MultiPoint containing all of the coordinates of a geometry.
ST_SRID — Returns the spatial reference identifier for the ST_Geometry as defined in spatial_ref_sys table.
ST_StartPoint — Returns the first point of a LINESTRING geometry as a POINT.
ST_Summary — Returns a text summary of the contents of the geometry.
ST_X — Return the X coordinate of the point, or NULL if not available. Input must be a point.
ST_XMax — Returns X maxima of a bounding box 2d or 3d or a geometry.
ST_XMin — Returns X minima of a bounding box 2d or 3d or a geometry.
ST_Y — Return the Y coordinate of the point, or NULL if not available. Input must be a point.
ST_YMax — Returns Y maxima of a bounding box 2d or 3d or a geometry.
ST_YMin — Returns Y minima of a bounding box 2d or 3d or a geometry.
ST_Z — Return the Z coordinate of the point, or NULL if not available. Input must be a point.
ST_ZMax — Returns Z minima of a bounding box 2d or 3d or a geometry.
ST_Zmflag — Returns ZM (dimension semantic) flag of the geometries as a small int. Values are: 0=2d, 1=3dm, 2=3dz, 3=4d.
ST_ZMin — Returns Z minima of a bounding box 2d or 3d or a geometry.

Name

GeometryType — Retourne le type de la géométrie, par exemple: 'LINESTRING', 'POLYGON', 'MULTIPOINT', etc.

Synopsis

text GeometryType(geometry geomA);

Description

Retourne le type de la géométrie, par exemple: 'LINESTRING', 'POLYGON', 'MULTIPOINT', etc.

OGC SPEC s2.1.1.1 - Retourne le nom du sous type instanciable de la géométrie. Le nom est retourné sous forme de texte.

[Note]

Cette fonction indique si la géométrie comporte une dimension de type mesure, en retournant un texte de de la forme 'POINTM'.

Amélioration: 2.0.0 introduction du support TIN, Triangles et surfaces polyhédriques.

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

This method supports Circular Strings and Curves

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

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

Exemples

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    

Voir aussi

ST_GeometryType


Name

ST_Boundary — Renvoie l'ensemble formant la frontière finie de cette géométrie.

Synopsis

geometry ST_Boundary(geometry geomA);

Description

Renvoie l'ensemble formant la frontière finie de cette géométrie. La notion de frontière est définie dans la section 3.12.3.2 des spécifications OGC. Le résultat de cette fonction est un ensemble topologiquement fermé, représentable avec les types de base, comme décrit dans la section 3.12.2 des spécifications OGC.

Réalisé par le module GEOS

[Note]

Avant la version 2.0.0, cette fonction renvoie une exception si une GEOMETRYCOLLECTION est passée en paramètre. A partir de la 2.0.0, la fonction renvoie null (paramètre non supporté).

This method implements the OpenGIS Simple Features Implementation Specification for SQL 1.1. OGC SPEC s2.1.1.1

This method implements the SQL/MM specification. SQL-MM 3: 5.1.14

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

Enhanced: 2.1.0 support for Triangle was introduced

Exemples

Linestring with boundary points overlaid

SELECT ST_Boundary(geom)
FROM (SELECT 'LINESTRING(100 150,50 60, 70 80, 160 170)'::geometry As geom) As f;
                                

-- ST_AsText output
MULTIPOINT(100 150,160 170)

polygon holes with boundary multilinestring

SELECT ST_Boundary(geom)
FROM (SELECT
'POLYGON (( 10 130, 50 190, 110 190, 140 150, 150 80, 100 10, 20 40, 10 130 ),
        ( 70 40, 100 50, 120 80, 80 110, 50 90, 70 40 ))'::geometry As geom) As f;
                                

-- ST_AsText output
MULTILINESTRING((10 130,50 190,110 190,140 150,150 80,100 10,20 40,10 130),
        (70 40,100 50,120 80,80 110,50 90,70 40))

SELECT ST_AsText(ST_Boundary(ST_GeomFromText('LINESTRING(1 1,0 0, -1 1)')));
st_astext
-----------
MULTIPOINT(1 1,-1 1)

SELECT ST_AsText(ST_Boundary(ST_GeomFromText('POLYGON((1 1,0 0, -1 1, 1 1))')));
st_astext
----------
LINESTRING(1 1,0 0,-1 1,1 1)

--Using a 3d polygon
SELECT ST_AsEWKT(ST_Boundary(ST_GeomFromEWKT('POLYGON((1 1 1,0 0 1, -1 1 1, 1 1 1))')));

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

--Using a 3d multilinestring
SELECT ST_AsEWKT(ST_Boundary(ST_GeomFromEWKT('MULTILINESTRING((1 1 1,0 0 0.5, -1 1 1),(1 1 0.5,0 0 0.5, -1 1 0.5, 1 1 0.5) )')));

st_asewkt
----------
MULTIPOINT(-1 1 1,1 1 0.75)

Name

ST_CoordDim — Retourne la dimension des coordonnées de la ST_Geometry.

Synopsis

integer ST_CoordDim(geometry geomA);

Description

Retourne la dimension des coordonnées d'une valeur ST_Geometry.

Alias SQL/MM pour la fonction ST_NDims

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

This method implements the SQL/MM specification. SQL-MM 3: 5.1.3

This method supports Circular Strings and Curves

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

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

Exemples

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

                

Voir aussi

ST_NDims


Name

ST_Dimension — La dimension intrinsèque de l'objet Geometry, inférieure ou égale à la dimension des coordonnées

Synopsis

integer ST_Dimension(geometry g);

Description

La dimension intrinsèque de l'objet Geometry, inférieure ou égale à la dimension des coordonnées. Section 2.1.1.1 des spécifications OGC. Retourne 0 pour un POINT, 1 pour une LINESTRING, 2 pour un POLYGON, et la dimesion maximale des éléments d'une GEOMETRYCOLLECTION. Renvoie NULL pour les géométries vides (GEOMETRY EMPTY).

This method implements the SQL/MM specification. SQL-MM 3: 5.1.2

Amélioration: 2.0.0 introduction du support TIN et surfaces polyhédriques. Ne renvoie plus une exception si une GEOMETRY EMPTY est passée.

[Note]

Avant la version 2.0.0, cette fonction renvoie une exception si une GEOMETRY EMPT est passée en paramètre.

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

Exemples

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

Voir aussi

ST_NDims


Name

ST_EndPoint — Returns the last point of a LINESTRING or CIRCULARLINESTRING geometry as a POINT.

Synopsis

boolean ST_EndPoint(geometry g);

Description

Retourne le dernier point d'une LINESTRING sous la forme d'un POINT, ou NULL si le paramètre n'est pas une LINESTRING.

This method implements the SQL/MM specification. SQL-MM 3: 7.1.4

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

This method supports Circular Strings and Curves

[Note]

Changement: 2.0.0: ne supporte plus les géométries multilinestring avec un seul élément. Dans les anciennes version de PostGIS, une multilinestring ne contenant qu'une ligne renvoyait le point d'origine de la ligne. A partir de la version 2.0.0, la fonction renvoie NULL comme avec toute autre multilinestring. L'ancien comportement n'était pas documenté. Le nouveau comportement peut renvoyer null si l'on considère que la table contient des LINESTRING (multilinestring avec un seul élément)

Exemples

postgis=# SELECT ST_AsText(ST_EndPoint('LINESTRING(1 1, 2 2, 3 3)'::geometry));
 st_astext
------------
 POINT(3 3)
(1 row)

postgis=# SELECT ST_EndPoint('POINT(1 1)'::geometry) IS NULL AS is_null;
  is_null
----------
 t
(1 row)

--3d endpoint
SELECT ST_AsEWKT(ST_EndPoint('LINESTRING(1 1 2, 1 2 3, 0 0 5)'));
  st_asewkt
--------------
 POINT(0 0 5)
(1 row)

Name

ST_Envelope — Renvoie une géométrie représentant la boite englobante de la géométrie donnée, sous forme de double precision (float8).

Synopsis

geometry ST_Envelope(geometry g1);

Description

Renvoie une géométrie représentant la boite englobante de la géométrie donnée, sous forme de float8. Le polygone est défini par les coins de la boite englobante ((MINX, MINY), (MINX, MAXY), (MAXX, MAXY), (MAXX, MINY), (MINX, MINY)). (PostGIS ajoute également les coordonnées ZMIN/ZMAX).

Les cas dégénérés (lignes verticales, points) renvoient une géométrie de dimension inférieure à celle d'un POLYGON, par exemple POINT ou LINESTRING.

Disponibilité: 1.5.0 changement pour renvoyer un type double précision à la place de float4

This method implements the OpenGIS Simple Features Implementation Specification for SQL 1.1. s2.1.1.1

This method implements the SQL/MM specification. SQL-MM 3: 5.1.15

Exemples

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;


        

Voir aussi

Box2D, Box3D


Name

ST_BoundingDiagonal — Returns the diagonal of the supplied geometry's bounding box.

Synopsis

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

Description

Returns the diagonal of the supplied geometry's bounding box as linestring. If the input geometry is empty, the diagonal line is also empty, otherwise it is a 2-points linestring with minimum values of each dimension in its start point and maximum values in its end point.

The returned linestring geometry always retains SRID and dimensionality (Z and M presence) of the input geometry.

The fits parameter specifies if the best fit is needed. If false, the diagonal of a somewhat larger bounding box can be accepted (is faster to obtain for geometries with a lot of vertices). In any case the bounding box of the returned diagonal line always covers the input geometry.

[Note]

In degenerate cases (a single vertex in input) the returned linestring will be topologically invalid (no interior). This does not make the return semantically invalid.

Availability: 2.2.0

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

This function supports M coordinates.

Exemples

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

Name

ST_ExteriorRing — Retourne une ligne représentant l'envelope extérieure du POLYGON. Renvoie NULL si la géométrie n'est pas un polygone. Ne marche pas avec un objet MULTIPOLYGON

Synopsis

geometry ST_ExteriorRing(geometry a_polygon);

Description

Retourne une ligne représentant l'envelope extérieure du POLYGON. Renvoie NULL si la géométrie n'est pas un polygone.

[Note]

Ne fonctionne qu'avec des géométries POLYGON

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

This method implements the SQL/MM specification. SQL-MM 3: 8.2.3, 8.3.3

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

Exemples

--If you have a table of polygons
SELECT gid, ST_ExteriorRing(the_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(the_geom)) AS erings
        FROM (SELECT gid, (ST_Dump(the_geom)).geom As the_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 — Retourne la nième géométrie, n commençant à 1, si la géométrie passée en paramètre est de type GEOMETRYCOLLECTION, (MULTI)POINT, (MULTI)LINESTRING, MULTICURVE ou (MULTI)POLYGON, POLYHEDRALSURFACE. Renvoie NULL dans les autres cas.

Synopsis

geometry ST_GeometryN(geometry geomA, integer n);

Description

Retourne la nième géométrie, n commençant à 1, si la géométrie passée en paramètre est de type GEOMETRYCOLLECTION, (MULTI)POINT, (MULTI)LINESTRING, MULTICURVE ou (MULTI)POLYGON, POLYHEDRALSURFACE. Renvoie NULL dans les autres cas.

[Note]

L'index commence à 1 pour respecter les spécificarions OGC depuis la version 0.8.0. Dans les versions antérieures, l'index commençait à 0.

[Note]

Si toutes les géométries composant une géométrie doivent être extraites, il faut mieux utiliser la fonction ST_Dump, qui est plus efficace et accepte les types simples en paramètre.

Amélioration: 2.0.0 introduction du support TIN, Triangles et surfaces polyhédriques.

Changement: 2.0.0. Les versions antérieures renvoient NULL pour les géometries simples (un seul objet). Renvoie désormais la géométrie pour le cas ST_GeometryN(..,1).

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

This method implements the SQL/MM specification. SQL-MM 3: 9.1.5

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

This method supports Circular Strings and Curves

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

Exemples

--Extracting a subset of points from a 3d multipoint
SELECT n, ST_AsEWKT(ST_GeometryN(the_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(the_geom)
        CROSS JOIN generate_series(1,100) n
WHERE n <= ST_NumGeometries(the_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(the_geom, n)
FROM sometable CROSS JOIN generate_series(1,100) n
WHERE n <= ST_NumGeometries(the_geom);

Exemples TIN, Triangle et Surfaces Polyhédriques

-- 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 — Renvoie le type de la géométrie passée en paramètre.

Synopsis

text ST_GeometryType(geometry g1);

Description

Renvoie le type de la géométrie sous forme de texte, par exemple: 'ST_Linestring', 'ST_Polygon','ST_MultiPolygon' etc. Cette fonction diffère de GeometryType(geometry) par la casse du texte renvoyé et par le préfixe ST_ en début de texte. N'indique pas si la géométrie comporte une dimension MESURE.

Amélioration: 2.0.0 introduction du support des surfaces polyhédriques.

This method implements the SQL/MM specification. SQL-MM 3: 5.1.4

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

This function supports Polyhedral surfaces.

Exemples

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    

Voir aussi

GeometryType


Name

ST_InteriorRingN — Retourne la nième ligne intérieure du polygone passé en paramètre. Renvoie NULL si la géométrie n'est pas un polygone ou si l'index ne correspond pas à un intérieur.

Synopsis

geometry ST_InteriorRingN(geometry a_polygon, integer n);

Description

Retourne la nième ligne intérieure du polygone passé en paramètre. Renvoie NULL si la géométrie n'est pas un polygone ou si l'index ne correspond pas à un intérieur. L'index démarre à 1.

[Note]

Ne support pas les MULTIPOLYGON. Utiliser en association avec ST_Dump pour les MULTIPOLYGON

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

This method implements the SQL/MM specification. SQL-MM 3: 8.2.6, 8.3.5

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

Exemples

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

Name

ST_IsCollection — Returns true if all exterior rings are oriented counter-clockwise and all interior rings are oriented clockwise.

Synopsis

boolean ST_IsEmpty(geometry geomA);

Description

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.

Renvoie vrai si la géométrie est une geometrycollection vide, un polygon, un point etc.

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

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

This function supports M coordinates.


Name

ST_IsCollection — Returns true if all exterior rings are oriented clockwise and all interior rings are oriented counter-clockwise.

Synopsis

boolean ST_IsEmpty(geometry geomA);

Description

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.

Renvoie vrai si la géométrie est une geometrycollection vide, un polygon, un point etc.

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

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

This function supports M coordinates.


Name

ST_IsClosed — Renvoie TRUE si les premier et dernier points de la LINESTRING sont identiques. Pour les surface polyhédriques, indique si la surface est surfacique (ouverte) ou volumétrique (fermée).

Synopsis

boolean ST_IsClosed(geometry g);

Description

Renvoie TRUE si les premier et dernier points de la LINESTRING sont identiques. Pour les surface polyhédriques, indique si la surface est surfacique (ouverte) ou volumétrique (fermée).

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

This method implements the SQL/MM specification. SQL-MM 3: 7.1.5, 9.3.3

[Note]

La norme SQL-MM indique que le résultat de la fonction ST_IsClosed(NULL) doit être 0 ; PostGIS renvoie NULL.

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

This method supports Circular Strings and Curves

Amélioration: 2.0.0 introduction du support des surfaces polyhédriques.

This function supports Polyhedral surfaces.

Exemples: points et lignes

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)

Exemples: surfaces polyhédriques

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

Voir aussi

ST_IsRing


Name

ST_IsCollection — Renvoie TRUE si le paramètre est une collection (MULTI*, GEOMETRYCOLLECTION, ...)

Synopsis

boolean ST_IsCollection(geometry g);

Description

Renvoie TRUE le type de la géométrie est soit:

  • GEOMETRYCOLLECTION

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

  • COMPOUNDCURVE

[Note]

Cette fonction analyse le type de la géométrie. Renvoie TRUE pour les collections vides ou ne contenant q'un seul élément.

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

This method supports Circular Strings and Curves

Exemples

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)

Name

ST_IsEmpty — Renvoie vrai si la géométrie est une geometrycollection vide, un polygon, un point etc.

Synopsis

boolean ST_IsEmpty(geometry geomA);

Description

Renvoie vrai si la géométrie est une géométrie vide. Si le résultat est vrai alors cette géométrie représente une geometrycollection vide, un polygon, un point etc.

[Note]

La norme SQL-MM stipule que ST_IsEmpty(NULL) doit renvoyer 0. PostGIS renvoie NULL.

This method implements the OpenGIS Simple Features Implementation Specification for SQL 1.1. s2.1.1.1

This method implements the SQL/MM specification. SQL-MM 3: 5.1.7

This method supports Circular Strings and Curves

[Warning]

Changement: 2.0.0 dans les version précédentes de PostGIS ST_GeomFromText('GEOMETRYCOLLECTION(EMPTY)') etait autorisé. C'est désormais interdit dans PostGIS 2.0.0 pour respecter la norme SQL/MM.

Exemples

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_IsRing — Renvoie TRUE si la LINESTRING est à la fois fermée et simple.

Synopsis

boolean ST_IsRing(geometry g);

Description

Renvoie TRUE si cette LINESTRING est à la fois ST_IsClosed (ST_StartPoint(g) ~= ST_Endpoint(g)) et ST_IsSimple (pas d'auto intersection).

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

This method implements the SQL/MM specification. SQL-MM 3: 7.1.6

[Note]

La norme SQL-MM stipule que ST_IsRing(NULL) doit renvoyer 0. PostGIS renvoie NULL.

Exemples

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

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

Name

ST_IsSimple — Renvoie (TRUE) si cette géométrie ne présente pas d'anomalie comme une auto intersection ou des segments tangentiels.

Synopsis

boolean ST_IsSimple(geometry geomA);

Description

Renvoie TRUE si cette géométrie ne présente pas d'anomalie comme une auto intersection ou des segments tangentiels. Pour plus d'information sur les notions OGC de simplicité et de validité, se référer à "Ensuring OpenGIS compliancy of geometries"

[Note]

La norme SQL-MM indique que le résultat de la fonction ST_IsSimple(NULL) doit être 0 ; PostGIS renvoie NULL.

This method implements the OpenGIS Simple Features Implementation Specification for SQL 1.1. s2.1.1.1

This method implements the SQL/MM specification. SQL-MM 3: 5.1.8

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

Exemples

SELECT ST_IsSimple(ST_GeomFromText('POLYGON((1 2, 3 4, 5 6, 1 2))'));
 st_issimple
-------------
 t
(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)

Voir aussi

ST_IsValid


Name

ST_IsValid — Renvoie true si la ST_Geometry est correctement constituée.

Synopsis

boolean ST_IsValid(geometry g);

boolean ST_IsValid(geometry g, integer flags);

Description

Test if an ST_Geometry value is well formed. For geometries that are invalid, the PostgreSQL NOTICE will provide details of why it is not valid. For more information on the OGC's definition of geometry simplicity and validity, refer to "Ensuring OpenGIS compliancy of geometries"

[Note]

SQL-MM définit le résultat de ST_IsValid(NULL) comme 0, pendant que PostGIS retourne NULL.

The version accepting flags is available starting with 2.0.0 and requires GEOS >= 3.3.0. Such version does not print a NOTICE explaining the invalidity. Allowed flags are documented in ST_IsValidDetail.

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

This method implements the SQL/MM specification. 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.

Exemples

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_IsValidReason — Returns text stating if a geometry is valid or not and if not valid, a reason why.

Synopsis

text ST_IsValidReason(geometry geomA);

text ST_IsValidReason(geometry geomA, integer flags);

Description

Returns text stating if a geometry is valid or not an if not valid, 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.

Disponibilité: 1.4 - nécessite GEOS >= 3.1.0.

Disponibilité: 2.0 - nécessite GEOS >= >= 3.3.0

Exemples

--First 3 Rejects from a successful quintuplet experiment
SELECT gid, ST_IsValidReason(the_geom) as validity_info
FROM
(SELECT ST_MakePolygon(ST_ExteriorRing(e.buff), ST_Accum(f.line)) As the_geom, gid
FROM (SELECT ST_Buffer(ST_MakePoint(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_MakePoint(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(the_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

                

Name

ST_IsValidDetail — Returns a valid_detail (valid,reason,location) row stating if a geometry is valid or not and if not valid, a reason why and a location where.

Synopsis

valid_detail ST_IsValidDetail(geometry geom);

valid_detail ST_IsValidDetail(geometry geom, integer flags);

Description

Returns a valid_detail row, formed by 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 substitute and improve the combination of ST_IsValid and ST_IsValidReason to generate a detailed report of invalid geometries.

The 'flags' argument is a bitfield. It can have the following values:

  • 1: Consider self-intersecting rings forming holes as valid. This is also know as "the ESRI flag". Note that this is against the OGC model.

Disponibilité: 2.0.0 - nécessite GEOS >= 3.3.0.

Exemples

--First 3 Rejects from a successful quintuplet experiment
SELECT gid, reason(ST_IsValidDetail(the_geom)), ST_AsText(location(ST_IsValidDetail(the_geom))) as location
FROM
(SELECT ST_MakePolygon(ST_ExteriorRing(e.buff), ST_Accum(f.line)) As the_geom, gid
FROM (SELECT ST_Buffer(ST_MakePoint(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_MakePoint(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(the_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_M — Retourne les coordonnées M d'un point, ou NULL si non disponible. L'entrée doit être un point.

Synopsis

float ST_M(geometry a_point);

Description

Return the M coordinate of the point, or NULL if not available. Input must be a point.

[Note]

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

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

This method implements the SQL/MM specification.

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

Exemples

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

                

Voir aussi

???, ST_X, ST_Y, ST_Z


Name

ST_NDims — Returns coordinate dimension of the geometry as a small int. Values are: 2,3 or 4.

Synopsis

integer ST_NDims(geometry g1);

Description

Returns the coordinate dimension of the geometry. PostGIS supports 2 - (x,y) , 3 - (x,y,z) or 2D with measure - x,y,m, and 4 - 3D with measure space x,y,z,m

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

Exemples

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 — Retourne le nombre de points (vertex) d'un objet géométrique.

Synopsis

integer ST_NPoints(geometry g1);

Description

Retourne le nombre de points d'un objet géométrique. Cela fonctionne pour tous les types de géométrie.

Amélioration: 2.0.0 introduction du support des surfaces polyhédriques.

[Note]

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

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

This method supports Circular Strings and Curves

This function supports Polyhedral surfaces.

Exemples

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 dans un espace en 3 Dimension
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

Voir aussi

ST_NumPoints


Name

ST_NRings — Si la géométrie est un polygone ou un multi-polygone renvoi le nombre d'anneaux.

Synopsis

integer ST_NRings(geometry geomA);

Description

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

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

This method supports Circular Strings and Curves

Exemples

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

Name

ST_NumGeometries — If geometry is a GEOMETRYCOLLECTION (or MULTI*) return the number of geometries, for single geometries will return 1, otherwise return NULL.

Synopsis

integer ST_NumGeometries(geometry geom);

Description

Returns the number of Geometries. If geometry is a GEOMETRYCOLLECTION (or MULTI*) return the number of geometries, for single geometries will return 1, otherwise return NULL.

Amélioration: 2.0.0 introduction du support TIN, Triangles et surfaces polyhédriques.

Changed: 2.0.0 In prior versions this would return NULL if the geometry was not a collection/MULTI type. 2.0.0+ now returns 1 for single geometries e.g POLYGON, LINESTRING, POINT.

This method implements the SQL/MM specification. SQL-MM 3: 9.1.4

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

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

Exemples

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

Name

ST_NumInteriorRings — Retourne le nombre de points (vertex) d'un objet géométrique.

Synopsis

integer ST_NumInteriorRings(geometry a_polygon);

Description

Retourne la nième ligne intérieure du polygone passé en paramètre. Renvoie NULL si la géométrie n'est pas un polygone ou si l'index ne correspond pas à un intérieur.

This method implements the SQL/MM specification. SQL-MM 3: 8.2.5

Changed: 2.0.0 - in prior versions it would allow passing a MULTIPOLYGON, returning the number of interior rings of first POLYGON.

Exemples

--If you have a regular polygon
SELECT gid, field1, field2, ST_NumInteriorRings(the_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(the_geom)) AS numholes
FROM (SELECT gid, field1, field2, (ST_Dump(the_geom)).geom As the_geom
        FROM sometable) As foo
GROUP BY gid, field1,field2;
                        

Name

ST_NumInteriorRing — Return the number of interior rings of a polygon in the geometry. Synonym 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);

Description

Return the number of faces on a Polyhedral Surface. Will return null for non-polyhedral geometries. This is an alias for ST_NumGeometries to support MM naming. Faster to use ST_NumGeometries if you don't care about MM convention.

Disponibilité : 2.0.0

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

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

This method implements the SQL/MM specification. SQL-MM 3: ?

This function supports Polyhedral surfaces.

Exemples

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 — Retourne le nombre de points d'un objet géométrique dans une valeur ST_LineString ou ST_CircularString.

Synopsis

integer ST_NumPoints(geometry g1);

Description

Return the number of points in an ST_LineString or ST_CircularString value. Prior to 1.4 only works with Linestrings as the specs state. From 1.4 forward this is an alias for ST_NPoints which returns number of vertexes for not just line strings. Consider using ST_NPoints instead which is multi-purpose and works with many geometry types.

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

This method implements the SQL/MM specification. SQL-MM 3: 7.2.4

Exemples

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

Voir aussi

ST_NPoints


Name

ST_PatchN — Return the 1-based Nth geometry (face) if the geometry is a POLYHEDRALSURFACE, POLYHEDRALSURFACEM. Otherwise, return NULL.

Synopsis

geometry ST_PatchN(geometry geomA, integer n);

Description

>Return the 1-based Nth geometry (face) if the geometry is a POLYHEDRALSURFACE, POLYHEDRALSURFACEM. Otherwise, return NULL. This returns the same answer as ST_GeometryN for Polyhedral Surfaces. Using ST_GemoetryN is faster.

[Note]

Index is 1-based.

[Note]

Si toutes les géométries composant une géométrie doivent être extraites, ST_Dump sera plus efficace.

Disponibilité : 2.0.0

This method implements the SQL/MM specification. SQL-MM 3: ?

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

This function supports Polyhedral surfaces.

Exemples

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

Name

ST_PointN — Return the Nth point in the first LineString or circular LineString in the geometry. Negative values are counted backwards from the end of the LineString. Returns NULL if there is no linestring in the geometry.

Synopsis

geometry ST_PointN(geometry a_linestring, integer n);

Description

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]

L'index commence à 1 pour respecter les spécificarions OGC depuis la version 0.8.0. Dans les versions antérieures, l'index commençait à 0.

[Note]

If you want to get the nth point of each line string in a multilinestring, use in conjunction with ST_Dump

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

This method implements the SQL/MM specification. SQL-MM 3: 7.2.5, 7.3.5

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

This method supports Circular Strings and Curves

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

Exemples

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

SELECT st_astext(f)
FROM ST_GeometryFromtext('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)"

Voir aussi

ST_NPoints


Name

ST_NPoints — Returns a MultiPoint containing all of the coordinates of a geometry.

Synopsis

geometry ST_StartPoint(geometry geomA);

Description

Returns a MultiPoint containing all of the coordinates of a geometry. Does not remove points that are duplicated in the input geometry, including start and end points of ring geometries. (If this behavior is undesired, duplicates may be removed using ST_RemoveRepeatedPoints).

M and Z ordinates will be preserved if present.

This method supports Circular Strings and Curves

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

Disponibilité : 2.0.0

Exemples

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_SRID — Returns the spatial reference identifier for the ST_Geometry as defined in spatial_ref_sys table.

Synopsis

integer ST_SRID(geometry g1);

Description

Returns the spatial reference identifier for the ST_Geometry as defined in spatial_ref_sys table. Section 4.3.1, “The SPATIAL_REF_SYS Table and 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.

This method implements the OpenGIS Simple Features Implementation Specification for SQL 1.1. s2.1.1.1

This method implements the SQL/MM specification. SQL-MM 3: 5.1.5

This method supports Circular Strings and Curves

Exemples

SELECT ST_SRID(ST_GeomFromText('POINT(-71.1043 42.315)',4326));
                --result
                4326
                

Name

ST_StartPoint — Returns the first point of a LINESTRING geometry as a POINT.

Synopsis

geometry ST_StartPoint(geometry geomA);

Description

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

This method implements the SQL/MM specification. SQL-MM 3: 7.1.3

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

This method supports Circular Strings and Curves

[Note]

Changement: 2.0.0: ne supporte plus les géométries multilinestring avec un seul élément. Dans les anciennes version de PostGIS, une multilinestring ne contenant qu'une ligne renvoyait le point d'origine de la ligne. A partir de la version 2.0.0, la fonction renvoie NULL comme avec toute autre multilinestring. L'ancien comportement n'était pas documenté. Le nouveau comportement peut renvoyer null si l'on considère que la table contient des LINESTRING (multilinestring avec un seul élément)

Exemples

SELECT ST_AsText(ST_StartPoint('LINESTRING(0 1, 0 2)'::geometry));
 st_astext
------------
 POINT(0 1)
(1 row)

SELECT ST_StartPoint('POINT(0 1)'::geometry) IS NULL AS is_null;
  is_null
----------
 t
(1 row)

--3d line
SELECT ST_AsEWKT(ST_StartPoint('LINESTRING(0 1 1, 0 2 2)'::geometry));
 st_asewkt
------------
 POINT(0 1 1)
(1 row)

-- circular linestring --
SELECT ST_AsText(ST_StartPoint('CIRCULARSTRING(5 2,-3 1.999999, -2 1, -4 2, 5 2)'::geometry));
 st_astext
------------
 POINT(5 2)

Name

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

Synopsis

text ST_Summary(geometry g);

text ST_Summary(geography g);

Description

Returns a text summary of the contents of the geometry.

Flags shown square brackets after the geometry type have the following meaning:

  • M : possède une ordonnée M

  • Z : possède une coordonnée Z

  • B : possède une bounding box en cache

  • G: is geodetic (geography)

  • S: has spatial reference system

This method supports Circular Strings and Curves

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

Availability: 1.2.2

Enhanced: 2.0.0 added support for geography

Enhanced: 2.1.0 S flag to denote if has a known spatial reference system

Enhanced: 2.2.0 Added support for TIN and Curves

Exemples

=# 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 — Return the X coordinate of the point, or NULL if not available. Input must be a point.

Synopsis

float ST_X(geometry a_point);

Description

Return the X coordinate of the point, or NULL if not available. Input must be a point.

[Note]

If you want to get the max min x values of any geometry look at ST_XMin, ST_XMax functions.

This method implements the SQL/MM specification. SQL-MM 3: 6.1.3

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

Exemples

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_XMax — Returns X maxima of a bounding box 2d or 3d or a geometry.

Synopsis

float ST_XMax(box3d aGeomorBox2DorBox3D);

Description

Returns X maxima of a bounding box 2d or 3d or a geometry.

[Note]

Although this function is only defined for box3d, it will work for box2d and geometry because of the auto-casting behavior defined for geometries and box2d. However you can not feed it a geometry or box2d text representation, since that will not auto-cast.

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

This method supports Circular Strings and Curves

Exemples

SELECT ST_XMax('BOX3D(1 2 3, 4 5 6)');
st_xmax
-------
4

SELECT ST_XMax(ST_GeomFromText('LINESTRING(1 3 4, 5 6 7)'));
st_xmax
-------
5

SELECT ST_XMax(CAST('BOX(-3 2, 3 4)' As box2d));
st_xmax
-------
3
--Observe CELA NE FONCTIONNE PAS par ce qu'il tentera de caster la représentation de la chaîne vers BOX3D
SELECT ST_XMax('LINESTRING(1 3, 5 6)');

--ERREUR :  BOX3D parser - ne démarre pas avec BOX3D(

SELECT ST_XMax(ST_GeomFromEWKT('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)'));
st_xmax
--------
220288.248780547
                

Name

ST_XMin — Returns X minima of a bounding box 2d or 3d or a geometry.

Synopsis

float ST_XMin(box3d aGeomorBox2DorBox3D);

Description

Returns X minima of a bounding box 2d or 3d or a geometry.

[Note]

Although this function is only defined for box3d, it will work for box2d and geometry because of the auto-casting behavior defined for geometries and box2d. However you can not feed it a geometry or box2d text representation, since that will not auto-cast.

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

This method supports Circular Strings and Curves

Exemples

SELECT ST_XMin('BOX3D(1 2 3, 4 5 6)');
st_xmin
-------
1

SELECT ST_XMin(ST_GeomFromText('LINESTRING(1 3 4, 5 6 7)'));
st_xmin
-------
1

SELECT ST_XMin(CAST('BOX(-3 2, 3 4)' As box2d));
st_xmin
-------
-3
--Observe THIS DOES NOT WORK because it will try to autocast the string representation to a BOX3D
SELECT ST_XMin('LINESTRING(1 3, 5 6)');

--ERROR: BOX3D parser - doesn't start with BOX3D(

SELECT ST_XMin(ST_GeomFromEWKT('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)'));
st_xmin
--------
220186.995121892
                

Name

ST_Y — Return the Y coordinate of the point, or NULL if not available. Input must be a point.

Synopsis

float ST_Y(geometry a_point);

Description

Return the Y coordinate of the point, or NULL if not available. Input must be a point.

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

This method implements the SQL/MM specification. SQL-MM 3: 6.1.4

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

Exemples

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_YMax — Returns Y maxima of a bounding box 2d or 3d or a geometry.

Synopsis

float ST_YMax(box3d aGeomorBox2DorBox3D);

Description

Returns Y maxima of a bounding box 2d or 3d or a geometry.

[Note]

Although this function is only defined for box3d, it will work for box2d and geometry because of the auto-casting behavior defined for geometries and box2d. However you can not feed it a geometry or box2d text representation, since that will not auto-cast.

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

This method supports Circular Strings and Curves

Exemples

SELECT ST_YMax('BOX3D(1 2 3, 4 5 6)');
st_ymax
-------
5

SELECT ST_YMax(ST_GeomFromText('LINESTRING(1 3 4, 5 6 7)'));
st_ymax
-------
6

SELECT ST_YMax(CAST('BOX(-3 2, 3 4)' As box2d));
st_ymax
-------
4
--Observe THIS DOES NOT WORK because it will try to autocast the string representation to a BOX3D
SELECT ST_YMax('LINESTRING(1 3, 5 6)');

--ERROR:  BOX3D parser - doesn't start with BOX3D(

SELECT ST_YMax(ST_GeomFromEWKT('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)'));
st_ymax
--------
150506.126829327
                

Name

ST_YMin — Returns Y minima of a bounding box 2d or 3d or a geometry.

Synopsis

float ST_YMin(box3d aGeomorBox2DorBox3D);

Description

Returns Y minima of a bounding box 2d or 3d or a geometry.

[Note]

Although this function is only defined for box3d, it will work for box2d and geometry because of the auto-casting behavior defined for geometries and box2d. However you can not feed it a geometry or box2d text representation, since that will not auto-cast.

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

This method supports Circular Strings and Curves

Exemples

SELECT ST_YMin('BOX3D(1 2 3, 4 5 6)');
st_ymin
-------
2

SELECT ST_YMin(ST_GeomFromText('LINESTRING(1 3 4, 5 6 7)'));
st_ymin
-------
3

SELECT ST_YMin(CAST('BOX(-3 2, 3 4)' As box2d));
st_ymin
-------
2
--Observe THIS DOES NOT WORK because it will try to autocast the string representation to a BOX3D
SELECT ST_YMin('LINESTRING(1 3, 5 6)');

--ERROR:  BOX3D parser - doesn't start with BOX3D(

SELECT ST_YMin(ST_GeomFromEWKT('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)'));
st_ymin
--------
150406
                

Name

ST_Z — Return the Z coordinate of the point, or NULL if not available. Input must be a point.

Synopsis

float ST_Z(geometry a_point);

Description

Return the Z coordinate of the point, or NULL if not available. Input must be a point.

This method implements the SQL/MM specification.

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

Exemples

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

                

Voir aussi

???, ST_M, ST_X, ST_Y, ST_ZMax, ST_ZMin


Name

ST_ZMax — Returns Z minima of a bounding box 2d or 3d or a geometry.

Synopsis

float ST_ZMax(box3d aGeomorBox2DorBox3D);

Description

Returns Z maxima of a bounding box 2d or 3d or a geometry.

[Note]

Although this function is only defined for box3d, it will work for box2d and geometry because of the auto-casting behavior defined for geometries and box2d. However you can not feed it a geometry or box2d text representation, since that will not auto-cast.

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

This method supports Circular Strings and Curves

Exemples

SELECT ST_ZMax('BOX3D(1 2 3, 4 5 6)');
st_zmax
-------
6

SELECT ST_ZMax(ST_GeomFromEWKT('LINESTRING(1 3 4, 5 6 7)'));
st_zmax
-------
7

SELECT ST_ZMax('BOX3D(-3 2 1, 3 4 1)' );
st_zmax
-------
1
--Observe THIS DOES NOT WORK because it will try to autocast the string representation to a BOX3D
SELECT ST_ZMax('LINESTRING(1 3 4, 5 6 7)');

--ERROR:  BOX3D parser - doesn't start with BOX3D(

SELECT ST_ZMax(ST_GeomFromEWKT('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)'));
st_zmax
--------
3
                

Name

ST_Zmflag — Returns ZM (dimension semantic) flag of the geometries as a small int. Values are: 0=2d, 1=3dm, 2=3dz, 3=4d.

Synopsis

smallint ST_Zmflag(geometry geomA);

Description

Returns ZM (dimension semantic) flag of the geometries as a small int. Values are: 0=2d, 1=3dm, 2=3dz, 3=4d.

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

This method supports Circular Strings and Curves

Exemples

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_ZMin — Returns Z minima of a bounding box 2d or 3d or a geometry.

Synopsis

float ST_ZMin(box3d aGeomorBox2DorBox3D);

Description

Returns Z minima of a bounding box 2d or 3d or a geometry.

[Note]

Although this function is only defined for box3d, it will work for box2d and geometry because of the auto-casting behavior defined for geometries and box2d. However you can not feed it a geometry or box2d text representation, since that will not auto-cast.

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

This method supports Circular Strings and Curves

Exemples

SELECT ST_ZMin('BOX3D(1 2 3, 4 5 6)');
st_zmin
-------
3

SELECT ST_ZMin(ST_GeomFromEWKT('LINESTRING(1 3 4, 5 6 7)'));
st_zmin
-------
4

SELECT ST_ZMin('BOX3D(-3 2 1, 3 4 1)' );
st_zmin
-------
1
--Observe THIS DOES NOT WORK because it will try to autocast the string representation to a BOX3D
SELECT ST_ZMin('LINESTRING(1 3 4, 5 6 7)');

--ERROR:  BOX3D parser - doesn't start with BOX3D(

SELECT ST_ZMin(ST_GeomFromEWKT('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)'));
st_zmin
--------
1
                

8.5. Geometry Editors

ST_AddPoint — Add a point to a LineString.
ST_Affine — Apply a 3d affine transformation to a geometry.
ST_Force2D — Force les géométries à utiliser le mode XYM.
ST_Force3D — Force les géométries à utiliser le mode XYM.
ST_Force3DZ — Force les géométries à utiliser le mode XYM.
ST_Force3DM — Force les géométries à utiliser le mode XYM.
ST_Force4D — Force les géométries à utiliser le mode XYM.
ST_ForcePolygonCCW — Orients all exterior rings counter-clockwise and all interior rings clockwise.
ST_ForceCollection — Convert the geometry into a GEOMETRYCOLLECTION.
ST_ForcePolygonCW — Orients all exterior rings clockwise and all interior rings counter-clockwise.
ST_ForceSFS — Force les géométries à utiliser le mode XYM.
ST_ForceRHR — Force the orientation of the vertices in a polygon to follow the Right-Hand-Rule.
ST_ForceCurve — Upcast a geometry into its curved type, if applicable.
ST_LineMerge — Return a (set of) LineString(s) formed by sewing together a MULTILINESTRING.
ST_CollectionExtract — Given a (multi)geometry, return a (multi)geometry consisting only of elements of the specified type.
ST_CollectionHomogenize — Given a geometry collection, return the "simplest" representation of the contents.
ST_Multi — Return the geometry as a MULTI* geometry.
ST_Normalize — Return the geometry in its canonical form.
ST_RemovePoint — Remove point from a linestring.
ST_Reverse — Return the geometry with vertex order reversed.
ST_Rotate — Rotate a geometry rotRadians counter-clockwise about an origin.
ST_RotateX — Rotate a geometry rotRadians about the X axis.
ST_RotateY — Rotate a geometry rotRadians about the Y axis.
ST_RotateZ — Rotate a geometry rotRadians about the Z axis.
ST_Scale — Scale a geometry by given factors.
ST_Segmentize — Return a modified geometry/geography having no segment longer than the given distance.
ST_SetPoint — Replace point of a linestring with a given point.
ST_SetSRID — Set the SRID on a geometry to a particular integer 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_Transform — Return a new geometry with its coordinates transformed to a different spatial reference.
ST_Translate — Translate a geometry by given offsets.
ST_TransScale — Translate a geometry by given factors and offsets.

Name

ST_AddPoint — Add a point to a LineString.

Synopsis

geometry ST_AddPoint(geometry linestring, geometry point);

geometry ST_AddPoint(geometry linestring, geometry point, integer position);

Description

Adds a point to a LineString before point <position> (0-based index). Third parameter can be omitted or set to -1 for appending.

Disponibilité: 1.1.0

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

Exemples

--guarantee all linestrings in a table are closed
                --by adding the start point of each linestring to the end of the line string
                --only for those that are not closed
                UPDATE sometable
                SET the_geom = ST_AddPoint(the_geom, ST_StartPoint(the_geom))
                FROM sometable
                WHERE ST_IsClosed(the_geom) = false;

                --Adding point to a 3-d line
                SELECT ST_AsEWKT(ST_AddPoint(ST_GeomFromEWKT('LINESTRING(0 0 1, 1 1 1)'), ST_MakePoint(1, 2, 3)));

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

Name

ST_Affine — Apply a 3d affine transformation to a geometry.

Synopsis

geometry ST_Affine(geometry geomA, float a, float b, float c, float d, float e, float f, float g, float h, float i, float xoff, float yoff, float zoff);

geometry ST_Affine(geometry geomA, float a, float b, float d, float e, float xoff, float yoff);

Description

Applies a 3d affine transformation to the geometry to do things like translate, rotate, scale in one step.

Version 1: The call

ST_Affine(geom, a, b, c, d, e, f, g, h, i, xoff, yoff, zoff) 

represents the transformation matrix

/ a  b  c  xoff \
| d  e  f  yoff |
| g  h  i  zoff |
\ 0  0  0     1 /

and the vertices are transformed as follows:

x' = a*x + b*y + c*z + xoff
y' = d*x + e*y + f*z + yoff
z' = g*x + h*y + i*z + zoff

All of the translate / scale functions below are expressed via such an affine transformation.

Version 2: Applies a 2d affine transformation to the geometry. The call

ST_Affine(geom, a, b, d, e, xoff, yoff)

represents the transformation matrix

/  a  b  0  xoff  \       /  a  b  xoff  \
|  d  e  0  yoff  | rsp.  |  d  e  yoff  |
|  0  0  1     0  |       \  0  0     1  /
\  0  0  0     1  /

and the vertices are transformed as follows:

x' = a*x + b*y + xoff
y' = d*x + e*y + yoff
z' = z 

This method is a subcase of the 3D method above.

Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.

Availability: 1.1.2. Name changed from Affine to ST_Affine in 1.2.2

[Note]

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

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

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

This method supports Circular Strings and Curves

Exemples

--Rotate a 3d line 180 degrees about the z axis.  Note this is long-hand for doing ST_Rotate();
 SELECT ST_AsEWKT(ST_Affine(the_geom,  cos(pi()), -sin(pi()), 0,  sin(pi()), cos(pi()), 0,  0, 0, 1,  0, 0, 0)) As using_affine,
         ST_AsEWKT(ST_Rotate(the_geom, pi())) As using_rotate
        FROM (SELECT ST_GeomFromEWKT('LINESTRING(1 2 3, 1 4 3)') As the_geom) As foo;
        using_affine         |        using_rotate
-----------------------------+-----------------------------
 LINESTRING(-1 -2 3,-1 -4 3) | LINESTRING(-1 -2 3,-1 -4 3)
(1 row)

--Rotate a 3d line 180 degrees in both the x and z axis
SELECT ST_AsEWKT(ST_Affine(the_geom, cos(pi()), -sin(pi()), 0, sin(pi()), cos(pi()), -sin(pi()), 0, sin(pi()), cos(pi()), 0, 0, 0))
        FROM (SELECT ST_GeomFromEWKT('LINESTRING(1 2 3, 1 4 3)') As the_geom) As foo;
           st_asewkt
-------------------------------
 LINESTRING(-1 -2 -3,-1 -4 -3)
(1 row)
                

Name

ST_Force2D — Force les géométries à utiliser le mode XYM.

Synopsis

geometry ST_Force2D(geometry geomA);

Description

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

Enhanced: 2.0.0 support for Polyhedral surfaces was introduced.

Changed: 2.1.0. Up to 2.0.x this was called ST_Force_2D.

This method supports Circular Strings and Curves

This function supports Polyhedral surfaces.

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

Exemples

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

                

Voir aussi

ST_Force3D


Name

ST_Force3D — Force les géométries à utiliser le mode XYM.

Synopsis

geometry ST_Force3D(geometry geomA);

Description

Forces the geometries into XYZ mode. This is an alias for ST_Force_3DZ. If a geometry has no Z component, then a 0 Z coordinate is tacked on.

Enhanced: 2.0.0 support for Polyhedral surfaces was introduced.

Changed: 2.1.0. Up to 2.0.x this was called ST_Force_3D.

This function supports Polyhedral surfaces.

This method supports Circular Strings and Curves

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

Exemples

--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 les géométries à utiliser le mode XYM.

Synopsis

geometry ST_Force3DZ(geometry geomA);

Description

Forces the geometries into XYZ mode. This is a synonym for ST_Force3DZ. If a geometry has no Z component, then a 0 Z coordinate is tacked on.

Enhanced: 2.0.0 support for Polyhedral surfaces was introduced.

Changed: 2.1.0. Up to 2.0.x this was called ST_Force_3DZ.

This function supports Polyhedral surfaces.

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

This method supports Circular Strings and Curves

Exemples

--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 les géométries à utiliser le mode XYM.

Synopsis

geometry ST_Force3DM(geometry geomA);

Description

Forces the geometries into XYM mode. If a geometry has no M component, then a 0 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.

This method supports Circular Strings and Curves

Exemples

--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 les géométries à utiliser le mode XYM.

Synopsis

geometry ST_Force4D(geometry geomA);

Description

Forces the geometries into XYZM mode. 0 is tacked on for missing Z and M dimensions.

Changed: 2.1.0. Up to 2.0.x this was called ST_Force_4D.

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

This method supports Circular Strings and Curves

Exemples

--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_ForcePolygonCCW — Orients all exterior rings counter-clockwise and all interior rings clockwise.

Synopsis

boolean ST_ForceRHR(geometry g);

Description

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.

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

This function supports M coordinates.


Name

ST_ForceCollection — Convert the geometry into a GEOMETRYCOLLECTION.

Synopsis

geometry ST_ForceCollection(geometry geomA);

Description

Converts the geometry into a GEOMETRYCOLLECTION. This is useful for simplifying the WKB representation.

Enhanced: 2.0.0 support for Polyhedral surfaces was introduced.

Availability: 1.2.2, prior to 1.3.4 this function will crash with Curves. This is fixed in 1.3.4+

Changed: 2.1.0. Up to 2.0.x this was called ST_Force_Collection.

This function supports Polyhedral surfaces.

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

This method supports Circular Strings and Curves

Exemples

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_ForcePolygonCW — Orients all exterior rings clockwise and all interior rings counter-clockwise.

Synopsis

boolean ST_ForceRHR(geometry g);

Description

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.

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

This function supports M coordinates.


Name

ST_ForceSFS — Force les géométries à utiliser le mode XYM.

Synopsis

geometry ST_ForceSFS(geometry geomA);

geometry ST_ForceSFS(geometry geomA, text version);

Description

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

This method supports Circular Strings and Curves

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


Name

ST_ForceRHR — Force the orientation of the vertices in a polygon to follow the Right-Hand-Rule.

Synopsis

boolean ST_ForceRHR(geometry g);

Description

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.

Enhanced: 2.0.0 support for Polyhedral surfaces was introduced.

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

This function supports Polyhedral surfaces.

Exemples

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_ForceCurve — Upcast a geometry into its curved type, if applicable.

Synopsis

geometry ST_ForceCurve(geometry g);

Description

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.

Availability: 2.2.0

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

This method supports Circular Strings and Curves

Exemples

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)

Voir aussi

ST_LineToCurve


Name

ST_LineMerge — Return a (set of) LineString(s) formed by sewing together a MULTILINESTRING.

Synopsis

geometry ST_LineMerge(geometry amultilinestring);

Description

Returns a (set of) LineString(s) formed by sewing together the constituent line work of a MULTILINESTRING.

[Note]

Only use with MULTILINESTRING/LINESTRINGs. If you feed a polygon or geometry collection into this function, it will return an empty GEOMETRYCOLLECTION

Disponibilité: 1.1.0

[Note]

requires GEOS >= 2.1.0

Exemples

SELECT ST_AsText(ST_LineMerge(
ST_GeomFromText('MULTILINESTRING((-29 -27,-30 -29.7,-36 -31,-45 -33),(-45 -33,-46 -32))')
                )
);
st_astext
--------------------------------------------------------------------------------------------------
LINESTRING(-29 -27,-30 -29.7,-36 -31,-45 -33,-46 -32)
(1 row)

--If can't be merged - original MULTILINESTRING is returned
SELECT ST_AsText(ST_LineMerge(
ST_GeomFromText('MULTILINESTRING((-29 -27,-30 -29.7,-36 -31,-45 -33),(-45.2 -33.2,-46 -32))')
)
);
st_astext
----------------
MULTILINESTRING((-45.2 -33.2,-46 -32),(-29 -27,-30 -29.7,-36 -31,-45 -33))
                        

Name

ST_CollectionExtract — Given a (multi)geometry, return a (multi)geometry consisting only of elements of the specified type.

Synopsis

geometry ST_CollectionExtract(geometry collection, integer type);

Description

Given a (multi)geometry, returns a (multi)geometry consisting only of elements of the specified type. Sub-geometries that are not the specified type are ignored. If there are no sub-geometries of the right type, an EMPTY geometry will be returned. Only points, lines and polygons are supported. Type numbers are 1 == POINT, 2 == LINESTRING, 3 == POLYGON.

Availability: 1.5.0

[Note]

Prior to 1.5.3 this function returned non-collection inputs untouched, no matter type. In 1.5.3 non-matching single geometries result in a NULL return. In of 2.0.0 every case of missing match results in a typed EMPTY return.

[Warning]

When specifying 3 == POLYGON a multipolygon is returned even when the edges are shared. This results in an invalid multipolygon for many cases such as applying this function on an ST_Split result.

Exemples

-- Constants: 1 == POINT, 2 == LINESTRING, 3 == POLYGON
SELECT ST_AsText(ST_CollectionExtract(ST_GeomFromText('GEOMETRYCOLLECTION(GEOMETRYCOLLECTION(POINT(0 0)))'),1));
st_astext
---------------
MULTIPOINT(0 0)
(1 row)

SELECT ST_AsText(ST_CollectionExtract(ST_GeomFromText('GEOMETRYCOLLECTION(GEOMETRYCOLLECTION(LINESTRING(0 0, 1 1)),LINESTRING(2 2, 3 3))'),2));
st_astext
---------------
MULTILINESTRING((0 0, 1 1), (2 2, 3 3))
(1 row)
                        

Name

ST_CollectionHomogenize — Given a geometry collection, return the "simplest" representation of the contents.

Synopsis

geometry ST_CollectionHomogenize(geometry collection);

Description

Given a geometry collection, returns the "simplest" representation of the contents. Singletons will be returned as singletons. Collections that are homogeneous will be returned as the appropriate multi-type.

[Warning]

When specifying 3 == POLYGON a multipolygon is returned even when the edges are shared. This results in an invalid multipolygon for many cases such as applying this function on an ST_Split result.

Availability: 2.0.0

Exemples

SELECT ST_AsText(ST_CollectionHomogenize('GEOMETRYCOLLECTION(POINT(0 0))'));

        st_astext
        ------------
         POINT(0 0)
        (1 row)

  SELECT ST_AsText(ST_CollectionHomogenize('GEOMETRYCOLLECTION(POINT(0 0),POINT(1 1))'));

        st_astext
        ---------------------
         MULTIPOINT(0 0,1 1)
        (1 row)

                                

Name

ST_Multi — Return the geometry as a MULTI* geometry.

Synopsis

geometry ST_Multi(geometry g1);

Description

Returns the geometry as a MULTI* geometry. If the geometry is already a MULTI*, it is returned unchanged.

Exemples

SELECT ST_AsText(ST_Multi(ST_GeomFromText('POLYGON((743238 2967416,743238 2967450,
                        743265 2967450,743265.625 2967416,743238 2967416))')));
                        st_astext
                        --------------------------------------------------------------------------------------------------
                        MULTIPOLYGON(((743238 2967416,743238 2967450,743265 2967450,743265.625 2967416,
                        743238 2967416)))
                        (1 row)
                        

Voir aussi

ST_AsText


Name

ST_Normalize — Return the geometry in its canonical form.

Synopsis

geometry ST_Multi(geometry g1);

Description

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

Exemples

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)
                        

Voir aussi

ST_Equals,


Name

ST_RemovePoint — Remove point from a linestring.

Synopsis

geometry ST_RemovePoint(geometry linestring, integer offset);

Description

Remove a point from a linestring, given its 0-based index. Useful for turning a closed ring into an open line string

Disponibilité: 1.1.0

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

Exemples

--guarantee no LINESTRINGS are closed
--by removing the end point.  The below assumes the_geom is of type LINESTRING
UPDATE sometable
        SET the_geom = ST_RemovePoint(the_geom, ST_NPoints(the_geom) - 1)
        FROM sometable
        WHERE ST_IsClosed(the_geom) = true;
                

Name

ST_Reverse — Return the geometry with vertex order reversed.

Synopsis

geometry ST_Reverse(geometry g1);

Description

Can be used on any geometry and reverses the order of the vertexes.

Exemples

SELECT ST_AsText(the_geom) as line, ST_AsText(ST_Reverse(the_geom)) As reverseline
FROM
(SELECT ST_MakeLine(ST_MakePoint(1,2),
                ST_MakePoint(1,10)) As the_geom) as foo;
--result
                line         |     reverseline
---------------------+----------------------
LINESTRING(1 2,1 10) | LINESTRING(1 10,1 2)

Name

ST_Rotate — Rotate a geometry rotRadians counter-clockwise about an origin.

Synopsis

geometry ST_Rotate(geometry geomA, float rotRadians);

geometry ST_Rotate(geometry geomA, float rotRadians, float x0, float y0);

geometry ST_Rotate(geometry geomA, float rotRadians, geometry pointOrigin);

Description

Rotates geometry rotRadians counter-clockwise about the origin. The rotation origin can be specified either as a POINT geometry, or as x and y coordinates. If the origin is not specified, the geometry is rotated about POINT(0 0).

Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.

Enhanced: 2.0.0 additional parameters for specifying the origin of rotation were added.

Availability: 1.1.2. Name changed from Rotate to ST_Rotate in 1.2.2

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

This method supports Circular Strings and Curves

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

Exemples

--Rotate 180 degrees
SELECT ST_AsEWKT(ST_Rotate('LINESTRING (50 160, 50 50, 100 50)', pi()));
               st_asewkt
---------------------------------------
 LINESTRING(-50 -160,-50 -50,-100 -50)
(1 row)

--Rotate 30 degrees counter-clockwise at x=50, y=160
SELECT ST_AsEWKT(ST_Rotate('LINESTRING (50 160, 50 50, 100 50)', pi()/6, 50, 160));
                                 st_asewkt
---------------------------------------------------------------------------
 LINESTRING(50 160,105 64.7372055837117,148.301270189222 89.7372055837117)
(1 row)

--Rotate 60 degrees clockwise from centroid
SELECT ST_AsEWKT(ST_Rotate(geom, -pi()/3, ST_Centroid(geom)))
FROM (SELECT 'LINESTRING (50 160, 50 50, 100 50)'::geometry AS geom) AS foo;
                           st_asewkt
--------------------------------------------------------------
 LINESTRING(116.4225 130.6721,21.1597 75.6721,46.1597 32.3708)
(1 row)
                

Name

ST_RotateX — Rotate a geometry rotRadians about the X axis.

Synopsis

geometry ST_RotateX(geometry geomA, float rotRadians);

Description

Rotate a geometry geomA - rotRadians about the X axis.

[Note]

ST_RotateX(geomA, rotRadians) is short-hand for ST_Affine(geomA, 1, 0, 0, 0, cos(rotRadians), -sin(rotRadians), 0, sin(rotRadians), cos(rotRadians), 0, 0, 0).

Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.

Availability: 1.1.2. Name changed from RotateX to ST_RotateX in 1.2.2

This function supports Polyhedral surfaces.

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

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

Exemples

--Rotate a line 90 degrees along x-axis
SELECT ST_AsEWKT(ST_RotateX(ST_GeomFromEWKT('LINESTRING(1 2 3, 1 1 1)'), pi()/2));
                 st_asewkt
---------------------------
 LINESTRING(1 -3 2,1 -1 1)

Name

ST_RotateY — Rotate a geometry rotRadians about the Y axis.

Synopsis

geometry ST_RotateY(geometry geomA, float rotRadians);

Description

Rotate a geometry geomA - rotRadians about the y axis.

[Note]

ST_RotateY(geomA, rotRadians) is short-hand for ST_Affine(geomA, cos(rotRadians), 0, sin(rotRadians), 0, 1, 0, -sin(rotRadians), 0, cos(rotRadians), 0, 0, 0).

Availability: 1.1.2. Name changed from RotateY to ST_RotateY in 1.2.2

Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.

This function supports Polyhedral surfaces.

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

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

Exemples

--Rotate a line 90 degrees along y-axis
 SELECT ST_AsEWKT(ST_RotateY(ST_GeomFromEWKT('LINESTRING(1 2 3, 1 1 1)'), pi()/2));
                 st_asewkt
---------------------------
 LINESTRING(3 2 -1,1 1 -1)

Name

ST_RotateZ — Rotate a geometry rotRadians about the Z axis.

Synopsis

geometry ST_RotateZ(geometry geomA, float rotRadians);

Description

Rotate a geometry geomA - rotRadians about the Z axis.

[Note]

This is a synonym for ST_Rotate

[Note]

ST_RotateZ(geomA, rotRadians) is short-hand for SELECT ST_Affine(geomA, cos(rotRadians), -sin(rotRadians), 0, sin(rotRadians), cos(rotRadians), 0, 0, 0, 1, 0, 0, 0).

Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.

Availability: 1.1.2. Name changed from RotateZ to ST_RotateZ in 1.2.2

[Note]

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

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

This method supports Circular Strings and Curves

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

Exemples

--Rotate a line 90 degrees along z-axis
SELECT ST_AsEWKT(ST_RotateZ(ST_GeomFromEWKT('LINESTRING(1 2 3, 1 1 1)'), pi()/2));
                 st_asewkt
---------------------------
 LINESTRING(-2 1 3,-1 1 1)

 --Rotate a curved circle around z-axis
SELECT ST_AsEWKT(ST_RotateZ(the_geom, pi()/2))
FROM (SELECT ST_LineToCurve(ST_Buffer(ST_GeomFromText('POINT(234 567)'), 3)) As the_geom) As foo;

                                                                                                           st_asewkt
----------------------------------------------------------------------------------------------------------------------------
 CURVEPOLYGON(CIRCULARSTRING(-567 237,-564.87867965644 236.12132034356,-564 234,-569.12132034356 231.87867965644,-567 237))


Name

ST_Scale — Scale a geometry by given factors.

Synopsis

geometry ST_Scale(geometry geomA, float XFactor, float YFactor, float ZFactor);

geometry ST_Scale(geometry geomA, float XFactor, float YFactor);

geometry ST_Scale(geometry geom, geometry factor);

Description

Scales the geometry to a new size by multiplying the ordinates with the corresponding factor parameters.

The version taking a geometry as the factor parameter allows passing a 2d, 3dm, 3dz or 4d point to set scaling factor for all supported dimensions. Missing dimensions in the factor point are equivalent to no scaling the corresponding dimension.

[Note]

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

Availability: 1.1.0.

Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.

Enhanced: 2.2.0 support for scaling all dimension (geometry parameter) was introduced.

This function supports Polyhedral surfaces.

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

This method supports Circular Strings and Curves

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

This function supports M coordinates.

Exemples

--Version 1: scale X, Y, Z
SELECT ST_AsEWKT(ST_Scale(ST_GeomFromEWKT('LINESTRING(1 2 3, 1 1 1)'), 0.5, 0.75, 0.8));
                          st_asewkt
--------------------------------------
 LINESTRING(0.5 1.5 2.4,0.5 0.75 0.8)

--Version 2: Scale X Y
 SELECT ST_AsEWKT(ST_Scale(ST_GeomFromEWKT('LINESTRING(1 2 3, 1 1 1)'), 0.5, 0.75));
                        st_asewkt
----------------------------------
 LINESTRING(0.5 1.5 3,0.5 0.75 1)

--Version 3: Scale X Y Z M
 SELECT ST_AsEWKT(ST_Scale(ST_GeomFromEWKT('LINESTRING(1 2 3 4, 1 1 1 1)'),
   ST_MakePoint(0.5, 0.75, 2, -1)));
                               st_asewkt
----------------------------------------
 LINESTRING(0.5 1.5 6 -4,0.5 0.75 2 -1)



Name

ST_Segmentize — Return a modified geometry/geography having no segment longer than the given distance.

Synopsis

geometry ST_Segmentize(geometry geom, float max_segment_length);

geography ST_Segmentize(geography geog, float max_segment_length);

Description

Returns a modified geometry having no segment longer than the given max_segment_length. Distance computation is performed in 2d only. For geometry, length units are in units of spatial reference. For geography, units are in meters.

Availability: 1.2.2

Enhanced: 2.3.0 Segmentize geography now uses equal length segments

Enhanced: 2.1.0 support for geography was introduced.

Changed: 2.1.0 As a result of the introduction of geography support: The construct SELECT ST_Segmentize('LINESTRING(1 2, 3 4)',0.5); will result in ambiguous function error. You need to have properly typed object e.g. a geometry/geography column, use ST_GeomFromText, ST_GeogFromText or SELECT ST_Segmentize('LINESTRING(1 2, 3 4)'::geometry,0.5);

[Note]

This will only increase segments. It will not lengthen segments shorter than max length

Exemples

SELECT ST_AsText(ST_Segmentize(
ST_GeomFromText('MULTILINESTRING((-29 -27,-30 -29.7,-36 -31,-45 -33),(-45 -33,-46 -32))')
                ,5)
);
st_astext
--------------------------------------------------------------------------------------------------
MULTILINESTRING((-29 -27,-30 -29.7,-34.886615700134 -30.758766735029,-36 -31,
-40.8809353009198 -32.0846522890933,-45 -33),
(-45 -33,-46 -32))
(1 row)

SELECT ST_AsText(ST_Segmentize(ST_GeomFromText('POLYGON((-29 28, -30 40, -29 28))'),10));
st_astext
-----------------------
POLYGON((-29 28,-29.8304547985374 37.9654575824488,-30 40,-29.1695452014626 30.0345424175512,-29 28))
(1 row)

                        

Name

ST_SetPoint — Replace point of a linestring with a given point.

Synopsis

geometry ST_SetPoint(geometry linestring, integer zerobasedposition, geometry point);

Description

Replace point N of linestring with given point. Index is 0-based.Negative index are counted backwards, so that -1 is last point. This is especially useful in triggers when trying to maintain relationship of joints when one vertex moves.

Disponibilité: 1.1.0

Updated 2.3.0 : negative indexing

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

Exemples

--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.the_geom, ST_NumPoints(foo.the_geom) - 1, ST_GeomFromEWKT('POINT(-1 1 3)')))
FROM (SELECT ST_GeomFromEWKT('LINESTRING(-1 2 3,-1 3 4, 5 6 7)') As the_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_SetSRID — Set the SRID on a geometry to a particular integer value.

Synopsis

geometry ST_SetSRID(geometry geom, integer srid);

Description

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.

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

This method supports Circular Strings and Curves

Exemples

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

Description

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.

Availability: 1.0.0RC1

Availability: 1.1.0 - Z and M support

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

Exemples

--Snap your geometries to a precision grid of 10^-3
UPDATE mytable
   SET the_geom = ST_SnapToGrid(the_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);

Description

Snaps the vertices and segments of a geometry another Geometry's vertices. A snap distance tolerance is used to control where snapping is performed.

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

Availability: 2.0.0 requires GEOS >= 3.3.0.

Exemples

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)
                                

Voir aussi

ST_SnapToGrid


Name

ST_Transform — Return a new geometry with its coordinates transformed to a different spatial reference.

Synopsis

geometry ST_Rotate(geometry geomA, float rotRadians);

geometry ST_Rotate(geometry geomA, float rotRadians, float x0, float y0);

geometry ST_Rotate(geometry geomA, float rotRadians, geometry pointOrigin);

Description

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.

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

Enhanced: 2.0.0 support for Polyhedral surfaces was introduced.

Enhanced: 2.3.0 support for direct PROJ.4 text was introduced.

This method implements the SQL/MM specification. SQL-MM 3: 5.1.6

This method supports Circular Strings and Curves

This function supports Polyhedral surfaces.

Exemples

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_the_geom_26986_parcels
  ON parcels
  USING gist
  (ST_Transform(the_geom, 26986))
  WHERE the_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 behaviour

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 behaviour 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_Translate — Translate a geometry by given offsets.

Synopsis

geometry ST_Translate(geometry g1, float deltax, float deltay);

geometry ST_Translate(geometry g1, float deltax, float deltay, float deltaz);

Description

Returns a new geometry whose coordinates are translated delta x,delta y,delta z units. Units are based on the units defined in spatial reference (SRID) for this geometry.

[Note]

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

Availability: 1.2.2

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

This method supports Circular Strings and Curves

Exemples

Move a point 1 degree longitude

SELECT ST_AsText(ST_Translate(ST_GeomFromText('POINT(-71.01 42.37)',4326),1,0)) As wgs_transgeomtxt;

        wgs_transgeomtxt
        ---------------------
        POINT(-70.01 42.37)
                

Move a linestring 1 degree longitude and 1/2 degree latitude

SELECT ST_AsText(ST_Translate(ST_GeomFromText('LINESTRING(-71.01 42.37,-71.11 42.38)',4326),1,0.5)) As wgs_transgeomtxt;
                   wgs_transgeomtxt
        ---------------------------------------
        LINESTRING(-70.01 42.87,-70.11 42.88)
                

Move a 3d point

SELECT ST_AsEWKT(ST_Translate(CAST('POINT(0 0 0)' As geometry), 5, 12,3));
        st_asewkt
        ---------
        POINT(5 12 3)
                

Move a curve and a point

SELECT ST_AsText(ST_Translate(ST_Collect('CURVEPOLYGON(CIRCULARSTRING(4 3,3.12 0.878,1 0,-1.121 5.1213,6 7, 8 9,4 3))','POINT(1 3)'),1,2));
                                                                                                                 st_astext
------------------------------------------------------------------------------------------------------------
 GEOMETRYCOLLECTION(CURVEPOLYGON(CIRCULARSTRING(5 5,4.12 2.878,2 2,-0.121 7.1213,7 9,9 11,5 5)),POINT(2 5))

Voir aussi

ST_Affine, ST_AsText, ???


Name

ST_TransScale — Translate a geometry by given factors and offsets.

Synopsis

geometry ST_TransScale(geometry geomA, float deltaX, float deltaY, float XFactor, float YFactor);

Description

Translates the geometry using the deltaX and deltaY args, then scales it using the XFactor, YFactor args, working in 2D only.

[Note]

ST_TransScale(geomA, deltaX, deltaY, XFactor, YFactor) is short-hand for ST_Affine(geomA, XFactor, 0, 0, 0, YFactor, 0, 0, 0, 1, deltaX*XFactor, deltaY*YFactor, 0).

[Note]

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

Availability: 1.1.0.

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

This method supports Circular Strings and Curves

Exemples

SELECT ST_AsEWKT(ST_TransScale(ST_GeomFromEWKT('LINESTRING(1 2 3, 1 1 1)'), 0.5, 1, 1, 2));
                  st_asewkt
-----------------------------
 LINESTRING(1.5 6 3,1.5 4 1)


--Buffer a point to get an approximation of a circle, convert to curve and then translate 1,2 and scale it 3,4
  SELECT ST_AsText(ST_Transscale(ST_LineToCurve(ST_Buffer('POINT(234 567)', 3)),1,2,3,4));
                                                                                                                  st_astext
------------------------------------------------------------------------------------------------------------------------------
 CURVEPOLYGON(CIRCULARSTRING(714 2276,711.363961030679 2267.51471862576,705 2264,698.636038969321 2284.48528137424,714 2276))

8.6. Geometry Outputs

ST_AsBinary — Return the Well-Known Binary (WKB) representation of the geometry/geography without SRID meta data.
ST_AsEncodedPolyline — Returns an Encoded Polyline from a LineString geometry.
ST_AsEWKB — Return the Well-Known Binary (WKB) representation of the geometry with SRID meta data.
ST_AsEWKT — Return the Well-Known Text (WKT) representation of the geometry with SRID meta data.
ST_AsGeoJSON — Return the geometry as a GeoJSON element.
ST_AsGML — Return the geometry as a GML version 2 or 3 element.
ST_AsHEXEWKB — Returns a Geometry in HEXEWKB format (as text) using either little-endian (NDR) or big-endian (XDR) encoding.
ST_AsKML — Return the geometry as a KML element. Several variants. Default version=2, default precision=15
ST_AsLatLonText — Return the Degrees, Minutes, Seconds representation of the given point.
ST_AsSVG — Returns a Geometry in SVG path data given a geometry or geography object.
ST_AsText — Return the Well-Known Text (WKT) representation of the geometry/geography without SRID metadata.
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.
ST_AsGeoJSON — Return a Geobuf representation of a set of rows.
ST_AsSVG — Transform a geometry into the coordinate space of a Mapbox Vector Tile.
ST_AsGML — Return a Mapbox Vector Tile representation of a set of rows.

Name

ST_AsBinary — Return the 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);

Description

Returns the Well-Known Binary representation of the geometry. There are 2 variants of the function. The first variant takes no endian encoding parameter and defaults to server machine endian. The second variant takes a second argument denoting the encoding - 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.

[Note]

The WKB spec does not include the SRID. To get the WKB with SRID format use ST_AsEWKB

[Note]

ST_AsBinary is the reverse of ??? for geometry. Use ??? to convert to a postgis geometry from ST_AsBinary representation.

[Note]

The default behavior in PostgreSQL 9.0 has been changed to output bytea in hex encoding. ST_AsBinary is the reverse of ??? for geometry. If your GUI tools require the old behavior, then SET bytea_output='escape' in your database.

Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.

Enhanced: 2.0.0 support for higher coordinate dimensions was introduced.

Enhanced: 2.0.0 support for specifying endian with geography was introduced.

Availability: 1.5.0 geography support was introduced.

Changed: 2.0.0 Inputs to this function can not be unknown -- must be geometry. Constructs such as ST_AsBinary('POINT(1 2)') are no longer valid and you will get an n st_asbinary(unknown) is not unique error. Code like that needs to be changed to ST_AsBinary('POINT(1 2)'::geometry);. If that is not possible, then install legacy.sql.

This method implements the OpenGIS Simple Features Implementation Specification for SQL 1.1. s2.1.1.1

This method implements the SQL/MM specification. SQL-MM 3: 5.1.37

This method supports Circular Strings and Curves

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

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

Examples

SELECT ST_AsBinary(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326));

                   st_asbinary
--------------------------------
\001\003\000\000\000\001\000\000\000\005
\000\000\000\000\000\000\000\000\000\000
\000\000\000\000\000\000\000\000\000\000
\000\000\000\000\000\000\000\000\000\000
\000\000\000\360?\000\000\000\000\000\000
\360?\000\000\000\000\000\000\360?\000\000
\000\000\000\000\360?\000\000\000\000\000
\000\000\000\000\000\000\000\000\000\000\000
\000\000\000\000\000\000\000\000
(1 row)
SELECT ST_AsBinary(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326), 'XDR');
                   st_asbinary
--------------------------------
\000\000\000\000\003\000\000\000\001\000\000\000\005\000\000\000\000\000
\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000
\000?\360\000\000\000\000\000\000?\360\000\000\000\000\000\000?\360\000\000
\000\000\000\000?\360\000\000\000\000\000\000\000\000\000\000\000\000\000\000
\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000
(1 row)

Name

ST_AsEncodedPolyline — Returns an Encoded Polyline from a LineString geometry.

Synopsis

text ST_AsEncodedPolyline(geometry geom, integer precision=5);

Description

Returns the geometry as an Encoded Polyline. This is a format very useful if you are using google maps

Availability: 2.2.0

Examples

Basic

SELECT ST_AsEncodedPolyline(GeomFromEWKT('SRID=4326;LINESTRING(-120.2 38.5,-120.95 40.7,-126.453 43.252)'));
        --result--
        |_p~iF~ps|U_ulLnnqC_mqNvxq`@
        

Use in conjunction with geography linestring and geography segmentize, and put on google maps

-- the SQL for Boston to San Francisco, segments every 100 KM
        SELECT ST_AsEncodedPolyline(
                ST_Segmentize(
                        ST_GeogFromText('LINESTRING(-71.0519 42.4935,-122.4483 37.64)'),
                                100000)::geometry) As encodedFlightPath;

javascript will look something like this where $ variable you replace with query result

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<script type="text/javascript">
         flightPath = new google.maps.Polyline({
                        path:  google.maps.geometry.encoding.decodePath("$encodedFlightPath"),
                        map: map,
                        strokeColor: '#0000CC',
                        strokeOpacity: 1.0,
                        strokeWeight: 4
                });
</script>
        

See Also

???, ST_AsGML


Name

ST_AsEWKB — Return the Well-Known Binary (WKB) representation of the geometry with SRID meta data.

Synopsis

bytea ST_AsEWKB(geometry g1);

bytea ST_AsEWKB(geometry g1, text NDR_or_XDR);

Description

Returns the Well-Known Binary representation of the geometry with SRID metadata. There are 2 variants of the function. The first variant takes no endian encoding parameter and defaults to little endian. The second variant takes a second argument denoting the encoding - 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.

[Note]

The WKB spec does not include the SRID. To get the OGC WKB format use ST_AsBinary

[Note]

ST_AsEWKB is the reverse of ST_GeomFromEWKB. Use ST_GeomFromEWKB to convert to a postgis geometry from ST_AsEWKB representation.

Enhanced: 2.0.0 support for Polyhedral surfaces, Triangles and TIN was introduced.

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

This method supports Circular Strings and Curves

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

Examples

SELECT ST_AsEWKB(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326));

                   st_asewkb
--------------------------------
\001\003\000\000 \346\020\000\000\001\000
\000\000\005\000\000\000\000
\000\000\000\000\000\000\000\000
\000\000\000\000\000\000\000\000\000
\000\000\000\000\000\000\000\000\000\000
\000\000\360?\000\000\000\000\000\000\360?
\000\000\000\000\000\000\360?\000\000\000\000\000
\000\360?\000\000\000\000\000\000\000\000\000\000\000
\000\000\000\000\000\000\000\000\000\000\000\000\000
(1 row)
SELECT ST_AsEWKB(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326), 'XDR');
                   st_asewkb
--------------------------------
\000 \000\000\003\000\000\020\346\000\000\000\001\000\000\000\005\000\000\000\000\
000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000?
\360\000\000\000\000\000\000?\360\000\000\000\000\000\000?\360\000\000\000\000
\000\000?\360\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000
\000\000\000\000\000\000\000\000\000\000\000\000\000
                

Name

ST_AsEWKT — Return the Well-Known Text (WKT) representation of the geometry with SRID meta data.

Synopsis

text ST_AsEWKT(geometry g1);

text ST_AsEWKT(geography g1);

Description

Returns the Well-Known Text representation of the geometry prefixed with the SRID.

[Note]

The WKT spec does not include the SRID. To get the OGC WKT format use ST_AsText

WKT format does not maintain precision so to prevent floating truncation, use ST_AsBinary or ST_AsEWKB format for transport.

[Note]

ST_AsEWKT is the reverse of ???. Use ??? to convert to a postgis geometry from ST_AsEWKT representation.

Enhanced: 2.0.0 support for Geography, Polyhedral surfaces, Triangles and TIN was introduced.

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

This method supports Circular Strings and Curves

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

Examples

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_AsGeoJSON — Return the geometry as a GeoJSON element.

Synopsis

text ST_AsGeoJSON(geometry geom, integer maxdecimaldigits=15, integer options=0);

text ST_AsGeoJSON(geography geog, integer maxdecimaldigits=15, integer options=0);

text ST_AsGeoJSON(integer gj_version, geometry geom, integer maxdecimaldigits=15, integer options=0);

text ST_AsGeoJSON(integer gj_version, geography geog, integer maxdecimaldigits=15, integer options=0);

Description

Return the geometry as a Geometry Javascript Object Notation (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 gj_version parameter is the major version of the GeoJSON spec. If specified, must be 1. This represents the spec version of GeoJSON.

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 Bbox

  • 2: GeoJSON Short CRS (e.g EPSG:4326)

  • 4: GeoJSON Long CRS (e.g urn:ogc:def:crs:EPSG::4326)

Version 1: ST_AsGeoJSON(geom) / precision=15 version=1 options=0

Version 2: ST_AsGeoJSON(geom, precision) / version=1 options=0

Version 3: ST_AsGeoJSON(geom, precision, options) / version=1

Version 4: ST_AsGeoJSON(gj_version, geom) / precision=15 options=0

Version 5: ST_AsGeoJSON(gj_version, geom, precision) /options=0

Version 6: ST_AsGeoJSON(gj_version, geom, precision,options)

Availability: 1.3.4

Availability: 1.5.0 geography support was introduced.

Changed: 2.0.0 support default args and named args.

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

Examples

GeoJSON format is generally more efficient than other formats for use in ajax mapping. One popular javascript client that supports this is Open Layers. Example of its use is OpenLayers GeoJSON Example

SELECT ST_AsGeoJSON(the_geom) from fe_edges limit 1;
                                           st_asgeojson
-----------------------------------------------------------------------------------------------------------

{"type":"MultiLineString","coordinates":[[[-89.734634999999997,31.492072000000000],
[-89.734955999999997,31.492237999999997]]]}
(1 row)
--3d point
SELECT ST_AsGeoJSON('LINESTRING(1 2 3, 4 5 6)');

st_asgeojson
-----------------------------------------------------------------------------------------
 {"type":"LineString","coordinates":[[1,2,3],[4,5,6]]}


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

Description

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 precision argument may be used to reduce the maximum number of decimal places (maxdecimaldigits) used in output (defaults to 15).

GML 2 refer to 2.1.2 version, GML 3 to 3.1.1 version

The 'options' argument is a bitfield. It could be used to define CRS output type in GML output, and to declare data as lat/lon:

  • 0: GML Short CRS (e.g EPSG:4326), default value

  • 1: GML Long CRS (e.g urn:ogc:def:crs:EPSG::4326)

  • 2: For GML 3 only, remove srsDimension attribute from output.

  • 4: For GML 3 only, use <LineString> rather than <Curve> tag for lines.

  • 16: Declare that datas are lat/lon (e.g srid=4326). Default is to assume that data are planars. This option is useful for GML 3.1.1 output only, related to axis order. So if you set it, it will swap the coordinates so order is lat lon instead of database lon lat.

  • 32: Output the box of the geometry (envelope).

The 'namespace prefix' argument may be used to specify a custom namespace prefix or no prefix (if empty). If null or omitted 'gml' prefix is used

Availability: 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.

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

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

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
>
                        

Examples: Version 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>
                        

See Also

???


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

Description

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

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

This method supports Circular Strings and Curves

Examples

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

Name

ST_AsKML — Return the geometry as a KML element. Several variants. Default version=2, default precision=15

Synopsis

text ST_AsKML(geometry geom, integer maxdecimaldigits=15);

text ST_AsKML(geography geog, integer maxdecimaldigits=15);

text ST_AsKML(integer version, geometry geom, integer maxdecimaldigits=15, text nprefix=NULL);

text ST_AsKML(integer version, geography geog, integer maxdecimaldigits=15, text nprefix=NULL);

Description

Return the geometry as a Keyhole Markup Language (KML) element. There are several variants of this function. maximum number of decimal places used in output (defaults to 15), version default to 2 and default namespace is no prefix.

Version 1: ST_AsKML(geom_or_geog, maxdecimaldigits) / version=2 / maxdecimaldigits=15

Version 2: ST_AsKML(version, geom_or_geog, maxdecimaldigits, nprefix) maxdecimaldigits=15 / nprefix=NULL

[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. Default is no prefix

[Note]

Changed: 2.0.0 - uses default args and supports named args

[Note]

AsKML output will not work with geometries that do not have an SRID

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

Examples

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>
                
                

Name

ST_AsLatLonText — Return the Degrees, Minutes, Seconds representation of the given point.

Synopsis

text ST_AsLatLonText(geometry pt, text format='');

Description

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.

Availability: 2.0

Examples

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_AsSVG — Returns a Geometry in SVG path data given a geometry or geography object.

Synopsis

text ST_AsSVG(geometry geom, integer rel=0, integer maxdecimaldigits=15);

text ST_AsSVG(geography geog, integer rel=0, integer maxdecimaldigits=15);

Description

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 (";").

[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

Changed: 2.0.0 to use default args and support named args

Examples

SELECT ST_AsSVG(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326));

                st_assvg
                --------
                M 0 0 L 0 -1 1 -1 1 0 Z

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(geography g1);

Description

Returns the Well-Known Text representation of the geometry/geography.

[Note]

The WKT spec does not include the SRID. To get the SRID as part of the data, use the non-standard PostGIS ST_AsEWKT

WKT format does not maintain precision so to prevent floating truncation, use ST_AsBinary or ST_AsEWKB format for transport.

[Note]

ST_AsText is the reverse of ???. Use ??? to convert to a postgis geometry from ST_AsText representation.

Availability: 1.5 - support for geography was introduced.

This method implements the OpenGIS Simple Features Implementation Specification for SQL 1.1. s2.1.1.1

This method implements the SQL/MM specification. SQL-MM 3: 5.1.25

This method supports Circular Strings and Curves

Examples

SELECT ST_AsText('01030000000100000005000000000000000000
000000000000000000000000000000000000000000000000
F03F000000000000F03F000000000000F03F000000000000F03
F000000000000000000000000000000000000000000000000');

                   st_astext
--------------------------------
 POLYGON((0 0,0 1,1 1,1 0,0 0))
(1 row)

Name

ST_AsTWKB — Returns the geometry as TWKB, aka "Tiny Well-Known Binary"

Synopsis

bytea ST_AsTWKB(geometry g1, integer decimaldigits_xy=0, integer decimaldigits_z=0, integer decimaldigits_m=0, boolean include_sizes=false, boolean include_bounding boxes=false);

bytea ST_AsTWKB(geometry[] geometries, bigint[] unique_ids, integer decimaldigits_xy=0, integer decimaldigits_z=0, integer decimaldigits_m=0, boolean include_sizes=false, boolean include_bounding_boxes=false);

Description

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.

Availability: 2.2.0

Examples

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

Description

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.

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

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

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>

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>

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

Description

Return a GeoHash representation (http://en.wikipedia.org/wiki/Geohash) of the geometry. A GeoHash encodes a 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 also be thought of as a box, that contains the actual point.

If no maxchars is specified ST_GeoHash returns a GeoHash based on full precision of the input geometry type. Points return a GeoHash with 20 characters of precision (about enough to hold the full double precision of the input). Other types return a GeoHash with a variable amount of precision, based on the size of the feature. Larger features are represented with less precision, smaller features with more precision. The idea is that the box implied by the GeoHash will always contain the input feature.

If maxchars is specified ST_GeoHash returns a GeoHash with at most that many characters so 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.

Availability: 1.4.0

[Note]

ST_GeoHash will not work with geometries that are not in geographic (lon/lat) coordinates.

This method supports Circular Strings and Curves

Examples

SELECT ST_GeoHash(ST_SetSRID(ST_MakePoint(-126,48),4326));

         st_geohash
----------------------
 c0w3hf1s70w3hf1s70w3

SELECT ST_GeoHash(ST_SetSRID(ST_MakePoint(-126,48),4326),5);

 st_geohash
------------
 c0w3h
                
                

See Also

???


Name

ST_AsGeoJSON — Return a Geobuf representation of a set of rows.

Synopsis

text ST_GeoHash(geometry geom, integer maxchars=full_precision_of_point);

Description

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.

geom_name is the name of the geometry column in the row data.

row row data with at least a geometry column.

Availability: 2.4.0

Examples

encode(ST_AsGeobuf('geom', q), '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_AsSVG — Transform a geometry into the coordinate space of a Mapbox Vector Tile.

Synopsis

text ST_AsHEXEWKB(geometry g1, text NDRorXDR);

text ST_AsHEXEWKB(geometry g1);

Description

Transform a geometry into the coordinate space of a Mapbox Vector Tile of a set of rows corresponding to a Layer. Makes best effort to keep and even correct validity and might collapse geometry into a lower dimension in the process.

geom is the geometry to transform.

bounds is the geometric bounds of the tile contents without buffer.

extent is the tile extent in tile coordinate space as defined by the specification. If NULL it will default to 4096.

buffer is the buffer distance in tile coordinate space to optionally clip geometries. If NULL it will default to 0.

clip_geom is a boolean to control if geometries should be clipped or encoded as is. If NULL it will default to true.

Availability: 2.4.0

Examples

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 4096,10 4091,5 4096)),((5 4096,0 4096,0 4101,5 4096)))

                
                

Name

ST_AsGML — Return a Mapbox Vector Tile representation of a set of rows.

Synopsis

text ST_AsX3D(geometry g1, integer maxdecimaldigits=15, integer options=0);

Description

Return a Mapbox Vector Tile representation of a set of rows corresponding to a Layer. Multiple calls can be concatenated to a tile with multiple Layers. Geometry is assumed to be in tile coordinate space and valid as per specification. Typically ST_AsSVG can be used to transform geometry into tile coordinate space. Other row data will be encoded as attributes.

The Mapbox Vector Tile format can store features with a different set of attributes per feature. To make use of this feature supply a JSONB column in the row data containing Json objects one level deep. The keys and values in the object will be parsed into feature attributes.

name is the name of the Layer

extent is the tile extent in screen space as defined by the specification. If NULL it will default to 4096.

geom_name is the name of the geometry column in the row data.

row row data with at least a geometry column.

Availability: 2.4.0

Examples

SELECT ST_AsMVT('test', 4096, 'geom', q) FROM (SELECT 1 AS c1,
    ST_AsMVTGeom(ST_GeomFromText('POLYGON ((35 10, 45 45, 15 40, 10 20, 35 10), (20 30, 35 35, 30 20, 20 30))'),
    ST_MakeBox2D(ST_Point(0, 0), ST_Point(4096, 4096)), 4096, 0, false) AS geom) AS q;
                              st_asmvt
--------------------------------------------------------------------
 \x1a330a0474657374122112020000180322190946ec3f2214453b0a092832140f091d271a1e09091e13130f1a026331220228017802

                
                

See Also

ST_AsSVG

8.7. Opérateurs

&& — Renvoi VRAI si la boite englobante 2D de A intersecte la boite englobante 2D de B.
&&(geometry,box2df) — Renvoi VRAI si la boite englobante 2D de A intersecte la boite englobante 2D de B.
&&(box2df,geometry) — Renvoi VRAI si la boite englobante 2D de A intersecte la boite englobante 2D de B.
&&(box2df,box2df) — Renvoi VRAI si la boite englobante 2D de A intersecte la boite englobante 2D de B.
&&& — Returns TRUE if A's n-D bounding box intersects B's n-D bounding box.
&&&(geometry,gidx) — Renvoi VRAI si la boite englobante 2D de A intersecte la boite englobante 2D de B.
&&&(gidx,geometry) — Renvoi VRAI si la boite englobante 2D de A intersecte la boite englobante 2D de B.
&&&(gidx,gidx) — Renvoi VRAI si la boite englobante 2D de A intersecte la boite englobante 2D de B.
&< — 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 A's bounding box is the same as B's. Uses double precision bounding box.
>> — 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) — Renvoi VRAI si la boite englobante 2D de A intersecte la boite englobante 2D de B.
@(box2df,geometry) — Renvoi VRAI si la boite englobante 2D de A intersecte la boite englobante 2D de B.
@(box2df,box2df) — Renvoi VRAI si la boite englobante 2D de A intersecte la boite englobante 2D de B.
|&> — 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) — Renvoi VRAI si la boite englobante 2D de A intersecte la boite englobante 2D de B.
~(box2df,geometry) — Renvoi VRAI si la boite englobante 2D de A intersecte la boite englobante 2D de B.
~(box2df,box2df) — Renvoi VRAI si la boite englobante 2D de A intersecte la boite englobante 2D de B.
~= — Returns TRUE if A's bounding box is the same as B's.
<-> — 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 centroids of A and B bounding boxes.
<<#>> — Returns the n-D distance between A and B bounding boxes.

Name

&& — Renvoi VRAI si la boite englobante 2D de A intersecte la boite englobante 2D de B.

Synopsis

booléen &&( geometry A , geometry B );

booléen &&( geography A , geography B );

Description

L'opérateur && renvoi VRAI si la boite englobante 2D de la géométrie A intersecte la boite englobante 2D de la géométrie B.

[Note]

This operand will make use of any indexes that may be available on the geometries.

Amélioration: la version 2.0.0 introduit le support des surfaces Polyédrique.

Disponibilité: La version 1.5.0 introduit le support des géographie.

This method supports Circular Strings and Curves

This function supports Polyhedral surfaces.

Exemples

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)

Voir Aussi

|&>, &>, &<|, &<, ~, @


Name

&&(geometry,box2df) — Renvoi VRAI si la boite englobante 2D de A intersecte la boite englobante 2D de B.

Synopsis

boolean &&( geometry A , box2df B );

Description

L'opérateur && renvoi VRAI si la boite englobante 2D de la géométrie A intersecte la boite englobante 2D de la géométrie B.

[Note]

This operand is intended to be used internally by BRIN indexes, more than by users.

Disponibilité: La version 1.5.0 introduit le support des géographie.

This method supports Circular Strings and Curves

This function supports Polyhedral surfaces.

Exemples

SELECT ST_MakePoint(1,1) && ST_MakeBox2D(ST_MakePoint(0,0), ST_MakePoint(2,2)) AS overlaps;

 overlaps
----------
 t
(1 row)

Name

&&(box2df,geometry) — Renvoi VRAI si la boite englobante 2D de A intersecte la boite englobante 2D de B.

Synopsis

boolean &&( box2df A , geometry B );

Description

L'opérateur && renvoi VRAI si la boite englobante 2D de la géométrie A intersecte la boite englobante 2D de la géométrie B.

[Note]

This operand is intended to be used internally by BRIN indexes, more than by users.

Disponibilité: La version 1.5.0 introduit le support des géographie.

This method supports Circular Strings and Curves

This function supports Polyhedral surfaces.

Exemples

SELECT ST_MakeBox2D(ST_MakePoint(0,0), ST_MakePoint(2,2)) && ST_MakePoint(1,1) AS overlaps;

 overlaps
----------
 t
(1 row)

Name

&&(box2df,box2df) — Renvoi VRAI si la boite englobante 2D de A intersecte la boite englobante 2D de B.

Synopsis

boolean &&( box2df A , box2df B );

Description

L'opérateur && renvoi VRAI si la boite englobante 2D de la géométrie A intersecte la boite englobante 2D de la géométrie B.

[Note]

This operator is intended to be used internally by BRIN indexes, more than by users.

Disponibilité: La version 1.5.0 introduit le support des géographie.

This method supports Circular Strings and Curves

This function supports Polyhedral surfaces.

Exemples

SELECT ST_MakeBox2D(ST_MakePoint(0,0), ST_MakePoint(2,2)) && ST_MakeBox2D(ST_MakePoint(1,1), ST_MakePoint(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 );

Description

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é : Version 2.0.0

This method supports Circular Strings and Curves

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

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

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

Voir Aussi

&&


Name

&&&(geometry,gidx) — Renvoi VRAI si la boite englobante 2D de A intersecte la boite englobante 2D de B.

Synopsis

boolean &&&( geometry A , gidx B );

Description

L'opérateur && renvoi VRAI si la boite englobante 2D de la géométrie A intersecte la boite englobante 2D de la géométrie B.

[Note]

This operator is intended to be used internally by BRIN indexes, more than by users.

Disponibilité: La version 1.5.0 introduit le support des géographie.

This method supports Circular Strings and Curves

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

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

Exemples

SELECT ST_MakePoint(1,1,1) &&& ST_3DMakeBox(ST_MakePoint(0,0,0), ST_MakePoint(2,2,2)) AS overlaps;

 overlaps
----------
 t
(1 row)

Name

&&&(gidx,geometry) — Renvoi VRAI si la boite englobante 2D de A intersecte la boite englobante 2D de B.

Synopsis

boolean &&&( gidx A , geometry B );

Description

L'opérateur && renvoi VRAI si la boite englobante 2D de la géométrie A intersecte la boite englobante 2D de la géométrie B.

[Note]

This operator is intended to be used internally by BRIN indexes, more than by users.

Disponibilité: La version 1.5.0 introduit le support des géographie.

This method supports Circular Strings and Curves

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

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

Exemples

SELECT ST_3DMakeBox(ST_MakePoint(0,0,0), ST_MakePoint(2,2,2)) &&& ST_MakePoint(1,1,1) AS overlaps;

 overlaps
----------
 t
(1 row)

Name

&&&(gidx,gidx) — Renvoi VRAI si la boite englobante 2D de A intersecte la boite englobante 2D de B.

Synopsis

boolean &&&( gidx A , gidx B );

Description

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.

Disponibilité: La version 1.5.0 introduit le support des géographie.

This method supports Circular Strings and Curves

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

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

Exemples

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)

Name

&< — Returns TRUE if A's bounding box overlaps or is to the left of B's.

Synopsis

boolean &<( geometry A , geometry B );

Description

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.

Exemples

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)

Voir Aussi

&&, |&>, &>, &<|


Name

&<| — Returns TRUE if A's bounding box overlaps or is below B's.

Synopsis

boolean &<|( geometry A , geometry B );

Description

The &<| operator returns TRUE if the bounding box of geometry A overlaps or is below of the bounding box of geometry B, or more accurately, overlaps or is NOT above the bounding box of geometry B.

This method supports Circular Strings and Curves

This function supports Polyhedral surfaces.

[Note]

This operand will make use of any indexes that may be available on the geometries.

Exemples

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)

Voir Aussi

&&, |&>, &>, &<


Name

&> — Returns TRUE if A' bounding box overlaps or is to the right of B's.

Synopsis

boolean &>( geometry A , geometry B );

Description

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.

Exemples

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)

Voir Aussi

&&, |&>, &<|, &<


Name

<< — Returns TRUE if A's bounding box is strictly to the left of B's.

Synopsis

boolean <<( geometry A , geometry B );

Description

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.

Exemples

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)

Voir Aussi

>>, |>>, <<|


Name

<<| — Returns TRUE if A's bounding box is strictly below B's.

Synopsis

boolean <<|( geometry A , geometry B );

Description

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.

Exemples

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)

Voir Aussi

<<, >>, |>>


Name

= — Returns TRUE if A's bounding box is the same as B's. Uses double precision bounding box.

Synopsis

boolean =( geometry A , geometry B );

boolean =( geography A , geography B );

Description

The = operator returns TRUE if the bounding box of geometry/geography A is the same as the bounding box 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).

[Warning]

This is cause for a lot of confusion. When you compare geometryA = geometryB it will return true even when the geometries are clearly different IF their bounding boxes are the same. To check for true equality use ST_OrderingEquals or ST_Equals

[Caution]

This operand will NOT make use of any indexes that may be available on the geometries.

This method supports Circular Strings and Curves

This function supports Polyhedral surfaces.

Changed: 2.0.0 , the bounding box of geometries was changed to use double precision instead of float4 precision of prior. The side effect of this is that in particular points in prior versions that were a little different may have returned true in prior versions and false in 2.0+ since their float4 boxes would be the same but there float8 (double precision), would be different.

Exemples

SELECT 'LINESTRING(0 0, 0 1, 1 0)'::geometry = 'LINESTRING(1 1, 0 0)'::geometry;
 ?column?
----------
 t
(1 row)

SELECT ST_AsText(column1)
FROM ( VALUES
        ('LINESTRING(0 0, 1 1)'::geometry),
        ('LINESTRING(1 1, 0 0)'::geometry)) AS foo;
          st_astext
---------------------
 LINESTRING(0 0,1 1)
 LINESTRING(1 1,0 0)
(2 rows)

-- 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)
(1 row)

-- In versions prior to 2.0, this used to return true --
 SELECT ST_GeomFromText('POINT(1707296.37 4820536.77)') =
        ST_GeomFromText('POINT(1707296.27 4820536.87)') As pt_intersect;

--pt_intersect --
f

Name

>> — Returns TRUE if A's bounding box is strictly to the right of B's.

Synopsis

boolean >>( geometry A , geometry B );

Description

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.

Exemples

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)

Voir Aussi

<<, |>>, <<|


Name

@ — Returns TRUE if A's bounding box is contained by B's.

Synopsis

boolean @( geometry A , geometry B );

Description

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.

Exemples

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)

Voir Aussi

~, &&


Name

@(geometry,box2df) — Renvoi VRAI si la boite englobante 2D de A intersecte la boite englobante 2D de B.

Synopsis

boolean @( geometry A , box2df B );

Description

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.

Disponibilité: La version 1.5.0 introduit le support des géographie.

This method supports Circular Strings and Curves

This function supports Polyhedral surfaces.

Exemples

SELECT ST_Buffer(ST_GeomFromText('POINT(2 2)'), 1) @ ST_MakeBox2D(ST_MakePoint(0,0), ST_MakePoint(5,5)) AS is_contained;

 is_contained
--------------
 t
(1 row)

Name

@(box2df,geometry) — Renvoi VRAI si la boite englobante 2D de A intersecte la boite englobante 2D de B.

Synopsis

boolean @( box2df A , geometry B );

Description

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.

Disponibilité: La version 1.5.0 introduit le support des géographie.

This method supports Circular Strings and Curves

This function supports Polyhedral surfaces.

Exemples

SELECT ST_MakeBox2D(ST_MakePoint(2,2), ST_MakePoint(3,3)) @ ST_Buffer(ST_GeomFromText('POINT(1 1)'), 10) AS is_contained;

 is_contained
--------------
 t
(1 row)

Name

@(box2df,box2df) — Renvoi VRAI si la boite englobante 2D de A intersecte la boite englobante 2D de B.

Synopsis

boolean @( box2df A , box2df B );

Description

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.

Disponibilité: La version 1.5.0 introduit le support des géographie.

This method supports Circular Strings and Curves

This function supports Polyhedral surfaces.

Exemples

SELECT ST_MakeBox2D(ST_MakePoint(2,2), ST_MakePoint(3,3)) @ ST_MakeBox2D(ST_MakePoint(0,0), ST_MakePoint(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 );

Description

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.

Exemples

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)

Voir Aussi

&&, &>, &<|, &<


Name

|>> — Returns TRUE if A's bounding box is strictly above B's.

Synopsis

boolean |>>( geometry A , geometry B );

Description

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.

Exemples

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)

Voir Aussi

<<, >>, <<|


Name

~ — Returns TRUE if A's bounding box contains B's.

Synopsis

boolean ~( geometry A , geometry B );

Description

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.

Exemples

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)

Voir Aussi

@, &&


Name

~(geometry,box2df) — Renvoi VRAI si la boite englobante 2D de A intersecte la boite englobante 2D de B.

Synopsis

boolean ~( geometry A , box2df B );

Description

L'opérateur && renvoi VRAI si la boite englobante 2D de la géométrie A intersecte la boite englobante 2D de la géométrie B.

[Note]

This operand is intended to be used internally by BRIN indexes, more than by users.

Disponibilité: La version 1.5.0 introduit le support des géographie.

This method supports Circular Strings and Curves

This function supports Polyhedral surfaces.

Exemples

SELECT ST_Buffer(ST_GeomFromText('POINT(1 1)'), 10) ~ ST_MakeBox2D(ST_MakePoint(0,0), ST_MakePoint(2,2)) AS contains;

 contains
----------
 t
(1 row)

Name

~(box2df,geometry) — Renvoi VRAI si la boite englobante 2D de A intersecte la boite englobante 2D de B.

Synopsis

boolean ~( box2df A , geometry B );

Description

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.

Disponibilité: La version 1.5.0 introduit le support des géographie.

This method supports Circular Strings and Curves

This function supports Polyhedral surfaces.

Exemples

SELECT ST_MakeBox2D(ST_MakePoint(0,0), ST_MakePoint(5,5)) ~ ST_Buffer(ST_GeomFromText('POINT(2 2)'), 1) AS contains;

 contains
----------
 t
(1 row)

Name

~(box2df,box2df) — Renvoi VRAI si la boite englobante 2D de A intersecte la boite englobante 2D de B.

Synopsis

boolean ~( box2df A , box2df B );

Description

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.

Disponibilité: La version 1.5.0 introduit le support des géographie.

This method supports Circular Strings and Curves

This function supports Polyhedral surfaces.

Exemples

SELECT ST_MakeBox2D(ST_MakePoint(0,0), ST_MakePoint(5,5)) ~ ST_MakeBox2D(ST_MakePoint(2,2), ST_MakePoint(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 );

Description

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

This function supports Polyhedral surfaces.

[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 and to check for bounding box equality =; operator is a safer option.

Exemples

select 'LINESTRING(0 0, 1 1)'::geometry ~= 'LINESTRING(0 1, 1 0)'::geometry as equality;
 equality   |
-----------------+
          t    |
                        

The above can be used to test if you have the new or old behavior of ~= operator.


Name

<-> — Returns the 2D distance between A and B.

Synopsis

double precision <->( geometry A , geometry B );

double precision <->( geography A , geography B );

Description

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 OpenGeo workshop: Nearest-Neighbour Searching for real live 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+

Exemples

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)

                        

Name

|=| — Returns the distance between A and B trajectories at their closest point of approach.

Synopsis

double precision |=|( geometry A , geometry B );

Description

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

Exemples

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

Description

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+

Exemples

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)

Name

<<->> — Returns the n-D distance between the centroids of A and B bounding boxes.

Synopsis

double precision <<->>( geometry A , geometry B );

Description

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+

Voir Aussi

<<#>>, <->


Name

<<#>> — Returns the n-D distance between A and B bounding boxes.

Synopsis

double precision <<#>>( geometry A , geometry B );

Description

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.2.0 -- KNN only available for PostgreSQL 9.1+

Voir Aussi

<<->>, <#>

8.8. Relations spatiales et mesures

ST_3DClosestPoint — Returns the 3-dimensional point on g1 that is closest to g2. This is the first point of the 3D shortest line.
ST_3DDistance — For geometry type Returns the 3-dimensional cartesian minimum distance (based on spatial ref) between two geometries in projected units.
ST_3DDWithin — For 3d (z) geometry type Returns true if two geometries 3d distance is within number of units.
ST_3DDFullyWithin — Returns true if all of the 3D geometries are within the specified distance of one another.
ST_3DIntersects — Returns TRUE if the Geometries "spatially intersect" in 3d - only for points, linestrings, polygons, polyhedral surface (area). With SFCGAL backend enabled also supports TINS
ST_3DLongestLine — Returns the 3-dimensional longest line between two geometries
ST_3DMaxDistance — For geometry type Returns the 3-dimensional cartesian maximum distance (based on spatial ref) between two geometries in projected units.
ST_3DShortestLine — Returns the 3-dimensional shortest line between two geometries
ST_Area — Returns the area of the surface if it is a Polygon or MultiPolygon. For geometry, a 2D Cartesian area is determined with units specified by the SRID. For geography, area is determined on a curved surface with units in square meters.
ST_Azimuth — Returns the north-based azimuth as the angle in radians measured clockwise from the vertical on pointA to pointB.
ST_Centroid — Returns the geometric center of a geometry.
ST_ClosestPoint — Returns the 2-dimensional point on g1 that is closest to g2. This is the first point of the shortest line.
ST_ClusterDBSCAN — Windowing function that returns integer id for the cluster each input geometry is in based on 2D implementation of Density-based spatial clustering of applications with noise (DBSCAN) algorithm.
ST_3DIntersects — Aggregate. Returns an array with the connected components of a set of geometries
ST_ClusterKMeans — Windowing function that returns integer id for the cluster each input geometry is in.
ST_DWithin — Aggregate. Returns an array of GeometryCollections, where each GeometryCollection represents a set of geometries separated by no more than the specified distance.
ST_Contains — Returns true if and only if no points of B lie in the exterior of A, and at least one point of the interior of B lies in the interior of A.
ST_ContainsProperly — Returns true if B intersects the interior of A but not the boundary (or exterior). A does not contain properly itself, but does contain itself.
ST_Covers — Returns 1 (TRUE) if no point in Geometry B is outside Geometry A
ST_CoveredBy — Returns 1 (TRUE) if no point in Geometry/Geography A is outside Geometry/Geography B
ST_Crosses — Returns TRUE if the supplied geometries have some, but not all, interior points in common.
ST_LineCrossingDirection — Given 2 linestrings, returns a number between -3 and 3 denoting what kind of crossing behavior. 0 is no crossing.
ST_Disjoint — Returns TRUE if the Geometries do not "spatially intersect" - if they do not share any space together.
ST_Distance — For geometry type Returns the 2D Cartesian distance between two geometries in projected units (based on spatial ref). For geography type defaults to return minimum geodesic distance between two geographies in meters.
ST_MinimumClearance — Returns the minimum clearance of a geometry, a measure of a geometry's robustness.
ST_MinimumClearanceLine — Returns the two-point LineString spanning a geometry's minimum clearance.
ST_HausdorffDistance — Returns the Hausdorff distance between two geometries. Basically a measure of how similar or dissimilar 2 geometries are. Units are in the units of the spatial reference system of the geometries.
ST_Distance — Returns the Fréchet distance between two geometries. This is a measure of similarity between curves that takes into account the location and ordering of the points along the curves. Units are in the units of the spatial reference system of the geometries.
ST_MaxDistance — Returns the 2-dimensional largest distance between two geometries in projected units.
ST_DistanceSphere — Returns minimum distance in meters between two lon/lat geometries. Uses a spherical earth and radius derived from the spheroid defined by the SRID. Faster than ST_DistanceSpheroid ST_DistanceSpheroid, but less accurate. PostGIS versions prior to 1.5 only implemented for points.
ST_DistanceSpheroid — Returns the minimum distance between two lon/lat geometries given a particular spheroid. PostGIS versions prior to 1.5 only support points.
ST_DFullyWithin — Returns true if all of the geometries are within the specified distance of one another
ST_DWithin — Returns true if the geometries are within the specified distance of one another. For geometry units are in those of spatial reference and For geography units are in meters and measurement is defaulted to use_spheroid=true (measure around spheroid), for faster check, use_spheroid=false to measure along sphere.
ST_Equals — Returns true if the given geometries represent the same geometry. Directionality is ignored.
ST_GeometricMedian — Returns the geometric median of a MultiPoint.
ST_HasArc — Returns true if a geometry or geometry collection contains a circular string
ST_Intersects — Returns TRUE if the Geometries/Geography "spatially intersect in 2D" - (share any portion of space) and FALSE if they don't (they are Disjoint). For geography -- tolerance is 0.00001 meters (so any points that close are considered to intersect)
ST_Length — Returns the 2D length of the geometry if it is a LineString or MultiLineString. geometry are in units of spatial reference and geography are in meters (default spheroid)
ST_Length2D — Returns the 2-dimensional length of the geometry if it is a linestring or multi-linestring. This is an alias for ST_Length
ST_3DLength — Returns the 3-dimensional or 2-dimensional length of the geometry if it is a linestring or multi-linestring.
ST_LengthSpheroid — Calculates the 2D or 3D length/perimeter of a geometry on an ellipsoid. This is useful if the coordinates of the geometry are in longitude/latitude and a length is desired without reprojection.
ST_Length2D_Spheroid — Calculates the 2D length/perimeter of a geometry on an ellipsoid. This is useful if the coordinates of the geometry are in longitude/latitude and a length is desired without reprojection.
ST_LongestLine — Returns the 2-dimensional longest line points of two geometries. The function will only return the first longest line if more than one, that the function finds. The line returned will always start in g1 and end in g2. The length of the line this function returns will always be the same as st_maxdistance returns for g1 and g2.
ST_OrderingEquals — Returns true if the given geometries represent the same geometry and points are in the same directional order.
ST_Overlaps — Returns TRUE if the Geometries share space, are of the same dimension, but are not completely contained by each other.
ST_Perimeter — Return the length measurement of the boundary of an ST_Surface or ST_MultiSurface geometry or geography. (Polygon, MultiPolygon). geometry measurement is in units of spatial reference and geography is in meters.
ST_Perimeter2D — Returns the 2-dimensional perimeter of the geometry, if it is a polygon or multi-polygon. This is currently an alias for ST_Perimeter.
ST_3DPerimeter — Returns the 3-dimensional perimeter of the geometry, if it is a polygon or multi-polygon.
ST_PointOnSurface — Returns a POINT guaranteed to lie on the surface.
ST_Project — Returns a POINT projected from a start point using a distance in meters and bearing (azimuth) in radians.
ST_Relate — Returns true if this Geometry is spatially related to anotherGeometry, by testing for intersections between the Interior, Boundary and Exterior of the two geometries as specified by the values in the intersectionMatrixPattern. If no intersectionMatrixPattern is passed in, then returns the maximum intersectionMatrixPattern that relates the 2 geometries.
ST_RelateMatch — Returns true if intersectionMattrixPattern1 implies intersectionMatrixPattern2
ST_ShortestLine — Returns the 2-dimensional shortest line between two geometries
ST_Touches — Returns TRUE if the geometries have at least one point in common, but their interiors do not intersect.
ST_Within — Returns true if the geometry A is completely inside geometry B

Name

ST_3DClosestPoint — Returns the 3-dimensional point on g1 that is closest to g2. This is the first point of the 3D shortest line.

Synopsis

geometry ST_3DClosestPoint(geometry g1, geometry g2);

Description

Returns the 3-dimensional point on g1 that is closest to g2. This is the first point of the 3D shortest line. The 3D length of the 3D shortest line is the 3D distance.

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

This function supports Polyhedral surfaces.

Disponibilité: 2.0.0

Changed: 2.2.0 - if 2 2D geometries are input, a 2D point is returned (instead of old behavior assuming 0 for missing Z). In case of 2D and 3D, Z is no longer assumed to be 0 for missing Z.

Exemples

linestring and point -- both 3d and 2d closest point

SELECT ST_AsEWKT(ST_3DClosestPoint(line,pt)) AS cp3d_line_pt, 
                ST_AsEWKT(ST_ClosestPoint(line,pt)) As cp2d_line_pt
        FROM (SELECT 'POINT(100 100 30)'::geometry As pt, 
                        'LINESTRING (20 80 20, 98 190 1, 110 180 3, 50 75 1000)'::geometry As line
                ) As foo;
        
                
 cp3d_line_pt                                                                        |               cp2d_line_pt
-----------------------------------------------------------+------------------------------------------
 POINT(54.6993798867619 128.935022917228 11.5475869506606) | POINT(73.0769230769231 115.384615384615)
                                        

linestring and multipoint -- both 3d and 2d closest point

SELECT ST_AsEWKT(ST_3DClosestPoint(line,pt)) AS cp3d_line_pt, 
                ST_AsEWKT(ST_ClosestPoint(line,pt)) As cp2d_line_pt
        FROM (SELECT 'MULTIPOINT(100 100 30, 50 74 1000)'::geometry As pt, 
                        'LINESTRING (20 80 20, 98 190 1, 110 180 3, 50 75 900)'::geometry As line
                ) As foo;
        
                
                       cp3d_line_pt                        | cp2d_line_pt
-----------------------------------------------------------+--------------
 POINT(54.6993798867619 128.935022917228 11.5475869506606) | POINT(50 75)
                                        

Multilinestring and polygon both 3d and 2d closest point

SELECT ST_AsEWKT(ST_3DClosestPoint(poly, mline)) As cp3d,
    ST_AsEWKT(ST_ClosestPoint(poly, mline)) As cp2d 
        FROM (SELECT  ST_GeomFromEWKT('POLYGON((175 150 5, 20 40 5, 35 45 5, 50 60 5, 100 100 5, 175 150 5))') As poly,
                ST_GeomFromEWKT('MULTILINESTRING((175 155 2, 20 40 20, 50 60 -2, 125 100 1, 175 155 1),
                (1 10 2, 5 20 1))') As mline ) As foo;
                   cp3d                    |     cp2d
-------------------------------------------+--------------
 POINT(39.993580415989 54.1889925532825 5) | POINT(20 40)
             


Name

ST_3DDistance — For geometry type Returns the 3-dimensional cartesian minimum distance (based on spatial ref) between two geometries in projected units.

Synopsis

float ST_3DDistance(geometry g1, geometry g2);

Description

For geometry type returns the 3-dimensional minimum cartesian distance between two geometries in projected units (spatial ref units).

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

This function supports Polyhedral surfaces.

This method implements the SQL/MM specification. SQL-MM ?

This method is also provided by SFCGAL backend.

Disponibilité: 2.0.0

Changed: 2.2.0 - In case of 2D and 3D, Z is no longer assumed to be 0 for missing Z.

Exemples

-- Geometry example - units in meters (SRID: 2163 US National Atlas Equal area) (3D point and line compared 2D point and line)
-- Note: currently no vertical datum support so Z is not transformed and assumed to be same units as final.
SELECT ST_3DDistance(
                        ST_Transform(ST_GeomFromEWKT('SRID=4326;POINT(-72.1235 42.3521 4)'),2163),
                        ST_Transform(ST_GeomFromEWKT('SRID=4326;LINESTRING(-72.1260 42.45 15, -72.123 42.1546 20)'),2163)
                ) As dist_3d,
                ST_Distance(
                        ST_Transform(ST_GeomFromText('POINT(-72.1235 42.3521)',4326),2163),
                        ST_Transform(ST_GeomFromText('LINESTRING(-72.1260 42.45, -72.123 42.1546)', 4326),2163)
                ) As dist_2d;

     dist_3d      |     dist_2d
------------------+-----------------
 127.295059324629 | 126.66425605671
SELECT ST_AsEWKT(ST_3DLongestLine(poly, mline)) As lol3d,
    ST_AsEWKT(ST_LongestLine(poly, mline)) As lol2d 
        FROM (SELECT  ST_GeomFromEWKT('POLYGON((175 150 5, 20 40 5, 35 45 5, 50 60 5, 100 100 5, 175 150 5))') As poly,
                ST_GeomFromEWKT('MULTILINESTRING((175 155 2, 20 40 20, 50 60 -2, 125 100 1, 175 155 1),
                (1 10 2, 5 20 1))') As mline ) As foo;
            lol3d             |          lol2d
------------------------------+--------------------------
 LINESTRING(175 150 5,1 10 2) | LINESTRING(175 150,1 10)

Name

ST_3DDWithin — For 3d (z) geometry type Returns true if two geometries 3d distance is within number of units.

Synopsis

boolean ST_3DDWithin(geometry g1, geometry g2, double precision distance_of_srid);

Description

For geometry type returns true if the 3d distance between two objects is within distance_of_srid specified projected units (spatial ref units).

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

This function supports Polyhedral surfaces.

This method implements the SQL/MM specification. SQL-MM ?

Disponibilité: 2.0.0

Exemples

-- Geometry example - units in meters (SRID: 2163 US National Atlas Equal area) (3D point and line compared 2D point and line)
-- Note: currently no vertical datum support so Z is not transformed and assumed to be same units as final.
SELECT ST_3DDWithin(
                        ST_Transform(ST_GeomFromEWKT('SRID=4326;POINT(-72.1235 42.3521 4)'),2163),
                        ST_Transform(ST_GeomFromEWKT('SRID=4326;LINESTRING(-72.1260 42.45 15, -72.123 42.1546 20)'),2163),
                        126.8
                ) As within_dist_3d,
ST_DWithin(
                        ST_Transform(ST_GeomFromEWKT('SRID=4326;POINT(-72.1235 42.3521 4)'),2163),
                        ST_Transform(ST_GeomFromEWKT('SRID=4326;LINESTRING(-72.1260 42.45 15, -72.123 42.1546 20)'),2163),
                        126.8
                ) As within_dist_2d;

 within_dist_3d | within_dist_2d
----------------+----------------
 f              | t

Name

ST_3DDFullyWithin — Returns true if all of the 3D geometries are within the specified distance of one another.

Synopsis

boolean ST_3DDFullyWithin(geometry g1, geometry g2, double precision distance);

Description

Returns true if the 3D geometries are fully within the specified distance of one another. The distance is specified in units defined by the spatial reference system of the geometries. For this function to make sense, the source geometries must both be of the same coordinate projection, having the same SRID.

[Note]

This function call will automatically include a bounding box comparison that will make use of any indexes that are available on the geometries.

Disponibilité: 2.0.0

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

This function supports Polyhedral surfaces.

Exemples

postgis=# SELECT ST_DFullyWithin(geom_a, geom_b, 10) as DFullyWithin10, ST_DWithin(geom_a, geom_b, 10) as DWithin10, ST_DFullyWithin(geom_a, geom_b, 20) as DFullyWithin20 from 
                (select ST_GeomFromText('POINT(1 1)') as geom_a,ST_GeomFromText('LINESTRING(1 5, 2 7, 1 9, 14 12)') as geom_b) t1;
   
-----------------
 DFullyWithin10 | DWithin10 | DFullyWithin20 |
---------------+----------+---------------+
 f             | t        | t             | 

Name

ST_3DIntersects — Returns TRUE if the Geometries "spatially intersect" in 3d - only for points, linestrings, polygons, polyhedral surface (area). With SFCGAL backend enabled also supports TINS

Synopsis

boolean ST_3DIntersects( geometry geomA , geometry geomB );

Description

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.

Disponibilité: 2.0.0

[Note]

This function call will automatically include a bounding box comparison that will make use of any indexes that are available on the geometries.

[Note]

In order to take advantage of support for TINS, you need to enable the SFCGAL backend. This can be done at session time with: set postgis.backend = sfcgal; or at the database or system level. Database level can be done with ALTER DATABASE gisdb SET postgis.backend = sfcgal;.

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

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

This method is also provided by SFCGAL backend.

This method implements the SQL/MM specification. SQL-MM 3: ?

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

set postgis.backend = sfcgal;
SELECT ST_3DIntersects('TIN(((0 0,1 0,0 1,0 0)))'::geometry, 'POINT(.1 .1)'::geometry);
 st_3dintersects
-----------------
 t

Voir également

ST_Intersects


Name

ST_3DLongestLine — Returns the 3-dimensional longest line between two geometries

Synopsis

geometry ST_3DLongestLine(geometry g1, geometry g2);

Description

Returns the 3-dimensional longest line between two geometries. The function will only return the first longest line if more than one. The line returned will always start in g1 and end in g2. The 3D length of the line this function returns will always be the same as ST_3DMaxDistance returns for g1 and g2.

Disponibilité: 2.0.0

Changed: 2.2.0 - if 2 2D geometries are input, a 2D point is returned (instead of old behavior assuming 0 for missing Z). In case of 2D and 3D, Z is no longer assumed to be 0 for missing Z.

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

This function supports Polyhedral surfaces.

Exemples

linestring and point -- both 3d and 2d longest line

SELECT ST_AsEWKT(ST_3DLongestLine(line,pt)) AS lol3d_line_pt, 
                ST_AsEWKT(ST_LongestLine(line,pt)) As lol2d_line_pt
        FROM (SELECT 'POINT(100 100 30)'::geometry As pt, 
                        'LINESTRING (20 80 20, 98 190 1, 110 180 3, 50 75 1000)'::geometry As line
                ) As foo;
        
                
           lol3d_line_pt           |       lol2d_line_pt
-----------------------------------+----------------------------
 LINESTRING(50 75 1000,100 100 30) | LINESTRING(98 190,100 100)
                                        

linestring and multipoint -- both 3d and 2d longest line

SELECT ST_AsEWKT(ST_3DLongestLine(line,pt)) AS lol3d_line_pt, 
                ST_AsEWKT(ST_LongestLine(line,pt)) As lol2d_line_pt
        FROM (SELECT 'MULTIPOINT(100 100 30, 50 74 1000)'::geometry As pt, 
                        'LINESTRING (20 80 20, 98 190 1, 110 180 3, 50 75 900)'::geometry As line
                ) As foo;
        
                
          lol3d_line_pt          |      lol2d_line_pt
---------------------------------+--------------------------
 LINESTRING(98 190 1,50 74 1000) | LINESTRING(98 190,50 74)
                                        

Multilinestring and polygon both 3d and 2d longest line

SELECT ST_AsEWKT(ST_3DLongestLine(poly, mline)) As lol3d,
    ST_AsEWKT(ST_LongestLine(poly, mline)) As lol2d 
        FROM (SELECT  ST_GeomFromEWKT('POLYGON((175 150 5, 20 40 5, 35 45 5, 50 60 5, 100 100 5, 175 150 5))') As poly,
                ST_GeomFromEWKT('MULTILINESTRING((175 155 2, 20 40 20, 50 60 -2, 125 100 1, 175 155 1),
                (1 10 2, 5 20 1))') As mline ) As foo;
            lol3d             |          lol2d
------------------------------+--------------------------
 LINESTRING(175 150 5,1 10 2) | LINESTRING(175 150,1 10)
             


Name

ST_3DMaxDistance — For geometry type Returns the 3-dimensional cartesian maximum distance (based on spatial ref) between two geometries in projected units.

Synopsis

float ST_3DMaxDistance(geometry g1, geometry g2);

Description

For geometry type returns the 3-dimensional maximum cartesian distance between two geometries in projected units (spatial ref units).

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

This function supports Polyhedral surfaces.

Disponibilité: 2.0.0

Changed: 2.2.0 - In case of 2D and 3D, Z is no longer assumed to be 0 for missing Z.

Exemples

-- Geometry example - units in meters (SRID: 2163 US National Atlas Equal area) (3D point and line compared 2D point and line)
-- Note: currently no vertical datum support so Z is not transformed and assumed to be same units as final.
SELECT ST_3DMaxDistance(
                        ST_Transform(ST_GeomFromEWKT('SRID=4326;POINT(-72.1235 42.3521 10000)'),2163),
                        ST_Transform(ST_GeomFromEWKT('SRID=4326;LINESTRING(-72.1260 42.45 15, -72.123 42.1546 20)'),2163)
                ) As dist_3d,
                ST_MaxDistance(
                        ST_Transform(ST_GeomFromEWKT('SRID=4326;POINT(-72.1235 42.3521 10000)'),2163),
                        ST_Transform(ST_GeomFromEWKT('SRID=4326;LINESTRING(-72.1260 42.45 15, -72.123 42.1546 20)'),2163)
                ) As dist_2d;

     dist_3d      |     dist_2d
------------------+------------------
 24383.7467488441 | 22247.8472107251

Name

ST_3DShortestLine — Returns the 3-dimensional shortest line between two geometries

Synopsis

geometry ST_3DShortestLine(geometry g1, geometry g2);

Description

Returns the 3-dimensional shortest line between two geometries. The function will only return the first shortest line if more than one, that the function finds. If g1 and g2 intersects in just one point the function will return a line with both start and end in that intersection-point. If g1 and g2 are intersecting with more than one point the function will return a line with start and end in the same point but it can be any of the intersecting points. The line returned will always start in g1 and end in g2. The 3D length of the line this function returns will always be the same as ST_3DDistance returns for g1 and g2.

Disponibilité: 2.0.0

Changed: 2.2.0 - if 2 2D geometries are input, a 2D point is returned (instead of old behavior assuming 0 for missing Z). In case of 2D and 3D, Z is no longer assumed to be 0 for missing Z.

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

This function supports Polyhedral surfaces.

Exemples

linestring and point -- both 3d and 2d shortest line

SELECT ST_AsEWKT(ST_3DShortestLine(line,pt)) AS shl3d_line_pt, 
                ST_AsEWKT(ST_ShortestLine(line,pt)) As shl2d_line_pt
        FROM (SELECT 'POINT(100 100 30)'::geometry As pt, 
                        'LINESTRING (20 80 20, 98 190 1, 110 180 3, 50 75 1000)'::geometry As line
                ) As foo;
        
                
 shl3d_line_pt                                                                                         |               shl2d_line_pt
----------------------------------------------------------------------------+------------------------------------------------------
 LINESTRING(54.6993798867619 128.935022917228 11.5475869506606,100 100 30)  | LINESTRING(73.0769230769231 115.384615384615,100 100)
                                        

linestring and multipoint -- both 3d and 2d shortest line

SELECT ST_AsEWKT(ST_3DShortestLine(line,pt)) AS shl3d_line_pt, 
                ST_AsEWKT(ST_ShortestLine(line,pt)) As shl2d_line_pt
        FROM (SELECT 'MULTIPOINT(100 100 30, 50 74 1000)'::geometry As pt, 
                        'LINESTRING (20 80 20, 98 190 1, 110 180 3, 50 75 900)'::geometry As line
                ) As foo;
        
                
                       shl3d_line_pt                                       | shl2d_line_pt
---------------------------------------------------------------------------+------------------------
 LINESTRING(54.6993798867619 128.935022917228 11.5475869506606,100 100 30) | LINESTRING(50 75,50 74)
                                        

Multilinestring and polygon both 3d and 2d shortest line

SELECT ST_AsEWKT(ST_3DShortestLine(poly, mline)) As shl3d,
    ST_AsEWKT(ST_ShortestLine(poly, mline)) As shl2d 
        FROM (SELECT  ST_GeomFromEWKT('POLYGON((175 150 5, 20 40 5, 35 45 5, 50 60 5, 100 100 5, 175 150 5))') As poly,
                ST_GeomFromEWKT('MULTILINESTRING((175 155 2, 20 40 20, 50 60 -2, 125 100 1, 175 155 1),
                (1 10 2, 5 20 1))') As mline ) As foo;
                   shl3d                                                                           |     shl2d
---------------------------------------------------------------------------------------------------+------------------------
 LINESTRING(39.993580415989 54.1889925532825 5,40.4078575708294 53.6052383805529 5.03423778139177) | LINESTRING(20 40,20 40)
             


Name

ST_Area — Returns the area of the surface if it is a Polygon or MultiPolygon. For geometry, a 2D Cartesian area is determined with units specified by the SRID. For geography, area is determined on a curved surface with units in square meters.

Synopsis

float ST_Area(geometry g1);

float ST_Area(geography geog, boolean use_spheroid=true);

Description

Returns the area of the geometry if it is a Polygon or MultiPolygon. Return the area measurement of an ST_Surface or ST_MultiSurface value. For geometry, a 2D Cartesian area is determined with units specified by the SRID. For geography, by default area is determined on a spheroid with units in square meters. To measure around the faster but less accurate sphere, use ST_Area(geog,false).

Enhanced: 2.0.0 - support for 2D polyhedral surfaces was introduced.

Enhanced: 2.2.0 - measurement on spheroid performed with GeographicLib for improved accuracy and robustness. Requires Proj >= 4.9.0 to take advantage of the new feature.

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

This method implements the SQL/MM specification. SQL-MM 3: 8.1.2, 9.5.3

This function supports Polyhedral surfaces.

[Note]

For polyhedral surfaces, only supports 2D polyhedral surfaces (not 2.5D). For 2.5D, may give a non-zero answer, but only for the faces that sit completely in XY plane.

This method is also provided by SFCGAL backend.

Exemples

Return area in square feet for a plot of Massachusetts land and multiply by conversion to get square meters. Note this is in square feet because EPSG:2249 is Massachusetts State Plane Feet

SELECT ST_Area(the_geom) As sqft, ST_Area(the_geom)*POWER(0.3048,2) As sqm
                FROM (SELECT
                ST_GeomFromText('POLYGON((743238 2967416,743238 2967450,
                        743265 2967450,743265.625 2967416,743238 2967416))',2249) ) As foo(the_geom);
  sqft   |     sqm
---------+-------------
 928.625 | 86.27208552

Return area square feet and transform to Massachusetts state plane meters (EPSG:26986) to get square meters. Note this is in square feet because 2249 is Massachusetts State Plane Feet and transformed area is in square meters since EPSG:26986 is state plane Massachusetts meters

SELECT ST_Area(the_geom) As sqft, ST_Area(ST_Transform(the_geom,26986)) As sqm
                FROM (SELECT
                ST_GeomFromText('POLYGON((743238 2967416,743238 2967450,
                        743265 2967450,743265.625 2967416,743238 2967416))',2249) ) As foo(the_geom);
  sqft   |       sqm
---------+------------------
 928.625 | 86.2724304199219
                        

Return area square feet and square meters using geography data type. Note that we transform to our geometry to geography (before you can do that make sure your geometry is in WGS 84 long lat 4326). Geography always measures in meters. This is just for demonstration to compare. Normally your table will be stored in geography data type already.

SELECT ST_Area(the_geog)/POWER(0.3048,2) As sqft_spheroid,  ST_Area(the_geog,false)/POWER(0.3048,2) As sqft_sphere, ST_Area(the_geog) As sqm_spheroid
                FROM (SELECT
                geography(
                ST_Transform(
                        ST_GeomFromText('POLYGON((743238 2967416,743238 2967450,743265 2967450,743265.625 2967416,743238 2967416))',
                                2249
                                ) ,4326
                        )
                )
        ) As foo(the_geog);
  sqft_spheroid   |   sqft_sphere    |   sqm_spheroid
------------------+------------------+------------------
 928.684403538925 | 927.049336105925 | 86.2776042893529

 --if your data is in geography already
 SELECT ST_Area(the_geog)/POWER(0.3048,2) As  sqft, ST_Area(the_geog) As sqm
        FROM somegeogtable;

Voir également

???, ???, ST_SetSRID, ST_Transform


Name

ST_Azimuth — Returns the north-based azimuth as the angle in radians measured clockwise from the vertical on pointA to pointB.

Synopsis

float ST_Azimuth(geometry pointA, geometry pointB);

float ST_Azimuth(geography pointA, geography pointB);

Description

Returns the azimuth in radians of the segment defined by the given point geometries, or NULL if the two points are coincident. The azimuth is angle is referenced from north, and is positive clockwise: North = 0; East = π/2; South = π; West = 3π/2.

For the geography type, the forward azimuth is solved as part of the inverse geodesic problem.

The azimuth is mathematical concept defined as the angle between a reference plane and a point, with angular units in radians. Units can be converted to degrees using a built-in PostgreSQL function degrees(), as shown in the example.

Availability: 1.1.0

Enhanced: 2.0.0 support for geography was introduced.

Enhanced: 2.2.0 measurement on spheroid performed with GeographicLib for improved accuracy and robustness. Requires Proj >= 4.9.0 to take advantage of the new feature.

Azimuth is especially useful in conjunction with ST_Translate for shifting an object along its perpendicular axis. See upgis_lineshift Plpgsqlfunctions PostGIS wiki section for example of this.

Exemples

Geometry Azimuth in degrees

SELECT degrees(ST_Azimuth(ST_Point(25, 45), ST_Point(75, 100))) AS degA_B,
            degrees(ST_Azimuth(ST_Point(75, 100), ST_Point(25, 45))) AS degB_A;

      dega_b       |     degb_a
------------------+------------------
 42.2736890060937 | 222.273689006094

Green: the start Point(25,45) with its vertical. Yellow: degA_B as the path to travel (azimuth).

Green: the start Point(75,100) with its vertical. Yellow: degB_A as the path to travel (azimuth).


Name

ST_Centroid — Returns the geometric center of a geometry.

Synopsis

geometry ST_Centroid(geometry g1);

Description

Computes the geometric center of a geometry, or equivalently, the center of mass of the geometry as a POINT. For [MULTI]POINTs, this is computed as the arithmetic mean of the input coordinates. For [MULTI]LINESTRINGs, this is computed as the weighted length of each line segment. For [MULTI]POLYGONs, "weight" is thought in terms of area. If an empty geometry is supplied, an empty GEOMETRYCOLLECTION is returned. If NULL is supplied, NULL is returned. If CIRCULARSTRING or COMPOUNDCURVE are supplied, they are converted to linestring wtih CurveToLine first, then same than for LINESTRING

New in 2.3.0 : support CIRCULARSTRING and COMPOUNDCURVE (using CurveToLine)

The centroid is equal to the centroid of the set of component Geometries of highest dimension (since the lower-dimension geometries contribute zero "weight" to the centroid).

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

This method implements the SQL/MM specification. SQL-MM 3: 8.1.4, 9.5.5

Exemples

In each of the following illustrations, the green dot represents the centroid of the source geometry.

Centroid of a MULTIPOINT

Centroid of a LINESTRING

Centroid of a POLYGON

Centroid of a GEOMETRYCOLLECTION

SELECT ST_AsText(ST_Centroid('MULTIPOINT ( -1 0, -1 2, -1 3, -1 4, -1 7, 0 1, 0 3, 1 1, 2 0, 6 0, 7 8, 9 8, 10 6 )'));
                                st_astext
------------------------------------------
 POINT(2.30769230769231 3.30769230769231)
(1 row)

SELECT ST_AsText(ST_centroid(g))
FROM  ST_GeomFromText('CIRCULARSTRING(0 2, -1 1,0 0, 0.5 0, 1 0, 2 1, 1 2, 0.5 2, 0 2)')  AS g ;
------------------------------------------
POINT(0.5 1)


SELECT ST_AsText(ST_centroid(g))
FROM  ST_GeomFromText('COMPOUNDCURVE(CIRCULARSTRING(0 2, -1 1,0 0),(0 0, 0.5 0, 1 0),CIRCULARSTRING( 1 0, 2 1, 1 2),(1 2, 0.5 2, 0 2))' ) AS g;
------------------------------------------
POINT(0.5 1)

Voir également

ST_PointOnSurface


Name

ST_ClosestPoint — Returns the 2-dimensional point on g1 that is closest to g2. This is the first point of the shortest line.

Synopsis

geometry ST_ClosestPoint(geometry g1, geometry g2);

Description

Returns the 2-dimensional point on g1 that is closest to g2. This is the first point of the shortest line.

[Note]

If you have a 3D Geometry, you may prefer to use ST_3DClosestPoint.

Availability: 1.5.0

Exemples

Closest between point and linestring is the point itself, but closest point between a linestring and point is the point on line string that is closest.

SELECT ST_AsText(ST_ClosestPoint(pt,line)) AS cp_pt_line, 
        ST_AsText(ST_ClosestPoint(line,pt)) As cp_line_pt
FROM (SELECT 'POINT(100 100)'::geometry As pt, 
                'LINESTRING (20 80, 98 190, 110 180, 50 75 )'::geometry As line
        ) As foo;

        
   cp_pt_line   |                cp_line_pt
----------------+------------------------------------------
 POINT(100 100) | POINT(73.0769230769231 115.384615384615)
                                

closest point on polygon A to polygon B

SELECT ST_AsText(
                ST_ClosestPoint(
                        ST_GeomFromText('POLYGON((175 150, 20 40, 50 60, 125 100, 175 150))'),
                        ST_Buffer(ST_GeomFromText('POINT(110 170)'), 20)
                        ) 
                ) As ptwkt;
                
                  ptwkt
------------------------------------------
 POINT(140.752120669087 125.695053378061)
                                


Name

ST_ClusterDBSCAN — Windowing function that returns integer id for the cluster each input geometry is in based on 2D implementation of Density-based spatial clustering of applications with noise (DBSCAN) algorithm.

Synopsis

boolean ST_DFullyWithin(geometry g1, geometry g2, double precision distance);

Description

Returns cluster number for each input geometry, based on a 2D implementation of the Density-based spatial clustering of applications with noise (DBSCAN) algorithm. Unlike ST_ClusterKMeans, it does not require the number of clusters to be specified, but instead uses the desired distance (eps) and density(minpoints) parameters to construct each cluster.

An input geometry will be added to a cluster if it is either:

  • A "core" geometry, that is within eps distance of at least minpoints input geometries (including itself) or

  • A "border" geometry, that is within eps distance of a core geometry.

Note that border geometries may be within eps distance of core geometries in more than one cluster; in this case, either assignment would be correct, and the border geometry will be arbitrarily asssigned to one of the available clusters. In these cases, it is possible for a correct cluster to be generated with fewer than minpoints geometries. When assignment of a border geometry is ambiguous, repeated calls to ST_ClusterDBSCAN will produce identical results if an ORDER BY clause is included in the window definition, but cluster assignments may differ from other implementations of the same algorithm.

[Note]

Input geometries that do not meet the criteria to join any other cluster will be assigned a cluster number of NULL.

Disponibilité: 2.0.0

Exemples

Assigning a cluster number to each parcel point:

SELECT parcel_id, ST_ClusterDBSCAN(geom, eps := 0.5, minpoints := 5) over () AS cid
FROM parcels;

Combining parcels with the same cluster number into a single geometry. This uses named argument calling

SELECT cid, ST_Collect(geom) AS cluster_geom, array_agg(parcel_id) AS ids_in_cluster FROM (
    SELECT parcel_id, ST_ClusterDBSCAN(geom, eps := 0.5, minpoints := 5) over () AS cid, geom
    FROM parcels) sq
GROUP BY cid;
    

Name

ST_3DIntersects — Aggregate. Returns an array with the connected components of a set of geometries

Synopsis

geometry ST_Centroid(geometry g1);

Description

ST_ClusterIntersecting is an aggregate function that returns an array of GeometryCollections, where each GeometryCollection represents an interconnected set of geometries.

Disponibilité: 2.0.0

Exemples

WITH testdata AS
  (SELECT unnest(ARRAY['LINESTRING (0 0, 1 1)'::geometry,
                       'LINESTRING (5 5, 4 4)'::geometry,
                       'LINESTRING (6 6, 7 7)'::geometry,
                       'LINESTRING (0 0, -1 -1)'::geometry,
                       'POLYGON ((0 0, 4 0, 4 4, 0 4, 0 0))'::geometry]) AS geom)

SELECT ST_AsText(unnest(ST_ClusterIntersecting(geom))) FROM testdata;

--result

st_astext
---------
GEOMETRYCOLLECTION(LINESTRING(0 0,1 1),LINESTRING(5 5,4 4),LINESTRING(0 0,-1 -1),POLYGON((0 0,4 0,4 4,0 4,0 0)))
GEOMETRYCOLLECTION(LINESTRING(6 6,7 7))
        

Name

ST_ClusterKMeans — Windowing function that returns integer id for the cluster each input geometry is in.

Synopsis

boolean ST_Contains(geometry geomA, geometry geomB);

Description

Returns 2D distance based k-means cluster number for each input geometry. The distance used for clustering is the distance between the centroids of the geometries.

Disponibilité: 2.0.0

Exemples

Generate dummy set of parcels for examples

CREATE TABLE parcels AS
SELECT lpad((row_number() over())::text,3,'0') As parcel_id, geom,
('{residential, commercial}'::text[])[1 + mod(row_number()OVER(),2)] As type
FROM
    ST_Subdivide(ST_Buffer('LINESTRING(40 100, 98 100, 100 150, 60 90)'::geometry,
    40, 'endcap=square'),12) As geom;

Original Parcels

Parcels color-coded by cluster number (cid)

SELECT ST_ClusterKMeans(geom, 5) OVER() AS cid, parcel_id, geom
FROM parcels;
-- result
 cid | parcel_id |   geom
-----+-----------+---------------
   0 | 001       | 0103000000...
   0 | 002       | 0103000000...
   1 | 003       | 0103000000...
   0 | 004       | 0103000000...
   1 | 005       | 0103000000...
   2 | 006       | 0103000000...
   2 | 007       | 0103000000...
(7 rows)

-- Partitioning parcel clusters by type
SELECT ST_ClusterKMeans(geom,3) over (PARTITION BY type) AS cid, parcel_id, type
FROM parcels;
-- result
 cid | parcel_id |    type
-----+-----------+-------------
   1 | 005       | commercial
   1 | 003       | commercial
   2 | 007       | commercial
   0 | 001       | commercial
   1 | 004       | residential
   0 | 002       | residential
   2 | 006       | residential
(7 rows)

Name

ST_DWithin — Aggregate. Returns an array of GeometryCollections, where each GeometryCollection represents a set of geometries separated by no more than the specified distance.

Synopsis

geometry ST_ClosestPoint(geometry g1, geometry g2);

Description

ST_ClusterWithin is an aggregate function that returns an array of GeometryCollections, where each GeometryCollection represents a set of geometries separated by no more than the specified distance.

Disponibilité: 2.0.0

Exemples

WITH testdata AS
  (SELECT unnest(ARRAY['LINESTRING (0 0, 1 1)'::geometry,
                       'LINESTRING (5 5, 4 4)'::geometry,
                       'LINESTRING (6 6, 7 7)'::geometry,
                       'LINESTRING (0 0, -1 -1)'::geometry,
                       'POLYGON ((0 0, 4 0, 4 4, 0 4, 0 0))'::geometry]) AS geom)

SELECT ST_AsText(unnest(ST_ClusterWithin(geom, 1.4))) FROM testdata;

--result

st_astext
---------
GEOMETRYCOLLECTION(LINESTRING(0 0,1 1),LINESTRING(5 5,4 4),LINESTRING(0 0,-1 -1),POLYGON((0 0,4 0,4 4,0 4,0 0)))
GEOMETRYCOLLECTION(LINESTRING(6 6,7 7))
        

Name

ST_Contains — Returns true if and only if no points of B lie in the exterior of A, and at least one point of the interior of B lies in the interior of A.

Synopsis

boolean ST_Contains(geometry geomA, geometry geomB);

Description

Geometry A contains Geometry B if and only if no points of B lie in the exterior of A, and at least one point of the interior of B lies in the interior of A. An important subtlety of this definition is that A does not contain its boundary, but A does contain itself. Contrast that to ST_ContainsProperly where geometry A does not Contain Properly itself.

Returns TRUE if geometry B is completely inside geometry A. For this function to make sense, the source geometries must both be of the same coordinate projection, having the same SRID. ST_Contains is the inverse of ST_Within. So ST_Contains(A,B) implies ST_Within(B,A) except in the case of invalid geometries where the result is always false regardless or not defined.

Performed by the GEOS module

Enhanced: 2.3.0 Enhancement to PIP short-circuit extended to support MultiPoints with few points. Prior versions only supported point in polygon.

[Important]

Do not call with a GEOMETRYCOLLECTION as an argument

[Important]

Do not use this function with invalid geometries. You will get unexpected results.

This function call will automatically include a bounding box comparison that will make use of any indexes that are available on the geometries. To avoid index use, use the function _ST_Contains.

NOTE: this is the "allowable" version that returns a boolean, not an integer.

This method implements the OpenGIS Simple Features Implementation Specification for SQL 1.1. s2.1.1.2 // s2.1.13.3 - same as within(geometry B, geometry A)

This method implements the SQL/MM specification. SQL-MM 3: 5.1.31

There are certain subtleties to ST_Contains and ST_Within that are not intuitively obvious. For details check out Subtleties of OGC Covers, Contains, Within

Exemples

The ST_Contains predicate returns TRUE in all the following illustrations.

LINESTRING / MULTIPOINT

POLYGON / POINT

POLYGON / LINESTRING

POLYGON / POLYGON

The ST_Contains predicate returns FALSE in all the following illustrations.

POLYGON / MULTIPOINT

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 — Returns true if B intersects the interior of A but not the boundary (or exterior). A does not contain properly itself, but does contain itself.

Synopsis

boolean ST_ContainsProperly(geometry geomA, geometry geomB);

Description

Returns true if B intersects the interior of A but not the boundary (or exterior).

A does not contain properly itself, but does contain itself.

Every point of the other geometry is a point of this geometry's interior. The DE-9IM Intersection Matrix for the two geometries matches [T**FF*FF*] used in ST_Relate

[Note]

From JTS docs slightly reworded: The advantage to using this predicate over ST_Contains and ST_Intersects is that it can be computed efficiently, with no need to compute topology at individual points.

An example use case 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 wholly inside the area. In these cases the intersection is known a priori to be exactly the original test geometry.

Availability: 1.4.0 - requires GEOS >= 3.1.0.

[Important]

Do not call with a GEOMETRYCOLLECTION as an argument

[Important]

Do not use this function with invalid geometries. You will get unexpected results.

This function call will automatically include a bounding box comparison that will make use of any indexes that are available on the geometries. To avoid index use, use the function _ST_ContainsProperly.

Exemples

--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_Covers — Returns 1 (TRUE) if no point in Geometry B is outside Geometry A

Synopsis

boolean ST_Covers(geometry geomA, geometry geomB);

boolean ST_Covers(geography geogpolyA, geography geogpointB);

Description

Returns 1 (TRUE) if no point in Geometry/Geography B is outside Geometry/Geography A

Performed by the GEOS module

[Important]

Do not call with a GEOMETRYCOLLECTION as an argument

[Important]

For geography only Polygon covers point is supported.

[Important]

Do not use this function with invalid geometries. You will get unexpected results.

This function call will automatically include a bounding box comparison that will make use of any indexes that are available on the geometries. To avoid index use, use the function _ST_Covers.

Enhanced: 2.3.0 Enhancement to PIP short-circuit for geometry extended to support MultiPoints with few points. Prior versions only supported point in polygon.

Availability: 1.5 - support for geography was introduced.

Availability: 1.2.2 - requires GEOS >= 3.0

NOTE: this is the "allowable" version that returns a boolean, not an integer.

Not an OGC standard, but Oracle has it too.

There are certain subtleties to ST_Contains and ST_Within that are not intuitively obvious. For details check out Subtleties of OGC Covers, Contains, Within

Exemples

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_CoveredBy — Returns 1 (TRUE) if no point in Geometry/Geography A is outside Geometry/Geography B

Synopsis

boolean ST_CoveredBy(geometry geomA, geometry geomB);

boolean ST_CoveredBy(geography geogA, geography geogB);

Description

Returns 1 (TRUE) if no point in Geometry/Geography A is outside Geometry/Geography B

Performed by the GEOS module

[Important]

Do not call with a GEOMETRYCOLLECTION as an argument

[Important]

Do not use this function with invalid geometries. You will get unexpected results.

Availability: 1.2.2 - requires GEOS >= 3.0

This function call will automatically include a bounding box comparison that will make use of any indexes that are available on the geometries. To avoid index use, use the function _ST_CoveredBy.

NOTE: this is the "allowable" version that returns a boolean, not an integer.

Not an OGC standard, but Oracle has it too.

There are certain subtleties to ST_Contains and ST_Within that are not intuitively obvious. For details check out Subtleties of OGC Covers, Contains, Within

Exemples

--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_Crosses — Returns TRUE if the supplied geometries have some, but not all, interior points in common.

Synopsis

boolean ST_Crosses(geometry g1, geometry g2);

Description

ST_Crosses takes two geometry objects and returns TRUE if their intersection "spatially cross", that is, the geometries have some, but not all interior points in common. The intersection of the interiors of the geometries must not be the empty set and must have a dimensionality less than the maximum dimension of the two input geometries. Additionally, the intersection of the two geometries must not equal either of the source geometries. Otherwise, it returns FALSE.

In mathematical terms, this is expressed as:

TODO: Insert appropriate MathML markup here or use a gif. Simple HTML markup does not work well in both IE and Firefox.

The DE-9IM Intersection Matrix for the two geometries is:

  • T*T****** (for Point/Line, Point/Area, and Line/Area situations)

  • T*****T** (for Line/Point, Area/Point, and Area/Line situations)

  • 0******** (for Line/Line situations)

For any other combination of dimensions this predicate returns false.

The OpenGIS Simple Features Specification defines this predicate only for Point/Line, Point/Area, Line/Line, and Line/Area situations. JTS / GEOS extends the definition to apply to Line/Point, Area/Point and Area/Line situations as well. This makes the relation symmetric.

[Important]

Do not call with a GEOMETRYCOLLECTION as an argument

[Note]

This function call will automatically include a bounding box comparison that will make use of any indexes that are available on the geometries.

This method implements the OpenGIS Simple Features Implementation Specification for SQL 1.1. s2.1.13.3

This method implements the SQL/MM specification. SQL-MM 3: 5.1.29

Exemples

The following illustrations 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,
  the_geom geometry,
  CONSTRAINT roads_pkey PRIMARY KEY (road_id)
);

CREATE TABLE highways (
  id serial NOT NULL,
  the_gem geometry,
  CONSTRAINT roads_pkey PRIMARY KEY (road_id)
);

To determine a list of roads that cross a highway, use a query similiar to:

SELECT roads.id
FROM roads, highways
WHERE ST_Crosses(roads.the_geom, highways.the_geom);

Name

ST_LineCrossingDirection — Given 2 linestrings, returns a number between -3 and 3 denoting what kind of crossing behavior. 0 is no crossing.

Synopsis

integer ST_LineCrossingDirection(geometry linestringA, geometry linestringB);

Description

Given 2 linestrings, returns a number between -3 and 3 denoting what kind of crossing behavior. 0 is no crossing. This is only supported for LINESTRING

Definition of integer constants is as follows:

  • 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

Exemples

Line 1 (green), Line 2 ball is start point, triangle are end points. Query below.

SELECT ST_LineCrossingDirection(foo.line1, foo.line2) As l1_cross_l2 ,
          ST_LineCrossingDirection(foo.line2, foo.line1) As l2_cross_l1
FROM (
SELECT
 ST_GeomFromText('LINESTRING(25 169,89 114,40 70,86 43)') As line1,
 ST_GeomFromText('LINESTRING(171 154,20 140,71 74,161 53)') As line2
        ) As foo;

 l1_cross_l2 | l2_cross_l1
-------------+-------------
           3 |          -3
                                

Line 1 (green), Line 2 (blue) ball is start point, triangle are end points. Query below.

SELECT ST_LineCrossingDirection(foo.line1, foo.line2) As l1_cross_l2 ,
          ST_LineCrossingDirection(foo.line2, foo.line1) As l2_cross_l1
FROM (
 SELECT
  ST_GeomFromText('LINESTRING(25 169,89 114,40 70,86 43)') As line1,
  ST_GeomFromText('LINESTRING (171 154, 20 140, 71 74, 2.99 90.16)') As line2
) As foo;

 l1_cross_l2 | l2_cross_l1
-------------+-------------
           2 |          -2
                                

Line 1 (green), Line 2 (blue) ball is start point, triangle are end points. Query below.

SELECT
        ST_LineCrossingDirection(foo.line1, foo.line2) As l1_cross_l2 ,
        ST_LineCrossingDirection(foo.line2, foo.line1) As l2_cross_l1
FROM (
 SELECT
  ST_GeomFromText('LINESTRING(25 169,89 114,40 70,86 43)') As line1,
  ST_GeomFromText('LINESTRING (20 140, 71 74, 161 53)') As line2
  ) As foo;

 l1_cross_l2 | l2_cross_l1
-------------+-------------
          -1 |          1
                                

Line 1 (green), Line 2 (blue) ball is start point, triangle are end points. Query below.

SELECT ST_LineCrossingDirection(foo.line1, foo.line2) As l1_cross_l2 ,
          ST_LineCrossingDirection(foo.line2, foo.line1) As l2_cross_l1
FROM (SELECT
        ST_GeomFromText('LINESTRING(25 169,89 114,40 70,86 43)') As line1,
        ST_GeomFromText('LINESTRING(2.99 90.16,71 74,20 140,171 154)') As line2
        ) As foo;

 l1_cross_l2 | l2_cross_l1
-------------+-------------
          -2 |          2
                                

SELECT s1.gid, s2.gid, ST_LineCrossingDirection(s1.the_geom, s2.the_geom)
        FROM streets s1 CROSS JOIN streets s2 ON (s1.gid != s2.gid AND s1.the_geom && s2.the_geom )
WHERE ST_CrossingDirection(s1.the_geom, s2.the_geom) > 0;

Voir également

ST_Crosses


Name

ST_Disjoint — Returns TRUE if the Geometries do not "spatially intersect" - if they do not share any space together.

Synopsis

boolean ST_Disjoint( geometry A , geometry B );

Description

Overlaps, Touches, Within all imply geometries are not spatially disjoint. If any of the aforementioned returns true, then the geometries are not spatially disjoint. Disjoint implies false for spatial intersection.

[Important]

Do not call with a GEOMETRYCOLLECTION as an argument

Performed by the GEOS module

[Note]

This function call does not use indexes

[Note]

NOTE: this is the "allowable" version that returns a boolean, not an integer.

This method implements the OpenGIS Simple Features Implementation Specification for SQL 1.1. s2.1.1.2 //s2.1.13.3 - a.Relate(b, 'FF*FF****')

This method implements the SQL/MM specification. SQL-MM 3: 5.1.26

Exemples

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)
                

Voir également

ST_IntersectsST_Intersects


Name

ST_Distance — For geometry type Returns the 2D Cartesian distance between two geometries in projected units (based on spatial ref). For geography type defaults to return minimum geodesic distance between two geographies in meters.

Synopsis

float ST_Distance(geometry g1, geometry g2);

float ST_Distance(geography gg1, geography gg2);

float ST_Distance(geography gg1, geography gg2, boolean use_spheroid);

Description

For geometry type returns the minimum 2D Cartesian distance between two geometries in projected units (spatial ref units). For geography type defaults to return the minimum geodesic distance between two geographies in meters. If use_spheroid is false, a faster sphere calculation is used instead of a spheroid.

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

This method implements the SQL/MM specification. SQL-MM 3: 5.1.23

This method supports Circular Strings and Curves

This method is also provided by SFCGAL backend.

Availability: 1.5.0 geography support was introduced in 1.5. Speed improvements for planar to better handle large or many vertex geometries

Enhanced: 2.1.0 improved speed for geography. See Making Geography faster for details.

Enhanced: 2.1.0 - support for curved geometries was introduced.

Enhanced: 2.2.0 - measurement on spheroid performed with GeographicLib for improved accuracy and robustness. Requires Proj >= 4.9.0 to take advantage of the new feature.

Basic Geometry Examples

--Geometry example - units in planar degrees 4326 is WGS 84 long lat unit=degrees
SELECT ST_Distance(
                ST_GeomFromText('POINT(-72.1235 42.3521)',4326),
                ST_GeomFromText('LINESTRING(-72.1260 42.45, -72.123 42.1546)', 4326)
        );
st_distance
-----------------
0.00150567726382282

-- Geometry example - units in meters (SRID: 26986 Massachusetts state plane meters) (most accurate for Massachusetts)
SELECT ST_Distance(
                        ST_Transform(ST_GeomFromText('POINT(-72.1235 42.3521)',4326),26986),
                        ST_Transform(ST_GeomFromText('LINESTRING(-72.1260 42.45, -72.123 42.1546)', 4326),26986)
                );
st_distance
-----------------
123.797937878454

-- Geometry example - units in meters (SRID: 2163 US National Atlas Equal area) (least accurate)
SELECT ST_Distance(
                        ST_Transform(ST_GeomFromText('POINT(-72.1235 42.3521)',4326),2163),
                        ST_Transform(ST_GeomFromText('LINESTRING(-72.1260 42.45, -72.123 42.1546)', 4326),2163)
                );

st_distance
------------------
126.664256056812

Geography Examples

-- same as geometry example but note units in meters - use sphere for slightly faster less accurate
SELECT ST_Distance(gg1, gg2) As spheroid_dist, ST_Distance(gg1, gg2, false) As sphere_dist
FROM (SELECT
        ST_GeogFromText('SRID=4326;POINT(-72.1235 42.3521)') As gg1,
        ST_GeogFromText('SRID=4326;LINESTRING(-72.1260 42.45, -72.123 42.1546)') As gg2
        ) As foo  ;

  spheroid_dist   |   sphere_dist
------------------+------------------
 123.802076746848 | 123.475736916397

Name

ST_MinimumClearance — Returns the minimum clearance of a geometry, a measure of a geometry's robustness.

Synopsis

float ST_Perimeter2D(geometry geomA);

Description

It is not uncommon to have a geometry that, while meeting the criteria for validity according to ST_IsValid (polygons) or ST_IsSimple (lines), would become invalid if one of the vertices moved by a slight distance, as can happen during conversion to text-based formats (such as WKT, KML, GML GeoJSON), or binary formats that do not use double-precision floating point coordinates (MapInfo TAB).

A geometry's "minimum clearance" is the smallest distance by which a vertex of the geometry could be moved to produce an invalid geometry. It can be thought of as a quantitative measure of a geometry's robustness, where increasing values of minimum clearance indicate increasing robustness.

If a geometry has a minimum clearance of e, it can be said that:

  • No two distinct vertices in the geometry are separated by less than e.

  • No vertex is closer than e to a line segement of which it is not an endpoint.

If no minimum clearance exists for a geometry (for example, a single point, or a multipoint whose points are identical), then ST_MinimumClearance will return Infinity.

Availability: 2.3.0 - requires GEOS >= 3.6.0

Exemples

SELECT ST_MinimumClearance('POLYGON ((0 0, 1 0, 1 1, 0.5 3.2e-4, 0 0))');
 st_minimumclearance
---------------------
             0.00032
     

Voir également

ST_MinimumClearanceLine


Name

ST_MinimumClearanceLine — Returns the two-point LineString spanning a geometry's minimum clearance.

Synopsis

geometry ST_PointOnSurface(geometry g1);

Description

Returns the two-point LineString spanning a geometry's minimum clearance. If the geometry does not have a minimum clearance, LINESTRING EMPTY will be returned.

Availability: 2.3.0 - requires GEOS >= 3.6.0

Exemples

SELECT ST_AsText(ST_MinimumClearanceLine('POLYGON ((0 0, 1 0, 1 1, 0.5 3.2e-4, 0 0))'));
st_astext
-------------------------------
LINESTRING(0.5 0.00032,0.5 0)
                  

Voir également

ST_MinimumClearance


Name

ST_HausdorffDistance — Returns the Hausdorff distance between two geometries. Basically a measure of how similar or dissimilar 2 geometries are. Units are in the units of the spatial reference system of the geometries.

Synopsis

float ST_HausdorffDistance(geometry g1, geometry g2);

float ST_HausdorffDistance(geometry g1, geometry g2, float densifyFrac);

Description

Implements algorithm for computing a distance metric which can be thought of as the "Discrete Hausdorff Distance". This is the Hausdorff distance restricted to discrete points for one of the geometries. Wikipedia article on Hausdorff distance Martin Davis note on how Hausdorff Distance calculation was used to prove correctness of the CascadePolygonUnion approach.

When densifyFrac is specified, this function performs a segment densification before computing the discrete hausdorff distance. The densifyFrac parameter sets the fraction by which to densify each segment. Each segment will be split into a number of equal-length subsegments, whose fraction of the total length is closest to the given fraction.

[Note]

The current implementation supports only vertices as the discrete locations. This could be extended to allow an arbitrary density of points to be used.

[Note]

This algorithm is NOT equivalent to the standard Hausdorff distance. However, it computes an approximation that is correct for a large subset of useful cases. One important part of this subset is Linestrings that are roughly parallel to each other, and roughly equal in length. This is a useful metric for line matching.

Availability: 1.5.0 - requires GEOS >= 3.2.0

Exemples

For each building, find the parcel that best represents it. First we require the parcel intersect with the geometry. DISTINCT ON guarantees we get each building listed only once, the ORDER BY .. ST_HausdorffDistance gives us a preference of parcel that is most similar to the building.

SELECT DISTINCT ON(buildings.gid) buildings.gid, parcels.parcel_id
   FROM buildings INNER JOIN parcels ON ST_Intersects(buildings.geom,parcels.geom)
     ORDER BY buildings.gid, ST_HausdorffDistance(buildings.geom, parcels.geom);
postgis=# SELECT ST_HausdorffDistance(
                                'LINESTRING (0 0, 2 0)'::geometry,
                                'MULTIPOINT (0 1, 1 0, 2 1)'::geometry);
 st_hausdorffdistance
 ----------------------
                                         1
(1 row)
                        
postgis=# SELECT st_hausdorffdistance('LINESTRING (130 0, 0 0, 0 150)'::geometry, 'LINESTRING (10 10, 10 150, 130 10)'::geometry, 0.5);
 st_hausdorffdistance
 ----------------------
                                        70
(1 row)
                        

Voir également

ST_Distance


Name

ST_Distance — Returns the Fréchet distance between two geometries. This is a measure of similarity between curves that takes into account the location and ordering of the points along the curves. Units are in the units of the spatial reference system of the geometries.

Synopsis

boolean ST_DFullyWithin(geometry g1, geometry g2, double precision distance);

Description

Implements algorithm for computing the Fréchet distance restricted to discrete points for both geometries, based on Computing Discrete Fréchet Distance. The Fréchet distance is a measure of similarity between curves that takes into account the location and ordering of the points along the curves. Therefore it is often better than the Hausdorff distance.

When the optional densifyFrac is specified, this function performs a segment densification before computing the discrete Fréchet distance. The densifyFrac parameter sets the fraction by which to densify each segment. Each segment will be split into a number of equal-length subsegments, whose fraction of the total length is closest to the given fraction.

[Note]

The current implementation supports only vertices as the discrete locations. This could be extended to allow an arbitrary density of points to be used.

[Note]

The smaller densifyFrac we specify, the more acurate Fréchet distance we get. But, the computation time and the memory usage increase with the square of the number of subsegments.

Disponibilité: 2.0.0

Exemples

postgis=# SELECT st_hausdorffdistance('LINESTRING (130 0, 0 0, 0 150)'::geometry, 'LINESTRING (10 10, 10 150, 130 10)'::geometry, 0.5);
 st_hausdorffdistance
 ----------------------
                                        70
(1 row)
                        
postgis=# SELECT st_hausdorffdistance('LINESTRING (130 0, 0 0, 0 150)'::geometry, 'LINESTRING (10 10, 10 150, 130 10)'::geometry, 0.5);
 st_hausdorffdistance
 ----------------------
                                        70
(1 row)
                        

Voir également

ST_HausdorffDistance


Name

ST_MaxDistance — Returns the 2-dimensional largest distance between two geometries in projected units.

Synopsis

float ST_MaxDistance(geometry g1, geometry g2);

Description

[Note]

Returns the 2-dimensional maximum distance between two geometries in projected units. If g1 and g2 is the same geometry the function will return the distance between the two vertices most far from each other in that geometry.

Availability: 1.5.0

Exemples

Basic furthest distance the point is to any part of the line

postgis=# SELECT ST_MaxDistance('POINT(0 0)'::geometry, 'LINESTRING ( 2 0, 0 2 )'::geometry);
   st_maxdistance
-----------------
 2
(1 row)

postgis=# SELECT ST_MaxDistance('POINT(0 0)'::geometry, 'LINESTRING ( 2 2, 2 2 )'::geometry);
  st_maxdistance  
------------------
 2.82842712474619
(1 row)

Name

ST_DistanceSphere — Returns minimum distance in meters between two lon/lat geometries. Uses a spherical earth and radius derived from the spheroid defined by the SRID. Faster than ST_DistanceSpheroid ST_DistanceSpheroid, but less accurate. PostGIS versions prior to 1.5 only implemented for points.

Synopsis

float ST_DistanceSphere(geometry geomlonlatA, geometry geomlonlatB);

Description

Returns minimum distance in meters between two lon/lat points. Uses a spherical earth and radius derived from the spheroid defined by the SRID. Faster than ST_DistanceSpheroid, but less accurate. PostGIS Versions prior to 1.5 only implemented for points.

Availability: 1.5 - support for other geometry types besides points was introduced. Prior versions only work with points.

Changed: 2.2.0 In prior versions this used to be called ST_Distance_Sphere

Exemples

SELECT round(CAST(ST_DistanceSphere(ST_Centroid(the_geom), ST_GeomFromText('POINT(-118 38)',4326)) As numeric),2) As dist_meters,
round(CAST(ST_Distance(ST_Transform(ST_Centroid(the_geom),32611),
                ST_Transform(ST_GeomFromText('POINT(-118 38)', 4326),32611)) As numeric),2) As dist_utm11_meters,
round(CAST(ST_Distance(ST_Centroid(the_geom), ST_GeomFromText('POINT(-118 38)', 4326)) As numeric),5) As dist_degrees,
round(CAST(ST_Distance(ST_Transform(the_geom,32611),
                ST_Transform(ST_GeomFromText('POINT(-118 38)', 4326),32611)) As numeric),2) As min_dist_line_point_meters
FROM
        (SELECT ST_GeomFromText('LINESTRING(-118.584 38.374,-118.583 38.5)', 4326) As the_geom) as foo;
         dist_meters | dist_utm11_meters | dist_degrees | min_dist_line_point_meters
        -------------+-------------------+--------------+----------------------------
                70424.47 |          70438.00 |      0.72900 |                   65871.18

        

Name

ST_DistanceSpheroid — Returns the minimum distance between two lon/lat geometries given a particular spheroid. PostGIS versions prior to 1.5 only support points.

Synopsis

float ST_DistanceSpheroid(geometry geomlonlatA, geometry geomlonlatB, spheroid measurement_spheroid);

Description

Returns minimum distance in meters between two lon/lat geometries given a particular spheroid. See the explanation of spheroids given for ST_LengthSpheroid. PostGIS version prior to 1.5 only support points.

[Note]

This function currently does not look at the SRID of a geometry and will always assume its represented in the coordinates of the passed in spheroid. Prior versions of this function only support points.

Availability: 1.5 - support for other geometry types besides points was introduced. Prior versions only work with points.

Changed: 2.2.0 In prior versions this used to be called ST_Distance_Spheroid

Exemples

SELECT round(CAST(
                ST_DistanceSpheroid(ST_Centroid(the_geom), ST_GeomFromText('POINT(-118 38)',4326), 'SPHEROID["WGS 84",6378137,298.257223563]')
                        As numeric),2) As dist_meters_spheroid,
                round(CAST(ST_DistanceSphere(ST_Centroid(the_geom), ST_GeomFromText('POINT(-118 38)',4326)) As numeric),2) As dist_meters_sphere,
round(CAST(ST_Distance(ST_Transform(ST_Centroid(the_geom),32611),
                ST_Transform(ST_GeomFromText('POINT(-118 38)', 4326),32611)) As numeric),2) As dist_utm11_meters
FROM
        (SELECT ST_GeomFromText('LINESTRING(-118.584 38.374,-118.583 38.5)', 4326) As the_geom) as foo;
 dist_meters_spheroid | dist_meters_sphere | dist_utm11_meters
----------------------+--------------------+-------------------
                         70454.92 |           70424.47 |          70438.00

        

Name

ST_DFullyWithin — Returns true if all of the geometries are within the specified distance of one another

Synopsis

boolean ST_DFullyWithin(geometry g1, geometry g2, double precision distance);

Description

Returns true if the geometries is fully within the specified distance of one another. The distance is specified in units defined by the spatial reference system of the geometries. For this function to make sense, the source geometries must both be of the same coordinate projection, having the same SRID.

[Note]

This function call will automatically include a bounding box comparison that will make use of any indexes that are available on the geometries.

Availability: 1.5.0

Exemples

postgis=# SELECT ST_DFullyWithin(geom_a, geom_b, 10) as DFullyWithin10, ST_DWithin(geom_a, geom_b, 10) as DWithin10, ST_DFullyWithin(geom_a, geom_b, 20) as DFullyWithin20 from 
                (select ST_GeomFromText('POINT(1 1)') as geom_a,ST_GeomFromText('LINESTRING(1 5, 2 7, 1 9, 14 12)') as geom_b) t1;
   
-----------------
 DFullyWithin10 | DWithin10 | DFullyWithin20 |
---------------+----------+---------------+
 f             | t        | t             |  

Voir également

ST_MaxDistance, ST_DWithin


Name

ST_DWithin — Returns true if the geometries are within the specified distance of one another. For geometry units are in those of spatial reference and For geography units are in meters and measurement is defaulted to use_spheroid=true (measure around spheroid), for faster check, use_spheroid=false to measure along sphere.

Synopsis

boolean ST_DWithin(geometry g1, geometry g2, double precision distance_of_srid);

boolean ST_DWithin(geography gg1, geography gg2, double precision distance_meters);

boolean ST_DWithin(geography gg1, geography gg2, double precision distance_meters, boolean use_spheroid);

Description

Returns true if the geometries are within the specified distance of one another.

For Geometries: The distance is specified in units defined by the spatial reference system of the geometries. For this function to make sense, the source geometries must both be of the same coordinate projection, having the same SRID.

For geography units are in meters and measurement is defaulted to use_spheroid=true, for faster check, use_spheroid=false to measure along sphere.

[Note]

This function call will automatically include a bounding box comparison that will make use of any indexes that are available on the geometries.

[Note]

Prior to 1.3, ST_Expand was commonly used in conjunction with && and ST_Distance to achieve the same effect and in pre-1.3.4 this function was basically short-hand for that construct. From 1.3.4, ST_DWithin uses a more short-circuit distance function which should make it more efficient than prior versions for larger buffer regions.

[Note]

Use ST_3DDWithin if you have 3D geometries.

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

Availability: 1.5.0 support for geography was introduced

Enhanced: 2.1.0 improved speed for geography. See Making Geography faster for details.

Enhanced: 2.1.0 support for curved geometries was introduced.

Exemples

--Find the nearest hospital to each school
--that is within 3000 units of the school.
-- We do an ST_DWithin search to utilize indexes to limit our search list
-- that the non-indexable ST_Distance needs to process
--If the units of the spatial reference is meters then units would be meters
SELECT DISTINCT ON (s.gid) s.gid, s.school_name, s.the_geom, h.hospital_name
        FROM schools s
                LEFT JOIN hospitals h ON ST_DWithin(s.the_geom, h.the_geom, 3000)
        ORDER BY s.gid, ST_Distance(s.the_geom, h.the_geom);

--The schools with no close hospitals
--Find all schools with no hospital within 3000 units
--away from the school.  Units is in units of spatial ref (e.g. meters, feet, degrees)
SELECT s.gid, s.school_name
        FROM schools s
                LEFT JOIN hospitals h ON ST_DWithin(s.the_geom, h.the_geom, 3000)
        WHERE h.gid IS NULL;
                          

Voir également

ST_Distance, ST_Expand


Name

ST_Equals — Returns true if the given geometries represent the same geometry. Directionality is ignored.

Synopsis

boolean ST_Equals(geometry A, geometry B);

Description

Returns TRUE if the given Geometries are "spatially equal". Use this for a 'better' answer than '='. Note by spatially equal we mean ST_Within(A,B) = true and ST_Within(B,A) = true and also mean ordering of points can be different but represent the same geometry structure. To verify the order of points is consistent, use ST_OrderingEquals (it must be noted ST_OrderingEquals is a little more stringent than simply verifying order of points are the same).

[Important]

This function will return false if either geometry is invalid except in the case where they are binary equal.

[Important]

Do not call with a GEOMETRYCOLLECTION as an argument.

This method implements the OpenGIS Simple Features Implementation Specification for SQL 1.1. s2.1.1.2

This method implements the SQL/MM specification. SQL-MM 3: 5.1.24

Changed: 2.2.0 Returns true even for invalid geometries if they are binary equal

Exemples

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_GeometricMedian — Returns the geometric median of a MultiPoint.

Synopsis

boolean ST_3DDWithin(geometry g1, geometry g2, double precision distance_of_srid);

Description

Computes the approximate geometric median of a MultiPoint geometry using the Weiszfeld algorithm. The geometric median provides a centrality measure that is less sensitive to outlier points than the centroid. The algorithm will iterate until the distance change between successive iterations is less than the supplied tolerance parameter. If this condition has not been met after max_iterations iterations, the function will produce an error and exit, unless fail_if_not_converged is set to false. If a tolerance value is not provided, a default tolerance value will be calculated based on the extent of the input geometry.

Disponibilité: 2.0.0

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

Exemples

Comparison of the centroid (turquoise point) and geometric median (red point) of a four-point MultiPoint (yellow points).

WITH test AS (
SELECT 'MULTIPOINT((0 0), (1 1), (2 2), (200 200))'::geometry geom)
SELECT
  ST_AsText(ST_Centroid(geom)) centroid,
  ST_AsText(ST_GeometricMedian(geom)) median
FROM test;
      centroid      |                 median
--------------------+----------------------------------------
 POINT(50.75 50.75) | POINT(1.9761550281255 1.9761550281255)
(1 row)
          

Voir également

ST_Centroid


Name

ST_HasArc — Returns true if a geometry or geometry collection contains a circular string

Synopsis

boolean ST_HasArc(geometry geomA);

Description

Returns true if a geometry or geometry collection contains a circular string

Availability: 1.2.3?

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

This method supports Circular Strings and Curves

Exemples

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_Intersects — Returns TRUE if the Geometries/Geography "spatially intersect in 2D" - (share any portion of space) and FALSE if they don't (they are Disjoint). For geography -- tolerance is 0.00001 meters (so any points that close are considered to intersect)

Synopsis

boolean ST_Intersects( geometry geomA , geometry geomB );

boolean ST_Intersects( geography geogA , geography geogB );

Description

If a geometry or geography shares any portion of space then they intersect. For geography -- tolerance is 0.00001 meters (so any points that are close are considered to intersect)

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.

[Important]

Do not call with a GEOMETRYCOLLECTION as an argument for geometry version. The geography version supports GEOMETRYCOLLECTION since its a thin wrapper around distance implementation.

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]

This function call will automatically include a bounding box comparison that will make use of any indexes that are available on the geometries.

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

This method implements the OpenGIS Simple Features Implementation Specification for SQL 1.1. s2.1.1.2 //s2.1.13.3 - ST_Intersects(g1, g2 ) --> Not (ST_Disjoint(g1, g2 ))

This method implements the SQL/MM specification. SQL-MM 3: 5.1.27

This method is also provided by SFCGAL backend.

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)
                

Geography Examples

SELECT ST_Intersects(
                ST_GeographyFromText('SRID=4326;LINESTRING(-43.23456 72.4567,-43.23456 72.4568)'),
                ST_GeographyFromText('SRID=4326;POINT(-43.23456 72.4567772)')
                );

 st_intersects
---------------
t

Name

ST_Length — Returns the 2D length of the geometry if it is a LineString or MultiLineString. geometry are in units of spatial reference and geography are in meters (default spheroid)

Synopsis

float ST_Length(geometry a_2dlinestring);

float ST_Length(geography geog, boolean use_spheroid=true);

Description

For geometry: Returns the 2D Cartesian length of the geometry if it is a LineString, MultiLineString, ST_Curve, ST_MultiCurve. 0 is returned for areal geometries. For areal geometries use ST_Perimeter. For geometry types, units for length measures are specified by the spatial reference system of the geometry.

For geography types, the calculations are performed using the inverse geodesic problem, where length units are in meters. If PostGIS is compiled with PROJ version 4.8.0 or later, the spheroid is specified by the SRID, otherwise it is exclusive to WGS84. If use_spheroid=false, then calculations will approximate a sphere instead of a spheroid.

Currently for geometry this is an alias for ST_Length2D, but this may change to support higher dimensions.

[Warning]

Changed: 2.0.0 Breaking change -- in prior versions applying this to a MULTI/POLYGON of type geography would give you the perimeter of the POLYGON/MULTIPOLYGON. In 2.0.0 this was changed to return 0 to be in line with geometry behavior. Please use ST_Perimeter if you want the perimeter of a polygon

[Note]

For geography measurement defaults spheroid measurement. To use the faster less accurate sphere use ST_Length(gg,false);

This method implements the OpenGIS Simple Features Implementation Specification for SQL 1.1. s2.1.5.1

This method implements the SQL/MM specification. SQL-MM 3: 7.1.2, 9.3.4

Availability: 1.5.0 geography support was introduced in 1.5.

This method is also provided by SFCGAL backend.

Geometry Examples

Return length in feet for line string. Note this is in feet because EPSG:2249 is Massachusetts State Plane Feet

SELECT ST_Length(ST_GeomFromText('LINESTRING(743238 2967416,743238 2967450,743265 2967450,
743265.625 2967416,743238 2967416)',2249));
st_length
---------
 122.630744000095


--Transforming WGS 84 LineString to Massachusetts state plane meters
SELECT ST_Length(
        ST_Transform(
                ST_GeomFromEWKT('SRID=4326;LINESTRING(-72.1260 42.45, -72.1240 42.45666, -72.123 42.1546)'),
                26986
        )
);
st_length
---------
34309.4563576191
                        

Geography Examples

Return length of WGS 84 geography line

-- default calculation is using a sphere rather than spheroid
SELECT ST_Length(the_geog) As length_spheroid,  ST_Length(the_geog,false) As length_sphere
FROM (SELECT ST_GeographyFromText(
'SRID=4326;LINESTRING(-72.1260 42.45, -72.1240 42.45666, -72.123 42.1546)') As the_geog)
 As foo;
 length_spheroid  |  length_sphere
------------------+------------------
 34310.5703627288 | 34346.2060960742
                        

Name

ST_Length2D — Returns the 2-dimensional length of the geometry if it is a linestring or multi-linestring. This is an alias for ST_Length

Synopsis

float ST_Length2D(geometry a_2dlinestring);

Description

Returns the 2-dimensional length of the geometry if it is a linestring or multi-linestring. This is an alias for ST_Length

Voir également

ST_Length, ST_3DLength


Name

ST_3DLength — Returns the 3-dimensional or 2-dimensional length of the geometry if it is a linestring or multi-linestring.

Synopsis

float ST_3DLength(geometry a_3dlinestring);

Description

Returns the 3-dimensional or 2-dimensional length of the geometry if it is a linestring or multi-linestring. For 2-d lines it will just return the 2-d length (same as ST_Length and ST_Length2D)

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

Changed: 2.0.0 In prior versions this used to be called ST_Length3D

Exemples

Return length in feet for a 3D cable. Note this is in feet because EPSG:2249 is Massachusetts State Plane Feet

SELECT ST_3DLength(ST_GeomFromText('LINESTRING(743238 2967416 1,743238 2967450 1,743265 2967450 3,
743265.625 2967416 3,743238 2967416 3)',2249));
ST_3DLength
-----------
122.704716741457
                

Voir également

ST_Length, ST_Length2D


Name

ST_LengthSpheroid — Calculates the 2D or 3D length/perimeter of a geometry on an ellipsoid. This is useful if the coordinates of the geometry are in longitude/latitude and a length is desired without reprojection.

Synopsis

float ST_Length2D_Spheroid(geometry a_linestring, spheroid a_spheroid);

Description

Calculates the length/perimeter of a geometry on an ellipsoid. This is useful if the coordinates of the geometry are in longitude/latitude and a length is desired without reprojection. The ellipsoid is a separate database type and can be constructed as follows:

SPHEROID[<NAME>,<SEMI-MAJOR AXIS>,<INVERSE FLATTENING>]

SPHEROID["GRS_1980",6378137,298.257222101]

Availability: 1.2.2

Changed: 2.2.0 In prior versions this used to be called ST_Length_Spheroid and used to have a ST_3DLength_Spheroid alias

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

Exemples

SELECT ST_LengthSpheroid( geometry_column,
                          'SPHEROID["GRS_1980",6378137,298.257222101]' )
                          FROM geometry_table;

SELECT ST_LengthSpheroid( the_geom, sph_m ) As tot_len,
ST_LengthSpheroid(ST_GeometryN(the_geom,1), sph_m) As len_line1,
ST_LengthSpheroid(ST_GeometryN(the_geom,2), sph_m) As len_line2
                          FROM (SELECT ST_GeomFromText('MULTILINESTRING((-118.584 38.374,-118.583 38.5),
        (-71.05957 42.3589 , -71.061 43))') As the_geom,
CAST('SPHEROID["GRS_1980",6378137,298.257222101]' As spheroid) As sph_m)  as foo;
        tot_len      |    len_line1     |    len_line2
------------------+------------------+------------------
 85204.5207562955 | 13986.8725229309 | 71217.6482333646

 --3D
SELECT ST_LengthSpheroid( the_geom, sph_m ) As tot_len,
ST_LengthSpheroid(ST_GeometryN(the_geom,1), sph_m) As len_line1,
ST_LengthSpheroid(ST_GeometryN(the_geom,2), sph_m) As len_line2
                          FROM (SELECT ST_GeomFromEWKT('MULTILINESTRING((-118.584 38.374 20,-118.583 38.5 30),
        (-71.05957 42.3589 75, -71.061 43 90))') As the_geom,
CAST('SPHEROID["GRS_1980",6378137,298.257222101]' As spheroid) As sph_m)  as foo;

         tot_len      |    len_line1    |    len_line2
------------------+-----------------+------------------
 85204.5259107402 | 13986.876097711 | 71217.6498130292

Voir également

ST_GeometryN, ST_Length


Name

ST_Length2D_Spheroid — Calculates the 2D length/perimeter of a geometry on an ellipsoid. This is useful if the coordinates of the geometry are in longitude/latitude and a length is desired without reprojection.

Synopsis

float ST_Length2D_Spheroid(geometry a_linestring, spheroid a_spheroid);

Description

Calculates the 2D length/perimeter of a geometry on an ellipsoid. This is useful if the coordinates of the geometry are in longitude/latitude and a length is desired without reprojection. The ellipsoid is a separate database type and can be constructed as follows:

SPHEROID[<NAME>,<SEMI-MAJOR AXIS>,<INVERSE FLATTENING>]

SPHEROID["GRS_1980",6378137,298.257222101]

[Note]

This is much like ST_LengthSpheroid except it will ignore the Z ordinate in calculations.

Exemples

SELECT ST_Length2D_Spheroid( geometry_column,
                          'SPHEROID["GRS_1980",6378137,298.257222101]' )
                          FROM geometry_table;

SELECT ST_Length2D_Spheroid( the_geom, sph_m ) As tot_len,
ST_Length2D_Spheroid(ST_GeometryN(the_geom,1), sph_m) As len_line1,
ST_Length2D_Spheroid(ST_GeometryN(the_geom,2), sph_m) As len_line2
                          FROM (SELECT ST_GeomFromText('MULTILINESTRING((-118.584 38.374,-118.583 38.5),
        (-71.05957 42.3589 , -71.061 43))') As the_geom,
CAST('SPHEROID["GRS_1980",6378137,298.257222101]' As spheroid) As sph_m)  as foo;
        tot_len      |    len_line1     |    len_line2
------------------+------------------+------------------
 85204.5207562955 | 13986.8725229309 | 71217.6482333646

 --3D Observe same answer
SELECT ST_Length2D_Spheroid( the_geom, sph_m ) As tot_len,
ST_Length2D_Spheroid(ST_GeometryN(the_geom,1), sph_m) As len_line1,
ST_Length2D_Spheroid(ST_GeometryN(the_geom,2), sph_m) As len_line2
                          FROM (SELECT ST_GeomFromEWKT('MULTILINESTRING((-118.584 38.374 20,-118.583 38.5 30),
        (-71.05957 42.3589 75, -71.061 43 90))') As the_geom,
CAST('SPHEROID["GRS_1980",6378137,298.257222101]' As spheroid) As sph_m)  as foo;

        tot_len      |    len_line1     |    len_line2
------------------+------------------+------------------
 85204.5207562955 | 13986.8725229309 | 71217.6482333646


Name

ST_LongestLine — Returns the 2-dimensional longest line points of two geometries. The function will only return the first longest line if more than one, that the function finds. The line returned will always start in g1 and end in g2. The length of the line this function returns will always be the same as st_maxdistance returns for g1 and g2.

Synopsis

geometry ST_LongestLine(geometry g1, geometry g2);

Description

Returns the 2-dimensional longest line between the points of two geometries.

Availability: 1.5.0

Exemples

Longest line between point and line

SELECT ST_AsText(
        ST_LongestLine('POINT(100 100)'::geometry, 
                'LINESTRING (20 80, 98 190, 110 180, 50 75 )'::geometry)
        ) As lline;

        
   lline
-----------------
LINESTRING(100 100,98 190)
                                

longest line between polygon and polygon

SELECT ST_AsText(
        ST_LongestLine(
                ST_GeomFromText('POLYGON((175 150, 20 40, 
                        50 60, 125 100, 175 150))'),
                ST_Buffer(ST_GeomFromText('POINT(110 170)'), 20)
                ) 
        ) As llinewkt;
                
   lline
-----------------
LINESTRING(20 40,121.111404660392 186.629392246051)
                                

longest straight distance to travel from one part of an elegant city to the other Note the max distance = to the length of the line.

SELECT ST_AsText(ST_LongestLine(c.the_geom, c.the_geom)) As llinewkt, 
        ST_MaxDistance(c.the_geom,c.the_geom) As max_dist, 
        ST_Length(ST_LongestLine(c.the_geom, c.the_geom)) As lenll 
FROM (SELECT ST_BuildArea(ST_Collect(the_geom)) As the_geom
        FROM (SELECT ST_Translate(ST_SnapToGrid(ST_Buffer(ST_Point(50 ,generate_series(50,190, 50) 
                        ),40, 'quad_segs=2'),1), x, 0)  As the_geom 
                        FROM generate_series(1,100,50) As x)  AS foo
) As c;
                
          llinewkt          |     max_dist     |      lenll
---------------------------+------------------+------------------
 LINESTRING(23 22,129 178) | 188.605408193933 | 188.605408193933
                                


Name

ST_OrderingEquals — Returns true if the given geometries represent the same geometry and points are in the same directional order.

Synopsis

boolean ST_OrderingEquals(geometry A, geometry B);

Description

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

This method implements the SQL/MM specification. SQL-MM 3: 5.1.43

Exemples

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)

Voir également

ST_Equals, ST_Reverse


Name

ST_Overlaps — Returns TRUE if the Geometries share space, are of the same dimension, but are not completely contained by each other.

Synopsis

boolean ST_Overlaps(geometry A, geometry B);

Description

Returns TRUE if the Geometries "spatially overlap". By that we mean they intersect, but one does not completely contain another.

Performed by the GEOS module

[Note]

Do not call with a GeometryCollection as an argument

This function call will automatically include a bounding box comparison that will make use of any indexes that are available on the geometries. To avoid index use, use the function _ST_Overlaps.

NOTE: this is the "allowable" version that returns a boolean, not an integer.

This method implements the OpenGIS Simple Features Implementation Specification for SQL 1.1. s2.1.1.2 // s2.1.13.3

This method implements the SQL/MM specification. SQL-MM 3: 5.1.32

Exemples

The following illustrations all return TRUE.

MULTIPOINT / MULTIPOINT

LINESTRING / LINESTRING

POLYGON / POLYGON

--a point on a line is contained by the line and is of a lower dimension, and therefore does not overlap the line
                        nor crosses

SELECT ST_Overlaps(a,b) As a_overlap_b,
        ST_Crosses(a,b) As a_crosses_b,
                ST_Intersects(a, b) As a_intersects_b, ST_Contains(b,a) As b_contains_a
FROM (SELECT ST_GeomFromText('POINT(1 0.5)') As a, ST_GeomFromText('LINESTRING(1 0, 1 1, 3 5)')  As b)
        As foo

a_overlap_b | a_crosses_b | a_intersects_b | b_contains_a
------------+-------------+----------------+--------------
f           | f           | t              | t

--a line that is partly contained by circle, but not fully is defined as intersecting and crossing,
-- but since of different dimension it does not overlap
SELECT ST_Overlaps(a,b) As a_overlap_b, ST_Crosses(a,b) As a_crosses_b,
        ST_Intersects(a, b) As a_intersects_b,
        ST_Contains(a,b) As a_contains_b
FROM (SELECT ST_Buffer(ST_GeomFromText('POINT(1 0.5)'), 3)  As a, ST_GeomFromText('LINESTRING(1 0, 1 1, 3 5)')  As b)
        As foo;

 a_overlap_b | a_crosses_b | a_intersects_b | a_contains_b
-------------+-------------+----------------+--------------
 f           | t           | t              | f

 -- a 2-dimensional bent hot dog (aka buffered line string) that intersects a circle,
 --        but is not fully contained by the circle is defined as overlapping since they are of the same dimension,
--        but it does not cross, because the intersection of the 2 is of the same dimension
--        as the maximum dimension of the 2

SELECT ST_Overlaps(a,b) As a_overlap_b, ST_Crosses(a,b) As a_crosses_b, ST_Intersects(a, b) As a_intersects_b,
ST_Contains(b,a) As b_contains_a,
ST_Dimension(a) As dim_a, ST_Dimension(b) as dim_b, ST_Dimension(ST_Intersection(a,b)) As dima_intersection_b
FROM (SELECT ST_Buffer(ST_GeomFromText('POINT(1 0.5)'), 3)  As a,
        ST_Buffer(ST_GeomFromText('LINESTRING(1 0, 1 1, 3 5)'),0.5)  As b)
        As foo;

 a_overlap_b | a_crosses_b | a_intersects_b | b_contains_a | dim_a | dim_b | dima_intersection_b
-------------+-------------+----------------+--------------+-------+-------+---------------------
 t           | f           | t              | f            |     2 |     2 |              2

Name

ST_Perimeter — Return the length measurement of the boundary of an ST_Surface or ST_MultiSurface geometry or geography. (Polygon, MultiPolygon). geometry measurement is in units of spatial reference and geography is in meters.

Synopsis

float ST_Perimeter(geometry g1);

float ST_Perimeter(geography geog, boolean use_spheroid=true);

Description

Returns the 2D perimeter of the geometry/geography if it is a ST_Surface, ST_MultiSurface (Polygon, MultiPolygon). 0 is returned for non-areal geometries. For linear geometries use ST_Length. For geometry types, units for perimeter measures are specified by the spatial reference system of the geometry.

For geography types, the calculations are performed using the inverse geodesic problem, where perimeter units are in meters. If PostGIS is compiled with PROJ version 4.8.0 or later, the spheroid is specified by the SRID, otherwise it is exclusive to WGS84. If use_spheroid=false, then calculations will approximate a sphere instead of a spheroid.

Currently this is an alias for ST_Perimeter2D, but this may change to support higher dimensions.

This method implements the OpenGIS Simple Features Implementation Specification for SQL 1.1. s2.1.5.1

This method implements the SQL/MM specification. SQL-MM 3: 8.1.3, 9.5.4

Availability 2.0.0: Support for geography was introduced

Examples: Geometry

Return perimeter in feet for Polygon and MultiPolygon. Note this is in feet because EPSG:2249 is Massachusetts State Plane Feet

SELECT ST_Perimeter(ST_GeomFromText('POLYGON((743238 2967416,743238 2967450,743265 2967450,
743265.625 2967416,743238 2967416))', 2249));
st_perimeter
---------
 122.630744000095
(1 row)

SELECT ST_Perimeter(ST_GeomFromText('MULTIPOLYGON(((763104.471273676 2949418.44119003,
763104.477769673 2949418.42538203,
763104.189609677 2949418.22343004,763104.471273676 2949418.44119003)),
((763104.471273676 2949418.44119003,763095.804579742 2949436.33850239,
763086.132105649 2949451.46730207,763078.452329651 2949462.11549407,
763075.354136904 2949466.17407812,763064.362142565 2949477.64291974,
763059.953961626 2949481.28983009,762994.637609571 2949532.04103014,
762990.568508415 2949535.06640477,762986.710889563 2949539.61421415,
763117.237897679 2949709.50493431,763235.236617789 2949617.95619822,
763287.718121842 2949562.20592617,763111.553321674 2949423.91664605,
763104.471273676 2949418.44119003)))', 2249));
st_perimeter
---------
 845.227713366825
(1 row)
                        

Examples: Geography

Return perimeter in meters and feet for Polygon and MultiPolygon. Note this is geography (WGS 84 long lat)

SELECT  ST_Perimeter(geog) As per_meters, ST_Perimeter(geog)/0.3048 As per_ft
FROM ST_GeogFromText('POLYGON((-71.1776848522251 42.3902896512902,-71.1776843766326 42.3903829478009,
-71.1775844305465 42.3903826677917,-71.1775825927231 42.3902893647987,-71.1776848522251 42.3902896512902))') As geog;

   per_meters    |      per_ft
-----------------+------------------
37.3790462565251 | 122.634666195949


-- MultiPolygon example --
SELECT  ST_Perimeter(geog) As per_meters, ST_Perimeter(geog,false) As per_sphere_meters,  ST_Perimeter(geog)/0.3048 As per_ft
FROM ST_GeogFromText('MULTIPOLYGON(((-71.1044543107478 42.340674480411,-71.1044542869917 42.3406744369506,
-71.1044553562977 42.340673886454,-71.1044543107478 42.340674480411)),
((-71.1044543107478 42.340674480411,-71.1044860600303 42.3407237015564,-71.1045215770124 42.3407653385914,
-71.1045498002983 42.3407946553165,-71.1045611902745 42.3408058316308,-71.1046016507427 42.340837442371,
-71.104617893173 42.3408475056957,-71.1048586153981 42.3409875993595,-71.1048736143677 42.3409959528211,
-71.1048878050242 42.3410084812078,-71.1044020965803 42.3414730072048,
-71.1039672113619 42.3412202916693,-71.1037740497748 42.3410666421308,
-71.1044280218456 42.3406894151355,-71.1044543107478 42.340674480411)))') As geog;

    per_meters    | per_sphere_meters |      per_ft
------------------+-------------------+------------------
 257.634283683311 |  257.412311446337 | 845.256836231335
                        

Voir également

???, ???, ST_Length


Name

ST_Perimeter2D — Returns the 2-dimensional perimeter of the geometry, if it is a polygon or multi-polygon. This is currently an alias for ST_Perimeter.

Synopsis

float ST_Perimeter2D(geometry geomA);

Description

Returns the 2-dimensional perimeter of the geometry, if it is a polygon or multi-polygon.

[Note]

This is currently an alias for ST_Perimeter. In future versions ST_Perimeter may return the highest dimension perimeter for a geometry. This is still under consideration

Voir également

ST_Perimeter


Name

ST_3DPerimeter — Returns the 3-dimensional perimeter of the geometry, if it is a polygon or multi-polygon.

Synopsis

float ST_3DPerimeter(geometry geomA);

Description

Returns the 3-dimensional perimeter of the geometry, if it is a polygon or multi-polygon. If the geometry is 2-dimensional, then the 2-dimensional perimeter is returned.

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

Changed: 2.0.0 In prior versions this used to be called ST_Perimeter3D

Exemples

Perimeter of a slightly elevated polygon in the air in Massachusetts state plane feet

SELECT ST_3DPerimeter(the_geom), ST_Perimeter2d(the_geom), ST_Perimeter(the_geom) FROM
                        (SELECT ST_GeomFromEWKT('SRID=2249;POLYGON((743238 2967416 2,743238 2967450 1,
743265.625 2967416 1,743238 2967416 2))') As the_geom) As foo;

  ST_3DPerimeter  |  st_perimeter2d  |   st_perimeter
------------------+------------------+------------------
 105.465793597674 | 105.432997272188 | 105.432997272188


Name

ST_PointOnSurface — Returns a POINT guaranteed to lie on the surface.

Synopsis

geometry ST_PointOnSurface(geometry g1);

Description

Returns a POINT guaranteed to intersect a surface.

This method implements the OpenGIS Simple Features Implementation Specification for SQL 1.1. s3.2.14.2 // s3.2.18.2

This method implements the SQL/MM specification. SQL-MM 3: 8.1.5, 9.5.6. According to the specs, ST_PointOnSurface works for surface geometries (POLYGONs, MULTIPOLYGONS, CURVED POLYGONS). So PostGIS seems to be extending what the spec allows here. Most databases Oracle,DB II, ESRI SDE seem to only support this function for surfaces. SQL Server 2008 like PostGIS supports for all common geometries.

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

Exemples

SELECT ST_AsText(ST_PointOnSurface('POINT(0 5)'::geometry));
 st_astext
------------
 POINT(0 5)
(1 row)

SELECT ST_AsText(ST_PointOnSurface('LINESTRING(0 5, 0 10)'::geometry));
 st_astext
------------
 POINT(0 5)
(1 row)

SELECT ST_AsText(ST_PointOnSurface('POLYGON((0 0, 0 5, 5 5, 5 0, 0 0))'::geometry));
   st_astext
----------------
 POINT(2.5 2.5)
(1 row)

SELECT ST_AsEWKT(ST_PointOnSurface(ST_GeomFromEWKT('LINESTRING(0 5 1, 0 0 1, 0 10 2)')));
   st_asewkt
----------------
 POINT(0 0 1)
(1 row)

Name

ST_Project — Returns a POINT projected from a start point using a distance in meters and bearing (azimuth) in radians.

Synopsis

geography ST_Project(geography g1, float distance, float azimuth);

Description

Returns a POINT projected along a geodesic from a start point using an azimuth (bearing) measured in radians and distance measured in meters. This is also called a direct geodesic problem.

The azimuth is sometimes called the heading or the bearing in navigation. It is measured relative to true north (azimuth zero). East is azimuth 90 (π/2), south is azimuth 180 (π), west is azimuth 270 (3π/2).

The distance is given in meters.

Disponibilité: 2.0.0

Example: Using degrees - projected point 100,000 meters and bearing 45 degrees

SELECT ST_AsText(ST_Project('POINT(0 0)'::geography, 100000, radians(45.0)));

                 st_astext
--------------------------------------------
 POINT(0.635231029125537 0.639472334729198)
(1 row)
      

Name

ST_Relate — Returns true if this Geometry is spatially related to anotherGeometry, by testing for intersections between the Interior, Boundary and Exterior of the two geometries as specified by the values in the intersectionMatrixPattern. If no intersectionMatrixPattern is passed in, then returns the maximum intersectionMatrixPattern that relates the 2 geometries.

Synopsis

boolean ST_Relate(geometry geomA, geometry geomB, text intersectionMatrixPattern);

text ST_Relate(geometry geomA, geometry geomB);

text ST_Relate(geometry geomA, geometry geomB, integer BoundaryNodeRule);

Description

Version 1: Takes geomA, geomB, intersectionMatrix and Returns 1 (TRUE) if this Geometry is spatially related to anotherGeometry, by testing for intersections between the Interior, Boundary and Exterior of the two geometries as specified by the values in the DE-9IM matrix pattern.

This is especially useful for testing compound checks of intersection, crosses, etc in one step.

Do not call with a GeometryCollection as an argument

[Note]

This is the "allowable" version that returns a boolean, not an integer. This is defined in OGC spec

[Note]

This DOES NOT automagically include an index call. The reason for that is some relationships are anti e.g. Disjoint. If you are using a relationship pattern that requires intersection, then include the && index call.

Version 2: Takes geomA and geomB and returns the Section 4.3.6, “Dimensionally Extended 9 Intersection Model (DE-9IM)”

Version 3: same as version 2, but allows to specify a boundary node rule (1:OGC/MOD2, 2:Endpoint, 3:MultivalentEndpoint, 4:MonovalentEndpoint)

[Note]

Do not call with a GeometryCollection as an argument

not in OGC spec, but implied. see s2.1.13.2

Performed by the GEOS module

This method implements the OpenGIS Simple Features Implementation Specification for SQL 1.1. s2.1.1.2 // s2.1.13.3

This method implements the SQL/MM specification. SQL-MM 3: 5.1.25

Enhanced: 2.0.0 - added support for specifying boundary node rule (requires GEOS >= 3.0).

Exemples

--Find all compounds that intersect and not touch a poly (interior intersects)
SELECT l.* , b.name As poly_name
        FROM polys As b
INNER JOIN compounds As l
ON (p.the_geom && b.the_geom
AND ST_Relate(l.the_geom, b.the_geom,'T********'));

SELECT ST_Relate(ST_GeometryFromText('POINT(1 2)'), ST_Buffer(ST_GeometryFromText('POINT(1 2)'),2));
st_relate
-----------
0FFFFF212

SELECT ST_Relate(ST_GeometryFromText('LINESTRING(1 2, 3 4)'), ST_GeometryFromText('LINESTRING(5 6, 7 8)'));
st_relate
-----------
FF1FF0102


SELECT ST_Relate(ST_GeometryFromText('POINT(1 2)'), ST_Buffer(ST_GeometryFromText('POINT(1 2)'),2), '0FFFFF212');
st_relate
-----------
t

SELECT ST_Relate(ST_GeometryFromText('POINT(1 2)'), ST_Buffer(ST_GeometryFromText('POINT(1 2)'),2), '*FF*FF212');
st_relate
-----------
t
                

Name

ST_RelateMatch — Returns true if intersectionMattrixPattern1 implies intersectionMatrixPattern2

Synopsis

boolean ST_RelateMatch(text intersectionMatrix, text intersectionMatrixPattern);

Description

Takes intersectionMatrix and intersectionMatrixPattern and Returns true if the intersectionMatrix satisfies the intersectionMatrixPattern. For more information refer to Section 4.3.6, “Dimensionally Extended 9 Intersection Model (DE-9IM)”.

Availability: 2.0.0 - requires GEOS >= 3.3.0.

Exemples

SELECT ST_RelateMatch('101202FFF', 'TTTTTTFFF') ;
-- result --
t
--example of common intersection matrix patterns and example matrices
-- comparing relationships of involving one invalid geometry and ( a line and polygon that intersect at interior and boundary)
SELECT mat.name, pat.name, ST_RelateMatch(mat.val, pat.val) As satisfied
    FROM
        ( VALUES ('Equality', 'T1FF1FFF1'),
                ('Overlaps', 'T*T***T**'),
                ('Within', 'T*F**F***'),
                ('Disjoint', 'FF*FF****') As pat(name,val)
        CROSS JOIN
            (        VALUES ('Self intersections (invalid)', '111111111'),
                    ('IE2_BI1_BB0_BE1_EI1_EE2', 'FF2101102'),
                    ('IB1_IE1_BB0_BE0_EI2_EI1_EE2', 'F11F00212')
            ) As mat(name,val);

                

Name

ST_ShortestLine — Returns the 2-dimensional shortest line between two geometries

Synopsis

geometry ST_ShortestLine(geometry g1, geometry g2);

Description

Returns the 2-dimensional shortest line between two geometries. The function will only return the first shortest line if more than one, that the function finds. If g1 and g2 intersects in just one point the function will return a line with both start and end in that intersection-point. If g1 and g2 are intersecting with more than one point the function will return a line with start and end in the same point but it can be any of the intersecting points. The line returned will always start in g1 and end in g2. The length of the line this function returns will always be the same as ST_Distance returns for g1 and g2.

Availability: 1.5.0

Exemples

Shortest line between point and linestring

SELECT ST_AsText(
        ST_LongestLine('POINT(100 100)'::geometry, 
                'LINESTRING (20 80, 98 190, 110 180, 50 75 )'::geometry)
        ) As lline;

        
   lline
-----------------
LINESTRING(100 100,98 190)
                                

shortest line between polygon and polygon

SELECT ST_AsText(
                ST_ClosestPoint(
                        ST_GeomFromText('POLYGON((175 150, 20 40, 50 60, 125 100, 175 150))'),
                        ST_Buffer(ST_GeomFromText('POINT(110 170)'), 20)
                        ) 
                ) As ptwkt;
                
                  ptwkt
------------------------------------------
 POINT(140.752120669087 125.695053378061)
                                


Name

ST_Touches — Returns TRUE if the geometries have at least one point in common, but their interiors do not intersect.

Synopsis

boolean ST_Touches(geometry g1, geometry g2);

Description

Returns TRUE if the only points in common between g1 and g2 lie in the union of the boundaries of g1 and g2. The ST_Touches relation applies to all Area/Area, Line/Line, Line/Area, Point/Area and Point/Line pairs of relationships, but not to the Point/Point pair.

In mathematical terms, this predicate is expressed as:

The allowable DE-9IM Intersection Matrices for the two geometries are:

  • FT*******

  • F**T*****

  • F***T****

[Important]

Do not call with a GEOMETRYCOLLECTION as an argument

[Note]

This function call will automatically include a bounding box comparison that will make use of any indexes that are available on the geometries. To avoid using an index, use _ST_Touches instead.

This method implements the OpenGIS Simple Features Implementation Specification for SQL 1.1. s2.1.1.2 // s2.1.13.3

This method implements the SQL/MM specification. SQL-MM 3: 5.1.28

Exemples

The ST_Touches predicate returns TRUE in all the following illustrations.

POLYGON / POLYGON

POLYGON / POLYGON

POLYGON / LINESTRING

LINESTRING / LINESTRING

LINESTRING / LINESTRING

POLYGON / POINT

SELECT ST_Touches('LINESTRING(0 0, 1 1, 0 2)'::geometry, 'POINT(1 1)'::geometry);
 st_touches
------------
 f
(1 row)

SELECT ST_Touches('LINESTRING(0 0, 1 1, 0 2)'::geometry, 'POINT(0 2)'::geometry);
 st_touches
------------
 t
(1 row)

Name

ST_Within — Returns true if the geometry A is completely inside geometry B

Synopsis

boolean ST_Within(geometry A, geometry B);

Description

Returns TRUE if geometry A is completely inside geometry B. For this function to make sense, the source geometries must both be of the same coordinate projection, having the same SRID. It is a given that if ST_Within(A,B) is true and ST_Within(B,A) is true, then the two geometries are considered spatially equal.

Performed by the GEOS module

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.

[Important]

Do not call with a GEOMETRYCOLLECTION as an argument

[Important]

Do not use this function with invalid geometries. You will get unexpected results.

This function call will automatically include a bounding box comparison that will make use of any indexes that are available on the geometries. To avoid index use, use the function _ST_Within.

NOTE: this is the "allowable" version that returns a boolean, not an integer.

This method implements the OpenGIS Simple Features Implementation Specification for SQL 1.1. s2.1.1.2 // s2.1.13.3 - a.Relate(b, 'T*F**F***')

This method implements the SQL/MM specification. SQL-MM 3: 5.1.30

Exemples

--a circle within a circle
SELECT ST_Within(smallc,smallc) As smallinsmall,
        ST_Within(smallc, bigc) As smallinbig,
        ST_Within(bigc,smallc) As biginsmall,
        ST_Within(ST_Union(smallc, bigc), bigc) as unioninbig,
        ST_Within(bigc, ST_Union(smallc, bigc)) as biginunion,
        ST_Equals(bigc, ST_Union(smallc, bigc)) as bigisunion
FROM
(
SELECT ST_Buffer(ST_GeomFromText('POINT(50 50)'), 20) As smallc,
        ST_Buffer(ST_GeomFromText('POINT(50 50)'), 40) As bigc) As foo;
--Result
 smallinsmall | smallinbig | biginsmall | unioninbig | biginunion | bigisunion
--------------+------------+------------+------------+------------+------------
 t            | t          | f          | t          | t          | t
(1 row)
                

8.9. SFCGAL Functions

Abstract

SFCGAL is a C++ wrapper library around CGAL that provides advanced 2D and 3D functions. For robustness, geometry coordinates have an exact rational number representation.

Installation instructions of the library can be found on SFCGAL home page http://www.sfcgal.org. To load the functions create extension postgis_sfcgal.

Some SFCGAL functions replace standard ones (ST_Intersects, ST_Intersection, ST_Difference, ST_Union, ST_Area and ST_Distance), to switch between standard functions and SFCGAL function use:

SET postgis.backend = sfcgal;

and

SET postgis.backend = geos;

postgis_sfcgal_version — Returns the version of SFCGAL in use
ST_Extrude — Extruder une surface vers un volume
ST_StraightSkeleton — Calcule un squelette (straight skeleton) à partir d'une géométrie
ST_ApproximateMedialAxis — Compute the approximate medial axis of an areal geometry.
ST_IsPlanar — Vérifie si une surface est planaire ou non
ST_Orientation — Détermine l'orientation d'une surface
ST_ForceLHR — Force l'orientation LHR d'un objet
ST_MinkowskiSum — Performs Minkowski sum
ST_3DIntersection — Perform 3D intersection
ST_3DDifference — Perform 3D difference
ST_3DUnion — Perform 3D union
ST_3DArea — Computes area of 3D surface geometries. Will return 0 for solids.
ST_Tesselate — Perform surface Tesselation of a polygon or polyhedralsurface and returns as a TIN or collection of TINS
ST_Volume — Computes the volume of a 3D solid. If applied to surface (even closed) geometries will return 0.
ST_MakeSolid — Cast the geometry into a solid. No check is performed. To obtain a valid solid, the input geometry must be a closed Polyhedral Surface or a closed TIN.
ST_IsSolid — Test if the geometry is a solid. No validity check is performed.

Name

postgis_sfcgal_version — Returns the version of SFCGAL in use

Synopsis

text postgis_sfcgal_version(void);

Description

Availability: 2.1.0

This method needs SFCGAL backend.

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

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).


Name

ST_Extrude — Extruder une surface vers un volume

Synopsis

geometry ST_Extrude(geometry geom, float x, float y, float z);

Description

Availability: 2.1.0

This method needs SFCGAL backend.

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

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

Examples

3D images were generated using PostGIS ST_AsX3D and rendering in HTML using X3Dom HTML Javascript rendering library.

SELECT ST_Buffer(ST_GeomFromText('POINT(100 90)'),
  50, 'quad_segs=2'),0,0,30);

Original octagon formed from buffering point

ST_Extrude(ST_Buffer(ST_GeomFromText('POINT(100 90)'),
 50, 'quad_segs=2'),0,0,30);

Hexagon extruded 30 units along Z produces a PolyhedralSurfaceZ

SELECT ST_GeomFromText('LINESTRING(50 50, 100 90, 95 150)')

Original linestring

SELECT ST_Extrude(
 ST_GeomFromText('LINESTRING(50 50, 100 90, 95 150)'),0,0,10));

LineString Extruded along Z produces a PolyhedralSurfaceZ

See Also

ST_AsX3D


Name

ST_StraightSkeleton — Calcule un squelette (straight skeleton) à partir d'une géométrie

Synopsis

geometry ST_StraightSkeleton(geometry geom);

Description

Availability: 2.1.0

This method needs SFCGAL backend.

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

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

Examples

SELECT ST_StraightSkeleton(ST_GeomFromText('POLYGON (( 190 190, 10 190, 10 10, 190 10, 190 20, 160 30, 60 30, 60 130, 190 140, 190 190 ))'));

Original polygon

Straight Skeleton of polygon


Name

ST_ApproximateMedialAxis — Compute the approximate medial axis of an areal geometry.

Synopsis

geometry ST_ApproximateMedialAxis(geometry geom);

Description

Return an approximate medial axis for the areal input based on its straight skeleton. Uses an SFCGAL specific API when built against a capable version (1.2.0+). Otherwise the function is just a wrapper around ST_StraightSkeleton (slower case).

Availability: 2.2.0

This method needs SFCGAL backend.

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

This function supports Polyhedral surfaces.

This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).

Examples

SELECT ST_ApproximateMedialAxis(ST_GeomFromText('POLYGON (( 190 190, 10 190, 10 10, 190 10, 190 20, 160 30, 60 30, 60 130, 190 140, 190 190 ))'));

A polygon and its approximate medial axis


Name

ST_IsPlanar — Vérifie si une surface est planaire ou non

Synopsis

boolean ST_IsPlanar(geometry geom);

Description

Availability: 2.2.0: This was documented in 2.1.0 but got accidentally left out in 2.1 release.

This method needs SFCGAL backend.

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