PostGIS est une extension du système de base de PostgreSQL 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 3.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.
PostGIS est une extension spatiale pour la base de données relationnelle PostgreSQL. Elle a été créée par Refractions Research Inc, sous la forme d'un projet de recherche sur les technologies de base de données spatiales. Refractions est une société de conseil en SIG et base de données basée à Victoria, British Columbia, Canada, et spécialisée en intégration de données et développement logiciel.
PostGIS est désormais un projet de la OSGeo Foundation. PostGIS est développé et financé par de nombreux développeurs et organismes FOSS4G dans le monde entier, qui bénéficient de manière significative de ses fonctionnalités et de sa polyvalence.
Le groupe de développement du projet PostGIS a en charge la maintenance et l'amélioration de PostGIS pour un meilleur support de fonctionnalités importantes en SIG, dans les domaines des standards OGC et SQL/MM, des constructions topologiques avancées (couvertures, surfaces, réseaux), des sources de données pour les outils graphiques de bureautique pour la visualisation et l'édition des donnée SIG, ainsi que dans le domaine des outils web.
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.
Support MVT, Correction de bugs, Améliorations des performances et de la stabilité, Nettoyage du GitHub, Alignement de PostGIS avec les publications PostgreSQL
Maintenance du robot de build, Build de production et expérimental pour Windows, documentation, Alignement de PostGIS avec les publications PostgreSQL, support X3D, support du géocoder TIGER, fonctions de gestion.
Améliorations des index, correction de bugs et améliorations des fonctions geometry/geography, SFCGAL, raster, nettoyage de GitHub, maintenance du robot de build.
Co-fondateur de PostGIS. Maintenance générale, maintenance des Geography, maintenance des index Geography et Geometry (index 2D, 3D, nD et tout index spatial), structures internes des Geometry, intégration des fonctionnalités GEOS et alignement avec les publications GEOS, alignement de PostGIS avec les publications PostgreSQL, loader/dumper, IHM de chargement Shapefile.
Maintenance et correction de bugs, maintenance du robot de build, gestion du miroir git, fonctions de gestions, intégration des fonctionnalités GEOS et alignement avec les publications GEOS, support des topologies, raster et fonctions de l'API bas-niveau.
Améliorations et ajouts de fonctions de distance (notamment fonctions de distance 3D et relations), format de sortie Tiny WKB (TWKB) et support utilisateur
Ajout de fonctions sur le clustering de géométries, améliorations sur les algorithmes sur les géométries, améliorations GEOS et support utilisateur
Améliorations GEOS et documentation
Fonctions MapBox Vector Tile et GeoBuf. Tests Gogs et expérimentations GitLab.
Traitement des géométries, PostgreSQL gist, correction de bugs
Ancien membre du PSC. Développement raster, intégration avec GDAL, loader raster, support utilisateur, correction de bugs, tests sur divers systèmes d'exploitation (Slackware, Mac, Windows, et autres)
Ancien membre du PSC. Coordination de l'effort de correction de bugs et de maintenance, sélectivité et liaisons des index spatiaux, loader/dumper, IHM de chargement Shapefile, intégration et amélioration de nouvelles fonctions.
Développement Raster, support du driver GDAL, outil de chargement
(Émérite) Fonctions d'entrée/sortie XML (KML,GML) et fonctions GeoJSON, support 3D et correction de bugs.
Ancien membre du PSC. Développement général, maintenance du site et du robot de build, gestion de l'incubation OSGeo
Support de CMake pour PostGIS, a développé le loader raster original en python et les fonctions d'API bas-niveau raster
Ancien membre du PSC. Documentation et outils pour la documentation, maintenance du robot de build, support utilisateur avancé sur le newsgroup PostGIS, et maintenance et améliorations des fonctions PostGIS.
Développeur originel 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.
Développement originel de l'outil de chargement/export de shapefiles.
Maintenance générale et développement de fonctions du noyau PostGIS. Amélioration du support des courbes. Interface graphique de chargement des shapefiles.
Architecte de l'implémentation raster de PostGIS. Architecture globale raster, prototypage, support au développement
Développement raster (principalement fonctions analytiques de map algebra)
Alex Bodnaru | Gino Lucrezi | Matt Bretl |
Alex Mayrhofer | Greg Troxel | Matthias Bay |
Andrea Peri | Guillaume Lelarge | Maxime Guillaud |
Andreas Forø Tollefsen | Giuseppe Broccolo | Maxime van Noppen |
Andreas Neumann | Han Wang | Michael Fuhr |
Andrew Gierth | Haribabu Kommi | Mike Toews |
Anne Ghisla | Havard Tveite | Nathan Wagner |
Antoine Bajolet | IIDA Tetsushi | Nathaniel Clay |
Arthur Lesuisse | Ingvild Nystuen | Nikita Shulga |
Artur Zakirov | Jackie Leng | Norman Vine |
Barbara Phillipot | James Marca | Patricia Tozer |
Ben Jubb | Jan Katins | Rafal Magda |
Bernhard Reiter | Jason Smith | Ralph Mason |
Björn Esser | Jeff Adams | Rémi Cura |
Brian Hamlin | Jim Jones | Richard Greenwood |
Bruce Rindahl | Joe Conway | Robert Coup |
Bruno Wolff III | Jonne Savolainen | Roger Crew |
Bryce L. Nordgren | Jose Carlos Martinez Llari | Ron Mayer |
Carl Anderson | Jörg Habenicht | Sebastiaan Couwenberg |
Charlie Savage | Julien Rouhaud | Sergei Shoulbakov |
Christian Schroeder | Kashif Rasul | Sergey Fedoseev |
Christoph Berg | Klaus Foerster | Shinichi Sugiyama |
Christoph Moench-Tegeder | Kris Jurka | Shoaib Burq |
Dane Springmeyer | Laurenz Albe | Silvio Grosso |
Daryl Herzmann | Lars Roessiger | Stefan Corneliu Petrea |
Dave Fuhry | Leo Hsu | Steffen Macke |
David Garnier | Loïc Bartoletti | Stepan Kuzmin |
David Skea | Loic Dachary | Stephen Frost |
David Techer | Luca S. Percich | Steven Ottens |
Dmitry Vasilyev | Lucas C. Villa Real | Talha Rizwan |
Eduin Carrillo | Maria Arias de Reyna | Tom Glancy |
Eugene Antimirov | Marc Ducobu | Tom van Tilburg |
Even Rouault | Mark Sondheim | Vincent Mora |
Frank Warmerdam | Markus Schaber | Vincent Picavet |
George Silva | Markus Wanner | Volf Tomáš |
Gerald Fenoy | Matt Amos |
Certaines organisations ont contribué du temps de développeur, de l'hébergement, ou du financement direct pour le projet PostGIS. Par ordre alphabétique :
Les campagnes de financement participatif sont des campagnes que nous organisons pour financer des fonctionnalités très demandées qui peuvent servir à une large communauté. Chaque campagne est centrée sur une fonctionnalité, ou un lot de fonctionnalités. Chaque sponsor apporte une petite fraction du financement nécessaire, et avec assez de personnes et d'organisations contribuant, nous obtenons les fonds nécessaires pour payer le travail qui aidera la communauté. Si vous pensez qu'une fonctionnalité pourrait être co-financée par de nombreux acteurs, vous pouvez poster votre idée sur le newsgroup PostGIS et ensemble nous pourrons la réaliser.
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 fonction toTopoGeometry et sortir le support de la topologie dans la version 2.0.0. Ce fut une réussite.
postgis64windows - Plus de 20 sponsors ont contribué chacun 100USD pour le support PostGIS 64-bit sur Windows. Ce fut une réussite.
GEOS, la bibliothèque pour les opérations sur les géometries
GDAL (Geospatial Data Abstraction Library), la bibliothèque utilisée pour propulser la plupart des fonctionnalités raster introduites dans PostGIS 2. En retour, les améliorations requises dans GDAL pour supporter PostGIS sont reversées dans le projet GDAL.
PROJ, la bibliothèque gérant les projections cartographiques
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 planificateur de requêtes, les index GiST et les nombreuses fonctionnalités SQL que fournit PostgreSQL.
Ce chapitre décrit les étapes nécessaires pour installer PostGIS.
Pour compiler, en supposant que toutes les dépendances soient dans votre chemin de recherche :
tar -xvfz postgis-3.4.0dev.tar.gz cd postgis-3.4.0dev ./configure make make install
Une fois PostGIS installé, il est nécessaire de l'activer (Section 3.3, “Création de bases de données spatiales”) ou de le mettre à jour (Section 3.4, “Upgrading spatial databases”) dans chaque base de données où vous voulez l'utiliser.
![]() | |
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 décrit le processus générique de compilation. Si vous compilez pour Windows ou d'autres systèmes d'exploitation, vous trouverez des instructions plus détaillées dans les wiki de la communauté guides de compilation et PostGIS Dev Wiki. Les paquets pré-compilés pour de multiples systèmes d'exploitation sont listés dans PostGIS Pre-built Packages Pour les utilisateurs Windows, des versions stables sont disponibles sur Stackbuilder ou sur le site de téléchargement PostGIS Windows. Des compilations expérimentales incluant les dernières fonctionnalités sont disponibles. Ces compilations sont généralement mises à jour une ou deux fois par 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 extensions pour le serveur backend PostgreSQL. Par conséquent, PostGIS 3.4.0dev nécessite l'ensemble des entêtes du serveur PostgreSQL pour pouvoir être compilé. PostGIS peut être compilé pour les versions PostgreSQL 12 à 16. Les versions précédentes de PostgreSQL ne sont pas supportées.
Référez-vous aux guides d'installation de PostgreSQL si vous ne l'avez pas encore installé : https://www.postgresql.org .
![]() | |
Pour les fonctionnalités 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.
Les sources de PostGIS sont disponible depuis http://postgis.net/stuff/postgis-3.4.0dev.tar.gz
wget http://postgis.net/stuff/postgis-3.4.0dev.tar.gz tar -xvzf postgis-3.4.0dev.tar.gz cd postgis-3.4.0dev
Un répertoire appelé postgis-3.4.0dev
sera créé dans le répertoire courant.
Les sources peuvent également être obtenues depuis le dépôt git https://git.osgeo.org/gitea/postgis/postgis/ .
git clone https://git.osgeo.org/gitea/postgis/postgis.git postgis cd postgis sh autogen.sh
Se placer dans le nouveau répertoire créé postgis-3.4.0dev
pour poursuivre l'installation.
./configure
La compilation et l'utilisation de PostGIS nécessitent les éléments suivants :
Obligatoire
PostgreSQL 12 - 16. Une installation complète de PostgreSQL est nécessaire (incluant les entêtes serveur). PostgreSQL est disponible depuis http://www.postgresql.org .
Pour une matrice complète de compatibilité PostgreSQL/PostGIS et PostGIS/GEOS, référez-vous à https://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.
Proj, bibliothèque de reprojection. Proj 6.1 ou supérieur est nécessaire. La bibliothèque Proj est utilisée pour fournir le support de reprojection de coordonnées dans PostGIS. Proj est disponible au téléchargement depuis https://proj.org/ .
GEOS, bibliothèque sur les géométries, version 3.6 ou supérieur, mais GEOS 3.11+ est nécessaire pour pleinement utiliser toutes les nouvelles fonctionnalités. GEOS est disponible au téléchargement depuis https://libgeos.org .
LibXML2, version 2.5.x ou supérieur. LibXML2 est actuellement utilisée dans certaines fonctions d'import (ST_GeomFromGML et ST_GeomFromKML). LibXML2 est disponible au téléchargement depuis https://gitlab.gnome.org/GNOME/libxml2/-/releases.
JSON-C, version 0.9 ou supérieure. JSON-C est utilisé pour l'import GeoJSON avec la fonction ST_GeomFromGeoJson. JSON-C est disponible depuis https://github.com/json-c/json-c/releases/.
GDAL, version 2+ nécessaire, 3+ de préférence. GDAL est nécessaire pour le support raster. https://gdal.org/download.html.
Si vous compilez avec PostgreSQL+JIT, LLVM version >=6 est nécessaire https://trac.osgeo.org/postgis/ticket/4125.
Optionnel
GDAL (pseudo optionnel) vous pouvez l'omettre seulement si vous ne voulez pas du support raster. Pensez également à activer les pilotes que vous souhaitez utiliser, comme décrit dans Section 3.2, “Configurer la prise en charge du raster”.
GTK (GTK+2.0, 2.8+) pour compiler le chargeur de shape file shp2pgsql-gui. http://www.gtk.org/ .
SFCGAL, version 1.3.1 (ou supérieur), 1.4.1 ou supérieur est recommandé et nécessaire pour utiliser l'ensemble des fonctionnalités. SFCGAL peut être utilisée pour fournir des fonctions additionnelles d'analyses avancées 2D et 3D dans PostGIS cf Section 8.20, “SFCGAL Functions”. Pour utiliser SFCGAL au lieu de GEOS pour certaines fonctions 2D disponibles dans les deux bibliothèques (comme ST_Intersection et ST_Area, par exemples), la variable de configuration PostgreSQL postgis.backend
vous permet de choisir quel backend utiliser lorsque SFCGAL est installé (GEOS par default). Note : SFCGAL 1.2 nécessite CGAL 4.3 ou supérieur et Boost 1.54 (cf. https://oslandia.gitlab.io/SFCGAL/dev.html) https://gitlab.com/Oslandia/SFCGAL/.
Pour compiler le Section 14.1, “Address Standardizer” vous devez également installer PCRE http://www.pcre.org (généralement installé sur les distribution *nix). Regex::Assemble
Le paquet perl CPAN est nécessaire uniquement en cas de compilation des données contenues dans parseaddress-stcities.h
. Section 14.1, “Address Standardizer” sera automatiquement compilé s'il détecte la bibliothèque PCRE ou si la variable --with-pcre-dir=/chemin/vers/pcre
lors de la phase de configuration (configure).
Pour permettre d'utiliser ST_AsMVT, la bibliothèque protobuf-c 1.1.0 ou supérieur (pour l'utilisation) et le compilateur protoc-c (pour la compilation) sont nécessaires. Également, pkg-config est nécessaire pour vérifier la version minimale correcte de protobuf-c. Voir protobuf-c. Par défaut, PostGIS utilise Wagyu pour valider les polygones MVT plus rapidement, ce qui nécessite un compilateur c++11. Ceci utilisera les CXXFLAGS et le même compilateur que l'installation PostgreSQL. Pour désactiver cela et utiliser GEOS à la place, utilisez la variable --without-wagyu
pendant l'étape de configuration.
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/ .
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.
À partir de PostGIS 3.0, les fichiers de bibliothèque générés par défaut n'auront plus la version mineur dans le nom de fichier. Ceci signifie que les libs PostGIS 3 se termineront par postgis-3
. Ceci a été fait pour faciliter l'usage de pg_upgrade, avec la contrainte que vous ne pouvez installer qu'une seule version de PostGIS 3 sur votre serveur. Pour basculer sur l'ancien comportement et avoir des fichiers qui incluent la version mineure : e.g. postgis-3.0
, ajoutez ce paramètre dans la commande de configuration.
Cela correspond à l'emplacement où les exécutables et librairies de PostGIS seront installés. Par défaut, cet emplacement est le même que celui de l'installation de PostgreSQL.
![]() | |
Ce paramètre est actuellement défectueux : le paquet s'installe uniquement dans le répertoire d'installation de PostgreSQL. Le suivi de ce bug est disponible depuis http://trac.osgeo.org/postgis/ticket/635 . |
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.
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.
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.
LibXML est la bibliothèque requise pour les traitements GML/KML. Elle est normalement auto détectée en cas d'installation normale, mais si ce n'est pas le cas ou si vous voulez utiliser une version spécifique, vous devez spécifier l’emplacement du fichier de configuration xml2-config
pour permettre de localiser l'emplacement de la bibliothèque LibXML. Utiliser ce paramètre (
>--with-xml2config=/path/to/xml2-config) pour spécifier le répertoire de LibXML qui sera utilisé pour la compilation de PostGIS.
Proj4 est la bibliothèque de reprojection nécessaire à PostGIS. Utilisez ce paramètre (--with-projdir=/path/to/projdir) pour spécifier le répertoire de Proj qui sera utilisé pour la compilation de PostGIS.
Répertoire d'installation d'iconv.
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.
PCRE (Perl Compatible Regular Expression) est une bibliothèque sous licence BSD requise par l'extension address_standardizer. Utilisez ce paramètre (--with-pcredir=/chemin/vers/pcredir) pour spécifier un répertoire contenant PCRE qui sera utilisé par PostGIS.
Compile l'interface graphique d'import de données (nécessite GTK+2.0). Ceci créé l'interface graphique shp2pgsql-gui à shp2pgsql.
Compilation sans support des raster.
Désactive le support des topologies. Il n'y a pas de bibliothèque correspondante car toute la logique requise pour les topologies est incluse dans postgis-3.4.0dev.
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.
Par défaut, PostGIS ne contiendra pas le support sfcgal sans cet argument. PATH
est un argument optionnel permettant de préciser un chemin alternatif vers sfcgal-config.
Désactive la mise à jour de postgis_revision.h à partir du HEAD courant du dépôt git.
![]() | |
Si vous avez téléchargé PostGIS depuis le dépôt du code , 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é. |
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 leur commentaire généré à partir de la documentation. Si vous souhaitez installer ces commentaires dans votre base de données spatiale plus tard, exécutez la commande suivante, qui nécessite docbook. Les fichiers de commentaires pour PostGIS postgis_comments.sql et pour les autres paquets raster_comments.sql, topology_comments.sql sont aussi inclus dans le paquet tar.gz de la distribution, dans le répertoire doc, il est donc inutile d'utiliser cette commande si vous installez depuis l'archive tar. Les commentaires sont aussi inclus par l'installation via CREATE EXTENSION.
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
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.
Les extensions devraient être automatiquement compilées lors du make install. Vous pouvez, si nécessaire, compiler à 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 export PGUSER=postgres # ecrase les variables psql make check # pour tester avant l'installation make install # pour tester les extensions make check RUNTESTFLAGS=--extension
![]() | |
|
Les fichiers extensions seront toujours les mêmes pour les mêmes versions de PostGIS et PostgreSQL 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 extensions/postgis/sql/*.sql
, extensions/postgis_topology/sql/*.sql
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 | 3.4.0dev | 3.4.0dev address_standardizer_data_us | 3.4.0dev | 3.4.0dev postgis | 3.4.0dev | 3.4.0dev postgis_raster | 3.4.0dev | 3.4.0dev postgis_sfcgal | 3.4.0dev | postgis_tiger_geocoder | 3.4.0dev | 3.4.0dev postgis_topology | 3.4.0dev | (6 rows)
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_raster; CREATE EXTENSION postgis_sfcgal; CREATE EXTENSION fuzzystrmatch; --nécessaire pour postgis_tiger_geocoder --utilisé optionnellement par postgis_tiger_geocoder, ou peut etre utilisé seul CREATE EXTENSION address_standardizer; CREATE EXTENSION address_standardizer_data_us; CREATE EXTENSION postgis_tiger_geocoder; CREATE EXTENSION postgis_topology;
Avec psql, vous pouvez contrôler les versions installées ainsi que les schémas d'installation.
\connect mygisdb \x \dx postgis*
List of installed extensions -[ RECORD 1 ]------------------------------------------------- Name | postgis Version | 3.4.0dev Schema | public Description | PostGIS geometry, geography, and raster spat.. -[ RECORD 2 ]------------------------------------------------- Name | postgis_raster Version | 3.0.0dev Schema | public Description | PostGIS raster types and functions -[ RECORD 3 ]------------------------------------------------- Name | postgis_tiger_geocoder Version | 3.4.0dev Schema | tiger Description | PostGIS tiger geocoder and reverse geocoder -[ RECORD 4 ]------------------------------------------------- Name | postgis_topology Version | 3.4.0dev Schema | topology Description | PostGIS topology spatial types and functions
![]() | |
Les tables d'extension |
Si vous avez installé la version 3.4.0dev sans utiliser le système d'extensions, il est possible de l'activer via les commandes suivantes pour packager les fonctions dans leurs extensions respectives. L'installation via `unpackaged` a été supprimé dans PostgreSQL 13, nous vous invitons donc à basculer sur une installation utilisant le système d'extensions avant de migrer à PostgreSQL 13.
CREATE EXTENSION postgis FROM unpackaged; CREATE EXTENSION postgis_raster FROM unpackaged; CREATE EXTENSION postgis_topology FROM unpackaged; CREATE EXTENSION postgis_tiger_geocoder FROM unpackaged;
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.
![]() | |
Si vous avez configuré PostGIS en utilisant un emplacement non standard de PostgreSQL, GEOS, ou Proj4, vous pourrez avoir besoin d'ajouter l'emplacement des bibliothèques à la variable d'environnement |
![]() | |
Pour le moment, make check repose sur les variables d'environnement |
Si réussi, make check sortira les résultats de près de 500 tests. Les résultats seront similaires à la sortie ci-dessous (avec de nombreuses lignes omises) :
CUnit - A unit testing framework for C - Version 2.1-3 http://cunit.sourceforge.net/ . . . Run Summary: Type Total Ran Passed Failed Inactive suites 44 44 n/a 0 0 tests 300 300 300 0 0 asserts 4215 4215 4215 0 n/a Elapsed time = 0.229 seconds . . . Running tests . . . Run tests: 134 Failed: 0 -- if you build with SFCGAL . . . Running tests . . . Run tests: 13 Failed: 0 -- if you built with raster support . . . Run Summary: Type Total Ran Passed Failed Inactive suites 12 12 n/a 0 0 tests 65 65 65 0 0 asserts 45896 45896 45896 0 n/a . . . Running tests . . . Run tests: 101 Failed: 0 -- topology regress . . . Running tests . . . Run tests: 51 Failed: 0 -- if you built --with-gui, you should see this too CUnit - A unit testing framework for C - Version 2.1-2 http://cunit.sourceforge.net/ . . . Run Summary: Type Total Ran Passed Failed Inactive suites 2 2 n/a 0 0 tests 4 4 4 0 0 asserts 4 4 4 0 n/a
Les extensions postgis_tiger_geocoder
et address_standardizer
ne supportent actuellement que l'installcheck de PostgreSQL. Pour les tester, cf ci-dessous. Note : Il n'est pas nécessaire de lancer make install si cette commande a déjà été lancée dans le répertoire racine des sources PostGIS.
Pour l'extension address_standardize :
cd extensions/address_standardizer make install make installcheck
La sortie de la commande devrait ressembler à :
============== 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. =====================
Le géocodeur tiger nécessite d'avoir les extensions postgis et fuzzystrmatch installée sur l'instance PostgreSQL. Les tests de l'extension address_standardizer seront lancés si PostGIS est compilé avec le support address_standardizer :
cd extensions/postgis_tiger_geocoder make install make installcheck
La sortie de la commande devrait ressembler à :
============== 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. =====================
Pour installer PostGIS, entrez
make install
Ceci copiera les fichiers d'installation de PostGIS dans leur sous-répertoires appropriés définis 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
![]() | |
|
L'extension address_standardizer
était précédemment livrée sous forme d'un paquet séparé nécessitant son propre téléchargement. Depuis la version 2.2 de PostGIS, cette extension est intégrée. Pour de plus amples informations sur cette extension, sa configuration, son utilisation, se référer à Section 14.1, “Address Standardizer”.
Ce normalisateur d'adresses peut être utilisé avec l'extension PostGIS tiger en remplacement de Normalize_Address. Se référer à la page Section 2.4.2, “Utilisation de l'Extension Address Standardizer avec le Geocodeur Tiger” pour mettre en place ce remplacement. Il peut également être utilisé pour fabriquer son propre géocodeur ou pour normaliser des adresses pour les comparer plus facilement.
Le normalisateur d'adresses se base sur PCRE, généralement installé sur les systèmes Nix. Il peut également être téléchargé ici : http://www.pcre.org. Durant la phase Section 2.2.3, “Configuration de la compilation”, si PCRE est détecté, le normalisateur d'adresses sera automatiquement compilé. Pour utiliser une installation personnalisée de PCRE, passer le paramètre --with-pcredir=/chemin/vers/pcre
dans la commande configure, où /chemin/vers/pcre
est le répertoire contenant les sous-répertoires pcre include et lib.
Pour les utilisateurs de Windows®, les versions 2.1 et supérieures de PostGIS sont livrées avec l'extension address_standardizer. Il n'est donc pas besoin de compiler cette extension. La commande CREATE EXTENSION
suffit.
Une fois installée, vous pouvez vous connecter à votre base de données et lancer le SQL :
CREATE EXTENSION address_standardizer;
Le test suivant ne nécessite pas de table rules, gas, ou lex
SELECT num, street, city, state, zip FROM parse_address('1 Devonshire Place PH301, Boston, MA 02109');
La sortie de la commande devrait ressembler à
num | street | city | state | zip -----+------------------------+--------+-------+------- 1 | Devonshire Place PH301 | Boston | MA | 02109
Le module Perl Regex:Assemble n'est plus nécessaire lors de la compilation de l'extension address_standardizer. Les fichiers qu'il génère sont désormais contenus dans les sources. Cependant, si vous devez modifier les fichiers usps-st-city-orig.txt
ou usps-st-city-orig.txt usps-st-city-adds.tx
, vous devez recompiler parseaddress-stcities.h
qui lui nécessite Regex:Assemble.
cpan Regexp::Assemble
ou si vous êtes sur Ubuntu / Debian, vous devrez peut-être faire
sudo perl -MCPAN -e "install Regexp::Assemble"
L'extension géocodeur Tiger peut ne pas être distribué avec votre installation de PostGIS. Si vous n'avez pas l'extension géocodeur Tiger, ou si vous souhaitez utiliser une version plus récente de celle de votre installation, vous pouvez utiliser les fichiers share/extension/postgis_tiger_geocoder.*
depuis les paquets disponibles à Windows Unreleased Versions, dans la section pour votre version de PostgreSQL. Même si ces paquets sont pour Windows, les fichiers d'extension postgis_tiger_geocoder fonctionneront quel que soit votre système d'exploitation car c'est une extension en SQL/plpgsql.
Installez ou compilez PostGIS depuis les sources de façon normale. Ceci devrait installer également les fichiers d'extension ainsi que les le géocodeur tiger.
Connectez-vous à la base de données avec psql ou PgAdmin (ou tout autre client) et lancez la commande SQL suivante. Note : Si l'installation se déroule sur une base de données contenant déjà PostGIS, la première étape n'est pas nécessaire. Si l'extension fuzzystrmatch
est déjà installée, la seconde étape n'est pas nécessaire non plus.
CREATE EXTENSION postgis; CREATE EXTENSION fuzzystrmatch; CREATE EXTENSION postgis_tiger_geocoder; --celle-ci est optionnelle si vous souhaitez utiliser les standardizer basé sur les règles (pagc_normalize_address) CREATE EXTENSION address_standardizer;
Si l'extension postgis_tiger_geocoder est déjà installée et que vous souhaitez la mettre à jour, lancez :
ALTER EXTENSION postgis UPDATE; ALTER EXTENSION postgis_tiger_geocoder UPDATE;
Si vous avez modifié tiger.loader_platform
ou tiger.loader_variables
, vous devrez peut être les mettre à jour.
Pour tester l'installation, lancez cette commande SQL sur la base de données :
SELECT na.address, na.streetname,na.streettypeabbrev, na.zip FROM normalize_address('1 Devonshire Place, Boston, MA 02109') AS na;
Qui devrait afficher
address | streetname | streettypeabbrev | zip ---------+------------+------------------+------- 1 | Devonshire | Pl | 02109
Créez un nouvel enregistrement dans la table tiger.loader_platform
contenant les chemins vers les exécutables et le serveur.
Par exemple, pour créer un profil nommé debbie suivant la convention sh
, vous feriez :
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';
Et modifiez les chemins dans la colonne declare_sect pour les faire correspondre aux chemins des programmes pg, unzip, shp2pgsql, psql, etc. sur le serveur Debbie.
Si vous ne modifiez pas la table loader_platform
, elle contiendra des chemins par défaut pour les programmes, et vous aurez à modifier les scripts après leur génération.
Depuis PostGIS 2.4.1, le chargement des données de "ZIP Code Tabulation Area" zcta5
a été modifié pour charger les données actuelles zcta5, celui-ci est inclus dans Loader_Generate_Nation_Script si activé. Le chargement est désactivé par défaut car cela prend du temps (20 à 60 minutes), occupe de l'espace disque, et n'est pas souvent utile.
Pour l'activer, exécutez :
UPDATE tiger.loader_lookuptables SET load = true WHERE table_name = 'zcta520';
Si disponible, la fonction Geocode peut l'utiliser lorsqu'un filtre de frontière est utilisé avec des codes zips. La fonction Reverse_Geocode l'utilise si l'adresse retournée n'a pas de code zip, ce qui arrive souvent avec le géocodage inverse sur des autoroutes.
Créez un répertoire nommé gisdata
à la racine du serveur ou de la machine locale si le réseau entre les deux est suffisamment rapide. Ce répertoire contiendra les fichiers tiger téléchargés et traités. Pour changer ce répertoire, modifier le champ staging_fold
dans la table tiger.loader_variables
.
Créez un répertoire nommé temp dans le répertoire gisdata
(ou dans le répertoire que vous avez configuré dans le champ staging_fold
). Ce répertoire contiendra les données tiger extraites.
Puis exécutez la fonction SQL Loader_Generate_Nation_Script, pour vous assurer que votre libellé de profil personnalisé est utilisé, et sauvegardez le script dans un fichier .sh ou .bat. Par exemple pour générer le script de chargement d'une nation :
psql -c "SELECT Loader_Generate_Nation_Script('debbie')" -d geocoder -tA > /gisdata/nation_script_load.sh
Exécutez en ligne de commande les scripts de chargement précédemment générés.
cd /gisdata sh nation_script_load.sh
Lorsque vous avez terminé d'exécuter les scripts, vous devriez avoir trois tables dans votre schéma tiger_data
, avec des données déjà remplies. Vous pouvez confirmer cela avec les requêtes suivantes, à exécuter dans psql ou pgAdmn
SELECT count(*) FROM tiger_data.county_all;
count ------- 3233 (1 row)
SELECT count(*) FROM tiger_data.state_all;
count ------- 56 (1 row)
Par défaut, les tables correspondant à bg
, tract
, tabblock20
ne sont pas chargées. Ces tables ne sont pas utilisées par le géocodeur, mais sont typiquement utilisées pour les statistiques de population. Si vous souhaitez charger ces données lors du chargement des états, exécutez la requête suivante.
UPDATE tiger.loader_lookuptables SET load = true WHERE load = false AND lookup_name IN('tract', 'bg', 'tabblock20');
Autrement, il est possible de charger juste ces tables après le chargement des données sur les états en utilisant le Loader_Generate_Census_Script
Pour chaque état dont vous voulez charger les données, générez un script d'état Loader_Generate_Script.
![]() | |
NE GÉNÉREZ PAS le script d'état avant d'avoir chargé les données de nation, car le script d'état utilise la liste des comtés chargés par le script de nation. |
psql -c "SELECT Loader_Generate_Script(ARRAY['MA'], 'debbie')" -d geocoder -tA > /gisdata/ma_load.sh
Lancez alors les lignes de commande générées.
cd /gisdata sh ma_load.sh
Après le chargement des données, ou lors d'une pause dans le chargement, il peut être utile de lancer analyze sur toutes les tables tiger pour mettre à jour les statistiques (y compris les statistiques héritées)
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;
Une des plaintes les plus récurrentes concerne la fonction Normalize_Address, qui normalise l'adresse avant de la géocoder. La normalisation est loin d'être parfaite, et corriger ces imperfections consomme énormément de ressources. Par conséquent, nous avons intégré un autre projet qui a un moteur de standardisation d'adresses bien meilleur. Pour utiliser ce nouveau address_standardizer, compilez l'extension en suivant Section 2.3, “Installation et utilisation de l'extension address standardize” et installez l'extension dans votre base de données.
Une fois que vous avez installé cette extension dans la même base de données où vous avez installé postgis_tiger_geocoder
, vous pouvez utiliser Pagc_Normalize_Address à la place de Normalize_Address. Cette extension ne dépend pas de Tiger, et peut donc être utilisée avec d'autres sources de données telles que des adresses internationales. L'extension de géocodage Tiger est installée avec ses propres versions spécifiques de rules table ( tiger.pagc_rules
) , gaz table (tiger.pagc_gaz
), et lex table (tiger.pagc_lex
). Vous pouvez les améliorer et ajouter des règles pour avoir de meilleurs résultats de géocodage pour vos besoins spécifiques.
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
Si vous mettez à jour depuis tiger_2010, vous aurez besoin d'abord de générer et exécuter le Drop_Nation_Tables_Generate_Script. Avant de charger les données d'états, vous devez charger les données de nation via Loader_Generate_Nation_Script. Celui-ci va générer un script de chargement pour vous. Loader_Generate_Nation_Script est une étape à exécuter une seule fois, pour la mises à jour (depuis des données tiger précédentes) ou pour de nouvelles installations.
Pour charger les données d'états, voir Loader_Generate_Script pour générer un script pour charger les données pour votre plateforme et les états que vous souhaitez. Note : vous pouvez les charger peu à peu, vous n'avez pas besoin de tout charger d'un coup. Vous pouvez les charger lorsque vous en avez besoin.
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
Tout d'abord, mettez à jour l'extension postgis_tiger_geocoder en exécutant :
ALTER EXTENSION postgis_tiger_geocoder UPDATE;
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 à 4 pour les instructions sur la manière de lancer le script généré. Cela doit être fait qu'une fois.
![]() | |
Vous pouvez avoir un mix de différentes années dans vos tables d'états et vous pouvez les mettre à jour indépendamment. Avant de mettre à jour un état, vous devez d'abord supprimer l'année précédente dans les tables d'états pour cet état en utilisant Drop_State_Tables_Generate_Script. |
Il y a plusieurs choses à vérifier quand votre installation ou mise à jour ne va pas dans la direction souhaitée.
Vérifiez que vous avez installé PostgreSQL 12 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 12 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
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é les chemins et versions de PostgreSQL, de la bibliothèque Proj.4 et de la blibliothèque GEOS.
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.
Tuning for PostGIS performance is much like tuning for any PostgreSQL workload. The only additional consideration is that geometries and rasters are usually large, so memory-related optimizations generally have more of an impact on PostGIS than other types of PostgreSQL queries.
For general details about optimizing PostgreSQL, refer to Tuning your PostgreSQL Server.
For PostgreSQL 9.4+ configuration can be set at the server level without touching postgresql.conf
or postgresql.auto.conf
by using the ALTER SYSTEM
command.
ALTER SYSTEM SET work_mem = '256MB'; -- this forces non-startup configs to take effect for new connections SELECT pg_reload_conf(); -- show current setting value -- use SHOW ALL to see all settings SHOW work_mem;
In addition to the Postgres settings, PostGIS has some custom settings which are listed in Section 8.23, “Variables PostGIS GUC (Grand Unified Custom Variables)”.
These settings are configured in postgresql.conf
:
Default: partition
This is generally used for table partitioning. The default for this is set to "partition" which is ideal for PostgreSQL 8.4 and above since it will force the planner to only analyze tables for constraint consideration if they are in an inherited hierarchy and not pay the planner penalty otherwise.
Default: ~128MB in PostgreSQL 9.6
Set to about 25% to 40% of available RAM. On windows you may not be able to set as high.
max_worker_processes This setting is only available for PostgreSQL 9.4+. For PostgreSQL 9.6+ this setting has additional importance in that it controls the max number of processes you can have for parallel queries.
Default: 8
Sets the maximum number of background processes that the system can support. This parameter can only be set at server start.
work_mem - sets the size of memory used for sort operations and complex queries
Default: 1-4MB
Adjust up for large dbs, complex queries, lots of RAM
Adjust down for many concurrent users or low RAM.
If you have lots of RAM and few developers:
SET work_mem TO '256MB';
maintenance_work_mem - the memory size used for VACUUM, CREATE INDEX, etc.
Default: 16-64MB
Generally too low - ties up I/O, locks objects while swapping memory
Recommend 32MB to 1GB on production servers w/lots of RAM, but depends on the # of concurrent users. If you have lots of RAM and few developers:
SET maintenance_work_mem TO '1GB';
max_parallel_workers_per_gather
This setting is only available for PostgreSQL 9.6+ and will only affect PostGIS 2.3+, since only PostGIS 2.3+ supports parallel queries. If set to higher than 0, then some queries such as those involving relation functions like ST_Intersects
can use multiple processes and can run more than twice as fast when doing so. If you have a lot of processors to spare, you should change the value of this to as many processors as you have. Also make sure to bump up max_worker_processes
to at least as high as this number.
Default: 0
Sets the maximum number of workers that can be started by a single Gather
node. Parallel workers are taken from the pool of processes established by max_worker_processes
. Note that the requested number of workers may not actually be available at run time. If this occurs, the plan will run with fewer workers than expected, which may be inefficient. Setting this value to 0, which is the default, disables parallel query execution.
Si vous activez la prise en charge du raster, vous devriez lire ce qui suit afin de bien la configurer.
À partir de PostGIS 2.1.3, tous les pilotes raster, et la prise en charge des rasters hors-connexion (out-of-db) est désactivé par défaut. Pour les activer, vous devez définir les variables d'environnement suivantes dans l'environnement du serveur : POSTGIS_GDAL_ENABLED_DRIVERS
and POSTGIS_ENABLE_OUTDB_RASTERS
. Depuis PostGIS 2.2, vous pouvez utiliser la méthode plus générique en définissant les Section 8.23, “Variables PostGIS GUC (Grand Unified Custom Variables)” correspondantes.
Si vous souhaitez activer le raster hors connexion :
POSTGIS_ENABLE_OUTDB_RASTERS=1
Si la variable a n'importe quelle autre valeur, ou si elle n'a pas de valeur, le support du raster hors-connexion sera désactivé.
Pour utiliser tous les pilotes GDAL disponibles dans votre installation GDAL, définissez la variable d'environnement via
POSTGIS_GDAL_ENABLED_DRIVERS=ENABLE_ALL
Si vous souhaitez activer une liste de pilotes spécifiques, définissez la variable d'environnement via :
POSTGIS_GDAL_ENABLED_DRIVERS="GTiff PNG JPEG GIF XYZ"
![]() | |
Si vous êtes sous Windows, ne pas mettre de guillemets autour de la liste des pilotes |
La définition des variables d'environnement dépend de votre système d'exploitation. Sous Ubuntu ou Debian avec PostgreSQL installé via apt-postgresql, la méthode conseillée est d'éditer le fichier de configuration /etc/postgresql/
où 10 est la version de PostgreSQL et main est le groupe de bases de données (cluster).10
/main
/environment
On windows, if you are running as a service, you can set via System variables which for Windows 7 you can get to by right-clicking on Computer->Properties Advanced System Settings or in explorer navigating to Control Panel\All Control Panel Items\System
. Then clicking Advanced System Settings ->Advanced->Environment Variables and adding new system variables.
Après avoir changé les variables d'environnement, vous devrez redémarrer le service PostgreSQL pour prendre en compte les changements.
Si vous utilisez PostgreSQL 9.1+ et avez compilé et installé les modules extensions/postgis, vous pouvez transformer une base de données en base de données spatiale en utilisant le mécanisme EXTENSION.
L'extension cœur postgis inclus le support des types geometry et geography, la table spatial_ref_sys ainsi que toutes les fonctions et commentaires. Les supports de raster et topologie sont fournis par des extensions dédiées.
Exécutez les requêtes SQL suivantes dans la base de données où vous souhaitez activer le support spatial :
CREATE EXTENSION IF NOT EXISTS plpgsql; CREATE EXTENSION postgis; CREATE EXTENSION postgis_raster; -- OPTIONNEL CREATE EXTENSION postgis_topology; -- OPTIONNEL
![]() | |
Cette méthode n'est en générale nécessaire que si vous ne pouvez pas ou ne voulez pas que PostGIS soit installé dans le répertoire des extensions PostgreSQL (par exemple pour des tests, du développement, ou dans un environnement restreint). |
L'ajout des objets et définitions des fonctions PostGIS dans votre base de données se fait en chargeant plusieurs fichiers sql présents dans [prefix]/share/contrib
, cet emplacement est celui qui a été défini durant la phase de compilation.
Les objets au cœur de PostGIS (types geometry et geography, et les fonctions associées) sont dans le script postgis.sql
. Les objets raster sont dans le script rtpostgis.sql
. Les objets de topologie sont dans le script topology.sql
.
Pour avoir la liste complète des définitions des systèmes de coordonnées EPSG, vous pouvez aussi charger le script spatial_ref_sys.sql
pour remplir la table spatial_ref_sys
. Cela permettre d'utiliser la fonction ST_Transform() pour effectuer des reprojections sur les géométries.
Si vous souhaitez ajouter les commentaires sur les fonctions PostGIS, vous pouvez les trouver dans le script postgis_comments.sql
. Vous pouvez accéder aux commentaires d'une fonction en tapant \dd [nom_de_la_fonction] depuis un terminal psql.
Exécutez les commandes Shell suivantes dans votre terminal :
DB=[ma_bdd_spatiale] SCRIPTSDIR=`pg_config --sharedir`/contrib/postgis-3.3/ # Objets coeur psql -d ${DB} -f ${SCRIPTSDIR}/postgis.sql psql -d ${DB} -f ${SCRIPTSDIR}/spatial_ref_sys.sql psql -d ${DB} -f ${SCRIPTSDIR}/postgis_comments.sql # OPTIONNEL # Support raster (OPTIONNEL) psql -d ${DB} -f ${SCRIPTSDIR}/rtpostgis.sql psql -d ${DB} -f ${SCRIPTSDIR}/raster_comments.sql # OPTIONNEL # Support topologies (OPTIONNEL) psql -d ${DB} -f ${SCRIPTSDIR}/topology.sql psql -d ${DB} -f ${SCRIPTSDIR}/topology_comments.sql # OPTIONNEL
Certaines distributions de PostGIS (en particulier l'installateur Win32 pour PostGIS >= 1.1.5) chargent les fonctions PostGIS dans la base de données de modèle (template) template_postgis
. Si la base de données template_postgis
existe sur votre installation PostgreSQL, il est alors possible pour vos utilisateurs et/ou applications de créer des bases de données spatiales en utilisant une seule ligne de commande. A noter que dans les deux cas, l'utilisateur sql doit avoir les permissions pour créer de nouvelles bases de données.
Depuis un shell :
# createdb -T template_postgis ma_bdd_spatiale
En SQL :
postgres=# CREATE DATABASE ma_bdd_spatiale TEMPLATE=template_postgis
Upgrading existing spatial databases can be tricky as it requires replacement or introduction of new PostGIS object definitions.
Unfortunately not all definitions can be easily replaced in a live database, so sometimes your best bet is a dump/reload process.
PostGIS provides a SOFT UPGRADE procedure for minor or bugfix releases, and a HARD UPGRADE procedure for major releases.
Before attempting to upgrade PostGIS, it is always worth to backup your data. If you use the -Fc flag to pg_dump you will always be able to restore the dump with a HARD UPGRADE.
If you installed your database using extensions, you'll need to upgrade using the extension model as well. If you installed using the old sql script way, you are advised to switch your install to extensions because the script way is no longer supported.
If you originally installed PostGIS with extensions, then you need to upgrade using extensions as well. Doing a minor upgrade with extensions, is fairly painless.
If you are running PostGIS 3 or above, then you should use the PostGIS_Extensions_Upgrade function to upgrade to the latest version you have installed.
SELECT postgis_extensions_upgrade();
If you are running PostGIS 2.5 or lower, then do the following:
ALTER EXTENSION postgis UPDATE; SELECT postgis_extensions_upgrade(); -- This second call is needed to rebundle postgis_raster extension SELECT postgis_extensions_upgrade();
If you have multiple versions of PostGIS installed, and you don't want to upgrade to the latest, you can explicitly specify the version as follows:
ALTER EXTENSION postgis UPDATE TO "3.4.0dev"; ALTER EXTENSION postgis_topology UPDATE TO "3.4.0dev";
If you get an error notice something like:
No migration path defined for … to 3.4.0dev
Then you'll need to backup your database, create a fresh one as described in Section 3.3.1, “Base de données spatiale en utilisant EXTENSION” and then restore your backup on top of this new database.
If you get a notice message like:
Version "3.4.0dev" of extension "postgis" is already installed
Then everything is already up to date and you can safely ignore it. UNLESS you're attempting to upgrade from an development version to the next (which doesn't get a new version number); in that case you can append "next" to the version string, and next time you'll need to drop the "next" suffix again:
ALTER EXTENSION postgis UPDATE TO "3.4.0devnext"; ALTER EXTENSION postgis_topology UPDATE TO "3.4.0devnext";
![]() | |
If you installed PostGIS originally without a version specified, you can often skip the reinstallation of postgis extension before restoring since the backup just has |
![]() | |
If you are upgrading PostGIS extension from a version prior to 3.0.0, you will have a new extension postgis_raster which you can safely drop, if you don't need raster support. You can drop as follows: DROP EXTENSION postgis_raster; |
This section applies only to those who installed PostGIS not using extensions. If you have extensions and try to upgrade with this approach you'll get messages like:
can't drop … because postgis extension depends on it
NOTE: if you are moving from PostGIS 1.* to PostGIS 2.* or from PostGIS 2.* prior to r7409, you cannot use this procedure but would rather need to do a HARD UPGRADE.
After compiling and installing (make install) you should find a set of *_upgrade.sql
files in the installation folders. You can list them all with:
ls `pg_config --sharedir`/contrib/postgis-3.4.0dev/*_upgrade.sql
Load them all in turn, starting from postgis_upgrade.sql
.
psql -f postgis_upgrade.sql -d your_spatial_database
The same procedure applies to raster, topology and sfcgal extensions, with upgrade files named rtpostgis_upgrade.sql
, topology_upgrade.sql
and sfcgal_upgrade.sql
respectively. If you need them:
psql -f rtpostgis_upgrade.sql -d your_spatial_database
psql -f topology_upgrade.sql -d your_spatial_database
psql -f sfcgal_upgrade.sql -d your_spatial_database
You are advised to switch to an extension based install by running
psql -c "SELECT postgis_extensions_upgrade();"
![]() | |
If you can't find the |
The PostGIS_Full_Version function should inform you about the need to run this kind of upgrade using a "procs need upgrade" message.
By HARD UPGRADE we mean full dump/reload of postgis-enabled databases. You need a HARD UPGRADE when PostGIS objects' internal storage changes or when SOFT UPGRADE is not possible. The Release Notes appendix reports for each version whether you need a dump/reload (HARD UPGRADE) to upgrade.
The dump/reload process is assisted by the postgis_restore.pl script which takes care of skipping from the dump all definitions which belong to PostGIS (including old ones), allowing you to restore your schemas and data into a database with PostGIS installed without getting duplicate symbol errors or bringing forward deprecated objects.
Supplementary instructions for windows users are available at Windows Hard upgrade.
The Procedure is as follows:
Create a "custom-format" dump of the database you want to upgrade (let's call it olddb
) include binary blobs (-b) and verbose (-v) output. The user can be the owner of the db, need not be postgres super account.
pg_dump -h localhost -p 5432 -U postgres -Fc -b -v -f "/somepath/olddb.backup" olddb
Do a fresh install of PostGIS in a new database -- we'll refer to this database as newdb
. Please refer to Section 3.3.2, “Base de données spatiale sans utiliser EXTENSION (non recommandé)” and Section 3.3.1, “Base de données spatiale en utilisant EXTENSION” for instructions on how to do this.
The spatial_ref_sys entries found in your dump will be restored, but they will not override existing ones in spatial_ref_sys. This is to ensure that fixes in the official set will be properly propagated to restored databases. If for any reason you really want your own overrides of standard entries just don't load the spatial_ref_sys.sql file when creating the new db.
If your database is really old or you know you've been using long deprecated functions in your views and functions, you might need to load legacy.sql
for all your functions and views etc. to properly come back. Only do this if _really_ needed. Consider upgrading your views and functions before dumping instead, if possible. The deprecated functions can be later removed by loading uninstall_legacy.sql
.
Restore your backup into your fresh newdb
database using postgis_restore.pl. Unexpected errors, if any, will be printed to the standard error stream by psql. Keep a log of those.
perl utils/postgis_restore.pl "/somepath/olddb.backup" | psql -h localhost -p 5432 -U postgres newdb 2> errors.txt
Errors may arise in the following cases:
Some of your views or functions make use of deprecated PostGIS objects. In order to fix this you may try loading legacy.sql
script prior to restore or you'll have to restore to a version of PostGIS which still contains those objects and try a migration again after porting your code. If the legacy.sql
way works for you, don't forget to fix your code to stop using deprecated functions and drop them loading uninstall_legacy.sql
.
Some custom records of spatial_ref_sys in dump file have an invalid SRID value. Valid SRID values are bigger than 0 and smaller than 999000. Values in the 999000.999999 range are reserved for internal use while values > 999999 can't be used at all. All your custom records with invalid SRIDs will be retained, with those > 999999 moved into the reserved range, but the spatial_ref_sys table would lose a check constraint guarding for that invariant to hold and possibly also its primary key ( when multiple invalid SRIDS get converted to the same reserved SRID value ).
In order to fix this you should copy your custom SRS to a SRID with a valid value (maybe in the 910000..910999 range), convert all your tables to the new srid (see UpdateGeometrySRID), delete the invalid entry from spatial_ref_sys and re-construct the check(s) with:
ALTER TABLE spatial_ref_sys ADD CONSTRAINT spatial_ref_sys_srid_check check (srid > 0 AND srid < 999000 );
ALTER TABLE spatial_ref_sys ADD PRIMARY KEY(srid));
If you are upgrading an old database containing french IGN cartography, you will have probably SRIDs out of range and you will see, when importing your database, issues like this :
WARNING: SRID 310642222 converted to 999175 (in reserved zone)
In this case, you can try following steps : first throw out completely the IGN from the sql which is resulting from postgis_restore.pl. So, after having run :
perl utils/postgis_restore.pl "/somepath/olddb.backup" > olddb.sql
run this command :
grep -v IGNF olddb.sql > olddb-without-IGN.sql
Create then your newdb, activate the required Postgis extensions, and insert properly the french system IGN with : this script After these operations, import your data :
psql -h localhost -p 5432 -U postgres -d newdb -f olddb-without-IGN.sql 2> errors.txt
L'Open Geospatial Consortium (OGC) a développé le standard Simple Features Access (SFA) pour fournir un modèle de données géospatiales. Ce standard définit le type spatial Geometry, ainsi que les opérations pour manipuler et transformer des géométries, et permettre des tâches d'analyses spatiales. PostGIS implémente le modèle OGC Geometry sous forme de types PostgreSQL geometry et geography.
Geometry est un type abstrait. Les valeurs géométriques utilisent les sous-types concrets, qui représentent les diverses formes géométriques. Ces types incluent les types atomiques Point, LineString, LinearRing et Polygon, ainsi que les types de collections MultiPoint, MultiLineString, MultiPolygon et GeometryCollection. Le standard Simple Features Access - Part 1: Common architecture v1.2.1 ajoute les sous-types pour les structures PolyhedralSurface, Triangle et TIN.
Geometry représente des formes dans le plan cartésien en 2 dimensions. Les types PolyhedralSurface, Triangle, et TIN peuvent également représenter des formes en 3 dimensions. La taille et la localisation des formes sont spécifiées par leurs coordonnées. Chaque coordonnées a une dimension X et une Y, qui déterminent sa position sur le plan. Les formes sont construites à partir de points ou de segments. Les points sont spécifiés par une seul coordonnée ; les segments par deux coordonnées.
Les coordonnées peuvent inclure des valeurs pour les dimensions optionnelles Z et M. La dimension Z est souvent utilisée pour représenter l'élévation. La dimension M contient une mesure, qui représente par exemple le temps ou une distance. Si la dimension Z ou M est présente pour une valeur géométrique, elle doit être définie pour tous les points de la géométrie. Si une géométrie a une dimension Z ou M, la dimension de la coordonnée est 3D ; si elle a à la fois les dimension Z et M, la dimension de la coordonnée est 4D.
Les valeurs géométriques sont associées à un système de coordonnées de référence (SCR, ou en anglais spatial reference system, SRS), qui indique dans quel système de coordonnées les valeurs sont définies. Le SCR est identifié par un identifiant appelé SRID. Les unités sur les axes X et Y sont déterminées par ce système de coordonnées de référence. Dans un système planaire, les coordonnées X et Y représentent les distances respectivement selon l'Est et le Nord. Dans un système géodésique elles représentent la longitude et la latitude. L'identifiant SRID 0 représente un plan cartésien infini, sans unité sur ses axes. Voir Section 4.5, “Spatial Reference Systems”.
La dimension d'une géométrie est une propriété des types géométriques. Les types Point ont une dimension 0, les types linéaires ont une dimension 1, et les types polygonaux ont une dimension 2. Les collections ont la dimension de leur élément de plus grande dimension.
Une valeur géométrique peut être vide. Une valeur vide ne contient aucun vertex (pour les types de géométriques atomiques) ou aucun élément (pour les collections).
Une propriété important des valeurs géométriques est leur emprise spatiale (extent en anglais) ou leur boîte englobante (bounding box en anglais), que le modèle OGC nomme enveloppe (envelope). La boîte englobante est la boîte 2D ou 3D qui contient les coordonnées d'une géométrie. C'est une façon efficace de représenter l'emprise d'une géométrie dans un espace et de tester comment deux géométries interagissent.
Le modèle de géométrie permet d'évaluer les relations topologiques, telles que décrites dans Section 5.1.1, “Dimensionally Extended 9-Intersection Model”. Pour supporter cela, les concepts de intérieur (interior en anglais), frontière (boundary en anglais) et extérieur (exterior en anglais) sont définis pour tous les types de géométries. Les géométries sont topologiquement fermées, donc elle contiennent toujours leur frontière. La dimension de la géométrie de la frontière est la dimension de la géométrie moins un.
Le modèle de géométrie OGC définie des règles de validité pour chaque type géométrique. Ces règles permettent de s'assurer que les valeurs géométriques représentent des situations réalistes (e.g. il est possible de définir un polygone avec un trou à l'extérieur, mais cela n'a pas de sens au niveau géométrique, et est donc invalide). PostGIS permet de stocker et de manipuler des valeurs géométriques invalides, ceci permet de les détecter et de les corriger si besoin. Voir Section 4.4, “Validation de la géométrie”
Un objet de type Point est une géométrie de dimension 0, qui représente un seul point dans l'espace.
POINT (1 2) POINT Z (1 2 3) POINT ZM (1 2 3 4)
Le type LineString est une ligne, de dimension 1, formée par une séquence de segments linéaires contigus. Chaque segment est défini par deux points, l'extrémité d'un segment étant le point de départ du segment suivant. Un LineString valide au sens OGC a soit zéro, soit deux points ou plus, mais PostGIS permet d'avoir des LineStrings avec un seul point. LineStrings peuvent se croiser (auto-intersection). Un LineString peut être fermé si les points de début et fin sont les mêmes. Un LineString est dit simple s'il ne s'auto-intersecte pas.
LINESTRING (1 2, 3 4, 5 6)
Le type LinearRing définit un LineString qui est à la fois fermé et simple. Autrement dit, le premier et dernier points doivent être égaux, et la ligne ne doit pas s'auto-intersecter.
LINEARRING (0 0 0, 4 0 0, 4 4 0, 0 4 0, 0 0 0)
Un polygone, de type Polygon est une région d'un plan, de dimension 2, délimité par une frontière extérieure (la coquille, shell en anglais) et zéro, une ou plusieurs frontières intérieures (trous, holes en anglais). Chaque frontière est un LinearRing.
POLYGON ((0 0 0,4 0 0,4 4 0,0 4 0,0 0 0),(1 1 0,2 1 0,2 2 0,1 2 0,1 1 0))
Le type MultiLineString est une collection de LineStrings. Un MultiLineString est fermé si tous ses éléments sont fermés.
MULTILINESTRING ( (0 0,1 1,1 2), (2 3,3 2,5 4) )
Un MultiPolygon est une collection de Polygons, non superposés et non adjacents. Les polygones de la collection peuvent se toucher, mais uniquement en un nombre fini de points.
MULTIPOLYGON (((1 5, 5 5, 5 1, 1 1, 1 5)), ((6 5, 9 1, 6 1, 6 5)))
Le type GeometryCollection représente une collection hétérogène de géométries (i.e. de types différents).
GEOMETRYCOLLECTION ( POINT(2 3), LINESTRING(2 3, 3 4))
Le type PolyhedralSurface modélise une surface polyédrique, sous la forme d'une collection de faces qui partagent des arêtes. Chaque face est un Polygon plan. Si les coordonnées du Polygon ont une dimension Z, alors la surface est de dimension 3.
POLYHEDRALSURFACE Z ( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )
Un Triangle est un polygone définit par trois sommets non colinéaires. Un Triangle étant un Polygon, et donc est fermé, il est définit par quatre coordonnées, la première et la dernière étant égales.
TRIANGLE ((0 0, 0 9, 9 0, 0 0))
Un TIN est une collection de Triangles non superposés, représentant un réseau irrégulier triangulé (Triangulated Irregular Network).
TIN Z ( ((0 0 0, 0 0 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 0 0 0)) )
The ISO/IEC 13249-3 SQL Multimedia - Spatial standard (SQL/MM) extends the OGC SFA to define Geometry subtypes containing curves with circular arcs. The SQL/MM types support 3DM, 3DZ and 4D coordinates.
![]() | |
All floating point comparisons within the SQL-MM implementation are performed to a specified tolerance, currently 1E-8. |
CircularString is the basic curve type, similar to a LineString in the linear world. A single arc segment is specified by three points: the start and end points (first and third) and some other point on the arc. To specify a closed circle the start and end points are the same and the middle point is the opposite point on the circle diameter (which is the center of the arc). In a sequence of arcs the end point of the previous arc is the start point of the next arc, just like the segments of a LineString. This means that a CircularString must have an odd number of points greater than 1.
CIRCULARSTRING(0 0, 1 1, 1 0) CIRCULARSTRING(0 0, 4 0, 4 4, 0 4, 0 0)
A CompoundCurve is a single continuous curve that may contain both circular arc segments and linear segments. That means that in addition to having well-formed components, the end point of every component (except the last) must be coincident with the start point of the following component.
COMPOUNDCURVE( CIRCULARSTRING(0 0, 1 1, 1 0),(1 0, 0 1))
A CurvePolygon is like a polygon, with an outer ring and zero or more inner rings. The difference is that a ring can be a CircularString or CompoundCurve as well as a LineString.
As of PostGIS 1.4 PostGIS supports compound curves in a curve polygon.
CURVEPOLYGON( CIRCULARSTRING(0 0, 4 0, 4 4, 0 4, 0 0), (1 1, 3 3, 3 1, 1 1) )
Example: A CurvePolygon with the shell defined by a CompoundCurve containing a CircularString and a LineString, and a hole defined by a CircularString
CURVEPOLYGON( COMPOUNDCURVE( CIRCULARSTRING(0 0,2 0, 2 1, 2 3, 4 3), (4 3, 4 5, 1 4, 0 0)), CIRCULARSTRING(1.7 1, 1.4 0.4, 1.6 0.4, 1.6 0.5, 1.7 1) )
A MultiCurve is a collection of curves which can include LineStrings, CircularStrings or CompoundCurves.
MULTICURVE( (0 0, 5 5), CIRCULARSTRING(4 0, 4 4, 8 4))
La spécification OGC SFA définit deux formats pour représenter des valeurs géométriques : Well-Known Text (WKT) et Well-Known Binary (WKB). Ces deux formats incluent les informations sur le type d'objet et sur les coordonnées qui le définissent.
Well-Known Text (WKT) fournit un standard pour représenter de façon textuelle des données spatiales. Voici quelques exemples de représentations WKT :
POINT(0 0)
POINT Z (0 0 0)
POINT ZM (0 0 0 0)
POINT EMPTY
LINESTRING(0 0,1 1,1 2)
LINESTRING EMPTY
POLYGON((0 0,4 0,4 4,0 4,0 0),(1 1, 2 1, 2 2, 1 2,1 1))
MULTIPOINT((0 0),(1 2))
MULTIPOINT Z ((0 0 0),(1 2 3))
MULTIPOINT EMPTY
MULTILINESTRING((0 0,1 1,1 2),(2 3,3 2,5 4))
MULTIPOLYGON(((0 0,4 0,4 4,0 4,0 0),(1 1,2 1,2 2,1 2,1 1)), ((-1 -1,-1 -2,-2 -2,-2 -1,-1 -1)))
GEOMETRYCOLLECTION(POINT(2 3),LINESTRING(2 3,3 4))
GEOMETRYCOLLECTION EMPTY
Des méthodes d'entrée/sortie en WKT sont fournies via les fonctions ST_AsText et ST_GeomFromText :
text WKT = ST_AsText(geometry); geometry = ST_GeomFromText(text WKT, SRID);
Par exemple, une requête pour créer et insérer une objet spatial sous forme de WKT et avec un SRID :
INSERT INTO geotable ( geom, nom ) VALUES ( ST_GeomFromText('POINT(-126.4 45.32)', 312), 'Un lieu');
Well-Known Binary (WKB) fournit un moyen portable et sans perte de précision pour représenter des données spatiales sous la forme de données binaires (tableau d'octets). Voici quelques exemples de représentations WKB :
WKT : POINT(1 1)
WKB : 0101000000000000000000F03F000000000000F03
WKT : LINESTRING (2 2, 9 9)
WKB : 0102000000020000000000000000000040000000000000004000000000000022400000000000002240
Des méthodes d'entrée/sortie en WKB sont fournies via les fonctions ST_AsBinary et ST_GeomFromWKB :
bytea WKB = ST_AsBinary(geometry); geometry = ST_GeomFromWKB(bytea WKB, SRID);
Par exemple, une requête pour créer et insérer une objet spatial sous forme de WKB :
INSERT INTO geotable ( geom, nom ) VALUES ( ST_GeomFromWKB('\x0101000000000000000000f03f000000000000f03f', 312), 'Un lieu');
PostGIS implémente le modèle Simple Features de l'OGC via un type PostgreSQL geometry
. Ce type représente tous les sous-types de géométries en utilisant un type interne (voir GeometryType et ST_GeometryType). Cela permet de modéliser les entités spatiales comme lignes de tables qui contiennent une colonne de type geometry
.
Le type geometry
est opaque, ce qui veut dire que tout accès est fait en appelant des fonctions sur les valeurs géométriques. Des fonctions permettent la création d'objets géométriques, l'accès et la mise à jour des champs internes, ainsi que le calcul de nouvelles valeurs géométriques. PostGIS supporte toutes les fonctions spécifiées par la spécification OGC Simple feature access - Part 2: SQL option (SFS), ainsi que de nombreuses autres. voir Chapter 8, Référence PostGIS pour une liste complète des fonctions disponibles.
![]() | |
PostGIS respecte le standard SFA en préfixant toutes les fonctions spatiales par "ST_". Initialement, cela voulait dire "Spatial and Temporal" (Spatial et Temporel), mais l'aspect temporel du standard n'a pas été développé. À la place, ceci peut être interprété comme "Spatial Type" (Type Spatial). |
La standard SFA spécifie que les objets spatiaux doivent inclure un identifiant de système de coordonnées de référence (SRID). Ce SRID est obligatoire lors de la création d'objets spatiaux pour l'insertion dans la base de données (mais peut être défini par défaut à 0). Voir ST_SRID et Section 4.5, “Spatial Reference Systems”
Pour optimiser les requêtes sur les géométries, PostGIS définit plusieurs types d'index spatiaux, ainsi que des opérateurs spatiaux pour les utiliser. Voir Section 4.9, “Spatial Indexes” et Section 5.2, “Using Spatial Indexes” pour plus d'informations.
Les spécifications OGC SFA ne supportaient initialement que les géométries 2D, et le SRID de la géométrie n'est pas inclut dans les représentations d'entrée/sortie. La spécification OGC SFA 1.2.1 (qui est alignée avec le standard ISO 19125) ajoute le support pour la 3D (ZYZ) et les mesures (XYM et XYZM), mais n'inclut toujours pas la valeur du SRID.
À cause de ces limitations, PostGIS définit les formats étendus EWKB ((Extended Well-Known Binary) et EWKT (Extended Well-Known Text). Ils supportent la 3D (XYZ et XYM) et 4D (XYZM) et incluent l'information de SRID. Le format EWKB incluant toutes les informations de la géométrie, cela permet à PostGIS d'utiliser ce format pour les enregistrements (e.g. dans les fichiers DUMP).
EWKB et EWKT sont utilisés pour les "formes canoniques" des objets spatiaux de PostGIS. En tant qu'entrée, la forme canonique pour les données binaires est EWKB ; pour les données textuelles EWKB et EWKT sont tous deux acceptés. Cela permet de créer des valeurs géométriques en transtypant une valeur textuelle en HEXEWKB ou EWKT vers une valeur géométrique en utilisant ::geometry
. Pour la sortie, la forme canonique pour les données binaires est EWKB et HEXEWKB (hex-encoded EWKB) pour les données textuelles.
Par exemple, cette requête créé une géométrie en transtypant depuis une chaîne de caractères contenant du EKWT, et retourne sa valeur sous sa forme canonique en HEXEWKB :
SELECT 'SRID=4;POINT(0 0)'::geometry; geometry ---------------------------------------------------- 01010000200400000000000000000000000000000000000000
La sortie PostGIS EWKT a quelques différences avec le OGC WKT :
Pour les géométries 3DZ, le qualificatif Z est omis :
OGC : POINT Z (1 2 3)
EWKT : POINT (1 2 3)
Pour les géométries 3DM, le qualificatif M est inclus :
OGC : POINT M (1 2 3)
EWKT : POINTM (1 2 3)
Pour les géométries 4D, le qualificatif ZM est omis :
OGC : POINT ZM (1 2 3 4)
EWKT : POINT (1 2 3 4)
EWKT évite de sur-spécifier les dimensions et ainsi éviter les inconsistances possibles avec le format OGC/ISO, comme :
POINT ZM (1 1)
POINT ZM (1 1 1)
POINT (1 1 1 1)
![]() | |
Les formats étendus PostGIS sont des sur-ensembles des formats OGC, donc les représentations valides WKB/WKT sont aussi des représentations EWKB/EWKT valides. Cependant, cela pourrait changer à l'avenir, si l'OGC définit un format qui rentrerait en conflit avec la définition de PosGIS. Vous ne devriez donc PAS vous appuyer sur cette compatibilité ! |
Voici quelques exemples de représentations d'objets spatiaux sous forme EWKT :
POINT(0 0 0) -- XYZ
SRID=32632;POINT(0 0) -- XY avec SRID
POINTM(0 0 0) -- XYM
POINT(0 0 0 0) -- XYZM
SRID=4326;MULTIPOINTM(0 0 0,1 2 1) -- XYM avec SRID
MULTILINESTRING((0 0 0,1 1 0,1 2 1),(2 3 1,3 2 1,5 4 1))
POLYGON((0 0 0,4 0 0,4 4 0,0 4 0,0 0 0),(1 1 0,2 1 0,2 2 0,1 2 0,1 1 0))
MULTIPOLYGON(((0 0 0,4 0 0,4 4 0,0 4 0,0 0 0),(1 1 0,2 1 0,2 2 0,1 2 0,1 1 0)),((-1 -1 0,-1 -2 0,-2 -2 0,-2 -1 0,-1 -1 0)))
GEOMETRYCOLLECTIONM( POINTM(2 3 9), LINESTRINGM(2 3 4, 3 4 5) )
MULTICURVE( (0 0, 5 5), CIRCULARSTRING(4 0, 4 4, 8 4) )
POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )
TRIANGLE ((0 0, 0 10, 10 0, 0 0))
TIN( ((0 0 0, 0 0 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 0 0 0)) )
Des méthodes d'entrée/sortie sont fournies via les fonctions suivantes :
bytea EWKB = ST_AsEWKB(geometry); text EWKT = ST_AsEWKT(geometry); geometry = ST_GeomFromEWKB(bytea EWKB); geometry = ST_GeomFromEWKT(text EWKT);
Par exemple, une requête pour créer et insérer une objet spatial sous forme de EWKT :
INSERT INTO geotable ( geom, nom ) VALUES ( ST_GeomFromEWKT('SRID=312;POINTM(-126.4 45.32 15)'), 'Un lieu' )
Le type de données PostGIS geography
permet le support des entités spatiales utilisant un système de coordonnées géographique (parfois appelé géodésique, ou "latitude/longitude" ou "longitude/latitude"). Les coordonnées géographiques sont des coordonnées sphériques, exprimées en unités d'angle (degrés).
Le type geometry de PostGIS est lié à un plan. Ainsi, le chemin le plus court entre deux points sur un plan est la ligne droite. Les fonctions sur les types geometry (aires, distances, intersections, etc.) sont donc calculées en utilisant des lignes droites et les mathématiques cartésiennes. Cela permet des implémentations plus faciles et plus rapides à exécuter, mais cela devient imprécis lorsque la rotondité de la Terre entre en jeu.
Le type PostGIS geography repose sur un modèle sphérique. Le chemin le plus court entre deux points sur une sphère est l'arc de cercle. Les fonctions sur les types geography (aires, distances, intersections, etc.) sont donc calculées en utilisant des arcs de cercle sur une sphère. En prenant en compte la rotondité de la Terre, ces fonctions permettent d'avoir une meilleure précision.
Les mathématiques utilisées pour les calculs étant plus compliquées, moins de fonctions sont définies pour le type geography que pour le type geometry. De nouveaux algorithmes sont ajoutés au fur et à mesure des versions de PostGIS, donc le support du type geography s'étend petit à petit. Si une fonction n'est pas disponible, il est toutefois possible de convertir un type geography en geometry puis vice-versa.
Comme le type geometry, les données géographiques sont liées à un identifiant de système de coordonnées de référence (SRID). Tout système géodésique (reposant sur longitude/latitude) peut être utilisé, tant qu'il défini dans la table spatial_ref_sys
. (Avant PostGIS 2.2, le type geography ne supportait que le SCR WGS 84 (SRID:4326)). Vous pouvez ajouter votre propre SCR géodésique, comme décrit dans Section 4.5.2, “User-Defined Spatial Reference Systems”.
Pour tous les systèmes de coordonnées de référence, les unités des valeurs retournées par les fonctions de mesure (e.g. ST_Distance, ST_Length, ST_Perimeter, ST_Area) et le paramètre de distance de ST_DWithin sont en mètres.
Vous pouvez créer une table pour stocker des données géographiques en utilisant la requête SQL CREATE TABLE, avec une colonne de type geography
. L'exemple suivant créé une table avec une colonne géographique pour stocker des lignes 2D dans un SCR géodésique WGS84 (SRID 4326) :
CREATE TABLE global_points ( id SERIAL PRIMARY KEY, name VARCHAR(64), location geography(POINT,4326) );
Le type geography supporte deux modificateurs de type :
le modificateur de type spatial restreint le type de formes et dimensions de la colonne. Les valeurs permises pour le type spatial sont : POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING, MULTIPOLYGON, GEOMETRYCOLLECTION. Le type geography ne supporte pas les CURVEs, TINS, ni POLYHEDRALSURFACEs. Le modificateur permet de restreindre la dimension, en ajoutant les suffixes : Z, M ou ZM. Par exemple, un modificateur 'LINESTRINGM' permet uniquement de stocker des LineStrings en 3D, et traite la troisième dimension comme une mesure. De façon similaire, 'POINTZM' limite aux données 4D (XYZM).
le modificateur SRID restreint à un SCR spécifique. Si omis, le SRID 4326 (WGS84 géodésique) est utilisé, et tous les calculs sont effectués en utilisant WGS84.
Exemples de création de tables utilisant des colonnes géographiques :
Création d'une table avec une géographie POINT 2D avec le SRID par défaut 4326 (WGS84 longitude/latitude) :
CREATE TABLE ptgeogwgs(gid serial PRIMARY KEY, geog geography(POINT) );
Création d'une table avec une géographie POINT 2D dans le CRS NAD83 longlat :
CREATE TABLE ptgeognad83(gid serial PRIMARY KEY, geog geography(POINT,4269) );
Création d'une table avec une géographie POINT 3D (XYZ) avec le SCR explicite 4326 :
CREATE TABLE ptzgeogwgs84(gid serial PRIMARY KEY, geog geography(POINTZ,4326) );
Création d'une table avec une géographie LINESTRING 2D avec le SRID par défaut 4326 :
CREATE TABLE lgeog(gid serial PRIMARY KEY, geog geography(LINESTRING) );
Création d'une table avec une géographie POLYGON 2D avec le SRC 4267 (NAD 1927 long lat) :
CREATE TABLE lgeognad27(gid serial PRIMARY KEY, geog geography(POLYGON,4267) );
Les colonnes géographiques sont enregistrées dans la vue système geography_columns
. Vous pouvez effectuer un requête sur la vue geography_columns
et vérifier que la table est bien listée :
SELECT * FROM geography_columns;
La création d'index spatiaux sur les colonnes de type geography fonctionne de la même manière qu'avec le type geometry. PostGIS va prendre en compte que le type de la colonne est GEOGRAPHY et créer un index sphérique au lieu d'un index planaire utilisé pour GEOMETRY.
-- Indexe la table test avec un index spherique CREATE INDEX global_points_gix ON global_points USING GIST ( location );
Vous pouvez insérer des données dans des tables géographiques de la même façon qu'avec les géométries. Les données géométriques seront automatiquement transtypées en type geography si le SRID des données est 4326. Les formats EWKT et EWKB peuvent aussi être utilisés pour spécifier les valeurs géographiques.
-- Ajoute quelques donnees dans la table de test INSERT INTO global_points (name, location) VALUES ('Town', 'SRID=4326;POINT(-110 30)'); INSERT INTO global_points (name, location) VALUES ('Forest', 'SRID=4326;POINT(-109 29)'); INSERT INTO global_points (name, location) VALUES ('London', 'SRID=4326;POINT(0 49)');
Tout CRS géodésique (longitude/latitude) disponible dans la table spatial_ref_sys
peut être utilisé comme SRID d'une géographie. L'utilisation d'un CRS non géodésique provoquera une erreur.
-- NAD 83 lon/lat SELECT 'SRID=4269;POINT(-123 34)'::geography; geography ---------------------------------------------------- 0101000020AD1000000000000000C05EC00000000000004140
-- NAD27 lon/lat SELECT 'SRID=4267;POINT(-123 34)'::geography; geography ---------------------------------------------------- 0101000020AB1000000000000000C05EC00000000000004140
-- NAD83 UTM zone meters - renvoie une erreur car c'est une projection planaire metrique SELECT 'SRID=26910;POINT(-123 34)'::geography; ERROR: Only lon/lat coordinate systems are supported in geography.
Les requêtes et les fonctions de mesure utilisent le mètre comme unité. Les paramètres de distance doivent être exprimés en mètres, et les valeurs de retours seront également en mètres (ou en mètres carré pour les surfaces).
-- Une requete de distance en utilisant 1000km de tolerance SELECT name FROM global_points WHERE ST_DWithin(location, 'SRID=4326;POINT(-110 29)'::geography, 1000000);
Vous pouvez vérifier la puissance des géographies en calculant à quel point un avion s'approche de Reykjavik (POINT(-21.96 64.15)) lors d'un trajet en arc de cercle depuis Seattle à Londres (LINESTRING(-122.33 47.606, 0.0 51.5)) (voir la route).
Le type geography donne la plus petite distance réelle de 122,235 km sur la sphère entre Reykjavik et l'arc de cercle entre Seattle et Londres.
-- Calcul de distance en utilisant GEOGRAPHY SELECT ST_Distance('LINESTRING(-122.33 47.606, 0.0 51.5)'::geography, 'POINT(-21.96 64.15)'::geography); st_distance ----------------- 122235.23815667
Le type geometry quant à lui calcule la distance cartésienne entre Reykjavik et la ligne droite entre Seattle et Londres, telle qu'elle serait tracée sur un plan. Cette distance n'a pas de sens réel, d'autant que l'unité du résultat est techniquement en degrés, mais que le résultat ne correspond à aucune différence angulaire entre les points, donc même considérer le résultat comme des degrés serait faux.
-- Calcul de distance en utilisant GEOMETRY SELECT ST_Distance('LINESTRING(-122.33 47.606, 0.0 51.5)'::geometry, 'POINT(-21.96 64.15)'::geometry); st_distance -------------------- 13.342271221453624
Le type de données geography permet de stocker des données en utilisant les coordonnées longitude/latitude, mais cela a un prix : il y a moins de fonctions disponibles sur le type GEOGRAPHY que sur le type GEOMETRY, et les fonctions disponibles prendront plus de temps CPU pour s'exécuter.
Le type de données à choisir devrait être déterminé par la zone de travail de l'application que vous construisez. Est-ce que vos données s'étendront sur l'ensemble du globe ou sur un continent, ou bien est-ce qu'elle seront locales, comme une région, un département ou une ville ?
Si vous données sont limitées à une petite zone, utiliser un SCR adéquat et le type GEOMETRY est la meilleure solution, à la fois en terme de performances que de fonctionnalités disponibles.
Si vos données s'étendent sur le monde entier ou couvrent un continent, le type GEOGRAPHY peut vous permettre de construire votre application sans trop vous soucier des projections. Vous pouvez stocker vos données en utilisant les coordonnées longitude/latitude, et utiliser les fonctions définies sur les GEOGRAPHY.
Si vous n'êtes pas à l'aise avec les projections, que vous ne souhaitez pas approfondir le sujet, et que vous êtes prêts à accepter les limitations sur les fonctionnalités offertes par GEOGRAPHY, alors ce peut être plus facile d'utiliser GEOGRAPHY au lieu de GEOMETRY. Chargez vos données en longitude/latitude et partez de là.
Référez-vous à Section 15.11, “PostGIS Function Support Matrix” pour comparer les supports Geography et Geometry. Pour avoir un résumé des fonctions géographiques disponibles, référez-vous à Section 15.4, “PostGIS Geography Support Functions”
4.3.4.1. | Les calculs sont-ils faits sur la sphère ou sur la sphéroïde ? |
Par défaut, tous les calculs sur les distances et les surfaces sont effectués sur la sphéroïde. Les résultats des calculs sur les petites zones devraient coïncider avec les résultats des calculs planaire en utilisant les projections locales adéquates. Sur de plus grandes zones, les calculs sphéroïdaux seront plus précis que ceux effectués sur un plan projeté. Toutes les fonctions géographiques ont une option pour calculer sur une sphère, en passant comme tout dernier paramètre booléen 'FALSE'. Ceci améliorera les performances des calculs, en particulier pour les géométries très simples. | |
4.3.4.2. | Qu'en est-il de la ligne de changement de date et des pôles ? |
Tous les calculs omettent les concepts de ligne de changement de date et de pôles. Les coordonnées étant sphériques (longitude/latitude), une forme traversant la ligne de changement de date n'est, d'un point de vue calculs, pas différente de toute autre forme. | |
4.3.4.3. | What is the longest arc you can process? |
We use great circle arcs as the "interpolation line" between two points. That means any two points are actually joined up two ways, depending on which direction you travel along the great circle. All our code assumes that the points are joined by the *shorter* of the two paths along the great circle. As a consequence, shapes that have arcs of more than 180 degrees will not be correctly modelled. | |
4.3.4.4. | Why is it so slow to calculate the area of Europe / Russia / insert big geographic region here ? |
Because the polygon is so darned huge! Big areas are bad for two reasons: their bounds are huge, so the index tends to pull the feature no matter what query you run; the number of vertices is huge, and tests (distance, containment) have to traverse the vertex list at least once and sometimes N times (with N being the number of vertices in the other candidate feature). As with GEOMETRY, we recommend that when you have very large polygons, but are doing queries in small areas, you "denormalize" your geometric data into smaller chunks so that the index can effectively subquery parts of the object and so queries don't have to pull out the whole object every time. Please consult ST_Subdivide function documentation. Just because you *can* store all of Europe in one polygon doesn't mean you *should*. |
PostGIS is compliant with the Open Geospatial Consortium’s (OGC) Simple Features specification. That standard defines the concepts of geometry being simple and valid. These definitions allow the Simple Features geometry model to represent spatial objects in a consistent and unambiguous way that supports efficient computation. (Note: the OGC SF and SQL/MM have the same definitions for simple and valid.)
A simple geometry is one that has no anomalous geometric points, such as self intersection or self tangency.
A POINT
is inherently simple as a 0-dimensional geometry object.
MULTIPOINT
s are simple if no two coordinates (POINT
s) are equal (have identical coordinate values).
A LINESTRING
is simple if it does not pass through the same point twice, except for the endpoints. If the endpoints of a simple LineString are identical it is called closed and referred to as a Linear Ring.
(a) and (c) are simple |
![]() (a) | ![]() (b) |
![]() (c) | ![]() (d) |
A MULTILINESTRING
is simple only if all of its elements are simple and the only intersection between any two elements occurs at points that are on the boundaries of both elements.
(e) and (f) are simple |
![]() (e) | ![]() (f) | ![]() (g) |
POLYGON
s are formed from linear rings, so valid polygonal geometry is always simple.
To test if a geometry is simple use the ST_IsSimple function:
SELECT ST_IsSimple('LINESTRING(0 0, 100 100)') AS straight, ST_IsSimple('LINESTRING(0 0, 100 100, 100 0, 0 100)') AS crossing; straight | crossing ----------+---------- t | f
Generally, PostGIS functions do not require geometric arguments to be simple. Simplicity is primarily used as a basis for defining geometric validity. It is also a requirement for some kinds of spatial data models (for example, linear networks often disallow lines that cross). Multipoint and linear geometry can be made simple using ST_UnaryUnion.
Geometry validity primarily applies to 2-dimensional geometries (POLYGON
s and MULTIPOLYGON
s) . Validity is defined by rules that allow polygonal geometry to model planar areas unambiguously.
A POLYGON
is valid if:
the polygon boundary rings (the exterior shell ring and interior hole rings) are simple (do not cross or self-touch). Because of this a polygon cannnot have cut lines, spikes or loops. This implies that polygon holes must be represented as interior rings, rather than by the exterior ring self-touching (a so-called "inverted hole").
boundary rings do not cross
boundary rings may touch at points but only as a tangent (i.e. not in a line)
interior rings are contained in the exterior ring
the polygon interior is simply connected (i.e. the rings must not touch in a way that splits the polygon into more than one part)
(h) and (i) are valid |
![]() (h) | ![]() (i) | ![]() (j) |
![]() (k) | ![]() (l) | ![]() (m) |
A MULTIPOLYGON
is valid if:
its element POLYGON
s are valid
elements do not overlap (i.e. their interiors must not intersect)
elements touch only at points (i.e. not along a line)
(n) is a valid |
![]() (n) | ![]() (o) | ![]() (p) |
These rules mean that valid polygonal geometry is also simple.
For linear geometry the only validity rule is that LINESTRING
s must have at least two points and have non-zero length (or equivalently, have at least two distinct points.) Note that non-simple (self-intersecting) lines are valid.
SELECT ST_IsValid('LINESTRING(0 0, 1 1)') AS len_nonzero, ST_IsValid('LINESTRING(0 0, 0 0, 0 0)') AS len_zero, ST_IsValid('LINESTRING(10 10, 150 150, 180 50, 20 130)') AS self_int; len_nonzero | len_zero | self_int -------------+----------+---------- t | f | t
POINT
and MULTIPOINT
geometries have no validity rules.
PostGIS allows creating and storing both valid and invalid Geometry. This allows invalid geometry to be detected and flagged or fixed. There are also situations where the OGC validity rules are stricter than desired (examples of this are zero-length linestrings and polygons with inverted holes.)
Many of the functions provided by PostGIS rely on the assumption that geometry arguments are valid. For example, it does not make sense to calculate the area of a polygon that has a hole defined outside of the polygon, or to construct a polygon from a non-simple boundary line. Assuming valid geometric inputs allows functions to operate more efficiently, since they do not need to check for topological correctness. (Notable exceptions are that zero-length lines and polygons with inversions are generally handled correctly.) Also, most PostGIS functions produce valid geometry output if the inputs are valid. This allows PostGIS functions to be chained together safely.
If you encounter unexpected error messages when calling PostGIS functions (such as "GEOS Intersection() threw an error!"), you should first confirm that the function arguments are valid. If they are not, then consider using one of the techniques below to ensure the data you are processing is valid.
![]() | |
If a function reports an error with valid inputs, then you may have found an error in either PostGIS or one of the libraries it uses, and you should report this to the PostGIS project. The same is true if a PostGIS function returns an invalid geometry for valid input. |
To test if a geometry is valid use the ST_IsValid function:
SELECT ST_IsValid('POLYGON ((20 180, 180 180, 180 20, 20 20, 20 180))'); ----------------- t
Information about the nature and location of an geometry invalidity are provided by the ST_IsValidDetail function:
SELECT valid, reason, ST_AsText(location) AS location FROM ST_IsValidDetail('POLYGON ((20 20, 120 190, 50 190, 170 50, 20 20))') AS t; valid | reason | location -------+-------------------+--------------------------------------------- f | Self-intersection | POINT(91.51162790697674 141.56976744186045)
In some situations it is desirable to correct invalid geometry automatically. Use the ST_MakeValid function to do this. (ST_MakeValid
is a case of a spatial function that does allow invalid input!)
By default, PostGIS does not check for validity when loading geometry, because validity testing can take a lot of CPU time for complex geometries. If you do not trust your data sources, you can enforce a validity check on your tables by adding a check constraint:
ALTER TABLE mytable ADD CONSTRAINT geometry_valid_check CHECK (ST_IsValid(geom));
A Spatial Reference System (SRS) (also called a Coordinate Reference System (CRS)) defines how geometry is referenced to locations on the Earth's surface. There are three types of SRS:
A geodetic SRS uses angular coordinates (longitude and latitude) which map directly to the surface of the earth.
A projected SRS uses a mathematical projection transformation to "flatten" the surface of the spheroidal earth onto a plane. It assigns location coordinates in a way that allows direct measurement of quantities such as distance, area, and angle. The coordinate system is Cartesian, which means it has a defined origin point and two perpendicular axes (usually oriented North and East). Each projected SRS uses a stated length unit (usually metres or feet). A projected SRS may be limited in its area of applicability to avoid distortion and fit within the defined coordinate bounds.
A local SRS is a Cartesian coordinate system which is not referenced to the earth's surface. In PostGIS this is specified by a SRID value of 0.
There are many different spatial reference systems in use. Common SRSes are standardized in the European Petroleum Survey Group EPSG database. For convenience PostGIS (and many other spatial systems) refers to SRS definitions using an integer identifier called a SRID.
A geometry is associated with a Spatial Reference System by its SRID value, which is accessed by ST_SRID. The SRID for a geometry can be assigned using ST_SetSRID. Some geometry constructor functions allow supplying a SRID (such as ST_Point and ST_MakeEnvelope). The EWKT format supports SRIDs with the SRID=n;
prefix.
Spatial functions processing pairs of geometries (such as overlay and relationship functions) require that the input geometries are in the same spatial reference system (have the same SRID). Geometry data can be transformed into a different spatial reference system using ST_Transform and ST_TransformPipeline. Geometry returned from functions has the same SRS as the input geometries.
The SPATIAL_REF_SYS
table used by PostGIS is an OGC-compliant database table that defines the available spatial reference systems. It holds the numeric SRIDs and textual descriptions of the coordinate systems.
The spatial_ref_sys
table definition is:
CREATE TABLE spatial_ref_sys ( srid INTEGER NOT NULL PRIMARY KEY, auth_name VARCHAR(256), auth_srid INTEGER, srtext VARCHAR(2048), proj4text VARCHAR(2048) )
The columns are:
An integer code that uniquely identifies the Spatial Reference System (SRS) within the database.
The name of the standard or standards body that is being cited for this reference system. For example, "EPSG" is a valid auth_name
.
The ID of the Spatial Reference System as defined by the Authority cited in the auth_name
. In the case of EPSG, this is the EPSG code.
The Well-Known Text representation of the Spatial Reference System. An example of a WKT SRS representation is:
PROJCS["NAD83 / UTM Zone 10N", GEOGCS["NAD83", DATUM["North_American_Datum_1983", SPHEROID["GRS 1980",6378137,298.257222101] ], PRIMEM["Greenwich",0], UNIT["degree",0.0174532925199433] ], PROJECTION["Transverse_Mercator"], PARAMETER["latitude_of_origin",0], PARAMETER["central_meridian",-123], PARAMETER["scale_factor",0.9996], PARAMETER["false_easting",500000], PARAMETER["false_northing",0], UNIT["metre",1] ]
For a discussion of SRS WKT, see the OGC standard Well-known text representation of coordinate reference systems.
PostGIS uses the PROJ library to provide coordinate transformation capabilities. The proj4text
column contains the PROJ coordinate definition string for a particular SRID. For example:
+proj=utm +zone=10 +ellps=clrk66 +datum=NAD27 +units=m
For more information see the PROJ web site. The spatial_ref_sys.sql
file contains both srtext
and proj4text
definitions for all EPSG projections.
When retrieving spatial reference system definitions for use in transformations, PostGIS uses fhe following strategy:
If auth_name
and auth_srid
are present (non-NULL) use the PROJ SRS based on those entries (if one exists).
If srtext
is present create a SRS using it, if possible.
If proj4text
is present create a SRS using it, if possible.
The PostGIS spatial_ref_sys
table contains over 3000 of the most common spatial reference system definitions that are handled by the PROJ projection library. But there are many coordinate systems that it does not contain. You can add SRS definitions to the table if you have the required information about the spatial reference system. Or, you can define your own custom spatial reference system if you are familiar with PROJ constructs. Keep in mind that most spatial reference systems are regional and have no meaning when used outside of the bounds they were intended for.
A resource for finding spatial reference systems not defined in the core set is http://spatialreference.org/
Some commonly used spatial reference systems are: 4326 - WGS 84 Long Lat, 4269 - NAD 83 Long Lat, 3395 - WGS 84 World Mercator, 2163 - US National Atlas Equal Area, and the 60 WGS84 UTM zones. UTM zones are one of the most ideal for measurement, but only cover 6-degree regions. (To determine which UTM zone to use for your area of interest, see the utmzone PostGIS plpgsql helper function.)
US states use State Plane spatial reference systems (meter or feet based) - usually one or 2 exists per state. Most of the meter-based ones are in the core set, but many of the feet-based ones or ESRI-created ones will need to be copied from spatialreference.org.
You can even define non-Earth-based coordinate systems, such as Mars 2000 This Mars coordinate system is non-planar (it's in degrees spheroidal), but you can use it with the geography
type to obtain length and proximity measurements in meters instead of degrees.
Here is an example of loading a custom coordinate system using an unassigned SRID and the PROJ definition for a US-centric Lambert Conformal projection:
INSERT INTO spatial_ref_sys (srid, proj4text) VALUES ( 990000, '+proj=lcc +lon_0=-95 +lat_0=25 +lat_1=25 +lat_2=25 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs' );
You can create a table to store geometry data using the CREATE TABLE SQL statement with a column of type geometry
. The following example creates a table with a geometry column storing 2D (XY) LineStrings in the BC-Albers coordinate system (SRID 3005):
CREATE TABLE roads ( id SERIAL PRIMARY KEY, name VARCHAR(64), geom geometry(LINESTRING,3005) );
The geometry
type supports two optional type modifiers:
the spatial type modifier restricts the kind of shapes and dimensions allowed in the column. The value can be any of the supported geometry subtypes (e.g. POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING, MULTIPOLYGON, GEOMETRYCOLLECTION, etc). The modifier supports coordinate dimensionality restrictions by adding suffixes: Z, M and ZM. For example, a modifier of 'LINESTRINGM' allows only linestrings with three dimensions, and treats the third dimension as a measure. Similarly, 'POINTZM' requires four dimensional (XYZM) data.
the SRID modifier restricts the spatial reference system SRID to a particular number. If omitted, the SRID defaults to 0.
Examples of creating tables with geometry columns:
Create a table holding any kind of geometry with the default SRID:
CREATE TABLE geoms(gid serial PRIMARY KEY, geom geometry );
Create a table with 2D POINT geometry with the default SRID:
CREATE TABLE pts(gid serial PRIMARY KEY, geom geometry(POINT) );
Create a table with 3D (XYZ) POINTs and an explicit SRID of 3005:
CREATE TABLE pts(gid serial PRIMARY KEY, geom geometry(POINTZ,3005) );
Create a table with 4D (XYZM) LINESTRING geometry with the default SRID:
CREATE TABLE lines(gid serial PRIMARY KEY, geom geometry(LINESTRINGZM) );
Create a table with 2D POLYGON geometry with the SRID 4267 (NAD 1927 long lat):
CREATE TABLE polys(gid serial PRIMARY KEY, geom geometry(POLYGON,4267) );
It is possible to have more than one geometry column in a table. This can be specified when the table is created, or a column can be added using the ALTER TABLE SQL statement. This example adds a column that can hold 3D LineStrings:
ALTER TABLE roads ADD COLUMN geom2 geometry(LINESTRINGZ,4326);
The OGC Simple Features Specification for SQL defines the GEOMETRY_COLUMNS
metadata table to describe geometry table structure. In PostGIS geometry_columns
is a view reading from database system catalog tables. This ensures that the spatial metadata information is always consistent with the currently defined tables and views. The view structure is:
\d geometry_columns
View "public.geometry_columns" Column | Type | Modifiers -------------------+------------------------+----------- f_table_catalog | character varying(256) | f_table_schema | character varying(256) | f_table_name | character varying(256) | f_geometry_column | character varying(256) | coord_dimension | integer | srid | integer | type | character varying(30) |
The columns are:
The fully qualified name of the feature table containing the geometry column. There is no PostgreSQL analogue of "catalog" so that column is left blank. For "schema" the PostgreSQL schema name is used (public
is the default).
The name of the geometry column in the feature table.
The coordinate dimension (2, 3 or 4) of the column.
The ID of the spatial reference system used for the coordinate geometry in this table. It is a foreign key reference to the spatial_ref_sys
table (see Section 4.5.1, “SPATIAL_REF_SYS Table”).
The type of the spatial object. To restrict the spatial column to a single type, use one of: POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING, MULTIPOLYGON, GEOMETRYCOLLECTION or corresponding XYM versions POINTM, LINESTRINGM, POLYGONM, MULTIPOINTM, MULTILINESTRINGM, MULTIPOLYGONM, GEOMETRYCOLLECTIONM. For heterogeneous (mixed-type) collections, you can use "GEOMETRY" as the type.
Two of the cases where you may need this are the case of SQL Views and bulk inserts. For bulk insert case, you can correct the registration in the geometry_columns table by constraining the column or doing an alter table. For views, you could expose using a CAST operation. Note, if your column is typmod based, the creation process would register it correctly, so no need to do anything. Also views that have no spatial function applied to the geometry will register the same as the underlying table geometry column.
-- Lets say you have a view created like this CREATE VIEW public.vwmytablemercator AS SELECT gid, ST_Transform(geom, 3395) As geom, f_name FROM public.mytable; -- For it to register correctly -- You need to cast the geometry -- DROP VIEW public.vwmytablemercator; CREATE VIEW public.vwmytablemercator AS SELECT gid, ST_Transform(geom, 3395)::geometry(Geometry, 3395) As geom, f_name FROM public.mytable; -- If you know the geometry type for sure is a 2D POLYGON then you could do DROP VIEW public.vwmytablemercator; CREATE VIEW public.vwmytablemercator AS SELECT gid, ST_Transform(geom,3395)::geometry(Polygon, 3395) As geom, f_name FROM public.mytable;
--Lets say you created a derivative table by doing a bulk insert SELECT poi.gid, poi.geom, citybounds.city_name INTO myschema.my_special_pois FROM poi INNER JOIN citybounds ON ST_Intersects(citybounds.geom, poi.geom); -- Create 2D index on new table CREATE INDEX idx_myschema_myspecialpois_geom_gist ON myschema.my_special_pois USING gist(geom); -- If your points are 3D points or 3M points, -- then you might want to create an nd index instead of a 2D index CREATE INDEX my_special_pois_geom_gist_nd ON my_special_pois USING gist(geom gist_geometry_ops_nd); -- To manually register this new table's geometry column in geometry_columns. -- Note it will also change the underlying structure of the table to -- to make the column typmod based. SELECT populate_geometry_columns('myschema.my_special_pois'::regclass); -- If you are using PostGIS 2.0 and for whatever reason, you -- you need the constraint based definition behavior -- (such as case of inherited tables where all children do not have the same type and srid) -- set optional use_typmod argument to false SELECT populate_geometry_columns('myschema.my_special_pois'::regclass, false);
Although the old-constraint based method is still supported, a constraint-based geometry column used directly in a view, will not register correctly in geometry_columns, as will a typmod one. In this example we define a column using typmod and another using constraints.
CREATE TABLE pois_ny(gid SERIAL PRIMARY KEY, poi_name text, cat text, geom geometry(POINT,4326)); SELECT AddGeometryColumn('pois_ny', 'geom_2160', 2160, 'POINT', 2, false);
If we run in psql
\d pois_ny;
We observe they are defined differently -- one is typmod, one is constraint
Table "public.pois_ny" Column | Type | Modifiers -----------+-----------------------+------------------------------------------------------ gid | integer | not null default nextval('pois_ny_gid_seq'::regclass) poi_name | text | cat | character varying(20) | geom | geometry(Point,4326) | geom_2160 | geometry | Indexes: "pois_ny_pkey" PRIMARY KEY, btree (gid) Check constraints: "enforce_dims_geom_2160" CHECK (st_ndims(geom_2160) = 2) "enforce_geotype_geom_2160" CHECK (geometrytype(geom_2160) = 'POINT'::text OR geom_2160 IS NULL) "enforce_srid_geom_2160" CHECK (st_srid(geom_2160) = 2160)
In geometry_columns, they both register correctly
SELECT f_table_name, f_geometry_column, srid, type FROM geometry_columns WHERE f_table_name = 'pois_ny';
f_table_name | f_geometry_column | srid | type -------------+-------------------+------+------- pois_ny | geom | 4326 | POINT pois_ny | geom_2160 | 2160 | POINT
However -- if we were to create a view like this
CREATE VIEW vw_pois_ny_parks AS SELECT * FROM pois_ny WHERE cat='park'; SELECT f_table_name, f_geometry_column, srid, type FROM geometry_columns WHERE f_table_name = 'vw_pois_ny_parks';
The typmod based geom view column registers correctly, but the constraint based one does not.
f_table_name | f_geometry_column | srid | type ------------------+-------------------+------+---------- vw_pois_ny_parks | geom | 4326 | POINT vw_pois_ny_parks | geom_2160 | 0 | GEOMETRY
This may change in future versions of PostGIS, but for now to force the constraint-based view column to register correctly, you need to do this:
DROP VIEW vw_pois_ny_parks; CREATE VIEW vw_pois_ny_parks AS SELECT gid, poi_name, cat, geom, geom_2160::geometry(POINT,2160) As geom_2160 FROM pois_ny WHERE cat = 'park'; SELECT f_table_name, f_geometry_column, srid, type FROM geometry_columns WHERE f_table_name = 'vw_pois_ny_parks';
f_table_name | f_geometry_column | srid | type ------------------+-------------------+------+------- vw_pois_ny_parks | geom | 4326 | POINT vw_pois_ny_parks | geom_2160 | 2160 | POINT
Once you have created a spatial table, you are ready to upload spatial data to the database. There are two built-in ways to get spatial data into a PostGIS/PostgreSQL database: using formatted SQL statements or using the Shapefile loader.
If spatial data can be converted to a text representation (as either WKT or WKB), then using SQL might be the easiest way to get data into PostGIS. Data can be bulk-loaded into PostGIS/PostgreSQL by loading a text file of SQL INSERT
statements using the psql
SQL utility.
A SQL load file (roads.sql
for example) might look like this:
BEGIN; INSERT INTO roads (road_id, roads_geom, road_name) VALUES (1,'LINESTRING(191232 243118,191108 243242)','Jeff Rd'); INSERT INTO roads (road_id, roads_geom, road_name) VALUES (2,'LINESTRING(189141 244158,189265 244817)','Geordie Rd'); INSERT INTO roads (road_id, roads_geom, road_name) VALUES (3,'LINESTRING(192783 228138,192612 229814)','Paul St'); INSERT INTO roads (road_id, roads_geom, road_name) VALUES (4,'LINESTRING(189412 252431,189631 259122)','Graeme Ave'); INSERT INTO roads (road_id, roads_geom, road_name) VALUES (5,'LINESTRING(190131 224148,190871 228134)','Phil Tce'); INSERT INTO roads (road_id, roads_geom, road_name) VALUES (6,'LINESTRING(198231 263418,198213 268322)','Dave Cres'); COMMIT;
The SQL file can be loaded into PostgreSQL using psql
:
psql -d [database] -f roads.sql
The shp2pgsql
data loader converts Shapefiles into SQL suitable for insertion into a PostGIS/PostgreSQL database either in geometry or geography format. The loader has several operating modes selected by command line flags.
There is also a shp2pgsql-gui
graphical interface with most of the options as the command-line loader. This may be easier to use for one-off non-scripted loading or if you are new to PostGIS. It can also be configured as a plugin to PgAdminIII.
Creates a new table and populates it from the Shapefile. This is the default mode.
Appends data from the Shapefile into the database table. Note that to use this option to load multiple files, the files must have the same attributes and same data types.
Drops the database table before creating a new table with the data in the Shapefile.
Only produces the table creation SQL code, without adding any actual data. This can be used if you need to completely separate the table creation and data loading steps.
Display help screen.
Use the PostgreSQL "dump" format for the output data. This can be combined with -a, -c and -d. It is much faster to load than the default "insert" SQL format. Use this for very large data sets.
Creates and populates the geometry tables with the specified SRID. Optionally specifies that the input shapefile uses the given FROM_SRID, in which case the geometries will be reprojected to the target SRID.
Keep identifiers' case (column, schema and attributes). Note that attributes in Shapefile are all UPPERCASE.
Coerce all integers to standard 32-bit integers, do not create 64-bit bigints, even if the DBF header signature appears to warrant it.
Create a GiST index on the geometry column.
-m a_file_name
Specify a file containing a set of mappings of (long) column names to 10 character DBF column names. The content of the file is one or more lines of two names separated by white space and no trailing or leading space. For example:
COLUMNNAME DBFFIELD1 AVERYLONGCOLUMNNAME DBFFIELD2
Generate simple geometries instead of MULTI geometries. Will only succeed if all the geometries are actually single (I.E. a MULTIPOLYGON with a single shell, or or a MULTIPOINT with a single vertex).
Force the output geometry to have the specified dimensionality. Use the following strings to indicate the dimensionality: 2D, 3DZ, 3DM, 4D.
If the input has fewer dimensions that specified, the output will have those dimensions filled in with zeroes. If the input has more dimensions that specified, the unwanted dimensions will be stripped.
Output WKT format, instead of WKB. Note that this can introduce coordinate drifts due to loss of precision.
Execute each statement on its own, without using a transaction. This allows loading of the majority of good data when there are some bad geometries that generate errors. Note that this cannot be used with the -D flag as the "dump" format always uses a transaction.
Specify encoding of the input data (dbf file). When used, all attributes of the dbf are converted from the specified encoding to UTF8. The resulting SQL output will contain a SET CLIENT_ENCODING to UTF8
command, so that the backend will be able to reconvert from UTF8 to whatever encoding the database is configured to use internally.
NULL geometries handling policy (insert*,skip,abort)
-n Only import DBF file. If your data has no corresponding shapefile, it will automatically switch to this mode and load just the dbf. So setting this flag is only needed if you have a full shapefile set, and you only want the attribute data and no geometry.
Use geography type instead of geometry (requires lon/lat data) in WGS84 long lat (SRID=4326)
Specify the tablespace for the new table. Indexes will still use the default tablespace unless the -X parameter is also used. The PostgreSQL documentation has a good description on when to use custom tablespaces.
Specify the tablespace for the new table's indexes. This applies to the primary key index, and the GIST spatial index if -I is also used.
When used, this flag will prevent the generation of ANALYZE
statements. Without the -Z flag (default behavior), the ANALYZE
statements will be generated.
An example session using the loader to create an input file and loading it might look like this:
# shp2pgsql -c -D -s 4269 -i -I shaperoads.shp myschema.roadstable > roads.sql # psql -d roadsdb -f roads.sql
A conversion and load can be done in one step using UNIX pipes:
# shp2pgsql shaperoads.shp myschema.roadstable | psql -d roadsdb
Spatial data can be extracted from the database using either SQL or the Shapefile dumper. The section on SQL presents some of the functions available to do comparisons and queries on spatial tables.
The most straightforward way of extracting spatial data out of the database is to use a SQL SELECT
query to define the data set to be extracted and dump the resulting columns into a parsable text file:
db=# SELECT road_id, ST_AsText(road_geom) AS geom, road_name FROM roads; road_id | geom | road_name --------+-----------------------------------------+----------- 1 | LINESTRING(191232 243118,191108 243242) | Jeff Rd 2 | LINESTRING(189141 244158,189265 244817) | Geordie Rd 3 | LINESTRING(192783 228138,192612 229814) | Paul St 4 | LINESTRING(189412 252431,189631 259122) | Graeme Ave 5 | LINESTRING(190131 224148,190871 228134) | Phil Tce 6 | LINESTRING(198231 263418,198213 268322) | Dave Cres 7 | LINESTRING(218421 284121,224123 241231) | Chris Way (6 rows)
There will be times when some kind of restriction is necessary to cut down the number of records returned. In the case of attribute-based restrictions, use the same SQL syntax as used with a non-spatial table. In the case of spatial restrictions, the following functions are useful:
This function tells whether two geometries share any space.
This tests whether two geometries are geometrically identical. For example, if 'POLYGON((0 0,1 1,1 0,0 0))' is the same as 'POLYGON((0 0,1 1,1 0,0 0))' (it is).
Next, you can use these operators in queries. Note that when specifying geometries and boxes on the SQL command line, you must explicitly turn the string representations into geometries function. The 312 is a fictitious spatial reference system that matches our data. So, for example:
SELECT road_id, road_name FROM roads WHERE roads_geom='SRID=312;LINESTRING(191232 243118,191108 243242)'::geometry;
The above query would return the single record from the "ROADS_GEOM" table in which the geometry was equal to that value.
To check whether some of the roads passes in the area defined by a polygon:
SELECT road_id, road_name FROM roads WHERE ST_Intersects(roads_geom, 'SRID=312;POLYGON((...))');
The most common spatial query will probably be a "frame-based" query, used by client software, like data browsers and web mappers, to grab a "map frame" worth of data for display.
When using the "&&" operator, you can specify either a BOX3D as the comparison feature or a GEOMETRY. When you specify a GEOMETRY, however, its bounding box will be used for the comparison.
Using a "BOX3D" object for the frame, such a query looks like this:
SELECT ST_AsText(roads_geom) AS geom FROM roads WHERE roads_geom && ST_MakeEnvelope(191232, 243117,191232, 243119,312);
Note the use of the SRID 312, to specify the projection of the envelope.
The pgsql2shp
table dumper connects to the database and converts a table (possibly defined by a query) into a shape file. The basic syntax is:
pgsql2shp [<options>] <database> [<schema>.]<table>
pgsql2shp [<options>] <database> <query>
The commandline options are:
Write the output to a particular filename.
The database host to connect to.
The port to connect to on the database host.
The password to use when connecting to the database.
The username to use when connecting to the database.
In the case of tables with multiple geometry columns, the geometry column to use when writing the shape file.
Use a binary cursor. This will make the operation faster, but will not work if any NON-geometry attribute in the table lacks a cast to text.
Raw mode. Do not drop the gid
field, or escape column names.
filename
Remap identifiers to ten character names. The content of the file is lines of two symbols separated by a single white space and no trailing or leading space: VERYLONGSYMBOL SHORTONE ANOTHERVERYLONGSYMBOL SHORTER etc.
Spatial indexes make using a spatial database for large data sets possible. Without indexing, a search for features requires a sequential scan of every record in the database. Indexing speeds up searching by organizing the data into a structure which can be quickly traversed to find matching records.
The B-tree index method commonly used for attribute data is not very useful for spatial data, since it only supports storing and querying data in a single dimension. Data such as geometry (which has 2 or more dimensions) requires an index method that supports range query across all the data dimensions. One of the key advantages of PostgreSQL for spatial data handling is that it offers several kinds of index methods which work well for multi-dimensional data: GiST, BRIN and SP-GiST indexes.
GiST (Generalized Search Tree) indexes break up data into "things to one side", "things which overlap", "things which are inside" and can be used on a wide range of data-types, including GIS data. PostGIS uses an R-Tree index implemented on top of GiST to index spatial data. GiST is the most commonly-used and versatile spatial index method, and offers very good query performance.
BRIN (Block Range Index) indexes operate by summarizing the spatial extent of ranges of table records. Search is done via a scan of the ranges. BRIN is only appropriate for use for some kinds of data (spatially sorted, with infrequent or no update). But it provides much faster index create time, and much smaller index size.
SP-GiST (Space-Partitioned Generalized Search Tree) is a generic index method that supports partitioned search trees such as quad-trees, k-d trees, and radix trees (tries).
Spatial indexes store only the bounding box of geometries. Spatial queries use the index as a primary filter to quickly determine a set of geometries potentially matching the query condition. Most spatial queries require a secondary filter that uses a spatial predicate function to test a more specific spatial condition. For more information on queying with spatial predicates see Section 5.2, “Using Spatial Indexes”.
See also the PostGIS Workshop section on spatial indexes, and the PostgreSQL manual.
GiST stands for "Generalized Search Tree" and is a generic form of indexing for multi-dimensional data. PostGIS uses an R-Tree index implemented on top of GiST to index spatial data. GiST is the most commonly-used and versatile spatial index method, and offers very good query performance. Other implementations of GiST are used to speed up searches on all kinds of irregular data structures (integer arrays, spectral data, etc) which are not amenable to normal B-Tree indexing. For more information see the PostgreSQL manual.
Once a spatial data table exceeds a few thousand rows, you will want to build an index to speed up spatial searches of the data (unless all your searches are based on attributes, in which case you'll want to build a normal index on the attribute fields).
The syntax for building a GiST index on a "geometry" column is as follows:
CREATE INDEX [nom_index] ON [nom_table] USING GIST ( [colonne_geometrique] );
The above syntax will always build a 2D-index. To get the an n-dimensional index for the geometry type, you can create one using this syntax:
CREATE INDEX [nom_index] ON [nom_table] USING GIST ([colonne_geometrie] gist_geometry_ops_nd);
Building a spatial index is a computationally intensive exercise. It also blocks write access to your table for the time it creates, so on a production system you may want to do in in a slower CONCURRENTLY-aware way:
CREATE INDEX CONCURRENTLY [indexname] ON [tablename] USING GIST ( [geometryfield] );
After building an index, it is sometimes helpful to force PostgreSQL to collect table statistics, which are used to optimize query plans:
VACUUM ANALYZE [table_name] [(column_name)];
BRIN stands for "Block Range Index". It is a general-purpose index method introduced in PostgreSQL 9.5. BRIN is a lossy index method, meaning that a secondary check is required to confirm that a record matches a given search condition (which is the case for all provided spatial indexes). It provides much faster index creation and much smaller index size, with reasonable read performance. Its primary purpose is to support indexing very large tables on columns which have a correlation with their physical location within the table. In addition to spatial indexing, BRIN can speed up searches on various kinds of attribute data structures (integer, arrays etc). For more information see the PostgreSQL manual.
Once a spatial table exceeds a few thousand rows, you will want to build an index to speed up spatial searches of the data. GiST indexes are very performant as long as their size doesn't exceed the amount of RAM available for the database, and as long as you can afford the index storage size, and the cost of index update on write. Otherwise, for very large tables BRIN index can be considered as an alternative.
A BRIN index stores the bounding box enclosing all the geometries contained in the rows in a contiguous set of table blocks, called a block range. When executing a query using the index the block ranges are scanned to find the ones that intersect the query extent. This is efficient only if the data is physically ordered so that the bounding boxes for block ranges have minimal overlap (and ideally are mutually exclusive). The resulting index is very small in size, but is typically less performant for read than a GiST index over the same data.
Building a BRIN index is much less CPU-intensive than building a GiST index. It's common to find that a BRIN index is ten times faster to build than a GiST index over the same data. And because a BRIN index stores only one bounding box for each range of table blocks, it's common to use up to a thousand times less disk space than a GiST index.
You can choose the number of blocks to summarize in a range. If you decrease this number, the index will be bigger but will probably provide better performance.
For BRIN to be effective, the table data should be stored in a physical order which minimizes the amount of block extent overlap. It may be that the data is already sorted appropriately (for instance, if it is loaded from another dataset that is already sorted in spatial order). Otherwise, this can be accomplished by sorting the data by a one-dimensional spatial key. One way to do this is to create a new table sorted by the geometry values (which in recent PostGIS versions uses an efficient Hilbert curve ordering):
CREATE TABLE table_sorted AS SELECT * FROM table ORDER BY geom;
Alternatively, data can be sorted in-place by using a GeoHash as a (temporary) index, and clustering on that index:
CREATE INDEX idx_temp_geohash ON table USING btree (ST_GeoHash( ST_Transform( geom, 4326 ), 20)); CLUSTER table USING idx_temp_geohash;
The syntax for building a BRIN index on a geometry
column is:
CREATE INDEX [indexname] ON [tablename] USING BRIN ( [geome_col] );
The above syntax builds a 2D index. To build a 3D-dimensional index, use this syntax:
CREATE INDEX [indexname] ON [tablename] USING BRIN ([geome_col] brin_geometry_inclusion_ops_3d);
You can also get a 4D-dimensional index using the 4D operator class:
CREATE INDEX [indexname] ON [tablename] USING BRIN ([geome_col] brin_geometry_inclusion_ops_4d);
The above commands use the default number of blocks in a range, which is 128. To specify the number of blocks to summarise in a range, use this syntax
CREATE INDEX [indexname] ON [tablename] USING BRIN ( [geome_col] ) WITH (pages_per_range = [number]);
Keep in mind that a BRIN index only stores one index entry for a large number of rows. If your table stores geometries with a mixed number of dimensions, it's likely that the resulting index will have poor performance. You can avoid this performance penalty by choosing the operator class with the least number of dimensions of the stored geometries
The geography
datatype is supported for BRIN indexing. The syntax for building a BRIN index on a geography column is:
CREATE INDEX [indexname] ON [tablename] USING BRIN ( [geog_col] );
The above syntax builds a 2D-index for geospatial objects on the spheroid.
Currently, only "inclusion support" is provided, meaning that just the &&
, ~
and @
operators can be used for the 2D cases (for both geometry
and geography
), and just the &&&
operator for 3D geometries. There is currently no support for kNN searches.
An important difference between BRIN and other index types is that the database does not maintain the index dynamically. Changes to spatial data in the table are simply appended to the end of the index. This will cause index search performance to degrade over time. The index can be updated by performing a VACUUM
, or by using a special function brin_summarize_new_values(regclass)
. For this reason BRIN may be most appropriate for use with data that is read-only, or only rarely changing. For more information refer to the manual.
To summarize using BRIN for spatial data:
Index build time is very fast, and index size is very small.
Index query time is slower than GiST, but can still be very acceptable.
Requires table data to be sorted in a spatial ordering.
Requires manual index maintenance.
Most appropriate for very large tables, with low or no overlap (e.g. points), which are static or change infrequently.
More effective for queries which return relatively large numbers of data records.
SP-GiST stands for "Space-Partitioned Generalized Search Tree" and is a generic form of indexing for multi-dimensional data types that supports partitioned search trees, such as quad-trees, k-d trees, and radix trees (tries). The common feature of these data structures is that they repeatedly divide the search space into partitions that need not be of equal size. In addition to spatial indexing, SP-GiST is used to speed up searches on many kinds of data, such as phone routing, ip routing, substring search, etc. For more information see the PostgreSQL manual.
As it is the case for GiST indexes, SP-GiST indexes are lossy, in the sense that they store the bounding box enclosing spatial objects. SP-GiST indexes can be considered as an alternative to GiST indexes.
Once a GIS data table exceeds a few thousand rows, an SP-GiST index may be used to speed up spatial searches of the data. The syntax for building an SP-GiST index on a "geometry" column is as follows:
CREATE INDEX [indexname] ON [tablename] USING SPGIST ( [geometryfield] );
The above syntax will build a 2-dimensional index. A 3-dimensional index for the geometry type can be created using the 3D operator class:
CREATE INDEX [indexname] ON [tablename] USING SPGIST ([geometryfield] spgist_geometry_ops_3d);
Building a spatial index is a computationally intensive operation. It also blocks write access to your table for the time it creates, so on a production system you may want to do in in a slower CONCURRENTLY-aware way:
CREATE INDEX CONCURRENTLY [indexname] ON [tablename] USING SPGIST ( [geometryfield] );
After building an index, it is sometimes helpful to force PostgreSQL to collect table statistics, which are used to optimize query plans:
VACUUM ANALYZE [table_name] [(column_name)];
An SP-GiST index can accelerate queries involving the following operators:
<<, &<, &>, >>, <<|, &<|, |&>, |>>, &&, @>, <@, and ~=, for 2-dimensional indexes,
&/&, ~==, @>>, and <<@, for 3-dimensional indexes.
There is no support for kNN searches at the moment.
Ordinarily, indexes invisibly speed up data access: once an index is built, the PostgreSQL query planner automatically decides when to use it to improve query performance. But there are some situations where the planner does not choose to use existing indexes, so queries end up using slow sequential scans instead of a spatial index.
If you find your spatial indexes are not being used, there are a few things you can do:
Examine the query plan and check your query actually computes the thing you need. An erroneous JOIN, either forgotten or to the wrong table, can unexpectedly retrieve table records multiple times. To get the query plan, execute with EXPLAIN
in front of the query.
Make sure statistics are gathered about the number and distributions of values in a table, to provide the query planner with better information to make decisions around index usage. VACUUM ANALYZE will compute both.
You should regularly vacuum your databases anyways. Many PostgreSQL DBAs run VACUUM as an off-peak cron job on a regular basis.
If vacuuming does not help, you can temporarily force the planner to use the index information by using the command SET ENABLE_SEQSCAN TO OFF;. This way you can check whether the planner is at all able to generate an index-accelerated query plan for your query. You should only use this command for debugging; generally speaking, the planner knows better than you do about when to use indexes. Once you have run your query, do not forget to run SET ENABLE_SEQSCAN TO ON; so that the planner will operate normally for other queries.
If SET ENABLE_SEQSCAN TO OFF; helps your query to run faster, your Postgres is likely not tuned for your hardware. If you find the planner wrong about the cost of sequential versus index scans try reducing the value of RANDOM_PAGE_COST
in postgresql.conf
, or use SET RANDOM_PAGE_COST TO 1.1;. The default value for RANDOM_PAGE_COST
is 4.0. Try setting it to 1.1 (for SSD) or 2.0 (for fast magnetic disks). Decreasing the value makes the planner more likely to use index scans.
If SET ENABLE_SEQSCAN TO OFF; does not help your query, the query may be using a SQL construct that the Postgres planner is not yet able to optimize. It may be possible to rewrite the query in a way that the planner is able to handle. For example, a subquery with an inline SELECT may not produce an efficient plan, but could possibly be rewritten using a LATERAL JOIN.
For more information see the Postgres manual section on Query Planning.
La raison d'être des bases de données spatiales est de réaliser à l'intérieur de la base de données des requêtes qui normalement nécessiteraient des fonctionnalités d'un SIG Desktop. Utiliser PostGIS requiert en effet la connaissance de quelles fonctions spatiales sont disponibles, comment les utiliser dans une requête, et de s'assurer de la mise en place adéquate des index, pour une bonne performance.
Les relations spatiales indiquent comment deux géométries interagissent l'une avec l'autre. Elles constituent une fonctionnalité fondamentale pour effectuer des requêtes sur des géométries.
According to the OpenGIS Simple Features Implementation Specification for SQL, "the basic approach to comparing two geometries is to make pair-wise tests of the intersections between the Interiors, Boundaries and Exteriors of the two geometries and to classify the relationship between the two geometries based on the entries in the resulting 'intersection' matrix."
In the theory of point-set topology, the points in a geometry embedded in 2-dimensional space are categorized into three sets:
The boundary of a geometry is the set of geometries of the next lower dimension. For POINT
s, which have a dimension of 0, the boundary is the empty set. The boundary of a LINESTRING
is the two endpoints. For POLYGON
s, the boundary is the linework of the exterior and interior rings.
The interior of a geometry are those points of a geometry that are not in the boundary. For POINT
s, the interior is the point itself. The interior of a LINESTRING
is the set of points between the endpoints. For POLYGON
s, the interior is the areal surface inside the polygon.
The exterior of a geometry is the rest of the space in which the geometry is embedded; in other words, all points not in the interior or on the boundary of the geometry. It is a 2-dimensional non-closed surface.
The Dimensionally Extended 9-Intersection Model (DE-9IM) describes the spatial relationship between two geometries by specifying the dimensions of the 9 intersections between the above sets for each geometry. The intersection dimensions can be formally represented in a 3x3 intersection matrix.
For a geometry g the Interior, Boundary, and Exterior are denoted using the notation I(g), B(g), and E(g). Also, dim(s) denotes the dimension of a set s with the domain of {0,1,2,F}
:
0
=> point
1
=> ligne
2
=> area
F
=> empty set
Using this notation, the intersection matrix for two geometries a and b is:
Interior | Boundary | Exterior | |
---|---|---|---|
Interior | dim( I(a) ∩ I(b) ) | dim( I(a) ∩ B(b) ) | dim( I(a) ∩ E(b) ) |
Boundary | dim( B(a) ∩ I(b) ) | dim( B(a) ∩ B(b) ) | dim( B(a) ∩ E(b) ) |
Exterior | dim( E(a) ∩ I(b) ) | dim( E(a) ∩ B(b) ) | dim( E(a) ∩ E(b) ) |
Visually, for two overlapping polygonal geometries, this looks like:
| ||||||||||||||||||
|
|
Reading from left to right and top to bottom, the intersection matrix is represented as the text string '212101212'.
For more information, refer to:
To make it easy to determine common spatial relationships, the OGC SFS defines a set of named spatial relationship predicates. PostGIS provides these as the functions ST_Contains, ST_Crosses, ST_Disjoint, ST_Equals, ST_Intersects, ST_Overlaps, ST_Touches, ST_Within. It also defines the non-standard relationship predicates ST_Covers, ST_CoveredBy, and ST_ContainsProperly.
Spatial predicates are usually used as conditions in SQL WHERE
or JOIN
clauses. The named spatial predicates automatically use a spatial index if one is available, so there is no need to use the bounding box operator &&
as well. For example:
SELECT city.name, state.name, city.geom FROM city JOIN state ON ST_Intersects(city.geom, state.geom);
For more details and illustrations, see the PostGIS Workshop.
In some cases the named spatial relationships are insufficient to provide a desired spatial filter condition.
![]() For example, consider a linear dataset representing a road network. It may be required to identify all road segments that cross each other, not at a point, but in a line (perhaps to validate some business rule). In this case ST_Crosses does not provide the necessary spatial filter, since for linear features it returns A two-step solution would be to first compute the actual intersection (ST_Intersection) of pairs of road lines that spatially intersect (ST_Intersects), and then check if the intersection's ST_GeometryType is ' Clearly, a simpler and faster solution is desirable. |
![]() A second example is locating wharves that intersect a lake's boundary on a line and where one end of the wharf is up on shore. In other words, where a wharf is within but not completely contained by a lake, intersects the boundary of a lake on a line, and where exactly one of the wharf's endpoints is within or on the boundary of the lake. It is possible to use a combination of spatial predicates to find the required features:
|
These requirements can be met by computing the full DE-9IM intersection matrix. PostGIS provides the ST_Relate function to do this:
SELECT ST_Relate( 'LINESTRING (1 1, 5 5)', 'POLYGON ((3 3, 3 7, 7 7, 7 3, 3 3))' ); st_relate ----------- 1010F0212
To test a particular spatial relationship, an intersection matrix pattern is used. This is the matrix representation augmented with the additional symbols {T,*}
:
T
=> intersection dimension is non-empty; i.e. is in {0,1,2}
*
=> don't care
Using intersection matrix patterns, specific spatial relationships can be evaluated in a more succinct way. The ST_Relate and the ST_RelateMatch functions can be used to test intersection matrix patterns. For the first example above, the intersection matrix pattern specifying two lines intersecting in a line is '1*1***1**':
-- Find road segments that intersect in a line SELECT a.id FROM roads a, roads b WHERE a.id != b.id AND a.geom && b.geom AND ST_Relate(a.geom, b.geom, '1*1***1**');
For the second example, the intersection matrix pattern specifying a line partly inside and partly outside a polygon is '102101FF2':
-- Find wharves partly on a lake's shoreline SELECT a.lake_id, b.wharf_id FROM lakes a, wharfs b WHERE a.geom && b.geom AND ST_Relate(a.geom, b.geom, '102101FF2');
When constructing queries using spatial conditions, for best performance it is important to ensure that a spatial index is used, if one exists (see Section 4.9, “Spatial Indexes”). To do this, a spatial operator or index-aware function must be used in a WHERE
or ON
clause of the query.
Spatial operators include the bounding box operators (of which the most commonly used is &&; see Section 8.10.1, “Opérateurs de Bounding Box” for the full list) and the distance operators used in nearest-neighbor queries (the most common being <->; see Section 8.10.2, “Opérateurs de distance” for the full list.)
Index-aware functions automatically add a bounding box operator to the spatial condition. Index-aware functions include the named spatial relationship predicates ST_Contains, ST_ContainsProperly, ST_CoveredBy, ST_Covers, ST_Crosses, ST_Intersects, ST_Overlaps, ST_Touches, ST_Within, ST_Within, and ST_3DIntersects, and the distance predicates ST_DWithin, ST_DFullyWithin, ST_3DDFullyWithin, and ST_3DDWithin .)
Functions such as ST_Distance do not use indexes to optimize their operation. For example, the following query would be quite slow on a large table:
SELECT geom FROM geom_table WHERE ST_Distance( geom, 'SRID=312;POINT(100000 200000)' ) < 100
This query selects all the geometries in geom_table
which are within 100 units of the point (100000, 200000). It will be slow because it is calculating the distance between each point in the table and the specified point, ie. one ST_Distance()
calculation is computed for every row in the table.
The number of rows processed can be reduced substantially by using the index-aware function ST_DWithin:
SELECT geom FROM geom_table WHERE ST_DWithin( geom, 'SRID=312;POINT(100000 200000)', 100 )
This query selects the same geometries, but it does it in a more efficient way. This is enabled by ST_DWithin()
using the &&
operator internally on an expanded bounding box of the query geometry. If there is a spatial index on geom
, the query planner will recognize that it can use the index to reduce the number of rows scanned before calculating the distance. The spatial index allows retrieving only records with geometries whose bounding boxes overlap the expanded extent and hence which might be within the required distance. The actual distance is then computed to confirm whether to include the record in the result set.
For more information and examples see the PostGIS Workshop.
The examples in this section make use of a table of linear roads, and a table of polygonal municipality boundaries. The definition of the bc_roads
table is:
Column | Type | Description ----------+-------------------+------------------- gid | integer | Unique ID name | character varying | Road Name geom | geometry | Location Geometry (Linestring)
The definition of the bc_municipality
table is:
Column | Type | Description ---------+-------------------+------------------- gid | integer | Unique ID code | integer | Unique ID name | character varying | City / Town Name geom | geometry | Location Geometry (Polygon)
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 vous souffrez de ce problème, utilisez la commande postgresql "EXPLAIN ANALYZE". Pour plus d'informations et les détails techniques, vous pouvez lire le fil de discussion sur la liste de diffusion sur les performances de PostgreSQL : http ://archives.postgresql.org/pgsql-performance/2005-02/msg00030.php
et un fil d'actualités plus récent sur PostGIS https://lists.osgeo.org/pipermail/postgis-devel/2017-June/026209.html
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)) ;
Modifiez maintenant votre requête pour utiliser l'opérateur && contre bbox au lieu de geom_column, comme suit :
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.
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.
Il arrive parfois que vous ayez des données 3D ou 4D dans votre table, mais que vous y accédiez toujours à l'aide des fonctions ST_AsText() ou ST_AsBinary() conformes à OpenGIS qui ne produisent que des géométries 2D. Pour ce faire, elles appellent en interne la fonction ST_Force2D(), qui introduit une surcharge importante pour les géométries de grande taille. Pour éviter cette surcharge, il peut être possible de pré-déposer ces dimensions supplémentaires une fois pour toutes :
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.
Le Minnesota MapServer est un serveur de cartographie Web conforme à la spécification OpenGIS Web Map Service.
La page internet de MapServer est http://mapserver.org.
The OpenGIS Web Map Service specification is at http://www.opengeospatial.org/standards/wms.
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 connexion entre les deux systèmes est rapide et meilleur seront les performances.
Compile and install MapServer, with whatever options you desire, including the "--with-postgis" configuration option.
Dans votre fichier MapFIle, ajoutez une couche PostGIS. Par exemple :
LAYER CONNECTIONTYPE postgis NAME "widehighways" # Connexion à 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 clair 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:
Pour les couches de données PostGIS, cela sera toujours "postgis".
The database connection is governed by the a 'connection string' which is a standard set of keys and values like this (with the default values in <>):
user=<username> password=<password> dbname=<username> hostname=<server> port=<5432>
An empty connection string is still valid, and any of the key/value pairs can be omitted. At a minimum you will generally supply the database name and username to connect with.
The form of this parameter is "<geocolumn> from <tablename> using srid=<srid> using unique <primary key>" where the column is the spatial column to be rendered to the map, the SRID is SRID used by the column and the primary key is the table primary key (or any other uniquely-valued column with an index).
You can omit the "using srid" and "using unique" clauses and MapServer will automatically determine the correct values if possible, but at the cost of running a few extra queries on the server for each map draw.
Putting in a CLOSE_CONNECTION=DEFER if you have multiple layers reuses existing connections instead of closing them. This improves speed. Refer to for MapServer PostGIS Performance Tips for a more detailed explanation.
The filter must be a valid SQL string corresponding to the logic normally following the "WHERE" keyword in a SQL query. So, for example, to render only roads with 6 or more lanes, use a filter of "num_lanes >= 6".
In your spatial database, ensure you have spatial (GiST) indexes built for any the layers you will be drawing.
CREATE INDEX [indexname] ON [tablename] USING GIST ( [geometrycolumn] ) ;
If you will be querying your layers using MapServer you will also need to use the "using unique" clause in your DATA statement.
MapServer requires unique identifiers for each spatial record when doing queries, and the PostGIS module of MapServer uses the unique value you specify in order to provide these unique identifiers. Using the table primary key is the best practice.
The USING
pseudo-SQL clause is used to add some information to help mapserver understand the results of more complex queries. More specifically, when either a view or a subselect is used as the source table (the thing to the right of "FROM" in a DATA
definition) it is more difficult for mapserver to automatically determine a unique identifier for each row and also the SRID for the table. The USING
clause can provide mapserver with these two pieces of information as follows:
DATA "geom FROM ( SELECT table1.geom AS geom, table1.gid AS gid, table2.data AS data FROM table1 LEFT JOIN table2 ON table1.id = table2.id ) AS new_table USING UNIQUE gid USING SRID=4326"
MapServer requires a unique id for each row in order to identify the row when doing map queries. Normally it identifies the primary key from the system tables. However, views and subselects don't automatically have an known unique column. If you want to use MapServer's query functionality, you need to ensure your view or subselect includes a uniquely valued column, and declare it with USING UNIQUE
. For example, you could explicitly select nee of the table's primary key values for this purpose, or any other column which is guaranteed to be unique for the result set.
![]() | |
"Querying a Map" is the action of clicking on a map to ask for information about the map features in that location. Don't confuse "map queries" with the SQL query in a |
PostGIS needs to know which spatial referencing system is being used by the geometries in order to return the correct data back to MapServer. Normally it is possible to find this information in the "geometry_columns" table in the PostGIS database, however, this is not possible for tables which are created on the fly such as subselects and views. So the USING SRID=
option allows the correct SRID to be specified in the DATA
definition.
Lets start with a simple example and work our way up. Consider the following MapServer layer definition:
LAYER CONNECTIONTYPE postgis NAME "roads" CONNECTION "user=theuser password=thepass dbname=thedb host=theserver" DATA "geom from roads" STATUS ON TYPE LINE CLASS STYLE COLOR 0 0 0 END END END
This layer will display all the road geometries in the roads table as black lines.
Now lets say we want to show only the highways until we get zoomed in to at least a 1:100000 scale - the next two layers will achieve this effect:
LAYER CONNECTIONTYPE postgis CONNECTION "user=theuser password=thepass dbname=thedb host=theserver" PROCESSING "CLOSE_CONNECTION=DEFER" DATA "geom from roads" MINSCALE 100000 STATUS ON TYPE LINE FILTER "road_type = 'highway'" CLASS COLOR 0 0 0 END END LAYER CONNECTIONTYPE postgis CONNECTION "user=theuser password=thepass dbname=thedb host=theserver" PROCESSING "CLOSE_CONNECTION=DEFER" DATA "geom from roads" MAXSCALE 100000 STATUS ON TYPE LINE CLASSITEM road_type CLASS EXPRESSION "highway" STYLE WIDTH 2 COLOR 255 0 0 END END CLASS STYLE COLOR 0 0 0 END END END
The first layer is used when the scale is greater than 1:100000, and displays only the roads of type "highway" as black lines. The FILTER
option causes only roads of type "highway" to be displayed.
The second layer is used when the scale is less than 1:100000, and will display highways as double-thick red lines, and other roads as regular black lines.
So, we have done a couple of interesting things using only MapServer functionality, but our DATA
SQL statement has remained simple. Suppose that the name of the road is stored in another table (for whatever reason) and we need to do a join to get it and label our roads.
LAYER CONNECTIONTYPE postgis CONNECTION "user=theuser password=thepass dbname=thedb host=theserver" DATA "geom FROM (SELECT roads.gid AS gid, roads.geom AS geom, road_names.name as name FROM roads LEFT JOIN road_names ON roads.road_name_id = road_names.road_name_id) AS named_roads USING UNIQUE gid USING SRID=4326" MAXSCALE 20000 STATUS ON TYPE ANNOTATION LABELITEM name CLASS LABEL ANGLE auto SIZE 8 COLOR 0 192 0 TYPE truetype FONT arial END END END
This annotation layer adds green labels to all the roads when the scale gets down to 1:20000 or less. It also demonstrates how to use an SQL join in a DATA
definition.
Java clients can access PostGIS "geometry" objects in the PostgreSQL database either directly as text representations or using the JDBC extension objects bundled with PostGIS. In order to use the extension objects, the "postgis.jar" file must be in your CLASSPATH along with the "postgresql.jar" JDBC driver package.
import java.sql.*; import java.util.*; import java.lang.*; import org.postgis.*; public class JavaGIS { public static void main(String[] args) { java.sql.Connection conn; try { /* * Load the JDBC driver and establish a connection. */ Class.forName("org.postgresql.Driver"); String url = "jdbc:postgresql://localhost:5432/database"; conn = DriverManager.getConnection(url, "postgres", ""); /* * Add the geometry types to the connection. Note that you * must cast the connection to the pgsql-specific connection * implementation before calling the addDataType() method. */ ((org.postgresql.PGConnection)conn).addDataType("geometry",Class.forName("org.postgis.PGgeometry")); ((org.postgresql.PGConnection)conn).addDataType("box3d",Class.forName("org.postgis.PGbox3d")); /* * Create a statement and execute a select query. */ Statement s = conn.createStatement(); ResultSet r = s.executeQuery("select geom,id from geomtable"); while( r.next() ) { /* * Retrieve the geometry as an object then cast it to the geometry type. * Print things out. */ PGgeometry geom = (PGgeometry)r.getObject(1); int id = r.getInt(2); System.out.println("Row " + id + ":"); System.out.println(geom.toString()); } s.close(); conn.close(); } catch( Exception e ) { e.printStackTrace(); } } }
The "PGgeometry" object is a wrapper object which contains a specific topological geometry object (subclasses of the abstract class "Geometry") depending on the type: Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon.
PGgeometry geom = (PGgeometry)r.getObject(1); if( geom.getType() == Geometry.POLYGON ) { Polygon pl = (Polygon)geom.getGeometry(); for( int r = 0; r < pl.numRings(); r++) { LinearRing rng = pl.getRing(r); System.out.println("Ring: " + r); for( int p = 0; p < rng.numPoints(); p++ ) { Point pt = rng.getPoint(p); System.out.println("Point: " + p); System.out.println(pt.toString()); } } }
The JavaDoc for the extension objects provides a reference for the various data accessor functions in the geometric objects.
...
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.
![]() | |
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. |
Cette section répertorie les types de données PostgreSQL personnalisés installés par PostGIS pour représenter les données spatiales.
Chaque type de données décrit son comportement de type cast. Un type cast convertit les valeurs d'un type de données en un autre type. PostgreSQL permet de définir le comportement de casting pour les types personnalisés, ainsi que les fonctions utilisées pour convertir les valeurs du type. Les cast peuvent avoir un comportement automatique, ce qui permet la conversion automatique d'un argument de fonction vers un type supporté par la fonction.
Certains castings ont un comportement explicite, ce qui signifie que le cast doit être spécifié en utilisant la syntaxe CAST(myval As sometype)
ou myval::sometype
. Le casting explicite évite le problème des casts ambigus, qui peuvent se produire lors de l'utilisation d'une fonction surchargée qui ne supporte pas un type donné. Par exemple, une fonction peut accepter un box2d ou un box3d, mais pas un geometry. Puisque la géométrie a un cast automatique vers les deux types de boîtes, cela produit une erreur de "fonction ambiguë". Pour éviter cette erreur, utilisez un cast explicite vers le type de boîte souhaité.
Tous les types de données peuvent être transformés en text
, il n'est donc pas nécessaire de le spécifier explicitement.
box2d — Le type représentant une boîte de délimitation bidimensionnelle.
box2d
est un type de données spatiales utilisé pour représenter la boîte de délimitation bidimensionnelle entourant une géométrie ou une collection de géométries. Par exemple, la fonction d'agrégation ST_Extent renvoie un objet box2d
.
La représentation contient les valeurs xmin, ymin, xmax, ymax
. Ce sont les valeurs minimales et maximales des étendues X et Y.
Les objets box2d
ont une représentation textuelle qui ressemble à BOX(1 2,5 6)
.
box3d — Le type représentant une boîte de délimitation tridimensionnelle.
box3d
est un type de données spatiales PostGIS utilisé pour représenter la boîte de délimitation tridimensionnelle entourant une géométrie ou une collection de géométries. Par exemple, la fonction d'agrégation ST_3DExtent renvoie un objet box3d
.
La représentation contient les valeurs xmin, ymin, zmin, xmax, ymax, zmax
. Il s'agit des valeurs minimales et maximales des étendues X, Y et Z.
Les objets box3d
ont une représentation textuelle qui ressemble à BOX3D(1 2 3,5 6 5)
.
geometry — Le type représentant les caractéristiques spatiales avec des systèmes de coordonnées planaires.
géométrie
est un type de données spatiales fondamental de PostGIS utilisé pour représenter une caractéristique dans des systèmes de coordonnées planes (euclidiennes).
Toutes les opérations spatiales sur la géométrie utilisent les unités du système de référence spatiale dans lequel se trouve la géométrie.
geometry_dump — Un type composite utilisé pour décrire les parties d'une géométrie complexe.
geometry_dump
est un type de données composite contenant les champs :
geom
- une géométrie représentant un composant de la géométrie explosée. Le type de géométrie dépend de la fonction d'origine.
path[]
- un tableau d'entiers qui définit le chemin de navigation dans la géométrie explosée vers le composant geom
. Le tableau de chemins est basé sur 1 (c'est-à-dire que path[1]
est le premier élément)
Il est utilisé par la famille de fonctions ST_Dump*
comme type de sortie pour exploser une géométrie complexe en ses parties constitutives.
geography — Le type représentant les entités spatiales avec des systèmes de coordonnées géodésiques (ellipsoïdales).
geography
est un type de données spatiales utilisé pour représenter une entité dans les systèmes de coordonnées géodésiques. Les systèmes de coordonnées géodésiques modélisent la terre à l'aide d'un ellipsoïde.
Les opérations spatiales sur le type geography fournissent des résultats plus précis en prenant en compte le modèle ellipsoïdal.
AddGeometryColumn — Ajoute une colonne de géométrie à une table existante.
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)
;
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.
![]() | |
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 à : Changement : 2.0.0 Si l'ancien mécanisme basé sur les contraintes est nécessaire, utiliser le paramètre |
![]() | |
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.6.3, “Manually Registering Geometry Columns”. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
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.
-- Create schema to hold data CREATE SCHEMA my_schema; -- Create a new simple PostgreSQL table CREATE TABLE my_schema.my_spatial_table (id serial); -- Describing the table shows a simple table with a single "id" column. postgis=# \d my_schema.my_spatial_table Table "my_schema.my_spatial_table" Column | Type | Modifiers --------+---------+------------------------------------------------------------------------- id | integer | not null default nextval('my_schema.my_spatial_table_id_seq'::regclass) -- Add a spatial column to the table SELECT AddGeometryColumn ('my_schema','my_spatial_table','geom',4326,'POINT',2); -- Add a point using the old constraint based behavior SELECT AddGeometryColumn ('my_schema','my_spatial_table','geom_c',4326,'POINT',2, false); --Add a curvepolygon using old constraint behavior SELECT AddGeometryColumn ('my_schema','my_spatial_table','geomcp_c',4326,'CURVEPOLYGON',2, false); -- Describe the table again reveals the addition of a new geometry columns. \d my_schema.my_spatial_table addgeometrycolumn ------------------------------------------------------------------------- my_schema.my_spatial_table.geomcp_c SRID:4326 TYPE:CURVEPOLYGON DIMS:2 (1 row) Table "my_schema.my_spatial_table" Column | Type | Modifiers ----------+----------------------+------------------------------------------------------------------------- id | integer | not null default nextval('my_schema.my_spatial_table_id_seq'::regclass) geom | geometry(Point,4326) | geom_c | geometry | geomcp_c | geometry | Check constraints: "enforce_dims_geom_c" CHECK (st_ndims(geom_c) = 2) "enforce_dims_geomcp_c" CHECK (st_ndims(geomcp_c) = 2) "enforce_geotype_geom_c" CHECK (geometrytype(geom_c) = 'POINT'::text OR geom_c IS NULL) "enforce_geotype_geomcp_c" CHECK (geometrytype(geomcp_c) = 'CURVEPOLYGON'::text OR geomcp_c IS NULL) "enforce_srid_geom_c" CHECK (st_srid(geom_c) = 4326) "enforce_srid_geomcp_c" CHECK (st_srid(geomcp_c) = 4326) -- geometry_columns view also registers the new columns -- SELECT f_geometry_column As col_name, type, srid, coord_dimension As ndims FROM geometry_columns WHERE f_table_name = 'my_spatial_table' AND f_table_schema = 'my_schema'; col_name | type | srid | ndims ----------+--------------+------+------- geom | Point | 4326 | 2 geom_c | Point | 4326 | 2 geomcp_c | CurvePolygon | 4326 | 2
DropGeometryColumn — Supprime une colonne géométrique d'une table spatiale.
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)
;
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 OGC Simple Features
Implementation Specification for SQL 1.1.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
![]() | |
Changement : 2.0.0 Fonction 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 être supprimée d'une table comme tout autre colonne en utilisant |
SELECT DropGeometryColumn ('my_schema','my_spatial_table','geom'); ----RESULT output --- dropgeometrycolumn ------------------------------------------------------ my_schema.my_spatial_table.geom effectively removed. -- In PostGIS 2.0+ the above is also equivalent to the standard -- the standard alter table. Both will deregister from geometry_columns ALTER TABLE my_schema.my_spatial_table DROP column geom;
DropGeometryTable — Supprime une table et toutes ces références dans geometry_columns.
boolean DropGeometryTable(
varchar table_name)
;
boolean DropGeometryTable(
varchar schema_name, varchar table_name)
;
boolean DropGeometryTable(
varchar catalog_name, varchar schema_name, varchar table_name)
;
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.
![]() | |
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 |
Find_SRID — Returns the SRID defined for a geometry column.
integer Find_SRID(
varchar a_schema_name, varchar a_table_name, varchar a_geomfield_name)
;
Returns the integer SRID of the specified geometry column by searching through the GEOMETRY_COLUMNS table. If the geometry column has not been properly added (e.g. with the AddGeometryColumn function), this function will not work.
Populate_Geometry_Columns — Ensures geometry columns are defined with type modifiers or have appropriate spatial constraints.
text Populate_Geometry_Columns(
boolean use_typmod=true)
;
int Populate_Geometry_Columns(
oid relation_oid, boolean use_typmod=true)
;
S'assure que les colonnes géométriques ont des modificateurs de type ou des contraintes spatiales appropriés pour garantir qu'elles sont enregistrées correctement dans la vue geometry_columns
. Par défaut, convertira toutes les colonnes géométriques sans modificateur de type en colonnes avec modificateur de type.
Pour conserver la rétro compatibilité et pour des besoins particuliers comme par exemple des tables héritées ayant des types géométriques différents, l'ancien mécanisme est toujours supporté. Si ce mécanisme est nécessaire, le nouveau paramètre optionnel doit être mis à false : use_typmod=false
. Avec cette valeur, la colonne géométrique sera créée sans modificateur de type mais 3 contraintes seront définies. Cela signifie concrètement que chaque colonne géométrique de la table aura au moins 3 contraintes :
enforce_dims_geom
- garantit que chaque géométrie a la même dimension (voir ST_NDims)
enforce_geotype_geom
- garantit que chaque géométrie est du même type (voir 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 le oid
d'une vue est fourni, comme avec un oid de table, cette fonction essaie de déterminer le srid, la dimension et le type de toutes les géométries de la vue, en insérant les entrées appropriées dans la table geometry_columns
, mais rien n'est fait pour appliquer 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.
CREATE TABLE public.myspatial_table(gid serial, geom geometry); INSERT INTO myspatial_table(geom) VALUES(ST_GeomFromText('LINESTRING(1 2, 3 4)',4326) ); -- This will now use typ modifiers. For this to work, there must exist data SELECT Populate_Geometry_Columns('public.myspatial_table'::regclass); populate_geometry_columns -------------------------- 1 \d myspatial_table Table "public.myspatial_table" Column | Type | Modifiers --------+---------------------------+--------------------------------------------------------------- gid | integer | not null default nextval('myspatial_table_gid_seq'::regclass) geom | geometry(LineString,4326) |
-- This will change the geometry columns to use constraints if they are not typmod or have constraints already. --For this to work, there must exist data CREATE TABLE public.myspatial_table_cs(gid serial, geom geometry); INSERT INTO myspatial_table_cs(geom) VALUES(ST_GeomFromText('LINESTRING(1 2, 3 4)',4326) ); SELECT Populate_Geometry_Columns('public.myspatial_table_cs'::regclass, false); populate_geometry_columns -------------------------- 1 \d myspatial_table_cs Table "public.myspatial_table_cs" Column | Type | Modifiers --------+----------+------------------------------------------------------------------ gid | integer | not null default nextval('myspatial_table_cs_gid_seq'::regclass) geom | geometry | Check constraints: "enforce_dims_geom" CHECK (st_ndims(geom) = 2) "enforce_geotype_geom" CHECK (geometrytype(geom) = 'LINESTRING'::text OR geom IS NULL) "enforce_srid_geom" CHECK (st_srid(geom) = 4326)
UpdateGeometrySRID — Updates the SRID of all features in a geometry column, and the table metadata.
text UpdateGeometrySRID(
varchar table_name, varchar column_name, integer srid)
;
text UpdateGeometrySRID(
varchar schema_name, varchar table_name, varchar column_name, integer srid)
;
text UpdateGeometrySRID(
varchar catalog_name, varchar schema_name, varchar table_name, varchar column_name, integer srid)
;
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
Insert geometries into roads table with a SRID set already using EWKT format:
COPY roads (geom) FROM STDIN; SRID=4326;LINESTRING(0 0, 10 10) SRID=4326;LINESTRING(10 10, 15 0) \.
Cela va changer le srid de la table roads à 4326 quelle que soit sa valeur avant :
SELECT UpdateGeometrySRID('roads','geom',4326) ;
L'exemple précédent est équivalent à cette requête DDL :
ALTER TABLE roads ALTER COLUMN geom TYPE geometry(MULTILINESTRING, 4326) USING ST_SetSRID(geom,4326);
Si vous vous êtes trompé de projection (ou si vous l'avez introduite en tant qu'inconnue) dans le chargement et que vous voulez transformer en mercator web en une seule fois, vous pouvez le faire avec DDL mais il n'y a pas de fonction de gestion PostGIS équivalente pour le faire en une seule fois.
ALTER TABLE roads ALTER COLUMN geom TYPE geometry(MULTILINESTRING, 3857) USING ST_Transform(ST_SetSRID(geom,4326),3857) ;
ST_Collect — Crée une géométrie GeometryCollection ou Multi à partir d'un ensemble de géométries.
geometry ST_Collect(
geometry g1, geometry g2)
;
geometry ST_Collect(
geometry[] g1_array)
;
geometry ST_Collect(
geometry set g1field)
;
Rassemble les géométries dans une collection de géométries. Le résultat est soit un Multi*, soit une GeometryCollection, selon que les géométries d'entrée ont des types identiques ou différents (homogènes ou hétérogènes). Les géométries d'entrée restent inchangées dans la collection.
Variante 1: accepte géométries en entrée
Variante 2: accepte un tableau de géométries
Variante 3: fonction agrégée acceptant un ensemble de géométries.
![]() | |
Si l'une des géométries en entrée est une collection (Multi* ou GeometryCollection), ST_Collect renvoie une GeometryCollection (puisque c'est le seul type qui peut contenir des collections imbriquées). Pour éviter cela, utilisez ST_Dump dans une sous-requête pour développer les collections d'entrée en leurs éléments atomiques (voir l'exemple ci-dessous). |
![]() | |
ST_Collect et ST_Union semblent similaires, mais fonctionnent en fait assez différemment. ST_Collect agrège les géométries dans une collection sans les modifier en aucune façon. ST_Union fusionne géométriquement les géométries lorsqu'elles se chevauchent, et divise les lignes aux intersections. Elle peut retourner des géométries uniques lorsqu'elle dissout les frontières. |
Disponibilité : 1.4.0 - ST_Collect(geomarray) a été introduit. ST_Collect a été amélioré pour gérer plus de géométries plus rapidement.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
Collectez les points 2D.
SELECT ST_AsText( ST_Collect( ST_GeomFromText('POINT(1 2)'), ST_GeomFromText('POINT(-2 3)') )) ; st_astext ---------- MULTIPOINT((1 2),(-2 3))
Collectez les points 3D.
SELECT ST_AsEWKT( ST_Collect( ST_GeomFromEWKT('POINT(1 2 3)'), ST_GeomFromEWKT('POINT(1 2 4)') ) ) ; st_asewkt ------------------------- MULTIPOINT(1 2 3,1 2 4)
Collectez les courbes.
SELECT ST_AsText( ST_Collect( 'CIRCULARSTRING(220268 150415,220227 150505,220227 150406)', 'CIRCULARSTRING(220227 150406,2220227 150407,220227 150406)')) ; st_astext ------------------------------------------------------------------------------------ MULTICURVE(CIRCULARSTRING(220268 150415,220227 150505,220227 150406), CIRCULARSTRING(220227 150406,2220227 150407,220227 150406))
Utilisation d'un constructeur de tableau pour une sous-requête.
SELECT ST_Collect( ARRAY( SELECT geom FROM sometable ) ) ;
Utilisation d'un constructeur de tableau pour les valeurs.
SELECT ST_AsText( ST_Collect( ARRAY[ ST_GeomFromText('LINESTRING(1 2, 3 4)'), ST_GeomFromText('LINESTRING(3 4, 4 5)') ] )) As wktcollect ; --wkt collect -- MULTILINESTRING((1 2,3 4),(3 4,4 5))
ST_LineFromMultiPoint — Crée une LineString à partir d'une géométrie MultiPoint.
geometry ST_LineFromMultiPoint(
geometry aMultiPoint)
;
Crée une LineString à partir d'une géométrie MultiPoint.
Utilisez ST_MakeLine pour créer des lignes à partir des entrées Point ou LineString.
This function supports 3d and will not drop the z-index.
ST_MakeEnvelope — Crée un polygone rectangulaire à partir des coordonnées minimales et maximales.
geometry ST_MakeEnvelope(
float xmin, float ymin, float xmax, float ymax, integer srid=unknown)
;
Crée un polygone rectangulaire à partir des valeurs minimales et maximales de X et Y. Les valeurs entrées doivent être dans le système de référence spatiale spécifié par le SRID. Si aucun SRID n'est spécifié, le système de référence spatiale inconnu (SRID 0) est utilisé.
Disponibilité : 1.5
Amélioré : 2.0 : La possibilité de spécifier une enveloppe sans spécifier un SRID a été introduite.
ST_MakeLine — Crée une LineString à partir de géométries Point, MultiPoint ou LineString.
geometry ST_MakeLine(
geometry geom1, geometry geom2)
;
geometry ST_MakeLine(
geometry[] geoms_array)
;
geometry ST_MakeLine(
geometry set geoms)
;
Crée une LineString contenant les points des géométries Point, MultiPoint ou LineString. Les autres types de géométrie provoquent une erreur.
Variante 1: accepte géométries en entrée
Variante 2: accepte un tableau de géométries
Variante 3: fonction agrégée acceptant un ensemble de géométries. Pour garantir l'ordre des géométries d'entrée, utilisez ORDER BY
dans l'appel de fonction, ou une sous-requête avec une clause ORDER BY
.
Les nœuds répétés au début des LineStrings d'entrée sont réduits à un seul point. Les points répétés dans les entrées Point et MultiPoint ne sont pas réduits. ST_RemoveRepeatedPoints peut être utilisé pour réduire les points répétés de la LineString de sortie.
This function supports 3d and will not drop the z-index.
Disponibilité : 2.3.0 - La prise en charge des éléments d'entrée MultiPoint a été introduite
Disponibilité : 2.0.0 - La prise en charge des éléments d'entrée LineString a été introduite
Disponibilité : 1.4.0 - création de ST_MakeLine(geomarray). L'agrégat spatial ST_MakeLine amélioré pour supporter plus de points plus rapidement.
Créez une ligne composée de deux points.
SELECT ST_AsText( ST_MakeLine(ST_Point(1,2), ST_Point(3,4)) ) ; st_astext --------------------- LINESTRING(1 2,3 4)
Créer une ligne 3D à partir de deux points 3D.
SELECT ST_AsEWKT( ST_MakeLine(ST_MakePoint(1,2,3), ST_MakePoint(3,4,5) )) ; st_asewkt ------------------------- LINESTRING(1 2 3,3 4 5)
Crée une ligne à partir de deux LineStrings disjointes.
select ST_AsText( ST_MakeLine( 'LINESTRING(0 0, 1 1)', 'LINESTRING(2 2, 3 3)' ) ) ; st_astext ----------------------------- LINESTRING(0 0,1 1,2 2,3 3)
Créer une ligne à partir d'un tableau formé par une sous-requête avec ordonnancement.
SELECT ST_MakeLine( ARRAY( SELECT ST_Centroid(geom) FROM visit_locations ORDER BY visit_time) ) ;
Créer une ligne 3D à partir d'un tableau de points 3D
SELECT ST_AsEWKT( ST_MakeLine( ARRAY[ ST_MakePoint(1,2,3), ST_MakePoint(3,4,5), ST_MakePoint(6,6,6) ] )) ; st_asewkt ------------------------- LINESTRING(1 2 3,3 4 5,6 6 6)
Cet exemple interroge des séquences temporelles de points GPS à partir d'un ensemble de pistes et crée un enregistrement pour chaque piste. Les géométries résultantes sont des LineStrings composées des points GPS dans l'ordre de leur déplacement.
L'utilisation de l'agrégat ORDER BY
fournit une LineString correctement ordonnée.
SELECT gps.track_id, ST_MakeLine(gps.geom ORDER BY gps_time) As geom FROM gps_points As gps GROUP BY track_id ;
Avant PostgreSQL 9, l'ordre dans une sous-requête peut être utilisé. Cependant, il arrive que le plan de requête ne respecte pas l'ordre de la sous-requête.
SELECT gps.track_id, ST_MakeLine(gps.geom) As geom FROM ( SELECT track_id, gps_time, geom FROM gps_points ORDER BY track_id, gps_time ) As gps GROUP BY track_id ;
ST_MakePoint — Crée un point 2D, 3DZ ou 4D.
geometry ST_MakePoint(
float x, float y)
;
geometry ST_MakePoint(
float x, float y, float z)
;
geometry ST_MakePoint(
float x, float y, float z, float m)
;
Crée une géométrie de points 2D, 3D Z ou 4D ZM.
Utilisez ST_MakePointM pour créer des points avec des coordonnées XYM.
Bien que non conforme à l'OGC, ST_MakePoint
est plus rapide et plus précis que ST_GeomFromText et ST_PointFromText. Elle est également plus facile à utiliser pour les valeurs de coordonnées numériques.
![]() | |
Pour les coordonnées géodésiques, |
This function supports 3d and will not drop the z-index.
--Return point with unknown SRID SELECT ST_MakePoint(-71.1043443253471, 42.3150676015829) ; --Return point marked as WGS 84 long lat SELECT ST_SetSRID(ST_MakePoint(-71.1043443253471, 42.3150676015829),4326) ; --Return a 3D point (e.g. has altitude) SELECT ST_MakePoint(1, 2,1.5) ; --Get z of point SELECT ST_Z(ST_MakePoint(1, 2,1.5)) ; result ------- 1.5
ST_MakePointM — Crée un point à partir des valeurs X, Y et M.
geometry ST_MakePointM(
float x, float y, float m)
;
Crée un point avec des coordonnées X, Y et M (mesure).
Utilisez ST_MakePoint pour créer des points avec des coordonnées XY, XYZ ou XYZM.
![]() | |
Pour les coordonnées géodésiques, |
Créer un point avec un SRID inconnu.
SELECT ST_AsEWKT( ST_MakePointM(-71.1043443253471, 42.3150676015829, 10) ) ; st_asewkt ----------------------------------------------- POINTM(-71.1043443253471 42.3150676015829 10)
Créer un point avec une mesure dans le système de coordonnées géodésiques WGS 84.
SELECT ST_AsEWKT( ST_SetSRID( ST_MakePointM(-71.104, 42.315, 10), 4326)) ; st_asewkt --------------------------------------------------------- SRID=4326;POINTM(-71.104 42.315 10)
Obtenir la mesure du point créé.
SELECT ST_M( ST_MakePointM(-71.104, 42.315, 10) ) ; result ------- 10
ST_MakePolygon — Crée un polygone à partir d'une collection et d'une liste facultative de trous.
geometry ST_MakePolygon(
geometry linestring)
;
geometry ST_MakePolygon(
geometry outerlinestring, geometry[] interiorlinestrings)
;
Crée un polygone formé par la collection donnée et un tableau optionnel de trous. Les géométries d'entrée doivent être des LineStrings (anneaux) fermés.
Variante 1: Accepte une collection de LineString.
Variante 2: Accepte une collection de LineString et un tableau de LineStrings internes (trous). Un tableau de géométrie peut être construit en utilisant les constructions PostgreSQL array_agg(), ARRAY[] ou ARRAY().
![]() | |
Cette fonction n'accepte pas les MultiLineStrings. Utilisez ST_LineMerge pour générer une LineString, ou ST_Dump pour extraire les LineStrings. |
This function supports 3d and will not drop the z-index.
Créez un polygone à partir d'une LineString 2D.
SELECT ST_MakePolygon( ST_GeomFromText('LINESTRING(75 29,77 29,77 29, 75 29)')) ;
Créez un polygone à partir d'une LineString ouverte, en utilisant ST_StartPoint et ST_AddPoint pour la fermer.
SELECT ST_MakePolygon( ST_AddPoint(foo.open_line, ST_StartPoint(foo.open_line)) ) FROM ( SELECT ST_GeomFromText('LINESTRING(75 29,77 29,77 29, 75 29)') As open_line) As foo ;
Créer un polygone à partir d'une LineString 3D
SELECT ST_AsEWKT( ST_MakePolygon( 'LINESTRING(75.15 29.53 1,77 29 1,77.6 29.5 1, 75.15 29.53 1)')) ; st_asewkt ----------- POLYGON((75.15 29.53 1,77 29 1,77.6 29.5 1,75.15 29.53 1))
Créer un polygone à partir d'une LineString avec des mesures
SELECT ST_AsEWKT( ST_MakePolygon( 'LINESTRINGM(75.15 29.53 1,77 29 1,77.6 29.5 2, 75.15 29.53 2)' )) ; st_asewkt ---------- POLYGONM((75.15 29.53 1,77 29 1,77.6 29.5 2,75.15 29.53 2))
Créer un polygone en forme de donut avec un trou supplémentaire
SELECT ST_MakePolygon( ST_ExteriorRing( ST_Buffer(ring.line,10)), ARRAY[ ST_Translate(ring.line, 1, 1), ST_ExteriorRing(ST_Buffer(ST_Point(20,20),1)) ] ) FROM (SELECT ST_ExteriorRing( ST_Buffer(ST_Point(10,10),10,10)) AS line ) AS ring ;
Créez un ensemble de frontières de province avec des trous représentant des lacs. L'entrée est un tableau de polygones/multipolygones de province et un tableau de lignes d'eau. Les lignes formant des lacs sont déterminées en utilisant ST_IsClosed. Le réseau de la province est extrait en utilisant ST_Boundary. Comme requis par ST_MakePolygon
, la frontière est forcée à être une seule LineString en utilisant ST_LineMerge. (Cependant, notez que si une province a plus d'une région ou a des îles, cela produira un polygone invalide). L'utilisation d'un LEFT JOIN garantit que toutes les provinces sont incluses, même si elles n'ont pas de lacs.
![]() | |
La construction CASE est utilisée car le passage d'un tableau nul dans ST_MakePolygon entraîne une valeur de retour NULL. |
SELECT p.gid, p.province_name, CASE WHEN array_agg(w.geom) IS NULL THEN p.geom ELSE ST_MakePolygon( ST_LineMerge(ST_Boundary(p.geom)), array_agg(w.geom)) END FROM provinces p LEFT JOIN waterlines w ON (ST_Within(w.geom, p.geom) AND ST_IsClosed(w.geom)) GROUP BY p.gid, p.province_name, p.geom ;
Une autre technique consiste à utiliser une sous-requête corrélée et le constructeur ARRAY() qui convertit un ensemble de lignes en un tableau.
SELECT p.gid, p.province_name, CASE WHEN EXISTS( SELECT w.geom FROM waterlines w WHERE ST_Within(w.geom, p.geom) AND ST_IsClosed(w.geom)) THEN ST_MakePolygon( ST_LineMerge(ST_Boundary(p.geom)), ARRAY( SELECT w.geom FROM waterlines w WHERE ST_Within(w.geom, p.geom) AND ST_IsClosed(w.geom))) ELSE p.geom END AS geom FROM provinces p ;
ST_Point — Crée un point avec des valeurs X, Y et SRID.
geometry ST_Point(
float x, float y)
;
geometry ST_Point(
float x, float y, integer srid=unknown)
;
Renvoie un point avec les valeurs de coordonnées X et Y données. C'est l'équivalent SQL-MM de ST_MakePoint qui ne prend que X et Y.
![]() | |
Pour les coordonnées géodésiques, |
Amélioration : 3.2.0 srid a été ajouté comme argument optionnel supplémentaire. Les anciennes installations nécessitent une combinaison avec ST_SetSRID pour marquer le srid sur la géométrie.
This method implements the SQL/MM specification. SQL-MM 3 : 6.1.2
SELECT ST_Point( -71.104, 42.315) ;
SELECT ST_SetSRID(ST_Point( -71.104, 42.315),4326) ;
Nouveau dans 3.2.0 : en spécifiant un SRID
SELECT ST_Point( -71.104, 42.315, 4326) ;
Syntaxe pré-PostGIS 3.2
SELECT CAST( ST_SetSRID(ST_Point( -71.104, 42.315), 4326) AS geography) ;
3.2 et plus vous pouvez inclure le srid
SELECT CAST( ST_Point( -71.104, 42.315, 4326) AS geography) ;
PostgreSQL fournit également l'abréviation ::
pour le casting
SELECT ST_Point( -71.104, 42.315, 4326)::geography ;
Si les coordonnées du point ne sont pas dans un système de coordonnées géodésiques (tel que WGS84), elles doivent être reprojetées avant d'être projetées dans une géographie. Dans cet exemple, un point en pieds du plan de l'État de Pennsylvanie (SRID 2273) est projeté en WGS84 (SRID 4326).
SELECT ST_Transform(ST_SetSRID( ST_Point( 3637510, 3014852 ), 2273), 4326)::geography ;
ST_PointZ — Crée un point avec des valeurs X, Y, Z et SRID.
geometry ST_PointZ(
float x, float y, float z, integer srid=unknown)
;
Renvoie un point avec les valeurs de coordonnées X, Y et Z données, et éventuellement un numéro SRID.
Amélioration : 3.2.0 srid a été ajouté comme argument optionnel supplémentaire. Les anciennes installations nécessitent une combinaison avec ST_SetSRID pour marquer le srid sur la géométrie.
ST_PointM — Crée un point avec des valeurs X, Y, M et SRID.
geometry ST_PointM(
float x, float y, float m, integer srid=unknown)
;
Renvoie un point avec les valeurs de coordonnées X, Y et M données, et éventuellement un numéro SRID.
Amélioration : 3.2.0 srid a été ajouté comme argument optionnel supplémentaire. Les anciennes installations nécessitent une combinaison avec ST_SetSRID pour marquer le srid sur la géométrie.
ST_PointZM — Crée un point avec des valeurs X, Y, Z, M et SRID.
geometry ST_PointZM(
float x, float y, float z, float m, integer srid=unknown)
;
Renvoie un point avec les valeurs de coordonnées X, Y, Z et M données, et éventuellement un numéro SRID.
Amélioration : 3.2.0 srid a été ajouté comme argument optionnel supplémentaire. Les anciennes installations nécessitent une combinaison avec ST_SetSRID pour marquer le srid sur la géométrie.
ST_Polygon — Crée un polygone à partir d'une LineString avec un SRID spécifié.
geometry ST_Polygon(
geometry lineString, integer srid)
;
Renvoie un polygone construit à partir de la LineString donnée et définit le système de référence spatiale à partir du srid
.
ST_Polygon est similaire à la variante 1 de ST_MakePolygon avec l'ajout de la définition du SRID.
Pour créer des polygones avec des trous, utilisez ST_MakePolygon la variante 2 et ensuite ST_SetSRID.
![]() | |
Cette fonction n'accepte pas les MultiLineStrings. Utilisez ST_LineMerge pour générer une LineString, ou ST_Dump pour extraire les LineStrings. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3 : 8.3.2
This function supports 3d and will not drop the z-index.
Créer un polygone 2D.
SELECT ST_AsText( ST_Polygon('LINESTRING(75 29, 77 29, 77 29, 75 29)'::geometry, 4326) ) ; -- résultat -- POLYGON((75 29, 77 29, 77 29, 75 29))
Créer un polygone 3D.
SELECT ST_AsEWKT( ST_Polygon( ST_GeomFromEWKT('LINESTRING(75 29 1, 77 29 2, 77 29 3, 75 29 1)'), 4326) ) ; -- résultat -- SRID=4326;POLYGON((75 29 1, 77 29 2, 77 29 3, 75 29 1))
ST_TileEnvelope — Crée un polygone rectangulaire dans Web Mercator (SRID:3857) en utilisant le système de tuiles XYZ.
geometry ST_TileEnvelope(
integer tileZoom, integer tileX, integer tileY, geometry bounds=SRID=3857;LINESTRING(-20037508.342789 -20037508.342789,20037508.342789 20037508.342789), float margin=0.0)
;
Crée un polygone rectangulaire donnant l'étendue d'une tuile dans le système de tuiles XYZ. La tuile est spécifiée par le niveau de zoom Z et l'indice XY de la tuile dans la grille à ce niveau. Peut être utilisé pour définir les limites de la tuile requises par ST_AsMVTGeom pour convertir la géométrie dans l'espace de coordonnées de la tuile MVT.
Par défaut, l'enveloppe de la tuile est dans le système de coordonnées Web Mercator (SRID:3857) utilisant la plage standard du système Web Mercator (-20037508.342789, 20037508.342789). Il s'agit du système de coordonnées le plus couramment utilisé pour les tuiles MVT. Le paramètre facultatif bounds
peut être utilisé pour générer des tuiles dans n'importe quel système de coordonnées. Il s'agit d'une géométrie qui possède le SRID et l'étendue du carré "Niveau de zoom zéro" dans lequel le système de tuiles XYZ est inscrit.
Le paramètre facultatif margin
peut être utilisé pour étendre une tuile du pourcentage donné. Par exemple, margin=0.125
étend la tuile de 12,5%, ce qui équivaut à buffer=512 lorsque la taille de l'étendue de la tuile est de 4096, comme utilisé dans ST_AsMVTGeom. Ceci est utile pour créer un tampon de tuile afin d'inclure des données situées en dehors de la zone visible de la tuile, mais dont l'existence affecte le rendu de la tuile. Par exemple, le nom d'une ville (un point) peut se trouver près du bord d'une tuile, son étiquette doit donc être rendue sur deux tuiles, même si le point se trouve dans la zone visible d'une seule tuile. L'utilisation de tuiles étendues dans une requête inclura le point de la ville dans les deux tuiles. Utilisez une valeur négative pour réduire la tuile à la place. Les valeurs inférieures à -0,5 sont interdites, car cela éliminerait complètement la tuile. Ne spécifiez pas de marge lors de l'utilisation avec ST_AsMVTGeom
. Voir l'exemple pour ST_AsMVT.
Amélioré : 3.1.0 Ajout d'un paramètre de marge.
Disponibilité : 3.0.0
SELECT ST_AsText( ST_TileEnvelope(2, 1, 1) ) ; st_astext ------------------------------ POLYGON((-10018754.1713945 0,-10018754.1713945 10018754.1713945,0 10018754.1713945,0 0,-10018754.1713945 0)) SELECT ST_AsText( ST_TileEnvelope(3, 1, 1, ST_MakeEnvelope(-180, -90, 180, 90, 4326) ) ) ; st_astext ------------------------------------------------------ POLYGON((-135 45,-135 67.5,-90 67.5,-90 45,-135 45))
ST_HexagonGrid — Renvoie un ensemble d'hexagones et d'indices de cellules qui couvrent complètement les limites de l'argument géométrie.
setof record ST_HexagonGrid(
float8 size, geometry bounds)
;
Commence par le concept d'un tuilage hexagonal du plan. (Pas un pavage hexagonal du globe, ce n'est pas le schéma de pavage H3). Pour un SRS plan donné, et une taille d'arête donnée, en commençant à l'origine du SRS, il existe un unique tuilage hexagonal du plan, Tiling(SRS, Size). Cette fonction répond à la question : quels hexagones dans un Tiling(SRS, Size) donné se chevauchent avec une limite donnée.
Le SRS pour les hexagones de sortie est le SRS fourni par la géométrie des limites.
Doubler ou tripler la taille des bords de l'hexagone génère un nouveau pavage parent qui s'adapte au pavage d'origine. Malheureusement, il n'est pas possible de générer des tuiles d'hexagones parents dans lesquelles les tuiles enfants s'insèrent parfaitement.
Disponibilité : 3.1.0
Pour faire un résumé des points par rapport à un pavage hexagonal, générez une grille hexagonale en utilisant l'étendue des points comme limites, puis joignez spatialement cette grille.
SELECT COUNT(*), hexes.geom FROM ST_HexagonGrid( 10000, ST_SetSRID(ST_EstimatedExtent('pointtable', 'geom'), 3857) ) AS hexes INNER JOIN pointtable AS pts ON ST_Intersects(pts.geom, hexes.geom) GROUP BY hexes.geom ;
Si nous générons un ensemble d'hexagones pour chaque limite de polygone et que nous éliminons par filtrage ceux qui n'intersectent pas leurs hexagones, nous obtenons un pavage pour chaque polygone.
La mise en mosaïque des états donne lieu à une couverture hexagonale de chaque état, et à des hexagones multiples se chevauchant aux frontières entre les états.
![]() | |
Le mot-clé LATERAL est implicite pour les fonctions de retour d'ensemble lorsqu'elles font référence à une table antérieure dans la liste FROM. Ainsi, CROSS JOIN LATERAL, CROSS JOIN, ou tout simplement , sont des constructions équivalentes pour cet exemple. |
SELECT admin1.gid, hex.geom FROM admin1 CROSS JOIN ST_HexagonGrid(100000, admin1.geom) AS hex WHERE adm0_a3 = 'USA' AND ST_Intersects(admin1.geom, hex.geom)
ST_Hexagon — Renvoie un seul hexagone, en utilisant la taille du bord et les coordonnées de la cellule fournies dans l'espace de la grille de l'hexagone.
geometry ST_Hexagon(
float8 size, integer cell_i, integer cell_j, geometry origin)
;
Utilise le même concept de tuilage d'hexagones que ST_HexagonGrid, mais génère un seul hexagone à la coordonnée de cellule souhaitée. En option, peut ajuster la coordonnée d'origine du tuilage, l'origine par défaut est à 0,0.
Les hexagones sont générés sans SRID défini, utilisez donc ST_SetSRID pour définir le SRID à celui que vous attendez.
Disponibilité : 3.1.0
ST_SquareGrid — Renvoie un ensemble de carrés de grille et d'indices de cellules qui couvrent complètement les limites de l'argument géométrie.
setof record ST_SquareGrid(
float8 size, geometry bounds)
;
Commence par le concept de tuilage carré du plan. Pour un SRS plan donné, et une taille d'arête donnée, en commençant à l'origine du SRS, il existe un unique pavage carré du plan, Tiling(SRS, Size). Cette fonction répond à la question : quelles grilles dans un Tiling(SRS, Size) donné se chevauchent avec une limite donnée.
Le SRS des carrés de sortie est le SRS fourni par la géométrie des limites.
Le doublement de la taille du carré ou de son bord génère un nouveau pavage parent qui s'adapte parfaitement au pavage d'origine. Les carrelages standard des cartes Web dans mercator ne sont que des puissances de deux grilles carrées dans le plan mercator.
Disponibilité : 3.1.0
La grille remplira toutes les limites du pays, donc si vous voulez seulement des carrés qui touchent le pays, vous devrez filtrer ensuite avec ST_Intersects.
WITH grid AS ( SELECT (ST_SquareGrid(1, ST_Transform(geom,4326))).* FROM admin0 WHERE name = 'Canada' ) SELEcT ST_AsText(geom) FROM grid
Pour faire un résumé des points par rapport à un tuilage carré, générez une grille carrée en utilisant l'étendue des points comme limites, puis joignez spatialement à cette grille. Notez que l'étendue estimée peut être différente de l'étendue réelle, soyez donc prudent et assurez-vous au moins d'avoir analysé votre tableau.
SELECT COUNT(*), squares.geom FROM pointtable AS pts INNER JOIN ST_SquareGrid( 1000, ST_SetSRID(ST_EstimatedExtent('pointtable', 'geom'), 3857) ) AS squares ON ST_Intersects(pts.geom, squares.geom) GROUP BY squares.geom
Cette méthode donne le même résultat que le premier exemple mais sera plus lente pour un grand nombre de points
SELECT COUNT(*), squares.geom FROM pointtable AS pts INNER JOIN ST_SquareGrid( 1000, pts.geom ) AS squares ON ST_Intersects(pts.geom, squares.geom) GROUP BY squares.geom
ST_Square — Renvoie un seul carré, en utilisant la taille du bord et la coordonnée de la cellule fournies dans l'espace de la grille du carré.
geometry ST_Square(
float8 size, integer cell_i, integer cell_j, geometry origin)
;
Utilise le même concept de tuilage carré que ST_SquareGrid, mais génère un seul carré à la coordonnée de cellule souhaitée. En option, peut ajuster la coordonnée d'origine du tuilage, l'origine par défaut est à 0,0.
Les carrés sont générés sans SRID défini, utilisez donc ST_SetSRID pour définir le SRID à celui que vous attendez.
Disponibilité : 3.1.0
ST_Letters — Renvoie les lettres d'entrée rendues sous forme de géométrie avec une position de départ par défaut à l'origine et une hauteur de texte par défaut de 100.
geometry ST_Letters(
text letters, json font)
;
Utilise une police intégrée pour rendre une chaîne de caractères sous forme de géométrie multipolygonale. La hauteur de texte par défaut est de 100,0, soit la distance entre le bas d'une descendante et le haut d'une capitale. La position de départ par défaut place le début de la ligne de base à l'origine. Pour remplacer la police, il faut passer une carte json, avec un caractère comme clé, et des TWKB encodés en base64 pour la forme de la police, les polices ayant une hauteur de 1000 unités du bas des descendantes au haut des capitales.
Le texte est généré à l'origine par défaut, donc pour repositionner et redimensionner le texte, appliquez d'abord la fonction ST_Scale
et ensuite appliquez la fonction ST_Translate
.
Disponibilité : 3.3.0
SELECT ST_AsText(ST_Letters('Yo'), 1) ;
Lettres générées par ST_Letters
geometry_dump
rows for the components of a geometry.geometry_dump
pour les coordonnées dans une géométrie.geometry_dump
pour les segments d'une géométrie.geometry_dump
rows for the exterior and interior rings of a Polygon.GeometryType — Renvoie le type d'une géométrie sous forme de texte.
text GeometryType(
geometry geomA)
;
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.
![]() | |
Cette fonction indique si la géométrie comporte une dimension de type mesure, en retournant un texte de la forme 'POINTM'. |
Amélioration : 2.0.0 introduction du support TIN, Triangles et surfaces polyédriques.
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method supports Circular Strings and Curves
This function supports 3d and will not drop the z-index.
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
SELECT GeometryType(ST_GeomFromText('LINESTRING(77.29 29.07,77.42 29.26,77.27 29.31,77.29 29.07)')) ; geometrytype -------------- LINESTRING
SELECT ST_GeometryType(ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )')); --result POLYHEDRALSURFACE
SELECT GeometryType(geom) as result FROM (SELECT ST_GeomFromEWKT('TIN ((( 0 0 0, 0 0 1, 0 1 0, 0 0 0 )), (( 0 0 0, 0 1 0, 1 1 0, 0 0 0 )) )') AS geom ) AS g; result -------- TIN
ST_Boundary — Renvoie la limite d'une géométrie.
geometry ST_Boundary(
geometry geomA)
;
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.
Effectué par le module GEOS
![]() | |
Avant la version 2.0.0, cette fonction renvoie une exception si une |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. OGC SPEC s2.1.1.1
This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 5.1.17
This function supports 3d and will not drop the z-index.
Amélioration : 2.1.0 introduction du support pour Triangle
Changed: 3.2.0 support for TIN, does not use geos, does not linearize curves
![]() Linestring with boundary points overlaid
SELECT ST_Boundary(geom) FROM (SELECT 'LINESTRING(100 150,50 60, 70 80, 160 170)'::geometry As geom) As f ;
-- ST_AsText output MULTIPOINT((100 150),(160 170))
| ![]() polygon holes with boundary multilinestring
SELECT ST_Boundary(geom) FROM (SELECT 'POLYGON (( 10 130, 50 190, 110 190, 140 150, 150 80, 100 10, 20 40, 10 130 ), ( 70 40, 100 50, 120 80, 80 110, 50 90, 70 40 ))'::geometry As geom) As f;
-- ST_AsText output MULTILINESTRING((10 130,50 190,110 190,140 150,150 80,100 10,20 40,10 130), (70 40,100 50,120 80,80 110,50 90,70 40))
|
SELECT ST_AsText(ST_Boundary(ST_GeomFromText('LINESTRING(1 1,0 0, -1 1)'))); st_astext ----------- MULTIPOINT((1 1),(-1 1)) SELECT ST_AsText(ST_Boundary(ST_GeomFromText('POLYGON((1 1,0 0, -1 1, 1 1))'))); st_astext ---------- LINESTRING(1 1,0 0,-1 1,1 1) --Using a 3d polygon SELECT ST_AsEWKT(ST_Boundary(ST_GeomFromEWKT('POLYGON((1 1 1,0 0 1, -1 1 1, 1 1 1))'))); st_asewkt ----------------------------------- LINESTRING(1 1 1,0 0 1,-1 1 1,1 1 1) --Using a 3d multilinestring SELECT ST_AsEWKT(ST_Boundary(ST_GeomFromEWKT('MULTILINESTRING((1 1 1,0 0 0.5, -1 1 1),(1 1 0.5,0 0 0.5, -1 1 0.5, 1 1 0.5) )'))); st_asewkt ---------- MULTIPOINT((-1 1 1),(1 1 0.75))
ST_BoundingDiagonal — Retourne la diagonale de la boîte englobante pour la géométrie en argument.
geometry ST_BoundingDiagonal(
geometry geom, boolean fits=false)
;
Returns the diagonal of the supplied geometry's bounding box as a LineString. The diagonal is a 2-point LineString with the minimum values of each dimension in its start point and the maximum values in its end point. If the input geometry is empty, the diagonal line is a LINESTRING EMPTY.
The optional fits
parameter specifies if the best fit is needed. If false, the diagonal of a somewhat larger bounding box can be accepted (which is faster to compute for geometries with many vertices). In either case, the bounding box of the returned diagonal line always covers the input geometry.
The returned geometry retains the SRID and dimensionality (Z and M presence) of the input geometry.
![]() | |
In degenerate cases (i.e. a single vertex in input) the returned linestring will be formally invalid (no interior). The result is still topologically valid. |
Disponibilité : 2.2.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_CoordDim — Renvoie la dimension des coordonnées d'une géométrie.
integer ST_CoordDim(
geometry geomA)
;
Retourne la dimension des coordonnées d'une valeur ST_Geometry.
Alias SQL/MM pour la fonction ST_NDims
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3 : 5.1.3
This method supports Circular Strings and Curves
This function supports 3d and will not drop the z-index.
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
ST_Dimension — Renvoie la dimension topologique d'une géométrie.
integer ST_Dimension(
geometry g)
;
Renvoie la dimension topologique de cet objet Geometry, qui doit être inférieure ou égale à la dimension des coordonnées. OGC SPEC s2.1.1.1 - renvoie 0 pour POINT
, 1 pour LINESTRING
, 2 pour POLYGON
, et la plus grande dimension des composants d'une GEOMETRYCOLLECTION
. Si la dimension est inconnue (par exemple, pour une GEOMETRYCOLLECTION
vide), 0 est renvoyé.
This method implements the SQL/MM specification. SQL-MM 3 : 5.1.2
Amélioration : 2.0.0 introduction du support TIN et surfaces polyédriques. Ne renvoie plus une exception si une GEOMETRY EMPTY est passée.
![]() | |
Avant la version 2.0.0, cette fonction lève une exception si elle est utilisée avec une géométrie vide. |
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
ST_Dump — Returns a set of geometry_dump
rows for the components of a geometry.
geometry_dump[] ST_Dump(
geometry g1)
;
A set-returning function (SRF) that extracts the components of a geometry. It returns a set of geometry_dump rows, each containing a geometry (geom
field) and an array of integers (path
field).
For an atomic geometry type (POINT,LINESTRING,POLYGON) a single record is returned with an empty path
array and the input geometry as geom
. For a collection or multi-geometry a record is returned for each of the collection components, and the path
denotes the position of the component inside the collection.
ST_Dump is useful for expanding geometries. It is the inverse of a ST_Collect / GROUP BY, in that it creates new rows. For example it can be use to expand MULTIPOLYGONS into POLYGONS.
Amélioration : 2.0.0 introduction du support TIN, Triangles et surfaces polyédriques.
Availability: PostGIS 1.0.0RC1. Requires PostgreSQL 7.3 or higher.
![]() | |
Prior to 1.3.4, this function crashes if used with geometries that contain CURVES. This is fixed in 1.3.4+ |
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
This function supports 3d and will not drop the z-index.
SELECT sometable.field1, sometable.field1, (ST_Dump(sometable.geom)).geom AS geom FROM sometable; -- Break a compound curve into its constituent linestrings and circularstrings SELECT ST_AsEWKT(a.geom), ST_HasArc(a.geom) FROM ( SELECT (ST_Dump(p_geom)).geom AS geom FROM (SELECT ST_GeomFromEWKT('COMPOUNDCURVE(CIRCULARSTRING(0 0, 1 1, 1 0),(1 0, 0 1))') AS p_geom) AS b ) AS a; st_asewkt | st_hasarc -----------------------------+---------- CIRCULARSTRING(0 0,1 1,1 0) | t LINESTRING(1 0,0 1) | f (2 rows)
-- Polyhedral surface example -- Break a Polyhedral surface into its faces SELECT (a.p_geom).path[1] As path, ST_AsEWKT((a.p_geom).geom) As geom_ewkt FROM (SELECT ST_Dump(ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )') ) AS p_geom ) AS a; path | geom_ewkt ------+------------------------------------------ 1 | POLYGON((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)) 2 | POLYGON((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)) 3 | POLYGON((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)) 4 | POLYGON((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)) 5 | POLYGON((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)) 6 | POLYGON((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1))
-- TIN -- SELECT (g.gdump).path, ST_AsEWKT((g.gdump).geom) as wkt FROM (SELECT ST_Dump( ST_GeomFromEWKT('TIN ((( 0 0 0, 0 0 1, 0 1 0, 0 0 0 )), (( 0 0 0, 0 1 0, 1 1 0, 0 0 0 )) )') ) AS gdump ) AS g; -- result -- path | wkt ------+------------------------------------- {1} | TRIANGLE((0 0 0,0 0 1,0 1 0,0 0 0)) {2} | TRIANGLE((0 0 0,0 1 0,1 1 0,0 0 0))
ST_DumpPoints — Renvoie un ensemble de lignes geometry_dump
pour les coordonnées dans une géométrie.
geometry_dump[] ST_DumpPoints(
geometry geom)
;
A set-returning function (SRF) that extracts the coordinates (vertices) of a geometry. It returns a set of geometry_dump rows, each containing a geometry (geom
field) and an array of integers (path
field).
the geom
field POINT
s represent the coordinates of the supplied geometry.
the path
field (an integer[]
) is an index enumerating the coordinate positions in the elements of the supplied geometry. The indices are 1-based. For example, for a LINESTRING
the paths are {i}
where i
is the nth
coordinate in the LINESTRING
. For a POLYGON
the paths are {i,j}
where i
is the ring number (1 is outer; inner rings follow) and j
is the coordinate position in the ring.
To obtain a single geometry containing the coordinates use ST_Points.
Enhanced: 2.1.0 Faster speed. Reimplemented as native-C.
Amélioration : 2.0.0 introduction du support TIN, Triangles et surfaces polyédriques.
Disponibilité : 1.5.0
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
This function supports 3d and will not drop the z-index.
SELECT edge_id, (dp).path[1] As index, ST_AsText((dp).geom) As wktnode FROM (SELECT 1 As edge_id , ST_DumpPoints(ST_GeomFromText('LINESTRING(1 2, 3 4, 10 10)')) AS dp UNION ALL SELECT 2 As edge_id , ST_DumpPoints(ST_GeomFromText('LINESTRING(3 5, 5 6, 9 10)')) AS dp ) As foo; edge_id | index | wktnode ---------+-------+-------------- 1 | 1 | POINT(1 2) 1 | 2 | POINT(3 4) 1 | 3 | POINT(10 10) 2 | 1 | POINT(3 5) 2 | 2 | POINT(5 6) 2 | 3 | POINT(9 10)
SELECT path, ST_AsText(geom) FROM ( SELECT (ST_DumpPoints(g.geom)).* FROM (SELECT 'GEOMETRYCOLLECTION( POINT ( 0 1 ), LINESTRING ( 0 3, 3 4 ), POLYGON (( 2 0, 2 3, 0 2, 2 0 )), POLYGON (( 3 0, 3 3, 6 3, 6 0, 3 0 ), ( 5 1, 4 2, 5 2, 5 1 )), MULTIPOLYGON ( (( 0 5, 0 8, 4 8, 4 5, 0 5 ), ( 1 6, 3 6, 2 7, 1 6 )), (( 5 4, 5 8, 6 7, 5 4 )) ) )'::geometry AS geom ) AS g ) j; path | st_astext -----------+------------ {1,1} | POINT(0 1) {2,1} | POINT(0 3) {2,2} | POINT(3 4) {3,1,1} | POINT(2 0) {3,1,2} | POINT(2 3) {3,1,3} | POINT(0 2) {3,1,4} | POINT(2 0) {4,1,1} | POINT(3 0) {4,1,2} | POINT(3 3) {4,1,3} | POINT(6 3) {4,1,4} | POINT(6 0) {4,1,5} | POINT(3 0) {4,2,1} | POINT(5 1) {4,2,2} | POINT(4 2) {4,2,3} | POINT(5 2) {4,2,4} | POINT(5 1) {5,1,1,1} | POINT(0 5) {5,1,1,2} | POINT(0 8) {5,1,1,3} | POINT(4 8) {5,1,1,4} | POINT(4 5) {5,1,1,5} | POINT(0 5) {5,1,2,1} | POINT(1 6) {5,1,2,2} | POINT(3 6) {5,1,2,3} | POINT(2 7) {5,1,2,4} | POINT(1 6) {5,2,1,1} | POINT(5 4) {5,2,1,2} | POINT(5 8) {5,2,1,3} | POINT(6 7) {5,2,1,4} | POINT(5 4) (29 rows)
-- Polyhedral surface cube -- SELECT (g.gdump).path, ST_AsEWKT((g.gdump).geom) as wkt FROM (SELECT ST_DumpPoints(ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )') ) AS gdump ) AS g; -- result -- path | wkt ---------+-------------- {1,1,1} | POINT(0 0 0) {1,1,2} | POINT(0 0 1) {1,1,3} | POINT(0 1 1) {1,1,4} | POINT(0 1 0) {1,1,5} | POINT(0 0 0) {2,1,1} | POINT(0 0 0) {2,1,2} | POINT(0 1 0) {2,1,3} | POINT(1 1 0) {2,1,4} | POINT(1 0 0) {2,1,5} | POINT(0 0 0) {3,1,1} | POINT(0 0 0) {3,1,2} | POINT(1 0 0) {3,1,3} | POINT(1 0 1) {3,1,4} | POINT(0 0 1) {3,1,5} | POINT(0 0 0) {4,1,1} | POINT(1 1 0) {4,1,2} | POINT(1 1 1) {4,1,3} | POINT(1 0 1) {4,1,4} | POINT(1 0 0) {4,1,5} | POINT(1 1 0) {5,1,1} | POINT(0 1 0) {5,1,2} | POINT(0 1 1) {5,1,3} | POINT(1 1 1) {5,1,4} | POINT(1 1 0) {5,1,5} | POINT(0 1 0) {6,1,1} | POINT(0 0 1) {6,1,2} | POINT(1 0 1) {6,1,3} | POINT(1 1 1) {6,1,4} | POINT(0 1 1) {6,1,5} | POINT(0 0 1) (30 rows)
-- Triangle -- SELECT (g.gdump).path, ST_AsText((g.gdump).geom) as wkt FROM (SELECT ST_DumpPoints( ST_GeomFromEWKT('TRIANGLE (( 0 0, 0 9, 9 0, 0 0 ))') ) AS gdump ) AS g; -- result -- path | wkt ------+------------ {1} | POINT(0 0) {2} | POINT(0 9) {3} | POINT(9 0) {4} | POINT(0 0)
-- TIN -- SELECT (g.gdump).path, ST_AsEWKT((g.gdump).geom) as wkt FROM (SELECT ST_DumpPoints( ST_GeomFromEWKT('TIN ((( 0 0 0, 0 0 1, 0 1 0, 0 0 0 )), (( 0 0 0, 0 1 0, 1 1 0, 0 0 0 )) )') ) AS gdump ) AS g; -- result -- path | wkt ---------+-------------- {1,1,1} | POINT(0 0 0) {1,1,2} | POINT(0 0 1) {1,1,3} | POINT(0 1 0) {1,1,4} | POINT(0 0 0) {2,1,1} | POINT(0 0 0) {2,1,2} | POINT(0 1 0) {2,1,3} | POINT(1 1 0) {2,1,4} | POINT(0 0 0) (8 rows)
ST_DumpSegments — Renvoie un ensemble de lignes geometry_dump
pour les segments d'une géométrie.
geometry_dump[] ST_DumpSegments(
geometry geom)
;
A set-returning function (SRF) that extracts the segments of a geometry. It returns a set of geometry_dump rows, each containing a geometry (geom
field) and an array of integers (path
field).
le champ géom
LINESTRING
représente les segments de la géométrie fournie.
the path
field (an integer[]
) is an index enumerating the segment start point positions in the elements of the supplied geometry. The indices are 1-based. For example, for a LINESTRING
the paths are {i}
where i
is the nth
segment start point in the LINESTRING
. For a POLYGON
the paths are {i,j}
where i
is the ring number (1 is outer; inner rings follow) and j
is the segment start point position in the ring.
Disponibilité : 3.2.0
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
This function supports 3d and will not drop the z-index.
SELECT path, ST_AsText(geom) FROM ( SELECT (ST_DumpSegments(g.geom)).* FROM (SELECT 'GEOMETRYCOLLECTION( LINESTRING(1 1, 3 3, 4 4), POLYGON((5 5, 6 6, 7 7, 5 5)) )'::geometry AS geom ) AS g ) j; path │ st_astext --------------------------------- {1,1} │ LINESTRING(1 1,3 3) {1,2} │ LINESTRING(3 3,4 4) {2,1,1} │ LINESTRING(5 5,6 6) {2,1,2} │ LINESTRING(6 6,7 7) {2,1,3} │ LINESTRING(7 7,5 5) (5 rows)
-- Triangle -- SELECT path, ST_AsText(geom) FROM ( SELECT (ST_DumpSegments(g.geom)).* FROM (SELECT 'TRIANGLE(( 0 0, 0 9, 9 0, 0 0 ))'::geometry AS geom ) AS g ) j; path │ st_astext --------------------------------- {1,1} │ LINESTRING(0 0,0 9) {1,2} │ LINESTRING(0 9,9 0) {1,3} │ LINESTRING(9 0,0 0) (3 rows)
-- TIN -- SELECT path, ST_AsEWKT(geom) FROM ( SELECT (ST_DumpSegments(g.geom)).* FROM (SELECT 'TIN((( 0 0 0, 0 0 1, 0 1 0, 0 0 0 )), (( 0 0 0, 0 1 0, 1 1 0, 0 0 0 )) )'::geometry AS geom ) AS g ) j; path │ st_asewkt --------------------------------- {1,1,1} │ LINESTRING(0 0 0,0 0 1) {1,1,2} │ LINESTRING(0 0 1,0 1 0) {1,1,3} │ LINESTRING(0 1 0,0 0 0) {2,1,1} │ LINESTRING(0 0 0,0 1 0) {2,1,2} │ LINESTRING(0 1 0,1 1 0) {2,1,3} │ LINESTRING(1 1 0,0 0 0) (6 rows)
ST_DumpRings — Returns a set of geometry_dump
rows for the exterior and interior rings of a Polygon.
geometry_dump[] ST_DumpRings(
geometry a_polygon)
;
A set-returning function (SRF) that extracts the rings of a polygon. It returns a set of geometry_dump rows, each containing a geometry (geom
field) and an array of integers (path
field).
The geom
field contains each ring as a POLYGON. The path
field is an integer array of length 1 containing the polygon ring index. The exterior ring (shell) has index 0. The interior rings (holes) have indices of 1 and higher.
![]() | |
Cela ne fonctionne que pour les géométries POLYGON. Il ne fonctionne pas pour les MULTIPOLYGONS. |
Availability: PostGIS 1.1.3. Requires PostgreSQL 7.3 or higher.
This function supports 3d and will not drop the z-index.
General form of query.
SELECT polyTable.field1, polyTable.field1, (ST_DumpRings(polyTable.geom)).geom As geom FROM polyTable;
A polygon with a single hole.
SELECT path, ST_AsEWKT(geom) As geom FROM ST_DumpRings( ST_GeomFromEWKT('POLYGON((-8149064 5133092 1,-8149064 5132986 1,-8148996 5132839 1,-8148972 5132767 1,-8148958 5132508 1,-8148941 5132466 1,-8148924 5132394 1, -8148903 5132210 1,-8148930 5131967 1,-8148992 5131978 1,-8149237 5132093 1,-8149404 5132211 1,-8149647 5132310 1,-8149757 5132394 1, -8150305 5132788 1,-8149064 5133092 1), (-8149362 5132394 1,-8149446 5132501 1,-8149548 5132597 1,-8149695 5132675 1,-8149362 5132394 1))') ) as foo; path | geom ---------------------------------------------------------------------------------------------------------------- {0} | POLYGON((-8149064 5133092 1,-8149064 5132986 1,-8148996 5132839 1,-8148972 5132767 1,-8148958 5132508 1, | -8148941 5132466 1,-8148924 5132394 1, | -8148903 5132210 1,-8148930 5131967 1, | -8148992 5131978 1,-8149237 5132093 1, | -8149404 5132211 1,-8149647 5132310 1,-8149757 5132394 1,-8150305 5132788 1,-8149064 5133092 1)) {1} | POLYGON((-8149362 5132394 1,-8149446 5132501 1, | -8149548 5132597 1,-8149695 5132675 1,-8149362 5132394 1))
ST_EndPoint — Renvoie le dernier point d'une LineString ou CircularLineString.
geometry ST_EndPoint(
geometry g)
;
Renvoie le dernier point d'une géométrie LINESTRING
ou CIRCULARLINESTRING
comme un POINT
. Renvoie NULL
si l'entrée n'est pas une LINESTRING
ou CIRCULARLINESTRING
.
This method implements the SQL/MM specification. SQL-MM 3 : 7.1.4
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
![]() | |
Modifié : 2.0.0 ne fonctionne plus avec les MultiLineStrings à géométrie unique. Dans les anciennes versions de PostGIS, une MultiLineString à géométrie unique fonctionnait avec cette fonction et renvoyait le point final. Dans la version 2.0.0, elle renvoie NULL comme toute autre MultiLineString. L'ancien comportement était une fonctionnalité non documentée, mais les personnes qui supposaient que leurs données étaient stockées en tant que LINESTRING peuvent voir ces dernières retourner NULL dans la version 2.0.0. |
End point of a LineString
postgis=# SELECT ST_AsText(ST_EndPoint('LINESTRING(1 1, 2 2, 3 3)'::geometry)); st_astext ------------ POINT(3 3)
End point of a non-LineString is NULL
SELECT ST_EndPoint('POINT(1 1)'::geometry) IS NULL AS is_null; is_null ---------- t
End point of a 3D LineString
--3d endpoint SELECT ST_AsEWKT(ST_EndPoint('LINESTRING(1 1 2, 1 2 3, 0 0 5)')); st_asewkt -------------- POINT(0 0 5)
Point d'arrivée d'une CircularString
SELECT ST_AsText(ST_EndPoint('CIRCULARSTRING(5 2,-3 1.999999, -2 1, -4 2, 6 3)'::geometry)); st_astext ------------ POINT(6 3)
ST_Envelope — Renvoie une géométrie représentant la boîte de délimitation d'une géométrie.
geometry ST_Envelope(
geometry g1)
;
Renvoie la boîte de délimitation minimale en double précision (float8) pour la géométrie fournie, en tant que géométrie. Le polygone est défini par les points d'angle de la boîte de délimitation ((MINX
, MINY
), (MINX
, MAXY
), (MAXX
, MAXY
), (MAXX
, MINY
), (MINX
, MINY
)). (PostGIS ajoutera également une coordonnée ZMIN
/ZMAX
).
D'autres cas (lignes verticales, points) retourneront une géométrie de dimension inférieure à POLYGON
, c'est-à-dire POINT
ou LINESTRING
.
Disponibilité : 1.5.0 changement pour renvoyer un type double précision à la place de float4
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s2.1.1.1
This method implements the SQL/MM specification. SQL-MM 3: 5.1.19
SELECT ST_AsText(ST_Envelope('POINT(1 3)'::geometry)); st_astext ------------ POINT(1 3) (1 row) SELECT ST_AsText(ST_Envelope('LINESTRING(0 0, 1 3)'::geometry)); st_astext -------------------------------- POLYGON((0 0,0 3,1 3,1 0,0 0)) (1 row) SELECT ST_AsText(ST_Envelope('POLYGON((0 0, 0 1, 1.0000001 1, 1.0000001 0, 0 0))'::geometry)); st_astext -------------------------------------------------------------- POLYGON((0 0,0 1,1.00000011920929 1,1.00000011920929 0,0 0)) (1 row) SELECT ST_AsText(ST_Envelope('POLYGON((0 0, 0 1, 1.0000000001 1, 1.0000000001 0, 0 0))'::geometry)); st_astext -------------------------------------------------------------- POLYGON((0 0,0 1,1.00000011920929 1,1.00000011920929 0,0 0)) (1 row) SELECT Box3D(geom), Box2D(geom), ST_AsText(ST_Envelope(geom)) As envelopewkt FROM (SELECT 'POLYGON((0 0, 0 1000012333334.34545678, 1.0000001 1, 1.0000001 0, 0 0))'::geometry As geom) As foo;
Envelope of a point and linestring.
SELECT ST_AsText(ST_Envelope( ST_Collect( ST_GeomFromText('LINESTRING(55 75,125 150)'), ST_Point(20, 80)) )) As wktenv; wktenv ----------- POLYGON((20 75,20 150,125 150,125 75,20 75))
ST_ExteriorRing — Returns a LineString representing the exterior ring of a Polygon.
geometry ST_ExteriorRing(
geometry a_polygon)
;
Renvoie une LINESTRING représentant l'anneau extérieur (coquille) d'un POLYGONE. Renvoie NULL si la géométrie n'est pas un polygone.
![]() | |
Cette fonction ne prend pas en charge les MULTIPOLYGONES. Pour les MULTIPOLYGONs, utilisez conjointement avec ST_GeometryN ou ST_Dump |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. 2.1.5.1
This method implements the SQL/MM specification. SQL-MM 3 : 8.2.3, 8.3.3
This function supports 3d and will not drop the z-index.
--Si vous avez un tableau de polygones SELECT gid, ST_ExteriorRing(the_geom) AS ering FROM sometable ; --Si vous avez une table de MULTIPOLYGONES --et voulez retourner un MULTILINESTRING composé des anneaux extérieurs de chaque polygone 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 ; --Example 3d SELECT ST_AsEWKT( ST_ExteriorRing( ST_GeomFromEWKT('POLYGON((0 0 1, 1 1 1, 1 2 1, 1 1 1, 0 0 1))') ) ) ; st_asewkt --------- LINESTRING(0 0 1,1 1 1,1 2 1,1 1 1,0 0 1)
ST_GeometryN — Renvoie un élément d'une collection de géométries.
geometry ST_GeometryN(
geometry geomA, integer n)
;
Renvoie la géométrie du Nième élément basé sur 1 d'une géométrie d'entrée qui est une GEOMETRYCOLLECTION, MULTIPOINT, MULTILINESTRING, MULTICURVE, MULTI)POLYGON ou POLYHEDRALSURFACE. Sinon, renvoie NULL.
![]() | |
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. |
![]() | |
Pour extraire tous les éléments d'une géométrie, ST_Dump est plus efficace et fonctionne pour les géométries atomiques. |
Amélioration : 2.0.0 introduction du support TIN, Triangles et surfaces polyé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 OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3 : 9.1.5
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
--Extracting a subset of points from a 3d multipoint SELECT n, ST_AsEWKT(ST_GeometryN(geom, n)) As geomewkt FROM ( VALUES (ST_GeomFromEWKT('MULTIPOINT((1 2 7), (3 4 7), (5 6 7), (8 9 10))') ), ( ST_GeomFromEWKT('MULTICURVE(CIRCULARSTRING(2.5 2.5,4.5 2.5, 3.5 3.5), (10 11, 12 11))') ) )As foo(geom) CROSS JOIN generate_series(1,100) n WHERE n <= ST_NumGeometries(geom); n | geomewkt ---+----------------------------------------- 1 | POINT(1 2 7) 2 | POINT(3 4 7) 3 | POINT(5 6 7) 4 | POINT(8 9 10) 1 | CIRCULARSTRING(2.5 2.5,4.5 2.5,3.5 3.5) 2 | LINESTRING(10 11,12 11) --Extracting all geometries (useful when you want to assign an id) SELECT gid, n, ST_GeometryN(geom, n) FROM sometable CROSS JOIN generate_series(1,100) n WHERE n <= ST_NumGeometries(geom);
-- Polyhedral surface example -- Break a Polyhedral surface into its faces SELECT ST_AsEWKT(ST_GeometryN(p_geom,3)) As geom_ewkt FROM (SELECT ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )') AS p_geom ) AS a; geom_ewkt ------------------------------------------ POLYGON((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0))
-- TIN -- SELECT ST_AsEWKT(ST_GeometryN(geom,2)) as wkt FROM (SELECT ST_GeomFromEWKT('TIN ((( 0 0 0, 0 0 1, 0 1 0, 0 0 0 )), (( 0 0 0, 0 1 0, 1 1 0, 0 0 0 )) )') AS geom ) AS g; -- result -- wkt ------------------------------------- TRIANGLE((0 0 0,0 1 0,1 1 0,0 0 0))
ST_GeometryType — Renvoie le type SQL-MM d'une géométrie sous forme de texte.
text ST_GeometryType(
geometry g1)
;
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 polyé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.
SELECT ST_GeometryType(ST_GeomFromText('LINESTRING(77.29 29.07,77.42 29.26,77.27 29.31,77.29 29.07)')) ; --résultat ST_LineString
SELECT ST_GeometryType(ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )')); --result ST_PolyhedralSurface
SELECT ST_GeometryType(ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )')); --result ST_PolyhedralSurface
SELECT ST_GeometryType(geom) as result FROM (SELECT ST_GeomFromEWKT('TIN ((( 0 0 0, 0 0 1, 0 1 0, 0 0 0 )), (( 0 0 0, 0 1 0, 1 1 0, 0 0 0 )) )') AS geom ) AS g; result -------- ST_Tin
ST_HasArc — Tests if a geometry contains a circular arc
boolean ST_HasArc(
geometry geomA)
;
Renvoie true si une géométrie ou une collection de géométries contient une circular string
Disponibilité : 1.2.3 ?
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
ST_InteriorRingN — Returns the Nth interior ring (hole) of a Polygon.
geometry ST_InteriorRingN(
geometry a_polygon, integer n)
;
Renvoie le Nième anneau intérieur (trou) d'une géométrie POLYGONE sous forme de LINESTRING. L'indice commence à 1. Renvoie NULL si la géométrie n'est pas un polygone ou si l'indice est hors de la plage.
![]() | |
Cette fonction ne prend pas en charge les MULTIPOLYGONES. Pour les MULTIPOLYGONs, utilisez conjointement avec ST_GeometryN ou ST_Dump |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3 : 8.2.6, 8.3.5
This function supports 3d and will not drop the z-index.
ST_IsClosed — Teste si les points de départ et d'arrivée d'une LineString coïncident. Pour une PolyhedralSurface, teste si elle est fermée (volumétrique).
boolean ST_IsClosed(
geometry g)
;
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 OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3 : 7.1.5, 9.3.3
![]() | |
La norme SQL-MM indique que le résultat de la fonction |
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 polyédriques.
This function supports Polyhedral surfaces.
postgis=# SELECT ST_IsClosed('LINESTRING(0 0, 1 1)'::geometry) ; st_isclosed ------------- f (1 row) postgis=# SELECT ST_IsClosed('LINESTRING(0 0, 0 1, 1 1, 0 0)'::geometry) ; st_isclosed ------------- t (1 row) postgis=# SELECT ST_IsClosed('MULTILINESTRING((0 0, 0 1, 1 1, 0 0),(0 0, 1 1))'::geometry) ; st_isclosed ------------- f (1 row) postgis=# SELECT ST_IsClosed('POINT(0 0)'::geometry) ; st_isclosed ------------- t (1 row) postgis=# SELECT ST_IsClosed('MULTIPOINT((0 0), (1 1))'::geometry) ; st_isclosed ------------- t (1 row)
-- A cube -- SELECT ST_IsClosed(ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )')); st_isclosed ------------- t -- Same as cube but missing a side -- SELECT ST_IsClosed(ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)) )')); st_isclosed ------------- f
ST_IsCollection — Teste si une géométrie est un type de collection de géométrie.
boolean ST_IsCollection(
geometry g)
;
Renvoie TRUE
si le type de géométrie de l'argument est un type de collection de géométrie. Les types de collection sont les suivants :
GEOMETRYCOLLECTION
MULTI{POINT,POLYGON,LINESTRING,CURVE,SURFACE}
COMPOUNDCURVE
![]() | |
Cette fonction analyse le type de la géométrie. Renvoie |
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
postgis=# SELECT ST_IsCollection('LINESTRING(0 0, 1 1)'::geometry) ; st_iscollection ------------- f (1 row) postgis=# SELECT ST_IsCollection('MULTIPOINT EMPTY'::geometry) ; st_iscollection ------------- t (1 row) postgis=# SELECT ST_IsCollection('MULTIPOINT((0 0))'::geometry) ; st_iscollection ------------- t (1 row) postgis=# SELECT ST_IsCollection('MULTIPOINT((0 0), (42 42))'::geometry) ; st_iscollection ------------- t (1 row) postgis=# SELECT ST_IsCollection('GEOMETRYCOLLECTION(POINT(0 0))'::geometry) ; st_iscollection ------------- t (1 row)
ST_IsEmpty — Tests if a geometry is empty.
boolean ST_IsEmpty(
geometry geomA)
;
Renvoie true si cette géométrie est une géométrie vide. Si vrai, alors cette géométrie représente une collection de géométrie vide, un polygone, un point, etc.
![]() | |
La norme SQL-MM stipule que ST_IsEmpty(NULL) doit renvoyer 0. PostGIS renvoie NULL. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s2.1.1.1
This method implements the SQL/MM specification. SQL-MM 3 : 5.1.7
This method supports Circular Strings and Curves
![]() | |
Modifié : 2.0.0 Dans les versions précédentes de PostGIS, ST_GeomFromText('GEOMETRYCOLLECTION(EMPTY)') était autorisé. Ceci est maintenant illégal dans PostGIS 2.0.0 pour mieux se conformer aux normes SQL/MM |
SELECT ST_IsEmpty(ST_GeomFromText('GEOMETRYCOLLECTION EMPTY')) ; st_isempty ------------ t (1 row) SELECT ST_IsEmpty(ST_GeomFromText('POLYGON EMPTY')) ; st_isempty ------------ t (1 row) SELECT ST_IsEmpty(ST_GeomFromText('POLYGON((1 2, 3 4, 5 6, 1 2))')) ; st_isempty ------------ f (1 row) SELECT ST_IsEmpty(ST_GeomFromText('POLYGON((1 2, 3 4, 5 6, 1 2))')) = false ; ?column ? ---------- t (1 row) SELECT ST_IsEmpty(ST_GeomFromText('CIRCULARSTRING EMPTY')) ; st_isempty ------------ t (1 row)
ST_IsPolygonCCW — Tests if Polygons have exterior rings oriented counter-clockwise and interior rings oriented clockwise.
boolean ST_IsPolygonCCW (
geometry geom )
;
Returns true if all polygonal components of the input geometry use a counter-clockwise orientation for their exterior ring, and a clockwise direction for all interior rings.
Returns true if the geometry has no polygonal components.
![]() | |
Closed linestrings are not considered polygonal components, so you would still get a true return by passing a single closed linestring no matter its orientation. |
![]() | |
If a polygonal geometry does not use reversed orientation for interior rings (i.e., if one or more interior rings are oriented in the same direction as an exterior ring) then both ST_IsPolygonCW and ST_IsPolygonCCW will return false. |
Disponibilité : 2.4.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_IsPolygonCW — Tests if Polygons have exterior rings oriented clockwise and interior rings oriented counter-clockwise.
boolean ST_IsPolygonCW (
geometry geom )
;
Returns true if all polygonal components of the input geometry use a clockwise orientation for their exterior ring, and a counter-clockwise direction for all interior rings.
Returns true if the geometry has no polygonal components.
![]() | |
Closed linestrings are not considered polygonal components, so you would still get a true return by passing a single closed linestring no matter its orientation. |
![]() | |
If a polygonal geometry does not use reversed orientation for interior rings (i.e., if one or more interior rings are oriented in the same direction as an exterior ring) then both ST_IsPolygonCW and ST_IsPolygonCCW will return false. |
Disponibilité : 2.4.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_IsRing — Tests if a LineString is closed and simple.
boolean ST_IsRing(
geometry g)
;
Renvoie TRUE
si cette LINESTRING
est à la fois ST_IsClosed (ST_StartPoint(
g
)~=
ST_Endpoint(
) et ST_IsSimple (pas d'auto intersection).g
)
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. 2.1.5.1
This method implements the SQL/MM specification. SQL-MM 3 : 7.1.6
![]() | |
La norme SQL-MM stipule que |
SELECT ST_IsRing(the_geom), ST_IsClosed(the_geom), ST_IsSimple(the_geom) FROM (SELECT 'LINESTRING(0 0, 0 1, 1 1, 1 0, 0 0)'::geometry AS the_geom) AS foo ; st_isring | st_isclosed | st_issimple -----------+-------------+------------- t | t | t (1 row) SELECT ST_IsRing(the_geom), ST_IsClosed(the_geom), ST_IsSimple(the_geom) FROM (SELECT 'LINESTRING(0 0, 0 1, 1 0, 1 1, 0 0)'::geometry AS the_geom) AS foo ; st_isring | st_isclosed | st_issimple -----------+-------------+------------- f | t | f (1 row)
ST_IsSimple — Teste si une géométrie n'a pas de points d'auto-intersection ou d'auto-tangente.
boolean ST_IsSimple(
geometry geomA)
;
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"
![]() | |
La norme SQL-MM indique que le résultat de la fonction |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s2.1.1.1
This method implements the SQL/MM specification. SQL-MM 3 : 5.1.8
This function supports 3d and will not drop the z-index.
ST_M — Returns the M coordinate of a Point.
float ST_M(
geometry a_point)
;
Retourne les coordonnées M d'un point, ou NULL si non disponible. L'entrée doit être un point.
![]() | |
This is not (yet) part of the OGC spec, but is listed here to complete the point coordinate extractor function list. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification.
This function supports 3d and will not drop the z-index.
ST_MemSize — Renvoie la quantité d'espace mémoire que prend une géométrie.
integer ST_MemSize(
geometry geomA)
;
Renvoie la quantité d'espace mémoire (en octets) que prend la géométrie.
This complements the PostgreSQL built-in database object functions pg_column_size, pg_size_pretty, pg_relation_size, pg_total_relation_size.
![]() | |
pg_relation_size which gives the byte size of a table may return byte size lower than ST_MemSize. This is because pg_relation_size does not add toasted table contribution and large geometries are stored in TOAST tables. pg_total_relation_size - includes, the table, the toasted tables, and the indexes. pg_column_size returns how much space a geometry would take in a column considering compression, so may be lower than ST_MemSize |
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Changed: 2.2.0 name changed to ST_MemSize to follow naming convention.
--Return how much byte space Boston takes up in our Mass data set SELECT pg_size_pretty(SUM(ST_MemSize(geom))) as totgeomsum, pg_size_pretty(SUM(CASE WHEN town = 'BOSTON' THEN ST_MemSize(geom) ELSE 0 END)) As bossum, CAST(SUM(CASE WHEN town = 'BOSTON' THEN ST_MemSize(geom) ELSE 0 END)*1.00 / SUM(ST_MemSize(geom))*100 As numeric(10,2)) As perbos FROM towns; totgeomsum bossum perbos ---------- ------ ------ 1522 kB 30 kB 1.99 SELECT ST_MemSize(ST_GeomFromText('CIRCULARSTRING(220268 150415,220227 150505,220227 150406)')); --- 73 --What percentage of our table is taken up by just the geometry SELECT pg_total_relation_size('public.neighborhoods') As fulltable_size, sum(ST_MemSize(geom)) As geomsize, sum(ST_MemSize(geom))*1.00/pg_total_relation_size('public.neighborhoods')*100 As pergeom FROM neighborhoods; fulltable_size geomsize pergeom ------------------------------------------------ 262144 96238 36.71188354492187500000
ST_NDims — Renvoie la dimension des coordonnées d'une géométrie.
integer ST_NDims(
geometry g1)
;
Returns the coordinate dimension of the geometry. PostGIS supports 2 - (x,y) , 3 - (x,y,z) or 2D with measure - x,y,m, and 4 - 3D with measure space x,y,z,m
This function supports 3d and will not drop the z-index.
ST_NPoints — Retourne le nombre de points (vertex) d'un objet géométrique.
integer ST_NPoints(
geometry g1)
;
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 polyédriques.
![]() | |
Prior to 1.3.4, this function crashes if used with geometries that contain CURVES. This is fixed in 1.3.4+ |
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
ST_NRings — Renvoie le nombre d'anneaux dans une géométrie polygonale.
integer ST_NRings(
geometry geomA)
;
If the geometry is a polygon or multi-polygon returns the number of rings. Unlike NumInteriorRings, it counts the outer rings as well.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
ST_NumGeometries — Renvoie le nombre d'éléments dans une collection de géométrie.
integer ST_NumGeometries(
geometry geom)
;
Returns the number of Geometries. If geometry is a GEOMETRYCOLLECTION (or MULTI*) return the number of geometries, for single geometries will return 1, otherwise return NULL.
Amélioration : 2.0.0 introduction du support TIN, Triangles et surfaces polyé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).
--Prior versions would have returned NULL for this -- in 2.0.0 this returns 1 SELECT ST_NumGeometries(ST_GeomFromText('LINESTRING(77.29 29.07,77.42 29.26,77.27 29.31,77.29 29.07)')); --result 1 --Geometry Collection Example - multis count as one geom in a collection SELECT ST_NumGeometries(ST_GeomFromEWKT('GEOMETRYCOLLECTION(MULTIPOINT((-2 3),(-2 2)), LINESTRING(5 5 ,10 10), POLYGON((-7 4.2,-7.1 5,-7.1 4.3,-7 4.2)))')); --result 3
ST_NumInteriorRings — Renvoie le nombre d'anneaux intérieurs (trous) d'un polygone.
integer ST_NumInteriorRings(
geometry a_polygon)
;
Return the number of interior rings of a polygon geometry. Return NULL if the geometry is not a polygon.
This method implements the SQL/MM specification. SQL-MM 3 : 8.2.5
Changed: 2.0.0 - in prior versions it would allow passing a MULTIPOLYGON, returning the number of interior rings of first POLYGON.
--If you have a regular polygon SELECT gid, field1, field2, ST_NumInteriorRings(geom) AS numholes FROM sometable; --If you have multipolygons --And you want to know the total number of interior rings in the MULTIPOLYGON SELECT gid, field1, field2, SUM(ST_NumInteriorRings(geom)) AS numholes FROM (SELECT gid, field1, field2, (ST_Dump(geom)).geom As geom FROM sometable) As foo GROUP BY gid, field1,field2;
ST_NumInteriorRing — Returns the number of interior rings (holes) of a Polygon. Aias for ST_NumInteriorRings
integer ST_NumInteriorRing(
geometry a_polygon)
;
ST_NumPatches — Return the number of faces on a Polyhedral Surface. Will return null for non-polyhedral geometries.
integer ST_NumPatches(
geometry g1)
;
Return the number of faces on a Polyhedral Surface. Will return null for non-polyhedral geometries. This is an alias for ST_NumGeometries to support MM naming. Faster to use ST_NumGeometries if you don't care about MM convention.
Disponibilité : 2.0.0
This function supports 3d and will not drop the z-index.
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM ISO/IEC 13249-3: 8.5
This function supports Polyhedral surfaces.
SELECT ST_NumPatches(ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )')); --result 6
ST_NumPoints — Renvoie le nombre de points dans une LineString ou une CircularString.
integer ST_NumPoints(
geometry g1)
;
Return the number of points in an ST_LineString or ST_CircularString value. Prior to 1.4 only works with linestrings as the specs state. From 1.4 forward this is an alias for ST_NPoints which returns number of vertexes for not just linestrings. Consider using ST_NPoints instead which is multi-purpose and works with many geometry types.
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3 : 7.2.4
ST_PatchN — Renvoie la Nième géométrie (face) d'une PolyhedralSurface.
geometry ST_PatchN(
geometry geomA, integer n)
;
Returns the 1-based Nth geometry (face) if the geometry is a POLYHEDRALSURFACE or POLYHEDRALSURFACEM. Otherwise, returns NULL. This returns the same answer as ST_GeometryN for PolyhedralSurfaces. Using ST_GeometryN is faster.
![]() | |
Index is 1-based. |
![]() | |
Si vous voulez extraire tous les éléments d'une géométrie, ST_Dump est plus efficace. |
Disponibilité : 2.0.0
This method implements the SQL/MM specification. SQL-MM ISO/IEC 13249-3: 8.5
This function supports 3d and will not drop the z-index.
This function supports Polyhedral surfaces.
--Extract the 2nd face of the polyhedral surface SELECT ST_AsEWKT(ST_PatchN(geom, 2)) As geomewkt FROM ( VALUES (ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )')) ) As foo(geom); geomewkt ---+----------------------------------------- POLYGON((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0))
ST_PointN — Renvoie le Nième point de la première LineString ou LineString circulaire d'une géométrie.
geometry ST_PointN(
geometry a_linestring, integer n)
;
Return the Nth point in a single linestring or circular linestring in the geometry. Negative values are counted backwards from the end of the LineString, so that -1 is the last point. Returns NULL if there is no linestring in the geometry.
![]() | |
Index is 1-based as for OGC specs since version 0.8.0. Backward indexing (negative index) is not in OGC Previous versions implemented this as 0-based instead. |
![]() | |
If you want to get the Nth point of each LineString in a MultiLineString, use in conjunction with ST_Dump |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3 : 7.2.5, 7.3.5
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
![]() | |
Changed: 2.0.0 no longer works with single geometry multilinestrings. In older versions of PostGIS -- a single line multilinestring would work happily with this function and return the start point. In 2.0.0 it just returns NULL like any other multilinestring. Changed: 2.3.0 : negative indexing available (-1 is last point) |
-- Extract all POINTs from a LINESTRING SELECT ST_AsText( ST_PointN( column1, generate_series(1, ST_NPoints(column1)) )) FROM ( VALUES ('LINESTRING(0 0, 1 1, 2 2)'::geometry) ) AS foo; st_astext ------------ POINT(0 0) POINT(1 1) POINT(2 2) (3 rows) --Example circular string SELECT ST_AsText(ST_PointN(ST_GeomFromText('CIRCULARSTRING(1 2, 3 2, 1 2)'), 2)); st_astext ------------ POINT(3 2) (1 row) SELECT ST_AsText(f) FROM ST_GeomFromText('LINESTRING(0 0 0, 1 1 1, 2 2 2)') AS g ,ST_PointN(g, -2) AS f; -- 1 based index st_astext ----------------- POINT Z (1 1 1) (1 row)
ST_Points — Renvoie un MultiPoint contenant les coordonnées d'une géométrie.
geometry ST_Points(
geometry geom )
;
Returns a MultiPoint containing all the coordinates of a geometry. Duplicate points are preserved, including the start and end points of ring geometries. (If desired, duplicate points can be removed by calling ST_RemoveRepeatedPoints on the result).
To obtain information about the position of each coordinate in the parent geometry use ST_DumpPoints.
M and Z coordinates are preserved if present.
This method supports Circular Strings and Curves
This function supports 3d and will not drop the z-index.
Disponibilité : 2.3.0
ST_StartPoint — Returns the first point of a LineString.
geometry ST_StartPoint(
geometry geomA)
;
Renvoie le premier point d'une géométrie LINESTRING
ou CIRCULARLINESTRING
comme un POINT
. Renvoie NULL
si l'entrée n'est pas une LINESTRING
ou CIRCULARLINESTRING
.
This method implements the SQL/MM specification. SQL-MM 3 : 7.1.3
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
![]() | |
Enhanced: 3.2.0 returns a point for all geometries. Prior behavior returns NULLs if input was not a LineString. Modifié : 2.0.0 ne fonctionne plus avec les MultiLineStrings à géométrie unique. Dans les anciennes versions de PostGIS, une MultiLineString à géométrie unique fonctionnait sans problème avec cette fonction et renvoyait le point de départ. Dans la version 2.0.0, elle renvoie simplement NULL comme toute autre MultiLineString. L'ancien comportement était une fonctionnalité non documentée, mais les personnes qui supposaient que leurs données étaient stockées en tant que LINESTRING peuvent voir ces données retourner NULL dans la version 2.0.0. |
Start point of a LineString
SELECT ST_AsText(ST_StartPoint('LINESTRING(0 1, 0 2)'::geometry)); st_astext ------------ POINT(0 1)
Start point of a non-LineString is NULL
SELECT ST_StartPoint('POINT(0 1)'::geometry) IS NULL AS is_null; is_null ---------- t
Start point of a 3D LineString
SELECT ST_AsEWKT(ST_StartPoint('LINESTRING(0 1 1, 0 2 2)'::geometry)); st_asewkt ------------ POINT(0 1 1)
Point de départ d'une CircularString
SELECT ST_AsText(ST_StartPoint('CIRCULARSTRING(5 2,-3 1.999999, -2 1, -4 2, 6 3)'::geometry)); st_astext ------------ POINT(5 2)
ST_Summary — Renvoie un résumé textuel du contenu d'une géométrie.
text ST_Summary(
geometry g)
;
text ST_Summary(
geography g)
;
Renvoie un résumé textuel du contenu de la géométrie.
Flags shown square brackets after the geometry type have the following meaning:
M : possède une coordonné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).
Disponibilité : 1.2.2
Enhanced: 2.0.0 added support for geography
Enhanced: 2.1.0 S flag to denote if has a known spatial reference system
Enhanced: 2.2.0 Added support for TIN and Curves
=# SELECT ST_Summary(ST_GeomFromText('LINESTRING(0 0, 1 1)')) as geom, ST_Summary(ST_GeogFromText('POLYGON((0 0, 1 1, 1 2, 1 1, 0 0))')) geog; geom | geog -----------------------------+-------------------------- LineString[B] with 2 points | Polygon[BGS] with 1 rings | ring 0 has 5 points : (1 row) =# SELECT ST_Summary(ST_GeogFromText('LINESTRING(0 0 1, 1 1 1)')) As geog_line, ST_Summary(ST_GeomFromText('SRID=4326;POLYGON((0 0 1, 1 1 2, 1 2 3, 1 1 1, 0 0 1))')) As geom_poly; ; geog_line | geom_poly -------------------------------- +-------------------------- LineString[ZBGS] with 2 points | Polygon[ZBS] with 1 rings : ring 0 has 5 points : (1 row)
ST_X — Returns the X coordinate of a Point.
float ST_X(
geometry a_point)
;
Renvoie la coordonnée X du point, ou NULL si elle n'est pas disponible. L'entrée doit être un point.
![]() | |
To get the minimum and maximum X value of geometry coordinates use the functions ST_XMin and ST_XMax. |
This method implements the SQL/MM specification. SQL-MM 3 : 6.1.3
This function supports 3d and will not drop the z-index.
ST_Y — Returns the Y coordinate of a Point.
float ST_Y(
geometry a_point)
;
Renvoie la coordonnée Y du point, ou NULL si elle n'est pas disponible. L'entrée doit être un point.
![]() | |
To get the minimum and maximum Y value of geometry coordinates use the functions ST_YMin and ST_YMax. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3 : 6.1.4
This function supports 3d and will not drop the z-index.
ST_Z — Returns the Z coordinate of a Point.
float ST_Z(
geometry a_point)
;
Renvoie la coordonnée Z du point, ou NULL si elle n'est pas disponible. L'entrée doit être un point.
![]() | |
To get the minimum and maximum Z value of geometry coordinates use the functions ST_ZMin and ST_ZMax. |
This method implements the SQL/MM specification.
This function supports 3d and will not drop the z-index.
ST_Zmflag — Retourne un code indiquant la dimension des coordonnées ZM d'une géométrie.
smallint ST_Zmflag(
geometry geomA)
;
Retourne un code indiquant la dimension des coordonnées ZM d'une géométrie.
Values are: 0 = 2D, 1 = 3D-M, 2 = 3D-Z, 3 = 4D.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
SELECT ST_Zmflag(ST_GeomFromEWKT('LINESTRING(1 2, 3 4)')) ; st_zmflag ----------- 0 SELECT ST_Zmflag(ST_GeomFromEWKT('LINESTRINGM(1 2 3, 3 4 3)')) ; st_zmflag ----------- 1 SELECT ST_Zmflag(ST_GeomFromEWKT('CIRCULARSTRING(1 2 3, 3 4 3, 5 6 3)')) ; st_zmflag ----------- 2 SELECT ST_Zmflag(ST_GeomFromEWKT('POINT(1 2 3 4)')) ; st_zmflag ----------- 3
ST_AddPoint — Add a point to a LineString.
geometry ST_AddPoint(
geometry linestring, geometry point)
;
geometry ST_AddPoint(
geometry linestring, geometry point, integer position = -1)
;
Adds a point to a LineString before the index position
(using a 0-based index). If the position
parameter is omitted or is -1 the point is appended to the end of the LineString.
Disponibilité : 1.1.0
This function supports 3d and will not drop the z-index.
Add a point to the end of a 3D line
SELECT ST_AsEWKT(ST_AddPoint('LINESTRING(0 0 1, 1 1 1)', ST_MakePoint(1, 2, 3))); st_asewkt ---------- LINESTRING(0 0 1,1 1 1,1 2 3)
Guarantee all lines in a table are closed by adding the start point of each line to the end of the line only for those that are not closed.
UPDATE sometable SET geom = ST_AddPoint(geom, ST_StartPoint(geom)) FROM sometable WHERE ST_IsClosed(geom) = false;
ST_CollectionExtract — Given a geometry collection, returns a multi-geometry containing only elements of a specified type.
geometry ST_CollectionExtract(
geometry collection)
;
geometry ST_CollectionExtract(
geometry collection, integer type)
;
Given a geometry collection, returns a homogeneous multi-geometry.
If the type
is not specified, returns a multi-geometry containing only geometries of the highest dimension. So polygons are preferred over lines, which are preferred over points.
If the type
is specified, returns a multi-geometry containing only that type. If there are no sub-geometries of the right type, an EMPTY geometry is returned. Only points, lines and polygons are supported. The type numbers are:
1 == POINT
2 == LINESTRING
3 == POLYGON
For atomic geometry inputs, the geometry is retured unchanged if the input type matches the requested type. Otherwise, the result is an EMPTY geometry of the specified type. If required, these can be converted to multi-geometries using ST_Multi.
![]() | |
MultiPolygon results are not checked for validity. If the polygon components are adjacent or overlapping the result will be invalid. (For example, this can occur when applying this function to an ST_Split result.) This situation can be checked with ST_IsValid and repaired with ST_MakeValid. |
Disponibilité : 1.5.0
![]() | |
Prior to 1.5.3 this function returned atomic inputs unchanged, no matter type. In 1.5.3 non-matching single geometries returned a NULL result. In 2.0.0 non-matching single geometries return an EMPTY result of the requested type. |
Extract highest-dimension type:
SELECT ST_AsText(ST_CollectionExtract( 'GEOMETRYCOLLECTION( POINT(0 0), LINESTRING(1 1, 2 2) )')); st_astext --------------- MULTILINESTRING((1 1, 2 2))
Extract points (type 1 == POINT):
SELECT ST_AsText(ST_CollectionExtract( 'GEOMETRYCOLLECTION(GEOMETRYCOLLECTION(POINT(0 0)))', 1 )); st_astext --------------- MULTIPOINT((0 0))
Extract lines (type 2 == LINESTRING):
SELECT ST_AsText(ST_CollectionExtract( 'GEOMETRYCOLLECTION(GEOMETRYCOLLECTION(LINESTRING(0 0, 1 1)),LINESTRING(2 2, 3 3))', 2 )); st_astext --------------- MULTILINESTRING((0 0, 1 1), (2 2, 3 3))
ST_CollectionHomogenize — Returns the simplest representation of a geometry collection.
geometry ST_CollectionHomogenize(
geometry collection)
;
Given a geometry collection, returns the "simplest" representation of the contents.
Homogeneous (uniform) collections are returned as the appropriate multi-geometry.
Heterogeneous (mixed) collections are flattened into a single GeometryCollection.
Collections containing a single atomic element are returned as that element.
Atomic geometries are returned unchanged. If required, these can be converted to a multi-geometry using ST_Multi.
![]() | |
This function does not ensure that the result is valid. In particular, a collection containing adjacent or overlapping Polygons will create an invalid MultiPolygon. This situation can be checked with ST_IsValid and repaired with ST_MakeValid. |
Disponibilité : 2.0.0
Single-element collection converted to an atomic geometry
SELECT ST_AsText(ST_CollectionHomogenize('GEOMETRYCOLLECTION(POINT(0 0))')); st_astext ------------ POINT(0 0)
Nested single-element collection converted to an atomic geometry:
SELECT ST_AsText(ST_CollectionHomogenize('GEOMETRYCOLLECTION(MULTIPOINT((0 0)))')); st_astext ------------ POINT(0 0)
Collection converted to a multi-geometry:
SELECT ST_AsText(ST_CollectionHomogenize('GEOMETRYCOLLECTION(POINT(0 0),POINT(1 1))')); st_astext --------------------- MULTIPOINT((0 0),(1 1))
Nested heterogeneous collection flattened to a GeometryCollection:
SELECT ST_AsText(ST_CollectionHomogenize('GEOMETRYCOLLECTION(POINT(0 0), GEOMETRYCOLLECTION( LINESTRING(1 1, 2 2)))')); st_astext --------------------- GEOMETRYCOLLECTION(POINT(0 0),LINESTRING(1 1,2 2))
Collection of Polygons converted to an (invalid) MultiPolygon:
SELECT ST_AsText(ST_CollectionHomogenize('GEOMETRYCOLLECTION (POLYGON ((10 50, 50 50, 50 10, 10 10, 10 50)), POLYGON ((90 50, 90 10, 50 10, 50 50, 90 50)))')); st_astext --------------------- MULTIPOLYGON(((10 50,50 50,50 10,10 10,10 50)),((90 50,90 10,50 10,50 50,90 50)))
ST_CurveToLine — Converts a geometry containing curves to a linear geometry.
geometry ST_CurveToLine(
geometry curveGeom, float tolerance, integer tolerance_type, integer flags)
;
Converts a CIRCULAR STRING to regular LINESTRING or CURVEPOLYGON to POLYGON or MULTISURFACE to MULTIPOLYGON. Useful for outputting to devices that can't support CIRCULARSTRING geometry types
Converts a given geometry to a linear geometry. Each curved geometry or segment is converted into a linear approximation using the given `tolerance` and options (32 segments per quadrant and no options by default).
The 'tolerance_type' argument determines interpretation of the `tolerance` argument. It can take the following values:
0 (default): Tolerance is max segments per quadrant.
1: Tolerance is max-deviation of line from curve, in source units.
2: Tolerance is max-angle, in radians, between generating radii.
The 'flags' argument is a bitfield. 0 by default. Supported bits are:
1: Symmetric (orientation idependent) output.
2: Retain angle, avoids reducing angles (segment lengths) when producing symmetric output. Has no effect when Symmetric flag is off.
Availability: 1.3.0
Enhanced: 2.4.0 added support for max-deviation and max-angle tolerance, and for symmetric output.
Enhanced: 3.0.0 implemented a minimum number of segments per linearized arc to prevent topological collapse.
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3: 7.1.7
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
SELECT ST_AsText(ST_CurveToLine(ST_GeomFromText('CIRCULARSTRING(220268 150415,220227 150505,220227 150406)'))); --Result -- LINESTRING(220268 150415,220269.95064912 150416.539364228,220271.823415575 150418.17258804,220273.613787707 150419.895736857, 220275.317452352 150421.704659462,220276.930305234 150423.594998003,220278.448460847 150425.562198489, 220279.868261823 150427.60152176,220281.186287736 150429.708054909,220282.399363347 150431.876723113, 220283.50456625 150434.10230186,220284.499233914 150436.379429536,220285.380970099 150438.702620341,220286.147650624 150441.066277505, 220286.797428488 150443.464706771,220287.328738321 150445.892130112,220287.740300149 150448.342699654, 220288.031122486 150450.810511759,220288.200504713 150453.289621251,220288.248038775 150455.77405574, 220288.173610157 150458.257830005,220287.977398166 150460.734960415,220287.659875492 150463.199479347, 220287.221807076 150465.64544956,220286.664248262 150468.066978495,220285.988542259 150470.458232479,220285.196316903 150472.81345077, 220284.289480732 150475.126959442,220283.270218395 150477.39318505,220282.140985384 150479.606668057, 220280.90450212 150481.762075989,220279.5637474 150483.85421628,220278.12195122 150485.87804878, 220276.582586992 150487.828697901,220274.949363179 150489.701464356,220273.226214362 150491.491836488, 220271.417291757 150493.195501133,220269.526953216 150494.808354014,220267.559752731 150496.326509628, 220265.520429459 150497.746310603,220263.41389631 150499.064336517,220261.245228106 150500.277412127, 220259.019649359 150501.38261503,220256.742521683 150502.377282695,220254.419330878 150503.259018879, 220252.055673714 150504.025699404,220249.657244448 150504.675477269,220247.229821107 150505.206787101, 220244.779251566 150505.61834893,220242.311439461 150505.909171266,220239.832329968 150506.078553494, 220237.347895479 150506.126087555,220234.864121215 150506.051658938,220232.386990804 150505.855446946, 220229.922471872 150505.537924272,220227.47650166 150505.099855856,220225.054972724 150504.542297043, 220222.663718741 150503.86659104,220220.308500449 150503.074365683, 220217.994991777 150502.167529512,220215.72876617 150501.148267175, 220213.515283163 150500.019034164,220211.35987523 150498.7825509, 220209.267734939 150497.441796181,220207.243902439 150496, 220205.293253319 150494.460635772,220203.420486864 150492.82741196,220201.630114732 150491.104263143, 220199.926450087 150489.295340538,220198.313597205 150487.405001997,220196.795441592 150485.437801511, 220195.375640616 150483.39847824,220194.057614703 150481.291945091,220192.844539092 150479.123276887,220191.739336189 150476.89769814, 220190.744668525 150474.620570464,220189.86293234 150472.297379659,220189.096251815 150469.933722495, 220188.446473951 150467.535293229,220187.915164118 150465.107869888,220187.50360229 150462.657300346, 220187.212779953 150460.189488241,220187.043397726 150457.710378749,220186.995863664 150455.22594426, 220187.070292282 150452.742169995,220187.266504273 150450.265039585,220187.584026947 150447.800520653, 220188.022095363 150445.35455044,220188.579654177 150442.933021505,220189.25536018 150440.541767521, 220190.047585536 150438.18654923,220190.954421707 150435.873040558,220191.973684044 150433.60681495, 220193.102917055 150431.393331943,220194.339400319 150429.237924011,220195.680155039 150427.14578372,220197.12195122 150425.12195122, 220198.661315447 150423.171302099,220200.29453926 150421.298535644,220202.017688077 150419.508163512,220203.826610682 150417.804498867, 220205.716949223 150416.191645986,220207.684149708 150414.673490372,220209.72347298 150413.253689397,220211.830006129 150411.935663483, 220213.998674333 150410.722587873,220216.22425308 150409.61738497,220218.501380756 150408.622717305,220220.824571561 150407.740981121, 220223.188228725 150406.974300596,220225.586657991 150406.324522731,220227 150406) --3d example SELECT ST_AsEWKT(ST_CurveToLine(ST_GeomFromEWKT('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)'))); Output ------ LINESTRING(220268 150415 1,220269.95064912 150416.539364228 1.0181172856673, 220271.823415575 150418.17258804 1.03623457133459,220273.613787707 150419.895736857 1.05435185700189,....AD INFINITUM .... 220225.586657991 150406.324522731 1.32611114201132,220227 150406 3) --use only 2 segments to approximate quarter circle SELECT ST_AsText(ST_CurveToLine(ST_GeomFromText('CIRCULARSTRING(220268 150415,220227 150505,220227 150406)'),2)); st_astext ------------------------------ LINESTRING(220268 150415,220287.740300149 150448.342699654,220278.12195122 150485.87804878, 220244.779251566 150505.61834893,220207.243902439 150496,220187.50360229 150462.657300346, 220197.12195122 150425.12195122,220227 150406) -- Ensure approximated line is no further than 20 units away from -- original curve, and make the result direction-neutral SELECT ST_AsText(ST_CurveToLine( 'CIRCULARSTRING(0 0,100 -100,200 0)'::geometry, 20, -- Tolerance 1, -- Above is max distance between curve and line 1 -- Symmetric flag )); st_astext ------------------------------------------------------------------------------------------- LINESTRING(0 0,50 -86.6025403784438,150 -86.6025403784439,200 -1.1331077795296e-13,200 0)
ST_Scroll — Change start point of a closed LineString.
geometry ST_Scroll(
geometry linestring, geometry point)
;
Changes the start/end point of a closed LineString to the given vertex point
.
Disponibilité : 3.2.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_FlipCoordinates — Returns a version of a geometry with X and Y axis flipped.
geometry ST_FlipCoordinates(
geometry geom)
;
Returns a version of the given geometry with X and Y axis flipped. Useful for fixing geometries which contain coordinates expressed as latitude/longitude (Y,X).
Disponibilité : 2.0.0
This method supports Circular Strings and Curves
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
ST_Force2D — Force the geometries into a "2-dimensional mode".
geometry ST_Force2D(
geometry geomA)
;
Forces the geometries into a "2-dimensional mode" so that all output representations will only have the X and Y coordinates. This is useful for force OGC-compliant output (since OGC only specifies 2-D geometries).
Amélioration : 2.0.0 introduction du support des surfaces polyédriques.
Changed: 2.1.0. Up to 2.0.x this was called ST_Force_2D.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports 3d and will not drop the z-index.
SELECT ST_AsEWKT(ST_Force2D(ST_GeomFromEWKT('CIRCULARSTRING(1 1 2, 2 3 2, 4 5 2, 6 7 2, 5 6 2)'))); st_asewkt ------------------------------------- CIRCULARSTRING(1 1,2 3,4 5,6 7,5 6) SELECT ST_AsEWKT(ST_Force2D('POLYGON((0 0 2,0 5 2,5 0 2,0 0 2),(1 1 2,3 1 2,1 3 2,1 1 2))')); st_asewkt ---------------------------------------------- POLYGON((0 0,0 5,5 0,0 0),(1 1,3 1,1 3,1 1))
ST_Force3D — Force the geometries into XYZ mode. This is an alias for ST_Force3DZ.
geometry ST_Force3D(
geometry geomA, float Zvalue = 0.0)
;
Forces the geometries into XYZ mode. This is an alias for ST_Force3DZ. If a geometry has no Z component, then a Zvalue
Z coordinate is tacked on.
Amélioration : 2.0.0 introduction du support des surfaces polyédriques.
Changed: 2.1.0. Up to 2.0.x this was called ST_Force_3D.
Changed: 3.1.0. Added support for supplying a non-zero Z value.
This function supports Polyhedral surfaces.
This method supports Circular Strings and Curves
This function supports 3d and will not drop the z-index.
--Nothing happens to an already 3D geometry SELECT ST_AsEWKT(ST_Force3D(ST_GeomFromEWKT('CIRCULARSTRING(1 1 2, 2 3 2, 4 5 2, 6 7 2, 5 6 2)'))); st_asewkt ----------------------------------------------- CIRCULARSTRING(1 1 2,2 3 2,4 5 2,6 7 2,5 6 2) SELECT ST_AsEWKT(ST_Force3D('POLYGON((0 0,0 5,5 0,0 0),(1 1,3 1,1 3,1 1))')); st_asewkt -------------------------------------------------------------- POLYGON((0 0 0,0 5 0,5 0 0,0 0 0),(1 1 0,3 1 0,1 3 0,1 1 0))
ST_Force3DZ — Force the geometries into XYZ mode.
geometry ST_Force3DZ(
geometry geomA, float Zvalue = 0.0)
;
Forces the geometries into XYZ mode. If a geometry has no Z component, then a Zvalue
Z coordinate is tacked on.
Amélioration : 2.0.0 introduction du support des surfaces polyédriques.
Changed: 2.1.0. Up to 2.0.x this was called ST_Force_3DZ.
Changed: 3.1.0. Added support for supplying a non-zero Z value.
This function supports Polyhedral surfaces.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
--Nothing happens to an already 3D geometry SELECT ST_AsEWKT(ST_Force3DZ(ST_GeomFromEWKT('CIRCULARSTRING(1 1 2, 2 3 2, 4 5 2, 6 7 2, 5 6 2)'))); st_asewkt ----------------------------------------------- CIRCULARSTRING(1 1 2,2 3 2,4 5 2,6 7 2,5 6 2) SELECT ST_AsEWKT(ST_Force3DZ('POLYGON((0 0,0 5,5 0,0 0),(1 1,3 1,1 3,1 1))')); st_asewkt -------------------------------------------------------------- POLYGON((0 0 0,0 5 0,5 0 0,0 0 0),(1 1 0,3 1 0,1 3 0,1 1 0))
ST_Force3DM — Force the geometries into XYM mode.
geometry ST_Force3DM(
geometry geomA, float Mvalue = 0.0)
;
Forces the geometries into XYM mode. If a geometry has no M component, then a Mvalue
M coordinate is tacked on. If it has a Z component, then Z is removed
Changed: 2.1.0. Up to 2.0.x this was called ST_Force_3DM.
Changed: 3.1.0. Added support for supplying a non-zero M value.
This method supports Circular Strings and Curves
--Nothing happens to an already 3D geometry SELECT ST_AsEWKT(ST_Force3DM(ST_GeomFromEWKT('CIRCULARSTRING(1 1 2, 2 3 2, 4 5 2, 6 7 2, 5 6 2)'))); st_asewkt ------------------------------------------------ CIRCULARSTRINGM(1 1 0,2 3 0,4 5 0,6 7 0,5 6 0) SELECT ST_AsEWKT(ST_Force3DM('POLYGON((0 0 1,0 5 1,5 0 1,0 0 1),(1 1 1,3 1 1,1 3 1,1 1 1))')); st_asewkt --------------------------------------------------------------- POLYGONM((0 0 0,0 5 0,5 0 0,0 0 0),(1 1 0,3 1 0,1 3 0,1 1 0))
ST_Force4D — Force the geometries into XYZM mode.
geometry ST_Force4D(
geometry geomA, float Zvalue = 0.0, float Mvalue = 0.0)
;
Forces the geometries into XYZM mode. Zvalue
and Mvalue
is tacked on for missing Z and M dimensions, respectively.
Changed: 2.1.0. Up to 2.0.x this was called ST_Force_4D.
Changed: 3.1.0. Added support for supplying non-zero Z and M values.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
--Nothing happens to an already 3D geometry SELECT ST_AsEWKT(ST_Force4D(ST_GeomFromEWKT('CIRCULARSTRING(1 1 2, 2 3 2, 4 5 2, 6 7 2, 5 6 2)'))); st_asewkt --------------------------------------------------------- CIRCULARSTRING(1 1 2 0,2 3 2 0,4 5 2 0,6 7 2 0,5 6 2 0) SELECT ST_AsEWKT(ST_Force4D('MULTILINESTRINGM((0 0 1,0 5 2,5 0 3,0 0 4),(1 1 1,3 1 1,1 3 1,1 1 1))')); st_asewkt -------------------------------------------------------------------------------------- MULTILINESTRING((0 0 0 1,0 5 0 2,5 0 0 3,0 0 0 4),(1 1 0 1,3 1 0 1,1 3 0 1,1 1 0 1))
ST_ForcePolygonCCW — Orients all exterior rings counter-clockwise and all interior rings clockwise.
geometry ST_ForcePolygonCCW (
geometry geom )
;
Forces (Multi)Polygons to use a counter-clockwise orientation for their exterior ring, and a clockwise orientation for their interior rings. Non-polygonal geometries are returned unchanged.
Disponibilité : 2.4.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_ForceCollection — Convert the geometry into a GEOMETRYCOLLECTION.
geometry ST_ForceCollection(
geometry geomA)
;
Converts the geometry into a GEOMETRYCOLLECTION. This is useful for simplifying the WKB representation.
Amélioration : 2.0.0 introduction du support des surfaces polyédriques.
Availability: 1.2.2, prior to 1.3.4 this function will crash with Curves. This is fixed in 1.3.4+
Changed: 2.1.0. Up to 2.0.x this was called ST_Force_Collection.
This function supports Polyhedral surfaces.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
SELECT ST_AsEWKT(ST_ForceCollection('POLYGON((0 0 1,0 5 1,5 0 1,0 0 1),(1 1 1,3 1 1,1 3 1,1 1 1))')); st_asewkt ---------------------------------------------------------------------------------- GEOMETRYCOLLECTION(POLYGON((0 0 1,0 5 1,5 0 1,0 0 1),(1 1 1,3 1 1,1 3 1,1 1 1))) SELECT ST_AsText(ST_ForceCollection('CIRCULARSTRING(220227 150406,2220227 150407,220227 150406)')); st_astext -------------------------------------------------------------------------------- GEOMETRYCOLLECTION(CIRCULARSTRING(220227 150406,2220227 150407,220227 150406)) (1 row)
-- POLYHEDRAL example -- SELECT ST_AsEWKT(ST_ForceCollection('POLYHEDRALSURFACE(((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)), ((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)), ((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)), ((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)), ((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)), ((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1)))')) st_asewkt ---------------------------------------------------------------------------------- GEOMETRYCOLLECTION( POLYGON((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)), POLYGON((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)), POLYGON((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)), POLYGON((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)), POLYGON((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)), POLYGON((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1)) )
ST_ForcePolygonCW — Orients all exterior rings clockwise and all interior rings counter-clockwise.
geometry ST_ForcePolygonCW (
geometry geom )
;
Forces (Multi)Polygons to use a clockwise orientation for their exterior ring, and a counter-clockwise orientation for their interior rings. Non-polygonal geometries are returned unchanged.
Disponibilité : 2.4.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_ForceSFS — Force the geometries to use SFS 1.1 geometry types only.
geometry ST_ForceSFS(
geometry geomA)
;
geometry ST_ForceSFS(
geometry geomA, text version)
;
ST_ForceRHR — Force the orientation of the vertices in a polygon to follow the Right-Hand-Rule.
geometry ST_ForceRHR(
geometry g)
;
Forces the orientation of the vertices in a polygon to follow a Right-Hand-Rule, in which the area that is bounded by the polygon is to the right of the boundary. In particular, the exterior ring is orientated in a clockwise direction and the interior rings in a counter-clockwise direction. This function is a synonym for ST_ForcePolygonCW
![]() | |
The above definition of the Right-Hand-Rule conflicts with definitions used in other contexts. To avoid confusion, it is recommended to use ST_ForcePolygonCW. |
Amélioration : 2.0.0 introduction du support des surfaces polyédriques.
This function supports 3d and will not drop the z-index.
This function supports Polyhedral surfaces.
SELECT ST_AsEWKT( ST_ForceRHR( 'POLYGON((0 0 2, 5 0 2, 0 5 2, 0 0 2),(1 1 2, 1 3 2, 3 1 2, 1 1 2))' ) ); st_asewkt -------------------------------------------------------------- POLYGON((0 0 2,0 5 2,5 0 2,0 0 2),(1 1 2,3 1 2,1 3 2,1 1 2)) (1 row)
ST_ForcePolygonCCW , ST_ForcePolygonCW , ST_IsPolygonCCW , ST_IsPolygonCW , ST_BuildArea, ST_Polygonize, ST_Reverse
ST_ForceCurve — Upcast a geometry into its curved type, if applicable.
geometry ST_ForceCurve(
geometry g)
;
Turns a geometry into its curved representation, if applicable: lines become compoundcurves, multilines become multicurves polygons become curvepolygons multipolygons become multisurfaces. If the geometry input is already a curved representation returns back same as input.
Disponibilité : 2.2.0
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
ST_LineToCurve — Converts a linear geometry to a curved geometry.
geometry ST_LineToCurve(
geometry geomANoncircular)
;
Converts plain LINESTRING/POLYGON to CIRCULAR STRINGs and Curved Polygons. Note much fewer points are needed to describe the curved equivalent.
![]() | |
If the input LINESTRING/POLYGON is not curved enough to clearly represent a curve, the function will return the same input geometry. |
Availability: 1.3.0
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
-- 2D Example SELECT ST_AsText(ST_LineToCurve(foo.geom)) As curvedastext,ST_AsText(foo.geom) As non_curvedastext FROM (SELECT ST_Buffer('POINT(1 3)'::geometry, 3) As geom) As foo; curvedatext non_curvedastext --------------------------------------------------------------------|----------------------------------------------------------------- CURVEPOLYGON(CIRCULARSTRING(4 3,3.12132034355964 0.878679656440359, | POLYGON((4 3,3.94235584120969 2.41472903395162,3.77163859753386 1.85194970290473, 1 0,-1.12132034355965 5.12132034355963,4 3)) | 3.49440883690764 1.33328930094119,3.12132034355964 0.878679656440359, | 2.66671069905881 0.505591163092366,2.14805029709527 0.228361402466141, | 1.58527096604839 0.0576441587903094,1 0, | 0.414729033951621 0.0576441587903077,-0.148050297095264 0.228361402466137, | -0.666710699058802 0.505591163092361,-1.12132034355964 0.878679656440353, | -1.49440883690763 1.33328930094119,-1.77163859753386 1.85194970290472 | --ETC-- ,3.94235584120969 3.58527096604839,4 3)) --3D example SELECT ST_AsText(ST_LineToCurve(geom)) As curved, ST_AsText(geom) AS not_curved FROM (SELECT ST_Translate(ST_Force3D(ST_Boundary(ST_Buffer(ST_Point(1,3), 2,2))),0,0,3) AS geom) AS foo; curved | not_curved ------------------------------------------------------+--------------------------------------------------------------------- CIRCULARSTRING Z (3 3 3,-1 2.99999999999999 3,3 3 3) | LINESTRING Z (3 3 3,2.4142135623731 1.58578643762691 3,1 1 3, | -0.414213562373092 1.5857864376269 3,-1 2.99999999999999 3, | -0.414213562373101 4.41421356237309 3, | 0.999999999999991 5 3,2.41421356237309 4.4142135623731 3,3 3 3) (1 row)
ST_Multi — Return the geometry as a MULTI* geometry.
geometry ST_Multi(
geometry geom)
;
Returns the geometry as a MULTI* geometry collection. If the geometry is already a collection, it is returned unchanged.
ST_Normalize — Return the geometry in its canonical form.
geometry ST_Normalize(
geometry geom)
;
Returns the geometry in its normalized/canonical form. May reorder vertices in polygon rings, rings in a polygon, elements in a multi-geometry complex.
Mostly only useful for testing purposes (comparing expected and obtained results).
Disponibilité : 2.3.0
SELECT ST_AsText(ST_Normalize(ST_GeomFromText( 'GEOMETRYCOLLECTION( POINT(2 3), MULTILINESTRING((0 0, 1 1),(2 2, 3 3)), POLYGON( (0 10,0 0,10 0,10 10,0 10), (4 2,2 2,2 4,4 4,4 2), (6 8,8 8,8 6,6 6,6 8) ) )' ))); st_astext ---------------------------------------------------------------------------------------------------------------------------------------------------- GEOMETRYCOLLECTION(POLYGON((0 0,0 10,10 10,10 0,0 0),(6 6,8 6,8 8,6 8,6 6),(2 2,4 2,4 4,2 4,2 2)),MULTILINESTRING((2 2,3 3),(0 0,1 1)),POINT(2 3)) (1 row)
ST_QuantizeCoordinates — Sets least significant bits of coordinates to zero
geometry ST_QuantizeCoordinates (
geometry g , int prec_x , int prec_y , int prec_z , int prec_m )
;
ST_QuantizeCoordinates
determines the number of bits (N
) required to represent a coordinate value with a specified number of digits after the decimal point, and then sets all but the N
most significant bits to zero. The resulting coordinate value will still round to the original value, but will have improved compressiblity. This can result in a significant disk usage reduction provided that the geometry column is using a compressible storage type. The function allows specification of a different number of digits after the decimal point in each dimension; unspecified dimensions are assumed to have the precision of the x
dimension. Negative digits are interpreted to refer digits to the left of the decimal point, (i.e., prec_x=-2
will preserve coordinate values to the nearest 100.
The coordinates produced by ST_QuantizeCoordinates
are independent of the geometry that contains those coordinates and the relative position of those coordinates within the geometry. As a result, existing topological relationships between geometries are unaffected by use of this function. The function may produce invalid geometry when it is called with a number of digits lower than the intrinsic precision of the geometry.
Disponibilité : 2.5.0
PostGIS stores all coordinate values as double-precision floating point integers, which can reliably represent 15 significant digits. However, PostGIS may be used to manage data that intrinsically has fewer than 15 significant digits. An example is TIGER data, which is provided as geographic coordinates with six digits of precision after the decimal point (thus requiring only nine significant digits of longitude and eight significant digits of latitude.)
When 15 significant digits are available, there are many possible representations of a number with 9 significant digits. A double precision floating point number uses 52 explicit bits to represent the significand (mantissa) of the coordinate. Only 30 bits are needed to represent a mantissa with 9 significant digits, leaving 22 insignificant bits; we can set their value to anything we like and still end up with a number that rounds to our input value. For example, the value 100.123456 can be represented by the floating point numbers closest to 100.123456000000, 100.123456000001, and 100.123456432199. All are equally valid, in that ST_AsText(geom, 6)
will return the same result with any of these inputs. As we can set these bits to any value, ST_QuantizeCoordinates
sets the 22 insignificant bits to zero. For a long coordinate sequence this creates a pattern of blocks of consecutive zeros that is compressed by PostgreSQL more effeciently.
![]() | |
Only the on-disk size of the geometry is potentially affected by |
SELECT ST_AsText(ST_QuantizeCoordinates('POINT (100.123456 0)'::geometry, 4)); st_astext ------------------------- POINT(100.123455047607 0)
WITH test AS (SELECT 'POINT (123.456789123456 123.456789123456)'::geometry AS geom) SELECT digits, encode(ST_QuantizeCoordinates(geom, digits), 'hex'), ST_AsText(ST_QuantizeCoordinates(geom, digits)) FROM test, generate_series(15, -15, -1) AS digits; digits | encode | st_astext --------+--------------------------------------------+------------------------------------------ 15 | 01010000005f9a72083cdd5e405f9a72083cdd5e40 | POINT(123.456789123456 123.456789123456) 14 | 01010000005f9a72083cdd5e405f9a72083cdd5e40 | POINT(123.456789123456 123.456789123456) 13 | 01010000005f9a72083cdd5e405f9a72083cdd5e40 | POINT(123.456789123456 123.456789123456) 12 | 01010000005c9a72083cdd5e405c9a72083cdd5e40 | POINT(123.456789123456 123.456789123456) 11 | 0101000000409a72083cdd5e40409a72083cdd5e40 | POINT(123.456789123456 123.456789123456) 10 | 0101000000009a72083cdd5e40009a72083cdd5e40 | POINT(123.456789123455 123.456789123455) 9 | 0101000000009072083cdd5e40009072083cdd5e40 | POINT(123.456789123418 123.456789123418) 8 | 0101000000008072083cdd5e40008072083cdd5e40 | POINT(123.45678912336 123.45678912336) 7 | 0101000000000070083cdd5e40000070083cdd5e40 | POINT(123.456789121032 123.456789121032) 6 | 0101000000000040083cdd5e40000040083cdd5e40 | POINT(123.456789076328 123.456789076328) 5 | 0101000000000000083cdd5e40000000083cdd5e40 | POINT(123.456789016724 123.456789016724) 4 | 0101000000000000003cdd5e40000000003cdd5e40 | POINT(123.456787109375 123.456787109375) 3 | 0101000000000000003cdd5e40000000003cdd5e40 | POINT(123.456787109375 123.456787109375) 2 | 01010000000000000038dd5e400000000038dd5e40 | POINT(123.45654296875 123.45654296875) 1 | 01010000000000000000dd5e400000000000dd5e40 | POINT(123.453125 123.453125) 0 | 01010000000000000000dc5e400000000000dc5e40 | POINT(123.4375 123.4375) -1 | 01010000000000000000c05e400000000000c05e40 | POINT(123 123) -2 | 01010000000000000000005e400000000000005e40 | POINT(120 120) -3 | 010100000000000000000058400000000000005840 | POINT(96 96) -4 | 010100000000000000000058400000000000005840 | POINT(96 96) -5 | 010100000000000000000058400000000000005840 | POINT(96 96) -6 | 010100000000000000000058400000000000005840 | POINT(96 96) -7 | 010100000000000000000058400000000000005840 | POINT(96 96) -8 | 010100000000000000000058400000000000005840 | POINT(96 96) -9 | 010100000000000000000058400000000000005840 | POINT(96 96) -10 | 010100000000000000000058400000000000005840 | POINT(96 96) -11 | 010100000000000000000058400000000000005840 | POINT(96 96) -12 | 010100000000000000000058400000000000005840 | POINT(96 96) -13 | 010100000000000000000058400000000000005840 | POINT(96 96) -14 | 010100000000000000000058400000000000005840 | POINT(96 96) -15 | 010100000000000000000058400000000000005840 | POINT(96 96)
ST_RemovePoint — Remove a point from a linestring.
geometry ST_RemovePoint(
geometry linestring, integer offset)
;
Removes a point from a LineString, given its index (0-based). Useful for turning a closed line (ring) into an open linestring.
Enhanced: 3.2.0
Disponibilité : 1.1.0
This function supports 3d and will not drop the z-index.
ST_RemoveRepeatedPoints — Returns a version of a geometry with duplicate points removed.
geometry ST_RemoveRepeatedPoints(
geometry geom, float8 tolerance)
;
Returns a version of the given geometry with duplicate consecutive points removed. The function processes only (Multi)LineStrings, (Multi)Polygons and MultiPoints but it can be called with any kind of geometry. Elements of GeometryCollections are processed individually. The endpoints of LineStrings are preserved.
If the tolerance
parameter is provided, vertices within the tolerance distance of one another are considered to be duplicates.
Enhanced: 3.2.0
Disponibilité : 2.2.0
This function supports Polyhedral surfaces.
This function supports 3d and will not drop the z-index.
SELECT ST_AsText( ST_RemoveRepeatedPoints( 'MULTIPOINT ((1 1), (2 2), (3 3), (2 2))')); ------------------------- MULTIPOINT(1 1,2 2,3 3)
SELECT ST_AsText( ST_RemoveRepeatedPoints( 'LINESTRING (0 0, 0 0, 1 1, 0 0, 1 1, 2 2)')); --------------------------------- LINESTRING(0 0,1 1,0 0,1 1,2 2)
Example: Collection elements are processed individually.
SELECT ST_AsText( ST_RemoveRepeatedPoints( 'GEOMETRYCOLLECTION (LINESTRING (1 1, 2 2, 2 2, 3 3), POINT (4 4), POINT (4 4), POINT (5 5))')); ------------------------------------------------------------------------------ GEOMETRYCOLLECTION(LINESTRING(1 1,2 2,3 3),POINT(4 4),POINT(4 4),POINT(5 5))
Example: Repeated point removal with a distance tolerance.
SELECT ST_AsText( ST_RemoveRepeatedPoints( 'LINESTRING (0 0, 0 0, 1 1, 5 5, 1 1, 2 2)', 2)); ------------------------- LINESTRING(0 0,5 5,2 2)
ST_Reverse — Return the geometry with vertex order reversed.
geometry ST_Reverse(
geometry g1)
;
ST_Segmentize — Return a modified geometry/geography having no segment longer than the given distance.
geometry ST_Segmentize(
geometry geom, float max_segment_length)
;
geography ST_Segmentize(
geography geog, float max_segment_length)
;
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.
Disponibilité : 1.2.2
Enhanced: 3.0.0 Segmentize geometry now uses equal length segments
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);
![]() | |
This will only increase segments. It will not lengthen segments shorter than max length |
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)
ST_SetPoint — Replace point of a linestring with a given point.
geometry ST_SetPoint(
geometry linestring, integer zerobasedposition, geometry point)
;
Replace point N of linestring with given point. Index is 0-based.Negative index are counted backwards, so that -1 is last point. This is especially useful in triggers when trying to maintain relationship of joints when one vertex moves.
Disponibilité : 1.1.0
Updated 2.3.0 : negative indexing
This function supports 3d and will not drop the z-index.
--Change first point in line string from -1 3 to -1 1 SELECT ST_AsText(ST_SetPoint('LINESTRING(-1 2,-1 3)', 0, 'POINT(-1 1)')); st_astext ----------------------- LINESTRING(-1 1,-1 3) ---Change last point in a line string (lets play with 3d linestring this time) SELECT ST_AsEWKT(ST_SetPoint(foo.geom, ST_NumPoints(foo.geom) - 1, ST_GeomFromEWKT('POINT(-1 1 3)'))) FROM (SELECT ST_GeomFromEWKT('LINESTRING(-1 2 3,-1 3 4, 5 6 7)') As geom) As foo; st_asewkt ----------------------- LINESTRING(-1 2 3,-1 3 4,-1 1 3) SELECT ST_AsText(ST_SetPoint(g, -3, p)) FROM ST_GEomFromText('LINESTRING(0 0, 1 1, 2 2, 3 3, 4 4)') AS g , ST_PointN(g,1) as p; st_astext ----------------------- LINESTRING(0 0,1 1,0 0,3 3,4 4)
ST_ShiftLongitude — Shifts the longitude coordinates of a geometry between -180..180 and 0..360.
geometry ST_ShiftLongitude(
geometry geom)
;
Reads every point/vertex in a geometry, and shifts its longitude coordinate from -180..0 to 180..360 and vice versa if between these ranges. This function is symmetrical so the result is a 0..360 representation of a -180..180 data and a -180..180 representation of a 0..360 data.
![]() | |
This is only useful for data with coordinates in longitude/latitude; e.g. SRID 4326 (WGS 84 geographic) |
![]() | |
Pre-1.3.4 bug prevented this from working for MULTIPOINT. 1.3.4+ works with MULTIPOINT as well. |
This function supports 3d and will not drop the z-index.
Amélioration : 2.0.0 introduction du support TIN et surfaces polyédriques.
NOTE: this function was renamed from "ST_Shift_Longitude" in 2.2.0
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
--single point forward transformation SELECT ST_AsText(ST_ShiftLongitude('SRID=4326;POINT(270 0)'::geometry)) st_astext ---------- POINT(-90 0) --single point reverse transformation SELECT ST_AsText(ST_ShiftLongitude('SRID=4326;POINT(-90 0)'::geometry)) st_astext ---------- POINT(270 0) --for linestrings the functions affects only to the sufficient coordinates SELECT ST_AsText(ST_ShiftLongitude('SRID=4326;LINESTRING(174 12, 182 13)'::geometry)) st_astext ---------- LINESTRING(174 12,-178 13)
ST_WrapX — Wrap a geometry around an X value.
geometry ST_WrapX(
geometry geom, float8 wrap, float8 move)
;
This function splits the input geometries and then moves every resulting component falling on the right (for negative 'move') or on the left (for positive 'move') of given 'wrap' line in the direction specified by the 'move' parameter, finally re-unioning the pieces together.
![]() | |
This is useful to "recenter" long-lat input to have features of interest not spawned from one side to the other. |
Availability: 2.3.0 requires GEOS
This function supports 3d and will not drop the z-index.
ST_SnapToGrid — Snap all points of the input geometry to a regular grid.
geometry ST_SnapToGrid(
geometry geomA, float originX, float originY, float sizeX, float sizeY)
;
geometry ST_SnapToGrid(
geometry geomA, float sizeX, float sizeY)
;
geometry ST_SnapToGrid(
geometry geomA, float size)
;
geometry ST_SnapToGrid(
geometry geomA, geometry pointOrigin, float sizeX, float sizeY, float sizeZ, float sizeM)
;
Variant 1,2,3: Snap all points of the input geometry to the grid defined by its origin and cell size. Remove consecutive points falling on the same cell, eventually returning NULL if output points are not enough to define a geometry of the given type. Collapsed geometries in a collection are stripped from it. Useful for reducing precision.
Variant 4: Introduced 1.1.0 - Snap all points of the input geometry to the grid defined by its origin (the second argument, must be a point) and cell sizes. Specify 0 as size for any dimension you don't want to snap to a grid.
![]() | |
The returned geometry might lose its simplicity (see ST_IsSimple). |
![]() | |
Before release 1.1.0 this function always returned a 2d geometry. Starting at 1.1.0 the returned geometry will have same dimensionality as the input one with higher dimension values untouched. Use the version taking a second geometry argument to define all grid dimensions. |
Disponibilité : 1.0.0RC1
Availability: 1.1.0 - Z and M support
This function supports 3d and will not drop the z-index.
--Snap your geometries to a precision grid of 10^-3 UPDATE mytable SET geom = ST_SnapToGrid(geom, 0.001); SELECT ST_AsText(ST_SnapToGrid( ST_GeomFromText('LINESTRING(1.1115678 2.123, 4.111111 3.2374897, 4.11112 3.23748667)'), 0.001) ); st_astext ------------------------------------- LINESTRING(1.112 2.123,4.111 3.237) --Snap a 4d geometry SELECT ST_AsEWKT(ST_SnapToGrid( ST_GeomFromEWKT('LINESTRING(-1.1115678 2.123 2.3456 1.11111, 4.111111 3.2374897 3.1234 1.1111, -1.11111112 2.123 2.3456 1.1111112)'), ST_GeomFromEWKT('POINT(1.12 2.22 3.2 4.4444)'), 0.1, 0.1, 0.1, 0.01) ); st_asewkt ------------------------------------------------------------------------------ LINESTRING(-1.08 2.12 2.3 1.1144,4.12 3.22 3.1 1.1144,-1.08 2.12 2.3 1.1144) --With a 4d geometry - the ST_SnapToGrid(geom,size) only touches x and y coords but keeps m and z the same SELECT ST_AsEWKT(ST_SnapToGrid(ST_GeomFromEWKT('LINESTRING(-1.1115678 2.123 3 2.3456, 4.111111 3.2374897 3.1234 1.1111)'), 0.01) ); st_asewkt --------------------------------------------------------- LINESTRING(-1.11 2.12 3 2.3456,4.11 3.24 3.1234 1.1111)
ST_Snap — Snap segments and vertices of input geometry to vertices of a reference geometry.
geometry ST_Snap(
geometry input, geometry reference, float tolerance)
;
Snaps the vertices and segments of a geometry to another Geometry's vertices. A snap distance tolerance is used to control where snapping is performed. The result geometry is the input geometry with the vertices snapped. If no snapping occurs then the input geometry is returned unchanged.
Snapping one geometry to another can improve robustness for overlay operations by eliminating nearly-coincident edges (which cause problems during noding and intersection calculation).
Too much snapping can result in invalid topology being created, so the number and location of snapped vertices is decided using heuristics to determine when it is safe to snap. This can result in some potential snaps being omitted, however.
![]() | |
The returned geometry might lose its simplicity (see ST_IsSimple) and validity (see ST_IsValid). |
Effectué par le module GEOS.
Disponibilité : 2.0.0
![]() A multipolygon shown with a linestring (before any snapping) | |
![]() A multipolygon snapped to linestring to tolerance: 1.01 of distance. The new multipolygon is shown with reference linestring
SELECT ST_AsText(ST_Snap(poly,line, ST_Distance(poly,line)*1.01)) AS polysnapped FROM (SELECT ST_GeomFromText('MULTIPOLYGON( ((26 125, 26 200, 126 200, 126 125, 26 125 ), ( 51 150, 101 150, 76 175, 51 150 )), (( 151 100, 151 200, 176 175, 151 100 )))') As poly, ST_GeomFromText('LINESTRING (5 107, 54 84, 101 100)') As line ) As foo; polysnapped --------------------------------------------------------------------- MULTIPOLYGON(((26 125,26 200,126 200,126 125,101 100,26 125), (51 150,101 150,76 175,51 150)),((151 100,151 200,176 175,151 100))) | ![]() A multipolygon snapped to linestring to tolerance: 1.25 of distance. The new multipolygon is shown with reference linestring
SELECT ST_AsText( ST_Snap(poly,line, ST_Distance(poly,line)*1.25) ) AS polysnapped FROM (SELECT ST_GeomFromText('MULTIPOLYGON( (( 26 125, 26 200, 126 200, 126 125, 26 125 ), ( 51 150, 101 150, 76 175, 51 150 )), (( 151 100, 151 200, 176 175, 151 100 )))') As poly, ST_GeomFromText('LINESTRING (5 107, 54 84, 101 100)') As line ) As foo; polysnapped --------------------------------------------------------------------- MULTIPOLYGON(((5 107,26 200,126 200,126 125,101 100,54 84,5 107), (51 150,101 150,76 175,51 150)),((151 100,151 200,176 175,151 100))) |
![]() The linestring snapped to the original multipolygon at tolerance 1.01 of distance. The new linestring is shown with reference multipolygon
SELECT ST_AsText( ST_Snap(line, poly, ST_Distance(poly,line)*1.01) ) AS linesnapped FROM (SELECT ST_GeomFromText('MULTIPOLYGON( ((26 125, 26 200, 126 200, 126 125, 26 125), (51 150, 101 150, 76 175, 51 150 )), ((151 100, 151 200, 176 175, 151 100)))') As poly, ST_GeomFromText('LINESTRING (5 107, 54 84, 101 100)') As line ) As foo; linesnapped ---------------------------------------- LINESTRING(5 107,26 125,54 84,101 100)
| ![]() The linestring snapped to the original multipolygon at tolerance 1.25 of distance. The new linestring is shown with reference multipolygon
SELECT ST_AsText( ST_Snap(line, poly, ST_Distance(poly,line)*1.25) ) AS linesnapped FROM (SELECT ST_GeomFromText('MULTIPOLYGON( (( 26 125, 26 200, 126 200, 126 125, 26 125 ), (51 150, 101 150, 76 175, 51 150 )), ((151 100, 151 200, 176 175, 151 100 )))') As poly, ST_GeomFromText('LINESTRING (5 107, 54 84, 101 100)') As line ) As foo; linesnapped --------------------------------------- LINESTRING(26 125,54 84,101 100) |
ST_SwapOrdinates — Returns a version of the given geometry with given ordinate values swapped.
geometry ST_SwapOrdinates(
geometry geom, cstring ords)
;
Returns a version of the given geometry with given ordinates swapped.
The ords
parameter is a 2-characters string naming the ordinates to swap. Valid names are: x,y,z and m.
Disponibilité : 2.2.0
This method supports Circular Strings and Curves
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Ces fonctions vérifient si les géométries sont valides selon la norme SFS de l'OGC. Elles fournissent également des informations sur la nature et la localisation de l'invalidité. Il existe également une fonction permettant de créer une géométrie valide à partir d'une géométrie invalide.
valid_detail
indiquant si une géométrie est valide ou sinon une raison et une localisation.ST_IsValid — Teste si une géométrie est bien formée en 2D.
boolean ST_IsValid(
geometry g)
;
boolean ST_IsValid(
geometry g, integer flags)
;
Teste si une valeur ST_Geometry est bien formée et valide en 2D selon les règles de l'OGC. Pour les géométries à 3 et 4 dimensions, la validité est toujours testée uniquement en 2 dimensions. Pour les géométries qui ne sont pas valides, une NOTICE PostgreSQL est émise fournissant les détails de la raison pour laquelle elle n'est pas valide.
Pour la version avec le paramètre flags
, les valeurs prises en charge sont documentées dans ST_IsValidDetail Cette version n'imprime pas de NOTICE expliquant l'invalidité.
Pour plus d'informations sur la définition de la validité des géométries, reportez-vous à Section 4.4, “Validation de la géométrie”.
![]() | |
SQL-MM définit le résultat de ST_IsValid(NULL) comme étant 0, alors que PostGIS renvoie NULL. |
Effectué par le module GEOS.
La version acceptant les flags est disponible à partir de la version 2.0.0.
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3 : 5.1.9
![]() | |
Les spécifications de l'OGC-SFS et de SQL-MM ne comprennent pas d'argument de type flag pour ST_IsValid. L'indicateur est une extension de PostGIS. |
ST_IsValidDetail — Renvoie une ligne valid_detail
indiquant si une géométrie est valide ou sinon une raison et une localisation.
valid_detail ST_IsValidDetail(
geometry geom, integer flags)
;
Renvoie une ligne valid_detail
, contenant un booléen (valid
) indiquant si une géométrie est valide, un varchar (reason
) indiquant une raison pour laquelle elle est invalide et une géométrie (location
) indiquant où elle est invalide.
Utile pour améliorer la combinaison de ST_IsValid et ST_IsValidReason afin de générer un rapport détaillé des géométries invalides.
Le paramètre facultatif flags
est un champ de type bit. Il peut avoir les valeurs suivantes :
0 : utiliser la sémantique de validité habituelle de l'OGC SFS.
1 : Considérer certains types d'anneaux auto-touchants (coquilles inversées et trous exverts) comme valides. Ceci est également connu sous le nom de "flag ESRI", car c'est le modèle de validité utilisé par ces outils. Notez que cela n'est pas valide selon le modèle OGC.
Effectué par le module GEOS.
Disponibilité : 2.0.0
--Premiers 3 Rejets d'une expérience de quintuplet réussie SELECT gid, reason(ST_IsValidDetail(geom)), ST_AsText(location(ST_IsValidDetail(geom))) as location FROM (SELECT ST_MakePolygon(ST_ExteriorRing(e.buff), array_agg(f.line)) As geom, gid FROM (SELECT ST_Buffer(ST_Point(x1*10,y1), z1) As buff, x1*10 + y1*100 + z1*1000 As gid FROM generate_series(-4,6) x1 CROSS JOIN generate_series(2,5) y1 CROSS JOIN generate_series(1,8) z1 WHERE x1 > y1*0.5 AND z1 < x1*y1) As e INNER JOIN (SELECT ST_Translate(ST_ExteriorRing(ST_Buffer(ST_Point(x1*10,y1), z1)),y1*1, z1*2) As line FROM generate_series(-3,6) x1 CROSS JOIN generate_series(2,5) y1 CROSS JOIN generate_series(1,10) z1 WHERE x1 > y1*0.75 AND z1 < x1*y1) As f ON (ST_Area(e.buff) > 78 AND ST_Contains(e.buff, f.line)) GROUP BY gid, e.buff) As quintuplet_experiment WHERE ST_IsValid(geom) = false ORDER BY gid LIMIT 3 ; gid | reason | location ------+-------------------+------------- 5330 | Self-intersection | POINT(32 5) 5340 | Self-intersection | POINT(42 5) 5350 | Self-intersection | POINT(52 5) --exemple simple SELECT * FROM ST_IsValidDetail('LINESTRING(220227 150406,2220227 150407,222020 150410)') ; valid | reason | location -------+--------+---------- t | |
ST_IsValidReason — Renvoie un texte indiquant si une géométrie est valide, ou la raison de son invalidité.
text ST_IsValidReason(
geometry geomA)
;
text ST_IsValidReason(
geometry geomA, integer flags)
;
Renvoie un texte indiquant si une géométrie est valide ou, si elle est invalide, une raison pour laquelle elle l'est.
Utile en combinaison avec ST_IsValid pour générer un rapport détaillé des géométries invalides et des raisons.
Les flags
autorisés sont documentés dans ST_IsValidDetail.
Effectué par le module GEOS.
Disponibilité : 1.4
Disponibilité : la version 2.0 prend des flags.
-- Polygone invalide en forme de nœud papillon SELECT ST_IsValidReason( 'POLYGON ((100 200, 100 100, 200 200, 200 100, 100 200))'::geometry) as validity_info ; validity_info -------------------------- Self-intersection[150 150]
--Premiers 3 Rejets d'une expérience de quintuplet réussie SELECT gid, ST_IsValidReason(geom) as validity_info FROM (SELECT ST_MakePolygon(ST_ExteriorRing(e.buff), array_agg(f.line)) As geom, gid FROM (SELECT ST_Buffer(ST_Point(x1*10,y1), z1) As buff, x1*10 + y1*100 + z1*1000 As gid FROM generate_series(-4,6) x1 CROSS JOIN generate_series(2,5) y1 CROSS JOIN generate_series(1,8) z1 WHERE x1 > y1*0.5 AND z1 < x1*y1) As e INNER JOIN (SELECT ST_Translate(ST_ExteriorRing(ST_Buffer(ST_Point(x1*10,y1), z1)),y1*1, z1*2) As line FROM generate_series(-3,6) x1 CROSS JOIN generate_series(2,5) y1 CROSS JOIN generate_series(1,10) z1 WHERE x1 > y1*0.75 AND z1 < x1*y1) As f ON (ST_Area(e.buff) > 78 AND ST_Contains(e.buff, f.line)) GROUP BY gid, e.buff) As quintuplet_experiment WHERE ST_IsValid(geom) = false ORDER BY gid LIMIT 3 ; gid | validity_info ------+-------------------------- 5330 | Self-intersection [32 5] 5340 | Self-intersection [42 5] 5350 | Self-intersection [52 5] --exemple simple SELECT ST_IsValidReason('LINESTRING(220227 150406,2220227 150407,222020 150410)') ; st_isvalidreason ------------------ Valid Geometry
ST_MakeValid — Tente de rendre valide une géométrie invalide sans perdre de sommets.
geometry ST_MakeValid(
geometry input)
;
geometry ST_MakeValid(
geometry input, text params)
;
La fonction tente de créer une représentation valide d'une géométrie invalide donnée sans perdre aucun des sommets d'entrée. Les géométries valides sont retournées inchangées.
Les types de données pris en charge sont : POINTS, MULTIPOINTS, LINESTRINGS, MULTILINESTRINGS, POLYGONS, MULTIPOLYGONS et GEOMETRYCOLLECTIONS contenant n'importe quel mélange de ces éléments.
En cas de diminution de dimension (total ou partiel), la géométrie de sortie peut être une collection de géométries de dimension inférieure à égale, ou une géométrie de dimension inférieure.
Les polygones simples peuvent devenir des multigéométries en cas d'auto-intersections.
L'argument params
peut être utilisé pour fournir une chaîne d'options permettant de sélectionner la méthode à utiliser pour construire une géométrie valide. La chaîne d'options est au format "method=linework|structure keepcollapsed=true|false".
La clé "method" a deux valeurs.
Le "linework" est l'algorithme original, et construit des géométries valides en extrayant d'abord toutes les lignes, en codant ce linework ensemble, puis en construisant une sortie de valeur à partir du linework.
La "structure" est un algorithme qui distingue les anneaux intérieurs et extérieurs, construisant une nouvelle géométrie en réunissant les anneaux extérieurs, puis en différenciant tous les anneaux intérieurs.
La clé "keepcollapsed" est uniquement valable pour l'algorithme "structure" et prend la valeur "true" ou "false". Lorsqu'elle est définie sur "false", les composants géométriques qui se réduisent à une dimension inférieure, par exemple une ligne à un point, sont abandonnés.
Effectué par le module GEOS.
Disponibilité : 2.0.0
Amélioré : 2.0.1, améliorations de la vitesse
Amélioration : 2.1.0, ajout du support pour GEOMETRYCOLLECTION et MULTIPOINT.
Amélioration : 3.1.0, suppression des coordonnées avec des valeurs NaN.
Amélioration : 3.2.0, ajout d'options d'algorithme, 'linework' et 'structure' qui nécessite GEOS >= 3.10.0.
This function supports 3d and will not drop the z-index.
![]() before_geom : MULTIPOLYGON de 2 polygones qui se superposent
![]() after_geom : MULTIPOLYGON de 4 polygones qui ne se superposent pas
![]() after_geom_structure : MULTIPOLYGON de 1 polygone qui ne se chevauche pas
SELECT f.geom AS before_geom, ST_MakeValid(f.geom) AS after_geom, ST_MakeValid(f.geom, 'method=structure') AS after_geom_structure FROM (SELECT 'MULTIPOLYGON(((186 194,187 194,188 195,189 195,190 195, 191 195,192 195,193 194,194 194,194 193,195 192,195 191, 195 190,195 189,195 188,194 187,194 186,14 6,13 6,12 5,11 5, 10 5,9 5,8 5,7 6,6 6,6 7,5 8,5 9,5 10,5 11,5 12,6 13,6 14,186 194)), ((150 90,149 80,146 71,142 62,135 55,128 48,119 44,110 41,100 40, 90 41,81 44,72 48,65 55,58 62,54 71,51 80,50 90,51 100, 54 109,58 118,65 125,72 132,81 136,90 139,100 140,110 139, 119 136,128 132,135 125,142 118,146 109,149 100,150 90)))'::geometry AS geom) AS f ;
|
![]() before_geom : MULTIPOLYGON de 6 polygones qui se superposent
![]() after_geom : MULTIPOLYGON de 14 polygones qui ne se superposent pas
![]() after_geom_structure : MULTIPOLYGON de 1 polygone qui ne se chevauche pas
SELECT c.geom AS before_geom, ST_MakeValid(c.geom) AS after_geom, ST_MakeValid(c.geom, 'method=structure') AS after_geom_structure FROM (SELECT 'MULTIPOLYGON(((91 50,79 22,51 10,23 22,11 50,23 78,51 90,79 78,91 50)), ((91 100,79 72,51 60,23 72,11 100,23 128,51 140,79 128,91 100)), ((91 150,79 122,51 110,23 122,11 150,23 178,51 190,79 178,91 150)), ((141 50,129 22,101 10,73 22,61 50,73 78,101 90,129 78,141 50)), ((141 100,129 72,101 60,73 72,61 100,73 128,101 140,129 128,141 100)), ((141 150,129 122,101 110,73 122,61 150,73 178,101 190,129 178,141 150)))'::geometry AS geom) AS c ;
|
ST_InverseTransformPipeline — Return a new geometry with coordinates transformed to a different spatial reference system using the inverse of a defined coordinate transformation pipeline.
geometry ST_InverseTransformPipeline(
geometry geom, text pipeline, integer to_srid)
;
Return a new geometry with coordinates transformed to a different spatial reference system using a defined coordinate transformation pipeline to go in the inverse direction.
Refer to ST_TransformPipeline for details on writing a transformation pipeline.
Availability: 3.4.0
The SRID of the input geometry is ignored, and the SRID of the output geometry will be set to zero unless a value is provided via the optional to_srid
parameter. When using ST_TransformPipeline the pipeline is executed in a forward direction. Using `ST_InverseTransformPipeline()` the pipeline is executed in the inverse direction.
Transforms using pipelines are a specialised version of ST_Transform. In most cases `ST_Transform` will choose the correct operations to convert between coordinate systems, and should be preferred.
Change WGS 84 long lat to UTM 31N using the EPSG:16031 conversion
-- Inverse direction SELECT ST_AsText(ST_InverseTransformPipeline('POINT(426857.9877165967 5427937.523342293)'::geometry, 'urn:ogc:def:coordinateOperation:EPSG::16031')) AS wgs_geom; wgs_geom ---------------------------- POINT(2 48.99999999999999) (1 row)
GDA2020 example.
-- using ST_Transform with automatic selection of a conversion pipeline. SELECT ST_AsText(ST_Transform('SRID=4939;POINT(143.0 -37.0)'::geometry, 7844)) AS gda2020_auto; gda2020_auto ----------------------------------------------- POINT(143.00000635638918 -36.999986706128176) (1 row)
ST_SetSRID — Set the SRID on a geometry.
geometry ST_SetSRID(
geometry geom, integer srid)
;
Sets the SRID on a geometry to a particular integer value. Useful in constructing bounding boxes for queries.
![]() | |
This function does not transform the geometry coordinates in any way - it simply sets the meta data defining the spatial reference system the geometry is assumed to be in. Use ST_Transform if you want to transform the geometry into a new projection. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method supports Circular Strings and Curves
-- Mark a point as WGS 84 long lat --
SELECT ST_SetSRID(ST_Point(-123.365556, 48.428611),4326) As wgs84long_lat; -- the ewkt representation (wrap with ST_AsEWKT) - SRID=4326;POINT(-123.365556 48.428611)
-- Mark a point as WGS 84 long lat and then transform to web mercator (Spherical Mercator) --
SELECT ST_Transform(ST_SetSRID(ST_Point(-123.365556, 48.428611),4326),3785) As spere_merc; -- the ewkt representation (wrap with ST_AsEWKT) - SRID=3785;POINT(-13732990.8753491 6178458.96425423)
ST_SRID — Returns the spatial reference identifier for a geometry.
integer ST_SRID(
geometry g1)
;
Returns the spatial reference identifier for the ST_Geometry as defined in spatial_ref_sys table. Section 4.5, “Spatial Reference Systems”
![]() | |
spatial_ref_sys table is a table that catalogs all spatial reference systems known to PostGIS and is used for transformations from one spatial reference system to another. So verifying you have the right spatial reference system identifier is important if you plan to ever transform your geometries. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s2.1.1.1
This method implements the SQL/MM specification. SQL-MM 3: 5.1.5
This method supports Circular Strings and Curves
ST_Transform — Return a new geometry with coordinates transformed to a different spatial reference system.
geometry ST_Transform(
geometry g1, integer srid)
;
geometry ST_Transform(
geometry geom, text to_proj)
;
geometry ST_Transform(
geometry geom, text from_proj, text to_proj)
;
geometry ST_Transform(
geometry geom, text from_proj, integer to_srid)
;
Returns a new geometry with its coordinates transformed to a different spatial reference system. The destination spatial reference to_srid
may be identified by a valid SRID integer parameter (i.e. it must exist in the spatial_ref_sys
table). Alternatively, a spatial reference defined as a PROJ.4 string can be used for to_proj
and/or from_proj
, however these methods are not optimized. If the destination spatial reference system is expressed with a PROJ.4 string instead of an SRID, the SRID of the output geometry will be set to zero. With the exception of functions with from_proj
, input geometries must have a defined SRID.
ST_Transform is often confused with ST_SetSRID. ST_Transform actually changes the coordinates of a geometry from one spatial reference system to another, while ST_SetSRID() simply changes the SRID identifier of the geometry.
ST_Transform automatically selects a suitable conversion pipeline given the source and target spatial reference systems. To use a specific conversion method, use ST_TransformPipeline.
![]() | |
Requires PostGIS be compiled with PROJ support. Use PostGIS_Full_Version to confirm you have PROJ support compiled in. |
![]() | |
If using more than one transformation, it is useful to have a functional index on the commonly used transformations to take advantage of index usage. |
![]() | |
Prior to 1.3.4, this function crashes if used with geometries that contain CURVES. This is fixed in 1.3.4+ |
Amélioration : 2.0.0 introduction du support des surfaces polyédriques.
Enhanced: 2.3.0 support for direct PROJ.4 text was introduced.
This method implements the SQL/MM specification. SQL-MM 3: 5.1.6
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
Change Massachusetts state plane US feet geometry to WGS 84 long lat
SELECT ST_AsText(ST_Transform(ST_GeomFromText('POLYGON((743238 2967416,743238 2967450, 743265 2967450,743265.625 2967416,743238 2967416))',2249),4326)) As wgs_geom; wgs_geom --------------------------- POLYGON((-71.1776848522251 42.3902896512902,-71.1776843766326 42.3903829478009, -71.1775844305465 42.3903826677917,-71.1775825927231 42.3902893647987,-71.177684 8522251 42.3902896512902)); (1 row) --3D Circular String example SELECT ST_AsEWKT(ST_Transform(ST_GeomFromEWKT('SRID=2249;CIRCULARSTRING(743238 2967416 1,743238 2967450 2,743265 2967450 3,743265.625 2967416 3,743238 2967416 4)'),4326)); st_asewkt -------------------------------------------------------------------------------------- SRID=4326;CIRCULARSTRING(-71.1776848522251 42.3902896512902 1,-71.1776843766326 42.3903829478009 2, -71.1775844305465 42.3903826677917 3, -71.1775825927231 42.3902893647987 3,-71.1776848522251 42.3902896512902 4)
Example of creating a partial functional index. For tables where you are not sure all the geometries will be filled in, its best to use a partial index that leaves out null geometries which will both conserve space and make your index smaller and more efficient.
CREATE INDEX idx_geom_26986_parcels ON parcels USING gist (ST_Transform(geom, 26986)) WHERE geom IS NOT NULL;
Examples of using PROJ.4 text to transform with custom spatial references.
-- Find intersection of two polygons near the North pole, using a custom Gnomic projection -- See http://boundlessgeo.com/2012/02/flattening-the-peel/ WITH data AS ( SELECT ST_GeomFromText('POLYGON((170 50,170 72,-130 72,-130 50,170 50))', 4326) AS p1, ST_GeomFromText('POLYGON((-170 68,-170 90,-141 90,-141 68,-170 68))', 4326) AS p2, '+proj=gnom +ellps=WGS84 +lat_0=70 +lon_0=-160 +no_defs'::text AS gnom ) SELECT ST_AsText( ST_Transform( ST_Intersection(ST_Transform(p1, gnom), ST_Transform(p2, gnom)), gnom, 4326)) FROM data; st_astext -------------------------------------------------------------------------------- POLYGON((-170 74.053793645338,-141 73.4268621378904,-141 68,-170 68,-170 74.053793645338))
Sometimes coordinate transformation involving a grid-shift can fail, for example if PROJ.4 has not been built with grid-shift files or the coordinate does not lie within the range for which the grid shift is defined. By default, PostGIS will throw an error if a grid shift file is not present, but this behavior can be configured on a per-SRID basis either by testing different to_proj
values of PROJ.4 text, or altering the proj4text
value within the spatial_ref_sys
table.
For example, the proj4text parameter +datum=NAD87 is a shorthand form for the following +nadgrids parameter:
+nadgrids=@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat
The @ prefix means no error is reported if the files are not present, but if the end of the list is reached with no file having been appropriate (ie. found and overlapping) then an error is issued.
If, conversely, you wanted to ensure that at least the standard files were present, but that if all files were scanned without a hit a null transformation is applied you could use:
+nadgrids=@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat,null
The null grid shift file is a valid grid shift file covering the whole world and applying no shift. So for a complete example, if you wanted to alter PostGIS so that transformations to SRID 4267 that didn't lie within the correct range did not throw an ERROR, you would use the following:
UPDATE spatial_ref_sys SET proj4text = '+proj=longlat +ellps=clrk66 +nadgrids=@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat,null +no_defs' WHERE srid = 4267;
ST_TransformPipeline — Return a new geometry with coordinates transformed to a different spatial reference system using a defined coordinate transformation pipeline.
geometry ST_TransformPipeline(
geometry g1, text pipeline, integer to_srid)
;
Return a new geometry with coordinates transformed to a different spatial reference system using a defined coordinate transformation pipeline.
Transformation pipelines are defined using any of the following string formats:
urn:ogc:def:coordinateOperation:AUTHORITY::CODE
. Note that a simple EPSG:CODE
string does not uniquely identify a coordinate operation: the same EPSG code can be used for a CRS definition.
A PROJ pipeline string of the form: +proj=pipeline ...
. Automatic axis normalisation will not be applied, and if necessary the caller will need to add an additional pipeline step, or remove axisswap
steps.
Concatenated operations of the form: urn:ogc:def:coordinateOperation,coordinateOperation:EPSG::3895,coordinateOperation:EPSG::1618
.
Availability: 3.4.0
The SRID of the input geometry is ignored, and the SRID of the output geometry will be set to zero unless a value is provided via the optional to_srid
parameter. When using `ST_TransformPipeline()` the pipeline is executed in a forward direction. Using ST_InverseTransformPipeline the pipeline is executed in the inverse direction.
Transforms using pipelines are a specialised version of ST_Transform. In most cases `ST_Transform` will choose the correct operations to convert between coordinate systems, and should be preferred.
Change WGS 84 long lat to UTM 31N using the EPSG:16031 conversion
-- Forward direction SELECT ST_AsText(ST_TransformPipeline('SRID=4326;POINT(2 49)'::geometry, 'urn:ogc:def:coordinateOperation:EPSG::16031') AS utm_geom); utm_geom -------------------------------------------- POINT(426857.9877165967 5427937.523342293) (1 row) -- Inverse direction SELECT ST_AsText(ST_InverseTransformPipeline('POINT(426857.9877165967 5427937.523342293)'::geometry, 'urn:ogc:def:coordinateOperation:EPSG::16031')) AS wgs_geom; wgs_geom ---------------------------- POINT(2 48.99999999999999) (1 row)
GDA2020 example.
-- using ST_Transform with automatic selection of a conversion pipeline. SELECT ST_AsText(ST_Transform('SRID=4939;POINT(143.0 -37.0)'::geometry, 7844)) AS gda2020_auto; gda2020_auto ----------------------------------------------- POINT(143.00000635638918 -36.999986706128176) (1 row) -- using a defined conversion (EPSG:8447) SELECT ST_AsText(ST_TransformPipeline('SRID=4939;POINT(143.0 -37.0)'::geometry, 'urn:ogc:def:coordinateOperation:EPSG::8447')) AS gda2020_code; gda2020_code ---------------------------------------------- POINT(143.0000063280214 -36.999986718287545) (1 row) -- using a PROJ pipeline definition matching EPSG:8447, as returned from -- 'projinfo -s EPSG:4939 -t EPSG:7844'. -- NOTE: any 'axisswap' steps must be removed. SELECT ST_AsText(ST_TransformPipeline('SRID=4939;POINT(143.0 -37.0)'::geometry, '+proj=pipeline +step +proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=hgridshift +grids=au_icsm_GDA94_GDA2020_conformal_and_distortion.tif +step +proj=unitconvert +xy_in=rad +xy_out=deg')) AS gda2020_pipeline; gda2020_pipeline ---------------------------------------------- POINT(143.0000063280214 -36.999986718287545) (1 row)
ST_BdPolyFromText — Construit un Polygon à partir d'une collection de lignes fermées, exprimées sous forme de MultiLineString en représentation Well-Known text.
geometry ST_BdPolyFromText(
text WKT, integer srid)
;
Construit un Polygon à partir d'une collection de lignes fermées, exprimées sous forme de MultiLineString en représentation Well-Known text.
![]() | |
Renvoie une erreur si le WKT n'est pas une MULTILINESTRING. Renvoie une erreur si le résultat est un MULTIPOLYGON. Utiliser ST_BdMPolyFromText dans ce cas, ou voir ST_BuildArea() pour une approche basée sur une fonction spécifique. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.6.2
Effectué par le module GEOS.
Disponibilité : 1.1.0
ST_BdMPolyFromText — Construit un MultiPolygon à partir d'une collection de lignes fermées, exprimées sous forme de MultiLineString en représentation Well-Known text.
geometry ST_BdMPolyFromText(
text WKT, integer srid)
;
Construit un Polygon à partir d'une collection de lignes fermées, de polygones ou de MultiLineStrings exprimés en représentation Well-Known text.
![]() | |
Renvoie une erreur si le WKT n'est pas une MULTILINESTRING. Force le type de retour en MULTIPOLYGON même si le résultat est en fait composé d'un seul POLYGON. Utiliser ST_BdPolyFromText si l'on est sûr que le résultat produit des Polygon, ou voir la fonction spécifique PostGIS ST_BuildArea(). |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.6.2
Effectué par le module GEOS.
Disponibilité : 1.1.0
ST_GeogFromText — Retourne un objet de type geography à partir de sa représentation Well-Know Text (WKT ou EWKT).
geography ST_GeogFromText(
text EWKT)
;
Retourne un objet de type geography à partir de sa représentation Well-Know Text (WKT ou EWKT). Le SRID 4326 est pris par défaut. Ceci est un alias pour ST_GeographyFromText. Les coordonnées des points sont exprimées en longitude latitude.
--- conversion des coordonnées lon lat en geography ALTER TABLE sometable ADD COLUMN geog geography(POINT,4326) ; UPDATE sometable SET geog = ST_GeogFromText('SRID=4326 ;POINT(' || lon || ' ' || lat || ')') ; --- spécifier un point géographique en utilisant EPSG :4267, NAD27 SELECT ST_AsEWKT(ST_GeogFromText('SRID=4267 ;POINT(-77.0092 38.889588)')) ;
ST_GeographyFromText — Retourne un objet de type geography à partir de sa représentation Well-Know Text (WKT ou EWKT).
geography ST_GeographyFromText(
text EWKT)
;
ST_GeomCollFromText — Crée une collection Geometry à partir de la collection WKT avec le SRID donné. Si le SRID n'est pas donné, la valeur par défaut est 0.
geometry ST_GeomCollFromText(
text WKT, integer srid)
;
geometry ST_GeomCollFromText(
text WKT)
;
Crée une géométrie de collection à partir de la représentation Well-Known-Text (WKT) avec le SRID donné. Si le SRID n'est pas donné, la valeur par défaut est 0.
OGC SPEC 3.2.6.2 - l'option SRID est issue des tests de conformité
Retourne null si le WKT n'est pas une GEOMETRYCOLLECTION
![]() | |
Si vous êtes absolument sûrs que toutes les géométries WKT sont des collections, ne pas utiliser cette fonction. Elle est plus lente que ST_GeomFromText à cause d'une étape de validation supplémentaire. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.6.2
This method implements the SQL/MM specification.
ST_GeomFromEWKT — Retourne un objet ST_Geometry à partir de sa représentation textuelle étendue (Extended Well-Known Text representation, EWKT).
geometry ST_GeomFromEWKT(
text EWKT)
;
Retourne un objet ST_Geometry à partir de sa représentation textuelle étendue OGC (Extended Well-Known Text representation, EWKT).
![]() | |
Le format EWKT n'est pas une norme OGC, mais un format spécifique à PostGIS incluant l'identifiant du système de référence des coordonnées (SRID) |
Amélioration : 2.0.0 introduction du support TIN et surfaces polyédriques.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
SELECT ST_GeomFromEWKT('SRID=4269 ;LINESTRING(-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932)') ; SELECT ST_GeomFromEWKT('SRID=4269 ;MULTILINESTRING((-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932))') ; SELECT ST_GeomFromEWKT('SRID=4269 ;POINT(-71.064544 42.28787)') ; SELECT ST_GeomFromEWKT('SRID=4269 ;POLYGON((-71.1776585052917 42.3902909739571,-71.1776820268866 42.3903701743239, -71.1776063012595 42.3903825660754,-71.1775826583081 42.3903033653531,-71.1776585052917 42.3902909739571))') ; SELECT ST_GeomFromEWKT('SRID=4269 ;MULTIPOLYGON(((-71.1031880899493 42.3152774590236, -71.1031627617667 42.3152960829043,-71.102923838298 42.3149156848307, -71.1023097974109 42.3151969047397,-71.1019285062273 42.3147384934248, -71.102505233663 42.3144722937587,-71.10277487471 42.3141658254797, -71.103113945163 42.3142739188902,-71.10324876416 42.31402489987, -71.1033002961013 42.3140393340215,-71.1033488797549 42.3139495090772, -71.103396240451 42.3138632439557,-71.1041521907712 42.3141153348029, -71.1041411411543 42.3141545014533,-71.1041287795912 42.3142114839058, -71.1041188134329 42.3142693656241,-71.1041112482575 42.3143272556118, -71.1041072845732 42.3143851580048,-71.1041057218871 42.3144430686681, -71.1041065602059 42.3145009876017,-71.1041097995362 42.3145589148055, -71.1041166403905 42.3146168544148,-71.1041258822717 42.3146748022936, -71.1041375307579 42.3147318674446,-71.1041492906949 42.3147711126569, -71.1041598612795 42.314808571739,-71.1042515013869 42.3151287620809, -71.1041173835118 42.3150739481917,-71.1040809891419 42.3151344119048, -71.1040438678912 42.3151191367447,-71.1040194562988 42.3151832057859, -71.1038734225584 42.3151140942995,-71.1038446938243 42.3151006300338, -71.1038315271889 42.315094347535,-71.1037393329282 42.315054824985, -71.1035447555574 42.3152608696313,-71.1033436658644 42.3151648370544, -71.1032580383161 42.3152269126061,-71.103223066939 42.3152517403219, -71.1031880899493 42.3152774590236)), ((-71.1043632495873 42.315113108546,-71.1043583974082 42.3151211109857, -71.1043443253471 42.3150676015829,-71.1043850704575 42.3150793250568,-71.1043632495873 42.315113108546)))') ;
--3d circular string SELECT ST_GeomFromEWKT('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)') ;
--Exemple de surface polyédrique SELECT ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )') ;
ST_GeomFromMARC21 — Prend les données géographiques MARC21/XML en entrée et renvoie un objet géométrique PostGIS.
geometry ST_GeomFromMARC21 (
text marcxml )
;
Cette fonction crée une géométrie PostGIS à partir d'un enregistrement MARC21/XML, qui peut contenir un POINT
ou un POLYGON
. En cas d'entrées de données géographiques multiples dans le même enregistrement MARC21/XML, un MULTIPOINT
ou MULTIPOLYGON
sera renvoyé. Si la notice contient des types de géométrie mixtes, une GEOMETRYCOLLECTION
sera retournée. Il renvoie NULL si l'enregistrement MARC21/XML ne contient pas de données géographiques (datafield :034).
Prise en charge des versions LOC MARC21/XML :
Disponibilité : 3.3.0, nécessite libxml2 2.6+
![]() | |
Les données mathématiques cartographiques codées MARC21/XML ne fournissent actuellement aucun moyen de décrire le système de référence spatiale des coordonnées codées, de sorte que cette fonction retournera toujours une géométrie avec |
![]() | |
Les géométries |
Conversion de données géographiques MARC21/XML contenant un seul POINT
encodé en hddd.dddddd
.
SELECT ST_AsText( ST_GeomFromMARC21(' <record xmlns="http://www.loc.gov/MARC21/slim"> <leader >00000nz a2200000nc 4500</leader> <controlfield tag="001" >040277569</controlfield> <datafield tag="034" ind1=" " ind2=" "> <subfield code="d" >W004.500000</subfield> <subfield code="e" >W004.500000</subfield> <subfield code="f" >N054.250000</subfield> <subfield code="g" >N054.250000</subfield> </datafield> </record >')) ; st_astext ------------------- POINT(-4.5 54.25) (1 row)
Conversion de données géographiques MARC21/XML contenant un seul POLYGON
encodé en hdddmmss
SELECT ST_AsText( ST_GeomFromMARC21(' <record xmlns="http://www.loc.gov/MARC21/slim"> <leader >01062cem a2200241 a 4500</leader> <controlfield tag="001" > 84696781 </controlfield> <datafield tag="034" ind1="1" ind2=" "> <subfield code="a" >a</subfield> <subfield code="b" >50000</subfield> <subfield code="d" >E0130600</subfield> <subfield code="e" >E0133100</subfield> <subfield code="f" >N0523900</subfield> <subfield code="g" >N0522300</subfield> </datafield> </record >')) ; st_astext ----------------------------------------------------------------------------------------------------------------------- POLYGON((13.1 52.65,13.516666666666667 52.65,13.516666666666667 52.38333333333333,13.1 52.38333333333333,13.1 52.65)) (1 row)
Conversion de données géographiques MARC21/XML contenant un POLYGON
et un POINT
:
SELECT ST_AsText( ST_GeomFromMARC21(' <record xmlns="http://www.loc.gov/MARC21/slim"> <datafield tag="034" ind1="1" ind2=" "> <subfield code="a" >a</subfield> <subfield code="b" >50000</subfield> <subfield code="d" >E0130600</subfield> <subfield code="e" >E0133100</subfield> <subfield code="f" >N0523900</subfield> <subfield code="g" >N0522300</subfield> </datafield> <datafield tag="034" ind1=" " ind2=" "> <subfield code="d" >W004.500000</subfield> <subfield code="e" >W004.500000</subfield> <subfield code="f" >N054.250000</subfield> <subfield code="g" >N054.250000</subfield> </datafield> </record >')) ; st_astext ------------------------------------------------------------------------------------------------------------------------------------------------------------- GEOMETRYCOLLECTION(POLYGON((13.1 52.65,13.516666666666667 52.65,13.516666666666667 52.38333333333333,13.1 52.38333333333333,13.1 52.65)),POINT(-4.5 54.25)) (1 row)
ST_GeometryFromText — Retourne un objet ST_Geometry à partir de sa représentation textuelle Well-Known Text (WKT). Alias pour ST_GeomFromText
geometry ST_GeometryFromText(
text WKT)
;
geometry ST_GeometryFromText(
text WKT, integer srid)
;
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3 : 5.1.40
ST_GeomFromText — Retourne un objet ST_Geometry à partir de sa représentation textuelle Well-Known Text (WKT).
geometry ST_GeomFromText(
text WKT)
;
geometry ST_GeomFromText(
text WKT, integer srid)
;
Construit un objet Postgis de type geometry à partir d'une représentation OGC Well-Known Text WKT.
![]() | |
Il existe deux variantes de la fonction ST_GeomFromText. La première ne prend pas de SRID et renvoie une géométrie sans système de référence spatiale défini (SRID=0). La seconde prend un SRID comme deuxième argument et renvoie une géométrie qui inclut ce SRID comme partie de ses métadonnées. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.6.2 - l'option SRID est issue des tests de conformité.
This method implements the SQL/MM specification. SQL-MM 3 : 5.1.40
This method supports Circular Strings and Curves
![]() | |
Bien que non conforme à l'OGC, ST_MakePoint est plus rapide que ST_GeomFromText et ST_PointFromText. Il est également plus facile à utiliser pour les valeurs de coordonnées numériques. ST_Point est une autre option similaire en vitesse à ST_MakePoint et est conforme à l'OGC, mais ne prend pas en charge autre chose que les points 2D. |
![]() | |
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. La forme privilégiée désormais est : ST_GeomFromText('GEOMETRYCOLLECTION EMPTY') |
SELECT ST_GeomFromText('LINESTRING(-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932)') ; SELECT ST_GeomFromText('LINESTRING(-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932)',4269) ; SELECT ST_GeomFromText('MULTILINESTRING((-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932))') ; SELECT ST_GeomFromText('POINT(-71.064544 42.28787)') ; SELECT ST_GeomFromText('POLYGON((-71.1776585052917 42.3902909739571,-71.1776820268866 42.3903701743239, -71.1776063012595 42.3903825660754,-71.1775826583081 42.3903033653531,-71.1776585052917 42.3902909739571))') ; SELECT ST_GeomFromText('MULTIPOLYGON(((-71.1031880899493 42.3152774590236, -71.1031627617667 42.3152960829043,-71.102923838298 42.3149156848307, -71.1023097974109 42.3151969047397,-71.1019285062273 42.3147384934248, -71.102505233663 42.3144722937587,-71.10277487471 42.3141658254797, -71.103113945163 42.3142739188902,-71.10324876416 42.31402489987, -71.1033002961013 42.3140393340215,-71.1033488797549 42.3139495090772, -71.103396240451 42.3138632439557,-71.1041521907712 42.3141153348029, -71.1041411411543 42.3141545014533,-71.1041287795912 42.3142114839058, -71.1041188134329 42.3142693656241,-71.1041112482575 42.3143272556118, -71.1041072845732 42.3143851580048,-71.1041057218871 42.3144430686681, -71.1041065602059 42.3145009876017,-71.1041097995362 42.3145589148055, -71.1041166403905 42.3146168544148,-71.1041258822717 42.3146748022936, -71.1041375307579 42.3147318674446,-71.1041492906949 42.3147711126569, -71.1041598612795 42.314808571739,-71.1042515013869 42.3151287620809, -71.1041173835118 42.3150739481917,-71.1040809891419 42.3151344119048, -71.1040438678912 42.3151191367447,-71.1040194562988 42.3151832057859, -71.1038734225584 42.3151140942995,-71.1038446938243 42.3151006300338, -71.1038315271889 42.315094347535,-71.1037393329282 42.315054824985, -71.1035447555574 42.3152608696313,-71.1033436658644 42.3151648370544, -71.1032580383161 42.3152269126061,-71.103223066939 42.3152517403219, -71.1031880899493 42.3152774590236)), ((-71.1043632495873 42.315113108546,-71.1043583974082 42.3151211109857, -71.1043443253471 42.3150676015829,-71.1043850704575 42.3150793250568,-71.1043632495873 42.315113108546)))',4326) ; SELECT ST_GeomFromText('CIRCULARSTRING(220268 150415,220227 150505,220227 150406)') ;
ST_LineFromText — Construit une géométrie à partir d'une représentation WKT avec le SRID donné. Si aucun SRID n'est donné, la valeur par défaut est 0.
geometry ST_LineFromText(
text WKT)
;
geometry ST_LineFromText(
text WKT, integer srid)
;
Crée une géométrie à partir de WKT avec le SRID donné. Si le SRID n'est pas donné, la valeur par défaut est 0. Si le WKT passé n'est pas un LINESTRING, null est retourné.
![]() | |
OGC SPEC 3.2.6.2 - option SRID issue des tests de conformité. |
![]() | |
Si vous êtes sûrs que toutes les géométries WKT sont des LINESTRINGS, la fonction ST_GeomFromText est plus efficace car elle ne contrôle pas le type de la géométrie renvoyée. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.6.2
This method implements the SQL/MM specification. SQL-MM 3 : 7.2.8
ST_MLineFromText — Retourne un objet de type ST_MultiLineString à partir de sa représentation WKT.
geometry ST_MLineFromText(
text WKT, integer srid)
;
geometry ST_MLineFromText(
text WKT)
;
Crée une géométrie à partir du texte connu (WKT) avec le SRID donné. Si le SRID n'est pas donné, la valeur par défaut est 0.
OGC SPEC 3.2.6.2 - l'option SRID est issue des tests de conformité
Retourne NULL si le WKT n'est pas une MULTILINESTRING
![]() | |
Si vous êtes absolument sûrs que toutes les géométries WKT sont des points, ne pas utiliser cette fonction. Elle est plus lente que ST_GeomFromText à cause d'une étape de validation supplémentaire. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.6.2
This method implements the SQL/MM specification.SQL-MM 3 : 9.4.4
ST_MPointFromText — Créé une Geometry depuis un WKT avec le SRID donné. Si le SRID n'est pas fourni, il sera défini par défaut à 0.
geometry ST_MPointFromText(
text WKT, integer srid)
;
geometry ST_MPointFromText(
text WKT)
;
Créé une Geometry depuis un WKT avec le SRID donné. Si le SRID n'est pas fourni, il sera défini par défaut à 0.
OGC SPEC 3.2.6.2 - l'option SRID est issue des tests de conformité
Retourne NULL si le WKT n'est pas une MULTIPOINT
![]() | |
Si vous êtes absolument sûrs que toutes les géométries WKT sont des points, ne pas utiliser cette fonction. Elle est plus lente que ST_GeomFromText à cause d'une étape de validation supplémentaire. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. 3.2.6.2
This method implements the SQL/MM specification. SQL-MM 3 : 9.2.4
ST_MPolyFromText — Crée une géométrie multi-polygone à partir de WKT avec le SRID donné. Si le SRID n'est pas donné, la valeur par défaut est 0.
geometry ST_MPolyFromText(
text WKT, integer srid)
;
geometry ST_MPolyFromText(
text WKT)
;
Crée un MultiPolygone à partir de WKT avec le SRID donné. Si le SRID n'est pas donné, la valeur par défaut est 0.
OGC SPEC 3.2.6.2 - l'option SRID est issue des tests de conformité
Retourne une erreur si le WKT n'est pas un MULTIPOLYGON
![]() | |
Si vous êtes absolument sûrs que toutes les géométries WKT sont des multipolygones, ne pas utiliser cette fonction. Elle est plus lente que ST_GeomFromText à cause d'une étape de validation supplémentaire. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.6.2
This method implements the SQL/MM specification. SQL-MM 3 : 9.6.4
SELECT ST_MPolyFromText('MULTIPOLYGON(((0 0 1,20 0 1,20 20 1,0 20 1,0 0 1),(5 5 3,5 7 3,7 7 3,7 5 3,5 5 3)))') ; SELECt ST_MPolyFromText('MULTIPOLYGON(((-70.916 42.1002,-70.9468 42.0946,-70.9765 42.0872,-70.9754 42.0875,-70.9749 42.0879,-70.9752 42.0881,-70.9754 42.0891,-70.9758 42.0894,-70.9759 42.0897,-70.9759 42.0899,-70.9754 42.0902,-70.9756 42.0906,-70.9753 42.0907,-70.9753 42.0917,-70.9757 42.0924,-70.9755 42.0928,-70.9755 42.0942,-70.9751 42.0948,-70.9755 42.0953,-70.9751 42.0958,-70.9751 42.0962,-70.9759 42.0983,-70.9767 42.0987,-70.9768 42.0991,-70.9771 42.0997,-70.9771 42.1003,-70.9768 42.1005,-70.977 42.1011,-70.9766 42.1019,-70.9768 42.1026,-70.9769 42.1033,-70.9775 42.1042,-70.9773 42.1043,-70.9776 42.1043,-70.9778 42.1048,-70.9773 42.1058,-70.9774 42.1061,-70.9779 42.1065,-70.9782 42.1078,-70.9788 42.1085,-70.9798 42.1087,-70.9806 42.109,-70.9807 42.1093,-70.9806 42.1099,-70.9809 42.1109,-70.9808 42.1112,-70.9798 42.1116,-70.9792 42.1127,-70.979 42.1129,-70.9787 42.1134,-70.979 42.1139,-70.9791 42.1141,-70.9987 42.1116,-71.0022 42.1273, -70.9408 42.1513,-70.9315 42.1165,-70.916 42.1002)))',4326) ;
ST_PointFromText — Construit une géométrie point à partir d'une représentation WKT et le SRID donné. Si aucun SRID n'est donné, la valeur par défaut est 0.
geometry ST_PointFromText(
text WKT)
;
geometry ST_PointFromText(
text WKT, integer srid)
;
Construit un objet point ST_Geometry de PostGIS à partir de la représentation textuelle Well-Known de l'OGC. Si le SRID n'est pas donné, il prend par défaut la valeur inconnue (actuellement 0). Si la géométrie n'est pas une représentation de point WKT, retourne null. Si la représentation WKT n'est pas du tout valide, une erreur est générée.
![]() | |
Il existe 2 versions de la fonction ST_PointFromText : la première ne prend pas de SRID en paramètre et retourne une geometry sans système de coordonnées. La seconde prend un SRID en second paramètre et retourne une ST_Geometry incluant un SRID dans ses métadonnées. Ce SRID doit obligatoirement exister dans la table spatial_ref_sys. |
![]() | |
Si vous êtes absolument sûrs que toutes les géométries WKT sont des points, ne pas utiliser cette fonction. Elle est plus lente que ST_GeomFromText à cause d'une étape de validation supplémentaire. Si le point doit être construit à partir de coordonnées latitude longitude et que la performance est recherchée, utiliser la fonction ST_MakePoint ou son équivalent OGC ST_Point. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.6.2 - l'option SRID est issue des tests de conformité.
This method implements the SQL/MM specification. SQL-MM 3 : 6.1.8
ST_PolygonFromText — Créé une Geometry depuis un WKT avec le SRID donné. Si le SRID n'est pas fourni, il sera défini par défaut à 0.
geometry ST_PolygonFromText(
text WKT)
;
geometry ST_PolygonFromText(
text WKT, integer srid)
;
Crée une géométrie à partir de WKT avec le SRID donné. Si le SRID n'est pas donné, la valeur par défaut est 0. Retourne null si WKT n'est pas un polygone.
OGC SPEC 3.2.6.2 - l'option SRID est issue des tests de conformité
![]() | |
Si vous êtes absolument sûrs que toutes les géométries WKT sont des polygones, ne pas utiliser cette fonction. Elle est plus lente que ST_GeomFromText à cause d'une étape de validation supplémentaire. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.6.2
This method implements the SQL/MM specification. SQL-MM 3 : 8.3.6
SELECT ST_PolygonFromText('POLYGON((-71.1776585052917 42.3902909739571,-71.1776820268866 42.3903701743239, -71.1776063012595 42.3903825660754,-71.1775826583081 42.3903033653531,-71.1776585052917 42.3902909739571))') ; st_polygonfromtext ------------------ 010300000001000000050000006... SELECT ST_PolygonFromText('POINT(1 2)') IS NULL as point_is_notpoly ; point_is_not_poly ---------- t
LINESTRING
depuis la représentation binaire WKB et le srid donnéST_GeogFromWKB — Retourne un objet de type geography à partir de sa représentation binaire Well-Know Binary (WKB ou EWKB).
geography ST_GeogFromWKB(
bytea wkb)
;
ST_GeogFromWKB
prend en paramètre une représentation binaire d'une géométrie (WKB ou EWKB) et crée une instance de type geography. Cette fonction assure le rôle de Geometry Factory en SQL.
Si le SRID n'est pas spécifié, la valeur 4326 est prise (WGS 84 long lat).
This method supports Circular Strings and Curves
--Bien que bytea rep contienne des \ simples, ceux-ci doivent être échappés lors de l'insertion dans une table SELECT ST_AsText( ST_GeogFromWKB(E'\\001\\002\\000\\000\\000\\002\\000\\000\\000\\037\\205\\353Q\\270~\\\\\\300\\323Mb\\020X\\231C@\\020X9\\264\\310~\\\\\\300)\\\\\\217\\302\\365\\230C@') ) ; st_astext ------------------------------------------------------ LINESTRING(-113.98 39.198,-113.981 39.195) (1 row)
ST_GeomFromEWKB — Retourne un objet ST_Geometry à partir de sa représentation binaire étendue (Extended Well-Known Binary representation, EWKB).
geometry ST_GeomFromEWKB(
bytea EWKB)
;
Retourne un objet ST_Geometry à partir de sa représentation textuelle étendue OGC (Extended Well-Known Text representation, EWKT).
![]() | |
Le format EWKB n'est pas une norme OGC, mais un format spécifique à PostGIS incluant l'identifiant du système de référence des coordonnées (SRID) |
Amélioration : 2.0.0 introduction du support TIN et surfaces polyédriques.
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).
line string binary rep 0f LINESTRING(-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932) in NAD 83 long lat (4269).
![]() | |
NOTE : Si le paramètre standard_conforming_strings est à la valeur off, il est nécessaire d'échapper les caractères \ et ' avec \ et ". Ceci diffère de la représentation AsEWKB. |
SELECT ST_GeomFromEWKB(E'\\001\\002\\000\\000 \\255\\020\\000\\000\\003\\000\\000\\000\\344J= \\013B\\312Q\\300n\\303(\\010\\036 !E@''\\277E''K \\312Q\\300\\366{b\\235* !E@\\225|\\354.P\\312Q \\300p\\231\\323e1 !E@') ;
![]() | |
Dans PostgreSQL 9.1+ - standard_conforming_strings est activé par défaut, alors que dans les versions précédentes il était désactivé. Vous pouvez modifier les valeurs par défaut selon vos besoins pour une seule requête ou au niveau de la base de données ou du serveur. Voici comment procéder avec standard_conforming_strings = on. Dans ce cas, nous échappons le ' avec le standard ansi ', mais les barres obliques ne sont pas échappées |
set standard_conforming_strings = on ; SELECT ST_GeomFromEWKB('\001\002\000\000 \255\020\000\000\003\000\000\000\344J=\012\013B \312Q\300n\303(\010\036 !E@''\277E''K\012\312Q\300\366{b\235* !E@\225|\354.P\312Q\012\300p\231\323e1')
ST_GeomFromWKB — Retourne un objet de type geometry à partir de sa représentation binaire Well-Know Binary (WKB) et d'un SRID optionnel.
geometry ST_GeomFromWKB(
bytea geom)
;
geometry ST_GeomFromWKB(
bytea geom, integer srid)
;
ST_GeomFromWKB
prend en paramètre une représentation binaire d'une géométrie (WKB ou EWKB) et un SRID optionnel (SRID
) et crée une instance de type geometry. Cette fonction assure le rôle de Geometry Factory en SQL. Alias pour ST_WKBToSQL.
Si le SRID n'est pas précisé, la valeur 0 (indéfini) est prise par défaut.
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.7.2 - le paramètre optionnel est issu des tests de conformité
This method implements the SQL/MM specification. SQL-MM 3 : 5.1.41
This method supports Circular Strings and Curves
--Bien que bytea rep contienne des \ simples, ceux-ci doivent être échappés lors de l'insertion dans une table. -- à moins que standard_conforming_strings ne soit activé. SELECT ST_AsEWKT( ST_GeomFromWKB(E'\\001\\002\\000\\000\\000\\002\\000\\000\\000\\037\\205\\353Q\\270~\\\\\\300\\323Mb\\020X\\231C@\\020X9\\264\\310~\\\\\\300)\\\\\\217\\302\\365\\230C@',4326) ) ; st_asewkt ------------------------------------------------------ SRID=4326;LINESTRING(-113.98 39.198,-113.981 39.195) (1 row) SELECT ST_AsText( ST_GeomFromWKB( ST_AsEWKB('POINT(2 5)'::geometry) ) ) ; st_astext ------------ POINT(2 5) (1 row)
ST_LineFromWKB — Construit une LINESTRING
depuis la représentation binaire WKB et le srid donné
geometry ST_LineFromWKB(
bytea WKB)
;
geometry ST_LineFromWKB(
bytea WKB, integer srid)
;
ST_LineFromWKB
prend en paramètre une représentation binaire d'une géométrie (WKB ou EWKB) et un SRID (SRID
) et crée une instance du bon type géométrique, en l'occurence une LINESTRING
. Cette fonction assure le rôle de Geometry Factory en SQL.
Si le SRID n'est pas précisé, la valeur 0 est prise par défaut. NULL
est retourné si le paramètre bytea
donné ne représente pas une LINESTRING
.
![]() | |
OGC SPEC 3.2.6.2 - option SRID issue des tests de conformité. |
![]() | |
Si vous êtes sûrs que toutes les géométries WKT sont des |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.6.2
This method implements the SQL/MM specification. SQL-MM 3 : 7.2.9
ST_LinestringFromWKB — Construit une géométrie depuis la représentation binaire WKB et le SRID donné.
geometry ST_LinestringFromWKB(
bytea WKB)
;
geometry ST_LinestringFromWKB(
bytea WKB, integer srid)
;
La fonction ST_LinestringFromWKB
prend en paramètre une représentation binaire d'une géométrie (WKB ou EWKB) et un SRID (SRID
) et crée une instance du bon type géométrique, en l'occurence une LINESTRING
. Cette fonction assure le rôle de Geometry Factory en SQL.
Si le SRID n'est pas précisé, la valeur 0 est prise par défaut. NULL
est retourné si le paramètre bytea
donné ne représente pas une LINESTRING
. Alias pour ST_LineFromWKB.
![]() | |
OGC SPEC 3.2.6.2 - SRID optionnel issu des tests de conformité. |
![]() | |
Si vous êtes sûrs que toutes les géométries WKT sont des |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.6.2
This method implements the SQL/MM specification. SQL-MM 3 : 7.2.9
SELECT ST_LineStringFromWKB( ST_AsBinary(ST_GeomFromText('LINESTRING(1 2, 3 4)')) ) AS aline, ST_LinestringFromWKB( ST_AsBinary(ST_GeomFromText('POINT(1 2)')) ) IS NULL AS null_return ; aline | null_return ------------------------------------------------ 010200000002000000000000000000F ... | t
ST_PointFromWKB — Construit une géométrie depuis la représentation binaire WKB et le SRID donné.
geometry ST_GeomFromWKB(
bytea geom)
;
geometry ST_GeomFromWKB(
bytea geom, integer srid)
;
ST_PointFromWKB
prend en paramètre une représentation binaire d'une géométrie et un SRID (SRID
) et crée une instance du bon type géométrique, en l'occurence une POINT
. Cette fonction assure le rôle de Geometry Factory en SQL.
Si le SRID n'est pas précisé, la valeur 0 est prise par défaut. NULL
est retourné si le paramètre bytea
donné ne représente pas une géométrie POINT
.
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.7.2
This method implements the SQL/MM specification. SQL-MM 3 : 6.1.9
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
ST_Box2dFromGeoHash — Retourne une BOX2D à partir d'une chaîne GeoHash.
box2d ST_Box2dFromGeoHash(
text geohash, integer precision=full_precision_of_geohash)
;
Retourne une BOX2D à partir d'une chaîne GeoHash.
Si aucune precision
n'est spécifiée, ST_Box2dFromGeoHash retourne un BOX2D basé sur la précision complète de la chaîne GeoHash d'entrée.
Si precision
est spécifié, ST_Box2dFromGeoHash utilise autant de caractère du GeoHash pour créer la BOX2D. Une précision plus basse retourne des BOXD2 plus grandes, et une valeur plus haute améliore la précision.
Disponibilité : 2.1.0
SELECT ST_Box2dFromGeoHash('9qqj7nmxncgyy4d0dbxqz0'); st_geomfromgeohash -------------------------------------------------- BOX(-115.172816 36.114646,-115.172816 36.114646) SELECT ST_Box2dFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 0); st_box2dfromgeohash ---------------------- BOX(-180 -90,180 90) SELECT ST_Box2dFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 10); st_box2dfromgeohash --------------------------------------------------------------------------- BOX(-115.17282128334 36.1146408319473,-115.172810554504 36.1146461963654)
ST_GeomFromGeoHash — Retourne une geometry depuis une chaîne GeoHash.
geometry ST_GeomFromGeoHash(
text geohash, integer precision=full_precision_of_geohash)
;
Retourne une Geometry à partir d'une chaîne GeoHash. La géométrie sera un polygone représentant les limites du GeoHash.
Si aucune precision
n'est spécifiée, ST_GeomFromGeoHash retourne un polygone basé sur la précision complète de la chaîne GeoHash en entrée.
Si precision
est spécifié, ST_GeomFromGeoHash utilise autant de caractère du GeoHash pour créer le polygone.
Disponibilité : 2.1.0
SELECT ST_AsText(ST_GeomFromGeoHash('9qqj7nmxncgyy4d0dbxqz0')); st_astext -------------------------------------------------------------------------------------------------------------------------- POLYGON((-115.172816 36.114646,-115.172816 36.114646,-115.172816 36.114646,-115.172816 36.114646,-115.172816 36.114646)) SELECT ST_AsText(ST_GeomFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 4)); st_astext ------------------------------------------------------------------------------------------------------------------------------ POLYGON((-115.3125 36.03515625,-115.3125 36.2109375,-114.9609375 36.2109375,-114.9609375 36.03515625,-115.3125 36.03515625)) SELECT ST_AsText(ST_GeomFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 10)); st_astext ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- POLYGON((-115.17282128334 36.1146408319473,-115.17282128334 36.1146461963654,-115.172810554504 36.1146461963654,-115.172810554504 36.1146408319473,-115.17282128334 36.1146408319473))
ST_GeomFromGML — Prend en paramètre une représentation GML d'une géométrie et renvoie un objet PostGIS de type geometry.
geometry ST_GeomFromGML(
text geomgml)
;
geometry ST_GeomFromGML(
text geomgml, integer srid)
;
Construit un objet PostGIS ST_Geometry à partir d'une représentation GML OGC.
La fonction ST_GeomFromGML fonctionne uniquement avec le fragment GML représentant la géométrie. Elle renvoie une error si un document GML complet est utilisé.
version OGC GML supportée :
GML 3.2.1 Namespace
GML 3.1.1 Simple Features profile SF-2 (with GML 3.1.0 and 3.0.0 backward compatibility)
GML 2.1.2
OGC GML standards, cf : http ://www.opengeospatial.org/standards/gml :
Disponibilité : 1.5, nécessite libxml2 1.6+
Amélioration : 2.0.0 introduction du support TIN et surfaces polyédriques.
Amélioration : 2.0.0 paramètre optionnel de srid par défaut ajouté.
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).
Le format GML supporte des objets de dimensions différentes (2D et 3D dans la même MultiGeometry par exemple). PostGIS ne supportant pas cela, la fonction convertit toute la géometrie en 2D si une seule coordonnée Z manque.
Le format GML supporte des objets ayant des SRID différents dans la même MultiGeometry. PostGIS ne supportant pas cela, ST_GeomFromGML reprojète toutes les sous géométries dans le SRS du noeud racine. Si aucun attribut srsName n'est disponible pour le noeud racine GML, la fonction renvoie une erreur.
La fonction ST_GeomFromGML n'impose pas d'utiliser un espace de noms GML explicite. Pour les usages courants, il peut être ignoré. Il est en revanche nécessaire en cas d'utilisation de la fonctionnalité XLink dans le GML.
![]() | |
La fonction ST_GeomFromGML ne supporte pas les géométries de type SQL/MM courbes. |
SELECT ST_GeomFromGML(' <gml:LineString srsName="EPSG:4269"> <gml:coordinates> -71.16028,42.258729 -71.160837,42.259112 -71.161143,42.25932 </gml:coordinates> </gml:LineString >');
SELECT ST_GeomFromGML(' <gml:LineString xmlns:gml="http://www.opengis.net/gml" xmlns:xlink="http://www.w3.org/1999/xlink" srsName="urn:ogc:def:crs:EPSG::4269"> <gml:pointProperty> <gml:Point gml:id="p1" ><gml:pos >42.258729 -71.16028</gml:pos ></gml:Point> </gml:pointProperty> <gml:pos >42.259112 -71.160837</gml:pos> <gml:pointProperty> <gml:Point xlink:type="simple" xlink:href="#p1"/> </gml:pointProperty> </gml:LineString >');) ;
SELECT ST_AsEWKT(ST_GeomFromGML(' <gml:PolyhedralSurface> <gml:polygonPatches> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing ><gml:posList srsDimension="3" >0 0 0 0 0 1 0 1 1 0 1 0 0 0 0</gml:posList ></gml:LinearRing> </gml:exterior> </gml:PolygonPatch> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing ><gml:posList srsDimension="3" >0 0 0 0 1 0 1 1 0 1 0 0 0 0 0</gml:posList ></gml:LinearRing> </gml:exterior> </gml:PolygonPatch> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing ><gml:posList srsDimension="3" >0 0 0 1 0 0 1 0 1 0 0 1 0 0 0</gml:posList ></gml:LinearRing> </gml:exterior> </gml:PolygonPatch> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing ><gml:posList srsDimension="3" >1 1 0 1 1 1 1 0 1 1 0 0 1 1 0</gml:posList ></gml:LinearRing> </gml:exterior> </gml:PolygonPatch> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing ><gml:posList srsDimension="3" >0 1 0 0 1 1 1 1 1 1 1 0 0 1 0</gml:posList ></gml:LinearRing> </gml:exterior> </gml:PolygonPatch> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing ><gml:posList srsDimension="3" >0 0 1 1 0 1 1 1 1 0 1 1 0 0 1</gml:posList ></gml:LinearRing> </gml:exterior> </gml:PolygonPatch> </gml:polygonPatches> </gml:PolyhedralSurface >')) ; -- résultat -- POLYHEDRALSURFACE(((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)), ((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)), ((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)), ((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)), ((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)), ((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1)))
ST_GeomFromGeoJSON — Prend en entrée une géométrie au format geojson et renvoie un objet Postgis de type geometry.
geometry ST_GeomFromGeoJSON(
text geomjson)
;
geometry ST_GeomFromGeoJSON(
json geomjson)
;
geometry ST_GeomFromGeoJSON(
jsonb geomjson)
;
Construit un objet Postgis de type geometry à partir d'une représentation GeoJSON.
La fonction ST_GeomFromGeoJSON fonctionne uniquement avec le fragment JSON représentant la géométrie. Elle renvoie une erreur si un document JSON complet est utilisé.
Amélioré : 3.0.0 La géométrie parsée prend par défaut la valeur SRID=4326 si elle n'est pas spécifiée autrement.
Amélioration : 2.5.0 peut maintenant accepter json et jsonb comme entrées.
Disponibilité : 2.0.0 nécessite JSON-C >= 0.9
![]() | |
Si JSON-C n'est pas disponible sur le système, une erreur est renvoyée. Pour activer JSON-C, lancer configure --with-jsondir=/path/to/json-c. Cf. Section 2.2.3, “Configuration de la compilation” pour plus de détails. |
This function supports 3d and will not drop the z-index.
SELECT ST_AsText(ST_GeomFromGeoJSON('{"type" :"Point","coordinates" :[-48.23456,20.12345]}')) As wkt ; wkt ------ POINT(-48.23456 20.12345)
-- une LineString 3D SELECT ST_AsText(ST_GeomFromGeoJSON('{"type" :"LineString","coordinates" :[[1,2,3],[4,5,6],[7,8,9]]}')) As wkt ; wkt ------------------- LINESTRING(1 2,4 5,7 8)
ST_GeomFromKML — Prend en entrée une géométrie au format KML et renvoie un objet Postgis de type geometry.
geometry ST_GeomFromKML(
text geomkml)
;
Construit un objet Postgis de type geometry à partir d'une représentation OGC KML.
La fonction ST_GeomFromKML fonctionne uniquement avec le fragment KML représentant la géométrie. Elle renvoie une erreur si un document KML complet est utilisé.
versions OGC KML supportées :
KML 2.2.0 Namespace
OGC KML standards, cf : http ://www.opengeospatial.org/standards/kml :
Disponibilité : 1.5, nécessite libxml2 2.6+
This function supports 3d and will not drop the z-index.
![]() | |
La fonction ST_GeomFromGML ne supporte pas les géométries de type SQL/MM courbes. |
ST_GeomFromTWKB — Crée une instance de geometry depuis une représentation de géométrie en TWKB ("Tiny Well-Known Binary").
geometry ST_GeomFromTWKB(
bytea twkb)
;
La fonction ST_GeomFromTWKB
prend une représentation de géométrie TWKB ("Tiny Well-Known Binary") et crée une instance du type de géométrie approprié.
SELECT ST_AsText(ST_GeomFromTWKB(ST_AsTWKB('LINESTRING(126 34, 127 35)' ::geometry))) ; st_astext ----------------------------- LINESTRING(126 34, 127 35) (1 row) SELECT ST_AsEWKT( ST_GeomFromTWKB(E'\\x620002f7f40dbce4040105') ) ; st_asewkt ------------------------------------------------------ LINESTRING(-113.98 39.198,-113.981 39.195) (1 row)
ST_GMLToSQL — Retourne un objet de type ST_Geometry à partir de sa représentation GML. Alias pour ST_GeomFromGML
geometry ST_GMLToSQL(
text geomgml)
;
geometry ST_GMLToSQL(
text geomgml, integer srid)
;
ST_LineFromEncodedPolyline — Crée une LineString depuis une polyligne encodée ( "Encoded Polyline" )
geometry ST_LineFromEncodedPolyline(
text polyline, integer precision=5)
;
Crée une LineString à partir d'une chaîne de polyligne encodée ( "Encoded Polyline")
L'option precision
spécifie le nombre de décimales qui seront préservées dans la polyligne encodée. La valeur doit être la même à l'encodage et au décodage, sinon les coordonnées seront incorrectes.
Voir http://developers.google.com/maps/documentation/utilities/polylinealgorithm
Disponibilité : 2.2.0
-- Créer une série de lignes à partir d'une polyligne SELECT ST_AsEWKT(ST_LineFromEncodedPolyline('_p~iF~ps|U_ulLnnqC_mqNvxq`@')) ; -- résultat -- SRID=4326;LINESTRING(-120.2 38.5,-120.95 40.7,-126.453 43.252) -- Sélectionnez une précision différente de celle utilisée pour l'encodage des polylignes. SELECT ST_AsEWKT(ST_LineFromEncodedPolyline('_p~iF~ps|U_ulLnnqC_mqNvxq`@',6)) ; -- résultat -- SRID=4326;LINESTRING(-12.02 3.85,-12.095 4.07,-12.6453 4.3252)
ST_PointFromGeoHash — Retourne un point à partir d'une chaîne GeoHash.
point ST_PointFromGeoHash(
text geohash, integer precision=full_precision_of_geohash)
;
Retourne une point à partir d'une chaîne GeoHash. Le point représente le centre du GeoHash.
Si aucune precision
n'est spécifiée, ST_PointFromGeoHash retourne une un point basé sur la précision complète de la chaîne GeoHash en entrée.
Si precision
est spécifié, ST_PointFromGeoHash utilise autant de caractère du GeoHash pour créer le point.
Disponibilité : 2.1.0
SELECT ST_AsText(ST_PointFromGeoHash('9qqj7nmxncgyy4d0dbxqz0')); st_astext ------------------------------ POINT(-115.172816 36.114646) SELECT ST_AsText(ST_PointFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 4)); st_astext ----------------------------------- POINT(-115.13671875 36.123046875) SELECT ST_AsText(ST_PointFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 10)); st_astext ------------------------------------------- POINT(-115.172815918922 36.1146435141563)
ST_FromFlatGeobufToTable — Crée une table basée sur la structure des données FlatGeobuf.
void ST_FromFlatGeobufToTable(
text schemaname, text tablename, bytea FlatGeobuf input data)
;
Crée une table basée sur la structure des données FlatGeobuf. (http://flatgeobuf.org).
schema
Nom du schéma.
table
Nom de la table.
data
Données FlatGeobuf en entrée.
Disponibilité : 3.2.0
ST_FromFlatGeobuf — Lit les données FlatGeobuf.
setof anyelement ST_FromFlatGeobuf(
anyelement Table reference, bytea FlatGeobuf input data)
;
Lit les données FlatGeobuf (http://flatgeobuf.org). REMARQUE : les chaînes binaires de PostgreSQL ne peuvent pas dépasser 1 Go.
tabletype
référence à un type de table.
data
données d'entrée FlatGeobuf.
Disponibilité : 3.2.0
ST_AsEWKT — Renvoie la représentation Well-Known Text (WKT) de la géométrie avec les métadonnées SRID.
text ST_AsEWKT(
geometry g1)
;
text ST_AsEWKT(
geometry g1, integer maxdecimaldigits=15)
;
text ST_AsEWKT(
geography g1)
;
text ST_AsEWKT(
geography g1, integer maxdecimaldigits=15)
;
Renvoie la représentation Well-Known Text de la géométrie préfixée par le SRID. L'argument facultatif maxdecimaldigits
peut être utilisé pour réduire le nombre maximal de chiffres décimaux après la virgule flottante utilisés dans la sortie (valeur par défaut : 15).
Pour effectuer la conversion inverse de la représentation EWKT en géométrie PostGIS, utilisez ST_GeomFromEWKT.
![]() | |
L'utilisation du paramètre |
![]() | |
La spécification WKT ne comprend pas le SRID. Pour obtenir le format WKT de l'OGC, utilisez ST_AsText. |
![]() | |
Le format WKT ne maintient pas la précision. Pour éviter la troncature flottante, utilisez le format ST_AsBinary ou ST_AsEWKB pour le transport. |
Amélioré : support du paramètre optionnel de précision dans la version 3.1.0.
Amélioration : la version 2.0.0 a introduit la prise en charge de la geography, des surfaces polyédriques, des triangles et des TIN.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
SELECT ST_AsEWKT('0103000020E61000000100000005000000000000 000000000000000000000000000000000000000000000000000000 F03F000000000000F03F000000000000F03F000000000000F03 F000000000000000000000000000000000000000000000000' ::geometry) ; st_asewkt -------------------------------- SRID=4326 ;POLYGON((0 0,0 1,1 1,1 0,0 0)) (1 row) SELECT ST_AsEWKT('0108000080030000000000000060E30A4100000000785C0241000000000000F03F0000000018 E20A4100000000485F024100000000000000400000000018 E20A4100000000305C02410000000000000840') --st_asewkt--- CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)
ST_AsText — Renvoie la représentation Well-Known Text (WKT) de la géométrie/geography sans métadonnées SRID.
text ST_AsText(
geometry g1)
;
text ST_AsText(
geometry g1, integer maxdecimaldigits = 15)
;
text ST_AsText(
geography g1)
;
text ST_AsText(
geography g1, integer maxdecimaldigits = 15)
;
Renvoie la représentation OGC Well-Known Text (WKT) de la géométrie/geography. L'argument facultatif maxdecimaldigits
peut être utilisé pour limiter le nombre de chiffres après la virgule dans les ordonnées de sortie (valeur par défaut : 15).
Pour effectuer la conversion inverse de la représentation WKT en géométrie PostGIS, utilisez ST_GeomFromText.
![]() | |
La représentation WKT standard de l'OGC n'inclut pas le SRID. Pour inclure le SRID dans la représentation de sortie, utilisez la fonction PostGIS non standard ST_AsEWKT |
![]() | |
La représentation textuelle des nombres en WKT peut ne pas maintenir une précision totale en virgule flottante. Pour garantir une précision totale pour le stockage ou le transport des données, il est préférable d'utiliser le format Well-Known Binary (WKB) (voir ST_AsBinary et |
![]() | |
L'utilisation du paramètre |
Disponibilité : 1.5 - le support de la geography a été introduit.
Amélioration : 2.5 - introduction de la précision des paramètres optionnels.
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s2.1.1.1
This method implements the SQL/MM specification. SQL-MM 3 : 5.1.25
This method supports Circular Strings and Curves
SELECT ST_AsText('01030000000100000005000000000000000000 000000000000000000000000000000000000000000000000 F03F000000000000F03F000000000000F03F000000000000F03 F000000000000000000000000000000000000000000000000') ; st_astext -------------------------------- POLYGON((0 0,0 1,1 1,1 0,0 0))
La sortie de précision complète est la valeur par défaut.
SELECT ST_AsText('POINT(111.1111111 1.1111111)')) ; st_astext ------------------------------ POINT(111.1111111 1.1111111)
L'argument maxdecimaldigits
peut être utilisé pour limiter la précision de la sortie.
SELECT ST_AsText('POINT(111.1111111 1.1111111)'), 2) ; st_astext -------------------- POINT(111.11 1.11)
ST_AsBinary — Renvoie la représentation OGC/ISO Well-Known Binary (WKB) de la géométrie/geography sans les métadonnées SRID.
bytea ST_AsBinary(
geometry g1)
;
bytea ST_AsBinary(
geometry g1, text NDR_or_XDR)
;
bytea ST_AsBinary(
geography g1)
;
bytea ST_AsBinary(
geography g1, text NDR_or_XDR)
;
Renvoie la représentation OGC/ISO Well-Known Binary (WKB) de la géométrie. La première variante de fonction propose par défaut un encodage utilisant l'endian de la machine serveur. La deuxième variante de la fonction prend un argument texte spécifiant l'encodage endian, soit little-endian ('NDR') ou big-endian ('XDR').
Le format WKB est utile pour lire les données géométriques de la base de données et maintenir une précision numérique totale. Cela permet d'éviter les arrondis de précision qui peuvent se produire avec les formats texte tels que WKT.
Pour effectuer la conversion inverse de la géométrie WKB en géométrie PostGIS, utilisez ST_GeomFromWKB.
![]() | |
Le format WKB de l'OGC/ISO ne comprend pas le SRID. Pour obtenir le format EWKB qui inclut le SRID, utilisez ST_AsEWKB |
![]() | |
Le comportement par défaut dans PostgreSQL 9.0 a été modifié pour sortir bytea en encodage hexagonal. Si vos outils GUI nécessitent l'ancien comportement, alors SET bytea_output='escape' dans votre base de données. |
Amélioration : 2.0.0 introduction du support TIN, Triangles et surfaces polyédriques.
Amélioration : 2.0.0 le support pour des dimensions de coordonnées plus élevées a été introduit.
Amélioration : 2.0.0 le support pour spécifier endian avec geography a été introduit.
Disponibilité : 1.5.0 Le support de la géographie a été introduit.
Modifié : 2.0.0 Les entrées de cette fonction ne peuvent pas être inconnues, elles doivent être des géométries. Des constructions telles que ST_AsBinary('POINT(1 2)')
ne sont plus valides et vous obtiendrez une erreur de type n st_asbinary(unknown) is not unique
. Un code comme celui-là doit être changé en ST_AsBinary('POINT(1 2)'::geometry);
. Si cela n'est pas possible, alors installez legacy.sql
.
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s2.1.1.1
This method implements the SQL/MM specification. SQL-MM 3 : 5.1.37
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
This function supports 3d and will not drop the z-index.
SELECT ST_AsBinary(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326)) ; st_asbinary -------------------------------- \x01030000000100000005000000000000000000000000000000000000000000000000000000000000 000000f03f000000000000f03f000000000000f03f000000000000f03f0000000000000000000000 00000000000000000000000000
SELECT ST_AsBinary(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326), 'XDR') ; st_asbinary -------------------------------- \x000000000300000001000000050000000000000000000000000000000000000000000000003ff000 00000000003ff00000000000003ff00000000000003ff00000000000000000000000000000000000 00000000000000000000000000
ST_AsEWKB — Renvoie la représentation Extended Well-Known Binary (EWKB) de la géométrie avec les métadonnées SRID.
bytea ST_AsEWKB(
geometry g1)
;
bytea ST_AsEWKB(
geometry g1, text NDR_or_XDR)
;
Renvoie la représentation Extended Well-Known Binary (EWKB) de la géométrie avec les métadonnées SRID. La première variante de la fonction utilise par défaut l'encodage endian de la machine du serveur. La deuxième variante de la fonction prend un argument texte spécifiant l'encodage endian, soit little-endian ('NDR') ou big-endian ('XDR').
Le format WKB est utile pour lire les données géométriques de la base de données et maintenir une précision numérique totale. Cela permet d'éviter les arrondis de précision qui peuvent se produire avec les formats texte tels que WKT.
Pour effectuer la conversion inverse de la géométrie EWKB en géométrie PostGIS, utilisez ST_GeomFromEWKB.
![]() | |
Pour obtenir le format OGC/ISO WKB, utilisez ST_AsBinary. Notez que le format OGC/ISO WKB ne comprend pas le SRID. |
Amélioration : 2.0.0 introduction du support TIN, Triangles et surfaces polyédriques.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
SELECT ST_AsEWKB(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326)) ; st_asewkb -------------------------------- \x0103000020e610000001000000050000000000000000000000000000000000000000000000000000 00000000000000f03f000000000000f03f000000000000f03f000000000000f03f00000000000000 0000000000000000000000000000000000
SELECT ST_AsEWKB(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326), 'XDR') ; st_asewkb -------------------------------- \x0020000003000010e600000001000000050000000000000000000000000000000000000000000000 003ff00000000000003ff00000000000003ff00000000000003ff000000000000000000000000000 0000000000000000000000000000000000
ST_AsHEXEWKB — Renvoie une géométrie au format HEXEWKB (en tant que texte) en utilisant l'encodage little-endian (NDR) ou big-endian (XDR).
text ST_AsHEXEWKB(
geometry g1, text NDRorXDR)
;
text ST_AsHEXEWKB(
geometry g1)
;
Renvoie une géométrie au format HEXEWKB (en tant que texte) en utilisant l'encodage little-endian (NDR) ou big-endian (XDR). Si aucun encodage n'est spécifié, NDR est utilisé.
![]() | |
Disponibilité : 1.2.2 |
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
SELECT ST_AsHEXEWKB(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326)) ; which gives same answer as SELECT ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326)::text ; st_ashexewkb -------- 0103000020E6100000010000000500 00000000000000000000000000000000 00000000000000000000000000000000F03F 000000000000F03F000000000000F03F000000000000F03 F000000000000000000000000000000000000000000000000
ST_AsEncodedPolyline — Renvoie une polyligne encodée à partir d'une géométrie LineString.
text ST_AsEncodedPolyline(
geometry geom, integer precision=5)
;
Renvoie la géométrie sous forme de polyligne encodée. Ce format est utilisé par Google Maps avec précision=5 et par Open Source Routing Machine avec précision=5 et 6.
L'option precision
spécifie le nombre de décimales qui seront préservées dans la polyligne encodée. La valeur doit être la même à l'encodage et au décodage, sinon les coordonnées seront incorrectes.
Disponibilité : 2.2.0
Base
SELECT ST_AsEncodedPolyline(GeomFromEWKT('SRID=4326;LINESTRING(-120.2 38.5,-120.95 40.7,-126.453 43.252)')) ; --résultat-- |_p~iF~ps|U_ulLnnqC_mqNvxq`@
Utiliser en conjonction avec geography linestring et geography segmentize, et mettre sur google maps
-- le SQL pour Boston à San Francisco, des segments tous les 100 KM SELECT ST_AsEncodedPolyline( ST_Segmentize( ST_GeogFromText('LINESTRING(-71.0519 42.4935,-122.4483 37.64)'), 100000)::geometry) As encodedFlightPath ;
Le javascript ressemblera à quelque chose comme ceci où la variable $ est remplacée par le résultat de la requête
<script type="text/javascript" src="http ://maps.googleapis.com/maps/api/js ?libraries=geometry" ></script> <script type="text/javascript"> flightPath = new google.maps.Polyline({ path : google.maps.geometry.encoding.decodePath("$encodedFlightPath"), map : map, strokeColor : '#0000CC', strokeOpacity : 1.0, strokeWeight : 4 }) ; </script>
ST_AsFlatGeobuf — Renvoie une représentation FlatGeobuf d'un ensemble de lignes.
bytea ST_AsFlatGeobuf(
anyelement set row)
;
bytea ST_AsFlatGeobuf(
anyelement row, bool index)
;
bytea ST_AsFlatGeobuf(
anyelement row, bool index, text geom_name)
;
Renvoie une représentation FlatGeobuf (http://flatgeobuf.org) d'un ensemble de lignes correspondant à une FeatureCollection. REMARQUE : les octets PostgreSQL ne peuvent pas dépasser 1 Go.
row
données de ligne avec au moins une colonne de géométrie.
index
basculer la création d'un index spatial. La valeur par défaut est false.
geom_name
est le nom de la colonne de géométrie dans les données de la ligne. Si elle est NULL, elle prendra par défaut la première colonne de géométrie trouvée.
Disponibilité : 3.2.0
ST_AsGeobuf — Retourne une représentation Geobuf d'un ensemble de lignes.
bytea ST_AsGeobuf(
anyelement set row)
;
bytea ST_AsGeobuf(
anyelement row, text geom_name)
;
Renvoie une représentation Geobuf (https://github.com/mapbox/geobuf) d'un ensemble de lignes correspondant à une FeatureCollection. Chaque géométrie en entrée est analysée afin de déterminer la précision maximale pour un stockage optimal. Notez que Geobuf dans sa forme actuelle ne peut pas être streamé, donc la sortie complète sera assemblée en mémoire.
row
données de ligne avec au moins une colonne de géométrie.
geom_name
est le nom de la colonne de géométrie dans les données de la ligne. Si elle est NULL, elle prendra par défaut la première colonne de géométrie trouvée.
Disponibilité : 2.4.0
ST_AsGeoJSON — Renvoie une géométrie sous la forme d'un élément GeoJSON.
text ST_AsGeoJSON(
record feature, text geomcolumnname, integer maxdecimaldigits=9, boolean pretty_bool=false)
;
text ST_AsGeoJSON(
geometry geom, integer maxdecimaldigits=9, integer options=8)
;
text ST_AsGeoJSON(
geography geog, integer maxdecimaldigits=9, integer options=0)
;
Renvoie une géométrie sous la forme d'une "géométrie" GeoJSON, ou une ligne sous la forme d'une "caractéristique" GeoJSON. (Voir le spécifications GeoJSON RFC 7946). Les géométries 2D et 3D sont toutes deux supportées. GeoJSON ne supporte que les types de géométrie SFS 1.1 (pas de support des courbes par exemple).
L'argument maxdecimaldigits
peut être utilisé pour réduire le nombre maximum de décimales utilisées dans la sortie (par défaut 9). Si vous utilisez EPSG:4326 et que vous sortez la géométrie uniquement pour l'affichage, maxdecimaldigits
=6 peut être un bon choix pour de nombreuses cartes.
![]() | |
L'utilisation du paramètre |
L'argument options
peut être utilisé pour ajouter BBOX ou CRS dans la sortie GeoJSON :
0 : signifie aucune option
1 : GeoJSON BBOX
2 : GeoJSON Short CRS (e.g. EPSG:4326)
4 : GeoJSON Long CRS (e.g. urn:ogc:def:crs:EPSG::4326)
8 : GeoJSON Short CRS si pas EPSG:4326 (par défaut)
Si nécessaire, la géométrie peut être projetée en WGS84 en utilisant ST_Transform : ST_Transform( geom, 4326 )
.
GeoJSON can be tested and viewed online at geojson.io and geojsonlint.com. It is widely supported by web mapping frameworks:
Availability: 1.3.4
Disponibilité : 1.5.0 Le support de la géographie a été introduit.
Changed: 2.0.0 support default args and named args.
Changed: 3.0.0 support records as input
Changed: 3.0.0 output SRID if not EPSG:4326.
This function supports 3d and will not drop the z-index.
Generate a FeatureCollection:
SELECT json_build_object( 'type', 'FeatureCollection', 'features', json_agg(ST_AsGeoJSON(t.*)::json) ) FROM ( VALUES (1, 'one', 'POINT(1 1)'::geometry), (2, 'two', 'POINT(2 2)'), (3, 'three', 'POINT(3 3)') ) as t(id, name, geom);
{"type" : "FeatureCollection", "features" : [{"type": "Feature", "geometry": {"type":"Point","coordinates":[1,1]}, "properties": {"id": 1, "name": "one"}}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[2,2]}, "properties": {"id": 2, "name": "two"}}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[3,3]}, "properties": {"id": 3, "name": "three"}}]}
Generate a Feature:
SELECT ST_AsGeoJSON(t.*) FROM (VALUES (1, 'one', 'POINT(1 1)'::geometry)) AS t(id, name, geom);
st_asgeojson ----------------------------------------------------------------------------------------------------------------- {"type": "Feature", "geometry": {"type":"Point","coordinates":[1,1]}, "properties": {"id": 1, "name": "one"}}
An alternate way to generate Features with an id
property is to use JSONB functions and operators:
SELECT jsonb_build_object( 'type', 'Feature', 'id', id, 'geometry', ST_AsGeoJSON(geom)::jsonb, 'properties', to_jsonb( t.* ) - 'id' - 'geom' ) AS json FROM (VALUES (1, 'one', 'POINT(1 1)'::geometry)) AS t(id, name, geom);
json ----------------------------------------------------------------------------------------------------------------- {"id": 1, "type": "Feature", "geometry": {"type": "Point", "coordinates": [1, 1]}, "properties": {"name": "one"}}
Don't forget to transform your data to WGS84 longitude, latitude to conform with the GeoJSON specification:
SELECT ST_AsGeoJSON(ST_Transform(geom,4326)) from fe_edges limit 1;
st_asgeojson ----------------------------------------------------------------------------------------------------------- {"type":"MultiLineString","coordinates":[[[-89.734634999999997,31.492072000000000], [-89.734955999999997,31.492237999999997]]]}
3D geometries are supported:
SELECT ST_AsGeoJSON('LINESTRING(1 2 3, 4 5 6)');
{"type":"LineString","coordinates":[[1,2,3],[4,5,6]]}
ST_AsGML — Return the geometry as a GML version 2 or 3 element.
text ST_AsGML(
geometry geom, integer maxdecimaldigits=15, integer options=0)
;
text ST_AsGML(
geography geog, integer maxdecimaldigits=15, integer options=0, text nprefix=null, text id=null)
;
text ST_AsGML(
integer version, geometry geom, integer maxdecimaldigits=15, integer options=0, text nprefix=null, text id=null)
;
text ST_AsGML(
integer version, geography geog, integer maxdecimaldigits=15, integer options=0, text nprefix=null, text id=null)
;
Return the geometry as a Geography Markup Language (GML) element. The version parameter, if specified, may be either 2 or 3. If no version parameter is specified then the default is assumed to be 2. The maxdecimaldigits
argument may be used to reduce the maximum number of decimal places used in output (defaults to 15).
![]() | |
L'utilisation du paramètre |
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
Disponibilité : 1.5.0 Le support de la géographie a été introduit.
Enhanced: 2.0.0 prefix support was introduced. Option 4 for GML3 was introduced to allow using LineString instead of Curve tag for lines. GML3 Support for Polyhedral surfaces and TINS was introduced. Option 32 was introduced to output the box.
Changed: 2.0.0 use default named args
Enhanced: 2.1.0 id support was introduced, for GML 3.
![]() | |
Only version 3+ of ST_AsGML supports Polyhedral Surfaces and TINS. |
This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 17.2
This function supports 3d and will not drop the z-index.
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
SELECT ST_AsGML(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326)); st_asgml -------- <gml:Polygon srsName="EPSG:4326" ><gml:outerBoundaryIs ><gml:LinearRing ><gml:coordinates >0,0 0,1 1,1 1,0 0,0</gml:coordinates ></gml:LinearRing ></gml:outerBoundaryIs ></gml:Polygon >
-- Flip coordinates and output extended EPSG (16 | 1)-- SELECT ST_AsGML(3, ST_GeomFromText('POINT(5.234234233242 6.34534534534)',4326), 5, 17); st_asgml -------- <gml:Point srsName="urn:ogc:def:crs:EPSG::4326"><gml:pos>6.34535 5.23423</gml:pos></gml:Point>
-- Output the envelope (32) -- SELECT ST_AsGML(3, ST_GeomFromText('LINESTRING(1 2, 3 4, 10 20)',4326), 5, 32); st_asgml -------- <gml:Envelope srsName="EPSG:4326"> <gml:lowerCorner>1 2</gml:lowerCorner> <gml:upperCorner>10 20</gml:upperCorner> </gml:Envelope>
-- Output the envelope (32) , reverse (lat lon instead of lon lat) (16), long srs (1)= 32 | 16 | 1 = 49 -- SELECT ST_AsGML(3, ST_GeomFromText('LINESTRING(1 2, 3 4, 10 20)',4326), 5, 49); st_asgml -------- <gml:Envelope srsName="urn:ogc:def:crs:EPSG::4326"> <gml:lowerCorner>2 1</gml:lowerCorner> <gml:upperCorner>20 10</gml:upperCorner> </gml:Envelope>
-- Polyhedral Example -- SELECT ST_AsGML(3, ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )')); st_asgml -------- <gml:PolyhedralSurface> <gml:polygonPatches> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing> <gml:posList srsDimension="3">0 0 0 0 0 1 0 1 1 0 1 0 0 0 0</gml:posList> </gml:LinearRing> </gml:exterior> </gml:PolygonPatch> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing> <gml:posList srsDimension="3">0 0 0 0 1 0 1 1 0 1 0 0 0 0 0</gml:posList> </gml:LinearRing> </gml:exterior> </gml:PolygonPatch> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing> <gml:posList srsDimension="3">0 0 0 1 0 0 1 0 1 0 0 1 0 0 0</gml:posList> </gml:LinearRing> </gml:exterior> </gml:PolygonPatch> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing> <gml:posList srsDimension="3">1 1 0 1 1 1 1 0 1 1 0 0 1 1 0</gml:posList> </gml:LinearRing> </gml:exterior> </gml:PolygonPatch> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing> <gml:posList srsDimension="3">0 1 0 0 1 1 1 1 1 1 1 0 0 1 0</gml:posList> </gml:LinearRing> </gml:exterior> </gml:PolygonPatch> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing> <gml:posList srsDimension="3">0 0 1 1 0 1 1 1 1 0 1 1 0 0 1</gml:posList> </gml:LinearRing> </gml:exterior> </gml:PolygonPatch> </gml:polygonPatches> </gml:PolyhedralSurface>
ST_AsKML — Return the geometry as a KML element.
text ST_AsKML(
geometry geom, integer maxdecimaldigits=15, text nprefix=NULL)
;
text ST_AsKML(
geography geog, integer maxdecimaldigits=15, text nprefix=NULL)
;
Return the geometry as a Keyhole Markup Language (KML) element. default maximum number of decimal places is 15, default namespace is no prefix.
![]() | |
L'utilisation du paramètre |
![]() | |
Requires PostGIS be compiled with Proj support. Use PostGIS_Full_Version to confirm you have proj support compiled in. |
![]() | |
Availability: 1.2.2 - later variants that include version param came in 1.3.2 |
![]() | |
Enhanced: 2.0.0 - Add prefix namespace, use default and named args |
![]() | |
Changed: 3.0.0 - Removed the "versioned" variant signature |
![]() | |
AsKML output will not work with geometries that do not have an SRID |
This function supports 3d and will not drop the z-index.
SELECT ST_AsKML(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326)); st_askml -------- <Polygon ><outerBoundaryIs ><LinearRing ><coordinates >0,0 0,1 1,1 1,0 0,0</coordinates ></LinearRing ></outerBoundaryIs ></Polygon> --3d linestring SELECT ST_AsKML('SRID=4326;LINESTRING(1 2 3, 4 5 6)'); <LineString ><coordinates >1,2,3 4,5,6</coordinates ></LineString>
ST_AsLatLonText — Return the Degrees, Minutes, Seconds representation of the given point.
text ST_AsLatLonText(
geometry pt, text format='')
;
Returns the Degrees, Minutes, Seconds representation of the point.
![]() | |
It is assumed the point is in a lat/lon projection. The X (lon) and Y (lat) coordinates are normalized in the output to the "normal" range (-180 to +180 for lon, -90 to +90 for lat). |
The text parameter is a format string containing the format for the resulting text, similar to a date format string. Valid tokens are "D" for degrees, "M" for minutes, "S" for seconds, and "C" for cardinal direction (NSEW). DMS tokens may be repeated to indicate desired width and precision ("SSS.SSSS" means " 1.0023").
"M", "S", and "C" are optional. If "C" is omitted, degrees are shown with a "-" sign if south or west. If "S" is omitted, minutes will be shown as decimal with as many digits of precision as you specify. If "M" is also omitted, degrees are shown as decimal with as many digits precision as you specify.
If the format string is omitted (or zero-length) a default format will be used.
Availability: 2.0
Default format.
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)')); st_aslatlontext ---------------------------- 2°19'29.928"S 3°14'3.243"W
Providing a format (same as the default).
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)', 'D°M''S.SSS"C')); st_aslatlontext ---------------------------- 2°19'29.928"S 3°14'3.243"W
Characters other than D, M, S, C and . are just passed through.
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)', 'D degrees, M minutes, S seconds to the C')); st_aslatlontext -------------------------------------------------------------------------------------- 2 degrees, 19 minutes, 30 seconds to the S 3 degrees, 14 minutes, 3 seconds to the W
Signed degrees instead of cardinal directions.
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)', 'D°M''S.SSS"')); st_aslatlontext ---------------------------- -2°19'29.928" -3°14'3.243"
Decimal degrees.
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)', 'D.DDDD degrees C')); st_aslatlontext ----------------------------------- 2.3250 degrees S 3.2342 degrees W
Excessively large values are normalized.
SELECT (ST_AsLatLonText('POINT (-302.2342342 -792.32498)')); st_aslatlontext ------------------------------- 72°19'29.928"S 57°45'56.757"E
ST_AsMARC21 — Returns geometry as a MARC21/XML record with a geographic datafield (034).
text ST_AsMARC21 (
geometry geom , text format='hdddmmss' )
;
This function returns a MARC21/XML record with Coded Cartographic Mathematical Data representing the bounding box of a given geometry. The format
parameter allows to encode the coordinates in subfields $d
,$e
,$f
and $g
in all formats supported by the MARC21/XML standard. Valid formats are:
cardinal direction, degrees, minutes and seconds (default): hdddmmss
decimal degrees with cardinal direction: hddd.dddddd
decimal degrees without cardinal direction: ddd.dddddd
decimal minutes with cardinal direction: hdddmm.mmmm
decimal minutes without cardinal direction: dddmm.mmmm
decimal seconds with cardinal direction: hdddmmss.sss
The decimal sign may be also a comma, e.g. hdddmm,mmmm
.
The precision of decimal formats can be limited by the number of characters after the decimal sign, e.g. hdddmm.mm
for decimal minutes with a precision of two decimals.
This function ignores the Z and M dimensions.
Prise en charge des versions LOC MARC21/XML :
Disponibilité : 3.3.0
![]() | |
This function does not support non lon/lat geometries, as they are not supported by the MARC21/XML standard (Coded Cartographic Mathematical Data). |
![]() | |
The MARC21/XML Standard does not provide any means to annotate the spatial reference system for Coded Cartographic Mathematical Data, which means that this information will be lost after conversion to MARC21/XML. |
Converting a POINT
to MARC21/XML formated as hdddmmss (default)
SELECT ST_AsMARC21('SRID=4326;POINT(-4.504289 54.253312)'::geometry); st_asmarc21 ------------------------------------------------- <record xmlns="http://www.loc.gov/MARC21/slim"> <datafield tag="034" ind1="1" ind2=" "> <subfield code="a">a</subfield> <subfield code="d">W0043015</subfield> <subfield code="e">W0043015</subfield> <subfield code="f">N0541512</subfield> <subfield code="g">N0541512</subfield> </datafield> </record>
Converting a POLYGON
to MARC21/XML formated in decimal degrees
SELECT ST_AsMARC21('SRID=4326;POLYGON((-4.5792388916015625 54.18172660239091,-4.56756591796875 54.196993557130355,-4.546623229980469 54.18313300502024,-4.5792388916015625 54.18172660239091))'::geometry,'hddd.dddd'); <record xmlns="http://www.loc.gov/MARC21/slim"> <datafield tag="034" ind1="1" ind2=" "> <subfield code="a">a</subfield> <subfield code="d">W004.5792</subfield> <subfield code="e">W004.5466</subfield> <subfield code="f">N054.1970</subfield> <subfield code="g">N054.1817</subfield> </datafield> </record>
Converting a GEOMETRYCOLLECTION
to MARC21/XML formated in decimal minutes. The geometries order in the MARC21/XML output correspond to their order in the collection.
SELECT ST_AsMARC21('SRID=4326;GEOMETRYCOLLECTION(POLYGON((13.1 52.65,13.516666666666667 52.65,13.516666666666667 52.38333333333333,13.1 52.38333333333333,13.1 52.65)),POINT(-4.5 54.25))'::geometry,'hdddmm.mmmm'); st_asmarc21 ------------------------------------------------- <record xmlns="http://www.loc.gov/MARC21/slim"> <datafield tag="034" ind1="1" ind2=" "> <subfield code="a">a</subfield> <subfield code="d">E01307.0000</subfield> <subfield code="e">E01331.0000</subfield> <subfield code="f">N05240.0000</subfield> <subfield code="g">N05224.0000</subfield> </datafield> <datafield tag="034" ind1="1" ind2=" "> <subfield code="a">a</subfield> <subfield code="d">W00430.0000</subfield> <subfield code="e">W00430.0000</subfield> <subfield code="f">N05415.0000</subfield> <subfield code="g">N05415.0000</subfield> </datafield> </record>
ST_AsMVTGeom — Transforms a geometry into the coordinate space of a MVT tile.
geometry ST_AsMVTGeom(
geometry geom, box2d bounds, integer extent=4096, integer buffer=256, boolean clip_geom=true)
;
Transforms a geometry into the coordinate space of a MVT (Mapbox Vector Tile) tile, clipping it to the tile bounds if required. The geometry must be in the coordinate system of the target map (using ST_Transform if needed). Commonly this is Web Mercator (SRID:3857).
The function attempts to preserve geometry validity, and corrects it if needed. This may cause the result geometry to collapse to a lower dimension.
The rectangular bounds of the tile in the target map coordinate space must be provided, so the geometry can be transformed, and clipped if required. The bounds can be generated using ST_TileEnvelope.
This function is used to convert geometry into the tile coordinate space required by ST_AsMVT.
geom
is the geometry to transform, in the coordinate system of the target map.
bounds
is the rectangular bounds of the tile in map coordinate space, with no buffer.
extent
is the tile extent size in tile coordinate space as defined by the MVT specification. Defaults to 4096.
buffer
is the buffer size in tile coordinate space for geometry clippig. Defaults to 256.
clip_geom
is a boolean to control if geometries are clipped or encoded as-is. Defaults to true.
Disponibilité : 2.4.0
![]() | |
From 3.0, Wagyu can be chosen at configure time to clip and validate MVT polygons. This library is faster and produces more correct results than the GEOS default, but it might drop small polygons. |
SELECT ST_AsText(ST_AsMVTGeom( ST_GeomFromText('POLYGON ((0 0, 10 0, 10 5, 0 -5, 0 0))'), ST_MakeBox2D(ST_Point(0, 0), ST_Point(4096, 4096)), 4096, 0, false)); st_astext -------------------------------------------------------------------- MULTIPOLYGON(((5 4096,10 4091,10 4096,5 4096)),((5 4096,0 4101,0 4096,5 4096)))
Canonical example for a Web Mercator tile using a computed tile bounds to query and clip geometry.
SELECT ST_AsMVTGeom( ST_Transform( geom, 3857 ), ST_TileEnvelope(12, 513, 412), extent => 4096, buffer => 64) AS geom FROM data WHERE geom && ST_TileEnvelope(12, 513, 412, margin => (64.0 / 4096))
ST_AsMVT — Aggregate function returning a MVT representation of a set of rows.
bytea ST_AsMVT(
anyelement set row)
;
bytea ST_AsMVT(
anyelement row, text name)
;
bytea ST_AsMVT(
anyelement row, text name, integer extent)
;
bytea ST_AsMVT(
anyelement row, text name, integer extent, text geom_name)
;
bytea ST_AsMVT(
anyelement row, text name, integer extent, text geom_name, text feature_id_name)
;
An aggregate function which returns a binary Mapbox Vector Tile representation of a set of rows corresponding to a tile layer. The rows must contain a geometry column which will be encoded as a feature geometry. The geometry must be in tile coordinate space and valid as per the MVT specification. ST_AsMVTGeom can be used to transform geometry into tile coordinate space. Other row columns are encoded as feature attributes.
The Mapbox Vector Tile format can store features with varying sets of attributes. To use this capability supply a JSONB column in the row data containing Json objects one level deep. The keys and values in the JSONB values will be encoded as feature attributes.
Tiles with multiple layers can be created by concatenating multiple calls to this function using ||
or STRING_AGG
.
![]() | |
Do not call with a |
row
données de ligne avec au moins une colonne de géométrie.
name
is the name of the layer. Default is the string "default".
extent
is the tile extent in screen space as defined by the specification. Default is 4096.
geom_name
is the name of the geometry column in the row data. Default is the first geometry column. Note that PostgreSQL by default automatically folds unquoted identifiers to lower case, which means that unless the geometry column is quoted, e.g. "MyMVTGeom"
, this parameter must be provided as lowercase.
feature_id_name
is the name of the Feature ID column in the row data. If NULL or negative the Feature ID is not set. The first column matching name and valid type (smallint, integer, bigint) will be used as Feature ID, and any subsequent column will be added as a property. JSON properties are not supported.
Enhanced: 3.0 - added support for Feature ID.
Enhanced: 2.5.0 - added support parallel query.
Disponibilité : 2.4.0
ST_AsSVG — Returns SVG path data for a geometry.
text ST_AsSVG(
geometry geom, integer rel=0, integer maxdecimaldigits=15)
;
text ST_AsSVG(
geography geog, integer rel=0, integer maxdecimaldigits=15)
;
Return the geometry as Scalar Vector Graphics (SVG) path data. Use 1 as second argument to have the path data implemented in terms of relative moves, the default (or 0) uses absolute moves. Third argument may be used to reduce the maximum number of decimal digits used in output (defaults to 15). Point geometries will be rendered as cx/cy when 'rel' arg is 0, x/y when 'rel' is 1. Multipoint geometries are delimited by commas (","), GeometryCollection geometries are delimited by semicolons (";").
![]() | |
Availability: 1.2.2. Availability: 1.4.0 Changed in PostGIS 1.4.0 to include L command in absolute path to conform to http://www.w3.org/TR/SVG/paths.html#PathDataBNF |
Changed: 2.0.0 to use default args and support named args
ST_AsTWKB — Returns the geometry as TWKB, aka "Tiny Well-Known Binary"
bytea ST_AsTWKB(
geometry geom, integer prec=0, integer prec_z=0, integer prec_m=0, boolean with_sizes=false, boolean with_boxes=false)
;
bytea ST_AsTWKB(
geometry[] geom, bigint[] ids, integer prec=0, integer prec_z=0, integer prec_m=0, boolean with_sizes=false, boolean with_boxes=false)
;
Returns the geometry in TWKB (Tiny Well-Known Binary) format. TWKB is a compressed binary format with a focus on minimizing the size of the output.
The decimal digits parameters control how much precision is stored in the output. By default, values are rounded to the nearest unit before encoding. If you want to transfer more precision, increase the number. For example, a value of 1 implies that the first digit to the right of the decimal point will be preserved.
The sizes and bounding boxes parameters control whether optional information about the encoded length of the object and the bounds of the object are included in the output. By default they are not. Do not turn them on unless your client software has a use for them, as they just use up space (and saving space is the point of TWKB).
The array-input form of the function is used to convert a collection of geometries and unique identifiers into a TWKB collection that preserves the identifiers. This is useful for clients that expect to unpack a collection and then access further information about the objects inside. You can create the arrays using the array_agg function. The other parameters operate the same as for the simple form of the function.
![]() | |
The format specification is available online at https://github.com/TWKB/Specification, and code for building a JavaScript client can be found at https://github.com/TWKB/twkb.js. |
Enhanced: 2.4.0 memory and speed improvements.
Disponibilité : 2.2.0
SELECT ST_AsTWKB('LINESTRING(1 1,5 5)'::geometry); st_astwkb -------------------------------------------- \x02000202020808
To create an aggregate TWKB object including identifiers aggregate the desired geometries and objects first, using "array_agg()", then call the appropriate TWKB function.
SELECT ST_AsTWKB(array_agg(geom), array_agg(gid)) FROM mytable; st_astwkb -------------------------------------------- \x040402020400000202
ST_AsX3D — Returns a Geometry in X3D xml node element format: ISO-IEC-19776-1.2-X3DEncodings-XML
text ST_AsX3D(
geometry g1, integer maxdecimaldigits=15, integer options=0)
;
Returns a geometry as an X3D xml formatted node element http://www.web3d.org/standards/number/19776-1. If maxdecimaldigits
(precision) is not specified then defaults to 15.
![]() | |
There are various options for translating PostGIS geometries to X3D since X3D geometry types don't map directly to PostGIS geometry types and some newer X3D types that might be better mappings we have avoided since most rendering tools don't currently support them. These are the mappings we have settled on. Feel free to post a bug ticket if you have thoughts on the idea or ways we can allow people to denote their preferred mappings. Below is how we currently map PostGIS 2D/3D types to X3D types |
The 'options' argument is a bitfield. For PostGIS 2.2+, this is used to denote whether to represent coordinates with X3D GeoCoordinates Geospatial node and also whether to flip the x/y axis. By default, ST_AsX3D
outputs in database form (long,lat or X,Y), but X3D default of lat/lon, y/x may be preferred.
0: X/Y in database order (e.g. long/lat = X,Y is standard database order), default value, and non-spatial coordinates (just regular old Coordinate tag).
1: Flip X and Y. If used in conjunction with the GeoCoordinate option switch, then output will be default "latitude_first" and coordinates will be flipped as well.
2: Output coordinates in GeoSpatial GeoCoordinates. This option will throw an error if geometries are not in WGS 84 long lat (srid: 4326). This is currently the only GeoCoordinate type supported. Refer to X3D specs specifying a spatial reference system.. Default output will be GeoCoordinate geoSystem='"GD" "WE" "longitude_first"'
. If you prefer the X3D default of GeoCoordinate geoSystem='"GD" "WE" "latitude_first"'
use (2 + 1)
= 3
PostGIS Type | 2D X3D Type | 3D X3D Type |
---|---|---|
LINESTRING | not yet implemented - will be PolyLine2D | LineSet |
MULTILINESTRING | not yet implemented - will be PolyLine2D | IndexedLineSet |
MULTIPOINT | Polypoint2D | PointSet |
POINT | outputs the space delimited coordinates | outputs the space delimited coordinates |
(MULTI) POLYGON, POLYHEDRALSURFACE | Invalid X3D markup | IndexedFaceSet (inner rings currently output as another faceset) |
TIN | TriangleSet2D (Not Yet Implemented) | IndexedTriangleSet |
![]() | |
2D geometry support not yet complete. Inner rings currently just drawn as separate polygons. We are working on these. |
Lots of advancements happening in 3D space particularly with X3D Integration with HTML5
There is also a nice open source X3D viewer you can use to view rendered geometries. Free Wrl http://freewrl.sourceforge.net/ binaries available for Mac, Linux, and Windows. Use the FreeWRL_Launcher packaged to view the geometries.
Also check out PostGIS minimalist X3D viewer that utilizes this function and x3dDom html/js open source toolkit.
Availability: 2.0.0: ISO-IEC-19776-1.2-X3DEncodings-XML
Enhanced: 2.2.0: Support for GeoCoordinates and axis (x/y, long/lat) flipping. Look at options for details.
This function supports 3d and will not drop the z-index.
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
SELECT '<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE X3D PUBLIC "ISO//Web3D//DTD X3D 3.0//EN" "http://www.web3d.org/specifications/x3d-3.0.dtd"> <X3D> <Scene> <Transform> <Shape> <Appearance> <Material emissiveColor=''0 0 1''/> </Appearance> ' || ST_AsX3D( ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )')) || '</Shape> </Transform> </Scene> </X3D>' As x3ddoc; x3ddoc -------- <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE X3D PUBLIC "ISO//Web3D//DTD X3D 3.0//EN" "http://www.web3d.org/specifications/x3d-3.0.dtd"> <X3D> <Scene> <Transform> <Shape> <Appearance> <Material emissiveColor='0 0 1'/> </Appearance> <IndexedFaceSet coordIndex='0 1 2 3 -1 4 5 6 7 -1 8 9 10 11 -1 12 13 14 15 -1 16 17 18 19 -1 20 21 22 23'> <Coordinate point='0 0 0 0 0 1 0 1 1 0 1 0 0 0 0 0 1 0 1 1 0 1 0 0 0 0 0 1 0 0 1 0 1 0 0 1 1 1 0 1 1 1 1 0 1 1 0 0 0 1 0 0 1 1 1 1 1 1 1 0 0 0 1 1 0 1 1 1 1 0 1 1' /> </IndexedFaceSet> </Shape> </Transform> </Scene> </X3D>
Copy and paste the output of this query to x3d scene viewer and click Show
SELECT string_agg('<Shape>' || ST_AsX3D(ST_Extrude(geom, 0,0, i*0.5)) || '<Appearance> <Material diffuseColor="' || (0.01*i)::text || ' 0.8 0.2" specularColor="' || (0.05*i)::text || ' 0 0.5"/> </Appearance> </Shape>', '') FROM ST_Subdivide(ST_Letters('PostGIS'),20) WITH ORDINALITY AS f(geom,i);
Buildings formed by subdividing PostGIS and extrusion
SELECT ST_AsX3D( ST_Translate( ST_Force_3d( ST_Buffer(ST_Point(10,10),5, 'quad_segs=2')), 0,0, 3) ,6) As x3dfrag; x3dfrag -------- <IndexedFaceSet coordIndex="0 1 2 3 4 5 6 7"> <Coordinate point="15 10 3 13.535534 6.464466 3 10 5 3 6.464466 6.464466 3 5 10 3 6.464466 13.535534 3 10 15 3 13.535534 13.535534 3 " /> </IndexedFaceSet>
SELECT ST_AsX3D(ST_GeomFromEWKT('TIN ((( 0 0 0, 0 0 1, 0 1 0, 0 0 0 )), (( 0 0 0, 0 1 0, 1 1 0, 0 0 0 )) )')) As x3dfrag; x3dfrag -------- <IndexedTriangleSet index='0 1 2 3 4 5'><Coordinate point='0 0 0 0 0 1 0 1 0 0 0 0 0 1 0 1 1 0'/></IndexedTriangleSet>
SELECT ST_AsX3D( ST_GeomFromEWKT('MULTILINESTRING((20 0 10,16 -12 10,0 -16 10,-12 -12 10,-20 0 10,-12 16 10,0 24 10,16 16 10,20 0 10), (12 0 10,8 8 10,0 12 10,-8 8 10,-8 0 10,-8 -4 10,0 -8 10,8 -4 10,12 0 10))') ) As x3dfrag; x3dfrag -------- <IndexedLineSet coordIndex='0 1 2 3 4 5 6 7 0 -1 8 9 10 11 12 13 14 15 8'> <Coordinate point='20 0 10 16 -12 10 0 -16 10 -12 -12 10 -20 0 10 -12 16 10 0 24 10 16 16 10 12 0 10 8 8 10 0 12 10 -8 8 10 -8 0 10 -8 -4 10 0 -8 10 8 -4 10 ' /> </IndexedLineSet>
ST_GeoHash — Return a GeoHash representation of the geometry.
text ST_GeoHash(
geometry geom, integer maxchars=full_precision_of_point)
;
Computes a GeoHash representation of a geometry. A GeoHash encodes a geographic Point into a text form that is sortable and searchable based on prefixing. A shorter GeoHash is a less precise representation of a point. It can be thought of as a box that contains the point.
Non-point geometry values with non-zero extent can also be mapped to GeoHash codes. The precision of the code depends on the geographic extent of the geometry.
If maxchars
is not specified, the returned GeoHash code is for the smallest cell containing the input geometry. Points return a GeoHash with 20 characters of precision (about enough to hold the full double precision of the input). Other geometric types may return a GeoHash with less precision, depending on the extent of the geometry. Larger geometries are represented with less precision, smaller ones with more precision. The box determined by the GeoHash code always contains the input feature.
If maxchars
is specified the returned GeoHash code has at most that many characters. It maps to a (possibly) lower precision representation of the input geometry. For non-points, the starting point of the calculation is the center of the bounding box of the geometry.
Disponibilité : 1.4.0
![]() | |
ST_GeoHash requires input geometry to be in geographic (lon/lat) coordinates. |
This method supports Circular Strings and Curves
SELECT ST_GeoHash( ST_Point(-126,48) ); st_geohash ---------------------- c0w3hf1s70w3hf1s70w3 SELECT ST_GeoHash( ST_Point(-126,48), 5); st_geohash ------------ c0w3h -- This line contains the point, so the GeoHash is a prefix of the point code SELECT ST_GeoHash('LINESTRING(-126 48, -126.1 48.1)'::geometry); st_geohash ------------ c0w3
VRAI
si la boite englobante 2D de A intersecte la boite englobante 2D de B.TRUE
si la boîte de délimitation 2D (en cache) d'une géométrie intersecte une boîte de délimitation 2D de précision flottante (BOX2DF).TRUE
si une boîte de délimitation 2D de précision flottante (BOX2DF) intersecte la boîte de délimitation 2D (mise en cache) d'une géométrie.TRUE
si deux boîtes de délimitation 2D à précision flottante (BOX2DF) se croisent.TRUE
si la boîte de délimitation n-D de A intersecte la boîte de délimitation n-D de B.TRUE
si la boîte de délimitation n-D (en cache) d'une géométrie intersecte une boîte de délimitation de précision flottante n-D (GIDX).TRUE
si une boîte de délimitation de précision flottante n-D (GIDX) intersecte la boîte de délimitation n-D (mise en cache) d'une géométrie.TRUE
si deux boîtes de délimitation (GIDX) de précision flottante n-D se croisent.TRUE
si la boîte englobante de A chevauche ou est à gauche de celle de B.TRUE
si la boîte englobante de A chevauche ou est inférieure à celle de B.TRUE
si la boîte de délimitation de A chevauche ou est à droite de celle de B.TRUE
si la boîte de délimitation de A est strictement à gauche de celle de B.TRUE
si la boîte de délimitation de A est strictement inférieure à celle de B.TRUE
si les coordonnées et l'ordre des coordonnées de la géométrie/géographie A sont les mêmes que les coordonnées et l'ordre des coordonnées de la géométrie/géographie B.TRUE
si la boîte de délimitation de A est strictement à droite de celle de B.TRUE
si la boîte de délimitation de A est contenue par celle de B.TRUE
si la boîte de délimitation 2D d'une géométrie est contenue dans une boîte de délimitation 2D à précision flottante (BOX2DF).TRUE
si une boîte de délimitation de précision flottante 2D (BOX2DF) est contenue dans la boîte de délimitation 2D d'une géométrie.TRUE
si une boîte de délimitation de précision flottante 2D (BOX2DF) est contenue dans une autre boîte de délimitation de précision flottante 2D.TRUE
si la boîte de délimitation de A chevauche ou est au-dessus de celle de B.TRUE
si la boîte de délimitation de A est strictement au-dessus de celle de B.TRUE
si la boîte de délimitation de A contient celle de B.TRUE
si la boîte de délimitation 2D d'une géométrie contient une boîte de délimitation de précision flottante 2D (GIDX).TRUE
si une boîte de délimitation de précision flottante 2D (BOX2DF) contient la boîte de délimitation 2D d'une géométrie.TRUE
si une boîte de délimitation de précision flottante 2D (BOX2DF) contient une autre boîte de délimitation de précision flottante 2D (BOX2DF).TRUE
si la boîte de délimitation de A est la même que celle de B.&& — Renvoi VRAI
si la boite englobante 2D de A intersecte la boite englobante 2D de B.
booléen &&(
geometry A , geometry B )
;
booléen &&(
geography A , geography B )
;
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.
![]() | |
Cette opérande utilisera tous les index qui peuvent être disponibles sur les géométries. |
Amélioration : 2.0.0 introduction du support des surfaces polyédriques.
Disponibilité : 1.5.0 le support de la géographie a été introduit.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
SELECT tbl1.column1, tbl2.column1, tbl1.column2 && tbl2.column2 AS overlaps FROM ( VALUES (1, 'LINESTRING(0 0, 3 3)'::geometry), (2, 'LINESTRING(0 1, 0 5)'::geometry)) AS tbl1, ( VALUES (3, 'LINESTRING(1 2, 4 6)'::geometry)) AS tbl2 ; column1 | column1 | overlaps ---------+---------+---------- 1 | 3 | t 2 | 3 | f (2 rows)
&&(geometry,box2df) — Renvoie TRUE
si la boîte de délimitation 2D (en cache) d'une géométrie intersecte une boîte de délimitation 2D de précision flottante (BOX2DF).
boolean &&(
geometry A , box2df B )
;
L'opérateur &&
renvoie TRUE
si la boîte de délimitation 2D mise en cache de la géométrie A intersecte la boîte de délimitation 2D B, en utilisant la précision float. Cela signifie que si B est un box2d (double précision), il sera converti en interne en une boîte de délimitation 2D à précision flottante (BOX2DF)
![]() | |
Cet opérande est destiné à être utilisé en interne par les index BRIN, plus que par les utilisateurs. |
Disponibilité : 2.3.0 le support des Block Range INdexes (BRIN) a été introduit. Nécessite PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
&&(box2df,geometry) — Renvoie TRUE
si une boîte de délimitation 2D de précision flottante (BOX2DF) intersecte la boîte de délimitation 2D (mise en cache) d'une géométrie.
boolean &&(
box2df A , geometry B )
;
L'opérateur &&
renvoie TRUE
si la boîte de délimitation 2D A intersecte la boîte de délimitation 2D mise en cache de la géométrie B, en utilisant la précision float. Cela signifie que si A est un box2d (double précision), il sera converti en interne en une boîte de délimitation 2D à précision flottante (BOX2DF)
![]() | |
Cet opérande est destiné à être utilisé en interne par les index BRIN, plus que par les utilisateurs. |
Disponibilité : 2.3.0 le support des Block Range INdexes (BRIN) a été introduit. Nécessite PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
&&(box2df,box2df) — Renvoie TRUE
si deux boîtes de délimitation 2D à précision flottante (BOX2DF) se croisent.
boolean &&(
box2df A , box2df B )
;
L'opérateur &&
renvoie TRUE
si deux boîtes de délimitation 2D A et B se croisent, en utilisant la précision float. Cela signifie que si A (ou B) est un box2d (double précision), il sera converti en interne en une boîte de délimitation 2D de précision flottante (BOX2DF)
![]() | |
Cet opérateur est destiné à être utilisé en interne par les index BRIN, plus que par les utilisateurs. |
Disponibilité : 2.3.0 le support des Block Range INdexes (BRIN) a été introduit. Nécessite PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
&&& — Renvoie TRUE
si la boîte de délimitation n-D de A intersecte la boîte de délimitation n-D de B.
boolean &&&(
geometry A , geometry B )
;
L'opérateur &&&
renvoie TRUE
si la boîte de délimitation n-D de la géométrie A intersecte la boîte de délimitation n-D de la géométrie B.
![]() | |
Cette opérande utilisera tous les index qui peuvent être disponibles sur les géométries. |
Disponibilité : 2.0.0
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
This function supports 3d and will not drop the z-index.
SELECT tbl1.column1, tbl2.column1, tbl1.column2 &&& tbl2.column2 AS overlaps_3d, tbl1.column2 && tbl2.column2 AS overlaps_2d FROM ( VALUES (1, 'LINESTRING Z(0 0 1, 3 3 2)'::geometry), (2, 'LINESTRING Z(1 2 0, 0 5 -1)'::geometry)) AS tbl1, ( VALUES (3, 'LINESTRING Z(1 2 1, 4 6 1)'::geometry)) AS tbl2 ; column1 | column1 | overlaps_3d | overlaps_2d ---------+---------+-------------+------------- 1 | 3 | t | t 2 | 3 | f | t
SELECT tbl1.column1, tbl2.column1, tbl1.column2 &&& tbl2.column2 AS overlaps_3zm, tbl1.column2 && tbl2.column2 AS overlaps_2d FROM ( VALUES (1, 'LINESTRING M(0 0 1, 3 3 2)'::geometry), (2, 'LINESTRING M(1 2 0, 0 5 -1)'::geometry)) AS tbl1, ( VALUES (3, 'LINESTRING M(1 2 1, 4 6 1)'::geometry)) AS tbl2 ; column1 | column1 | overlaps_3zm | overlaps_2d ---------+---------+-------------+------------- 1 | 3 | t | t 2 | 3 | f | t
&&&(geometry,gidx) — Renvoie TRUE
si la boîte de délimitation n-D (en cache) d'une géométrie intersecte une boîte de délimitation de précision flottante n-D (GIDX).
boolean &&&(
geometry A , gidx B )
;
L'opérateur &&&
renvoie TRUE
si la boîte de délimitation n-D mise en cache de la géométrie A intersecte la boîte de délimitation n-D B, en utilisant la précision float. Cela signifie que si B est un box3d (double précision), il sera converti en interne en une boîte de délimitation 3D de précision flottante (GIDX)
![]() | |
Cet opérateur est destiné à être utilisé en interne par les index BRIN, plus que par les utilisateurs. |
Disponibilité : 2.3.0 le support des Block Range INdexes (BRIN) a été introduit. Nécessite PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
This function supports 3d and will not drop the z-index.
&&&(gidx,geometry) — Renvoie TRUE
si une boîte de délimitation de précision flottante n-D (GIDX) intersecte la boîte de délimitation n-D (mise en cache) d'une géométrie.
boolean &&&(
gidx A , geometry B )
;
L'opérateur &&&
renvoie TRUE
si la boîte de délimitation n-D A intersecte la boîte de délimitation n-D mise en cache de la géométrie B, en utilisant la précision float. Cela signifie que si A est un box3d (à double précision), il sera converti en interne en une boîte de délimitation 3D à précision flottante (GIDX)
![]() | |
Cet opérateur est destiné à être utilisé en interne par les index BRIN, plus que par les utilisateurs. |
Disponibilité : 2.3.0 le support des Block Range INdexes (BRIN) a été introduit. Nécessite PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
This function supports 3d and will not drop the z-index.
&&&(gidx,gidx) — Renvoie TRUE
si deux boîtes de délimitation (GIDX) de précision flottante n-D se croisent.
boolean &&&(
gidx A , gidx B )
;
L'opérateur &&&
renvoie TRUE
si deux boîtes de délimitation n-D A et B se croisent, en utilisant la précision float. Cela signifie que si A (ou B) est un box3d (double précision), il sera converti en interne en une boîte de délimitation 3D de précision flottante (GIDX).
![]() | |
Cet opérateur est destiné à être utilisé en interne par les index BRIN, plus que par les utilisateurs. |
Disponibilité : 2.3.0 le support des Block Range INdexes (BRIN) a été introduit. Nécessite PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
This function supports 3d and will not drop the z-index.
&< — Renvoie TRUE
si la boîte englobante de A chevauche ou est à gauche de celle de B.
boolean &<(
geometry A , geometry B )
;
L'opérateur &<
renvoie TRUE
si la boîte de délimitation de la géométrie A chevauche ou est à gauche de la boîte de délimitation de la géométrie B, ou plus exactement, chevauche ou n'est PAS à droite de la boîte de délimitation de la géométrie B.
![]() | |
Cette opérande utilisera tous les index qui peuvent être disponibles sur les géométries. |
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)
&<| — Renvoie TRUE
si la boîte englobante de A chevauche ou est inférieure à celle de B.
boolean &<|(
geometry A , geometry B )
;
L'opérateur &<|
renvoie TRUE
si la boîte de délimitation de la géométrie A chevauche ou est en dessous de la boîte de délimitation de la géométrie B, ou plus exactement, chevauche ou n'est PAS au-dessus de la boîte de délimitation de la géométrie B.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
![]() | |
Cette opérande utilisera tous les index qui peuvent être disponibles sur les géométries. |
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)
&> — Renvoie TRUE
si la boîte de délimitation de A chevauche ou est à droite de celle de B.
boolean &>(
geometry A , geometry B )
;
L'opérateur &>
renvoie TRUE
si la boîte de délimitation de la géométrie A chevauche ou est à droite de la boîte de délimitation de la géométrie B, ou plus exactement, chevauche ou n'est PAS à gauche de la boîte de délimitation de la géométrie B.
![]() | |
Cette opérande utilisera tous les index qui peuvent être disponibles sur les géométries. |
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)
<< — Renvoie TRUE
si la boîte de délimitation de A est strictement à gauche de celle de B.
boolean <<(
geometry A , geometry B )
;
L'opérateur <<
renvoie TRUE
si la boîte de délimitation de la géométrie A est strictement à gauche de la boîte de délimitation de la géométrie B.
![]() | |
Cette opérande utilisera tous les index qui peuvent être disponibles sur les géométries. |
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)
<<| — Renvoie TRUE
si la boîte de délimitation de A est strictement inférieure à celle de B.
boolean <<|(
geometry A , geometry B )
;
L'opérateur <<|
renvoie TRUE
si la boîte de délimitation de la géométrie A est strictement inférieure à la boîte de délimitation de la géométrie B.
![]() | |
Cette opérande utilisera tous les index qui peuvent être disponibles sur les géométries. |
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)
= — Renvoie TRUE
si les coordonnées et l'ordre des coordonnées de la géométrie/géographie A sont les mêmes que les coordonnées et l'ordre des coordonnées de la géométrie/géographie B.
boolean =(
geometry A , geometry B )
;
boolean =(
geography A , geography B )
;
L'opérateur =
renvoie TRUE
si les coordonnées et l'ordre des coordonnées de la géométrie/géographie A sont les mêmes que les coordonnées et l'ordre des coordonnées de la géométrie/géographie B. PostgreSQL utilise les opérateurs =, <, et > définis pour les géométries pour effectuer des classements internes et des comparaisons de géométries (c'est-à-dire dans une clause GROUP BY ou ORDER BY).
![]() | |
Seules les géométries/géographies qui sont exactement égales à tous égards, avec les mêmes coordonnées, dans le même ordre, sont considérées comme égales par cet opérateur. Pour une "égalité spatiale", qui ignore des choses comme l'ordre des coordonnées, et peut détecter des caractéristiques qui couvrent la même zone spatiale avec des représentations différentes, utilisez ST_OrderingEquals ou ST_Equals |
![]() | |
Cet opérande n'utilisera PAS les index qui peuvent être disponibles sur les géométries. Pour un test d'égalité exact assisté par index, combinez = avec &&. |
Modifié : 2.4.0, dans les versions précédentes, il s'agissait d'une égalité de boîte de délimitation et non d'une égalité géométrique. Si vous avez besoin d'une égalité de boîte de délimitation, utilisez ~= à la place.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
SELECT 'LINESTRING(0 0, 0 1, 1 0)' ::geometry = 'LINESTRING(1 1, 0 0)' ::geometry ; ?column ? ---------- f (1 row) SELECT ST_AsText(column1) FROM ( VALUES ('LINESTRING(0 0, 1 1)' ::geometry), ('LINESTRING(1 1, 0 0)' ::geometry)) AS foo ; st_astext --------------------- LINESTRING(0 0,1 1) LINESTRING(1 1,0 0) (2 rows) -- Note : le GROUP BY utilise le "=" pour comparer pour l'équivalence de géométrie. SELECT ST_AsText(column1) FROM ( VALUES ('LINESTRING(0 0, 1 1)' ::geometry), ('LINESTRING(1 1, 0 0)' ::geometry)) AS foo GROUP BY column1 ; st_astext --------------------- LINESTRING(0 0,1 1) LINESTRING(1 1,0 0) (2 rows) -- Dans les versions antérieures à 2.0, ceci retournait vrai -- SELECT ST_GeomFromText('POINT(1707296.37 4820536.77)') = ST_GeomFromText('POINT(1707296.27 4820536.87)') As pt_intersect ; --pt_intersect -- f
>> — Renvoie TRUE
si la boîte de délimitation de A est strictement à droite de celle de B.
boolean >>(
geometry A , geometry B )
;
L'opérateur >>
renvoie TRUE
si la boîte de délimitation de la géométrie A est strictement à droite de la boîte de délimitation de la géométrie B.
![]() | |
Cette opérande utilisera tous les index qui peuvent être disponibles sur les géométries. |
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)
@ — Renvoie TRUE
si la boîte de délimitation de A est contenue par celle de B.
boolean @(
geometry A , geometry B )
;
L'opérateur @
renvoie TRUE
si la boîte de délimitation de la géométrie A est complètement contenue par la boîte de délimitation de la géométrie B.
![]() | |
Cette opérande utilisera tous les index qui peuvent être disponibles sur les géométries. |
SELECT tbl1.column1, tbl2.column1, tbl1.column2 @ tbl2.column2 AS contained FROM ( VALUES (1, 'LINESTRING (1 1, 3 3)'::geometry)) AS tbl1, ( VALUES (2, 'LINESTRING (0 0, 4 4)'::geometry), (3, 'LINESTRING (2 2, 4 4)'::geometry), (4, 'LINESTRING (1 1, 3 3)'::geometry)) AS tbl2 ; column1 | column1 | contained ---------+---------+----------- 1 | 2 | t 1 | 3 | f 1 | 4 | t (3 rows)
@(geometry,box2df) — Renvoie TRUE
si la boîte de délimitation 2D d'une géométrie est contenue dans une boîte de délimitation 2D à précision flottante (BOX2DF).
boolean @(
geometry A , box2df B )
;
L'opérateur @
renvoie TRUE
si la boîte de délimitation 2D de la géométrie A est contenue dans la boîte de délimitation 2D B, en utilisant la précision float. Cela signifie que si B est un box2d (double précision), il sera converti en interne en une boîte de délimitation 2D de précision flottante (BOX2DF)
![]() | |
Cet opérande est destiné à être utilisé en interne par les index BRIN, plus que par les utilisateurs. |
Disponibilité : 2.3.0 le support des Block Range INdexes (BRIN) a été introduit. Nécessite PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
@(box2df,geometry) — Renvoie TRUE
si une boîte de délimitation de précision flottante 2D (BOX2DF) est contenue dans la boîte de délimitation 2D d'une géométrie.
boolean @(
box2df A , geometry B )
;
L'opérateur @
renvoie TRUE
si la boîte de délimitation 2D A est contenue dans la boîte de délimitation 2D de la géométrie B, en utilisant la précision float. Cela signifie que si B est un box2d (double précision), il sera converti en interne en une boîte de délimitation 2D de précision flottante (BOX2DF)
![]() | |
Cet opérande est destiné à être utilisé en interne par les index BRIN, plus que par les utilisateurs. |
Disponibilité : 2.3.0 le support des Block Range INdexes (BRIN) a été introduit. Nécessite PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
@(box2df,box2df) — Renvoie TRUE
si une boîte de délimitation de précision flottante 2D (BOX2DF) est contenue dans une autre boîte de délimitation de précision flottante 2D.
boolean @(
box2df A , box2df B )
;
L'opérateur @
renvoie TRUE
si la boîte de délimitation 2D A est contenue dans la boîte de délimitation 2D B, en utilisant la précision float. Cela signifie que si A (ou B) est un box2d (double précision), il sera converti en interne en une boîte de délimitation 2D à précision flottante (BOX2DF)
![]() | |
Cet opérande est destiné à être utilisé en interne par les index BRIN, plus que par les utilisateurs. |
Disponibilité : 2.3.0 le support des Block Range INdexes (BRIN) a été introduit. Nécessite PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
|&> — Renvoie TRUE
si la boîte de délimitation de A chevauche ou est au-dessus de celle de B.
boolean |&>(
geometry A , geometry B )
;
L'opérateur |&>
renvoie TRUE
si la boîte de délimitation de la géométrie A chevauche ou est au-dessus de la boîte de délimitation de la géométrie B, ou plus exactement, chevauche ou n'est PAS au-dessous de la boîte de délimitation de la géométrie B.
![]() | |
Cette opérande utilisera tous les index qui peuvent être disponibles sur les géométries. |
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)
|>> — Renvoie TRUE
si la boîte de délimitation de A est strictement au-dessus de celle de B.
boolean |>>(
geometry A , geometry B )
;
L'opérateur |>>
renvoie TRUE
si la boîte de délimitation de la géométrie A est strictement au-dessus de la boîte de délimitation de la géométrie B.
![]() | |
Cette opérande utilisera tous les index qui peuvent être disponibles sur les géométries. |
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)
~ — Renvoie TRUE
si la boîte de délimitation de A contient celle de B.
boolean ~(
geometry A , geometry B )
;
L'opérateur ~
renvoie TRUE
si la boîte de délimitation de la géométrie A contient complètement la boîte de délimitation de la géométrie B.
![]() | |
Cette opérande utilisera tous les index qui peuvent être disponibles sur les géométries. |
SELECT tbl1.column1, tbl2.column1, tbl1.column2 ~ tbl2.column2 AS contains FROM ( VALUES (1, 'LINESTRING (0 0, 3 3)'::geometry)) AS tbl1, ( VALUES (2, 'LINESTRING (0 0, 4 4)'::geometry), (3, 'LINESTRING (1 1, 2 2)'::geometry), (4, 'LINESTRING (0 0, 3 3)'::geometry)) AS tbl2 ; column1 | column1 | contains ---------+---------+---------- 1 | 2 | f 1 | 3 | t 1 | 4 | t (3 rows)
~(geometry,box2df) — Renvoie TRUE
si la boîte de délimitation 2D d'une géométrie contient une boîte de délimitation de précision flottante 2D (GIDX).
boolean ~(
geometry A , box2df B )
;
L'opérateur ~
renvoie TRUE
si la boîte de délimitation 2D d'une géométrie A contient la boîte de délimitation 2D B, en utilisant la précision float. Cela signifie que si B est un box2d (double précision), il sera converti en interne en une boîte de délimitation 2D de précision flottante (BOX2DF)
![]() | |
Cet opérande est destiné à être utilisé en interne par les index BRIN, plus que par les utilisateurs. |
Disponibilité : 2.3.0 le support des Block Range INdexes (BRIN) a été introduit. Nécessite PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
~(box2df,geometry) — Renvoie TRUE
si une boîte de délimitation de précision flottante 2D (BOX2DF) contient la boîte de délimitation 2D d'une géométrie.
boolean ~(
box2df A , geometry B )
;
L'opérateur ~
renvoie TRUE
si la boîte de délimitation 2D A contient la boîte de délimitation de la géométrie B, en utilisant la précision float. Cela signifie que si A est un box2d (double précision), il sera converti en interne en une boîte de délimitation 2D de précision flottante (BOX2DF)
![]() | |
Cet opérande est destiné à être utilisé en interne par les index BRIN, plus que par les utilisateurs. |
Disponibilité : 2.3.0 le support des Block Range INdexes (BRIN) a été introduit. Nécessite PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
~(box2df,box2df) — Renvoie TRUE
si une boîte de délimitation de précision flottante 2D (BOX2DF) contient une autre boîte de délimitation de précision flottante 2D (BOX2DF).
boolean ~(
box2df A , box2df B )
;
L'opérateur ~
renvoie TRUE
si la boîte de délimitation 2D A contient la boîte de délimitation 2D B, en utilisant la précision float. Cela signifie que si A est un box2d (double précision), il sera converti en interne en une boîte de délimitation 2D de précision flottante (BOX2DF)
![]() | |
Cet opérande est destiné à être utilisé en interne par les index BRIN, plus que par les utilisateurs. |
Disponibilité : 2.3.0 le support des Block Range INdexes (BRIN) a été introduit. Nécessite PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
~= — Renvoie TRUE
si la boîte de délimitation de A est la même que celle de B.
boolean ~=(
geometry A , geometry B )
;
L'opérateur ~=
renvoie TRUE
si la boîte de délimitation de la géométrie/géographie A est la même que la boîte de délimitation de la géométrie/géographie B.
![]() | |
Cette opérande utilisera tous les index qui peuvent être disponibles sur les géométries. |
Disponibilité : 1.5.0 comportement changé
This function supports Polyhedral surfaces.
![]() | |
Cet opérateur a changé de comportement dans PostGIS 1.5, passant de la vérification de l'égalité géométrique réelle à la vérification de l'égalité du rectangle de délimitation. Pour compliquer les choses, le comportement de votre base de données dépend également du type de mise à niveau (hard ou soft) que vous avez effectué. Pour savoir quel est le comportement de votre base de données, vous pouvez exécuter la requête ci-dessous. Pour vérifier l'égalité réelle, utilisez ST_OrderingEquals ou ST_Equals. |
<-> — Renvoie la distance en 2D entre A et B.
double precision <->(
geometry A , geometry B )
;
double precision <->(
geography A , geography B )
;
L'opérateur <->
renvoie la distance 2D entre deux géométries. Utilisé dans la clause "ORDER BY" fournit des ensembles de résultats de plus proches voisins assistés par index. Pour PostgreSQL inférieur à 9.5, donne uniquement la distance centroïde des boîtes englobantes et pour PostgreSQL 9.5+, fait une vraie recherche de distance KNN donnant la vraie distance entre les géométries, et la sphère de distance pour les géographies.
![]() | |
Cet opérande utilise les index 2D GiST qui peuvent être disponibles sur les géométries. Il est différent des autres opérateurs qui utilisent des index spatiaux en ce sens que l'index spatial n'est utilisé que lorsque l'opérateur est dans la clause ORDER BY. |
![]() | |
L'index n'intervient que si l'une des géométries est une constante (pas dans une sous-requête/cte). Par exemple, 'SRID=3005;POINT(1011102 450541)'::geometry au lieu de a.geom |
Reportez-vous à l'atelier PostGIS : La recherche du plus proche voisin pour un exemple détaillé.
Amélioré : 2.2.0 -- Comportement KNN ("K nearest neighbor") réel pour la géométrie et la géographie pour PostgreSQL 9.5+. Note : pour la géographie, KNN est basé sur la sphère plutôt que sur le sphéroïde. Pour PostgreSQL 9.4 et moins, le support de la géographie est nouveau mais ne supporte que le centroïde de la boîte de délimitation.
Modifié : 2.2.0 -- Pour les utilisateurs de PostgreSQL 9.5, l'ancienne syntaxe Hybrid peut être plus lente, donc vous voudrez vous débarrasser de ce hack si vous exécutez votre code uniquement sur PostGIS 2.2+ 9.5+. Voir les exemples ci-dessous.
Disponibilité : 2.0.0 -- Le KNN fournit des voisins les plus proches basés sur les distances entre les centroïdes géométriques au lieu des distances réelles. Résultats exacts pour les points, inexacts pour tous les autres types. Disponible pour PostgreSQL 9.1+
SELECT ST_Distance(geom, 'SRID=3005;POINT(1011102 450541)'::geometry) as d,edabbr, vaabbr FROM va2005 ORDER BY d limit 10 ; d | edabbr | vaabbr ------------------+--------+-------- 0 | ALQ | 128 5541.57712511724 | ALQ | 129A 5579.67450712005 | ALQ | 001 6083.4207708641 | ALQ | 131 7691.2205404848 | ALQ | 003 7900.75451037313 | ALQ | 122 8694.20710669982 | ALQ | 129B 9564.24289057111 | ALQ | 130 12089.665931705 | ALQ | 127 18472.5531479404 | ALQ | 002 (10 rows)
Puis la réponse brute KNN :
SELECT st_distance(geom, 'SRID=3005;POINT(1011102 450541)'::geometry) as d,edabbr, vaabbr FROM va2005 ORDER BY geom <-> 'SRID=3005;POINT(1011102 450541)'::geometry limit 10 ; d | edabbr | vaabbr ------------------+--------+-------- 0 | ALQ | 128 5541.57712511724 | ALQ | 129A 5579.67450712005 | ALQ | 001 6083.4207708641 | ALQ | 131 7691.2205404848 | ALQ | 003 7900.75451037313 | ALQ | 122 8694.20710669982 | ALQ | 129B 9564.24289057111 | ALQ | 130 12089.665931705 | ALQ | 127 18472.5531479404 | ALQ | 002 (10 rows)
Si vous exécutez "EXPLAIN ANALYZE" sur les deux requêtes, vous constaterez une amélioration des performances pour la seconde.
Pour les utilisateurs utilisant PostgreSQL < 9.5, utilisez une requête hybride pour trouver les vrais plus proches voisins. D'abord une requête CTE utilisant le KNN assisté par index, puis une requête exacte pour obtenir l'ordre correct :
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)
|=| — Renvoie la distance entre les trajectoires A et B à leur point d'approche le plus proche.
double precision |=|(
geometry A , geometry B )
;
L'opérateur |=|
renvoie la distance 3D entre deux trajectoires (Voir ST_IsValidTrajectory). C'est la même chose que ST_DistanceCPA mais en tant qu'opérateur, il peut être utilisé pour effectuer des recherches du plus proche voisin en utilisant un index à N dimensions (nécessite PostgreSQL 9.5.0 ou plus).
![]() | |
Cet opérande utilisera les index ND GiST qui peuvent être disponibles sur les géométries. Il est différent des autres opérateurs qui utilisent des index spatiaux en ce sens que l'index spatial n'est utilisé que lorsque l'opérateur est dans la clause ORDER BY. |
![]() | |
L'index n'intervient que si l'une des géométries est une constante (pas dans une sous-requête/cte). Par exemple, 'SRID=3005;LINESTRINGM(0 0 0,0 0 1)'::geometry au lieu de a.geom |
Disponibilité : 2.2.0. La prise en charge des index est disponible uniquement pour PostgreSQL 9.5+
-- Enregistrer une trajectoire de requête littérale dans une variable psql... \set qt 'ST_AddMeasure(ST_MakeLine(ST_MakePointM(-350,300,0),ST_MakePointM(-410,490,0)),10,20)' -- Exécuter la requête ! 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)
<#> — Renvoie la distance 2D entre les boîtes de délimitation A et B.
double precision <#>(
geometry A , geometry B )
;
L'opérateur <#>
renvoie la distance entre deux boîtes de délimitation en virgule flottante, en les lisant éventuellement à partir d'un index spatial (PostgreSQL 9.1+ requis). Utile pour effectuer un ordonnancement par distance du plus proche voisin approximate.
![]() | |
Cet opérande utilisera tous les index qui peuvent être disponibles sur les géométries. Il est différent des autres opérateurs qui utilisent des index spatiaux en ce sens que l'index spatial n'est utilisé que lorsque l'opérateur est dans la clause ORDER BY. |
![]() | |
L'index n'intervient que si l'une des géométries est une constante, par exemple ORDER BY (ST_GeomFromText('POINT(1 2)') <#> geom) au lieu de g1.geom <#>. |
Disponibilité : 2.0.0 -- KNN disponible uniquement pour PostgreSQL 9.1+
SELECT * FROM ( SELECT b.tlid, b.mtfcc, b.geom <# > ST_GeomFromText('LINESTRING(746149 2948672,745954 2948576, 745787 2948499,745740 2948468,745712 2948438, 745690 2948384,745677 2948319)',2249) As b_dist, ST_Distance(b.geom, ST_GeomFromText('LINESTRING(746149 2948672,745954 2948576, 745787 2948499,745740 2948468,745712 2948438, 745690 2948384,745677 2948319)',2249)) As act_dist FROM bos_roads As b ORDER BY b_dist, b.tlid LIMIT 100) As foo ORDER BY act_dist, tlid LIMIT 10 ; tlid | mtfcc | b_dist | act_dist -----------+-------+------------------+------------------ 85732027 | S1400 | 0 | 0 85732029 | S1400 | 0 | 0 85732031 | S1400 | 0 | 0 85734335 | S1400 | 0 | 0 85736037 | S1400 | 0 | 0 624683742 | S1400 | 0 | 128.528874268666 85719343 | S1400 | 260.839270432962 | 260.839270432962 85741826 | S1400 | 164.759294123275 | 260.839270432962 85732032 | S1400 | 277.75 | 311.830282365264 85735592 | S1400 | 222.25 | 311.830282365264 (10 rows)
<<->> — Renvoie la distance n-D entre les centroïdes des boîtes de délimitation A et B.
double precision <<->>(
geometry A , geometry B )
;
L'opérateur <<->>
renvoie la distance n-D (euclidienne) entre les centroïdes des boîtes englobantes de deux géométries. Utile pour effectuer le classement par distance du plus proche voisin approximate.
![]() | |
Cet opérande utilise les index GiST n-D qui peuvent être disponibles sur les géométries. Il est différent des autres opérateurs qui utilisent des index spatiaux en ce sens que l'index spatial n'est utilisé que lorsque l'opérateur est dans la clause ORDER BY. |
![]() | |
L'index n'intervient que si l'une des géométries est une constante (pas dans une sous-requête/cte). Par exemple, 'SRID=3005;POINT(1011102 450541)'::geometry au lieu de a.geom |
Disponibilité : 2.2.0 -- KNN disponible uniquement pour PostgreSQL 9.1+.
<<#>> — Renvoie la distance n-D entre les boîtes de délimitation A et B.
double precision <<#>>(
geometry A , geometry B )
;
L'opérateur <<#>>
renvoie la distance entre deux boîtes de délimitation en virgule flottante, en les lisant éventuellement à partir d'un index spatial (PostgreSQL 9.1+ requis). Utile pour effectuer un classement par distance du plus proche voisin approximate.
![]() | |
Cet opérande utilisera tous les index qui peuvent être disponibles sur les géométries. Il est différent des autres opérateurs qui utilisent des index spatiaux en ce sens que l'index spatial n'est utilisé que lorsque l'opérateur est dans la clause ORDER BY. |
![]() | |
L'index n'intervient que si l'une des géométries est une constante, par exemple ORDER BY (ST_GeomFromText('POINT(1 2)') <<#>> geom) au lieu de g1.geom <<#>>. |
Disponibilité : 2.2.0 -- KNN disponible uniquement pour PostgreSQL 9.1+.
ST_3DIntersects — Tests if two geometries spatially intersect in 3D - only for points, linestrings, polygons, polyhedral surface (area)
boolean ST_3DIntersects(
geometry geomA , geometry geomB )
;
Overlaps, Touches, Within all imply spatial intersection. If any of the aforementioned returns true, then the geometries also spatially intersect. Disjoint implies false for spatial intersection.
![]() | |
This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available on the geometries. |
Changed: 3.0.0 SFCGAL backend removed, GEOS backend supports TINs.
Disponibilité : 2.0.0
This function supports 3d and will not drop the z-index.
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 5.1
SELECT ST_3DIntersects(pt, line), ST_Intersects(pt, line) FROM (SELECT 'POINT(0 0 2)'::geometry As pt, 'LINESTRING (0 0 1, 0 2 3)'::geometry As line) As foo; st_3dintersects | st_intersects -----------------+--------------- f | t (1 row)
ST_Contains — Tests if every point of B lies in A, and their interiors have a point in common
boolean ST_Contains(
geometry geomA, geometry geomB)
;
Returns TRUE if geometry A contains geometry B. A contains B if and only if all points of B lie inside (i.e. in the interior or boundary of) A (or equivalently, no points of B lie in the exterior of A), and the interiors of A and B have at least one point in common.
The contains relationship is reflexive: every geometry contains itself. (In contrast, in the ST_ContainsProperly predicate a geometry does not properly contain itself.) The relationship is antisymmetric: if ST_Contains(A,B) = true
and ST_Contains(B,A) = true
, then the two geometries must be topologically equal (ST_Equals(A,B) = true
).
ST_Contains is the converse of ST_Within. So, ST_Contains(A,B) = ST_Within(B,A)
.
![]() | |
Because the interiors must have a common point, a subtlety of the definition is that polygons and lines do not contain lines and points lying fully in their boundary. For further details see Subtleties of OGC Covers, Contains, Within. The ST_Covers predicate provides a more inclusive relationship. |
![]() | |
This function automatically includes a bounding box comparison
that makes use of any spatial indexes that are available on the geometries. To avoid index use, use the function |
Effectué par le module GEOS
Enhanced: 2.3.0 Enhancement to PIP short-circuit extended to support MultiPoints with few points. Prior versions only supported point in polygon.
![]() | |
Enhanced: 3.0.0 enabled support for |
![]() | |
Do not use this function with invalid geometries. You will get unexpected results. |
NOTE: this is the "allowable" version that returns a boolean, not an integer.
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s2.1.1.2 // s2.1.13.3 - same as within(geometry B, geometry A)
This method implements the SQL/MM specification. SQL-MM 3: 5.1.31
ST_Contains
returns TRUE
in the following situations:
![]()
| ![]()
|
![]()
| ![]()
|
ST_Contains
returns FALSE
in the following situations:
![]()
| ![]()
|
Due to the interior intersection condition ST_Contains
returns FALSE
in the following situations (whereas ST_Covers
returns TRUE
):
![]()
| ![]()
|
-- A circle within a circle SELECT ST_Contains(smallc, bigc) As smallcontainsbig, ST_Contains(bigc,smallc) As bigcontainssmall, ST_Contains(bigc, ST_Union(smallc, bigc)) as bigcontainsunion, ST_Equals(bigc, ST_Union(smallc, bigc)) as bigisunion, ST_Covers(bigc, ST_ExteriorRing(bigc)) As bigcoversexterior, ST_Contains(bigc, ST_ExteriorRing(bigc)) As bigcontainsexterior FROM (SELECT ST_Buffer(ST_GeomFromText('POINT(1 2)'), 10) As smallc, ST_Buffer(ST_GeomFromText('POINT(1 2)'), 20) As bigc) As foo; -- Result smallcontainsbig | bigcontainssmall | bigcontainsunion | bigisunion | bigcoversexterior | bigcontainsexterior ------------------+------------------+------------------+------------+-------------------+--------------------- f | t | t | t | t | f -- Example demonstrating difference between contains and contains properly SELECT ST_GeometryType(geomA) As geomtype, ST_Contains(geomA,geomA) AS acontainsa, ST_ContainsProperly(geomA, geomA) AS acontainspropa, ST_Contains(geomA, ST_Boundary(geomA)) As acontainsba, ST_ContainsProperly(geomA, ST_Boundary(geomA)) As acontainspropba FROM (VALUES ( ST_Buffer(ST_Point(1,1), 5,1) ), ( ST_MakeLine(ST_Point(1,1), ST_Point(-1,-1) ) ), ( ST_Point(1,1) ) ) As foo(geomA); geomtype | acontainsa | acontainspropa | acontainsba | acontainspropba --------------+------------+----------------+-------------+----------------- ST_Polygon | t | f | f | f ST_LineString | t | f | f | f ST_Point | t | t | f | f
ST_ContainsProperly — Tests if every point of B lies in the interior of A
boolean ST_ContainsProperly(
geometry geomA, geometry geomB)
;
Returns true
if every point of B lies inside A (or equivalently, no point of B lies in the the boundary or exterior of A).
A does not properly contain itself, but does contain itself.
Every point of the other geometry is a point of this geometry's interior. The DE-9IM Intersection Matrix for the two geometries matches [T**FF*FF*] used in ST_Relate
A use for this predicate is computing the intersections of a set of geometries with a large polygonal geometry. Since intersection is a fairly slow operation, it can be more efficient to use containsProperly to filter out test geometries which lie fully inside the area. In these cases the intersection is known a priori to be exactly the original test geometry.
![]() | |
This function automatically includes a bounding box comparison
that makes use of any spatial indexes that are available on the geometries. To avoid index use, use the function |
![]() | |
The advantage of this predicate over ST_Contains and ST_Intersects is that it can be computed more efficiently, with no need to compute topology at individual points. |
Effectué par le module GEOS.
Disponibilité : 1.4.0
![]() | |
Enhanced: 3.0.0 enabled support for |
![]() | |
Do not use this function with invalid geometries. You will get unexpected results. |
--a circle within a circle SELECT ST_ContainsProperly(smallc, bigc) As smallcontainspropbig, ST_ContainsProperly(bigc,smallc) As bigcontainspropsmall, ST_ContainsProperly(bigc, ST_Union(smallc, bigc)) as bigcontainspropunion, ST_Equals(bigc, ST_Union(smallc, bigc)) as bigisunion, ST_Covers(bigc, ST_ExteriorRing(bigc)) As bigcoversexterior, ST_ContainsProperly(bigc, ST_ExteriorRing(bigc)) As bigcontainsexterior FROM (SELECT ST_Buffer(ST_GeomFromText('POINT(1 2)'), 10) As smallc, ST_Buffer(ST_GeomFromText('POINT(1 2)'), 20) As bigc) As foo; --Result smallcontainspropbig | bigcontainspropsmall | bigcontainspropunion | bigisunion | bigcoversexterior | bigcontainsexterior ------------------+------------------+------------------+------------+-------------------+--------------------- f | t | f | t | t | f --example demonstrating difference between contains and contains properly SELECT ST_GeometryType(geomA) As geomtype, ST_Contains(geomA,geomA) AS acontainsa, ST_ContainsProperly(geomA, geomA) AS acontainspropa, ST_Contains(geomA, ST_Boundary(geomA)) As acontainsba, ST_ContainsProperly(geomA, ST_Boundary(geomA)) As acontainspropba FROM (VALUES ( ST_Buffer(ST_Point(1,1), 5,1) ), ( ST_MakeLine(ST_Point(1,1), ST_Point(-1,-1) ) ), ( ST_Point(1,1) ) ) As foo(geomA); geomtype | acontainsa | acontainspropa | acontainsba | acontainspropba --------------+------------+----------------+-------------+----------------- ST_Polygon | t | f | f | f ST_LineString | t | f | f | f ST_Point | t | t | f | f
ST_GeometryType, ST_Boundary, ST_Contains, ST_Covers, ST_CoveredBy, ST_Equals, ST_Relate, ST_Within
ST_CoveredBy — Tests if every point of A lies in B
boolean ST_CoveredBy(
geometry geomA, geometry geomB)
;
boolean ST_CoveredBy(
geography geogA, geography geogB)
;
Returns true
if every point in Geometry/Geography A lies inside (i.e. intersects the interior or boundary of) Geometry/Geography B. Equivalently, tests that no point of A lies outside (in the exterior of) B.
ST_CoveredBy is the converse of ST_Covers. So, ST_CoveredBy(A,B) = ST_Covers(B,A)
.
Generally this function should be used instead of ST_Within, since it has a simpler definition which does not have the quirk that "boundaries are not within their geometry".
![]() | |
This function automatically includes a bounding box comparison
that makes use of any spatial indexes that are available on the geometries. To avoid index use, use the function |
![]() | |
Enhanced: 3.0.0 enabled support for |
![]() | |
Do not use this function with invalid geometries. You will get unexpected results. |
Effectué par le module GEOS
Disponibilité : 1.2.2
NOTE: this is the "allowable" version that returns a boolean, not an integer.
Not an OGC standard, but Oracle has it too.
--a circle coveredby a circle SELECT ST_CoveredBy(smallc,smallc) As smallinsmall, ST_CoveredBy(smallc, bigc) As smallcoveredbybig, ST_CoveredBy(ST_ExteriorRing(bigc), bigc) As exteriorcoveredbybig, ST_Within(ST_ExteriorRing(bigc),bigc) As exeriorwithinbig FROM (SELECT ST_Buffer(ST_GeomFromText('POINT(1 2)'), 10) As smallc, ST_Buffer(ST_GeomFromText('POINT(1 2)'), 20) As bigc) As foo; --Result smallinsmall | smallcoveredbybig | exteriorcoveredbybig | exeriorwithinbig --------------+-------------------+----------------------+------------------ t | t | t | f (1 row)
ST_Covers — Tests if every point of B lies in A
boolean ST_Covers(
geometry geomA, geometry geomB)
;
boolean ST_Covers(
geography geogpolyA, geography geogpointB)
;
Returns true
if every point in Geometry/Geography B lies inside (i.e. intersects the interior or boundary of) Geometry/Geography A. Equivalently, tests that no point of B lies outside (in the exterior of) A.
ST_Covers is the converse of ST_CoveredBy. So, ST_Covers(A,B) = ST_CoveredBy(B,A)
.
Generally this function should be used instead of ST_Contains, since it has a simpler definition which does not have the quirk that "geometries do not contain their boundary".
![]() | |
This function automatically includes a bounding box comparison
that makes use of any spatial indexes that are available on the geometries. To avoid index use, use the function |
![]() | |
Enhanced: 3.0.0 enabled support for |
![]() | |
Do not use this function with invalid geometries. You will get unexpected results. |
Effectué par le module GEOS
Enhanced: 2.4.0 Support for polygon in polygon and line in polygon added for geography type
Enhanced: 2.3.0 Enhancement to PIP short-circuit for geometry extended to support MultiPoints with few points. Prior versions only supported point in polygon.
Disponibilité : 1.5 - le support de la geography a été introduit.
Disponibilité : 1.2.2
NOTE: this is the "allowable" version that returns a boolean, not an integer.
Not an OGC standard, but Oracle has it too.
Geometry example
--a circle covering a circle SELECT ST_Covers(smallc,smallc) As smallinsmall, ST_Covers(smallc, bigc) As smallcoversbig, ST_Covers(bigc, ST_ExteriorRing(bigc)) As bigcoversexterior, ST_Contains(bigc, ST_ExteriorRing(bigc)) As bigcontainsexterior FROM (SELECT ST_Buffer(ST_GeomFromText('POINT(1 2)'), 10) As smallc, ST_Buffer(ST_GeomFromText('POINT(1 2)'), 20) As bigc) As foo; --Result smallinsmall | smallcoversbig | bigcoversexterior | bigcontainsexterior --------------+----------------+-------------------+--------------------- t | f | t | f (1 row)
Geeography Example
-- a point with a 300 meter buffer compared to a point, a point and its 10 meter buffer SELECT ST_Covers(geog_poly, geog_pt) As poly_covers_pt, ST_Covers(ST_Buffer(geog_pt,10), geog_pt) As buff_10m_covers_cent FROM (SELECT ST_Buffer(ST_GeogFromText('SRID=4326;POINT(-99.327 31.4821)'), 300) As geog_poly, ST_GeogFromText('SRID=4326;POINT(-99.33 31.483)') As geog_pt ) As foo; poly_covers_pt | buff_10m_covers_cent ----------------+------------------ f | t
ST_Crosses — Tests if two geometries have some, but not all, interior points in common
boolean ST_Crosses(
geometry g1, geometry g2)
;
Compares two geometry objects and returns true
if their intersection "spatially cross", that is, the geometries have some, but not all interior points in common. The intersection of the interiors of the geometries must be non-empty and must have dimension less than the maximum dimension of the two input geometries. Additionally, the intersection of the two geometries must not equal either of the source geometries. Otherwise, it returns false
.
In mathematical terms, this is:
Geometries cross if their DE-9IM Intersection Matrix matches:
T*T******
for Point/Line, Point/Area, and Line/Area situations
T*****T**
for Line/Point, Area/Point, and Area/Line situations
0********
for Line/Line situations
For Point/Point and Area/Area situations this predicate returns false
.
The OpenGIS Simple Features Specification defines this predicate only for Point/Line, Point/Area, Line/Line, and Line/Area situations. JTS / GEOS extends the definition to apply to Line/Point, Area/Point and Area/Line situations as well. This makes the relation symmetric.
![]() | |
This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available on the geometries. |
![]() | |
Enhanced: 3.0.0 enabled support for |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s2.1.13.3
This method implements the SQL/MM specification. SQL-MM 3: 5.1.29
The following situations all return true
.
![]()
| ![]()
|
![]()
| ![]()
|
Consider a situation where a user has two tables: a table of roads and a table of highways.
CREATE TABLE roads ( id serial NOT NULL, geom geometry, CONSTRAINT roads_pkey PRIMARY KEY (road_id) );
|
CREATE TABLE highways ( id serial NOT NULL, the_gem geometry, CONSTRAINT roads_pkey PRIMARY KEY (road_id) );
|
To determine a list of roads that cross a highway, use a query similiar to:
SELECT roads.id FROM roads, highways WHERE ST_Crosses(roads.geom, highways.geom);
ST_Disjoint — Tests if two geometries have no points in common
boolean ST_Disjoint(
geometry A , geometry B )
;
Overlaps, Touches, Within all imply geometries are not spatially disjoint. If any of the aforementioned returns true, then the geometries are not spatially disjoint. Disjoint implies false for spatial intersection.
![]() | |
Enhanced: 3.0.0 enabled support for |
Effectué par le module GEOS
![]() | |
This function call does not use indexes. A negated ST_Intersects predicate can be used as a more performant alternative that uses indexes: |
![]() | |
NOTE: this is the "allowable" version that returns a boolean, not an integer. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s2.1.1.2 //s2.1.13.3 - a.Relate(b, 'FF*FF****')
This method implements the SQL/MM specification. SQL-MM 3: 5.1.26
ST_Equals — Tests if two geometries include the same set of points
boolean ST_Equals(
geometry A, geometry B)
;
Returns true
if the given geometries are "spatially equal". Use this for a 'better' answer than '='. Note by spatially equal we mean ST_Within(A,B) = true and ST_Within(B,A) = true and also mean ordering of points can be different but represent the same geometry structure. To verify the order of points is consistent, use ST_OrderingEquals (it must be noted ST_OrderingEquals is a little more stringent than simply verifying order of points are the same).
![]() | |
Enhanced: 3.0.0 enabled support for |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s2.1.1.2
This method implements the SQL/MM specification. SQL-MM 3: 5.1.24
Changed: 2.2.0 Returns true even for invalid geometries if they are binary equal
SELECT ST_Equals(ST_GeomFromText('LINESTRING(0 0, 10 10)'), ST_GeomFromText('LINESTRING(0 0, 5 5, 10 10)')); st_equals ----------- t (1 row) SELECT ST_Equals(ST_Reverse(ST_GeomFromText('LINESTRING(0 0, 10 10)')), ST_GeomFromText('LINESTRING(0 0, 5 5, 10 10)')); st_equals ----------- t (1 row)
ST_Intersects — Tests if two geometries intersect (they have at least one point in common)
boolean ST_Intersects(
geometry geomA , geometry geomB )
;
boolean ST_Intersects(
geography geogA , geography geogB )
;
Compares two geometries and returns true
if they intersect. Geometries intersect if they have any point in common.
For geography, a distance tolerance of 0.00001 meters is used (so points that are very close are considered to intersect).
Geometries intersect if their DE-9IM Intersection Matrix matches one of:
T********
*T*******
***T*****
****T****
Spatial intersection is implied by all the other spatial relationship tests, except ST_Disjoint, which tests that geometries do NOT intersect.
![]() | |
This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available on the geometries. |
Changed: 3.0.0 SFCGAL version removed and native support for 2D TINS added.
Enhanced: 2.5.0 Supports GEOMETRYCOLLECTION.
Enhanced: 2.3.0 Enhancement to PIP short-circuit extended to support MultiPoints with few points. Prior versions only supported point in polygon.
Performed by the GEOS module (for geometry), geography is native
Availability: 1.5 support for geography was introduced.
![]() | |
For geography, this function has a distance tolerance of about 0.00001 meters and uses the sphere rather than spheroid calculation. |
![]() | |
NOTE: this is the "allowable" version that returns a boolean, not an integer. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s2.1.1.2 //s2.1.13.3 - ST_Intersects(g1, g2 ) --> Not (ST_Disjoint(g1, g2 ))
This method implements the SQL/MM specification. SQL-MM 3: 5.1.27
This method supports Circular Strings and Curves
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
SELECT ST_Intersects('POINT(0 0)'::geometry, 'LINESTRING ( 2 0, 0 2 )'::geometry); st_intersects --------------- f (1 row) SELECT ST_Intersects('POINT(0 0)'::geometry, 'LINESTRING ( 0 0, 0 2 )'::geometry); st_intersects --------------- t (1 row) -- Look up in table. Make sure table has a GiST index on geometry column for faster lookup. SELECT id, name FROM cities WHERE ST_Intersects(geom, 'SRID=4326;POLYGON((28 53,27.707 52.293,27 52,26.293 52.293,26 53,26.293 53.707,27 54,27.707 53.707,28 53))'); id | name ----+------- 2 | Minsk (1 row)