PostGIS es una extension del sistema de base de datos relacional PostgreSQL que permite almacenar objetos SIG (Sistemas de Información Geografica) en la base de datos. PostGIS incluye soporte de indices de tipos basados en GiST R-Tree, y funciones de análisis y procesado de objetos SIG.
Este es el manual 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 is a spatial extension for the PostgreSQL relational database that was created by Refractions Research Inc, as a spatial database technology research project. Refractions is a GIS and database consulting company in Victoria, British Columbia, Canada, specializing in data integration and custom software development.
PostGIS is now a project of the OSGeo Foundation and is developed and funded by many FOSS4G developers and organizations all over the world that gain great benefit from its functionality and versatility.
The PostGIS project development group plans on supporting and enhancing PostGIS to better support a range of important GIS functionality in the areas of OGC and SQL/MM spatial standards, advanced topological constructs (coverages, surfaces, networks), data source for desktop user interface tools for viewing and editing GIS data, and web-based access tools.
El Comité de Dirección del Proyecto PostGIS (PSC por sus siglas en Ingles, Project Steering Committee) coordina la dirección general, ciclos de publicación,documentación, y el alcance de los esfuerzos para el proyecto PostGIS. Ademas el PSC da soporte general a usuarios, acepta y aprueba los parches de la comunidad general de PostGIS y vota sobre diversos asuntos relacionados con PostGIS como el acceso de nuevos desarrolladores, los nuevos miembros del PSC o cambios importantes en el API.
MVT support, Bug fixing, Performance and stability improvements, GitHub curation, alignment of PostGIS with PostgreSQL releases
Buildbot Maintenance, Windows production and experimental builds, documentation, alignment of PostGIS with PostgreSQL releases, X3D support, TIGER geocoder support, management functions.
Index improvements, bug fixing and geometry/geography function improvements, SFCGAL, raster, GitHub curation, and bot maintenance.
Co-founder of PostGIS project. General bug fixing, geography support, geography and geometry index support (2D, 3D, nD index and anything spatial index), underlying geometry internal structures, GEOS functionality integration and alignment with GEOS releases, alignment of PostGIS with PostgreSQL releases, loader/dumper, and Shapefile GUI loader.
Bug fixes and maintenance, buildbot maintenance, git mirror management, management functions, integration of new GEOS functionality and alignment with GEOS releases, topology support, and raster framework and low level API functions.
Distance function enhancements (including 3D distance and relationship functions) and additions, Tiny WKB (TWKB) output format and general user support
Geometry clustering function additions, other geometry algorithm enhancements, GEOS enhancements and general user support
GEOS enhancements and documentation
MapBox Vector Tile and GeoBuf functions. Gogs testing and GitLab experimentation.
Geometry Processing, PostgreSQL gist, general bug fixing
Prior PSC Member. Raster development, integration with GDAL, raster loader, user support, general bug fixing, testing on various OS (Slackware, Mac, Windows, and more)
Prior PSC Member. Coordinated bug fixing and maintenance effort, spatial index selectivity and binding, loader/dumper, and Shapefile GUI Loader, integration of new and new function enhancements.
Desarrollo raster, soporte del driver GDAL, cargador
Entrada y salida XML (KML,GML)/Funciones GeoJSON, soporte 3D y corrección de errores.
Anterior miembro del PSC. Desarrollo en general, mantenimiento del sitio web y buildbot, gestor de la incubación en el OSGeo
CMake support for PostGIS, built original raster loader in python and low level raster API functions
Prior PSC Member. Documentation and documentation support tools, buildbot maintenance, advanced user support on PostGIS newsgroup, and PostGIS maintenance function enhancements.
El desarrollado/Cofundador de PostGIS original. Dave escribió el código de los objetos del lado del servidor, enlaces de los indices y muchas otras funciones analíticas del lado del servidor.
Desarrollo original del cargador/descargador de ficheros Shape. Es el propietario representativo actual del proyecto PostGIS.
Mantenimiento y desarrollo de funciones básicas. Soporte de la curva de mejora. Cargador de Shapefiles.
Architect of PostGIS raster implementation. Raster overall architecture, prototyping, programming support
Raster development (mostly map algebra analytic functions)
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 Zwarg | Loïc Bartoletti | Stepan Kuzmin |
David Zwarg | Loic Dachary | Stephen Frost |
David Zwarg | 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 |
Estas son compañías que han contribuido con tiempo de desarrollo, alojamiento o con aportes de capital económico al proyecto PostGIS
Crowd funding campaigns are campaigns we run to get badly wanted features funded that can service a large number of people. Each campaign is specifically focused on a particular feature or set of features. Each sponsor chips in a small fraction of the needed funding and with enough people/organizations contributing, we have the funds to pay for the work that will help many. If you have an idea for a feature you think many others would be willing to co-fund, please post to the PostGIS newsgroup your thoughts and together we can make it happen.
PostGIS 2.0.0 fue la primer version en la que utilizamos esta estrategia. Utilizamos PledgeBank y hemos tenido dos campañas con éxito para realizarlas.
postgistopology - 10 patrocinadores contribuyeron con $ 250 USD cada uno para construir la función toTopoGeometry y con este apoyo, topología 2.0.0. Sucedió.
postgistopology - 10 patrocinadores contribuyeron con $ 250 USD cada uno para construir la función toTopoGeometry y con este apoyo, topología 2.0.0. Sucedió.
The GEOS geometry operations library
The GDAL Geospatial Data Abstraction Library used to power much of the raster functionality introduced in PostGIS 2. In kind, improvements needed in GDAL to support PostGIS are contributed back to the GDAL project.
The PROJ cartographic projection library
Por ultimo pero no menos importante, PostgreSQL DBMS, El Gigante sobre el que se apoya PostGIS. Gran parte de la velocidad y la flexibilidad de PostGIS no sería viable sin la extensibilidad, gran planeador de consultas, el índice de GIST, y gran cantidad de funciones SQL que ofrece PostgreSQL.
En este capítulo se detallan los pasos necesarios para instalar PostGIS .
Para compilar asumiendo que tiene todas las dependencias en su ruta de búsqueda:
tar xvfz postgis-3.4.0dev.tar.gz cd postgis-3.4.0dev ./configure make make install
Una vez que se instala PostGIS, es necesario habilitarlo en cada base de datos en la que desee utilizarlo.
![]() | |
Muchos Sistemas Operativos incluyen ya paquetes precompilados PostgreSQL/PostGIS. En la mayoría de casos no es necesario compilar salvo si quieres las ultimas versiones o haces mantenimiento de paquetes. This section includes general compilation instructions, if you are compiling for Windows etc or another OS, you may find additional more detailed help at PostGIS User contributed compile guides and PostGIS Dev Wiki. Pre-Built Packages for various OS are listed in PostGIS Pre-built Packages Si eres usuario de Windows, puedes obtener versiones estables compiladas via Stackbuilder o el sitio de descargas de PostGIS para Windows También tenemos versiones experimentales para Windows que son publicadas normalmente una o dos veces por semana o cuando ocurre algo interesante. Puedes utilizar éstas para experimentar con las versiones de desarrollo de PostGIS |
The PostGIS module is an extension to the PostgreSQL backend server. As such, PostGIS 3.4.0dev requires full PostgreSQL server headers access in order to compile. It can be built against PostgreSQL versions 12 - 16. Earlier versions of PostgreSQL are not supported.
Refer to the PostgreSQL installation guides if you haven't already installed PostgreSQL. https://www.postgresql.org .
![]() | |
Para tener compatibilidad con las funcionalidades GEOS, cuando instales PostgreSQL necesitar hacer un enlace explícito con la librería estándar C++: LDFLAGS=-lstdc++ ./configure [PON TUS OPCIONES AQUÍ] Esta es una solución para falsas excepciones C++ con herramientas de desarrollo antiguas. Prueba este truco si experimentas problemas extraños (backend cerrado inesperadamente o cosas similares). Porc supuesto, será necesario volver a compilar PostgreSQL desde cero. |
Los siguientes pasos describen la configuración y compilación del código fuente de PostGIS. Están escritas para usuarios Linux y no funcionarán con Windows o Mac.
Retrieve the PostGIS source archive from the downloads website http://postgis.net/stuff/postgis-3.4.0dev.tar.gz
wget http://postgis.net/stuff/postgis-3.4.0dev.tar.gz tar -xvzf postgis-3.4.0dev.tar.gz cd postgis-3.4.0dev
Esto creara un directorio llamado postgis-3.4.0dev
en el directorio de trabajo actual.
De forma alternativa se puede obtener el código fuente del git repositorio https://git.osgeo.org/gitea/postgis/postgis/ .
git clone https://git.osgeo.org/gitea/postgis/postgis.git postgis cd postgis sh autogen.sh
Vaya al nuevo directorio postgis-3.4.0dev
creado para continuar con la instalación.
./configure
PostGIS tiene los siguientes requisitos para compilarlo y usarlo:
Requerido
PostgreSQL 12 - 16. A complete installation of PostgreSQL (including server headers) is required. PostgreSQL is available from http://www.postgresql.org .
For a full PostgreSQL / PostGIS support matrix and PostGIS/GEOS support matrix refer to https://trac.osgeo.org/postgis/wiki/UsersWikiPostgreSQLPostGIS
compilador GNU C (gcc
). Otros compiladores ANSI C pueden utilizarse para compilar PostGIS, pero encontraremos menos problemas al compilar con gcc
.
GNU Make (gmake
or make
). Para muchos sistemas , GNU make
es la versión por defecto de make. Para verificar la versión de make podemos ejecutar el siguiente comando make -v
. Otras versiones de make
pueden no procesar el fichero PostGIS Makefile
de forma correcta.
Proj reprojection library. Proj 6.1 or above is required. The Proj library is used to provide coordinate reprojection support within PostGIS. Proj is available for download from https://proj.org/ .
GEOS geometry library, version 3.6 or greater, but GEOS 3.11+ is required to take full advantage of all the new functions and features. GEOS is available for download from https://libgeos.org .
LibXML2, version 2.5.x or higher. LibXML2 is currently used in some imports functions (ST_GeomFromGML and ST_GeomFromKML). LibXML2 is available for download from https://gitlab.gnome.org/GNOME/libxml2/-/releases.
JSON-C, version 0.9 or higher. JSON-C is currently used to import GeoJSON via the function ST_GeomFromGeoJson. JSON-C is available for download from https://github.com/json-c/json-c/releases/.
GDAL, version 2+ is required 3+ is preferred. This is required for raster support. https://gdal.org/download.html.
If compiling with PostgreSQL+JIT, LLVM version >=6 is required https://trac.osgeo.org/postgis/ticket/4125.
Opcional
GDAL (pseudo optional) only if you don't want raster you can leave it out. Also make sure to enable the drivers you want to use as described in Section 3.2, “Configuring raster support”.
GTK (GTK+2.0, 2.8+ requerida) para compilar el cargador de shapefiles shp2pgsql-gui. http://www.gtk.org/ .
SFCGAL, version 1.3.1 (or higher), 1.4.1 or higher is recommended and required to be able to use all functionality. SFCGAL can be used to provide additional 2D and 3D advanced analysis functions to PostGIS cf Section 8.20, “SFCGAL Functions”. And also allow to use SFCGAL rather than GEOS for some 2D functions provided by both backends (like ST_Intersection or ST_Area, for instance). A PostgreSQL configuration variable postgis.backend
allow end user to control which backend he want to use if SFCGAL is installed (GEOS by default). Nota: SFCGAL 1.2 require at least CGAL 4.3 and Boost 1.54 (cf: https://oslandia.gitlab.io/SFCGAL/dev.html) https://gitlab.com/Oslandia/SFCGAL/.
In order to build the Section 14.1, “Normalizador de Direcciones” you will also need PCRE http://www.pcre.org (which generally is already installed on nix systems). Regex::Assemble
perl CPAN package is only needed if you want to rebuild the data encoded in parseaddress-stcities.h
. Section 14.1, “Normalizador de Direcciones” will automatically be built if it detects a PCRE library, or you pass in a valid --with-pcre-dir=/path/to/pcre
during configure.
To enable ST_AsMVT protobuf-c library 1.1.0 or higher (for usage) and the protoc-c compiler (for building) are required. Also, pkg-config is required to verify the correct minimum version of protobuf-c. See protobuf-c. By default, Postgis will use Wagyu to validate MVT polygons faster which requires a c++11 compiler. It will use CXXFLAGS and the same compiler as the PostgreSQL installation. To disable this and use GEOS instead use the --without-wagyu
during the configure step.
CUnit (CUnit
). Se necesita para hacer test de regresión. http://cunit.sourceforge.net/
DocBook (xsltproc
) es necesario para compilar la documentación. Docbook esta disponible en http://www.docbook.org/ .
DBLatex (dblatex
) necesario para construir la documentación en formato PDF. DBLatex esta disponible en http://dblatex.sourceforge.net/ .
ImageMagick (convert
) es necesario para generar las imágenes empleadas en la documentación. ImageMagick esta disponible en http://www.imagemagick.org/ .
Como en la gran mayoría de instalaciones Linux, el primer paso es generar el Makefile que se utilizara para compilar el código fuente. Esto se hace ejecutando el script de shell.
./configure
Sin parámetros adicionales, este comando intentara localizar los componentes y librerías necesarios para construir el código fuente PostGIS de forma automática en tu sistema. Aunque este es el uso mas común de ./configure, el script acepta varios parámetros para aquellos que han instalado las librerías y programas en lugares no standard.
La siguiente lista muestra los parámetros utilizados mas comunes. Para obtener una lista completa, puedes utilizar los parámetros --help o --help=short.
Starting with PostGIS 3.0, the library files generated by default will no longer have the minor version as part of the file name. This means all PostGIS 3 libs will end in postgis-3
. This was done to make pg_upgrade easier, with downside that you can only install one version PostGIS 3 series in your server. To get the old behavior of file including the minor version: e.g. postgis-3.0
add this switch to your configure statement.
Esta es la localización donde se instalaran las librerías PostGIS y los scripts SQL. Por defecto, esta localización es la misma que la detectada para la instalación PostgreSQL.
![]() | |
Este parámetro está roto actualmente, ya que el paquete sólo se instalará en el directorio de instalación de PostgreSQL. Para seguir avence de este bug visita http://trac.osgeo.org/postgis/ticket/635 |
PostgreSQL tiene una herramienta llamada pg_config para activar extensiones como PostGIS o para localizar el directorio de instalación de PostgreSQL. Utiliza este parámetro (--with-pgconfig=/path/to/pg_config) para especificar una instalación personalizada de PostgreSQL de forma manual que PostGIS utilizara para compilar.
GDAL, una biblioteca necesaria, proporciona la funcionalidad necesaria para el soporte de raster gdal-config para activar la instalación de software para localizar el directorio de instalación de GDAL. Utilice este parámetro ( - with-gdalconfig = / ruta /a/ gdal config-) para especificar manualmente una instalación de GDAL personalizada que PostGIS utilizara para compilar.
GEOS, libreria de geometrías requerida, tiene una utilidad llamada geos-config para activar la localización del directorio de instalación del software GEOS. Utiliza este parametro (--with-geosconfig=/path/to/geos-config) para especificar de forma manual una instalación personalizada de GEOS que PostGIS puede utilizar para compilar.
LibXML es una libreria necesaria para procesar GeomFromKML/GML. Normalmente encontrara si tienes instalada la libreria libxml, pero si no esta instalada, o quieres usar una versión especifica, necesitaras que PostGIS apunte a un fichero de configuración particular xml2-config
para localizar un directorio de instalación LibXML para activar la instalación del Software. Utiliza el siguiente parámetro (
>--with-xml2config=/path/to/xml2-config) para especificar de forma manual una instalación personalizada de LibXML con la que compilar PostGIS.
Proj4 es una libreria de reproyecciones necesaria de PostGIS. Utiliza el siguiente parametro (--with-projdir=/path/to/projdir) para definir manualmente una instalación personalizada de Proj4 para compilar PostGIS.
Directorio donde iconv esta instalado.
JSON-Ces una libreria con licencia MIT-licensed JSON necesaria para dar soporte a PostGIS ST_GeomFromJSON. Utiliza este parametro (--with-jsondir=/path/to/jsondir) para especificar de forma manual el directorio de instalación personalizado de instalación de JSON-C que PostGIS utilizara para compilar.
PCRE is an BSD-licensed Perl Compatible Regular Expression library required by address_standardizer extension. Use this parameter (--with-pcredir=/path/to/pcredir) to manually specify a particular PCRE installation directory that PostGIS will build against.
Compilar la GUI de importar datos (necesita GTK+2.0). Esto creara una interfaz gráfica shp2pgsql-gui para el comando shp2pgsql.
Compile without raster support.
Disable topology support. There is no corresponding library as all logic needed for topology is in postgis-3.4.0dev library.
PostGIS intentara detectar soporte gettext y compilar con el por defecto, de todas formas si existen incompatibilidades que causan errores de carga, se puede desactivar por completo con este comando. Para ver un ejemplo de resolución de problemas configurando en gettext puedes ver el siguiente enlace http://trac.osgeo.org/postgis/ticket/748. NOTA: No te pierdes mucho si desactivas esta opción. Se utiliza principalmente para soporte de ayuda/etiquetas internacionales en la GUI de carga, que actualmente no esta documentada y sigue siendo experimental.
By default PostGIS will not install with sfcgal support without this switch. PATH
is an optional argument that allows to specify an alternate PATH to sfcgal-config.
Disable updating postgis_revision.h to match current HEAD of the git repository.
![]() | |
If you obtained PostGIS from the code repository , the first step is really to run the script ./autogen.sh Este Script generara el script configure que a su vez se utiliza para personalizar la instalación de PostGIS. Si, por el contrario, as obtenido PostGIS como tarball, ejecutar ./autogen.sh no es necesario ya que ya se ha generado configure. |
Una vez generado el Makefile, compilar PostGIS es tan simple como ejecutar
make
La ultima linea de salida del terminal debe ser "PostGIS copilado con éxito. Listo para instalar.
"
As of PostGIS v1.4.0, all the functions have comments generated from the documentation. If you wish to install these comments into your spatial databases later, run the command which requires docbook. The postgis_comments.sql and other package comments files raster_comments.sql, topology_comments.sql are also packaged in the tar.gz distribution in the doc folder so no need to make comments if installing from the tar ball. Comments are also included as part of the CREATE EXTENSION install.
make comments
Introducido en la version PostGIS 2.0. Esto genera hojas de referencia html para una referencia rápida o para los folletos. Esto requiere xsltproc para compilar y generará 4 ficheros en la carpeta doc topology_cheatsheet.html
, tiger_geocoder_cheatsheet.html
, raster_cheatsheet.html
, postgis_cheatsheet.html
Puedes descargar algunos ya compilados en formato html o pdf en Guias de Estudio PostGIS / PostgreSQL
make cheatsheets
Las extensiones de PosGIS son compiladas e instaladas de forma automatica si estas utilizando la version 9.1+ de PostgreSQL
Si estas compilando desde el repositorio de código fuente, necesitas compilar primero la función descriptions. Si tienes instaldo docbook ya esta compilado. También puedes compilarla manualmente con la sentencia:
make comments
Compilar los comentarios no es necesario si estas compilando desde un tar ya que están en el paquete pre-compilados con el tar.
Si estas compilando para PostgreSQL 9.1, la extension debería compilarse de forma automática como parte del proceso del comando make install. Si lo necesitas, puedes compilar la extensión desde las carpetas de la extensión o copiar los ficheros en un servidor diferente.
cd extensions cd postgis make clean make export PGUSER=postgres #overwrite psql variables make check #to test before install make install # to test extensions make check RUNTESTFLAGS=--extension
![]() | |
|
Los ficheros de la extension serán siempre los mismos para la misma versión de PostgreSQL independientemente del Sistema Operativo, así que se pueden copiar los ficheros de la extensión de un Sistema Operativo a otro si ya tienes los binarios de PostGIS ya instalados en tus servidores.
Si quieres instalar la extensión de forma manual en un servidor separado de tu servidor de desarrollo, necesitas copiar los siguientes archivos de la carpeta de la extensión en la carpeta PostgreSQL / share / extension
de la instalación de PostgreSQL y los binarios normales para PostGIS si no los tienes instalados en el servidor.
Estos son los ficheros de control que contienen información como la versión de la extensión a instalar si no lo has especificado. postgis.control, postgis_topology.control
.
Todos los ficheros en la carpeta /sql de la extension. Estos ficheros deben ser copiados en la raiz de PostgreSQL en la carpeta share/extension extensions/postgis/sql/*.sql
, extensions/postgis_topology/sql/*.sql
Una vez hecho esto deberías ver postgis
, postgis_topology
como extensiones disponibles en PgAdmin -> extensiones.
Si estas utilizando psql, puedes verificar que las extensiones están instaladas ejecutando la siguiente sentencia:
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_sfcgal | 3.4.0dev | postgis_tiger_geocoder | 3.4.0dev | 3.4.0dev postgis_topology | 3.4.0dev | (6 rows)
Si tienes instalada una extension en la base de datos que estas consultando, deberías verla mencionada la columna installed_version
. Si la consulta no devuelve ningún registro, significa que no tienes la extension PostGIS instalada en el servidor. PgAdmin III 1.14+ muestra esta información en la sección extensiones
en el navegador de bases de datos y permite actualizar o instalar haciendo click derecho.
Si la extension esta disponible, puedes instalar la extension postgis en la base de datos de tu elección utilizando la interfaz de extensiones de pgAdmin o ejecutando la siguiente sentencia:
CREATE EXTENSION postgis; CREATE EXTENSION postgis_sfcgal; CREATE EXTENSION fuzzystrmatch; --needed for postgis_tiger_geocoder --optional used by postgis_tiger_geocoder, or can be used standalone CREATE EXTENSION address_standardizer; CREATE EXTENSION address_standardizer_data_us; CREATE EXTENSION postgis_tiger_geocoder; CREATE EXTENSION postgis_topology;
In psql you can use to see what versions you have installed and also what schema they are installed.
\connect mygisdb \x \dx postgis*
List of installed extensions -[ RECORD 1 ]------------------------------------------------- Name | postgis Version | 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
![]() | |
No se pueden hacer copias de seguridad explicitas de las tablas de las extensiones |
If you installed 3.4.0dev, without using our wonderful extension system, you can change it to be extension based by running the below commands to package the functions in their respective extension. Installing using `unpackaged` was removed in PostgreSQL 13, so you are advised to switch to an extension build before upgrading to PostgreSQL 13.
CREATE EXTENSION postgis FROM unpackaged; CREATE EXTENSION postgis_raster FROM unpackaged; CREATE EXTENSION postgis_topology FROM unpackaged; CREATE EXTENSION postgis_tiger_geocoder FROM unpackaged;
Si quieres hacer un test en la compilación de PostGIS, ejecuta
make check
El comando anterior ejecutará varias comprobaciones y tests de regresión utilizando la librería generada para la version de base de datos PostgreSQL actual.
![]() | |
Si has configurado PostGIS con instalaciones de PostgreSQL, GEOS, o Proj4 en directorios personalizados, necesitaras añadir las localizaciones de las librerías personalizadas en la variable de entorno LD_LIBRARY_PATH. |
![]() | |
Actualmente, el comando make check une las variables de entorno |
If successful, make check will produce the output of almost 500 tests. The results will look similar to the following (numerous lines omitted below):
CUnit - A unit testing framework for C - Version 2.1-3 http://cunit.sourceforge.net/ . . . Run Summary: Type Total Ran Passed Failed Inactive suites 44 44 n/a 0 0 tests 300 300 300 0 0 asserts 4215 4215 4215 0 n/a Elapsed time = 0.229 seconds . . . Running tests . . . Run tests: 134 Failed: 0 -- if you build with SFCGAL . . . Running tests . . . Run tests: 13 Failed: 0 -- if you built with raster support . . . Run Summary: Type Total Ran Passed Failed Inactive suites 12 12 n/a 0 0 tests 65 65 65 0 0 asserts 45896 45896 45896 0 n/a . . . Running tests . . . Run tests: 101 Failed: 0 -- topology regress . . . Running tests . . . Run tests: 51 Failed: 0 -- if you built --with-gui, you should see this too CUnit - A unit testing framework for C - Version 2.1-2 http://cunit.sourceforge.net/ . . . Run Summary: Type Total Ran Passed Failed Inactive suites 2 2 n/a 0 0 tests 4 4 4 0 0 asserts 4 4 4 0 n/a
The postgis_tiger_geocoder
and address_standardizer
extensions, currently only support the standard PostgreSQL installcheck. To test these use the below. Note: the make install is not necessary if you already did make install at root of PostGIS code folder.
For address_standardizer:
cd extensions/address_standardizer make install make installcheck
Output should look like:
============== dropping database "contrib_regression" ============== DROP DATABASE ============== creating database "contrib_regression" ============== CREATE DATABASE ALTER DATABASE ============== running regression test queries ============== test test-init-extensions ... ok test test-parseaddress ... ok test test-standardize_address_1 ... ok test test-standardize_address_2 ... ok ===================== All 4 tests passed. =====================
For tiger geocoder, make sure you have postgis and fuzzystrmatch extensions available in your PostgreSQL instance. The address_standardizer tests will also kick in if you built postgis with address_standardizer support:
cd extensions/postgis_tiger_geocoder make install make installcheck
output should look like:
============== dropping database "contrib_regression" ============== DROP DATABASE ============== creating database "contrib_regression" ============== CREATE DATABASE ALTER DATABASE ============== installing fuzzystrmatch ============== CREATE EXTENSION ============== installing postgis ============== CREATE EXTENSION ============== installing postgis_tiger_geocoder ============== CREATE EXTENSION ============== installing address_standardizer ============== CREATE EXTENSION ============== running regression test queries ============== test test-normalize_address ... ok test test-pagc_normalize_address ... ok ===================== All 2 tests passed. =====================
Para instalar PostGIS entre
make install
Esto copiará los ficheros de instalación de PostGIS en el subdirectorio especificado por el parámetro de configuración --prefix del comando . En particular:
Los archivos binarios de carga y dumper estarán instalados en [prefix]/bin
.
Los archivos SQL, tal como postgis.sql
, están instalados en [prefix]/share/contrib
.
Las librerías de PostGIS estarán instaladas en [prefix]/lib
.
Si has ejecutado el comando make comments previamente para generar los ficheros postgis_comments.sql
, raster_comments.sql
, instala los ficheros sql ejecutando:
make comments-install
![]() | |
|
The address_standardizer
extension used to be a separate package that required separate download. From PostGIS 2.2 on, it is now bundled in. For more information about the address_standardize, what it does, and how to configure it for your needs, refer to Section 14.1, “Normalizador de Direcciones”.
This standardizer can be used in conjunction with the PostGIS packaged tiger geocoder extension as a replacement for the Normalize_Address discussed. To use as replacement refer to Section 2.4.2, “Using Address Standardizer Extension with Tiger geocoder”. You can also use it as a building block for your own geocoder or use it to standardize your addresses for easier compare of addresses.
The address standardizer relies on PCRE which is usually already installed on many Nix systems, but you can download the latest at: http://www.pcre.org. If during Section 2.2.3, “Configuración”, PCRE is found, then the address standardizer extension will automatically be built. If you have a custom pcre install you want to use instead, pass to configure --with-pcredir=/path/to/pcre
where /path/to/pcre
is the root folder for your pcre include and lib directories.
For Windows users, the PostGIS 2.1+ bundle is packaged with the address_standardizer already so no need to compile and can move straight to CREATE EXTENSION
step.
Once you have installed, you can connect to your database and run the SQL:
CREATE EXTENSION address_standardizer;
The following test requires no rules, gaz, or lex tables
SELECT num, street, city, state, zip FROM parse_address('1 Devonshire Place PH301, Boston, MA 02109');
Output should be
num | street | city | state | zip -----+------------------------+--------+-------+------- 1 | Devonshire Place PH301 | Boston | MA | 02109
Perl Regex:Assemble is no longer needed for compiling address_standardizer extension since the files it generates are part of the source tree. However if you need to edit the usps-st-city-orig.txt
or usps-st-city-orig.txt usps-st-city-adds.tx
, you need to rebuild parseaddress-stcities.h
which does require Regex:Assemble.
cpan Regexp::Assemble
or if you are on Ubuntu / Debian you might need to do
sudo perl -MCPAN -e "install Regexp::Assemble"
Extras like Tiger geocoder may not be packaged in your PostGIS distribution. If you are missing the tiger geocoder extension or want a newer version than what your install comes with, then use the share/extension/postgis_tiger_geocoder.*
files from the packages in Windows Unreleased Versions section for your version of PostgreSQL. Although these packages are for windows, the postgis_tiger_geocoder extension files will work on any OS since the extension is an SQL/plpgsql only extension.
First get binaries for PostGIS 2.1+ or compile and install as usual. This should install the necessary extension files as well for tiger geocoder.
Connect to your database via psql or pgAdmin or some other tool and run the following SQL commands. Note that if you are installing in a database that already has postgis, you don't need to do the first step. If you have fuzzystrmatch
extension already installed, you don't need to do the second step either.
CREATE EXTENSION postgis; CREATE EXTENSION fuzzystrmatch; CREATE EXTENSION postgis_tiger_geocoder; --this one is optional if you want to use the rules based standardizer (pagc_normalize_address) CREATE EXTENSION address_standardizer;
If you already have postgis_tiger_geocoder extension installed, and just want to update to the latest run:
ALTER EXTENSION postgis UPDATE; ALTER EXTENSION postgis_tiger_geocoder UPDATE;
If you made custom entries or changes to tiger.loader_platform
and tiger.loader_variables
you may need to update these.
To confirm your install is working correctly, run this sql in your database:
SELECT na.address, na.streetname,na.streettypeabbrev, na.zip FROM normalize_address('1 Devonshire Place, Boston, MA 02109') AS na;
Which should output
address | streetname | streettypeabbrev | zip ---------+------------+------------------+------- 1 | Devonshire | Pl | 02109
Create a new record in tiger.loader_platform
table with the paths of your executables and server.
So for example to create a profile called debbie that follows sh
convention. You would do:
INSERT INTO tiger.loader_platform(os, declare_sect, pgbin, wget, unzip_command, psql, path_sep, loader, environ_set_command, county_process_command) SELECT 'debbie', declare_sect, pgbin, wget, unzip_command, psql, path_sep, loader, environ_set_command, county_process_command FROM tiger.loader_platform WHERE os = 'sh';
And then edit the paths in the declare_sect column to those that fit Debbie's pg, unzip,shp2pgsql, psql, etc path locations.
If you don't edit this loader_platform
table, it will just contain common case locations of items and you'll have to edit the generated script after the script is generated.
As of PostGIS 2.4.1 the Zip code-5 digit tabulation area zcta5
load step was revised to load current zcta5 data and is part of the Loader_Generate_Nation_Script when enabled. It is turned off by default because it takes quite a bit of time to load (20 to 60 minutes), takes up quite a bit of disk space, and is not used that often.
To enable it, do the following:
UPDATE tiger.loader_lookuptables SET load = true WHERE table_name = 'zcta520';
If present the Geocode function can use it if a boundary filter is added to limit to just zips in that boundary. The Reverse_Geocode function uses it if the returned address is missing a zip, which often happens with highway reverse geocoding.
Create a folder called gisdata
on root of server or your local pc if you have a fast network connection to the server. This folder is where the tiger files will be downloaded to and processed. If you are not happy with having the folder on the root of the server, or simply want to change to a different folder for staging, then edit the field staging_fold
in the tiger.loader_variables
table.
Create a folder called temp in the gisdata
folder or wherever you designated the staging_fold
to be. This will be the folder where the loader extracts the downloaded tiger data.
Then run the Loader_Generate_Nation_Script SQL function make sure to use the name of your custom profile and copy the script to a .sh or .bat file. So for example to build the nation load:
psql -c "SELECT Loader_Generate_Nation_Script('debbie')" -d geocoder -tA > /gisdata/nation_script_load.sh
Run the generated nation load commandline scripts.
cd /gisdata sh nation_script_load.sh
After you are done running the nation script, you should have three tables in your tiger_data
schema and they should be filled with data. Confirm you do by doing the following queries from psql or pgAdmin
SELECT count(*) FROM tiger_data.county_all;
count ------- 3233 (1 row)
SELECT count(*) FROM tiger_data.state_all;
count ------- 56 (1 row)
By default the tables corresponding to bg
, tract
, tabblock20
are not loaded. These tables are not used by the geocoder but are used by folks for population statistics. If you wish to load them as part of your state loads, run the following statement to enable them.
UPDATE tiger.loader_lookuptables SET load = true WHERE load = false AND lookup_name IN('tract', 'bg', 'tabblock20');
Alternatively you can load just these tables after loading state data using the Loader_Generate_Census_Script
For each state you want to load data for, generate a state script Loader_Generate_Script.
![]() | |
DO NOT Generate the state script until you have already loaded the nation data, because the state script utilizes county list loaded by nation script. |
psql -c "SELECT Loader_Generate_Script(ARRAY['MA'], 'debbie')" -d geocoder -tA > /gisdata/ma_load.sh
Run the generated commandline scripts.
cd /gisdata sh ma_load.sh
After you are done loading all data or at a stopping point, it's a good idea to analyze all the tiger tables to update the stats (include inherited stats)
SELECT install_missing_indexes(); vacuum (analyze, verbose) tiger.addr; vacuum (analyze, verbose) tiger.edges; vacuum (analyze, verbose) tiger.faces; vacuum (analyze, verbose) tiger.featnames; vacuum (analyze, verbose) tiger.place; vacuum (analyze, verbose) tiger.cousub; vacuum (analyze, verbose) tiger.county; vacuum (analyze, verbose) tiger.state; vacuum (analyze, verbose) tiger.zip_lookup_base; vacuum (analyze, verbose) tiger.zip_state; vacuum (analyze, verbose) tiger.zip_state_loc;
One of the many complaints of folks is the address normalizer function Normalize_Address function that normalizes an address for prepping before geocoding. The normalizer is far from perfect and trying to patch its imperfectness takes a vast amount of resources. As such we have integrated with another project that has a much better address standardizer engine. To use this new address_standardizer, you compile the extension as described in Section 2.3, “Installing and Using the address standardizer” and install as an extension in your database.
Once you install this extension in the same database as you have installed postgis_tiger_geocoder
, then the Pagc_Normalize_Address can be used instead of Normalize_Address. This extension is tiger agnostic, so can be used with other data sources such as international addresses. The tiger geocoder extension does come packaged with its own custom versions of rules table ( tiger.pagc_rules
) , gaz table (tiger.pagc_gaz
), and lex table (tiger.pagc_lex
). These you can add and update to improve your standardizing experience for your own needs.
El proceso de carga, descarga datos desde el sitio web del censo de las respectivas naciones de los estados pedidos, extrae los ficheros, y carga cada estado en un conjunto separado por estados en su propia tabla. Cada tabla de estado hereda el esquema de tablas definido en tiger
así que basta con hacer una consulta a estas tablas para acceder a todos los datos de la tabla de estados en cualquier momento utilizando Drop_State_Tables_Generate_Script si necesita volver a cargar un estado o si ya no lo necesitas mas.
Para poder cargar los datos necesitarás las siguientes herramientas:
Una herramienta para descomprimir ficheros zip de la pagina web del censo.
Para sistemas Unix: el ejecutable unzip
que normalmente esta instalado en la mayoría de sistemas Unix.
Para windows, 7-zip es una herramienta libre de compresión/descompresión que puedes descargar en http://www.7-zip.org/
El comando shp2pgsql
que se instala por defecto cuando instalas PostGIS.
wget
que es una herramienta de captura web, normalmente instalado en los sistemas Unix/Linux.
Si estas en windows, puedes obtener ejecutables precompilados en http://gnuwin32.sourceforge.net/packages/wget.htm
If you are upgrading from tiger_2010, you'll need to first generate and run Drop_Nation_Tables_Generate_Script. Before you load any state data, you need to load the nation wide data which you do with Loader_Generate_Nation_Script. Which will generate a loader script for you. Loader_Generate_Nation_Script is a one-time step that should be done for upgrading (from a prior year tiger census data) and for new installs.
To load state data refer to Loader_Generate_Script to generate a data load script for your platform for the states you desire. Note that you can install these piecemeal. You don't have to load all the states you want all at once. You can load them as you need them.
Una vez que los estados que quieres han sido cargados, asegurare de ejecutar:
SELECT install_missing_indexes();
como se explica en Install_Missing_Indexes.
Para probar que las cosas han funcionado como deberían, intenta ejecutar una geocodificacion en una dirección del estado descargado utilizando Geocode
First upgrade your postgis_tiger_geocoder extension as follows:
ALTER EXTENSION postgis_tiger_geocoder UPDATE;
Después, elimina todas las tabals de naciones y carga las nuevas. Genera un script drop con esta sentencia SQL como se detalla en Drop_Nation_Tables_Generate_Script
SELECT drop_nation_tables_generate_script();
Ejecuta la sentencia SQL drop
Genera un script de carga de naciones con esta sentencia SELECT como se detalla en Loader_Generate_Nation_Script
Para windows
SELECT loader_generate_nation_script('windows');
Para unix/linux
SELECT loader_generate_nation_script('sh');
Para mas información sobre como ejecutar los scripts generados visita 4. Esto solo es necesario hacerlo una vez.
![]() | |
You can have a mix of different year state tables and can upgrade each state separately. Before you upgrade a state you first need to drop the prior year state tables for that state using Drop_State_Tables_Generate_Script. |
Hay varias cosas a comprobar cuando la instalación o actualización no han fusionado como se esperaba.
Comprueba que tienes instalado PostgreSQL 12 o posterior, y que estas compilando para esta version de PostgreSQL que estas utilizando. Se pueden producir confusiones cuando tu distribución (Linux)ya tiene instalada PostgreSQL, o has instalado antes PostgreSQL y lo has olvidado. PostGIS solo funcionará con PostgreSQL 12 o superior, y errores inesperados o extraños pueden ocurrir si utilizas una version mas antigua. Para comprobar la version de PostgreSQL que esta instalada y ejecutándose, conectare a la base de datos utilizando psql y ejecuta la siguiente consulta:
SELECT version();
Si estas ejecutando una version basada en una distribución RPM, puedes comprobar si existen paquetes pre-instalados utilizando el comando rpm como sigue: rpm -qa | grep postgresql
Si tienes errores en la actualización, asegúrate de que estas restaurando tu base de datos en una que tenga instalada PostGIS.
SELECT postgis_full_version();
Comprueba que tu configuración detecta la ubicación y la version correctas de PostgreSQL, la librería Proj4 y la librería GEOS.
La salida de configure se utiliza para generar el fichero postgis_config.h
. Comprueba que la variables POSTGIS_PGSQL_VERSION
, POSTGIS_PROJ_VERSION
y POSTGIS_GEOS_VERSION
, han sido bien configuradas.
Tuning for PostGIS performance is much like tuning for any PostgreSQL workload. The only additional consideration is that geometries and rasters are usually large, so memory-related optimizations generally have more of an impact on PostGIS than other types of PostgreSQL queries.
For general details about optimizing PostgreSQL, refer to Tuning your PostgreSQL Server.
For PostgreSQL 9.4+ configuration can be set at the server level without touching postgresql.conf
or postgresql.auto.conf
by using the ALTER SYSTEM
command.
ALTER SYSTEM SET work_mem = '256MB'; -- this forces non-startup configs to take effect for new connections SELECT pg_reload_conf(); -- show current setting value -- use SHOW ALL to see all settings SHOW work_mem;
In addition to the Postgres settings, PostGIS has some custom settings which are listed in Section 8.23, “Grand Unified Custom Variables (GUCs)”.
These settings are configured in postgresql.conf
:
Default: partition
This is generally used for table partitioning. The default for this is set to "partition" which is ideal for PostgreSQL 8.4 and above since it will force the planner to only analyze tables for constraint consideration if they are in an inherited hierarchy and not pay the planner penalty otherwise.
Default: ~128MB in PostgreSQL 9.6
Set to about 25% to 40% of available RAM. On windows you may not be able to set as high.
max_worker_processes This setting is only available for PostgreSQL 9.4+. For PostgreSQL 9.6+ this setting has additional importance in that it controls the max number of processes you can have for parallel queries.
Predeterminado: 18
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.
If you enabled raster support you may want to read below how to properly configure it.
As of PostGIS 2.1.3, out-of-db rasters and all raster drivers are disabled by default. In order to re-enable these, you need to set the following environment variables POSTGIS_GDAL_ENABLED_DRIVERS
and POSTGIS_ENABLE_OUTDB_RASTERS
in the server environment. For PostGIS 2.2, you can use the more cross-platform approach of setting the corresponding Section 8.23, “Grand Unified Custom Variables (GUCs)”.
If you want to enable offline raster:
POSTGIS_ENABLE_OUTDB_RASTERS=1
Any other setting or no setting at all will disable out of db rasters.
In order to enable all GDAL drivers available in your GDAL install, set this environment variable as follows
POSTGIS_GDAL_ENABLED_DRIVERS=ENABLE_ALL
If you want to only enable specific drivers, set your environment variable as follows:
POSTGIS_GDAL_ENABLED_DRIVERS="GTiff PNG JPEG GIF XYZ"
![]() | |
If you are on windows, do not quote the driver list |
Setting environment variables varies depending on OS. For PostgreSQL installed on Ubuntu or Debian via apt-postgresql, the preferred way is to edit /etc/postgresql/
where 10 refers to version of PostgreSQL and main refers to the 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.
After you set the environment variables, you'll need to restart your PostgreSQL service for the changes to take effect.
If you are using PostgreSQL 9.1+ and have compiled and installed the extensions/postgis modules, you can turn a database into a spatial one using the EXTENSION mechanism.
Core postgis extension includes geometry, geography, spatial_ref_sys and all the functions and comments. Raster and topology are packaged as a separate extension.
Run the following SQL snippet in the database you want to enable spatially:
CREATE EXTENSION IF NOT EXISTS plpgsql; CREATE EXTENSION postgis; CREATE EXTENSION postgis_raster; -- OPTIONAL CREATE EXTENSION postgis_topology; -- OPTIONAL
![]() | |
This is generally only needed if you cannot or don't want to get PostGIS installed in the PostgreSQL extension directory (for example during testing, development or in a restricted environment). |
Adding PostGIS objects and function definitions into your database is done by loading the various sql files located in [prefix]/share/contrib
as specified during the build phase.
The core PostGIS objects (geometry and geography types, and their support functions) are in the postgis.sql
script. Raster objects are in the rtpostgis.sql
script. Topology objects are in the topology.sql
script.
For a complete set of EPSG coordinate system definition identifiers, you can also load the spatial_ref_sys.sql
definitions file and populate the spatial_ref_sys
table. This will permit you to perform ST_Transform() operations on geometries.
If you wish to add comments to the PostGIS functions, you can find them in the postgis_comments.sql
script. Comments can be viewed by simply typing \dd [function_name] from a psql terminal window.
Run the following Shell commands in your terminal:
DB=[yourdatabase] SCRIPTSDIR=`pg_config --sharedir`/contrib/postgis-3.3/ # Core objects psql -d ${DB} -f ${SCRIPTSDIR}/postgis.sql psql -d ${DB} -f ${SCRIPTSDIR}/spatial_ref_sys.sql psql -d ${DB} -f ${SCRIPTSDIR}/postgis_comments.sql # OPTIONAL # Raster support (OPTIONAL) psql -d ${DB} -f ${SCRIPTSDIR}/rtpostgis.sql psql -d ${DB} -f ${SCRIPTSDIR}/raster_comments.sql # OPTIONAL # Topology support (OPTIONAL) psql -d ${DB} -f ${SCRIPTSDIR}/topology.sql psql -d ${DB} -f ${SCRIPTSDIR}/topology_comments.sql # OPTIONAL
Some packaged distributions of PostGIS (in particular the Win32 installers for PostGIS >= 1.1.5) load the PostGIS functions into a template database called template_postgis
. If the template_postgis
database exists in your PostgreSQL installation then it is possible for users and/or applications to create spatially-enabled databases using a single command. Note that in both cases, the database user must have been granted the privilege to create new databases.
From the shell:
# createdb -T template_postgis my_spatial_db
From SQL:
postgres=# CREATE DATABASE my_spatial_db TEMPLATE=template_postgis
Upgrading existing spatial databases can be tricky as it requires replacement or introduction of new PostGIS object definitions.
Unfortunately not all definitions can be easily replaced in a live database, so sometimes your best bet is a dump/reload process.
PostGIS provides a SOFT UPGRADE procedure for minor or bugfix releases, and a HARD UPGRADE procedure for major releases.
Before attempting to upgrade PostGIS, it is always worth to backup your data. If you use the -Fc flag to pg_dump you will always be able to restore the dump with a HARD UPGRADE.
If you installed your database using extensions, you'll need to upgrade using the extension model as well. If you installed using the old sql script way, you are advised to switch your install to extensions because the script way is no longer supported.
If you originally installed PostGIS with extensions, then you need to upgrade using extensions as well. Doing a minor upgrade with extensions, is fairly painless.
If you are running PostGIS 3 or above, then you should use the PostGIS_Extensions_Upgrade function to upgrade to the latest version you have installed.
SELECT postgis_extensions_upgrade();
If you are running PostGIS 2.5 or lower, then do the following:
ALTER EXTENSION postgis UPDATE; SELECT postgis_extensions_upgrade(); -- This second call is needed to rebundle postgis_raster extension SELECT postgis_extensions_upgrade();
If you have multiple versions of PostGIS installed, and you don't want to upgrade to the latest, you can explicitly specify the version as follows:
ALTER EXTENSION postgis UPDATE TO "3.4.0dev"; ALTER EXTENSION postgis_topology UPDATE TO "3.4.0dev";
If you get an error notice something like:
No migration path defined for … to 3.4.0dev
Then you'll need to backup your database, create a fresh one as described in Section 3.3.1, “Spatially enable database using EXTENSION” and then restore your backup on top of this new database.
If you get a notice message like:
Version "3.4.0dev" of extension "postgis" is already installed
Then everything is already up to date and you can safely ignore it. UNLESS you're attempting to upgrade from an development version to the next (which doesn't get a new version number); in that case you can append "next" to the version string, and next time you'll need to drop the "next" suffix again:
ALTER EXTENSION postgis UPDATE TO "3.4.0devnext"; ALTER EXTENSION postgis_topology UPDATE TO "3.4.0devnext";
![]() | |
If you installed PostGIS originally without a version specified, you can often skip the reinstallation of postgis extension before restoring since the backup just has |
![]() | |
If you are upgrading PostGIS extension from a version prior to 3.0.0, you will have a new extension postgis_raster which you can safely drop, if you don't need raster support. You can drop as follows: DROP EXTENSION postgis_raster; |
This section applies only to those who installed PostGIS not using extensions. If you have extensions and try to upgrade with this approach you'll get messages like:
can't drop … because postgis extension depends on it
NOTE: if you are moving from PostGIS 1.* to PostGIS 2.* or from PostGIS 2.* prior to r7409, you cannot use this procedure but would rather need to do a HARD UPGRADE.
After compiling and installing (make install) you should find a set of *_upgrade.sql
files in the installation folders. You can list them all with:
ls `pg_config --sharedir`/contrib/postgis-3.4.0dev/*_upgrade.sql
Load them all in turn, starting from postgis_upgrade.sql
.
psql -f postgis_upgrade.sql -d your_spatial_database
The same procedure applies to raster, topology and sfcgal extensions, with upgrade files named rtpostgis_upgrade.sql
, topology_upgrade.sql
and sfcgal_upgrade.sql
respectively. If you need them:
psql -f rtpostgis_upgrade.sql -d your_spatial_database
psql -f topology_upgrade.sql -d your_spatial_database
psql -f sfcgal_upgrade.sql -d your_spatial_database
You are advised to switch to an extension based install by running
psql -c "SELECT postgis_extensions_upgrade();"
![]() | |
If you can't find the |
The PostGIS_Full_Version function should inform you about the need to run this kind of upgrade using a "procs need upgrade" message.
By HARD UPGRADE we mean full dump/reload of postgis-enabled databases. You need a HARD UPGRADE when PostGIS objects' internal storage changes or when SOFT UPGRADE is not possible. The Release Notes appendix reports for each version whether you need a dump/reload (HARD UPGRADE) to upgrade.
The dump/reload process is assisted by the postgis_restore.pl script which takes care of skipping from the dump all definitions which belong to PostGIS (including old ones), allowing you to restore your schemas and data into a database with PostGIS installed without getting duplicate symbol errors or bringing forward deprecated objects.
Supplementary instructions for windows users are available at Windows Hard upgrade.
The Procedure is as follows:
Create a "custom-format" dump of the database you want to upgrade (let's call it olddb
) include binary blobs (-b) and verbose (-v) output. The user can be the owner of the db, need not be postgres super account.
pg_dump -h localhost -p 5432 -U postgres -Fc -b -v -f "/somepath/olddb.backup" olddb
Do a fresh install of PostGIS in a new database -- we'll refer to this database as newdb
. Please refer to Section 3.3.2, “Spatially enable database without using EXTENSION (discouraged)” and Section 3.3.1, “Spatially enable database using EXTENSION” for instructions on how to do this.
The spatial_ref_sys entries found in your dump will be restored, but they will not override existing ones in spatial_ref_sys. This is to ensure that fixes in the official set will be properly propagated to restored databases. If for any reason you really want your own overrides of standard entries just don't load the spatial_ref_sys.sql file when creating the new db.
If your database is really old or you know you've been using long deprecated functions in your views and functions, you might need to load legacy.sql
for all your functions and views etc. to properly come back. Only do this if _really_ needed. Consider upgrading your views and functions before dumping instead, if possible. The deprecated functions can be later removed by loading uninstall_legacy.sql
.
Restore your backup into your fresh newdb
database using postgis_restore.pl. Unexpected errors, if any, will be printed to the standard error stream by psql. Keep a log of those.
perl utils/postgis_restore.pl "/somepath/olddb.backup" | psql -h localhost -p 5432 -U postgres newdb 2> errors.txt
Errors may arise in the following cases:
Some of your views or functions make use of deprecated PostGIS objects. In order to fix this you may try loading legacy.sql
script prior to restore or you'll have to restore to a version of PostGIS which still contains those objects and try a migration again after porting your code. If the legacy.sql
way works for you, don't forget to fix your code to stop using deprecated functions and drop them loading uninstall_legacy.sql
.
Some custom records of spatial_ref_sys in dump file have an invalid SRID value. Valid SRID values are bigger than 0 and smaller than 999000. Values in the 999000.999999 range are reserved for internal use while values > 999999 can't be used at all. All your custom records with invalid SRIDs will be retained, with those > 999999 moved into the reserved range, but the spatial_ref_sys table would lose a check constraint guarding for that invariant to hold and possibly also its primary key ( when multiple invalid SRIDS get converted to the same reserved SRID value ).
In order to fix this you should copy your custom SRS to a SRID with a valid value (maybe in the 910000..910999 range), convert all your tables to the new srid (see UpdateGeometrySRID), delete the invalid entry from spatial_ref_sys and re-construct the check(s) with:
ALTER TABLE spatial_ref_sys ADD CONSTRAINT spatial_ref_sys_srid_check check (srid > 0 AND srid < 999000 );
ALTER TABLE spatial_ref_sys ADD PRIMARY KEY(srid));
If you are upgrading an old database containing french IGN cartography, you will have probably SRIDs out of range and you will see, when importing your database, issues like this :
WARNING: SRID 310642222 converted to 999175 (in reserved zone)
In this case, you can try following steps : first throw out completely the IGN from the sql which is resulting from postgis_restore.pl. So, after having run :
perl utils/postgis_restore.pl "/somepath/olddb.backup" > olddb.sql
run this command :
grep -v IGNF olddb.sql > olddb-without-IGN.sql
Create then your newdb, activate the required Postgis extensions, and insert properly the french system IGN with : this script After these operations, import your data :
psql -h localhost -p 5432 -U postgres -d newdb -f olddb-without-IGN.sql 2> errors.txt
The Open Geospatial Consortium (OGC) developed the Simple Features Access standard (SFA) to provide a model for geospatial data. It defines the fundamental spatial type of Geometry, along with operations which manipulate and transform geometry values to perform spatial analysis tasks. PostGIS implements the OGC Geometry model as the PostgreSQL data types geometry and geography.
Geometry is an abstract type. Geometry values belong to one of its concrete subtypes which represent various kinds and dimensions of geometric shapes. These include the atomic types Point, LineString, LinearRing and Polygon, and the collection types MultiPoint, MultiLineString, MultiPolygon and GeometryCollection. The Simple Features Access - Part 1: Common architecture v1.2.1 adds subtypes for the structures PolyhedralSurface, Triangle and TIN.
Geometry models shapes in the 2-dimensional Cartesian plane. The PolyhedralSurface, Triangle, and TIN types can also represent shapes in 3-dimensional space. The size and location of shapes are specified by their coordinates. Each coordinate has a X and Y ordinate value determining its location in the plane. Shapes are constructed from points or line segments, with points specified by a single coordinate, and line segments by two coordinates.
Coordinates may contain optional Z and M ordinate values. The Z ordinate is often used to represent elevation. The M ordinate contains a measure value, which may represent time or distance. If Z or M values are present in a geometry value, they must be defined for each point in the geometry. If a geometry has Z or M ordinates the coordinate dimension is 3D; if it has both Z and M the coordinate dimension is 4D.
Geometry values are associated with a spatial reference system indicating the coordinate system in which it is embedded. The spatial reference system is identified by the geometry SRID number. The units of the X and Y axes are determined by the spatial reference system. In planar reference systems the X and Y coordinates typically represent easting and northing, while in geodetic systems they represent longitude and latitude. SRID 0 represents an infinite Cartesian plane with no units assigned to its axes. See Section 4.5, “Spatial Reference Systems”.
The geometry dimension is a property of geometry types. Point types have dimension 0, linear types have dimension 1, and polygonal types have dimension 2. Collections have the dimension of the maximum element dimension.
A geometry value may be empty. Empty values contain no vertices (for atomic geometry types) or no elements (for collections).
An important property of geometry values is their spatial extent or bounding box, which the OGC model calls envelope. This is the 2 or 3-dimensional box which encloses the coordinates of a geometry. It is an efficient way to represent a geometry's extent in coordinate space and to check whether two geometries interact.
The geometry model allows evaluating topological spatial relationships as described in Section 5.1.1, “Dimensionally Extended 9-Intersection Model”. To support this the concepts of interior, boundary and exterior are defined for each geometry type. Geometries are topologically closed, so they always contain their boundary. The boundary is a geometry of dimension one less than that of the geometry itself.
The OGC geometry model defines validity rules for each geometry type. These rules ensure that geometry values represents realistic situations (e.g. it is possible to specify a polygon with a hole lying outside the shell, but this makes no sense geometrically and is thus invalid). PostGIS also allows storing and manipulating invalid geometry values. This allows detecting and fixing them if needed. See Section 4.4, “Geometry Validation”
A Point is a 0-dimensional geometry that represents a single location in coordinate space.
POINT (1 2) POINT Z (1 2 3) POINT ZM (1 2 3 4)
A LineString is a 1-dimensional line formed by a contiguous sequence of line segments. Each line segment is defined by two points, with the end point of one segment forming the start point of the next segment. An OGC-valid LineString has either zero or two or more points, but PostGIS also allows single-point LineStrings. LineStrings may cross themselves (self-intersect). A LineString is closed if the start and end points are the same. A LineString is simple if it does not self-intersect.
LINESTRING (1 2, 3 4, 5 6)
A LinearRing is a LineString which is both closed and simple. The first and last points must be equal, and the line must not self-intersect.
LINEARRING (0 0 0, 4 0 0, 4 4 0, 0 4 0, 0 0 0)
A Polygon is a 2-dimensional planar region, delimited by an exterior boundary (the shell) and zero or more interior boundaries (holes). Each boundary is a LinearRing.
POLYGON ((0 0 0,4 0 0,4 4 0,0 4 0,0 0 0),(1 1 0,2 1 0,2 2 0,1 2 0,1 1 0))
A MultiLineString is a collection of LineStrings. A MultiLineString is closed if each of its elements is closed.
MULTILINESTRING ( (0 0,1 1,1 2), (2 3,3 2,5 4) )
A MultiPolygon is a collection of non-overlapping, non-adjacent Polygons. Polygons in the collection may touch only at a finite number of points.
MULTIPOLYGON (((1 5, 5 5, 5 1, 1 1, 1 5)), ((6 5, 9 1, 6 1, 6 5)))
A GeometryCollection is a heterogeneous (mixed) collection of geometries.
GEOMETRYCOLLECTION ( POINT(2 3), LINESTRING(2 3, 3 4))
A PolyhedralSurface is a contiguous collection of patches or facets which share some edges. Each patch is a planar Polygon. If the Polygon coordinates have Z ordinates then the surface is 3-dimensional.
POLYHEDRALSURFACE Z ( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )
A Triangle is a polygon defined by three distinct non-collinear vertices. Because a Triangle is a polygon it is specified by four coordinates, with the first and fourth being equal.
TRIANGLE ((0 0, 0 9, 9 0, 0 0))
A TIN is a collection of non-overlapping Triangles representing a Triangulated Irregular Network.
TIN Z ( ((0 0 0, 0 0 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 0 0 0)) )
The ISO/IEC 13249-3 SQL Multimedia - Spatial standard (SQL/MM) extends the OGC SFA to define Geometry subtypes containing curves with circular arcs. The SQL/MM types support 3DM, 3DZ and 4D coordinates.
![]() | |
Todas las comparaciones de coma flotante en la implementación SQL-MM se desarrollan para una tolerancia específica, normalmente 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.
A partir de PostGIS 1.4, PostGIS soporta curvas compuestas en un polígono curvo.
CURVEPOLYGON( CIRCULARSTRING(0 0, 4 0, 4 4, 0 4, 0 0), (1 1, 3 3, 3 1, 1 1) )
Example: A CurvePolygon with the shell defined by a CompoundCurve containing a CircularString and a LineString, and a hole defined by a CircularString
CURVEPOLYGON( COMPOUNDCURVE( CIRCULARSTRING(0 0,2 0, 2 1, 2 3, 4 3), (4 3, 4 5, 1 4, 0 0)), CIRCULARSTRING(1.7 1, 1.4 0.4, 1.6 0.4, 1.6 0.5, 1.7 1) )
A MultiCurve is a collection of curves which can include LineStrings, CircularStrings or CompoundCurves.
MULTICURVE( (0 0, 5 5), CIRCULARSTRING(4 0, 4 4, 8 4))
The OGC SFA specification defines two formats for representing geometry values for external use: Well-Known Text (WKT) and Well-Known Binary (WKB). Both WKT and WKB include information about the type of the object and the coordinates which define it.
Well-Known Text (WKT) provides a standard textual representation of spatial data. Examples of WKT representations of spatial objects are:
POINT(0 0)
POINT Z (0 0 0)
POINT ZM (0 0 0 0)
POINT EMPTY
LINESTRING(0 0,1 1,1 2)
LINESTRING EMPTY
POLYGON((0 0,4 0,4 4,0 4,0 0),(1 1, 2 1, 2 2, 1 2,1 1))
MULTIPOINT((0 0),(1 2))
MULTIPOINT Z ((0 0 0),(1 2 3))
MULTIPOINT EMPTY
MULTILINESTRING((0 0,1 1,1 2),(2 3,3 2,5 4))
MULTIPOLYGON(((0 0,4 0,4 4,0 4,0 0),(1 1,2 1,2 2,1 2,1 1)), ((-1 -1,-1 -2,-2 -2,-2 -1,-1 -1)))
GEOMETRYCOLLECTION(POINT(2 3),LINESTRING(2 3,3 4))
GEOMETRYCOLLECTION EMPTY
Input and output of WKT is provided by the functions ST_AsText and ST_GeomFromText:
text WKT = ST_AsText(geometry); geometry = ST_GeomFromText(text WKT, SRID);
For example, a statement to create and insert a spatial object from WKT and a SRID is:
INSERT INTO geotable ( geom, name ) VALUES ( ST_GeomFromText('POINT(-126.4 45.32)', 312), 'A Place');
Well-Known Binary (WKB) provides a portable, full-precision representation of spatial data as binary data (arrays of bytes). Examples of the WKB representations of spatial objects are:
WKT: POINT(1 1)
WKB: 0101000000000000000000F03F000000000000F03
WKT: LINESTRING (2 2, 9 9)
WKB: 0102000000020000000000000000000040000000000000004000000000000022400000000000002240
Input and output of WKB is provided by the functions ST_AsBinary and ST_GeomFromWKB:
bytea WKB = ST_AsBinary(geometry); geometry = ST_GeomFromWKB(bytea WKB, SRID);
For example, a statement to create and insert a spatial object from WKB is:
INSERT INTO geotable ( geom, name ) VALUES ( ST_GeomFromWKB('\x0101000000000000000000f03f000000000000f03f', 312), 'A Place');
PostGIS implements the OGC Simple Features model by defining a PostgreSQL data type called geometry
. It represents all of the geometry subtypes by using an internal type code (see GeometryType and ST_GeometryType). This allows modelling spatial features as rows of tables defined with a column of type geometry
.
The geometry
data type is opaque, which means that all access is done via invoking functions on geometry values. Functions allow creating geometry objects, accessing or updating all internal fields, and compute new geometry values. PostGIS supports all the functions specified in the OGC Simple feature access - Part 2: SQL option (SFS) specification, as well many others. See Chapter 8, Manual de Referencia PostGIS for the full list of functions.
![]() | |
PostGIS follows the SFA standard by prefixing spatial functions with "ST_". This was intended to stand for "Spatial and Temporal", but the temporal part of the standard was never developed. Instead it can be interpreted as "Spatial Type". |
The SFA standard specifies that spatial objects include a Spatial Reference System identifier (SRID). The SRID is required when creating spatial objects for insertion into the database (it may be defaulted to 0). See ST_SRID and Section 4.5, “Spatial Reference Systems”
To make querying geometry efficient PostGIS defines various kinds of spatial indexes, and spatial operators to use them. See Section 4.9, “Spatial Indexes” and Section 5.2, “Using Spatial Indexes” for details.
OGC SFA specifications initially supported only 2D geometries, and the geometry SRID is not included in the input/output representations. The OGC SFA specification 1.2.1 (which aligns with the ISO 19125 standard) adds support for 3D (ZYZ) and measured (XYM and XYZM) coordinates, but still does not include the SRID value.
Because of these limitations PostGIS defined extended EWKB and EWKT formats. They provide 3D (XYZ and XYM) and 4D (XYZM) coordinate support and include SRID information. Including all geometry information allows PostGIS to use EWKB as the format of record (e.g. in DUMP files).
EWKB and EWKT are used for the "canonical forms" of PostGIS data objects. For input, the canonical form for binary data is EWKB, and for text data either EWKB or EWKT is accepted. This allows geometry values to be created by casting a text value in either HEXEWKB or EWKT to a geometry value using ::geometry
. For output, the canonical form for binary is EWKB, and for text it is HEXEWKB (hex-encoded EWKB).
For example this statement creates a geometry by casting from an EWKT text value, and outputs it using the canonical form of HEXEWKB:
SELECT 'SRID=4;POINT(0 0)'::geometry; geometry ---------------------------------------------------- 01010000200400000000000000000000000000000000000000
PostGIS EWKT output has a few differences to OGC WKT:
For 3DZ geometries the Z qualifier is omitted:
OGC: POINT Z (1 2 3)
EWKT: POINT (1 2 3)
For 3DM geometries the M qualifier is included:
OGC: POINT M (1 2 3)
EWKT: POINTM (1 2 3)
For 4D geometries the ZM qualifier is omitted:
OGC: POINT ZM (1 2 3 4)
EWKT: POINT (1 2 3 4)
EWKT avoids over-specifying dimensionality and the inconsistencies that can occur with the OGC/ISO format, such as:
POINT ZM (1 1)
POINT ZM (1 1 1)
POINT (1 1 1 1)
![]() | |
PostGIS extended formats are currently a superset of the OGC ones, so that every valid OGC WKB/WKT is also valid EWKB/EWKT. However, this might vary in the future, if the OGC extends a format in a way that conflicts with the PosGIS definition. Thus you SHOULD NOT rely on this compatibility! |
Examples of the EWKT text representation of spatial objects are:
POINT(0 0 0) -- XYZ
SRID=32632;POINT(0 0) -- XY with SRID
POINTM(0 0 0) -- XYM
POINT(0 0 0 0) -- XYZM
SRID=4326;MULTIPOINTM(0 0 0,1 2 1) -- XYM with SRID
MULTILINESTRING((0 0 0,1 1 0,1 2 1),(2 3 1,3 2 1,5 4 1))
POLYGON((0 0 0,4 0 0,4 4 0,0 4 0,0 0 0),(1 1 0,2 1 0,2 2 0,1 2 0,1 1 0))
MULTIPOLYGON(((0 0 0,4 0 0,4 4 0,0 4 0,0 0 0),(1 1 0,2 1 0,2 2 0,1 2 0,1 1 0)),((-1 -1 0,-1 -2 0,-2 -2 0,-2 -1 0,-1 -1 0)))
GEOMETRYCOLLECTIONM( POINTM(2 3 9), LINESTRINGM(2 3 4, 3 4 5) )
MULTICURVE( (0 0, 5 5), CIRCULARSTRING(4 0, 4 4, 8 4) )
POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )
TRIANGLE ((0 0, 0 10, 10 0, 0 0))
TIN( ((0 0 0, 0 0 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 0 0 0)) )
Input and output using these formats is available using the following functions:
bytea EWKB = ST_AsEWKB(geometry); text EWKT = ST_AsEWKT(geometry); geometry = ST_GeomFromEWKB(bytea EWKB); geometry = ST_GeomFromEWKT(text EWKT);
For example, a statement to create and insert a PostGIS spatial object using EWKT is:
INSERT INTO geotable ( geom, name ) VALUES ( ST_GeomFromEWKT('SRID=312;POINTM(-126.4 45.32 15)'), 'A Place' )
The PostGIS geography
data type provides native support for spatial features represented on "geographic" coordinates (sometimes called "geodetic" coordinates, or "lat/lon", or "lon/lat"). Geographic coordinates are spherical coordinates expressed in angular units (degrees).
The basis for the PostGIS geometry data type is a plane. The shortest path between two points on the plane is a straight line. That means functions on geometries (areas, distances, lengths, intersections, etc) are calculated using straight line vectors and cartesian mathematics. This makes them simpler to implement and faster to execute, but also makes them inaccurate for data on the spheroidal surface of the earth.
The PostGIS geography data type is based on a spherical model. The shortest path between two points on the sphere is a great circle arc. Functions on geographies (areas, distances, lengths, intersections, etc) are calculated using arcs on the sphere. By taking the spheroidal shape of the world into account, the functions provide more accurate results.
Because the underlying mathematics is more complicated, there are fewer functions defined for the geography type than for the geometry type. Over time, as new algorithms are added the capabilities of the geography type will expand. As a workaround one can convert back and forth between geometry and geography types.
Like the geometry data type, geography data is associated with a spatial reference system via a spatial reference system identifier (SRID). Any geodetic (long/lat based) spatial reference system defined in the spatial_ref_sys
table can be used. (Prior to PostGIS 2.2, the geography type supported only WGS 84 geodetic (SRID:4326)). You can add your own custom geodetic spatial reference system as described in Section 4.5.2, “User-Defined Spatial Reference Systems”.
For all spatial reference systems the units returned by measurement functions (e.g. ST_Distance, ST_Length, ST_Perimeter, ST_Area) and for the distance argument of ST_DWithin are in meters.
You can create a table to store geography data using the CREATE TABLE SQL statement with a column of type geography
. The following example creates a table with a geography column storing 2D LineStrings in the WGS84 geodetic coordinate system (SRID 4326):
CREATE TABLE global_points ( id SERIAL PRIMARY KEY, name VARCHAR(64), location geography(POINT,4326) );
The geography type supports two optional type modifiers:
the spatial type modifier restricts the kind of shapes and dimensions allowed in the column. Values allowed for the spatial type are: POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING, MULTIPOLYGON, GEOMETRYCOLLECTION. The geography type does not support curves, TINS, or POLYHEDRALSURFACEs. The modifier supports coordinate dimensionality restrictions by adding suffixes: Z, M and ZM. For example, a modifier of 'LINESTRINGM' only allows linestrings with three dimensions, and treats the third dimension as a measure. Similarly, 'POINTZM' requires four dimensional (XYZM) data.
the SRID modifier restricts the spatial reference system SRID to a particular number. If omitted, the SRID defaults to 4326 (WGS84 geodetic), and all calculations are performed using WGS84.
Examples of creating tables with geography columns:
Create a table with 2D POINT geography with the default SRID 4326 (WGS84 long/lat):
CREATE TABLE ptgeogwgs(gid serial PRIMARY KEY, geog geography(POINT) );
Create a table with 2D POINT geography in NAD83 longlat:
CREATE TABLE ptgeognad83(gid serial PRIMARY KEY, geog geography(POINT,4269) );
Create a table with 3D (XYZ) POINTs and an explicit SRID of 4326:
CREATE TABLE ptzgeogwgs84(gid serial PRIMARY KEY, geog geography(POINTZ,4326) );
Create a table with 2D LINESTRING geography with the default SRID 4326:
CREATE TABLE lgeog(gid serial PRIMARY KEY, geog geography(LINESTRING) );
Create a table with 2D POLYGON geography with the SRID 4267 (NAD 1927 long lat):
CREATE TABLE lgeognad27(gid serial PRIMARY KEY, geog geography(POLYGON,4267) );
Geography fields are registered in the geography_columns
system view. You can query the geography_columns
view and see that the table is listed:
SELECT * FROM geography_columns;
Creating a spatial index works the same as for geometry columns. PostGIS will note that the column type is GEOGRAPHY and create an appropriate sphere-based index instead of the usual planar index used for GEOMETRY.
-- Index the test table with a spherical index CREATE INDEX global_points_gix ON global_points USING GIST ( location );
You can insert data into geography tables in the same way as geometry. Geometry data will autocast to the geography type if it has SRID 4326. The EWKT and EWKB formats can also be used to specify geography values.
-- Add some data into the test table INSERT INTO global_points (name, location) VALUES ('Town', 'SRID=4326;POINT(-110 30)'); INSERT INTO global_points (name, location) VALUES ('Forest', 'SRID=4326;POINT(-109 29)'); INSERT INTO global_points (name, location) VALUES ('London', 'SRID=4326;POINT(0 49)');
Any geodetic (long/lat) spatial reference system listed in spatial_ref_sys
table may be specified as a geography SRID. Non-geodetic coordinate systems raise an error if used.
-- NAD 83 lon/lat SELECT 'SRID=4269;POINT(-123 34)'::geography; geography ---------------------------------------------------- 0101000020AD1000000000000000C05EC00000000000004140
-- NAD27 lon/lat SELECT 'SRID=4267;POINT(-123 34)'::geography; geography ---------------------------------------------------- 0101000020AB1000000000000000C05EC00000000000004140
-- NAD83 UTM zone meters - gives an error since it is a meter-based planar projection SELECT 'SRID=26910;POINT(-123 34)'::geography; ERROR: Only lon/lat coordinate systems are supported in geography.
Las consultas y las funciones de medidas utilizan metros cho unidad. Asi que los parámetros de distancia deben estar expresados en metros, y los valores devueltos deben estar expresados en metros (o metros cuadrados para áreas)
-- A distance query using a 1000km tolerance SELECT name FROM global_points WHERE ST_DWithin(location, 'SRID=4326;POINT(-110 29)'::geography, 1000000);
You can see the power of geography in action by calculating how close a plane flying a great circle route from Seattle to London (LINESTRING(-122.33 47.606, 0.0 51.5)) comes to Reykjavik (POINT(-21.96 64.15)) (map the route).
The geography type calculates the true shortest distance of 122.235 km over the sphere between Reykjavik and the great circle flight path between Seattle and London.
-- Distance calculation using GEOGRAPHY SELECT ST_Distance('LINESTRING(-122.33 47.606, 0.0 51.5)'::geography, 'POINT(-21.96 64.15)'::geography); st_distance ----------------- 122235.23815667
The geometry type calculates a meaningless cartesian distance between Reykjavik and the straight line path from Seattle to London plotted on a flat map of the world. The nominal units of the result is "degrees", but the result doesn't correspond to any true angular difference between the points, so even calling them "degrees" is inaccurate.
-- Distance calculation using GEOMETRY SELECT ST_Distance('LINESTRING(-122.33 47.606, 0.0 51.5)'::geometry, 'POINT(-21.96 64.15)'::geometry); st_distance -------------------- 13.342271221453624
The geography data type allows you to store data in longitude/latitude coordinates, but at a cost: there are fewer functions defined on GEOGRAPHY than there are on GEOMETRY; those functions that are defined take more CPU time to execute.
The data type you choose should be determined by the expected working area of the application you are building. Will your data span the globe or a large continental area, or is it local to a state, county or municipality?
Si tus datos están un área pequeña, la mejor solución seria elegir una proyección adecuada y utilizando GEOMETRY, en términos de rendimiento y funcionalidades disponibles.
Si tus datos son globales o cubren una región continental, veras que GEOGRAPHY te permite construir un sistema sin tener que preocuparte sobre detalles de proyección. Almacenas tus datos en longitud/latitud, y utilizas las funciones definidas en GEOGRAPHY.
Si no entiendes las proyecciones, y no quieres aprender sobre ellas, y estas preparado a aceptar las funcionalidades limitadas disponibles en GEOGRAPHY, entonces sera mas fácil para ti, utilizar GEOGRAPHY en lugar de GEOMETRY. Simplemente carga tus datos como longitud/latitud y continua desde allí.
Para tener una comparación entre lo que esta soportado entre Geography y Geometry ve a Section 15.11, “PostGIS Function Support Matrix”. Para obtener una lista con la descripción de las funciones Geography ve a Section 15.4, “PostGIS Geography Support Functions”
4.3.4.1. | ¿Se calcula en la esfera o en el esferoide? |
Por defecto, todos los cálculos de distancia y área están hechos sobre el esferoide. Deberías ver que los resultados de los cálculos en áreas locales deberán coincidir con los resultados en coordenadas locales planas con proyecciones locales correctas. En grandes áreas, los cálculos esferoidales serán mas precisas que cualquier calculo realizado en planas. Todas las funciones "geography" tienen la opción de utilizar el calculo sobre la esfera, seleccionando el parámetro final boleano a 'FALSE'. Esto puede acelerar los cálculos, particularmente en casos donde las geometrias son muy simples. | |
4.3.4.2. | ¿Que ocurre con los husos horarios y los polos? |
Todos los cálculos no tienen nociones de husos horarios o polos, las coordenadas son esféricas(longitud/latitud) así que una forma que atraviesa husos horarios no es, desde un punto de vista de los cálculos, a cualquier otra forma. | |
4.3.4.3. | ¿Cual es el arco mas largo que se pude procesar? |
Utilizamos grandes arcos de circulo como la "linea de interpolación" entre dos puntos. Esto significa que actualmente, dos puntos se unen de dos formas, dependiendo de la dirección del viaje sobre el arco. Todo nuestro código asume que los puntos están unidos por el *mas corto* de los dos caminos a traves del arco de circunferencia. Como consecuencia, las formas que tienen arcos mayores de 180 grados no serán modeladas correctamente. | |
4.3.4.4. | ¿ Por que es tan lento el calculo del area de Europa / Rusia / añade una región geográfica grande aquí? |
¡Por que el poligono es condenadamente grande! Las grandes áreas son malas por dos razones: Sus limites son grandes, así que el indice tiende a tirar de la función sin importar la consulta que estes ejecutando; el numero de vértices es grande, y los tests (distancia, de contención) tiene que recorrer la lista de vértices al menos una vez y a veces N veces ( con N igual al numero de vértices en el otro objeto candidato). 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 son simples simple si dos coordenadas (POINT
s) no son iguales (tienen valores de coordenadas identicos).
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.
La representación Well-Known Text del Sistema de Referencia Espacial (SRS). Un ejemplo de representación WKT SRS es:
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).
El nombre de la columna de geometrías de la tabla de objetos espaciales.
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”).
El tipo de objeto espacial. Para restringir la columna espacial a un tipo unico, utiliza uno de: POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING, MULTIPOLYGON, GEOMETRYCOLLECTION o su version correspondiente de XYM POINTM, LINESTRINGM, POLYGONM, MULTIPOINTM, MULTILINESTRINGM, MULTIPOLYGONM, GEOMETRYCOLLECTIONM. Para colecciones heterogéneas (tipos mixtos), puedes utilizar "GEOMETRY" como tipo.
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);
Si ejecutamos en psql
\d pois_ny;
Vemos que están definidas de forma diferente -- una es typmod, la otra por restricciones.
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)
En geometry_columns, ambas se registran de forma correcta
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
De todas formas -- si queremos crear una vista de la siguiente forma
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';
La columna de la vista basada en typmos se registra de forma correcta, pero la basada en restricciones no.
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.
Solo produce el código del comando SQL de creación de la tabla, sin añadir ningún dato. Esto puede utilizarse si necesitas separar completamente los pasos de creación de la tabla y de carga de datos
Muestra la ayuda en pantalla.
Utiliza el formato "dump" de PostgreSQL en la salida de datos. Esto puede combinarse con -a, -c, y -d. Es mucho mas rápido cargar este fichero "dump" que utilizando en comando SQL "INSERT" por defecto. Utiliza esto ara grandes conjuntos de datos.
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.
Mantiene las mayúsculas en los identificadores (columnas, esquemas y atributos). Observa que los atributos en los shapefiles están siempre en MAYÚSCULAS.
Fuerza la creación de enteros a enteros estándar de 32-bits, no crea enteros bigint de 64-bits, aunque la firma de la cabecera del DBF parezca que lo garantiza.
Crea un indice GiST de la columna de geometrias.
-m a_file_name
Especifica un fichero que contiene un conjunto de asignaciones de nombres (largos) de columnas a nombres de columna DBF de 10 caracteres. El contenido del archivo es una o más líneas de dos nombres separados por espacios en blanco y no se arrastra o espacio inicial. Por ejemplo:
COLUMNNAME DBFFIELD1 AVERYLONGCOLUMNNAME DBFFIELD2
Genera geometrías simples en lugar de MULTI geometrías. Solo funcionará si todas las geometrias son actualmente simples (I.E. un MULTIPOLYGON con una única capa, o un MULTIPOINT con un único vértice).
Fuerza a que la geometría de salida tenga la dimensión especificada. Utiliza las siguientes cadenas para indicar la dimensión: 2D, 3DZ, 3DM, 4D.
Si la entrada tiene menos dimensiones de las especificadas, la salida tendrá estas dimensiones rellenas con ceros. Si la entrada tiene mas dimensiones de las especificadas, las dimensiones no deseadas se eliminarán.
Salida en formato WKT, en vez de WKB. Observa que esto puede introducir derivas en las coordenadas debido a la perdida de precisión.
Ejecuta cada sentencia una por una, sin utilizar una transacción. Esto permite cargar la mayoría de datos correctos cuando existen algunas geometrías no validas que generan errores. Observa que esta opción no se puede utilizar con -D ya que el formato "dump" siempre utiliza transacciones.
Especifica la codificación de los datos de entrada (fichero dbf). Cuando se utiliza, todos los atributos del fichero dbf son convertidos desde la codificación especificada a UTF8. La salida SQL resultante contendrá un comando SET CLIENT_ENCODING to UTF8
, así que el backend sera capaz de reconvertir desde UTF8 a cualquier codificación que este configurada en la base de datos para uso interno.
Políticas de gestión de geometrías NULL (insert*, skip, abort)
-n solo importa los ficheros dbf. Si tus datos no tienen shapefiles correspondientes, se cambiara de forma automática a este modo y se cargara únicamente el dbf. Así que esta opción solo se necesita si lo unifico que quieres cargar son los atributos y no las geometrías.
Utiliza el tipo "geography" en lugar del tipo "geometry" (requiere datos en lon/lat) en WGS84 long lat (SRID=4326)
Especifica el "tablespace" para la nueva tabla.Los indices seguirán utilizando el "tablespace" por defecto a menos que el parámetro -X este en uso. La documentación de PostgreSQL tiene una buena descripción de los "tablespaces" personalizados.
Especifica el "tablespace" para los indices de la nueva tabla. Esto se aplica a los indices de clave primaria y a los indices espaciales GiST si se usa también la opción -l.
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.
Este test comprueba si dos geometrías son geométricamente idénticas. Por ejemplo, si 'POLYGON((0 0,1 1,1 0,0 0))' es la misma que 'POLYGON((0 0,1 1,1 0,0 0))' (si que lo es).
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;
La consulta anterior deberá devolver el único registro de la tabla "ROADS_GEOM" cuya geometría era igual a este valor.
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.
Cuando utilizamos el operador "&&", puedes especificar ya sea un BOX3D como la función de comparación o una GEOMETRY. Cuando se especifica una geometría, sin embargo, se utiliza para la comparación su cuadro delimitador (bounding box).
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);
Observa el uso del SRID 123, para espeficar la proyección de la envolvente.
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>
Las opciones del comando son:
Escribe la salida en un fichero con un nombre particular
Especifica el servidor al que conectarse.
Especifica el puerto del servidor de la base de datos al que conectarse.
La contraseña a utilizar en la conexión de la base de datos.
El nombre del usuario a utilizar en la conexión a la base de datos.
En el caso que las tablas tengan varias columnas de geometrías, la columna de geometrías a utilizar cuando se escriba el fichero shape.
Utiliza un cursor binario. Esto hada las operaciones mas rápido, pero no funcionará si algún atributo NO-geométrico de la tabla carece de conversion a texto.
Modo Raw. No suprime el campo gid
, o omite los nombres de las columnas.
filename
Reasignar los identificadores de diez nombres de los personajes. El contenido del archivo son líneas de dos símbolos separados por un único espacio en blanco y sin espacios al final, o al inicio: 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).
La sintaxis para la creación de un indice GiST en una columna "geometry" es como sigue:
CREATE INDEX [indexname] ON [tablename] USING GIST ( [geometryfield] );
The above syntax will always build a 2D-index. To get the an n-dimensional index for the geometry type, you can create one using this syntax:
CREATE INDEX [indexname] ON [tablename] USING GIST ([geometryfield] gist_geometry_ops_nd);
Building a spatial index is a computationally intensive exercise. It also blocks write access to your table for the time it creates, so on a production system you may want to do in in a slower CONCURRENTLY-aware way:
CREATE INDEX CONCURRENTLY [indexname] ON [tablename] USING GIST ( [geometryfield] );
After building an index, it is sometimes helpful to force PostgreSQL to collect table statistics, which are used to optimize query plans:
VACUUM ANALYZE [table_name] [(column_name)];
BRIN stands for "Block Range Index". It is a general-purpose index method introduced in PostgreSQL 9.5. BRIN is a lossy index method, meaning that a secondary check is required to confirm that a record matches a given search condition (which is the case for all provided spatial indexes). It provides much faster index creation and much smaller index size, with reasonable read performance. Its primary purpose is to support indexing very large tables on columns which have a correlation with their physical location within the table. In addition to spatial indexing, BRIN can speed up searches on various kinds of attribute data structures (integer, arrays etc). For more information see the PostgreSQL manual.
Once a spatial table exceeds a few thousand rows, you will want to build an index to speed up spatial searches of the data. GiST indexes are very performant as long as their size doesn't exceed the amount of RAM available for the database, and as long as you can afford the index storage size, and the cost of index update on write. Otherwise, for very large tables BRIN index can be considered as an alternative.
A BRIN index stores the bounding box enclosing all the geometries contained in the rows in a contiguous set of table blocks, called a block range. When executing a query using the index the block ranges are scanned to find the ones that intersect the query extent. This is efficient only if the data is physically ordered so that the bounding boxes for block ranges have minimal overlap (and ideally are mutually exclusive). The resulting index is very small in size, but is typically less performant for read than a GiST index over the same data.
Building a BRIN index is much less CPU-intensive than building a GiST index. It's common to find that a BRIN index is ten times faster to build than a GiST index over the same data. And because a BRIN index stores only one bounding box for each range of table blocks, it's common to use up to a thousand times less disk space than a GiST index.
You can choose the number of blocks to summarize in a range. If you decrease this number, the index will be bigger but will probably provide better performance.
For BRIN to be effective, the table data should be stored in a physical order which minimizes the amount of block extent overlap. It may be that the data is already sorted appropriately (for instance, if it is loaded from another dataset that is already sorted in spatial order). Otherwise, this can be accomplished by sorting the data by a one-dimensional spatial key. One way to do this is to create a new table sorted by the geometry values (which in recent PostGIS versions uses an efficient Hilbert curve ordering):
CREATE TABLE table_sorted AS SELECT * FROM table ORDER BY geom;
Alternatively, data can be sorted in-place by using a GeoHash as a (temporary) index, and clustering on that index:
CREATE INDEX idx_temp_geohash ON table USING btree (ST_GeoHash( ST_Transform( geom, 4326 ), 20)); CLUSTER table USING idx_temp_geohash;
The syntax for building a BRIN index on a geometry
column is:
CREATE INDEX [indexname] ON [tablename] USING BRIN ( [geome_col] );
The above syntax builds a 2D index. To build a 3D-dimensional index, use this syntax:
CREATE INDEX [indexname] ON [tablename] USING BRIN ([geome_col] brin_geometry_inclusion_ops_3d);
You can also get a 4D-dimensional index using the 4D operator class:
CREATE INDEX [indexname] ON [tablename] USING BRIN ([geome_col] brin_geometry_inclusion_ops_4d);
The above commands use the default number of blocks in a range, which is 128. To specify the number of blocks to summarise in a range, use this syntax
CREATE INDEX [indexname] ON [tablename] USING BRIN ( [geome_col] ) WITH (pages_per_range = [number]);
Keep in mind that a BRIN index only stores one index entry for a large number of rows. If your table stores geometries with a mixed number of dimensions, it's likely that the resulting index will have poor performance. You can avoid this performance penalty by choosing the operator class with the least number of dimensions of the stored geometries
The geography
datatype is supported for BRIN indexing. The syntax for building a BRIN index on a geography column is:
CREATE INDEX [indexname] ON [tablename] USING BRIN ( [geog_col] );
The above syntax builds a 2D-index for geospatial objects on the spheroid.
Currently, only "inclusion support" is provided, meaning that just the &&
, ~
and @
operators can be used for the 2D cases (for both geometry
and geography
), and just the &&&
operator for 3D geometries. There is currently no support for kNN searches.
An important difference between BRIN and other index types is that the database does not maintain the index dynamically. Changes to spatial data in the table are simply appended to the end of the index. This will cause index search performance to degrade over time. The index can be updated by performing a VACUUM
, or by using a special function brin_summarize_new_values(regclass)
. For this reason BRIN may be most appropriate for use with data that is read-only, or only rarely changing. For more information refer to the manual.
To summarize using BRIN for spatial data:
Index build time is very fast, and index size is very small.
Index query time is slower than GiST, but can still be very acceptable.
Requires table data to be sorted in a spatial ordering.
Requires manual index maintenance.
Most appropriate for very large tables, with low or no overlap (e.g. points), which are static or change infrequently.
More effective for queries which return relatively large numbers of data records.
SP-GiST stands for "Space-Partitioned Generalized Search Tree" and is a generic form of indexing for multi-dimensional data types that supports partitioned search trees, such as quad-trees, k-d trees, and radix trees (tries). The common feature of these data structures is that they repeatedly divide the search space into partitions that need not be of equal size. In addition to spatial indexing, SP-GiST is used to speed up searches on many kinds of data, such as phone routing, ip routing, substring search, etc. For more information see the PostgreSQL manual.
As it is the case for GiST indexes, SP-GiST indexes are lossy, in the sense that they store the bounding box enclosing spatial objects. SP-GiST indexes can be considered as an alternative to GiST indexes.
Once a GIS data table exceeds a few thousand rows, an SP-GiST index may be used to speed up spatial searches of the data. The syntax for building an SP-GiST index on a "geometry" column is as follows:
CREATE INDEX [indexname] ON [tablename] USING SPGIST ( [geometryfield] );
The above syntax will build a 2-dimensional index. A 3-dimensional index for the geometry type can be created using the 3D operator class:
CREATE INDEX [indexname] ON [tablename] USING SPGIST ([geometryfield] spgist_geometry_ops_3d);
Building a spatial index is a computationally intensive operation. It also blocks write access to your table for the time it creates, so on a production system you may want to do in in a slower CONCURRENTLY-aware way:
CREATE INDEX CONCURRENTLY [indexname] ON [tablename] USING SPGIST ( [geometryfield] );
After building an index, it is sometimes helpful to force PostgreSQL to collect table statistics, which are used to optimize query plans:
VACUUM ANALYZE [table_name] [(column_name)];
An SP-GiST index can accelerate queries involving the following operators:
<<, &<, &>, >>, <<|, &<|, |&>, |>>, &&, @>, <@, and ~=, for 2-dimensional indexes,
&/&, ~==, @>>, and <<@, for 3-dimensional indexes.
There is no support for kNN searches at the moment.
Ordinarily, indexes invisibly speed up data access: once an index is built, the PostgreSQL query planner automatically decides when to use it to improve query performance. But there are some situations where the planner does not choose to use existing indexes, so queries end up using slow sequential scans instead of a spatial index.
If you find your spatial indexes are not being used, there are a few things you can do:
Examine the query plan and check your query actually computes the thing you need. An erroneous JOIN, either forgotten or to the wrong table, can unexpectedly retrieve table records multiple times. To get the query plan, execute with EXPLAIN
in front of the query.
Make sure statistics are gathered about the number and distributions of values in a table, to provide the query planner with better information to make decisions around index usage. VACUUM ANALYZE will compute both.
You should regularly vacuum your databases anyways. Many PostgreSQL DBAs run VACUUM as an off-peak cron job on a regular basis.
If vacuuming does not help, you can temporarily force the planner to use the index information by using the command SET ENABLE_SEQSCAN TO OFF;. This way you can check whether the planner is at all able to generate an index-accelerated query plan for your query. You should only use this command for debugging; generally speaking, the planner knows better than you do about when to use indexes. Once you have run your query, do not forget to run SET ENABLE_SEQSCAN TO ON; so that the planner will operate normally for other queries.
If SET ENABLE_SEQSCAN TO OFF; helps your query to run faster, your Postgres is likely not tuned for your hardware. If you find the planner wrong about the cost of sequential versus index scans try reducing the value of RANDOM_PAGE_COST
in postgresql.conf
, or use SET RANDOM_PAGE_COST TO 1.1;. The default value for RANDOM_PAGE_COST
is 4.0. Try setting it to 1.1 (for SSD) or 2.0 (for fast magnetic disks). Decreasing the value makes the planner more likely to use index scans.
If SET ENABLE_SEQSCAN TO OFF; does not help your query, the query may be using a SQL construct that the Postgres planner is not yet able to optimize. It may be possible to rewrite the query in a way that the planner is able to handle. For example, a subquery with an inline SELECT may not produce an efficient plan, but could possibly be rewritten using a LATERAL JOIN.
For more information see the Postgres manual section on Query Planning.
The raison d'etre of spatial databases is to perform queries inside the database which would ordinarily require desktop GIS functionality. Using PostGIS effectively requires knowing what spatial functions are available, how to use them in queries, and ensuring that appropriate indexes are in place to provide good performance.
Spatial relationships indicate how two geometries interact with one another. They are a fundamental capability for querying geometry.
According to the OpenGIS Simple Features Implementation Specification for SQL, "the basic approach to comparing two geometries is to make pair-wise tests of the intersections between the Interiors, Boundaries and Exteriors of the two geometries and to classify the relationship between the two geometries based on the entries in the resulting 'intersection' matrix."
In the theory of point-set topology, the points in a geometry embedded in 2-dimensional space are categorized into three sets:
The boundary of a geometry is the set of geometries of the next lower dimension. For POINT
s, which have a dimension of 0, the boundary is the empty set. The boundary of a LINESTRING
is the two endpoints. For POLYGON
s, the boundary is the linework of the exterior and interior rings.
The interior of a geometry are those points of a geometry that are not in the boundary. For POINT
s, the interior is the point itself. The interior of a LINESTRING
is the set of points between the endpoints. For POLYGON
s, the interior is the areal surface inside the polygon.
The exterior of a geometry is the rest of the space in which the geometry is embedded; in other words, all points not in the interior or on the boundary of the geometry. It is a 2-dimensional non-closed surface.
The Dimensionally Extended 9-Intersection Model (DE-9IM) describes the spatial relationship between two geometries by specifying the dimensions of the 9 intersections between the above sets for each geometry. The intersection dimensions can be formally represented in a 3x3 intersection matrix.
For a geometry g the Interior, Boundary, and Exterior are denoted using the notation I(g), B(g), and E(g). Also, dim(s) denotes the dimension of a set s with the domain of {0,1,2,F}
:
0
=> point
1
=> line
2
=> area
F
=> empty set
Using this notation, the intersection matrix for two geometries a and b is:
Interior | Boundary | Exterior | |
---|---|---|---|
Interior | dim( I(a) ∩ I(b) ) | dim( I(a) ∩ B(b) ) | dim( I(a) ∩ E(b) ) |
Boundary | dim( B(a) ∩ I(b) ) | dim( B(a) ∩ B(b) ) | dim( B(a) ∩ E(b) ) |
Exterior | dim( E(a) ∩ I(b) ) | dim( E(a) ∩ B(b) ) | dim( E(a) ∩ E(b) ) |
Visually, for two overlapping polygonal geometries, this looks like:
| ||||||||||||||||||
|
|
Reading from left to right and top to bottom, the intersection matrix is represented as the text string '212101212'.
For more information, refer to:
To make it easy to determine common spatial relationships, the OGC SFS defines a set of named spatial relationship predicates. PostGIS provides these as the functions ST_Contains, ST_Crosses, ST_Disjoint, ST_Equals, ST_Intersects, ST_Overlaps, ST_Touches, ST_Within. It also defines the non-standard relationship predicates ST_Covers, ST_CoveredBy, and ST_ContainsProperly.
Spatial predicates are usually used as conditions in SQL WHERE
or JOIN
clauses. The named spatial predicates automatically use a spatial index if one is available, so there is no need to use the bounding box operator &&
as well. For example:
SELECT city.name, state.name, city.geom FROM city JOIN state ON ST_Intersects(city.geom, state.geom);
For more details and illustrations, see the PostGIS Workshop.
In some cases the named spatial relationships are insufficient to provide a desired spatial filter condition.
![]() For example, consider a linear dataset representing a road network. It may be required to identify all road segments that cross each other, not at a point, but in a line (perhaps to validate some business rule). In this case ST_Crosses does not provide the necessary spatial filter, since for linear features it returns A two-step solution would be to first compute the actual intersection (ST_Intersection) of pairs of road lines that spatially intersect (ST_Intersects), and then check if the intersection's ST_GeometryType is ' Clearly, a simpler and faster solution is desirable. |
![]() A second example is locating wharves that intersect a lake's boundary on a line and where one end of the wharf is up on shore. In other words, where a wharf is within but not completely contained by a lake, intersects the boundary of a lake on a line, and where exactly one of the wharf's endpoints is within or on the boundary of the lake. It is possible to use a combination of spatial predicates to find the required features:
|
These requirements can be met by computing the full DE-9IM intersection matrix. PostGIS provides the ST_Relate function to do this:
SELECT ST_Relate( 'LINESTRING (1 1, 5 5)', 'POLYGON ((3 3, 3 7, 7 7, 7 3, 3 3))' ); st_relate ----------- 1010F0212
To test a particular spatial relationship, an intersection matrix pattern is used. This is the matrix representation augmented with the additional symbols {T,*}
:
T
=> intersection dimension is non-empty; i.e. is in {0,1,2}
*
=> don't care
Using intersection matrix patterns, specific spatial relationships can be evaluated in a more succinct way. The ST_Relate and the ST_RelateMatch functions can be used to test intersection matrix patterns. For the first example above, the intersection matrix pattern specifying two lines intersecting in a line is '1*1***1**':
-- Find road segments that intersect in a line SELECT a.id FROM roads a, roads b WHERE a.id != b.id AND a.geom && b.geom AND ST_Relate(a.geom, b.geom, '1*1***1**');
For the second example, the intersection matrix pattern specifying a line partly inside and partly outside a polygon is '102101FF2':
-- Find wharves partly on a lake's shoreline SELECT a.lake_id, b.wharf_id FROM lakes a, wharfs b WHERE a.geom && b.geom AND ST_Relate(a.geom, b.geom, '102101FF2');
When constructing queries using spatial conditions, for best performance it is important to ensure that a spatial index is used, if one exists (see Section 4.9, “Spatial Indexes”). To do this, a spatial operator or index-aware function must be used in a WHERE
or ON
clause of the query.
Spatial operators include the bounding box operators (of which the most commonly used is &&; see Section 8.10.1, “Bounding Box Operators” for the full list) and the distance operators used in nearest-neighbor queries (the most common being <->; see Section 8.10.2, “Operadores” 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)
Versiones actuales de PostgreSQL (incluyendo la 8.0) tienen algunas debilidades en la optimización de consultas respecto a tablas TOAST. Las tablas TOAST son una especie de "cámara de extensiones" utilizadas para almacenar valores grandes (en sentido de tamaño de datos) que no se pueden mostrar en paginas de datos (como textos largos, imágenes o geometrías complejas con muchos vértices). Para mas información visita the PostgreSQL Documentation for TOAST
El problema aparece si ocurre que tienes una tabla con geometrías bastante grandes, pero no demasiadas filas de ellas (como una tabla que contiene los límites de todos los países europeos en alta resolución). A continuación, la tabla en sí es pequeña, pero utiliza una gran cantidad de espacio TOAST. En nuestro caso de ejemplo, la tabla en sí tenía alrededor de 80 filas y se utiliza sólo 3 páginas de datos, pero la tabla TOAST utiliza 8225 páginas.
Ahora al emitir una consulta en la que utilizas el operador geométrico && para buscar un límite que coincide sólo unas pocas de esas filas, el optimizador de consultas ve que la tabla sólo tiene 3 páginas y 80 filas. Se estima que un escaseo secuencial en una tabla pequeña de este tipo es mucho más rápida que usando un índice. Y por lo que decide ignorar el índice de GIST. Por lo general, esta estimación es correcta. Pero en nuestro caso, el operador && tiene que buscar en cada geometría del disco la comparación de los limites, y leer todas las páginas TOAST también.
Para comprobar si padeces de este error, utiliza el comando "EXPLAIN ANALYZE" postgresql. Para obtener más información y los detalles técnicos, puedes leer el hilo en la lista de correo de rendimiento postgres: http://archives.postgresql.org/pgsql-performance/2005-02/msg00030.php
and newer thread on PostGIS https://lists.osgeo.org/pipermail/postgis-devel/2017-June/026209.html
La gente de PostgreSQL esta intentando resolver este problema haciendo la estimación de la consulta compatible con TOAST. Por el momento, aquí van dos soluciones provisionales:
La primera consiste en forzar la consulta a utilizar indices. Envia "SET enable_seqscan TO off;" al servidor antes de ejecutar la consulta. Esto, básicamente fuerza al planificador de consultas a evitar exploraciones secuenciales siempre que sea posible. Por lo tanto, utiliza el índice GIST como de costumbre. Pero este comando debe ser establecido en cada conexión, y hace que el planeador de consultas cometa errores de estimación en otros casos, por lo que debes enviar al servidor "SET enable_seqscan TO on;" después de la consulta.
La segunda solución es hacer el escaseo secuencia tan rápido como el planificador de consultas cree. Esto, se puede lograr creando una consulta que "cachee" los limites o bbox, y hacer coincidir en contra de esta. En nuestro ejemplo, los comandos son:
SELECT AddGeometryColumn('myschema','mytable','bbox','4326','GEOMETRY','2'); UPDATE mytable SET bbox = ST_Envelope(ST_Force_2d(the_geom));
Ahora cambia tu consulta para utilizar el operador espacial && con bbox en vez de geom_column, así:
SELECT geom_column FROM mytable WHERE bbox && ST_SetSRID('BOX3D(0 0,1 1)'::box3d,4326);
Por supuesto, si añades o cambias filas de "mutable", tienes que mantener el campo bbox sincronizado. La forma mas transparente de hacerlo son los triggers o funciones disparadoras, pero también puedes modificar tu aplicación para mantener la columna bbox o ejecutar la consulta UPDATE siguiente después de cada modificación.
Para las tablas que en su mayoría son de sólo lectura, y donde se utiliza un índice único para la mayoría de las consultas, PostgreSQL ofrece el comando CLUSTER. Este comando reordena físicamente todas las filas de datos en el mismo orden que los criterios de índice, dando dos ventajas de rendimiento: En primer lugar, para los recorridos de intervalo del índice, el número de búsquedas en la tabla de datos se reduce drásticamente. En segundo lugar, si el conjunto de trabajo se concentra en algunos intervalos pequeños en los índices, tienes un caché más eficiente porque las filas de datos se distribuyen a lo largo de un menor número de páginas de datos. (Te invitamos a leer la documentación de comandos CLUSTER del manual de PostgreSQL sobre este tema.)
De todas formas, PostgreSQL no permite el "clustering" en indices GiST de PostGIS por que los indices GiST simplemente ignoran los valores NULL, tendrás el siguiente mensaje de error:
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.
Como sugiere el mensaje de ayuda, podemos evitar esta deficiencia añadiendo una restricción "not null" a la tabla:
lwgeom=# ALTER TABLE my_table ALTER COLUMN the_geom SET not null; ALTER TABLE
Por supuesto, esto no funcionará si necesitas valores NULL en tu columna de geometrías. Adicionalmente, debes utilizar el método anterior para añadir la restricción, utilizando restricciones CHEK como "ALTER TABLE blubb ADD CHECK (geómetra is not nulo);" no funcionara.
A veces, sucede que tienes datos en 3D o 4D en tus tablas pero siempre, al acceder a ella utilizando funciones conformes con OpenGIS como ST_AsText () o ST_AsBinary (), sólo devuelven geometrías 2D de salida. Esto ocurre por que lo hacen llamando internamente a la función ST_Force_2d (), que introduce una sobrecarga significativa para geometrías grandes . Para evitar esta sobrecarga, puede ser factible comprobar la validez de suprimir esas dimensiones adicionales de una vez por todas:
UPDATE mytable SET the_geom = ST_Force_2d(the_geom); VACUUM FULL ANALYZE mytable;
Ten en cuenta que si las has añadido a tu columna de geometría utilizando addGeometryColumn () habrá una restricción en la dimensión de la geometría. Para pasar la restricción por alto tendrás que quitarla. Recuerda actualizar la entrada en la tabla geometry_columns y volver a crear la restricción después.
En el caso de tablas de gran tamaño, puede ser conveniente dividir este UPDATE en porciones más pequeñas, restringiendo la actualización de una parte de la tabla a través de una cláusula WHERE y su clave primaria o de otros criterios, y la ejecución de un simple "VACUUM"; entre los UPDATE. Esto reduce drásticamente la necesidad de espacio de disco temporal. Además, si has mezclado dimensiones de geometrías, que restringen el UPDATE con "WHERE dimension(the_geom)>2" salta la reescritura de geometrías que ya están en 2D.
El Minnesota MapServer es un servidor web de mapas para internet que cumple la especificación OpenGIS Web Mapping Server 'Servidor de Mapas Web'.
La página principal de MapServer está en http://mapserver.org.
La Especificación de OpenGIS para Mapas Web está en http://www.opengeospatial.org/standards/wms.
Para utilizar PostGIS con MapServer necesitará saber como configurar MapServer, lo cual está fuera del alcance de esta documentación. Esta sección cubrirá cuestiones específicas de PostGIS y detalles de su configuración.
Para usar PostGIS con MapServer, necesitará:
La versión 0.6 o posterior de PostGIS.
La versión 3.5 o posterior de MapServer.
MapServer accede a los datos de PostGIS/PostgreSQL como cualquier otro cliente de PostgreSQL -- usando la interfaz libpq
. Esto significa que MapServer puede instalarse en cualquier máquina con acceso de red al servidor PostGIS, y usar PostGIS como una fuente de datos. La conexión entre los sistemas será mejor cuanto más rápida sea ésta.
Compile e instale MapServer con las opciones que desee, incluyendo la opción de configuración "--with-postgis".
En el fichero de mapas de MapServer agregue una capa PostGIS. Por ejemplo:
LAYER CONNECTIONTYPE postgis NAME "widehighways" # Conectar a una base de datos espacial remota CONNECTION "user=dbuser dbname=gisdatabase host=bigserver" PROCESSING "CLOSE_CONNECTION=DEFER" # Obtener las filas de la columna 'geom' de la tabla 'roads' DATA "geom from roads using srid=4326 using unique gid" STATUS ON TYPE LINE # De las filas, sólo dibujar las autopistas de 4 o más carriles FILTER "type = 'highway' and numlanes >= 4" CLASS # Hacer que las superautopistas sean más brillantes y de 2 pixels de grososr EXPRESSION ([numlanes] >= 6) STYLE COLOR 255 22 22 WIDTH 2 END END CLASS # El resto son más oscuras y de sólo 1 pixel de grososr EXPRESSION ([numlanes] < 6) STYLE COLOR 205 92 82 END END END
En el ejemplo de arriba, las directivas específicas de PostGIS son:
Para las capas PostGIS, es siempre "postgis".
La conexión a la base de datos se rige por una 'cadena de conexión' que se compone de un conjunto estándar de claves y valores como (con los valores por defecto en <>):
user=<username> password=<password> dbname=<username> hostname=<server> port=<5432>
Cualquier par clave/valor puede omitirse, incluso es válida una cadena de conexión vacía. Como mínimo generalmente se proporcionará el nombre de la base de datos y el del usuario con el que conectarse.
Este parámetro toma la forma "<geocolumn> from <tablename> using srid=<srid> using unique <primary key>" donde 'geocolumn' es la columna espacial a representar en el mapa, el 'srid' es el identificador del sistema de referencia utilizado por dicha columna y la 'primary key' es la clave primaria de la tabla (o cualquier otra columna con valores únicos y un índice).
Se pueden omitir las cláusulas "using srid" y "using unique" y MapServer determinará automáticamente los valores correctos si ello es posible, pero al precio de ejecutar unas pocas consultas extra al servidor cada vez que se dibuje el mapa.
Si tenemos múltiples capas, el poner CLOSE_CONNECTION=DEFER hace que se reutilicen conexiones existentes en vez de cerrarlas. Esto mejora la velocidad. Para una explicación más detallada se puede consultar MapServer PostGIS Performance Tips.
El filtro debe ser una cadena SQL correcta que corresponda a lo que sigue habitualmente a la palabra clave "WHERE" en una consulta SQL. Así que, por ejemplo, para representar solamente carreteras con 6 o más carriles usaremos un filtro con "num_lanes >= 6".
Asegúrese de haber generado índices espaciales (GIST) en su base de datos espacial para cualquiera de las capas a ser dibujadas.
CREATE INDEX [nombreindice] ON [nombretabla] USING GIST ( [columnageometria] );
Si va a hacer consultas de las capas usando MapServer necesitará también usar la cláusula "using unique" en el enunciado DATA.
MapServer requiere identificadores únicos para cada registro espacial cuando realiza las consultas, y el módulo PostGIS de MapServer utiliza el valor único especificado para proporcionar esos identificadores únicos. La mejor práctica es el uso de la clave primaria.
Se usa la cláusula pseudo-SQL USING
para añadir alguna información que ayude a MapServer a comprender los resultados de consultas más complejas. Más específicamente, cuando se usa bien una vista o una subselección como la tabla origen (lo que está a la derecha de "FROM" en una definición DATA
) es más difícil para MapServer determinar automáticamente un identificador único para cada fila y también el SRID para la tabla. La cláusula USING
puede proporcionar a MapServer estas dos piezas de información de la siguiente manera:
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 requiere un identificador único para poder identificar la fila cuando se hacen consultas al mapa. Normalmente identifica la clave primaria de las tablas del sistema. Sin embargo, vistas y subconsultas no tienen automáticamente una columna única conocida. Si quiere usar la funcionalidad de consultas de MapServer debe asegurarse de que la vista o subconsulta incluye una columna de valores únicos, y declararla con USING UNIQUE
. Por ejemplo, podría seleccionar explícitamente valores de la clave primaria de la tabla para este propósito, o cualquier otra columna que garantice ser única para el conjunto de resultados.
![]() | |
"Consultar un mapa" es la acción de hacer click sobre un mapa para obtener información acerca de los elementos del mapa en esa posición. No confundir con "consultas al mapa" con la petición SQL en una definición |
PostGIS necesita saber qué sistema de referencia espacial están usando las geometrías para poder devolver los datos correctos a MapServer. Normalmente es posible encontrar esta información en la tabla 'geometry_columns' de la base de datos PostGIS, sin embargo esto no es posible con tablas que se crean al vuelo tal como subconsultas y vistas. Así que la opción USING SRID=
permite indicar el SRID correcto en la definición DATA
.
Comencemos con un ejemplo sencillo. Consideremos la siguiente definición de capa en MapServer:
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
Esta capa visualizará todas las geometrías de carreteras de la tabla carreteras 'roads' como líneas negras.
Ahora, digamos que queremos mostrar sólo las autopistas cuando hagamos un zoom al menos de una escala 1:100000. Las siguientes dos capas conseguirán este efecto:
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
La primera capa se usa cuando la escala es superior a 1:100000 y muestra sólo las carreteras de tipo "highway" como líneas negras. La opción FILTER
hace que sólo se visualicen las carreteras de tipo "highway".
La segunda capa se usa cuando la escala es menor de 1:100000 y mostrará las autopistas como líneas rojas de doble grueso, y las otras carreteras como líneas negras de grosor normal.
Así que, hemos hecho un par de cosas interesantes usando sólo la funcionalidad de MapServer, pero nuestra sentencia SQL DATA
ha seguido siendo sencilla. Supongamos que el nombre de las carreteras está almacenado en otra tabla (por la razón que sea) y necesitamos hacer una unión (join) para obtenerlo y etiquetar nuestras carreteras.
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
Esta capa de anotaciones añade etiquetas verdes a todas las carreteras cuando la escala baje a 1:20000 o menos. También demuestra como usar una unión (join) SQL en una definición DATA
.
Los clientes java pueden acceder a los objetos 'geometry' de PostGIS en la base de datos PostgreSQL bien directamente como representaciones en texto o usando los objetos de extensión JDBC incluídos con PostGIS. Para poder usar los objetos de extensión, el fichero "postgis.jar" debe estar en su CLASSPATH así como el paquete controlador JDBC "postgresql.jar".
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 { /* * Cargar el controlador JDBC y establecer la conexión. */ Class.forName("org.postgresql.Driver"); String url = "jdbc:postgresql://localhost:5432/database"; conn = DriverManager.getConnection(url, "postgres", ""); /* * Agregar los tipos 'geometry' a la conexión. Tenga en cuenta que * debe adaptar la conexión a la implementación de la conexión * específica pgsql antes de llamar al método addDataType(). */ ((org.postgresql.PGConnection)conn).addDataType("geometry",Class.forName("org.postgis.PGgeometry")); ((org.postgresql.PGConnection)conn).addDataType("box3d",Class.forName("org.postgis.PGbox3d")); /* * Crear una sentencia y ejecutar una consulta 'select'. */ Statement s = conn.createStatement(); ResultSet r = s.executeQuery("select geom,id from geomtable"); while( r.next() ) { /* * Recuperar la geometría como un objeto, luego convertirlo al tipo geometry. * Imprimir resultados. */ 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(); } } }
El objeto "PGeometry" es un objeto envoltorio que contiene un objeto geométrico de topología específica (subclase de la clase abstracta "Geometry") dependiendo del tipo: 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()); } } }
JavaDoc proporciona una referencia para los objetos extensión para las diferentes funciones de acceso a datos en los objetos geométricos.
...
Las siguientes funciones son las que probablemente necesite un usuario PortGIS . Existen otras funciones de soporte necesarias para los objetos PostGIS que no se usan por la mayoría de usuarios.
![]() | |
PostGIS ha comenzado una transición de la convención de nomenclatura existente, a una convención SQL-MM-céntrica. Como resultado, la mayoría de las funciones que conoces y adoras han sido renombradas usando el prefijo espacial estándar (ST). Funciones anteriores están todavía disponibles, aunque no se enumeran en este documento donde las funciones actualizadas son equivalentes. Las funciones no st_ no mencionadas en esta documentación están en desuso y se eliminarán en una versión futura de modo que DEJA DE UTILIZARLAS. |
Esta sección detalla los tipos de dato de PostgreSQL instalados por PostGIS. Note que describimos el comportamiento de la conversión de tipos en los casos en los que es muy importante, especialmente cuando se diseñe sis propias funciones.
Each data type describes its type casting behavior. A type cast converts values of one data type into another type. PostgreSQL allows defining casting behavior for custom types, along with the functions used to convert type values. Casts can have automatic behavior, which allows automatic conversion of a function argument to a type supported by the function.
Some casts have explicit behavior, which means the cast must be specified using the syntax CAST(myval As sometype)
or myval::sometype
. Explicit casting avoids the issue of ambiguous casts, which can occur when using an overloaded function which does not support a given type. For example, a function may accept a box2d or a box3d, but not a geometry. Since geometry has an automatic cast to both box types, this produces an "ambiguous function" error. To prevent the error use an explicit cast to the desired box type.
All data types can be cast to text
, so this does not need to be specified explicitly.
box2d — The type representing a 2-dimensional bounding box.
box3d es un tipo de dato espacial usado para representar la caja que contiene una geometría o un grupo de geometrías. ST_3DExtent devuelve un objecto box3d.
The representation contains the values xmin, ymin, xmax, ymax
. These are the minimum and maximum values of the X and Y extents.
box2d
objects have a text representation which looks like BOX(1 2,5 6)
.
box3d — The type representing a 3-dimensional bounding box.
box3d es un tipo de dato espacial usado para representar la caja que contiene una geometría o un grupo de geometrías. ST_3DExtent devuelve un objecto box3d.
The representation contains the values xmin, ymin, zmin, xmax, ymax, zmax
. These are the minimum and maxium values of the X, Y and Z extents.
box3d
objects have a text representation which looks like BOX3D(1 2 3,5 6 5)
.
geometry — geography es un tipo de dato espacial usado para representar una feature en un sistema de coordenadas de Tierra esférica.
geometry es un tipo de datos postgis fundamental, usado para representar una feature en un sistema de coordenadas euclidiano.
All spatial operations on geometry use the units of the Spatial Reference System the geometry is in.
geometry_dump — A composite type used to describe the parts of complex geometry.
geometry_dump
is a composite data type containing the fields:
geom
- a geometry representing a component of the dumped geometry. The geometry type depends on the originating function.
path[]
- an integer array that defines the navigation path within the dumped geometry to the geom
component. The path array is 1-based (i.e. path[1]
is the first element.)
It is used by the ST_Dump*
family of functions as an output type to explode a complex geometry into its constituent parts.
geography — The type representing spatial features with geodetic (ellipsoidal) coordinate systems.
geography es un tipo de dato espacial usado para representar una feature en un sistema de coordenadas de Tierra esférica.
Spatial operations on the geography type provide more accurate results by taking the ellipsoidal model into account.
AddGeometryColumn — Suprime una columna de geometrías de una tabla espacial.
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)
;
Añade una columna de geometría a una tabla existente de atributos. schema_name
es el nombre del esquema de la tabla. srid
debe ser una referencia de valor entero a una entrada en la tabla SPATIAL_REF_SYS. type
debe ser una cadena que corresponde al tipo de geometría, por ejemplo, 'POLYGON' or 'MULTILINESTRING'. Se lanza un error si no existe el schemaname (o no esta visible en el search_path actual) o el SRID, el tipo de geometría, o la dimensión no son validos.
![]() | |
Cambiado: 2.0.0 Esta función ya no se actualiza desde geometry_columns ya que geometry_columns es una vista que se lee dede los catálogos del sistema. Por defecto tampoco crea las restricciones, sino que utiliza el modificador de tipo de PostgreSQL. Así que para la construcción de una columna de tipo POINT en wgs84 con esta función ejemplo que hoy es equivalente a: Cambiado: 2.0.0 Si necesitas el comportamiento antiguo de restricciones, utiliza el valor predeterminado |
![]() | |
Cambiado: 2.0.0 Las Vistas ya no pueden ser registradas manualmente en geometry_columns, no obstante las vistas se que construyan a partir de geometrías typmod de las tablas de geometrías y sean utilizadas sin funciones wrapper se registraran correctamente porque heredan el comportamiento typmod de su columna de la tabla padre. Las vistas que utilizan funciones de geometría que devuelvan geometrías necesitarán de transformación cast a geometrías typmod para esta columnas de geometrías de la vista y que se registren correctamente en geometry_columns. Consulta 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
Mejorada: 2.0.0 introducción del argumento use_typmod. El valor predeterminado es crearcolumnas de geometrías basadas en typmod en lugar de las basadas en restricciones.
-- Crear esquema para contener datos CREATE SCHEMA my_schema; -- Crear una nueva tabla simple PostgreSQL CREATE TABLE my_schema.my_spatial_table (id serial); -- La descripción de la tabla muestra una tabla sencilla con una sola columna "id". postgis=# \d my_schema.my_spatial_table Table "my_schema.my_spatial_table" Column | Type | Modifiers --------+---------+------------------------------------------------------------------------- id | integer | not null default nextval('my_schema.my_spatial_table_id_seq'::regclass) -- Agrega una columna espacial a la tabla SELECT AddGeometryColumn ('my_schema','my_spatial_table','geom',4326,'POINT',2); -- Agrega un punto usando el antiguo comportamiento basado en restricciones SELECT AddGeometryColumn ('my_schema','my_spatial_table','geom_c',4326,'POINT',2, false); -- Agrega un curvepolygon usando el viejo comportamiento de restricción SELECT AddGeometryColumn ('my_schema','my_spatial_table','geomcp_c',4326,'CURVEPOLYGON',2, false); -- Describe la tabla otra vez revelando la adición de una nueva columna geométrica. \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) -- la vista geometry_columns también registra las nuevas columnas -- 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 — Suprime una columna de geometrías de una tabla espacial.
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)
;
Suprime una columna de geometrías de una tabla espacial. Observa que schema_name debe apuntar al campo f_table_schema del registro de la tabla 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
![]() | |
Cambiado: 2.0.0 Se proporciona esta función para la compatibilidad con versiones anteriores. Ahora que geometry_columns es una vista y no un catálogo del sistema, se puede eliminar una columna de geometría como cualquier otra columna de la tabla utilizando |
SELECT DropGeometryColumn ('my_schema','my_spatial_table','geom'); ----RESULT output --- dropgeometrycolumn ------------------------------------------------------ my_schema.my_spatial_table.geom effectively removed. -- En PostGIS 2.0+ lo anterior también es equivalente al estándar -- El estándar alterar tabla. Ambos anularán el registro de geometry_columns ALTER TABLE my_schema.my_spatial_table DROP column geom;
DropGeometryTable — Borra una tabla y todas sus referencias en la tabla geómetra_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)
;
Borra la tabla y todas sus referencias en la tabla geómetra_column. Nota: utiliza el esquema current_schema() de una instalación pgsql si el esquema no se especifica.
![]() | |
Cambiado: 2.0.0 Se proporciona esta función para la compatibilidad con versiones anteriores. Ahora que geometry_columns es una vista y no un catálogo del sistema, se puede borrar una tabla con columnas de geometría como cualquier otra tabla utilizando |
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)
;
Asegura que las columnas de geometría se define con modificadores de tipo o tienen restricciones espaciales apropiadas Esto asegura que se registrarán correctamente en la vista geometry_columns
. Por defecto se convertirán todas las columnas de geometría sin modificador de tipo a modificadores de tipo. Para conseguir el comportamiento del sistema antiguo selecciona use_typmod = false
Para la compatibilidad con versiones anteriores y para necesidades espaciales, como la herencia de tablas, donde cada tabla secundaria puede tener un tipo de geometría diferente, el comportamiento de restricción de comprobación anterior sigue siendo compatible. Si necesita el comportamiento antiguo, debe pasar el nuevo argumento opcional como falso use_typmod=false
. Cuando se haga esto, las columnas de geometría se crearán sin modificadores de tipo pero tendrán 3 restricciones definidas. En particular, esto significa que cada columna geométrica que pertenezca a una tabla tiene al menos tres restricciones:
enforce_dims_the_geom
- asegura que cada geometría posee la misma dimensión (mira en ST_NDims)
enforce_geotype_the_geom
- asegura que cada geometría es del mismo tipo (mira en GeometryType)
enforce_srid_the_geom
- asegura que cada geometría tiene la misma proyección (mira en ST_SRID)
Si se da una tabla oid
, esta función trata de determinar el srid, la dimensión, y el tipo de geometría de todas las columnas de geometrías en la tabla, añadiendo las restricciones si es necesario. Si no hay errores, una fila apropiada se insertará en la tabla geometry_columns, si hay errores, se captura la excepción y se envía un mensaje de error con la descripción del problema.
Si se da una vista oíd
, como en el caso de una tabla oíd, esta función trata de determinar el srid, la dimensión, y el tipo de geometría de todas las columnas de geometrías en la tabla, añadiendo las filas apropiadas tabla geometry_columns
, pero no se ejecuta nada para hacer cumplir las restricciones.
La variante sin parámetros es un simple wrapper de la variante con parámetros que trunca y rellena la tabla geometry_columns para cada tabla y vista espacial de la base de datos, añadiendo restricciones espaciales apropiadas a cada tabla. Devuelve un sumario de los numero de columnas de geometrías detectadas en la base de datos y el numeroque se insertaron en la tabla geometry_columns
. La versión con parámetros simplemente devuelve el numero de filas insertado en la tabla geometry_columns
.
Disponibilidad: 1.4.0
Cambiado: 2.0.0 Por defecto, ahora utiliza modificadores de tipo en lugar de restricciones de tipo check para limitar los tipos de geometría. Puedes seguir utilizando el comportamiento de las restricciones check con el uso de la nueva variable use_typmod
y estableciéndolo a false.
Mejorado: 2.0.0 el argumento opcional use_typmod
fue introducido y permite controlar si las columnas se crean con modificadores de tipo o con restricciones de tipo check.
CREATE TABLE public.myspatial_table(gid serial, geom geometry); INSERT INTO myspatial_table(geom) VALUES(ST_GeomFromText('LINESTRING(1 2, 3 4)',4326) ); -- Esto ahora usará modificadores de typ. Para que esto funcione, deben existir datos 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) |
-- Esto cambiará las columnas de geometría para usar restricciones si no son typmod o ya tienen restricciones.. --Para que esto funcione, deben existir datos 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)
;
Actualiza el SRID de todos los registros de una columna de geometrías, actualizando las restricciones y referencias en geometry_columns. Nota: utiliza current_schema() en instalaciones pgsql que aceptan esquemas, si no se pasa ningún esquema.
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) \.
Esto cambiará el srid de la tabla de roads a 4326 de lo que era antes
SELECT UpdateGeometrySRID('roads','geom',4326);
El ejemplo previo es equivalente a esta sentencia DDL
ALTER TABLE roads ALTER COLUMN geom TYPE geometry(MULTILINESTRING, 4326) USING ST_SetSRID(geom,4326);
Si se obtuvo la proyección incorrecta (o que se señala como desconocido) en la carga y que quería transformar a mercator web todo en una sola toma, puede hacer esto con DDL pero no hay ninguna función de gestión de PostGIS equivalente para hacerlo de una sola vez.
ALTER TABLE roads ALTER COLUMN geom TYPE geometry(MULTILINESTRING, 3857) USING ST_Transform(ST_SetSRID(geom,4326),3857) ;
ST_GeomCollFromText — Creates a GeometryCollection or Multi* geometry from a set of geometries.
geometry ST_MakeLine(
geometry set geoms)
;
geometry ST_MakeLine(
geometry geom1, geometry geom2)
;
geometry ST_MakeLine(
geometry[] geoms_array)
;
Collects geometries into a geometry collection. The result is either a Multi* or a GeometryCollection, depending on whether the input geometries have the same or different types (homogeneous or heterogeneous). The input geometries are left unchanged within the collection.
Variant 1: accepts two input geometries
Variant 2: accepts an array of geometries
Variant 3: aggregate function accepting a rowset of geometries.
![]() | |
If any of the input geometries are collections (Multi* or GeometryCollection) ST_Collect returns a GeometryCollection (since that is the only type which can contain nested collections). To prevent this, use ST_Dump in a subquery to expand the input collections to their atomic elements (see example below). |
![]() | |
ST_Collect and ST_Union appear similar, but in fact operate quite differently. ST_Collect aggregates geometries into a collection without changing them in any way. ST_Union geometrically merges geometries where they overlap, and splits linestrings at intersections. It may return single geometries when it dissolves boundaries. |
Disponibilidad: 1.4.0 - ST_MakeLine (geomarray) fue introducido. Las Funciones agregadas ST_MakeLine se mejoraron para manejar más puntos más rápido.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
Collect 2D points.
SELECT ST_AsText( ST_Collect( ST_GeomFromText('POINT(1 2)'), ST_GeomFromText('POINT(-2 3)') )); st_astext ---------- MULTIPOINT((1 2),(-2 3))
Collect 3D points.
SELECT ST_AsEWKT( ST_Collect( ST_GeomFromEWKT('POINT(1 2 3)'), ST_GeomFromEWKT('POINT(1 2 4)') ) ); st_asewkt ------------------------- MULTIPOINT(1 2 3,1 2 4)
Collect curves.
SELECT ST_AsText( ST_Collect( 'CIRCULARSTRING(220268 150415,220227 150505,220227 150406)', 'CIRCULARSTRING(220227 150406,2220227 150407,220227 150406)')); st_astext ------------------------------------------------------------------------------------ MULTICURVE(CIRCULARSTRING(220268 150415,220227 150505,220227 150406), CIRCULARSTRING(220227 150406,2220227 150407,220227 150406))
Using an array constructor for a subquery.
SELECT ST_Collect( ARRAY( SELECT geom FROM sometable ) );
Using an array constructor for values.
SELECT ST_AsText( ST_Collect( ARRAY[ ST_GeomFromText('LINESTRING(1 2, 3 4)'), ST_GeomFromText('LINESTRING(3 4, 4 5)') ] )) As wktcollect; --wkt collect -- MULTILINESTRING((1 2,3 4),(3 4,4 5))
ST_LineFromMultiPoint — Crea una LineString desde una geometría MultiPoint.
geometry ST_LineFromMultiPoint(
geometry aMultiPoint)
;
Crea una LineString desde una geometría MultiPoint.
Use ST_MakeLine to create lines from Point or LineString inputs.
This function supports 3d and will not drop the z-index.
ST_MakeEnvelope — Crea un polígono rectangular formado a partir de los mínimos y máximos especificados. Los valores de entrada deben estar en el SRS especificado en el SRID.
geometry ST_MakeEnvelope(
double precision xmin, double precision ymin, double precision xmax, double precision ymax, integer srid=unknown)
;
Crea un polígono rectangular formado a partir de los mínimos y máximos de la caja dada. Los valores de entrada deben estar en el SRS especificado por el SRID. Si no se especifica SRID se supone que el sistema de referencia espacial es desconocido.
Disponibilidad: 1.5
Mejorado: 2.0: Se introdujo capacidad de especificar una caja sin especificar un SRID.
ST_MakeLine — Crea una cadena de línea desde geometrías de punto, multipunto o de línea.
geometry ST_MakeLine(
geometry set geoms)
;
geometry ST_MakeLine(
geometry geom1, geometry geom2)
;
geometry ST_MakeLine(
geometry[] geoms_array)
;
Creates a LineString containing the points of Point, MultiPoint, or LineString geometries. Other geometry types cause an error.
Variant 1: accepts two input geometries
Variant 2: accepts an array of geometries
Variant 3: aggregate function accepting a rowset of geometries. To ensure the order of the input geometries use ORDER BY
in the function call, or a subquery with an ORDER BY
clause.
Repeated nodes at the beginning of input LineStrings are collapsed to a single point. Repeated points in Point and MultiPoint inputs are not collapsed. ST_RemoveRepeatedPoints can be used to collapse repeated points from the output LineString.
This function supports 3d and will not drop the z-index.
Disponibilidad: 2.3.0 - Se introdujo soporte para elementos de entrada multipunto
Disponibilidad: 2.0.0 - Se introdujo el soporte de una cadena lineal como elemento de entrada
Disponibilidad: 1.4.0 - ST_MakeLine (geomarray) fue introducido. Las Funciones agregadas ST_MakeLine se mejoraron para manejar más puntos más rápido.
Create a line composed of two points.
SELECT ST_MakeLine(ARRAY(SELECT ST_Centroid(the_geom) FROM visit_locations ORDER BY visit_time)); -- Haciendo una linea 3d com 3 puntos 3-d SELECT ST_AsEWKT(ST_MakeLine(ARRAY[ST_MakePoint(1,2,3), ST_MakePoint(3,4,5), ST_MakePoint(6,6,6)])); st_asewkt ------------------------- LINESTRING(1 2 3,3 4 5,6 6 6)
Crea una BOX3D definida por las geometrías puntuales 2 3D dadas.
SELECT ST_AsEWKT( ST_MakeLine(ST_MakePoint(1,2,3), ST_MakePoint(3,4,5) )); st_asewkt ------------------------- LINESTRING(1 2 3,3 4 5)
Crea una cadena de línea desde geometrías de punto, multipunto o de línea.
select ST_AsText( ST_MakeLine( 'LINESTRING(0 0, 1 1)', 'LINESTRING(2 2, 3 3)' ) ); st_astext ----------------------------- LINESTRING(0 0,1 1,2 2,3 3)
Create a line from an array formed by a subquery with ordering.
SELECT ST_MakeLine( ARRAY( SELECT ST_Centroid(geom) FROM visit_locations ORDER BY visit_time) );
Create a 3D line from an array of 3D points
SELECT ST_MakeLine(ARRAY(SELECT ST_Centroid(the_geom) FROM visit_locations ORDER BY visit_time)); -- Haciendo una linea 3d com 3 puntos 3-d 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)
Este ejemplo toma una secuencia de puntos GPS y crea un registro para cada trayecto GPS donde el campo geómetra es una cadena lineal compuesta de los puntos GPS en el orden del trayecto.
Using aggregate ORDER BY
provides a correctly-ordered LineString.
SELECT gps.track_id, ST_MakeLine(gps.geom ORDER BY gps_time) As geom FROM gps_points As gps GROUP BY track_id;
Prior to PostgreSQL 9, ordering in a subquery can be used. However, sometimes the query plan may not respect the order of the subquery.
SELECT gps.track_id, ST_MakeLine(gps.geom) As geom FROM ( SELECT track_id, gps_time, geom FROM gps_points ORDER BY track_id, gps_time ) As gps GROUP BY track_id;
ST_MakePoint — Creates a 2D, 3DZ or 4D Point.
geometry ST_Point(
float x_lon, float y_lat)
;
geometry ST_MakePointM(
float x, float y, float m)
;
geometry ST_MakePoint(
double precision x, double precision y, double precision z, double precision m)
;
Crea una BOX2D definida por los puntos de la geometría dada.
Use ST_MakePointM to make points with XYM coordinates.
While not OGC-compliant, ST_MakePoint
is faster and more precise than ST_GeomFromText and ST_PointFromText. It is also easier to use for numeric coordinate values.
![]() | |
For geodetic coordinates, |
This function supports 3d and will not drop the z-index.
--Devuelve un punto con un SRID desconocido SELECT ST_MakePoint(-71.1043443253471, 42.3150676015829); --Devuelve un punto como WGS 84 long lat SELECT ST_SetSRID(ST_MakePoint(-71.1043443253471, 42.3150676015829),4326); --Devuelve un punto 3D (por ejemplo, tiene altitud) SELECT ST_MakePoint(1, 2,1.5); --Obtiene z del punto SELECT ST_Z(ST_MakePoint(1, 2,1.5)); result ------- 1.5
ST_MakePointM — Crea un punto con coordenadas x, y y un valor de medida.
geometry ST_MakePointM(
float x, float y, float m)
;
Crea un punto con coordenadas x, y y un valor de medida.
Use ST_MakePoint to make points with XY, XYZ, or XYZM coordinates.
![]() | |
For geodetic coordinates, |
Create point with unknown SRID.
SELECT ST_AsEWKT( ST_MakePointM(-71.1043443253471, 42.3150676015829, 10) ); st_asewkt ----------------------------------------------- POINTM(-71.1043443253471 42.3150676015829 10)
Crea un punto con coordenadas x, y y un valor de medida.
SELECT ST_AsEWKT( ST_SetSRID( ST_MakePointM(-71.104, 42.315, 10), 4326)); st_asewkt --------------------------------------------------------- SRID=4326;POINTM(-71.104 42.315 10)
Get measure of created point.
SELECT ST_M( ST_MakePointM(-71.104, 42.315, 10) ); result ------- 10
ST_MakePolygon — Creates a Polygon from a shell and optional list of holes.
geometry ST_MakePolygon(
geometry linestring)
;
geometry ST_MakePolygon(
geometry outerlinestring, geometry[] interiorlinestrings)
;
Crea un polígono formado por el contorno dado. Las geometrías de entrada deben ser LINESTRINGS cerradas.
Variant 1: Accepts one shell LineString.
Variant 2: Accepts a shell LineString and an array of inner (hole) LineStrings. A geometry array can be constructed using the PostgreSQL array_agg(), ARRAY[] or ARRAY() constructs.
![]() | |
Esta función no acepta una MULTILINESTRING. Utiliza ST_LineMerge o ST_Dump para generar una linestring. |
This function supports 3d and will not drop the z-index.
Crea un LineString desde una cadena de polilínea codificada.
SELECT ST_MLineFromText('MULTILINESTRING((1 2, 3 4), (4 5, 6 7))');
Create a Polygon from an open LineString, using ST_StartPoint and ST_AddPoint to close it.
SELECT ST_MakePolygon( ST_AddPoint(foo.open_line, ST_StartPoint(foo.open_line)) ) FROM ( SELECT ST_GeomFromText('LINESTRING(75 29,77 29,77 29, 75 29)') As open_line) As foo;
Crea un LineString desde una cadena de polilínea codificada.
SELECT ST_AsEWKT( ST_MakePolygon( 'LINESTRING(75.15 29.53 1,77 29 1,77.6 29.5 1, 75.15 29.53 1)')); st_asewkt ----------- POLYGON((75.15 29.53 1,77 29 1,77.6 29.5 1,75.15 29.53 1))
Create a Polygon from a LineString with measures
SELECT ST_AsEWKT( ST_MakePolygon( 'LINESTRINGM(75.15 29.53 1,77 29 1,77.6 29.5 2, 75.15 29.53 2)' )); st_asewkt ---------- POLYGONM((75.15 29.53 1,77 29 1,77.6 29.5 2,75.15 29.53 2))
Contruye un donut con un agujero de hormiga
SELECT ST_MakePolygon( ST_ExteriorRing(ST_Buffer(foo.line,10)), ARRAY[ST_Translate(foo.line,1,1), ST_ExteriorRing(ST_Buffer(ST_MakePoint(20,20),1)) ] ) FROM (SELECT ST_ExteriorRing(ST_Buffer(ST_MakePoint(10,10),10,10)) As line ) As foo;
Create a set of province boundaries with holes representing lakes. The input is a table of province Polygons/MultiPolygons and a table of water linestrings. Lines forming lakes are determined by using ST_IsClosed. The province linework is extracted by using ST_Boundary. As required by ST_MakePolygon
, the boundary is forced to be a single LineString by using ST_LineMerge. (However, note that if a province has more than one region or has islands this will produce an invalid polygon.) Using a LEFT JOIN ensures all provinces are included even if they have no lakes.
![]() | |
El constructor CASE se utiliza porque la alimentación de una matriz nula en ST_MakePolygon resulta en 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;
Another technique is to utilize a correlated subquery and the ARRAY() constructor that converts a row set to an array.
SELECT p.gid, p.province_name, CASE WHEN ST_Accum(w.the_geom) IS NULL THEN p.the_geom ELSE ST_MakePolygon(ST_LineMerge(ST_Boundary(p.the_geom)), ST_Accum(w.the_geom)) END FROM provinces p LEFT JOIN waterlines w ON (ST_Within(w.the_geom, p.the_geom) AND ST_IsClosed(w.the_geom)) GROUP BY p.gid, p.province_name, p.the_geom; -- El mismo ejemplo que antes pero utilizando una subconsulta correlada -- y la función ARRAY() de PostgreSQL, que convierte todo el conjunto de filas en una array SELECT p.gid, p.province_name, CASE WHEN EXISTS(SELECT w.the_geom FROM waterlines w WHERE ST_Within(w.the_geom, p.the_geom) AND ST_IsClosed(w.the_geom)) THEN ST_MakePolygon(ST_LineMerge(ST_Boundary(p.the_geom)), ARRAY(SELECT w.the_geom FROM waterlines w WHERE ST_Within(w.the_geom, p.the_geom) AND ST_IsClosed(w.the_geom))) ELSE p.the_geom END As the_geom FROM provinces p;
ST_Point — Creates a Point with X, Y and SRID values.
geometry ST_Point(
float x_lon, float y_lat)
;
geometry ST_MakePointM(
float x, float y, float m)
;
Returns a Point with the given X and Y coordinate values. This is the SQL-MM equivalent for ST_MakePoint that takes just X and Y.
![]() | |
For geodetic coordinates, |
Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID to mark the srid on the geometry.
This method implements the SQL/MM specification. SQL-MM 3: 6.1.2
SELECT ST_Point( -71.104, 42.315);
SELECT ST_SetSRID(ST_Point( -71.104, 42.315),4326);
New in 3.2.0: With SRID specified
SELECT ST_Point( -71.104, 42.315, 4326);
Pre-PostGIS 3.2 syntax
SELECT CAST( ST_SetSRID(ST_Point( -71.104, 42.315), 4326) AS geography);
3.2 and on you can include the srid
SELECT CAST( ST_Point( -71.104, 42.315, 4326) AS geography);
PostgreSQL also provides the ::
short-hand for casting
SELECT ST_Point( -71.104, 42.315, 4326)::geography;
If the point coordinates are not in a geodetic coordinate system (such as WGS84), then they must be reprojected before casting to a geography. In this example a point in Pennsylvania State Plane feet (SRID 2273) is projected to WGS84 (SRID 4326).
SELECT CAST(ST_SetSRID(ST_Point(-71.1043443253471, 42.3150676015829),4326) As geography);
Section 4.3, “Geography Data Type”, ST_MakePoint, ST_SetSRID, ST_Transform, ST_Point, ST_Point, ST_Point
ST_Point — Creates a Point with X, Y, Z and SRID values.
geometry ST_MakePoint(
double precision x, double precision y, double precision z, double precision m)
;
Devuelve un ST_Point con el valor de coordenadas dado. Es un alias de ST_MakePoint del OGC.
Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID to mark the srid on the geometry.
ST_Point — Creates a Point with X, Y, M and SRID values.
geometry ST_PointM(
float x, float y, float m, integer srid=unknown)
;
Devuelve un ST_Point con el valor de coordenadas dado. Es un alias de ST_MakePoint del OGC.
Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID to mark the srid on the geometry.
ST_Point — Creates a Point with X, Y, Z, M and SRID values.
geometry ST_MakeEnvelope(
double precision xmin, double precision ymin, double precision xmax, double precision ymax, integer srid=unknown)
;
Devuelve un ST_Point con el valor de coordenadas dado. Es un alias de ST_MakePoint del OGC.
Enhanced: 3.2.0 srid as an extra optional argument was added. Older installs require combining with ST_SetSRID to mark the srid on the geometry.
ST_Polygon — Creates a Polygon from a LineString with a specified SRID.
geometry ST_Polygon(
geometry aLineString, integer srid)
;
Returns a polygon built from the given LineString and sets the spatial reference system from the srid
.
ST_Polygon is similar to ST_MakePolygon Variant 1 with the addition of setting the SRID.
![]() | |
Esta función no acepta una MULTILINESTRING. Utiliza ST_LineMerge o ST_Dump para generar una linestring. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3: 8.3.2
This function supports 3d and will not drop the z-index.
Create a 2D polygon.
SELECT ST_AsText( ST_Polygon('LINESTRING(75 29, 77 29, 77 29, 75 29)'::geometry, 4326) ); -- result -- POLYGON((75 29, 77 29, 77 29, 75 29))
Create a 3D polygon.
SELECT ST_AsEWKT( ST_Polygon( ST_GeomFromEWKT('LINESTRING(75 29 1, 77 29 2, 77 29 3, 75 29 1)'), 4326) ); -- result -- SRID=4326;POLYGON((75 29 1, 77 29 2, 77 29 3, 75 29 1))
ST_MakeEnvelope — Creates a rectangular Polygon in Web Mercator (SRID:3857) using the XYZ tile system.
geometry ST_MakePoint(
double precision x, double precision y, double precision z, double precision m)
;
Creates a rectangular Polygon giving the extent of a tile in the XYZ tile system. The tile is specifed by the zoom level Z and the XY index of the tile in the grid at that level. Can be used to define the tile bounds required by ST_AsMVTGeom to convert geometry into the MVT tile coordinate space.
By default, the tile envelope is in the Web Mercator coordinate system (SRID:3857) using the standard range of the Web Mercator system (-20037508.342789, 20037508.342789). This is the most common coordinate system used for MVT tiles. The optional bounds
parameter can be used to generate tiles in any coordinate system. It is a geometry that has the SRID and extent of the "Zoom Level zero" square within which the XYZ tile system is inscribed.
The optional margin
parameter can be used to expand a tile by the given percentage. E.g. margin=0.125
expands the tile by 12.5%, which is equivalent to buffer=512 when the tile extent size is 4096, as used in ST_AsMVTGeom. This is useful to create a tile buffer to include data lying outside of the tile's visible area, but whose existence affects the tile rendering. For example, a city name (a point) could be near an edge of a tile, so its label should be rendered on two tiles, even though the point is located in the visible area of just one tile. Using expanded tiles in a query will include the city point in both tiles. Use a negative value to shrink the tile instead. Values less than -0.5 are prohibited because that would eliminate the tile completely. Do not specify a margin when using with ST_AsMVTGeom
. See the example for ST_AsMVT.
Mejorada: 2.0.0 se agregó el parámetro por defecto opcional srid.
Disponibilidad: 2.1.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 — Returns a set of hexagons and cell indices that completely cover the bounds of the geometry argument.
geometry ST_Point(
float x_lon, float y_lat)
;
Starts with the concept of a hexagon tiling of the plane. (Not a hexagon tiling of the globe, this is not the H3 tiling scheme.) For a given planar SRS, and a given edge size, starting at the origin of the SRS, there is one unique hexagonal tiling of the plane, Tiling(SRS, Size). This function answers the question: what hexagons in a given Tiling(SRS, Size) overlap with a given bounds.
The SRS for the output hexagons is the SRS provided by the bounds geometry.
Doubling or tripling the edge size of the hexagon generates a new parent tiling that fits with the origin tiling. Unfortunately, it is not possible to generate parent hexagon tilings that the child tiles perfectly fit inside.
Disponibilidad: 2.1.0
To do a point summary against a hexagonal tiling, generate a hexagon grid using the extent of the points as the bounds, then spatially join to that grid.
SELECT COUNT(*), hexes.geom FROM ST_HexagonGrid( 10000, ST_SetSRID(ST_EstimatedExtent('pointtable', 'geom'), 3857) ) AS hexes INNER JOIN pointtable AS pts ON ST_Intersects(pts.geom, hexes.geom) GROUP BY hexes.geom;
If we generate a set of hexagons for each polygon boundary and filter out those that do not intersect their hexagons, we end up with a tiling for each polygon.
Tiling states results in a hexagon coverage of each state, and multiple hexagons overlapping at the borders between states.
![]() | |
The LATERAL keyword is implied for set-returning functions when referring to a prior table in the FROM list. So CROSS JOIN LATERAL, CROSS JOIN, or just plain , are equivalent constructs for this example. |
SELECT admin1.gid, hex.geom FROM admin1 CROSS JOIN ST_HexagonGrid(100000, admin1.geom) AS hex WHERE adm0_a3 = 'USA' AND ST_Intersects(admin1.geom, hex.geom)
ST_Hexagon — Returns a single hexagon, using the provided edge size and cell coordinate within the hexagon grid space.
geometry ST_MakePoint(
double precision x, double precision y, double precision z, double precision m)
;
Uses the same hexagon tiling concept as ST_HexagonGrid, but generates just one hexagon at the desired cell coordinate. Optionally, can adjust origin coordinate of the tiling, the default origin is at 0,0.
Hexagons are generated with no SRID set, so use ST_SetSRID to set the SRID to the one you expect.
Disponibilidad: 2.1.0
ST_SquareGrid — Returns a set of grid squares and cell indices that completely cover the bounds of the geometry argument.
geometry ST_Point(
float x_lon, float y_lat)
;
Starts with the concept of a square tiling of the plane. For a given planar SRS, and a given edge size, starting at the origin of the SRS, there is one unique square tiling of the plane, Tiling(SRS, Size). This function answers the question: what grids in a given Tiling(SRS, Size) overlap with a given bounds.
The SRS for the output squares is the SRS provided by the bounds geometry.
Doubling or edge size of the square generates a new parent tiling that perfectly fits with the original tiling. Standard web map tilings in mercator are just powers-of-two square grids in the mercator plane.
Disponibilidad: 2.1.0
The grid will fill the whole bounds of the country, so if you want just squares that touch the country you will have to filter afterwards with ST_Intersects.
WITH grid AS ( SELECT (ST_SquareGrid(1, ST_Transform(geom,4326))).* FROM admin0 WHERE name = 'Canada' ) SELEcT ST_AsText(geom) FROM grid
To do a point summary against a square tiling, generate a square grid using the extent of the points as the bounds, then spatially join to that grid. Note the estimated extent might be off from actual extent, so be cautious and at very least make sure you've analyzed your table.
SELECT COUNT(*), squares.geom FROM pointtable AS pts INNER JOIN ST_SquareGrid( 1000, ST_SetSRID(ST_EstimatedExtent('pointtable', 'geom'), 3857) ) AS squares ON ST_Intersects(pts.geom, squares.geom) GROUP BY squares.geom
This yields the same result as the first example but will be slower for a large number of points
SELECT COUNT(*), squares.geom FROM pointtable AS pts INNER JOIN ST_SquareGrid( 1000, pts.geom ) AS squares ON ST_Intersects(pts.geom, squares.geom) GROUP BY squares.geom
ST_Square — Returns a single square, using the provided edge size and cell coordinate within the square grid space.
geometry ST_MakePoint(
double precision x, double precision y, double precision z, double precision m)
;
Uses the same square tiling concept as ST_SquareGrid, but generates just one square at the desired cell coordinate. Optionally, can adjust origin coordinate of the tiling, the default origin is at 0,0.
Squares are generated with no SRID set, so use ST_SetSRID to set the SRID to the one you expect.
Disponibilidad: 2.1.0
ST_Letters — Returns the input letters rendered as geometry with a default start position at the origin and default text height of 100.
geometry ST_Letters(
text letters, json font)
;
Uses a built-in font to render out a string as a multipolygon geometry. The default text height is 100.0, the distance from the bottom of a descender to the top of a capital. The default start position places the start of the baseline at the origin. Over-riding the font involves passing in a json map, with a character as the key, and base64 encoded TWKB for the font shape, with the fonts having a height of 1000 units from the bottom of the descenders to the tops of the capitals.
The text is generated at the origin by default, so to reposition and resize the text, first apply the ST_Scale
function and then apply the ST_Translate
function.
Disponibilidad: 2.1.0
geometry_dump
rows for the components of a geometry.geometry_dump
rows for the exterior and interior rings of a Polygon.TRUE
si los puntos de inicio y final de una LINESTRING
son coincidentes. Para superficies poliedricas si son cerradas (volumetricas). GeometryType — Devuelve el tipo de geometría del valor de ST_Geometry.
text GeometryType(
geometry geomA)
;
Devuelve el tipo de geometría como una cadena de texto. Ej: 'LINESTRING', 'POLYGON', 'MULTIPOINT', etc.
OGC SPEC s2.1.1.1 - Devuelve el nombre del subtipo de la instancia de la geometría de la cual la instancia de la geometría es miembro. El nombre del subtipo de geometría de la instancia se devuelve en forma de cadena de texto.
![]() | |
Esta función también indica si la geometría tiene valores de medida, devolviendo una cadena de tipo 'POINTM'. |
Mejorado: 2.0.0 se introdujo soporte para superficies poliédricas, Triangulos y TIN.
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method supports Circular Strings and Curves
This function supports 3d and will not drop the z-index.
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
SELECT GeometryType(ST_GeomFromText('LINESTRING(77.29 29.07,77.42 29.26,77.27 29.31,77.29 29.07)')); geometrytype -------------- LINESTRING
SELECT ST_GeometryType(ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )')); --result POLYHEDRALSURFACE
SELECT GeometryType(geom) as result FROM (SELECT ST_GeomFromEWKT('TIN ((( 0 0 0, 0 0 1, 0 1 0, 0 0 0 )), (( 0 0 0, 0 1 0, 1 1 0, 0 0 0 )) )') AS geom ) AS g; result -------- TIN
ST_Boundary — Devuelve el cierre del limite combinatorio de esta geometría.
geometry ST_Boundary(
geometry geomA)
;
Devuelve el cierre del limite combinatorio de esta geometría. El limite combinatorio esta definido como se describe en la sección 3.12.3.2 de la especificación OGC. Ya que el resultado de esta función es un cerco, y por lo tanto topológicamente cerrado, el límite resultante puede ser representado utilizando geometrías primitivas como se discute en la especificación OGC en la sección 3.12.2.
Realizado por el módulo de GEOS
![]() | |
Anterior a la version 2.0.0, esta función lanza una excepción si se utiliza con |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. OGC SPEC s2.1.1.1
This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 5.1.17
This function supports 3d and will not drop the z-index.
Mejorado: 2.1.0 Se ha introducido soporte para Triangle
Changed: 3.2.0 support for TIN, does not use geos, does not linearize curves
![]() LineString con puntos de límite superpuestos
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))
| ![]() Agujeros de polígono con límite 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;
-- Salida de ST_AsText 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 — Devuelve la diagonal del cuadro delimitador de la geometría suministrada.
geometry ST_BoundingDiagonal(
geometry geom, boolean fits=false)
;
Devuelve la diagonal del cuadro delimitador de la geometría suministrada como una cadena de línea. Si la geometría de entrada está vacía, la línea diagonal también está vacía, de lo contrario es una cadena de línea de 2 puntos con valores mínimos de cada dimensión en su punto de inicio y valores máximos en su punto final.
El parámetro fits
especifica si se necesita el mejor ajuste. Si es false, se puede aceptar la diagonal de un cuadro delimitador algo más grande (es más rápido para obtener geometrías con muchos vértices). En cualquier caso, el cuadro delimitador de la línea diagonal devuelta siempre cubre la geometría de entrada.
La geometría cadena de línea devuelta siempre conserva SRID y dimensionalidad (z y m presente) de la geometría de entrada.
![]() | |
En los casos degenerados (un solo vértice en la entrada) la cadena de líneas devuelta será topológicamente inválida (no interior). Esto no hace que el retorno sea semánticamente inválido. |
Disponibilidad: 2.2.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_CoordDim — Devuelve la dimensión de las coordenadas del valor de ST_Geometry.
integer ST_CoordDim(
geometry geomA)
;
Devuelve la dimensión de las coordenadas del valor de ST_Geometry.
Es el alias de ST_NDims conforme a MM
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 — Devuelve la dimensión de las coordenadas del valor de ST_Geometry.
integer ST_Dimension(
geometry g)
;
La dimensión inherente del objeto Geometry, la cual debe ser menor o igual a la dimensión de coordenadas. En la Especificación OGC s2.1.1.1 - devuelve 0 para un POINT
, 1 para una LINESTRING
, 2 para un POLYGON
, y la dimensión mayor de los componentes de una GEOMETRYCOLLECTION
. Si es desconocida (geometría vacía) se devuelve null.
This method implements the SQL/MM specification. SQL-MM 3: 5.1.2
Mejora: 2.0.0 se introdujeron soporte de superficies poliédricas y TIN. No lanza una excepción si se envia una geometría vacía.
![]() | |
Anterior a la versión 2.0.0, esta función lanzaba una excepción si se enviaba una geometría vacía. |
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
ST_Dump — Returns a set of geometry_dump
rows for the components of a geometry.
geometry ST_Envelope(
geometry g1)
;
A set-returning function (SRF) that extracts the components of a geometry. It returns a set of geometry_dump rows, each containing a geometry (geom
field) and an array of integers (path
field).
For an atomic geometry type (POINT,LINESTRING,POLYGON) a single record is returned with an empty path
array and the input geometry as geom
. For a collection or multi-geometry a record is returned for each of the collection components, and the path
denotes the position of the component inside the collection.
ST_Dump is useful for expanding geometries. It is the inverse of a ST_GeomCollFromText / GROUP BY, in that it creates new rows. For example it can be use to expand MULTIPOLYGONS into POLYGONS.
Mejorado: 2.0.0 se introdujo soporte para superficies poliédricas, Triangulos y TIN.
Availability: PostGIS 1.0.0RC1. Requires PostgreSQL 7.3 or higher.
![]() | |
Anterior a 1.3.4, esta función daba errores si se utilizaba con geometrias que contenían CURVES. Esto se corrigió en 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)
-- Ejemplo de superficie de poliedros -- Romper una superficie poliédrica en sus caras 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_NumPoints — Devuelve un resumen de texto del contenido de la geometría.
geometry ST_Points(
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.
Mejorado: 2.0.0 se introdujo soporte para superficies poliédricas, Triangulos y TIN.
Disponibilidad: 1.2.2
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)
-- 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))
-- 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_NumPoints — Devuelve un resumen de texto del contenido de la geometría.
geometry ST_Points(
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).
Devuelve TRUE
si esta LINESTRING
es simple y cerrada.
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.
Disponibilidad: 2.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)
-- 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))
-- 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_NRings — Returns a set of geometry_dump
rows for the exterior and interior rings of a Polygon.
geometry ST_ExteriorRing(
geometry a_polygon)
;
A set-returning function (SRF) that extracts the rings of a polygon. It returns a set of geometry_dump rows, each containing a geometry (geom
field) and an array of integers (path
field).
The geom
field contains each ring as a POLYGON. The path
field is an integer array of length 1 containing the polygon ring index. The exterior ring (shell) has index 0. The interior rings (holes) have indices of 1 and higher.
![]() | |
Esto no funcionara con MULTIPOLYGONs. Para MULTIPOLYGONs utilizaba junto a ST_Dump. |
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 — Devuelve el número de puntos en un valor ST_LineString o ST_CircularString.
geometry ST_Points(
geometry geom )
;
Devuelve el primer punto de una geometría LINESTRING
o CIRCULARLINESTRING
como un POINT
o NULL
si el parámetro de entrada no es un LINESTRING
o 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
![]() | |
Cambiado: 2.0.0 ya no funciona con multilinestrings de geometrías simples. En versiones anteriores de PostGIS -- una linea simple multilinestring funciona sin problemas con esta función y devuelve el punto inicial. En la version 2.0.0 simplemente devuelve NULL como con cualquier multilinestring. La antigua version era una función sin documentar, pero la gente que asumía que tenia sus datos almacenados en LINESTRING pueden experimentar este comportamiento ahora de resultado NULL en la version 2.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)
Devuelve el número de puntos en un valor ST_LineString o ST_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 — Devuelve una geometría que representa la caja en doble precisión (float8) de la geometría dada.
geometry ST_Envelope(
geometry g1)
;
Devuelve una geometría que representa la caja mínima en doble precisión (float8) de la geometría dada. El polígono definido por las esquinas de la caja ((MINX
, MINY
), (MINX
, MAXY
), (MAXX
, MAXY
), (MAXX
, MINY
), (MINX
, MINY
)). (PostGIS añadirá las coordenadas ZMIN
/ZMAX
también).
Algunos casos particulares(lineas verticales, puntos) devolverán una geometría de dimension menor que POLYGON
, por ejemplo POINT
o LINESTRING
.
Disponibilidad: 1.5.0 comportamiento modificado para devolver doble precisión en vez 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 — Devuelva el número de anillos interiores de una geometría poligonal.
geometry ST_ExteriorRing(
geometry a_polygon)
;
Devuelve una linestring representando el anillo exterior de una geometria tipo POLYGON
. Devuelve NULL si la geometria no es un poligono. No funcionará con MULTIPOLYGON
![]() | |
Esto no funcionara con MULTIPOLYGONs. Para MULTIPOLYGONs utilizaba junto a 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 tienes una tabla de poligonos SELECT gid, ST_ExteriorRing(the_geom) AS ering FROM sometable; --Si tienes una tbla de MULTIPOLYGONos --y quieres que te devuelva una MULTILINESTRING compuesta por los anillos exteriores de cada poligono 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; --Ejemplo 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 — Devuelve el tipo de geometría del valor de ST_Geometry.
geometry ST_GeometryN(
geometry geomA, integer n)
;
Devuelve la geometría en la cual se basa si la geometría es una GEOMETRYCOLLECTION, un (MULTI)POINT, una (MULTI)LINESTRING, una MULTICURVE o un (MULTI)POLYGON, una POLYHEDRALSURFACE si no devuelve NULL.
![]() | |
El indice es 1-based en la especificación OGC desde la version 0.8.0. Versiones anteriormente implementadas era de tipo 0-based. |
![]() | |
Si quieres extraer todas las geometrías de una geometría, ST_Dump es mas eficiente y funcionará con geometrías simples. |
Mejorado: 2.0.0 se introdujo soporte para superficies poliédricas, Triangulos y TIN.
Cambiado: 2.0.0 Versiones anteriores devuelven NULL para geometrias simples. Esto ha sido cambiado para devolver la geometría en el caso de 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);
-- Ejemplo de superficie de poliedros -- Romper una superficie poliédrica en sus caras 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 — Devuelve el tipo de geometría del valor de ST_Geometry.
text ST_GeometryType(
geometry g1)
;
Devuelve el tipo de geometría como una cadena de texto. Por Ejemplo: 'ST_LineString', 'ST_Polygon','ST_MultiPolygon' etc. Esta función difiere de GeometryType(geometría) en este caso se devuelve la cadena de texto y ST delante, como el hecho de que no indicará como se mide la geometría.
Mejora: 2.0.0 se introdujo soporte de superficies poliédricas.
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)')); --resultado ST_LineString
SELECT ST_GeometryType(ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )')); --result ST_PolyhedralSurface
SELECT ST_GeometryType(ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )')); --result ST_PolyhedralSurface
SELECT ST_GeometryType(geom) as result FROM (SELECT ST_GeomFromEWKT('TIN ((( 0 0 0, 0 0 1, 0 1 0, 0 0 0 )), (( 0 0 0, 0 1 0, 1 1 0, 0 0 0 )) )') AS geom ) AS g; result -------- ST_Tin
ST_HasArc — Tests if a geometry contains a circular arc
boolean ST_IsEmpty(
geometry geomA)
;
Devuelve True si la Geometría es una colección vacía, polígono vacio, punto vacío etc.
Disponibilidad: 1.2.2
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
ST_InteriorRingN — Devuelva el número de anillos interiores de una geometría poligonal.
geometry ST_InteriorRingN(
geometry a_polygon, integer n)
;
Devuelve la cadena de texto del anillo interior N del poligono. Devuelve NULL si la geometría no es un polígono o el indice N dado esta fuera de rango.
![]() | |
Esto no funcionara con MULTIPOLYGONs. Para MULTIPOLYGONs utilizaba junto a 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 — Devuelve TRUE
si los puntos de inicio y final de una LINESTRING
son coincidentes. Para superficies poliedricas si son cerradas (volumetricas).
boolean ST_IsClosed(
geometry g)
;
Devuelve TRUE
si los puntos de inicio y final de una LINESTRING
son coincidentes. Para superficies poliédricas , te dice si las superficies son áreas (abiertas) o si son volumétricas (cerradas).
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3: 7.1.5, 9.3.3
![]() | |
SQL-MM define que el resultado de |
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
Mejora: 2.0.0 se introdujo soporte de superficies poliédricas.
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)
-- Un cubo -- 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 -- Mismo cubo pero faltando un lado -- 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 — Devuelve True si la Geometría es una colección vacía, polígono vacio, punto vacío etc.
boolean ST_IsCollection(
geometry g)
;
Devuelve TRUE
si la geometría del argumento es:
GEOMETRYCOLLECTION
MULTI{POINT,POLYGON,LINESTRING,CURVE,SURFACE}
COMPOUNDCURVE
![]() | |
Esta función analiza el tipo de geometría. Esto significa que devolverá |
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)
;
Devuelve True si la Geometría es una geometría vacía. Si es cierto, entonces esta Geometría representa una colección de geometrías vacías, polígonos vacíos, puntos vacíos, etc.
![]() | |
SQL-MM define que el resultado de ST_IsEmpty(NULL) debe ser 0, mientras que PostGIS devuelve |
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
![]() | |
Cambiado: 2.0.0 En las versiones anteriores de PostGIS ST_GeomFromText('GEOMETRYCOLLECTION(EMPTY)') estaba permitido. Esto no esta permitido ahora en PostGIS 2.0.0 para ajustarse mejor a las normas 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 — Devuelve true si todos los aros exteriores están orientados hacia la izquierda y todos los aros interiores están orientados hacia la derecha.
boolean ST_IsPolygonCCW (
geometry geom )
;
Devuelve true si todos los componentes poligonales de la geometría de entrada utilizan una orientación contraria a las manecillas del reloj para su aro exterior y una dirección en el sentido de las manecillas del reloj para todos los anillos interiores.
Devuelve true si la geometría no tiene componentes poligonales.
![]() | |
Cadenas de líneas cerradas no se consideran componentes poligonales, por lo que aún obtendrá como devolución verdadero por pasar una sola cadena de líneas cerrada sin importar su orientación. |
![]() | |
Si una geometría poligonal no utiliza la orientación inversa para los anillos interiores (es decir, si uno o más anillos interiores están orientados en la misma dirección que un anillo exterior), ambos ST_IsPolygonCW y ST_IsPolygonCCW devolverán false. |
Disponibilidad: 2.2.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_IsPolygonCW — Devuelve true si todos los aros exteriores están orientados hacia la derecha y todos los aros interiores están orientados en sentido contrario a las agujas del reloj.
boolean ST_IsPolygonCW (
geometry geom )
;
Devuelve true si todos los componentes poligonales de la geometría de entrada utilizan una orientación horaria para su aro exterior y una dirección contraria a las manecillas del reloj para todos los anillos interiores.
Devuelve true si la geometría no tiene componentes poligonales.
![]() | |
Cadenas de líneas cerradas no se consideran componentes poligonales, por lo que aún obtendrá como devolución verdadero por pasar una sola cadena de líneas cerrada sin importar su orientación. |
![]() | |
Si una geometría poligonal no utiliza la orientación inversa para los anillos interiores (es decir, si uno o más anillos interiores están orientados en la misma dirección que un anillo exterior), ambos ST_IsPolygonCW y ST_IsPolygonCCW devolverán false. |
Disponibilidad: 2.2.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_IsRing — Tests if a LineString is closed and simple.
boolean ST_IsRing(
geometry g)
;
Devuelve TRUE
si esta LINESTRING
es ST_IsClosed (ST_StartPoint(
g
)~=
ST_Endpoint(
) y ST_IsSimple (no se intersecta con ella misma).g
)
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. 2.1.5.1
This method implements the SQL/MM specification. SQL-MM 3: 7.1.6
![]() | |
SQL-MM define que el resultado de |
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 — Devuelve (TRUE) si la geometría no tiene puntos geométricos anómalos, como auto intersecciones o tangencias.
boolean ST_IsSimple(
geometry geomA)
;
Devuelve TRUE si la geometría no tiene puntos geométricos anómalos, como auto intersecciones o tangencias. Para mas información sobre la definición del OGC de simplicidad y validez geométrica, visita el enlace "Ensuring OpenGIS compliancy of geometries"
![]() | |
SQL-MM define que el resultado de ST_IsSimple(NULL) debe ser 0, mientras que PostGIS devuelve NULL. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s2.1.1.1
This method implements the SQL/MM specification. SQL-MM 3: 5.1.8
This function supports 3d and will not drop the z-index.
ST_M — Returns the M coordinate of a Point.
float ST_M(
geometry a_point)
;
Devuelve la coordenada M del punto, o NULL si no seta disponible. La entrada debe ser un punto.
![]() | |
Esto no es (todavía) parte de la especificación OGC, pero esta incluida aquí para completar la lista de extracción de coordenadas de un punto. |
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 — Devuelve el tipo de geometría del valor de ST_Geometry.
integer ST_NRings(
geometry geomA)
;
Devuelve el tipo de geometría del valor de ST_Geometry.
This complements the PostgreSQL built-in database object functions pg_column_size, pg_size_pretty, pg_relation_size, pg_total_relation_size.
![]() | |
pg_relation_size which gives the byte size of a table may return byte size lower than ST_MemSize. This is because pg_relation_size does not add toasted table contribution and large geometries are stored in TOAST tables. pg_total_relation_size - includes, the table, the toasted tables, and the indexes. pg_column_size returns how much space a geometry would take in a column considering compression, so may be lower than ST_MemSize |
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Changed: 2.2.0 name changed to ST_MemSize to follow naming convention.
--Return how much byte space Boston takes up in our Mass data set SELECT pg_size_pretty(SUM(ST_MemSize(geom))) as totgeomsum, pg_size_pretty(SUM(CASE WHEN town = 'BOSTON' THEN ST_MemSize(geom) ELSE 0 END)) As bossum, CAST(SUM(CASE WHEN town = 'BOSTON' THEN ST_MemSize(geom) ELSE 0 END)*1.00 / SUM(ST_MemSize(geom))*100 As numeric(10,2)) As perbos FROM towns; totgeomsum bossum perbos ---------- ------ ------ 1522 kB 30 kB 1.99 SELECT ST_MemSize(ST_GeomFromText('CIRCULARSTRING(220268 150415,220227 150505,220227 150406)')); --- 73 --What percentage of our table is taken up by just the geometry SELECT pg_total_relation_size('public.neighborhoods') As fulltable_size, sum(ST_MemSize(geom)) As geomsize, sum(ST_MemSize(geom))*1.00/pg_total_relation_size('public.neighborhoods')*100 As pergeom FROM neighborhoods; fulltable_size geomsize pergeom ------------------------------------------------ 262144 96238 36.71188354492187500000
ST_NDims — Devuelve la dimensión de las coordenadas del valor de ST_Geometry.
integer ST_NDims(
geometry g1)
;
Devuelve la dimension de las coordenadas de la geometría. PostGIS soporta 2 - (x,y), 3 - (x,y,z) o 2D con medidas - x,y,m y 4 -3D con mediadas en el espacio x,y,z,m.
This function supports 3d and will not drop the z-index.
ST_NPoints — Devuelve el numero de puntos (vértices) en la geometría.
integer ST_NPoints(
geometry g1)
;
Devuelve el numero de puntos en la geometría. Funciona con todas las geometrías.
Mejora: 2.0.0 se introdujo soporte de superficies poliédricas.
![]() | |
Anterior a 1.3.4, esta función daba errores si se utilizaba con geometrias que contenían CURVES. Esto se corrigió en 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 — Devuelva el número de anillos interiores de una geometría poligonal.
integer ST_NRings(
geometry geomA)
;
Si la geometria es un polígono o un multi-polígono devuelve el numero de anillos. Al contrario que NumInteriorRings, cuenta el anille exterior tambien.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
ST_NumGeometries — Devuelve el numero de puntos en la geometría. Funciona con todas las geometrías.
integer ST_NumGeometries(
geometry geom)
;
Devuelve el numero de geometrías. Si la geometría es una GEOMETRYCOLLECTION (o MULTI*) devuelve el numero de geometrías, para geometrias simples devuelve 1, si no devuelve NULL.
Mejorado: 2.0.0 se introdujo soporte para superficies poliédricas, Triangulos y TIN.
Cambiado: 2.0.0 En versiones anteriores esto devolvería NULL si la geometría no era de tipo collection/MULTI. 2.0.0+ devuelve 1 para geometrías simples, por ejemplo, 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 — Devuelva el número de anillos interiores de una geometría poligonal.
integer ST_NumInteriorRings(
geometry a_polygon)
;
Devuelve el número de anillos interiores de una geometría poligonal. Devuelve NULL si la geometría no es un polígono.
This method implements the SQL/MM specification. SQL-MM 3: 8.2.5
Cambiado: 2.0.0 - En versiones anteriores permitiría pasar un multipolígono, devolviendo el número de anillos interiores de primer polígono.
-- Si tiene un polígono regular SELECT gid, field1, field2, ST_NumInteriorRings(the_geom) AS numholes FROM sometable; -- Si tiene multipolígonos. -- Y quieres saber el número total de anillos interiores en el MULTIPOLYGON SELECT gid, field1, field2, SUM(ST_NumInteriorRings(the_geom)) AS numholes FROM (SELECT gid, field1, field2, (ST_Dump(the_geom)).geom As the_geom FROM sometable) As foo GROUP BY gid, field1,field2;
ST_NumInteriorRing — Devuelve el número de anillos interiores de un polígono en la geometría. Sinónimo de ST_NumInteriorRings.
integer ST_NumInteriorRing(
geometry a_polygon)
;
ST_NumPatches — Devuelve el número de caras en una superficie poliédrica. Devolverá nulo para geometrías no poliédricas.
integer ST_NumPatches(
geometry g1)
;
Devuelve el número de caras en una superficie poliédrica. Devolverá nulo para geometrías no poliédricas. Esto es un alias para ST_NumGeometries para admitir nombres MM. Más rápido para usar ST_NumGeometries si no te importa la convención MM.
Disponibilidad: 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 — Devuelve el número de puntos en un valor ST_LineString o ST_CircularString.
integer ST_NumPoints(
geometry g1)
;
Devuelve el número de puntos en un valor ST_LineString o ST_CircularString. Antes de 1.4 sólo funcionaba con cadenas de línea como el estado de especificaciones. A partir de 1.4, esto es un alias para ST_NPoints que devuelve el número de vértices para no sólo las cadenas de línea. Considere el uso de ST_NPoints en su lugar, que es multiuso y funciona con muchos tipos de geometría.
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 — Devuelve el tipo de geometría del valor de ST_Geometry.
geometry ST_PatchN(
geometry geomA, integer n)
;
Devuelve la 1 geometría de base n-ésima (cara) si la geometría es un POLYHEDRALSURFACE, POLYHEDRALSURFACEM. De lo contrario, devuelve NULL. Esto devuelve la misma respuesta que ST_GeometryN para las superficies de poliedros. Usar ST_GemoetryN es más rápido.
![]() | |
El índice está basado en 1. |
![]() | |
Si desea extraer todas las geometrías, de una geometría, ST_Dump es más eficiente. |
Disponibilidad: 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.
-- Extraer la 2ª cara de la superficie poliédrica 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 — Devuelve el número de puntos en un valor ST_LineString o ST_CircularString.
geometry ST_PointN(
geometry a_linestring, integer n)
;
Devuelve el punto enésimo en una sola cadena de línea o cadena de línea circular en la geometría. Los valores negativos se contabilizan hacia atrás desde el final de la cadena de línea, por lo que -1 es el último punto. Devuelve NULL si no hay cadena de línea en la geometría.
![]() | |
El índice se basa en 1 como para las especificaciones OGC desde la versión 0.8.0. La indexación hacia atrás (índice negativo) no se encuentra en versiones anteriores de OGC implementado esto como basado en 0 en su lugar. |
![]() | |
Si desea obtener el punto n-ésimo de cada cadena de línea en una multiple cadena de línea, utilícelo en conjunción con 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
![]() | |
Cambiado: 2.0.0 ya no funciona con una sola geometría multilinestrings. En versiones antiguas de PostGIS -- una sola línea MultiLineString trabajaría felizmente con esta función y regresaría el punto de inicio. En 2.0.0 sólo devuelve NULL como cualquier otro MultiLineString. Cambiado: 2.3.0: indexación negativa disponible (-1 es el último punto) |
-- Extraer todos los POINTs de un 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) -- Ejemplo de cadena circular SELECT ST_AsText(ST_PointN(ST_GeomFromText('CIRCULARSTRING(1 2, 3 2, 1 2)'),2)); st_astext ---------- POINT(3 2) SELECT st_astext(f) FROM ST_GeometryFromtext('LINESTRING(0 0 0, 1 1 1, 2 2 2)') as g ,ST_PointN(g, -2) AS f -- 1 based index st_astext ---------- "POINT Z (1 1 1)"
ST_Points — Devuelve un MultiPoint que contiene todas las coordenadas de una geometría.
geometry ST_Points(
geometry geom )
;
Returns a MultiPoint containing all the coordinates of a geometry. Duplicate points are preserved, including the start and end points of ring geometries. (If desired, duplicate points can be removed by calling ST_RemoveRepeatedPoints on the result).
To obtain information about the position of each coordinate in the parent geometry use ST_NumPoints.
M and Z coordinates are preserved if present.
This method supports Circular Strings and Curves
This function supports 3d and will not drop the z-index.
Disponibilidad: 2.3.0
ST_StartPoint — Returns the first point of a LineString.
geometry ST_StartPoint(
geometry geomA)
;
Devuelve el primer punto de una geometría LINESTRING
o CIRCULARLINESTRING
como un POINT
o NULL
si el parámetro de entrada no es un LINESTRING
o 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. Cambiado: 2.0.0 ya no funciona con multilinestrings de geometrías simples. En versiones anteriores de PostGIS -- una linea simple multilinestring funciona sin problemas con esta función y devuelve el punto inicial. En la version 2.0.0 simplemente devuelve NULL como con cualquier multilinestring. La antigua version era una función sin documentar, pero la gente que asumía que tenia sus datos almacenados en LINESTRING pueden experimentar este comportamiento ahora de resultado NULL en la version 2.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)
Devuelve el número de puntos en un valor ST_LineString o ST_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 — Devuelve un resumen de texto del contenido de la geometría.
text ST_Summary(
geometry g)
;
text ST_Summary(
geography g)
;
Devuelve un resumen de texto del contenido de la geometría.
Las banderas que se muestran entre corchetes después del tipo de geometría tienen el siguiente significado:
M: tiene ordenada M
Z: tiene ordenada Z
B: Tiene un cuadro de delimitación en caché
G: es geodésico (geography)
S: tiene un sistema de referencia espacial
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Disponibilidad: 1.2.2
Mejorado: 2.0.0 agregó soporte para geography
Mejorada: 2.1.0 Indicador S para señalar si tiene un sistema de referencia espacial conocido
Mejorado: 2.2.0 agregó soporte para TIN y curvas
=# 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)
;
Devuelve la coordenada X del punto, o NULL si no está disponible. La entrada debe ser un punto.
![]() | |
To get the minimum and maximum X value of geometry coordinates use the functions ST_XMin and ST_XMax. |
This method implements the SQL/MM specification. SQL-MM 3: 6.1.3
This function supports 3d and will not drop the z-index.
ST_Y — Returns the Y coordinate of a Point.
float ST_Y(
geometry a_point)
;
Devuelve la coordenada Y del punto, o NULL si no está disponible. La entrada debe ser un punto.
![]() | |
To get the minimum and maximum Y value of geometry coordinates use the functions ST_YMin and ST_YMax. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3: 6.1.4
This function supports 3d and will not drop the z-index.
ST_Z — Returns the Z coordinate of a Point.
float ST_Z(
geometry a_point)
;
Devuelve la coordenada Z del punto, o NULL si no está disponible. La entrada debe ser un punto.
![]() | |
To get the minimum and maximum Z value of geometry coordinates use the functions ST_ZMin and ST_ZMax. |
This method implements the SQL/MM specification.
This function supports 3d and will not drop the z-index.
ST_Zmflag — Devuelve la dimensión de las coordenadas del valor de ST_Geometry.
smallint ST_Zmflag(
geometry geomA)
;
Devuelve la dimensión de las coordenadas del valor de ST_Geometry.
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 — Añade un punto a una cadena de línea.
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.
Disponibilidad: 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. |
Disponibilidad: 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. |
Disponibilidad: 2.0.0
Single-element collection converted to an atomic geometry
SELECT ST_AsText(ST_CollectionHomogenize('GEOMETRYCOLLECTION(POINT(0 0))')); st_astext ------------ POINT(0 0)
Nested single-element collection converted to an atomic geometry:
SELECT ST_AsText(ST_CollectionHomogenize('GEOMETRYCOLLECTION(MULTIPOINT((0 0)))')); st_astext ------------ POINT(0 0)
Collection converted to a multi-geometry:
SELECT ST_AsText(ST_CollectionHomogenize('GEOMETRYCOLLECTION(POINT(0 0),POINT(1 1))')); st_astext --------------------- MULTIPOINT((0 0),(1 1))
Nested heterogeneous collection flattened to a GeometryCollection:
SELECT ST_AsText(ST_CollectionHomogenize('GEOMETRYCOLLECTION(POINT(0 0), GEOMETRYCOLLECTION( LINESTRING(1 1, 2 2)))')); st_astext --------------------- GEOMETRYCOLLECTION(POINT(0 0),LINESTRING(1 1,2 2))
Collection of Polygons converted to an (invalid) MultiPolygon:
SELECT ST_AsText(ST_CollectionHomogenize('GEOMETRYCOLLECTION (POLYGON ((10 50, 50 50, 50 10, 10 10, 10 50)), POLYGON ((90 50, 90 10, 50 10, 50 50, 90 50)))')); st_astext --------------------- MULTIPOLYGON(((10 50,50 50,50 10,10 10,10 50)),((90 50,90 10,50 10,50 50,90 50)))
ST_CurveToLine — Converts a geometry containing curves to a linear geometry.
geometry ST_CurveToLine(
geometry curveGeom, float tolerance, integer tolerance_type, integer flags)
;
Converts a CIRCULAR STRING to regular LINESTRING or CURVEPOLYGON to POLYGON or MULTISURFACE to MULTIPOLYGON. Useful for outputting to devices that can't support CIRCULARSTRING geometry types
Converts a given geometry to a linear geometry. Each curved geometry or segment is converted into a linear approximation using the given `tolerance` and options (32 segments per quadrant and no options by default).
The 'tolerance_type' argument determines interpretation of the `tolerance` argument. It can take the following values:
0 (default): Tolerance is max segments per quadrant.
1: Tolerance is max-deviation of line from curve, in source units.
2: Tolerance is max-angle, in radians, between generating radii.
The 'flags' argument is a bitfield. 0 by default. Supported bits are:
1: Symmetric (orientation idependent) output.
2: Retain angle, avoids reducing angles (segment lengths) when producing symmetric output. Has no effect when Symmetric flag is off.
Availability: 1.3.0
Enhanced: 2.4.0 added support for max-deviation and max-angle tolerance, and for symmetric output.
Enhanced: 3.0.0 implemented a minimum number of segments per linearized arc to prevent topological collapse.
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3: 7.1.7
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
SELECT ST_AsText(ST_CurveToLine(ST_GeomFromText('CIRCULARSTRING(220268 150415,220227 150505,220227 150406)'))); --Result -- LINESTRING(220268 150415,220269.95064912 150416.539364228,220271.823415575 150418.17258804,220273.613787707 150419.895736857, 220275.317452352 150421.704659462,220276.930305234 150423.594998003,220278.448460847 150425.562198489, 220279.868261823 150427.60152176,220281.186287736 150429.708054909,220282.399363347 150431.876723113, 220283.50456625 150434.10230186,220284.499233914 150436.379429536,220285.380970099 150438.702620341,220286.147650624 150441.066277505, 220286.797428488 150443.464706771,220287.328738321 150445.892130112,220287.740300149 150448.342699654, 220288.031122486 150450.810511759,220288.200504713 150453.289621251,220288.248038775 150455.77405574, 220288.173610157 150458.257830005,220287.977398166 150460.734960415,220287.659875492 150463.199479347, 220287.221807076 150465.64544956,220286.664248262 150468.066978495,220285.988542259 150470.458232479,220285.196316903 150472.81345077, 220284.289480732 150475.126959442,220283.270218395 150477.39318505,220282.140985384 150479.606668057, 220280.90450212 150481.762075989,220279.5637474 150483.85421628,220278.12195122 150485.87804878, 220276.582586992 150487.828697901,220274.949363179 150489.701464356,220273.226214362 150491.491836488, 220271.417291757 150493.195501133,220269.526953216 150494.808354014,220267.559752731 150496.326509628, 220265.520429459 150497.746310603,220263.41389631 150499.064336517,220261.245228106 150500.277412127, 220259.019649359 150501.38261503,220256.742521683 150502.377282695,220254.419330878 150503.259018879, 220252.055673714 150504.025699404,220249.657244448 150504.675477269,220247.229821107 150505.206787101, 220244.779251566 150505.61834893,220242.311439461 150505.909171266,220239.832329968 150506.078553494, 220237.347895479 150506.126087555,220234.864121215 150506.051658938,220232.386990804 150505.855446946, 220229.922471872 150505.537924272,220227.47650166 150505.099855856,220225.054972724 150504.542297043, 220222.663718741 150503.86659104,220220.308500449 150503.074365683, 220217.994991777 150502.167529512,220215.72876617 150501.148267175, 220213.515283163 150500.019034164,220211.35987523 150498.7825509, 220209.267734939 150497.441796181,220207.243902439 150496, 220205.293253319 150494.460635772,220203.420486864 150492.82741196,220201.630114732 150491.104263143, 220199.926450087 150489.295340538,220198.313597205 150487.405001997,220196.795441592 150485.437801511, 220195.375640616 150483.39847824,220194.057614703 150481.291945091,220192.844539092 150479.123276887,220191.739336189 150476.89769814, 220190.744668525 150474.620570464,220189.86293234 150472.297379659,220189.096251815 150469.933722495, 220188.446473951 150467.535293229,220187.915164118 150465.107869888,220187.50360229 150462.657300346, 220187.212779953 150460.189488241,220187.043397726 150457.710378749,220186.995863664 150455.22594426, 220187.070292282 150452.742169995,220187.266504273 150450.265039585,220187.584026947 150447.800520653, 220188.022095363 150445.35455044,220188.579654177 150442.933021505,220189.25536018 150440.541767521, 220190.047585536 150438.18654923,220190.954421707 150435.873040558,220191.973684044 150433.60681495, 220193.102917055 150431.393331943,220194.339400319 150429.237924011,220195.680155039 150427.14578372,220197.12195122 150425.12195122, 220198.661315447 150423.171302099,220200.29453926 150421.298535644,220202.017688077 150419.508163512,220203.826610682 150417.804498867, 220205.716949223 150416.191645986,220207.684149708 150414.673490372,220209.72347298 150413.253689397,220211.830006129 150411.935663483, 220213.998674333 150410.722587873,220216.22425308 150409.61738497,220218.501380756 150408.622717305,220220.824571561 150407.740981121, 220223.188228725 150406.974300596,220225.586657991 150406.324522731,220227 150406) --3d example SELECT ST_AsEWKT(ST_CurveToLine(ST_GeomFromEWKT('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)'))); Output ------ LINESTRING(220268 150415 1,220269.95064912 150416.539364228 1.0181172856673, 220271.823415575 150418.17258804 1.03623457133459,220273.613787707 150419.895736857 1.05435185700189,....AD INFINITUM .... 220225.586657991 150406.324522731 1.32611114201132,220227 150406 3) --use only 2 segments to approximate quarter circle SELECT ST_AsText(ST_CurveToLine(ST_GeomFromText('CIRCULARSTRING(220268 150415,220227 150505,220227 150406)'),2)); st_astext ------------------------------ LINESTRING(220268 150415,220287.740300149 150448.342699654,220278.12195122 150485.87804878, 220244.779251566 150505.61834893,220207.243902439 150496,220187.50360229 150462.657300346, 220197.12195122 150425.12195122,220227 150406) -- Ensure approximated line is no further than 20 units away from -- original curve, and make the result direction-neutral SELECT ST_AsText(ST_CurveToLine( 'CIRCULARSTRING(0 0,100 -100,200 0)'::geometry, 20, -- Tolerance 1, -- Above is max distance between curve and line 1 -- Symmetric flag )); st_astext ------------------------------------------------------------------------------------------- LINESTRING(0 0,50 -86.6025403784438,150 -86.6025403784439,200 -1.1331077795296e-13,200 0)
ST_Scroll — Change start point of a closed LineString.
geometry ST_Scroll(
geometry linestring, geometry point)
;
Changes the start/end point of a closed LineString to the given vertex point
.
Availability: 3.2.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_FlipCoordinates — Returns a version of a geometry with X and Y axis flipped.
geometry ST_FlipCoordinates(
geometry geom)
;
Returns a version of the given geometry with X and Y axis flipped. Useful for fixing geometries which contain coordinates expressed as latitude/longitude (Y,X).
Disponibilidad: 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 — Forzar las geometrías en un "modo de 2 dimensiones".
geometry ST_Force2D(
geometry geomA)
;
Forzar las geometrías en un "modo de 2 dimensiones" para que todas las representaciones de salida sólo tengan las coordenadas X e Y. Esto es útil para forzar la salida compatible con OGC (ya que OGC sólo especifica geometría 2D).
Mejorado: 2.0.0 soporte para superficies poliédricas fue introducida.
Cambiado: 2.1.0. Hasta la 2.0.x esto se llamaba 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 — Forzar las geometrías en modo XYZ. Este es un alias para 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.
Mejorado: 2.0.0 soporte para superficies poliédricas fue introducida.
Cambiado: 2.1.0. Hasta la 2.0.x esto se llamaba 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.
--Nada le pasa a una geometría que ya es 3D 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 — Fuerza las geometrías en modo XYZ.
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.
Mejorado: 2.0.0 soporte para superficies poliédricas fue introducida.
Cambiado: 2.1.0. Hasta la 2.0.x esto se llamaba 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
--Nada le pasa a una geometría que ya es 3D 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 — Fuerza las geometrías en modo XYM.
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
Cambiado: 2.1.0. Hasta la 2.0.x esto se llamaba ST_Force_3DM.
Changed: 3.1.0. Added support for supplying a non-zero M value.
This method supports Circular Strings and Curves
--Nada le pasa a una geometría que ya es 3D 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 — Fuerza las geometrías en modo XYZM.
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.
Cambiado: 2.1.0. Hasta la 2.0.x esto se llamaba 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
--Nada le pasa a una geometría que ya es 3D 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 — Orienta todos los aros exteriores en sentido contrario a las agujas del reloj y todos los aros interiores en sentido horario.
geometry ST_ForcePolygonCCW (
geometry geom )
;
Fuerza (Multi)polígonos a utilizar una orientación en sentido contrario a las manecillas del reloj para su anillo exterior, y una orientación en el sentido de las agujas del reloj para sus anillos interiores. Las geometrías no poligonales se devuelven sin cambios.
Availability: 2.4.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_ForceCollection — Convertir la geometría en una GEOMETRYCOLLECTION.
geometry ST_ForceCollection(
geometry geomA)
;
Convierte la geometría en una GEOMETRYCOLLECTION. Esto es útil para simplificar la representación WKB.
Mejorado: 2.0.0 soporte para superficies poliédricas fue introducida.
Disponibilidad: 1.2.2, antes de 1.3.4 esta función se bloqueará con curvas. Esto se fija en 1.3.4 +
Cambiado: 2.1.0. Hasta la 2.0.x esto se llamaba 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)
-- Ejemplo POLYHEDRAL -- 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 — Orienta todos los anillos exteriores en el sentido de las agujas del reloj y todos los anillos interiores en sentido contrario a las agujas del reloj.
geometry ST_ForcePolygonCW (
geometry geom )
;
Fuerza (Multi)Polígonos a utilizar una orientación en el sentido de las agujas del reloj para su anillo exterior, y una orientación en sentido contrario a las agujas del reloj para sus anillos interiores. Las geometrías no poligonales se devuelven sin cambios.
Availability: 2.4.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_ForceSFS — Fuerza las geometrías para usar sólo los tipos de geometría SFS 1.1.
geometry ST_ForceSFS(
geometry geomA)
;
geometry ST_ForceSFS(
geometry geomA, text version)
;
ST_ForceRHR — Fuerza la orientación de los vértices en un polígono para seguir la regla de la mano derecha.
geometry ST_ForceRHR(
geometry g)
;
Fuerce la orientación de los vértices en un polígono para seguir la regla de la mano derecha, en el cual, el área que está delimitada por el polígono está a la derecha del límite. En particular, el anillo exterior está orientado en el sentido de las agujas del reloj y el interior está orientado en sentido contrario a las agujas del reloj. Esta función es sinónimo de ST_ForcePolygonCW
![]() | |
La definición anterior de la regla de la derecha entra en conflicto con definiciones utilizadas en otros contextos. Para evitar la confusión, se recomienda utilizar ST_ForcePolygonCW. |
Mejorado: 2.0.0 soporte para superficies poliédricas fue introducida.
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 — Relanzar una geometría en su tipo curvo, si corresponde.
geometry ST_ForceCurve(
geometry g)
;
Convierte una geometría en su representación curvada, si corresponde: las líneas se convierten en curvas compuestas, las multilíneas se convierten en polígonos multicurvos se convierten en polígonos de curvas los multipolígonos se convierten en multisuperficies. Si la entrada de geometría es ya una representación curvada regresa igual que la entrada.
Disponibilidad: 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 — Devuelve la geometría como una geometría MULTI*.
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 — Devuelve la geometría en su forma canónica.
geometry ST_Normalize(
geometry geom)
;
Devuelve la geometría en su forma normalizada/canónica. Puede reordenar vértices en anillos poligonales, anillos en un polígono, elementos en un complejo de geometría múltiple.
Principalmente útil sólo para propósitos de prueba (comparando los resultados esperados y los obtenidos).
Disponibilidad: 2.3.0
SELECT ST_AsText(ST_Normalize(ST_GeomFromText( 'GEOMETRYCOLLECTION( POINT(2 3), MULTILINESTRING((0 0, 1 1),(2 2, 3 3)), POLYGON( (0 10,0 0,10 0,10 10,0 10), (4 2,2 2,2 4,4 4,4 2), (6 8,8 8,8 6,6 6,6 8) ) )' ))); st_astext ---------------------------------------------------------------------------------------------------------------------------------------------------- GEOMETRYCOLLECTION(POLYGON((0 0,0 10,10 10,10 0,0 0),(6 6,8 6,8 8,6 8,6 6),(2 2,4 2,4 4,2 4,2 2)),MULTILINESTRING((2 2,3 3),(0 0,1 1)),POINT(2 3)) (1 row)
ST_QuantizeCoordinates — Sets least significant bits of coordinates to zero
geometry ST_QuantizeCoordinates (
geometry g , int prec_x , int prec_y , int prec_z , int prec_m )
;
ST_QuantizeCoordinates
determines the number of bits (N
) required to represent a coordinate value with a specified number of digits after the decimal point, and then sets all but the N
most significant bits to zero. The resulting coordinate value will still round to the original value, but will have improved compressiblity. This can result in a significant disk usage reduction provided that the geometry column is using a compressible storage type. The function allows specification of a different number of digits after the decimal point in each dimension; unspecified dimensions are assumed to have the precision of the x
dimension. Negative digits are interpreted to refer digits to the left of the decimal point, (i.e., prec_x=-2
will preserve coordinate values to the nearest 100.
The coordinates produced by ST_QuantizeCoordinates
are independent of the geometry that contains those coordinates and the relative position of those coordinates within the geometry. As a result, existing topological relationships between geometries are unaffected by use of this function. The function may produce invalid geometry when it is called with a number of digits lower than the intrinsic precision of the geometry.
Availability: 2.5.0
PostGIS stores all coordinate values as double-precision floating point integers, which can reliably represent 15 significant digits. However, PostGIS may be used to manage data that intrinsically has fewer than 15 significant digits. An example is TIGER data, which is provided as geographic coordinates with six digits of precision after the decimal point (thus requiring only nine significant digits of longitude and eight significant digits of latitude.)
When 15 significant digits are available, there are many possible representations of a number with 9 significant digits. A double precision floating point number uses 52 explicit bits to represent the significand (mantissa) of the coordinate. Only 30 bits are needed to represent a mantissa with 9 significant digits, leaving 22 insignificant bits; we can set their value to anything we like and still end up with a number that rounds to our input value. For example, the value 100.123456 can be represented by the floating point numbers closest to 100.123456000000, 100.123456000001, and 100.123456432199. All are equally valid, in that ST_AsText(geom, 6)
will return the same result with any of these inputs. As we can set these bits to any value, ST_QuantizeCoordinates
sets the 22 insignificant bits to zero. For a long coordinate sequence this creates a pattern of blocks of consecutive zeros that is compressed by PostgreSQL more effeciently.
![]() | |
Only the on-disk size of the geometry is potentially affected by |
SELECT ST_AsText(ST_QuantizeCoordinates('POINT (100.123456 0)'::geometry, 4)); st_astext ------------------------- POINT(100.123455047607 0)
WITH test AS (SELECT 'POINT (123.456789123456 123.456789123456)'::geometry AS geom) SELECT digits, encode(ST_QuantizeCoordinates(geom, digits), 'hex'), ST_AsText(ST_QuantizeCoordinates(geom, digits)) FROM test, generate_series(15, -15, -1) AS digits; digits | encode | st_astext --------+--------------------------------------------+------------------------------------------ 15 | 01010000005f9a72083cdd5e405f9a72083cdd5e40 | POINT(123.456789123456 123.456789123456) 14 | 01010000005f9a72083cdd5e405f9a72083cdd5e40 | POINT(123.456789123456 123.456789123456) 13 | 01010000005f9a72083cdd5e405f9a72083cdd5e40 | POINT(123.456789123456 123.456789123456) 12 | 01010000005c9a72083cdd5e405c9a72083cdd5e40 | POINT(123.456789123456 123.456789123456) 11 | 0101000000409a72083cdd5e40409a72083cdd5e40 | POINT(123.456789123456 123.456789123456) 10 | 0101000000009a72083cdd5e40009a72083cdd5e40 | POINT(123.456789123455 123.456789123455) 9 | 0101000000009072083cdd5e40009072083cdd5e40 | POINT(123.456789123418 123.456789123418) 8 | 0101000000008072083cdd5e40008072083cdd5e40 | POINT(123.45678912336 123.45678912336) 7 | 0101000000000070083cdd5e40000070083cdd5e40 | POINT(123.456789121032 123.456789121032) 6 | 0101000000000040083cdd5e40000040083cdd5e40 | POINT(123.456789076328 123.456789076328) 5 | 0101000000000000083cdd5e40000000083cdd5e40 | POINT(123.456789016724 123.456789016724) 4 | 0101000000000000003cdd5e40000000003cdd5e40 | POINT(123.456787109375 123.456787109375) 3 | 0101000000000000003cdd5e40000000003cdd5e40 | POINT(123.456787109375 123.456787109375) 2 | 01010000000000000038dd5e400000000038dd5e40 | POINT(123.45654296875 123.45654296875) 1 | 01010000000000000000dd5e400000000000dd5e40 | POINT(123.453125 123.453125) 0 | 01010000000000000000dc5e400000000000dc5e40 | POINT(123.4375 123.4375) -1 | 01010000000000000000c05e400000000000c05e40 | POINT(123 123) -2 | 01010000000000000000005e400000000000005e40 | POINT(120 120) -3 | 010100000000000000000058400000000000005840 | POINT(96 96) -4 | 010100000000000000000058400000000000005840 | POINT(96 96) -5 | 010100000000000000000058400000000000005840 | POINT(96 96) -6 | 010100000000000000000058400000000000005840 | POINT(96 96) -7 | 010100000000000000000058400000000000005840 | POINT(96 96) -8 | 010100000000000000000058400000000000005840 | POINT(96 96) -9 | 010100000000000000000058400000000000005840 | POINT(96 96) -10 | 010100000000000000000058400000000000005840 | POINT(96 96) -11 | 010100000000000000000058400000000000005840 | POINT(96 96) -12 | 010100000000000000000058400000000000005840 | POINT(96 96) -13 | 010100000000000000000058400000000000005840 | POINT(96 96) -14 | 010100000000000000000058400000000000005840 | POINT(96 96) -15 | 010100000000000000000058400000000000005840 | POINT(96 96)
ST_RemovePoint — Remove a point from a linestring.
geometry ST_RemovePoint(
geometry linestring, integer offset)
;
Removes a point from a LineString, given its index (0-based). Useful for turning a closed line (ring) into an open linestring.
Enhanced: 3.2.0
Disponibilidad: 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
Disponibilidad: 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 — Devuelve la geometría con el orden de vértice invertido.
geometry ST_Reverse(
geometry g1)
;
ST_Segmentize — Devuelve una geometry/geography modificada que no tenga un segmento mayor que la distancia dada.
geometry ST_Segmentize(
geometry geom, float max_segment_length)
;
geography ST_Segmentize(
geography geog, float max_segment_length)
;
Devuelve una geometría modificada que no tiene ningún segmento más largo que el max_segment_length
dado . El cálculo de distancia se realiza en 2d solamente. Para geometry, las unidades de longitud están en unidades de referencia espacial. Para geography, las unidades están en metros.
Disponibilidad: 1.2.2
Enhanced: 3.0.0 Segmentize geometry now uses equal length segments
Mejorada: 2.3.0 Segmentize geography ahora utiliza segmentos de igual longitud
Mejorada: 2.1.0 se introdujo el soporte para geography.
Cambiado: 2.1.0 como resultado de la introducción del soporte a geography: la construcción SELECT ST_Segmentize('LINESTRING(1 2, 3 4)',0.5);
producirá un error de función ambigua. Debe tener un objeto correctamente tecleado, por ejemplo, una columna geometry/geography, utilice ST_GeomFromText, ST_GeogFromText o SELECT ST_Segmentize('LINESTRING(1 2, 3 4)'::geometry,0.5);
![]() | |
Esto sólo aumentará los segmentos. No alargará segmentos más cortos que la longitud máxima |
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 — Reemplace el punto de una cadena de línea con un punto dado.
geometry ST_SetPoint(
geometry linestring, integer zerobasedposition, geometry point)
;
Reemplace el punto N de una cadena de línea con el punto dado. El índice comineza en 0. El índice negativo se cuenta hacia atrás, por lo que -1 es el último punto. Esto es especialmente útil en los disparadores cuando se trata de mantener la relación de las articulaciones cuando un vértice se mueve.
Disponibilidad: 1.1.0
Actualizado 2.3.0: indexación negativa
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.
Mejora: 2.0.0 se introdujeron soporte de superficies poliédricas y TIN.
NOTE: this function was renamed from "ST_Shift_Longitude" in 2.2.0
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
--single point forward transformation SELECT ST_AsText(ST_ShiftLongitude('SRID=4326;POINT(270 0)'::geometry)) st_astext ---------- POINT(-90 0) --single point reverse transformation SELECT ST_AsText(ST_ShiftLongitude('SRID=4326;POINT(-90 0)'::geometry)) st_astext ---------- POINT(270 0) --for linestrings the functions affects only to the sufficient coordinates SELECT ST_AsText(ST_ShiftLongitude('SRID=4326;LINESTRING(174 12, 182 13)'::geometry)) st_astext ---------- LINESTRING(174 12,-178 13)
ST_WrapX — Wrap a geometry around an X value.
geometry ST_WrapX(
geometry geom, float8 wrap, float8 move)
;
This function splits the input geometries and then moves every resulting component falling on the right (for negative 'move') or on the left (for positive 'move') of given 'wrap' line in the direction specified by the 'move' parameter, finally re-unioning the pieces together.
![]() | |
This is useful to "recenter" long-lat input to have features of interest not spawned from one side to the other. |
Availability: 2.3.0 requires GEOS
This function supports 3d and will not drop the z-index.
ST_SnapToGrid — Ajusta todos los puntos de la geometría de entrada a una cuadrícula regular.
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)
;
Variante 1, 2, 3: ajusta todos los puntos de la geometría de entrada a la cuadrícula definida por su origen y tamaño de celda. Elimina los puntos consecutivos que caen en la misma celda, eventualmente devuelve NULL si los puntos de salida no son suficientes para definir una geometría del tipo dado. Las geometrías contraídas de una colección se despojan de ella. Útil para reducir la precisión.
Variante 4: introducido 1.1.0 - Ajusta todos los puntos de la geometría de entrada a la cuadrícula definida por su origen (el segundo argumento, debe ser un punto) y tamaños de celda. Especifique 0 como tamaño para cualquier dimensión que no desee ajustar a una cuadrícula.
![]() | |
La geometría devuelta podría perder su simplicidad (ver ST_IsSimple). |
![]() | |
Antes del lanzamiento 1.1.0 esta función siempre devolvió una geometría 2d. A partir de 1.1.0 la geometría devuelta tendrá la misma dimensionalidad que la entrada con valores de dimensión más altos sin tocar. Utilice la versión que toma un segundo argumento de geometría para definir todas las dimensiones de cuadrícula. |
Disponibilidad: 1.0.0RC1
Disponibilidad: 1.1.0 - soporte de Z y M
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 — Ajusta segmentos y vértices de la geometría de entrada a vértices de una geometría de referencia.
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.
El ajustar una geometría a otra puede mejorar la robustez de las operaciones de superposición eliminando los bordes casi coincidentes (que causan problemas durante el cálculo de noding y de intersección).
Un ajuste excesivo puede resultar en la creación de una topología no válida, por lo que el número y la ubicación de los vértices ajustados se deciden usando heurísticas para determinar cuándo es seguro ajustar. Sin embargo, esto puede resultar en que algunos potenciales ajustes se omitan.
![]() | |
La geometría devuelta puede perder su simplicidad (ver ST_IsSimple) y su validez (ver ST_IsValid). |
Realizado por el módulo GEOS.
Disponibilidad: 2.0.0
![]() Un multipolígono mostrado con una cadena de líneas (antes de cualquier ajuste) | |
![]() Un multipolígono se ajustó a una cadena de línea a la tolerancia: 1,01 de distancia. El nuevo multipolígono se muestra en referencia a la cadena de línea
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))) | ![]() Un multipolígono se ajustó a una cadena de línea a la tolerancia: 1,25 de distancia. El nuevo multipolígono se muestra en referencia a la cadena de línea
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))) |
![]() La cadena de línea se ajustó al multipolígono original a la tolerancia 1,01 de distancia. La nueva cadena de línea se muestra con referencia al multipolígono
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)
| ![]() La cadena de línea se ajustó al multipolígono original a la tolerancia 1,25 de distancia. La nueva cadena de línea se muestra con referencia al multipolígono
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.
Disponibilidad: 2.2.0
This method supports Circular Strings and Curves
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
valid_detail
row stating if a geometry is valid or if not a reason and a location.ST_IsValid — Tests if a geometry is well-formed in 2D.
boolean ST_IsValid(
geometry g)
;
boolean ST_IsValid(
geometry g, integer flags)
;
Tests if an ST_Geometry value is well-formed and valid in 2D according to the OGC rules. For geometries with 3 and 4 dimensions, the validity is still only tested in 2 dimensions. For geometries that are invalid, a PostgreSQL NOTICE is emitted providing details of why it is not valid.
For the version with the flags
parameter, supported values are documented in ST_IsValidDetail This version does not print a NOTICE explaining invalidity.
For more information on the definition of geometry validity, refer to Section 4.4, “Geometry Validation”
![]() | |
SQL-MM defines the result of ST_IsValid(NULL) to be 0, while PostGIS returns NULL. |
Performed by the GEOS module.
The version accepting flags is available starting with 2.0.0.
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3: 5.1.9
![]() | |
Neither OGC-SFS nor SQL-MM specifications include a flag argument for ST_IsValid. The flag is a PostGIS extension. |
ST_IsValidDetail — Returns a valid_detail
row stating if a geometry is valid or if not a reason and a location.
valid_detail ST_IsValidDetail(
geometry geom, integer flags)
;
Returns a valid_detail
row, containing a boolean (valid
) stating if a geometry is valid, a varchar (reason
) stating a reason why it is invalid and a geometry (location
) pointing out where it is invalid.
Useful to improve on the combination of ST_IsValid and ST_IsValidReason to generate a detailed report of invalid geometries.
The optional flags
parameter is a bitfield. It can have the following values:
0: Use usual OGC SFS validity semantics.
1: Consider certain kinds of self-touching rings (inverted shells and exverted holes) as valid. This is also known as "the ESRI flag", since this is the validity model used by those tools. Note that this is invalid under the OGC model.
Performed by the GEOS module.
Availability: 2.0.0
--First 3 Rejects from a successful quintuplet experiment SELECT gid, reason(ST_IsValidDetail(geom)), ST_AsText(location(ST_IsValidDetail(geom))) as location FROM (SELECT ST_MakePolygon(ST_ExteriorRing(e.buff), array_agg(f.line)) As geom, gid FROM (SELECT ST_Buffer(ST_Point(x1*10,y1), z1) As buff, x1*10 + y1*100 + z1*1000 As gid FROM generate_series(-4,6) x1 CROSS JOIN generate_series(2,5) y1 CROSS JOIN generate_series(1,8) z1 WHERE x1 > y1*0.5 AND z1 < x1*y1) As e INNER JOIN (SELECT ST_Translate(ST_ExteriorRing(ST_Buffer(ST_Point(x1*10,y1), z1)),y1*1, z1*2) As line FROM generate_series(-3,6) x1 CROSS JOIN generate_series(2,5) y1 CROSS JOIN generate_series(1,10) z1 WHERE x1 > y1*0.75 AND z1 < x1*y1) As f ON (ST_Area(e.buff) > 78 AND ST_Contains(e.buff, f.line)) GROUP BY gid, e.buff) As quintuplet_experiment WHERE ST_IsValid(geom) = false ORDER BY gid LIMIT 3; gid | reason | location ------+-------------------+------------- 5330 | Self-intersection | POINT(32 5) 5340 | Self-intersection | POINT(42 5) 5350 | Self-intersection | POINT(52 5) --simple example SELECT * FROM ST_IsValidDetail('LINESTRING(220227 150406,2220227 150407,222020 150410)'); valid | reason | location -------+--------+---------- t | |
ST_IsValidReason — Returns text stating if a geometry is valid, or a reason for invalidity.
text ST_IsValidReason(
geometry geomA)
;
text ST_IsValidReason(
geometry geomA, integer flags)
;
Returns text stating if a geometry is valid, or if invalid a reason why.
Useful in combination with ST_IsValid to generate a detailed report of invalid geometries and reasons.
Allowed flags
are documented in ST_IsValidDetail.
Performed by the GEOS module.
Availability: 1.4
Availability: 2.0 version taking flags.
-- invalid bow-tie polygon SELECT ST_IsValidReason( 'POLYGON ((100 200, 100 100, 200 200, 200 100, 100 200))'::geometry) as validity_info; validity_info -------------------------- Self-intersection[150 150]
--First 3 Rejects from a successful quintuplet experiment SELECT gid, ST_IsValidReason(geom) as validity_info FROM (SELECT ST_MakePolygon(ST_ExteriorRing(e.buff), array_agg(f.line)) As geom, gid FROM (SELECT ST_Buffer(ST_Point(x1*10,y1), z1) As buff, x1*10 + y1*100 + z1*1000 As gid FROM generate_series(-4,6) x1 CROSS JOIN generate_series(2,5) y1 CROSS JOIN generate_series(1,8) z1 WHERE x1 > y1*0.5 AND z1 < x1*y1) As e INNER JOIN (SELECT ST_Translate(ST_ExteriorRing(ST_Buffer(ST_Point(x1*10,y1), z1)),y1*1, z1*2) As line FROM generate_series(-3,6) x1 CROSS JOIN generate_series(2,5) y1 CROSS JOIN generate_series(1,10) z1 WHERE x1 > y1*0.75 AND z1 < x1*y1) As f ON (ST_Area(e.buff) > 78 AND ST_Contains(e.buff, f.line)) GROUP BY gid, e.buff) As quintuplet_experiment WHERE ST_IsValid(geom) = false ORDER BY gid LIMIT 3; gid | validity_info ------+-------------------------- 5330 | Self-intersection [32 5] 5340 | Self-intersection [42 5] 5350 | Self-intersection [52 5] --simple example SELECT ST_IsValidReason('LINESTRING(220227 150406,2220227 150407,222020 150410)'); st_isvalidreason ------------------ Valid Geometry
ST_MakeValid — Attempts to make an invalid geometry valid without losing vertices.
geometry ST_MakeValid(
geometry input)
;
geometry ST_MakeValid(
geometry input, text params)
;
The function attempts to create a valid representation of a given invalid geometry without losing any of the input vertices. Valid geometries are returned unchanged.
Supported inputs are: POINTS, MULTIPOINTS, LINESTRINGS, MULTILINESTRINGS, POLYGONS, MULTIPOLYGONS and GEOMETRYCOLLECTIONS containing any mix of them.
In case of full or partial dimensional collapses, the output geometry may be a collection of lower-to-equal dimension geometries, or a geometry of lower dimension.
Single polygons may become multi-geometries in case of self-intersections.
The params
argument can be used to supply an options string to select the method to use for building valid geometry. The options string is in the format "method=linework|structure keepcollapsed=true|false".
The "method" key has two values.
"linework" is the original algorithm, and builds valid geometries by first extracting all lines, noding that linework together, then building a value output from the linework.
"structure" is an algorithm that distinguishes between interior and exterior rings, building new geometry by unioning exterior rings, and then differencing all interior rings.
The "keepcollapsed" key is only valid for the "structure" algorithm, and takes a value of "true" or "false". When set to "false", geometry components that collapse to a lower dimensionality, for example a one-point linestring would be dropped.
Performed by the GEOS module.
Availability: 2.0.0
Enhanced: 2.0.1, speed improvements
Enhanced: 2.1.0, added support for GEOMETRYCOLLECTION and MULTIPOINT.
Enhanced: 3.1.0, added removal of Coordinates with NaN values.
Enhanced: 3.2.0, added algorithm options, 'linework' and 'structure' which requires GEOS >= 3.10.0.
This function supports 3d and will not drop the z-index.
![]() before_geom: MULTIPOLYGON of 2 overlapping polygons
![]() after_geom: MULTIPOLYGON of 4 non-overlapping polygons
![]() after_geom_structure: MULTIPOLYGON of 1 non-overlapping polygon
SELECT f.geom AS before_geom, ST_MakeValid(f.geom) AS after_geom, ST_MakeValid(f.geom, 'method=structure') AS after_geom_structure FROM (SELECT 'MULTIPOLYGON(((186 194,187 194,188 195,189 195,190 195, 191 195,192 195,193 194,194 194,194 193,195 192,195 191, 195 190,195 189,195 188,194 187,194 186,14 6,13 6,12 5,11 5, 10 5,9 5,8 5,7 6,6 6,6 7,5 8,5 9,5 10,5 11,5 12,6 13,6 14,186 194)), ((150 90,149 80,146 71,142 62,135 55,128 48,119 44,110 41,100 40, 90 41,81 44,72 48,65 55,58 62,54 71,51 80,50 90,51 100, 54 109,58 118,65 125,72 132,81 136,90 139,100 140,110 139, 119 136,128 132,135 125,142 118,146 109,149 100,150 90)))'::geometry AS geom) AS f;
|
![]() before_geom: MULTIPOLYGON of 6 overlapping polygons
![]() after_geom: MULTIPOLYGON of 14 Non-overlapping polygons
![]() after_geom_structure: MULTIPOLYGON of 1 Non-overlapping polygon
SELECT c.geom AS before_geom, ST_MakeValid(c.geom) AS after_geom, ST_MakeValid(c.geom, 'method=structure') AS after_geom_structure FROM (SELECT 'MULTIPOLYGON(((91 50,79 22,51 10,23 22,11 50,23 78,51 90,79 78,91 50)), ((91 100,79 72,51 60,23 72,11 100,23 128,51 140,79 128,91 100)), ((91 150,79 122,51 110,23 122,11 150,23 178,51 190,79 178,91 150)), ((141 50,129 22,101 10,73 22,61 50,73 78,101 90,129 78,141 50)), ((141 100,129 72,101 60,73 72,61 100,73 128,101 140,129 128,141 100)), ((141 150,129 122,101 110,73 122,61 150,73 178,101 190,129 178,141 150)))'::geometry AS geom) AS c;
|
ST_InverseTransformPipeline — Return a new geometry with coordinates transformed to a different spatial reference system using the inverse of a defined coordinate transformation pipeline.
geometry ST_InverseTransformPipeline(
geometry geom, text pipeline, integer to_srid)
;
Return a new geometry with coordinates transformed to a different spatial reference system using a defined coordinate transformation pipeline to go in the inverse direction.
Refer to ST_TransformPipeline for details on writing a transformation pipeline.
Availability: 3.4.0
The SRID of the input geometry is ignored, and the SRID of the output geometry will be set to zero unless a value is provided via the optional to_srid
parameter. When using ST_TransformPipeline the pipeline is executed in a forward direction. Using `ST_InverseTransformPipeline()` the pipeline is executed in the inverse direction.
Transforms using pipelines are a specialised version of ST_Transform. In most cases `ST_Transform` will choose the correct operations to convert between coordinate systems, and should be preferred.
Change WGS 84 long lat to UTM 31N using the EPSG:16031 conversion
-- Inverse direction SELECT ST_AsText(ST_InverseTransformPipeline('POINT(426857.9877165967 5427937.523342293)'::geometry, 'urn:ogc:def:coordinateOperation:EPSG::16031')) AS wgs_geom; wgs_geom ---------------------------- POINT(2 48.99999999999999) (1 row)
GDA2020 example.
-- using ST_Transform with automatic selection of a conversion pipeline. SELECT ST_AsText(ST_Transform('SRID=4939;POINT(143.0 -37.0)'::geometry, 7844)) AS gda2020_auto; gda2020_auto ----------------------------------------------- POINT(143.00000635638918 -36.999986706128176) (1 row)
ST_SetSRID — Set the SRID on a geometry.
geometry ST_SetSRID(
geometry geom, integer srid)
;
Sets the SRID on a geometry to a particular integer value. Useful in constructing bounding boxes for queries.
![]() | |
This function does not transform the geometry coordinates in any way - it simply sets the meta data defining the spatial reference system the geometry is assumed to be in. Use ST_Transform if you want to transform the geometry into a new projection. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method supports Circular Strings and Curves
-- Mark a point as WGS 84 long lat --
SELECT ST_SetSRID(ST_Point(-123.365556, 48.428611),4326) As wgs84long_lat; -- the ewkt representation (wrap with ST_AsEWKT) - SRID=4326;POINT(-123.365556 48.428611)
-- Mark a point as WGS 84 long lat and then transform to web mercator (Spherical Mercator) --
SELECT ST_Transform(ST_SetSRID(ST_Point(-123.365556, 48.428611),4326),3785) As spere_merc; -- the ewkt representation (wrap with ST_AsEWKT) - SRID=3785;POINT(-13732990.8753491 6178458.96425423)
ST_SRID — Returns the spatial reference identifier for a geometry.
integer ST_SRID(
geometry g1)
;
Returns the spatial reference identifier for the ST_Geometry as defined in spatial_ref_sys table. Section 4.5, “Spatial Reference Systems”
![]() | |
spatial_ref_sys table is a table that catalogs all spatial reference systems known to PostGIS and is used for transformations from one spatial reference system to another. So verifying you have the right spatial reference system identifier is important if you plan to ever transform your geometries. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s2.1.1.1
This method implements the SQL/MM specification. SQL-MM 3: 5.1.5
This method supports Circular Strings and Curves
ST_Transform — Return a new geometry with coordinates transformed to a different spatial reference system.
geometry ST_Transform(
geometry g1, integer srid)
;
geometry ST_Transform(
geometry geom, text to_proj)
;
geometry ST_Transform(
geometry geom, text from_proj, text to_proj)
;
geometry ST_Transform(
geometry geom, text from_proj, integer to_srid)
;
Returns a new geometry with its coordinates transformed to a different spatial reference system. The destination spatial reference to_srid
may be identified by a valid SRID integer parameter (i.e. it must exist in the spatial_ref_sys
table). Alternatively, a spatial reference defined as a PROJ.4 string can be used for to_proj
and/or from_proj
, however these methods are not optimized. If the destination spatial reference system is expressed with a PROJ.4 string instead of an SRID, the SRID of the output geometry will be set to zero. With the exception of functions with from_proj
, input geometries must have a defined SRID.
ST_Transform is often confused with ST_SetSRID. ST_Transform actually changes the coordinates of a geometry from one spatial reference system to another, while ST_SetSRID() simply changes the SRID identifier of the geometry.
ST_Transform automatically selects a suitable conversion pipeline given the source and target spatial reference systems. To use a specific conversion method, use ST_TransformPipeline.
![]() | |
Requires PostGIS be compiled with PROJ support. Use PostGIS_Full_Version to confirm you have PROJ support compiled in. |
![]() | |
If using more than one transformation, it is useful to have a functional index on the commonly used transformations to take advantage of index usage. |
![]() | |
Prior to 1.3.4, this function crashes if used with geometries that contain CURVES. This is fixed in 1.3.4+ |
Enhanced: 2.0.0 support for Polyhedral surfaces was introduced.
Enhanced: 2.3.0 support for direct PROJ.4 text was introduced.
This method implements the SQL/MM specification. SQL-MM 3: 5.1.6
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
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 — Construye un polígono dando una colección arbitraria de cadenas de líneas cerradas como representación "MultiLineString" de texto "Well-Known".
geometry ST_BdPolyFromText(
text WKT, integer srid)
;
Construye un polígono dando una colección arbitraria de cadenas de líneas cerradas como representación "MultiLineString" de texto "Well-Known".
![]() | |
Envia un error si la cadena WKT no representa una MULTILINESTRING. Envía un error si la salida es un MULTIPOLYGON; en este caso puedes utilizar ST_BdMPolyFromText, o mira ST_BuildArea() para un enfoque mas especifico de postgis. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.6.2
Realizado por el módulo GEOS.
Disponibilidad: 1.1.0
ST_BdMPolyFromText — Construye un multipolígono dando una colección arbitraria de cadenas de líneas cerradas como representación "MultiLineString" de texto "Well-Known".
geometry ST_BdMPolyFromText(
text WKT, integer srid)
;
Construye un Polígono dando una colección arbitraria de cadenas de líneas cerradas, polígonos, "MultiLineString" en formato de texto "Well-Known".
![]() | |
Envia un error si el WKT no es una MULTILINESTRING. Fuerza una salida MULTIPOLYGON aunque el resultado este compuesto por un único POLYGON; puedes utilizar ST_BdPolyFromText si estas seguro que un único POLYGON será el resultado de la operación, o ver ST_BuildArea() para un enfoque mas especifico de postgis. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.6.2
Realizado por el módulo GEOS.
Disponibilidad: 1.1.0
ST_GeogFromText — Devuelve un valor especifico "geography" desde una representación "Well-Known Text" (WKT) o extendida.
geography ST_GeogFromText(
text EWKT)
;
Devuelve un objeto geográfico del texto bien conocido o de la representación bien conocida extendida. Se asume SRID 4326 si no se especifica. Este es un alias para ST_GeographyFromText. Los puntos se expresan siempre en forma latitud longitud.
--- convertir coordenadas latitud longitud a geográficas ALTER TABLE sometable ADD COLUMN geog geography(POINT,4326); UPDATE sometable SET geog = ST_GeogFromText('SRID=4326;POINT(' || lon || ' ' || lat || ')'); --- Especificar un punto geográfico usando EPSG:4267, NAD27 SELECT ST_AsEWKT(ST_GeogFromText('SRID=4267;POINT(-77.0092 38.889588)'));
ST_GeographyFromText — Devuelve un valor especifico "geography" desde una representación "Well-Known Text" (WKT) o extendida.
geography ST_GeographyFromText(
text EWKT)
;
ST_GeomCollFromText — Hace una colección Geometry de la colección WKT con el SRID dado. Si no se da SRID, el valor predeterminado es 0.
geometry ST_GeomCollFromText(
text WKT, integer srid)
;
geometry ST_GeomCollFromText(
text WKT)
;
Hace una colección Geometry de la representación de texto conocido (WKT) con el SRID dado. Si no se da SRID, el valor predeterminado es 0.
OGC SPEC 3.2.6.2 - La opción SRID es del paquete de conformidad
Devuelve null si el WKT no es una GEOMETRYCOLLECTION
![]() | |
Si estas completamente seguro que todas tus geometrias WKT son colecciones, no utilices esta función. Es mas lenta que ST_GeomFromText ya que añade pasos de validación adicionales. |
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 — Devuelve un valor especificado ST_Geometry desde una representación "Extended Well-Known Text" (EWKT).
geometry ST_GeomFromEWKT(
text EWKT)
;
Construye un objeto PostGIS ST_Geometry desde una representación OGC "Extended Well-Known text" (EWKT).
![]() | |
El formato EWKT no es un estándar OGC, sino un formato especifico PostGIS que incluye el identificador del sistema de referencia espacial (SRID). |
Mejora: 2.0.0 se introdujeron soporte de superficies poliédricas y TIN.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
SELECT ST_GeomFromEWKT('SRID=4269;LINESTRING(-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932)'); SELECT ST_GeomFromEWKT('SRID=4269;MULTILINESTRING((-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932))'); SELECT ST_GeomFromEWKT('SRID=4269;POINT(-71.064544 42.28787)'); SELECT ST_GeomFromEWKT('SRID=4269;POLYGON((-71.1776585052917 42.3902909739571,-71.1776820268866 42.3903701743239, -71.1776063012595 42.3903825660754,-71.1775826583081 42.3903033653531,-71.1776585052917 42.3902909739571))'); SELECT ST_GeomFromEWKT('SRID=4269;MULTIPOLYGON(((-71.1031880899493 42.3152774590236, -71.1031627617667 42.3152960829043,-71.102923838298 42.3149156848307, -71.1023097974109 42.3151969047397,-71.1019285062273 42.3147384934248, -71.102505233663 42.3144722937587,-71.10277487471 42.3141658254797, -71.103113945163 42.3142739188902,-71.10324876416 42.31402489987, -71.1033002961013 42.3140393340215,-71.1033488797549 42.3139495090772, -71.103396240451 42.3138632439557,-71.1041521907712 42.3141153348029, -71.1041411411543 42.3141545014533,-71.1041287795912 42.3142114839058, -71.1041188134329 42.3142693656241,-71.1041112482575 42.3143272556118, -71.1041072845732 42.3143851580048,-71.1041057218871 42.3144430686681, -71.1041065602059 42.3145009876017,-71.1041097995362 42.3145589148055, -71.1041166403905 42.3146168544148,-71.1041258822717 42.3146748022936, -71.1041375307579 42.3147318674446,-71.1041492906949 42.3147711126569, -71.1041598612795 42.314808571739,-71.1042515013869 42.3151287620809, -71.1041173835118 42.3150739481917,-71.1040809891419 42.3151344119048, -71.1040438678912 42.3151191367447,-71.1040194562988 42.3151832057859, -71.1038734225584 42.3151140942995,-71.1038446938243 42.3151006300338, -71.1038315271889 42.315094347535,-71.1037393329282 42.315054824985, -71.1035447555574 42.3152608696313,-71.1033436658644 42.3151648370544, -71.1032580383161 42.3152269126061,-71.103223066939 42.3152517403219, -71.1031880899493 42.3152774590236)), ((-71.1043632495873 42.315113108546,-71.1043583974082 42.3151211109857, -71.1043443253471 42.3150676015829,-71.1043850704575 42.3150793250568,-71.1043632495873 42.315113108546)))');
-- Cadena circular 3d SELECT ST_GeomFromEWKT('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)');
-- Ejemplo de superficie de poliedros SELECT ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )');
ST_GeomFromMARC21 — Takes MARC21/XML geographic data as input and returns a PostGIS geometry object.
geometry ST_GeomFromMARC21 (
text marcxml )
;
This function creates a PostGIS geometry from a MARC21/XML record, which can contain a POINT
or a POLYGON
. In case of multiple geographic data entries in the same MARC21/XML record, a MULTIPOINT
or MULTIPOLYGON
will be returned. If the record contains mixed geometry types, a GEOMETRYCOLLECTION
will be returned. It returns NULL if the MARC21/XML record does not contain any geographic data (datafield:034).
LOC MARC21/XML versions supported:
Availability: 3.3.0, requires libxml2 2.6+
![]() | |
The MARC21/XML Coded Cartographic Mathematical Data currently does not provide any means to describe the Spatial Reference System of the encoded coordinates, so this function will always return a geometry with |
![]() | |
Returned |
Converting MARC21/XML geographic data containing a single POINT
encoded as hddd.dddddd
SELECT ST_AsText( ST_GeomFromMARC21(' <record xmlns="http://www.loc.gov/MARC21/slim"> <leader>00000nz a2200000nc 4500</leader> <controlfield tag="001">040277569</controlfield> <datafield tag="034" ind1=" " ind2=" "> <subfield code="d">W004.500000</subfield> <subfield code="e">W004.500000</subfield> <subfield code="f">N054.250000</subfield> <subfield code="g">N054.250000</subfield> </datafield> </record>')); st_astext ------------------- POINT(-4.5 54.25) (1 row)
Converting MARC21/XML geographic data containing a single POLYGON
encoded as hdddmmss
SELECT ST_AsText( ST_GeomFromMARC21(' <record xmlns="http://www.loc.gov/MARC21/slim"> <leader>01062cem a2200241 a 4500</leader> <controlfield tag="001"> 84696781 </controlfield> <datafield tag="034" ind1="1" ind2=" "> <subfield code="a">a</subfield> <subfield code="b">50000</subfield> <subfield code="d">E0130600</subfield> <subfield code="e">E0133100</subfield> <subfield code="f">N0523900</subfield> <subfield code="g">N0522300</subfield> </datafield> </record>')); st_astext ----------------------------------------------------------------------------------------------------------------------- POLYGON((13.1 52.65,13.516666666666667 52.65,13.516666666666667 52.38333333333333,13.1 52.38333333333333,13.1 52.65)) (1 row)
Converting MARC21/XML geographic data containing a POLYGON
and a POINT
:
SELECT ST_AsText( ST_GeomFromMARC21(' <record xmlns="http://www.loc.gov/MARC21/slim"> <datafield tag="034" ind1="1" ind2=" "> <subfield code="a">a</subfield> <subfield code="b">50000</subfield> <subfield code="d">E0130600</subfield> <subfield code="e">E0133100</subfield> <subfield code="f">N0523900</subfield> <subfield code="g">N0522300</subfield> </datafield> <datafield tag="034" ind1=" " ind2=" "> <subfield code="d">W004.500000</subfield> <subfield code="e">W004.500000</subfield> <subfield code="f">N054.250000</subfield> <subfield code="g">N054.250000</subfield> </datafield> </record>')); st_astext ------------------------------------------------------------------------------------------------------------------------------------------------------------- GEOMETRYCOLLECTION(POLYGON((13.1 52.65,13.516666666666667 52.65,13.516666666666667 52.38333333333333,13.1 52.38333333333333,13.1 52.65)),POINT(-4.5 54.25)) (1 row)
ST_GeometryFromText — Devuelve un valor especifico de ST_Geometry desde una representación "Well-Known Text" (WKT). Es un alias para 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 — Devuelve un valor especifico de ST_Geometry desde una representación "Extended Well-Known Binary" (EWKB).
geometry ST_GeomFromText(
text WKT)
;
geometry ST_GeomFromText(
text WKT, integer srid)
;
Construye un objeto ST_Geometry de PostGIS desde una representación OGC "Well-Known Text" (WKT).
![]() | |
Hay dos variantes de la función ST_GeomFromText. El primero no toma SRID y devuelve una geometría sin sistema de referencia espacial definido (SRID = 0). La segunda toma un SRID como segundo argumento y devuelve una geometría que incluye esta SRID como parte de sus metadatos. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.6.2 - la opción SRID es de la suite de conformidad.
This method implements the SQL/MM specification. SQL-MM 3: 5.1.40
This method supports Circular Strings and Curves
![]() | |
While not OGC-compliant, ST_MakePoint is faster than ST_GeomFromText and ST_PointFromText. It is also easier to use for numeric coordinate values. ST_Point is another option similar in speed to ST_MakePoint and is OGC-compliant, but doesn't support anything but 2D points. |
![]() | |
Cambiado: 2.0.0 En las versiones anteriores de PostGIS ST_GeomFromText('GEOMETRYCOLLECTION(EMPTY)') estaba permitido. Esto no esta permitido ahora en PostGIS 2.0.0 para ajustarse mejor a las normas SQL/MM. Esto debería ser escrito como 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 — Hace una geometría de la representación WKT con el SRID dado. Si SRID no se da, el valor predeterminado es 0.
geometry ST_LineFromText(
text WKT)
;
geometry ST_LineFromText(
text WKT, integer srid)
;
Hace una Geometry desde un WKT con el SRID dado. Si no se da un SRID, el valor predeterminado es 0. Si el WKT pasado no es un LINESTRING, se devuelve null.
![]() | |
OGC SPEC 3.2.6.2 - La opción SRID es del paquete de conformidad |
![]() | |
Si sabes que todas tus geometrías son LINESTRING, es mas eficiente el uso de ST_GeomFromText. Esto llama únicamente a ST_GeomFromText y añade validaciones adicionales que devuelven un linestring. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.6.2
This method implements the SQL/MM specification. SQL-MM 3: 7.2.8
ST_MLineFromText — Devuelve un valor especificado ST_MultiLineString desde una representación WKT.
geometry ST_MLineFromText(
text WKT, integer srid)
;
geometry ST_MLineFromText(
text WKT)
;
Hace una Geometry desde el texto bien conocido (WKT) con el SRID dado. Si no se da un SRID, el valor predeterminado es 0.
OGC SPEC 3.2.6.2 - La opción SRID es del paquete de conformidad
Devuelve NULL si el WKT no es un MULTILINESTRING
![]() | |
Si estas completamente seguro que todas tus geometrias WKT son puntos, no utilices esta función. Es mas lenta que ST_GeomFromText ya que añade algunos pasos de validación. |
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 — Hace una geometría desde un WKT con el SRID dado. Si no se da un SRID, el valor predeterminado es 0.
geometry ST_MPointFromText(
text WKT, integer srid)
;
geometry ST_MPointFromText(
text WKT)
;
Hace una geometría desde un WKT con el SRID dado. Si no se da un SRID, el valor predeterminado es 0.
OGC SPEC 3.2.6.2 - La opción SRID es del paquete de conformidad
Devuelve NULL si el WKT no es un MULTIPUNTO
![]() | |
Si estas completamente seguro que todas tus geometrias WKT son puntos, no utilices esta función. Es mas lenta que ST_GeomFromText ya que añade algunos pasos de validación. |
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 — Hace una Geometría MultiPolygon desde un WKT con el SRID dado. Si no se da SRID, el valor predeterminado es 0.
geometry ST_MPolyFromText(
text WKT, integer srid)
;
geometry ST_MPolyFromText(
text WKT)
;
Hace un MultiPolygon desde un WKT con el SRID dado. Si no se da SRID, el valor predeterminado es 0.
OGC SPEC 3.2.6.2 - La opción SRID es del paquete de conformidad
Devuelve un error si el WKT no es un MULTIPOLYGON
![]() | |
Si estas completamente seguro que todas tus geometrías WKT son multipolygon, no utilices esta función. Es mas lenta que ST_GeomFromText ya que añade algunos pasos de validación adicionales. |
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 — Crea una geometría puntual desde un WKT con el SRID dado. Si no se especifica el SRID por defecto será unknown.
geometry ST_PointFromText(
text WKT)
;
geometry ST_PointFromText(
text WKT, integer srid)
;
Construye un objeto de punto de PostGIS ST_GEOMETRY de la representación bien conocida del texto de OGC. Si no se da SRID, se omite a desconocido (actualmente 0). Si la geometría no es una representación de punto WKT, devuelve null. Si WKT es totalmente inválido, entonces lanza un error.
![]() | |
Hay 2 variantes de la función ST_PointFromText, la primera no toma SRID y devuelve una geometría sin sistema de referencia espacial definido. La segunda toma un id de un sistema de referencia como segundo argumento y devuelve una ST_Geometry que incluye este srid como parte de sus metadatos. El srid debe estar definido en la tabla spatial_ref_sys. |
![]() | |
Si estas completamente seguro que todas tus geometrias WKT son puntos, no utilices esta función. Es mas lenta que ST_GeomFromText ya que añade algunos pasos de validación. Si estas construyendo puntos desde coordenadas long lat y te interesan mas el rendimiento y la precisión que la conformidad con OGC, utiliza ST_MakePoint o el alias conforme al OGCST_Point. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.6.2 - la opción SRID es de la suite de conformidad.
This method implements the SQL/MM specification. SQL-MM 3: 6.1.8
ST_PolygonFromText — Hace una geometría desde un WKT con el SRID dado. Si no se da un SRID, el valor predeterminado es 0.
geometry ST_PolygonFromText(
text WKT)
;
geometry ST_PolygonFromText(
text WKT, integer srid)
;
Hace una geometría desde WKT con el SRID dado. Si no se da SRID, el valor predeterminado es 0. Devuelve null si WKT no es un polígono.
OGC SPEC 3.2.6.2 - La opción SRID es del paquete de conformidad
![]() | |
Si estas completamente seguro que todas tus geometrías WKT son poligonos, no utilices esta función. Es mas lenta que ST_GeomFromText ya que añade algunos pasos de validación adicionales. |
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
desde un WKB con el SRID dadoST_GeogFromWKB — Crea una instancia "geography" desde la representación de una geometría en "Well-Known Binary" (WKB) o "Extended Well-Known Binary" (EWKB).
geography ST_GeogFromWKB(
bytea wkb)
;
La función ST_GeogFromWKB
, toma una representación de una geometría en "Well-Known Binary" (WKB) o la versión extendida de PostGIS y crea la instancia apropiada de tipo "geography". Esta función juega el rol de "Geometry Factory" en SQL.
Si no se define un SRID, por defecto es 4326 (WGS 84 long lat).
This method supports Circular Strings and Curves
--Aunque bytes rep contiene solo \, esto se necesita para escapar caracteres cuando se e insertan en una tabla 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 — Devuelve un valor especifico de ST_Geometry desde una representación " Extended Well-Known Binary" (EWKB).
geometry ST_GeomFromEWKB(
bytea EWKB)
;
Construye un objeto ST_Geometry de PostGIS desde un formato OGC "Extended Well-Known Binary" (EWKB).
![]() | |
El formato EWKB no es un estándar del OGC, sino un formato especifico de PostGIS que incluye el identificador del sistema de referencia espacial (SRID) |
Mejora: 2.0.0 se introdujeron soporte de superficies poliédricas y 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).
Representación binaria de LINESTRING(-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932) en NAD 83 long lat (4269).
![]() | |
Nota: Aunque los arrays de bits están delimitados por \ y deben tener ', necesitaremos escapar ambos con \ y '' si el valor de standard_conforming_strings es off. Asi que esto puede no ser exactamente como la representación 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@');
![]() | |
En PostgreSQL 9.1 +-standard_conforming_strings se establece en on de forma predeterminada, donde como en versiones anteriores se estableció en off. Puede cambiar los valores predeterminados según sea necesario para una sola consulta o a nivel de base de datos o de servidor. A continuación se muestra cómo lo haría con standard_conforming_strings = on. En este caso nos escapamos del ' with standard ansi ', pero las barras no se escapan |
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 — Crea una instancia de geometría desde la representación de una geometría en "Well-Known Binary" (WKB) y un SRID opcional.
geometry ST_GeomFromWKB(
bytea geom)
;
geometry ST_GeomFromWKB(
bytea geom, integer srid)
;
La función ST_GeomFromWKB
, toma una representación binaria "well-known" de una geometría y un ID de un Sistema de Referencia Espacial (SRID
) y crea una instancia del tipo de geometría adecuado. Esta función juega un rol de "Geometry Factory" en SQL. Es un nombre alternativo para ST_WKBToSQL.
Si no se especifica SRID, el valor predeterminado es 0 (desconocido).
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.7.2 - El SRID opcional es para el paquete de conformidad
This method implements the SQL/MM specification. SQL-MM 3: 5.1.41
This method supports Circular Strings and Curves
-- Aunque bytea rep contiene single \, estos deben ser escapados al insertar en una tabla -- a menos que standard_conforming_strings esté establecido en on. SELECT ST_AsEWKT( ST_GeomFromWKB(E'\\001\\002\\000\\000\\000\\002\\000\\000\\000\\037\\205\\353Q\\270~\\\\\\300\\323Mb\\020X\\231C@\\020X9\\264\\310~\\\\\\300)\\\\\\217\\302\\365\\230C@',4326) ); st_asewkt ------------------------------------------------------ SRID=4326;LINESTRING(-113.98 39.198,-113.981 39.195) (1 row) SELECT ST_AsText( ST_GeomFromWKB( ST_AsEWKB('POINT(2 5)'::geometry) ) ); st_astext ------------ POINT(2 5) (1 row)
ST_LineFromWKB — Crea un LINESTRING
desde un WKB con el SRID dado
geometry ST_LineFromWKB(
bytea WKB)
;
geometry ST_LineFromWKB(
bytea WKB, integer srid)
;
La función ST_GeomFromWKB
, toma una representación binaria "well-known" de una geometría y un ID de un Sistema de Referencia Espacial (SRID
) y crea una instancia del tipo de geometría adecuado - en este caso una geometría LINESTRING
. Esta función juega un rol de "Geometry Factory" en SQL.
Si no se especifica un SRID, el valor predeterminado es 0. NULL
se devuelve si la entrada bytea
no representa un LINESTRING
.
![]() | |
OGC SPEC 3.2.6.2 - La opción SRID es del paquete de conformidad |
![]() | |
Si sabes que todas tus geometrías son |
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 — Crea una geometría desde un WKB con el SRID dado.
geometry ST_LinestringFromWKB(
bytea WKB)
;
geometry ST_LinestringFromWKB(
bytea WKB, integer srid)
;
La función ST_LinestringFromWKB
, toma una representación de una geometría en "well-known binary" y un ID de un Sistema de Referencia Espacial (SRID
) y crea una instancia del tipo apropiado de geometría - en este caso, una geometría LINESTRING
. Esta función juega un rol de "Geometry Factory" en SQL.
Si no se especifica un SRID, el valor predeterminado es 0.NULL
se devuelve si la entrada bytea
no representa una geometría LINESTRING
. Esto es un alias para ST_LineFromWKB.
![]() | |
OGC SPEC 3.2.6.2 - La opción SRID es del paquete de conformidad |
![]() | |
Si sabes que todas tus geometrías son |
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 — Crea una geometría desde un WKB con el SRID dado.
geometry ST_GeomFromWKB(
bytea geom)
;
geometry ST_GeomFromWKB(
bytea geom, integer srid)
;
La función ST_PointFromWKB
, toma una representación binaria "well-known" de una geometría y un ID de un Sistema de Referencia Espacial (SRID
) y crea una instancia del tipo de geometría adecuado - en este caso una geometría POINT
. Esta función juega un rol de "Geometry Factory" en SQL.
Si no se especifica un SRID, el valor predeterminado es 0. NULL
se devuelve si la entrada bytea
no representa una geometría de 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 — Devuelve un BOX2D de una cadena de GeoHash.
box2d ST_Box2dFromGeoHash(
text geohash, integer precision=full_precision_of_geohash)
;
Devuelve un BOX2D de una cadena de GeoHash.
If no precision
is specified ST_Box2dFromGeoHash returns a BOX2D based on full precision of the input GeoHash string.
Si es especificada la precisión
ST_Box2dFromGeoHash utilizará muchos caracteres del GeoHash para crear el BOX2D. Los valores de precisión más bajos resultan en BOX2Ds más grandes y los valores más grandes aumentan la precisión.
Disponibilidad: 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 — Devuelve una geometría de una cadena de GeoHash.
geometry ST_GeomFromGeoHash(
text geohash, integer precision=full_precision_of_geohash)
;
Devuelve una geometría de una cadena de GeoHash. La geometría será un polígono que representa los límites de GeoHash.
Si no se especifica ninguna precisión
, ST_GeomFromGeoHash devuelve un polígono basándose en la precisión completa de la cadena de GeoHash de entrada.
Si se especifica la precisión
, ST_GeomFromGeoHash utilizará muchos caracteres del GeoHash para crear el polígono.
Disponibilidad: 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 — Toma una representación GML como entrada de una geometría y extrae un objeto geométrico PostGIS
geometry ST_GeomFromGML(
text geomgml)
;
geometry ST_GeomFromGML(
text geomgml, integer srid)
;
Construye un objeto ST_Geometry de PostGIS desde una representación OGC GML.
ST_GeomFromGML funciona solamente para fragmentos geométricos GML. Lanza un error si intentas utilizar un documento GML completo.
Versiones OGC GML soportadas:
GML 3.2.1 Namespace
GML 3.1.1 Simple Features profile SF-2 (con GML 3.1.0 y 3.0.0 compatibilidad para versiones anteriores)
GML 2.1.2
OGC GML standards, cf: http://www.opengeospatial.org/standards/gml:
Disponibilidad: 1.5, requiere libxml2 1.6+
Mejora: 2.0.0 se introdujeron soporte de superficies poliédricas y TIN.
Mejorada: 2.0.0 se agregó el parámetro por defecto opcional srid.
This function supports 3d and will not drop the z-index.
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
GML permite dimensiones mixtas (2D y 3D dentro de la misma MultiGeometry, por ejemplo). Como las geometrías PostGIS no lo hacen, ST_GeomFromGML convierte todas las geometrías a 2D si se encuentra una dimensión Z que falta.
GML soporta SRS diferentes en la misma MultiGeometry. Como las geometrías de PostGIS no lo hacen, ST_GeomFromGML, en este caso, reproyecta todas las subgeometrías al SRS del nodo padre. Si no esta disponible el atributo srsName en el nodo padre del GML, la función lanza un error.
La función ST_GeomFromGML no es muy estricta con los namespaces explícitos de un GML. Puedes evitar mencionarlos explícitamente para usos comunes. Pero lo necesitas si deseas utilizar la función XLink dentro del GML.
![]() | |
La función ST_GeomFromGML no soporta geometrias curvas SQL/MM. |
SELECT ST_GeomFromGML(' <gml:LineString srsName="EPSG:4269"> <gml:coordinates> -71.16028,42.258729 -71.160837,42.259112 -71.161143,42.25932 </gml:coordinates> </gml:LineString >');
SELECT ST_GeomFromGML(' <gml:LineString xmlns:gml="http://www.opengis.net/gml" xmlns:xlink="http://www.w3.org/1999/xlink" srsName="urn:ogc:def:crs:EPSG::4269"> <gml:pointProperty> <gml:Point gml:id="p1" ><gml:pos >42.258729 -71.16028</gml:pos ></gml:Point> </gml:pointProperty> <gml:pos >42.259112 -71.160837</gml:pos> <gml:pointProperty> <gml:Point xlink:type="simple" xlink:href="#p1"/> </gml:pointProperty> </gml:LineString >'););
SELECT ST_AsEWKT(ST_GeomFromGML(' <gml:PolyhedralSurface> <gml:polygonPatches> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing ><gml:posList srsDimension="3" >0 0 0 0 0 1 0 1 1 0 1 0 0 0 0</gml:posList ></gml:LinearRing> </gml:exterior> </gml:PolygonPatch> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing ><gml:posList srsDimension="3" >0 0 0 0 1 0 1 1 0 1 0 0 0 0 0</gml:posList ></gml:LinearRing> </gml:exterior> </gml:PolygonPatch> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing ><gml:posList srsDimension="3" >0 0 0 1 0 0 1 0 1 0 0 1 0 0 0</gml:posList ></gml:LinearRing> </gml:exterior> </gml:PolygonPatch> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing ><gml:posList srsDimension="3" >1 1 0 1 1 1 1 0 1 1 0 0 1 1 0</gml:posList ></gml:LinearRing> </gml:exterior> </gml:PolygonPatch> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing ><gml:posList srsDimension="3" >0 1 0 0 1 1 1 1 1 1 1 0 0 1 0</gml:posList ></gml:LinearRing> </gml:exterior> </gml:PolygonPatch> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing ><gml:posList srsDimension="3" >0 0 1 1 0 1 1 1 1 0 1 1 0 0 1</gml:posList ></gml:LinearRing> </gml:exterior> </gml:PolygonPatch> </gml:polygonPatches> </gml:PolyhedralSurface >')); -- result -- POLYHEDRALSURFACE(((0 0 0,0 0 1,0 1 1,0 1 0,0 0 0)), ((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0)), ((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0)), ((1 1 0,1 1 1,1 0 1,1 0 0,1 1 0)), ((0 1 0,0 1 1,1 1 1,1 1 0,0 1 0)), ((0 0 1,1 0 1,1 1 1,0 1 1,0 0 1)))
ST_GeomFromGeoJSON — Toma como entrada una representación geojson de una geometría y devuelve un objeto geométrico PostGIS
geometry ST_GeomFromGeoJSON(
text geomjson)
;
geometry ST_GeomFromGeoJSON(
json geomjson)
;
geometry ST_GeomFromGeoJSON(
jsonb geomjson)
;
Construye un objeto geométrico PostGIS desde una representación GeoJSON.
ST_GeomFromGeoJSON solo funciona con fragmentos geométricos JSON. Devolverá un error si intentas utilizar un documento JSON completo.
Enhanced: 3.0.0 parsed geometry defaults to SRID=4326 if not specified otherwise.
Enhanced: 2.5.0 can now accept json and jsonb as inputs.
Disponibilidad: 2.0.0 necesita de - JSON-C >= 0.9
![]() | |
Si no tienes activado el soporte de JSON-C, tendrás un mensaje error en vez de ver la salida. Para activar el soporte JSON-C, ejecuta configure --with-jsondir=/path/to/json-c. Para mas detalles ve a Section 2.2.3, “Configuración”. |
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)
-- un 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 — Toma una representación de una geometría KML de entrada y devuelve un objeto geométrico PostGIS
geometry ST_GeomFromKML(
text geomkml)
;
Construye un objeto ST_Geometry de PostGIS desde una representación OGC KML.
ST_GeomFromKML solo funciona con fragmentos geométricos KML. Devuelve un error si intentas utilizar un documento KML completo.
Versiones soportadas OGC KML:
KML 2.2.0 Namespace
OGC KML standards, cf: http://www.opengeospatial.org/standards/kml:
Availability: 1.5, requires libxml2 2.6+
This function supports 3d and will not drop the z-index.
![]() | |
ST_GeomFromKML no soporta geometrías curvas SQL/MM. |
ST_GeomFromTWKB — Crea una instancia de geometría de una representación geométrica TWKB ("Tiny Well-Known Binary").
geometry ST_GeomFromTWKB(
bytea twkb)
;
La función ST_GeomFromTWKB
toma un TWKB ("Tiny Well-Known Binary") a una representación geométrica (WKB) y crea una instancia apropiada de un tipo de geometía.
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 — Devuelve un valor especifico ST_Geometry desde una representación GML. Esto es un alias de ST_GeomFromGML
geometry ST_GMLToSQL(
text geomgml)
;
geometry ST_GMLToSQL(
text geomgml, integer srid)
;
ST_LineFromEncodedPolyline — Crea un LineString desde una polilínea codificada.
geometry ST_LineFromEncodedPolyline(
text polyline, integer precision=5)
;
Crea un LineString desde una cadena de polilínea codificada.
Optional precision
specifies how many decimal places will be preserved in Encoded Polyline. Value should be the same on encoding and decoding, or coordinates will be incorrect.
Ver http://developers.google.com/maps/documentation/utilities/polylinealgorithm
Disponibilidad: 2.2.0
-- Create a line string from a polyline SELECT ST_AsEWKT(ST_LineFromEncodedPolyline('_p~iF~ps|U_ulLnnqC_mqNvxq`@')); -- result -- SRID=4326;LINESTRING(-120.2 38.5,-120.95 40.7,-126.453 43.252) -- Select different precision that was used for polyline encoding SELECT ST_AsEWKT(ST_LineFromEncodedPolyline('_p~iF~ps|U_ulLnnqC_mqNvxq`@',6)); -- result -- SRID=4326;LINESTRING(-12.02 3.85,-12.095 4.07,-12.6453 4.3252)
ST_PointFromGeoHash — Devuelve un punto de una cadena de GeoHash.
point ST_PointFromGeoHash(
text geohash, integer precision=full_precision_of_geohash)
;
Devuelve un punto de una cadena de GeoHash. El punto representa el punto central del GeoHash.
Si no se especifica ninguna precisión
, ST_PointFromGeoHash devuelve un punto basándose en la precisión completa de la cadena de GeoHash de entrada.
Si precision
es especificado ST_PointFromGeoHash utilizará muchos caracteres de GeoHash para crear el punto.
Disponibilidad: 2.1.0
SELECT ST_AsText(ST_PointFromGeoHash('9qqj7nmxncgyy4d0dbxqz0')); st_astext ------------------------------ POINT(-115.172816 36.114646) SELECT ST_AsText(ST_PointFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 4)); st_astext ----------------------------------- POINT(-115.13671875 36.123046875) SELECT ST_AsText(ST_PointFromGeoHash('9qqj7nmxncgyy4d0dbxqz0', 10)); st_astext ------------------------------------------- POINT(-115.172815918922 36.1146435141563)
ST_FromFlatGeobufToTable — Creates a table based on the structure of FlatGeobuf data.
geometry ST_BdPolyFromText(
text WKT, integer srid)
;
Creates a table based on the structure of FlatGeobuf data. (http://flatgeobuf.org).
schema
Schema name.
table
Table name.
data
Input FlatGeobuf data.
Availability: 3.2.0
ST_FromFlatGeobuf — Reads FlatGeobuf data.
setof anyelement ST_FromFlatGeobuf(
anyelement Table reference, bytea FlatGeobuf input data)
;
Reads FlatGeobuf data (http://flatgeobuf.org). NOTE: PostgreSQL bytea cannot exceed 1GB.
tabletype
reference to a table type.
data
input FlatGeobuf data.
Availability: 3.2.0
ST_AsEWKT — Return the Well-Known Text (WKT) representation of the geometry with SRID meta data.
text ST_AsEWKT(
geometry g1)
;
text ST_AsEWKT(
geometry g1, integer maxdecimaldigits=15)
;
text ST_AsEWKT(
geography g1)
;
text ST_AsEWKT(
geography g1, integer maxdecimaldigits=15)
;
Returns the Well-Known Text representation of the geometry prefixed with the SRID. The optional maxdecimaldigits
argument may be used to reduce the maximum number of decimal digits after floating point used in output (defaults to 15).
To perform the inverse conversion of EWKT representation to PostGIS geometry use ST_GeomFromEWKT.
![]() | |
Using the |
![]() | |
The WKT spec does not include the SRID. To get the OGC WKT format use ST_AsText. |
![]() | |
WKT format does not maintain precision so to prevent floating truncation, use ST_AsBinary or ST_AsEWKB format for transport. |
Enhanced: 3.1.0 support for optional precision parameter.
Enhanced: 2.0.0 support for Geography, Polyhedral surfaces, Triangles and TIN was introduced.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
SELECT ST_AsEWKT('0103000020E61000000100000005000000000000 000000000000000000000000000000000000000000000000000000 F03F000000000000F03F000000000000F03F000000000000F03 F000000000000000000000000000000000000000000000000'::geometry); st_asewkt -------------------------------- SRID=4326;POLYGON((0 0,0 1,1 1,1 0,0 0)) (1 row) SELECT ST_AsEWKT('0108000080030000000000000060E30A4100000000785C0241000000000000F03F0000000018 E20A4100000000485F024100000000000000400000000018 E20A4100000000305C02410000000000000840') --st_asewkt--- CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)
ST_AsText — Return the Well-Known Text (WKT) representation of the geometry/geography without SRID metadata.
text ST_AsText(
geometry g1)
;
text ST_AsText(
geometry g1, integer maxdecimaldigits = 15)
;
text ST_AsText(
geography g1)
;
text ST_AsText(
geography g1, integer maxdecimaldigits = 15)
;
Returns the OGC Well-Known Text (WKT) representation of the geometry/geography. The optional maxdecimaldigits
argument may be used to limit the number of digits after the decimal point in output ordinates (defaults to 15).
To perform the inverse conversion of WKT representation to PostGIS geometry use ST_GeomFromText.
![]() | |
The standard OGC WKT representation does not include the SRID. To include the SRID as part of the output representation, use the non-standard PostGIS function ST_AsEWKT |
![]() | |
The textual representation of numbers in WKT may not maintain full floating-point precision. To ensure full accuracy for data storage or transport it is best to use Well-Known Binary (WKB) format (see ST_AsBinary and |
![]() | |
Using the |
Availability: 1.5 - support for geography was introduced.
Enhanced: 2.5 - optional parameter precision introduced.
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s2.1.1.1
This method implements the SQL/MM specification. SQL-MM 3: 5.1.25
This method supports Circular Strings and Curves
SELECT ST_AsText('01030000000100000005000000000000000000 000000000000000000000000000000000000000000000000 F03F000000000000F03F000000000000F03F000000000000F03 F000000000000000000000000000000000000000000000000'); st_astext -------------------------------- POLYGON((0 0,0 1,1 1,1 0,0 0))
Full precision output is the default.
SELECT ST_AsText('POINT(111.1111111 1.1111111)')); st_astext ------------------------------ POINT(111.1111111 1.1111111)
The maxdecimaldigits
argument can be used to limit output precision.
SELECT ST_AsText('POINT(111.1111111 1.1111111)'), 2); st_astext -------------------- POINT(111.11 1.11)
ST_AsBinary — Return the OGC/ISO Well-Known Binary (WKB) representation of the geometry/geography without SRID meta data.
bytea ST_AsBinary(
geometry g1)
;
bytea ST_AsBinary(
geometry g1, text NDR_or_XDR)
;
bytea ST_AsBinary(
geography g1)
;
bytea ST_AsBinary(
geography g1, text NDR_or_XDR)
;
Returns the OGC/ISO Well-Known Binary (WKB) representation of the geometry. The first function variant defaults to encoding using server machine endian. The second function variant takes a text argument specifying the endian encoding, either little-endian ('NDR') or big-endian ('XDR').
WKB format is useful to read geometry data from the database and maintaining full numeric precision. This avoids the precision rounding that can happen with text formats such as WKT.
To perform the inverse conversion of WKB to PostGIS geometry use ST_GeomFromWKB.
![]() | |
The OGC/ISO WKB format does not include the SRID. To get the EWKB format which does include the SRID use ST_AsEWKB |
![]() | |
The default behavior in PostgreSQL 9.0 has been changed to output bytea in hex encoding. If your GUI tools require the old behavior, then SET bytea_output='escape' in your database. |
Mejorado: 2.0.0 soporte para superficies poliédricas, triángulos y TIN fue introducida.
Enhanced: 2.0.0 support for higher coordinate dimensions was introduced.
Enhanced: 2.0.0 support for specifying endian with geography was introduced.
Availability: 1.5.0 geography support was introduced.
Changed: 2.0.0 Inputs to this function can not be unknown -- must be geometry. Constructs such as ST_AsBinary('POINT(1 2)')
are no longer valid and you will get an n st_asbinary(unknown) is not unique error
. Code like that needs to be changed to ST_AsBinary('POINT(1 2)'::geometry);
. If that is not possible, then install legacy.sql
.
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s2.1.1.1
This method implements the SQL/MM specification. SQL-MM 3: 5.1.37
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
This function supports 3d and will not drop the z-index.
SELECT ST_AsBinary(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326)); st_asbinary -------------------------------- \x01030000000100000005000000000000000000000000000000000000000000000000000000000000 000000f03f000000000000f03f000000000000f03f000000000000f03f0000000000000000000000 00000000000000000000000000
SELECT ST_AsBinary(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326), 'XDR'); st_asbinary -------------------------------- \x000000000300000001000000050000000000000000000000000000000000000000000000003ff000 00000000003ff00000000000003ff00000000000003ff00000000000000000000000000000000000 00000000000000000000000000
ST_AsEWKB — Return the Extended Well-Known Binary (EWKB) representation of the geometry with SRID meta data.
bytea ST_AsEWKB(
geometry g1)
;
bytea ST_AsEWKB(
geometry g1, text NDR_or_XDR)
;
Returns the Extended Well-Known Binary (EWKB) representation of the geometry with SRID metadata. The first function variant defaults to encoding using server machine endian. The second function variant takes a text argument specifying the endian encoding, either little-endian ('NDR') or big-endian ('XDR').
WKB format is useful to read geometry data from the database and maintaining full numeric precision. This avoids the precision rounding that can happen with text formats such as WKT.
To perform the inverse conversion of EWKB to PostGIS geometry use ST_GeomFromEWKB.
![]() | |
To get the OGC/ISO WKB format use ST_AsBinary. Note that OGC/ISO WKB format does not include the SRID. |
Mejorado: 2.0.0 soporte para superficies poliédricas, triángulos y TIN fue introducida.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
SELECT ST_AsEWKB(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326)); st_asewkb -------------------------------- \x0103000020e610000001000000050000000000000000000000000000000000000000000000000000 00000000000000f03f000000000000f03f000000000000f03f000000000000f03f00000000000000 0000000000000000000000000000000000
SELECT ST_AsEWKB(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326), 'XDR'); st_asewkb -------------------------------- \x0020000003000010e600000001000000050000000000000000000000000000000000000000000000 003ff00000000000003ff00000000000003ff00000000000003ff000000000000000000000000000 0000000000000000000000000000000000
ST_AsHEXEWKB — Returns a Geometry in HEXEWKB format (as text) using either little-endian (NDR) or big-endian (XDR) encoding.
text ST_AsHEXEWKB(
geometry g1, text NDRorXDR)
;
text ST_AsHEXEWKB(
geometry g1)
;
Returns a Geometry in HEXEWKB format (as text) using either little-endian (NDR) or big-endian (XDR) encoding. If no encoding is specified, then NDR is used.
![]() | |
Disponibilidad: 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 — Returns an Encoded Polyline from a LineString geometry.
text ST_AsEncodedPolyline(
geometry geom, integer precision=5)
;
Returns the geometry as an Encoded Polyline. This format is used by Google Maps with precision=5 and by Open Source Routing Machine with precision=5 and 6.
Optional precision
specifies how many decimal places will be preserved in Encoded Polyline. Value should be the same on encoding and decoding, or coordinates will be incorrect.
Disponibilidad: 2.2.0
Basic
SELECT ST_AsEncodedPolyline(GeomFromEWKT('SRID=4326;LINESTRING(-120.2 38.5,-120.95 40.7,-126.453 43.252)')); --result-- |_p~iF~ps|U_ulLnnqC_mqNvxq`@
Use in conjunction with geography linestring and geography segmentize, and put on google maps
-- the SQL for Boston to San Francisco, segments every 100 KM SELECT ST_AsEncodedPolyline( ST_Segmentize( ST_GeogFromText('LINESTRING(-71.0519 42.4935,-122.4483 37.64)'), 100000)::geometry) As encodedFlightPath;
javascript will look something like this where $ variable you replace with query result
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=geometry"></script> <script type="text/javascript"> flightPath = new google.maps.Polyline({ path: google.maps.geometry.encoding.decodePath("$encodedFlightPath"), map: map, strokeColor: '#0000CC', strokeOpacity: 1.0, strokeWeight: 4 }); </script>
ST_AsFlatGeobuf — Return a FlatGeobuf representation of a set of rows.
bytea ST_AsFlatGeobuf(
anyelement set row)
;
bytea ST_AsFlatGeobuf(
anyelement row, bool index)
;
bytea ST_AsFlatGeobuf(
anyelement row, bool index, text geom_name)
;
Return a FlatGeobuf representation (http://flatgeobuf.org) of a set of rows corresponding to a FeatureCollection. NOTE: PostgreSQL bytea cannot exceed 1GB.
row
row data with at least a geometry column.
index
toggle spatial index creation. Default is false.
geom_name
is the name of the geometry column in the row data. If NULL it will default to the first found geometry column.
Availability: 3.2.0
ST_AsGeobuf — Return a Geobuf representation of a set of rows.
bytea ST_AsGeobuf(
anyelement set row)
;
bytea ST_AsGeobuf(
anyelement row, text geom_name)
;
Return a Geobuf representation (https://github.com/mapbox/geobuf) of a set of rows corresponding to a FeatureCollection. Every input geometry is analyzed to determine maximum precision for optimal storage. Note that Geobuf in its current form cannot be streamed so the full output will be assembled in memory.
row
row data with at least a geometry column.
geom_name
is the name of the geometry column in the row data. If NULL it will default to the first found geometry column.
Availability: 2.4.0
ST_AsGeoJSON — Return a geometry as a GeoJSON element.
text ST_AsGeoJSON(
record feature, text geomcolumnname, integer maxdecimaldigits=9, boolean pretty_bool=false)
;
text ST_AsGeoJSON(
geometry geom, integer maxdecimaldigits=9, integer options=8)
;
text ST_AsGeoJSON(
geography geog, integer maxdecimaldigits=9, integer options=0)
;
Returns a geometry as a GeoJSON "geometry", or a row as a GeoJSON "feature". (See the GeoJSON specifications RFC 7946). 2D and 3D Geometries are both supported. GeoJSON only support SFS 1.1 geometry types (no curve support for example).
The maxdecimaldigits
argument may be used to reduce the maximum number of decimal places used in output (defaults to 9). If you are using EPSG:4326 and are outputting the geometry only for display, maxdecimaldigits
=6 can be a good choice for many maps.
![]() | |
Using the |
The options
argument can be used to add BBOX or CRS in GeoJSON output:
0: means no option
1: GeoJSON BBOX
2: GeoJSON Short CRS (e.g EPSG:4326)
4: GeoJSON Long CRS (e.g urn:ogc:def:crs:EPSG::4326)
8: GeoJSON Short CRS if not EPSG:4326 (default)
The GeoJSON specification states that polygons are oriented using the Right-Hand Rule, and some clients require this orientation. This can be ensured by using ST_ForcePolygonCCW . The specification also requires that geometry be in the WGS84 coordinate system (SRID = 4326). If necessary geometry can be projected into WGS84 using ST_Transform: ST_Transform( geom, 4326 )
.
GeoJSON can be tested and viewed online at geojson.io and geojsonlint.com. It is widely supported by web mapping frameworks:
Disponibilidad: 1.3.4
Availability: 1.5.0 geography support was introduced.
Changed: 2.0.0 support default args and named args.
Changed: 3.0.0 support records as input
Changed: 3.0.0 output SRID if not EPSG:4326.
This function supports 3d and will not drop the z-index.
Generate a FeatureCollection:
SELECT json_build_object( 'type', 'FeatureCollection', 'features', json_agg(ST_AsGeoJSON(t.*)::json) ) FROM ( VALUES (1, 'one', 'POINT(1 1)'::geometry), (2, 'two', 'POINT(2 2)'), (3, 'three', 'POINT(3 3)') ) as t(id, name, geom);
{"type" : "FeatureCollection", "features" : [{"type": "Feature", "geometry": {"type":"Point","coordinates":[1,1]}, "properties": {"id": 1, "name": "one"}}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[2,2]}, "properties": {"id": 2, "name": "two"}}, {"type": "Feature", "geometry": {"type":"Point","coordinates":[3,3]}, "properties": {"id": 3, "name": "three"}}]}
Generate a Feature:
SELECT ST_AsGeoJSON(t.*) FROM (VALUES (1, 'one', 'POINT(1 1)'::geometry)) AS t(id, name, geom);
st_asgeojson ----------------------------------------------------------------------------------------------------------------- {"type": "Feature", "geometry": {"type":"Point","coordinates":[1,1]}, "properties": {"id": 1, "name": "one"}}
An alternate way to generate Features with an id
property is to use JSONB functions and operators:
SELECT jsonb_build_object( 'type', 'Feature', 'id', id, 'geometry', ST_AsGeoJSON(geom)::jsonb, 'properties', to_jsonb( t.* ) - 'id' - 'geom' ) AS json FROM (VALUES (1, 'one', 'POINT(1 1)'::geometry)) AS t(id, name, geom);
json ----------------------------------------------------------------------------------------------------------------- {"id": 1, "type": "Feature", "geometry": {"type": "Point", "coordinates": [1, 1]}, "properties": {"name": "one"}}
Don't forget to transform your data to WGS84 longitude, latitude to conform with the GeoJSON specification:
SELECT ST_AsGeoJSON(ST_Transform(geom,4326)) from fe_edges limit 1;
st_asgeojson ----------------------------------------------------------------------------------------------------------- {"type":"MultiLineString","coordinates":[[[-89.734634999999997,31.492072000000000], [-89.734955999999997,31.492237999999997]]]}
3D geometries are supported:
SELECT ST_AsGeoJSON('LINESTRING(1 2 3, 4 5 6)');
{"type":"LineString","coordinates":[[1,2,3],[4,5,6]]}
ST_AsGML — Return the geometry as a GML version 2 or 3 element.
text ST_AsGML(
geometry geom, integer maxdecimaldigits=15, integer options=0)
;
text ST_AsGML(
geography geog, integer maxdecimaldigits=15, integer options=0, text nprefix=null, text id=null)
;
text ST_AsGML(
integer version, geometry geom, integer maxdecimaldigits=15, integer options=0, text nprefix=null, text id=null)
;
text ST_AsGML(
integer version, geography geog, integer maxdecimaldigits=15, integer options=0, text nprefix=null, text id=null)
;
Return the geometry as a Geography Markup Language (GML) element. The version parameter, if specified, may be either 2 or 3. If no version parameter is specified then the default is assumed to be 2. The maxdecimaldigits
argument may be used to reduce the maximum number of decimal places used in output (defaults to 15).
![]() | |
Using the |
GML 2 refer to 2.1.2 version, GML 3 to 3.1.1 version
The 'options' argument is a bitfield. It could be used to define CRS output type in GML output, and to declare data as lat/lon:
0: GML Short CRS (e.g EPSG:4326), default value
1: GML Long CRS (e.g urn:ogc:def:crs:EPSG::4326)
2: For GML 3 only, remove srsDimension attribute from output.
4: For GML 3 only, use <LineString> rather than <Curve> tag for lines.
16: Declare that datas are lat/lon (e.g srid=4326). Default is to assume that data are planars. This option is useful for GML 3.1.1 output only, related to axis order. So if you set it, it will swap the coordinates so order is lat lon instead of database lon lat.
32: Output the box of the geometry (envelope).
The 'namespace prefix' argument may be used to specify a custom namespace prefix or no prefix (if empty). If null or omitted 'gml' prefix is used
Disponibilidad: 1.3.2
Availability: 1.5.0 geography support was introduced.
Enhanced: 2.0.0 prefix support was introduced. Option 4 for GML3 was introduced to allow using LineString instead of Curve tag for lines. GML3 Support for Polyhedral surfaces and TINS was introduced. Option 32 was introduced to output the box.
Changed: 2.0.0 use default named args
Enhanced: 2.1.0 id support was introduced, for GML 3.
![]() | |
Only version 3+ of ST_AsGML supports Polyhedral Surfaces and TINS. |
This method implements the SQL/MM specification. SQL-MM IEC 13249-3: 17.2
This function supports 3d and will not drop the z-index.
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
SELECT ST_AsGML(ST_GeomFromText('POLYGON((0 0,0 1,1 1,1 0,0 0))',4326)); st_asgml -------- <gml:Polygon srsName="EPSG:4326"><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>0,0 0,1 1,1 1,0 0,0</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon>
-- Flip coordinates and output extended EPSG (16 | 1)-- SELECT ST_AsGML(3, ST_GeomFromText('POINT(5.234234233242 6.34534534534)',4326), 5, 17); st_asgml -------- <gml:Point srsName="urn:ogc:def:crs:EPSG::4326"><gml:pos>6.34535 5.23423</gml:pos></gml:Point>
-- Output the envelope (32) -- SELECT ST_AsGML(3, ST_GeomFromText('LINESTRING(1 2, 3 4, 10 20)',4326), 5, 32); st_asgml -------- <gml:Envelope srsName="EPSG:4326"> <gml:lowerCorner>1 2</gml:lowerCorner> <gml:upperCorner>10 20</gml:upperCorner> </gml:Envelope>
-- Output the envelope (32) , reverse (lat lon instead of lon lat) (16), long srs (1)= 32 | 16 | 1 = 49 -- SELECT ST_AsGML(3, ST_GeomFromText('LINESTRING(1 2, 3 4, 10 20)',4326), 5, 49); st_asgml -------- <gml:Envelope srsName="urn:ogc:def:crs:EPSG::4326"> <gml:lowerCorner>2 1</gml:lowerCorner> <gml:upperCorner>20 10</gml:upperCorner> </gml:Envelope>
-- Polyhedral Example -- SELECT ST_AsGML(3, ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )')); st_asgml -------- <gml:PolyhedralSurface> <gml:polygonPatches> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing> <gml:posList srsDimension="3">0 0 0 0 0 1 0 1 1 0 1 0 0 0 0</gml:posList> </gml:LinearRing> </gml:exterior> </gml:PolygonPatch> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing> <gml:posList srsDimension="3">0 0 0 0 1 0 1 1 0 1 0 0 0 0 0</gml:posList> </gml:LinearRing> </gml:exterior> </gml:PolygonPatch> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing> <gml:posList srsDimension="3">0 0 0 1 0 0 1 0 1 0 0 1 0 0 0</gml:posList> </gml:LinearRing> </gml:exterior> </gml:PolygonPatch> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing> <gml:posList srsDimension="3">1 1 0 1 1 1 1 0 1 1 0 0 1 1 0</gml:posList> </gml:LinearRing> </gml:exterior> </gml:PolygonPatch> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing> <gml:posList srsDimension="3">0 1 0 0 1 1 1 1 1 1 1 0 0 1 0</gml:posList> </gml:LinearRing> </gml:exterior> </gml:PolygonPatch> <gml:PolygonPatch> <gml:exterior> <gml:LinearRing> <gml:posList srsDimension="3">0 0 1 1 0 1 1 1 1 0 1 1 0 0 1</gml:posList> </gml:LinearRing> </gml:exterior> </gml:PolygonPatch> </gml:polygonPatches> </gml:PolyhedralSurface>
ST_AsKML — Return the geometry as a KML element.
text ST_AsKML(
geometry geom, integer maxdecimaldigits=15, text nprefix=NULL)
;
text ST_AsKML(
geography geog, integer maxdecimaldigits=15, text nprefix=NULL)
;
Return the geometry as a Keyhole Markup Language (KML) element. default maximum number of decimal places is 15, default namespace is no prefix.
![]() | |
Using the |
![]() | |
Requiere que PostGIS sea compilado con soporte de Proj. Utilice PostGIS_Full_Version para confirmar que ha compilado el soporte de proyectos. |
![]() | |
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.
Disponibilidad: 2.0
Default format.
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)')); st_aslatlontext ---------------------------- 2°19'29.928"S 3°14'3.243"W
Providing a format (same as the default).
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)', 'D°M''S.SSS"C')); st_aslatlontext ---------------------------- 2°19'29.928"S 3°14'3.243"W
Characters other than D, M, S, C and . are just passed through.
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)', 'D degrees, M minutes, S seconds to the C')); st_aslatlontext -------------------------------------------------------------------------------------- 2 degrees, 19 minutes, 30 seconds to the S 3 degrees, 14 minutes, 3 seconds to the W
Signed degrees instead of cardinal directions.
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)', 'D°M''S.SSS"')); st_aslatlontext ---------------------------- -2°19'29.928" -3°14'3.243"
Decimal degrees.
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)', 'D.DDDD degrees C')); st_aslatlontext ----------------------------------- 2.3250 degrees S 3.2342 degrees W
Excessively large values are normalized.
SELECT (ST_AsLatLonText('POINT (-302.2342342 -792.32498)')); st_aslatlontext ------------------------------- 72°19'29.928"S 57°45'56.757"E
ST_AsMARC21 — Returns geometry as a MARC21/XML record with a geographic datafield (034).
text ST_AsMARC21 (
geometry geom , text format='hdddmmss' )
;
This function returns a MARC21/XML record with Coded Cartographic Mathematical Data representing the bounding box of a given geometry. The format
parameter allows to encode the coordinates in subfields $d
,$e
,$f
and $g
in all formats supported by the MARC21/XML standard. Valid formats are:
cardinal direction, degrees, minutes and seconds (default): hdddmmss
decimal degrees with cardinal direction: hddd.dddddd
decimal degrees without cardinal direction: ddd.dddddd
decimal minutes with cardinal direction: hdddmm.mmmm
decimal minutes without cardinal direction: dddmm.mmmm
decimal seconds with cardinal direction: hdddmmss.sss
The decimal sign may be also a comma, e.g. hdddmm,mmmm
.
The precision of decimal formats can be limited by the number of characters after the decimal sign, e.g. hdddmm.mm
for decimal minutes with a precision of two decimals.
This function ignores the Z and M dimensions.
LOC MARC21/XML versions supported:
Availability: 3.3.0
![]() | |
This function does not support non lon/lat geometries, as they are not supported by the MARC21/XML standard (Coded Cartographic Mathematical Data). |
![]() | |
The MARC21/XML Standard does not provide any means to annotate the spatial reference system for Coded Cartographic Mathematical Data, which means that this information will be lost after conversion to MARC21/XML. |
Converting a POINT
to MARC21/XML formated as hdddmmss (default)
SELECT ST_AsMARC21('SRID=4326;POINT(-4.504289 54.253312)'::geometry); st_asmarc21 ------------------------------------------------- <record xmlns="http://www.loc.gov/MARC21/slim"> <datafield tag="034" ind1="1" ind2=" "> <subfield code="a">a</subfield> <subfield code="d">W0043015</subfield> <subfield code="e">W0043015</subfield> <subfield code="f">N0541512</subfield> <subfield code="g">N0541512</subfield> </datafield> </record>
Converting a POLYGON
to MARC21/XML formated in decimal degrees
SELECT ST_AsMARC21('SRID=4326;POLYGON((-4.5792388916015625 54.18172660239091,-4.56756591796875 54.196993557130355,-4.546623229980469 54.18313300502024,-4.5792388916015625 54.18172660239091))'::geometry,'hddd.dddd'); <record xmlns="http://www.loc.gov/MARC21/slim"> <datafield tag="034" ind1="1" ind2=" "> <subfield code="a">a</subfield> <subfield code="d">W004.5792</subfield> <subfield code="e">W004.5466</subfield> <subfield code="f">N054.1970</subfield> <subfield code="g">N054.1817</subfield> </datafield> </record>
Converting a GEOMETRYCOLLECTION
to MARC21/XML formated in decimal minutes. The geometries order in the MARC21/XML output correspond to their order in the collection.
SELECT ST_AsMARC21('SRID=4326;GEOMETRYCOLLECTION(POLYGON((13.1 52.65,13.516666666666667 52.65,13.516666666666667 52.38333333333333,13.1 52.38333333333333,13.1 52.65)),POINT(-4.5 54.25))'::geometry,'hdddmm.mmmm'); st_asmarc21 ------------------------------------------------- <record xmlns="http://www.loc.gov/MARC21/slim"> <datafield tag="034" ind1="1" ind2=" "> <subfield code="a">a</subfield> <subfield code="d">E01307.0000</subfield> <subfield code="e">E01331.0000</subfield> <subfield code="f">N05240.0000</subfield> <subfield code="g">N05224.0000</subfield> </datafield> <datafield tag="034" ind1="1" ind2=" "> <subfield code="a">a</subfield> <subfield code="d">W00430.0000</subfield> <subfield code="e">W00430.0000</subfield> <subfield code="f">N05415.0000</subfield> <subfield code="g">N05415.0000</subfield> </datafield> </record>
ST_AsMVTGeom — Transforms a geometry into the coordinate space of a MVT tile.
geometry ST_AsMVTGeom(
geometry geom, box2d bounds, integer extent=4096, integer buffer=256, boolean clip_geom=true)
;
Transforms a geometry into the coordinate space of a MVT (Mapbox Vector Tile) tile, clipping it to the tile bounds if required. The geometry must be in the coordinate system of the target map (using ST_Transform if needed). Commonly this is Web Mercator (SRID:3857).
The function attempts to preserve geometry validity, and corrects it if needed. This may cause the result geometry to collapse to a lower dimension.
The rectangular bounds of the tile in the target map coordinate space must be provided, so the geometry can be transformed, and clipped if required. The bounds can be generated using ST_MakeEnvelope.
This function is used to convert geometry into the tile coordinate space required by ST_AsMVT.
geom
is the geometry to transform, in the coordinate system of the target map.
bounds
is the rectangular bounds of the tile in map coordinate space, with no buffer.
extent
is the tile extent size in tile coordinate space as defined by the MVT specification. Defaults to 4096.
buffer
is the buffer size in tile coordinate space for geometry clippig. Defaults to 256.
clip_geom
is a boolean to control if geometries are clipped or encoded as-is. Defaults to true.
Availability: 2.4.0
![]() | |
From 3.0, Wagyu can be chosen at configure time to clip and validate MVT polygons. This library is faster and produces more correct results than the GEOS default, but it might drop small polygons. |
SELECT ST_AsText(ST_AsMVTGeom( ST_GeomFromText('POLYGON ((0 0, 10 0, 10 5, 0 -5, 0 0))'), ST_MakeBox2D(ST_Point(0, 0), ST_Point(4096, 4096)), 4096, 0, false)); st_astext -------------------------------------------------------------------- MULTIPOLYGON(((5 4096,10 4091,10 4096,5 4096)),((5 4096,0 4101,0 4096,5 4096)))
Canonical example for a Web Mercator tile using a computed tile bounds to query and clip geometry.
SELECT ST_AsMVTGeom( ST_Transform( geom, 3857 ), ST_TileEnvelope(12, 513, 412), extent => 4096, buffer => 64) AS geom FROM data WHERE geom && ST_TileEnvelope(12, 513, 412, margin => (64.0 / 4096))
ST_AsMVT — Aggregate function returning a MVT representation of a set of rows.
bytea ST_AsMVT(
anyelement set row)
;
bytea ST_AsMVT(
anyelement row, text name)
;
bytea ST_AsMVT(
anyelement row, text name, integer extent)
;
bytea ST_AsMVT(
anyelement row, text name, integer extent, text geom_name)
;
bytea ST_AsMVT(
anyelement row, text name, integer extent, text geom_name, text feature_id_name)
;
An aggregate function which returns a binary Mapbox Vector Tile representation of a set of rows corresponding to a tile layer. The rows must contain a geometry column which will be encoded as a feature geometry. The geometry must be in tile coordinate space and valid as per the MVT specification. ST_AsMVTGeom can be used to transform geometry into tile coordinate space. Other row columns are encoded as feature attributes.
The Mapbox Vector Tile format can store features with varying sets of attributes. To use this capability supply a JSONB column in the row data containing Json objects one level deep. The keys and values in the JSONB values will be encoded as feature attributes.
Tiles with multiple layers can be created by concatenating multiple calls to this function using ||
or STRING_AGG
.
![]() | |
Do not call with a |
row
row data with at least a geometry column.
name
is the name of the layer. Default is the string "default".
extent
is the tile extent in screen space as defined by the specification. Default is 4096.
geom_name
is the name of the geometry column in the row data. Default is the first geometry column. Note that PostgreSQL by default automatically folds unquoted identifiers to lower case, which means that unless the geometry column is quoted, e.g. "MyMVTGeom"
, this parameter must be provided as lowercase.
feature_id_name
is the name of the Feature ID column in the row data. If NULL or negative the Feature ID is not set. The first column matching name and valid type (smallint, integer, bigint) will be used as Feature ID, and any subsequent column will be added as a property. JSON properties are not supported.
Enhanced: 3.0 - added support for Feature ID.
Enhanced: 2.5.0 - added support parallel query.
Availability: 2.4.0
ST_AsSVG — Returns SVG path data for a geometry.
text ST_AsSVG(
geometry geom, integer rel=0, integer maxdecimaldigits=15)
;
text ST_AsSVG(
geography geog, integer rel=0, integer maxdecimaldigits=15)
;
Return the geometry as Scalar Vector Graphics (SVG) path data. Use 1 as second argument to have the path data implemented in terms of relative moves, the default (or 0) uses absolute moves. Third argument may be used to reduce the maximum number of decimal digits used in output (defaults to 15). Point geometries will be rendered as cx/cy when 'rel' arg is 0, x/y when 'rel' is 1. Multipoint geometries are delimited by commas (","), GeometryCollection geometries are delimited by semicolons (";").
![]() | |
Availability: 1.2.2. Availability: 1.4.0 Changed in PostGIS 1.4.0 to include L command in absolute path to conform to http://www.w3.org/TR/SVG/paths.html#PathDataBNF |
Changed: 2.0.0 to use default args and support named args
ST_AsTWKB — Returns the geometry as TWKB, aka "Tiny Well-Known Binary"
bytea ST_AsTWKB(
geometry geom, integer prec=0, integer prec_z=0, integer prec_m=0, boolean with_sizes=false, boolean with_boxes=false)
;
bytea ST_AsTWKB(
geometry[] geom, bigint[] ids, integer prec=0, integer prec_z=0, integer prec_m=0, boolean with_sizes=false, boolean with_boxes=false)
;
Returns the geometry in TWKB (Tiny Well-Known Binary) format. TWKB is a compressed binary format with a focus on minimizing the size of the output.
The decimal digits parameters control how much precision is stored in the output. By default, values are rounded to the nearest unit before encoding. If you want to transfer more precision, increase the number. For example, a value of 1 implies that the first digit to the right of the decimal point will be preserved.
The sizes and bounding boxes parameters control whether optional information about the encoded length of the object and the bounds of the object are included in the output. By default they are not. Do not turn them on unless your client software has a use for them, as they just use up space (and saving space is the point of TWKB).
The array-input form of the function is used to convert a collection of geometries and unique identifiers into a TWKB collection that preserves the identifiers. This is useful for clients that expect to unpack a collection and then access further information about the objects inside. You can create the arrays using the array_agg function. The other parameters operate the same as for the simple form of the function.
![]() | |
The format specification is available online at https://github.com/TWKB/Specification, and code for building a JavaScript client can be found at https://github.com/TWKB/twkb.js. |
Enhanced: 2.4.0 memory and speed improvements.
Disponibilidad: 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.
Disponibilidad: 1.4.0
![]() | |
ST_GeoHash requires input geometry to be in geographic (lon/lat) coordinates. |
This method supports Circular Strings and Curves
SELECT ST_GeoHash( ST_Point(-126,48) ); st_geohash ---------------------- c0w3hf1s70w3hf1s70w3 SELECT ST_GeoHash( ST_Point(-126,48), 5); st_geohash ------------ c0w3h -- This line contains the point, so the GeoHash is a prefix of the point code SELECT ST_GeoHash('LINESTRING(-126 48, -126.1 48.1)'::geometry); st_geohash ------------ c0w3
TRUE
if A's 2D bounding box intersects B's 2D bounding box.TRUE
if a geometry's (cached) 2D bounding box intersects a 2D float precision bounding box (BOX2DF).TRUE
if a 2D float precision bounding box (BOX2DF) intersects a geometry's (cached) 2D bounding box.TRUE
if two 2D float precision bounding boxes (BOX2DF) intersect each other.TRUE
if A's n-D bounding box intersects B's n-D bounding box.TRUE
if a geometry's (cached) n-D bounding box intersects a n-D float precision bounding box (GIDX).TRUE
if a n-D float precision bounding box (GIDX) intersects a geometry's (cached) n-D bounding box.TRUE
if two n-D float precision bounding boxes (GIDX) intersect each other.TRUE
if A's bounding box overlaps or is to the left of B's.TRUE
if A's bounding box overlaps or is below B's.TRUE
if A' bounding box overlaps or is to the right of B's.TRUE
if A's bounding box is strictly to the left of B's.TRUE
if A's bounding box is strictly below B's.TRUE
if the coordinates and coordinate order geometry/geography A are the same as the coordinates and coordinate order of geometry/geography B.TRUE
if A's bounding box is strictly to the right of B's.TRUE
if A's bounding box is contained by B's.TRUE
if a geometry's 2D bounding box is contained into a 2D float precision bounding box (BOX2DF).TRUE
if a 2D float precision bounding box (BOX2DF) is contained into a geometry's 2D bounding box.TRUE
if a 2D float precision bounding box (BOX2DF) is contained into another 2D float precision bounding box.TRUE
if A's bounding box overlaps or is above B's.TRUE
if A's bounding box is strictly above B's.TRUE
if A's bounding box contains B's.TRUE
if a geometry's 2D bonding box contains a 2D float precision bounding box (GIDX).TRUE
if a 2D float precision bounding box (BOX2DF) contains a geometry's 2D bonding box.TRUE
if a 2D float precision bounding box (BOX2DF) contains another 2D float precision bounding box (BOX2DF).TRUE
if A's bounding box is the same as B's.&& — Returns TRUE
if A's 2D bounding box intersects B's 2D bounding box.
boolean &&(
geometry A , geometry B )
;
boolean &&(
geography A , geography B )
;
The &&
operator returns TRUE
if the 2D bounding box of geometry A intersects the 2D bounding box of geometry B.
![]() | |
This operand will make use of any indexes that may be available on the geometries. |
Mejorado: 2.0.0 soporte para superficies poliédricas fue introducida.
Availability: 1.5.0 support for geography was introduced.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
SELECT tbl1.column1, tbl2.column1, tbl1.column2 && tbl2.column2 AS overlaps FROM ( VALUES (1, 'LINESTRING(0 0, 3 3)'::geometry), (2, 'LINESTRING(0 1, 0 5)'::geometry)) AS tbl1, ( VALUES (3, 'LINESTRING(1 2, 4 6)'::geometry)) AS tbl2; column1 | column1 | overlaps ---------+---------+---------- 1 | 3 | t 2 | 3 | f (2 rows)
&&(geometry,box2df) — Returns TRUE
if a geometry's (cached) 2D bounding box intersects a 2D float precision bounding box (BOX2DF).
boolean &&(
geometry A , box2df B )
;
The &&
operator returns TRUE
if the cached 2D bounding box of geometry A intersects the 2D bounding box B, using float precision. This means that if B is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)
![]() | |
This operand is intended to be used internally by BRIN indexes, more than by users. |
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
&&(box2df,geometry) — Returns TRUE
if a 2D float precision bounding box (BOX2DF) intersects a geometry's (cached) 2D bounding box.
boolean &&(
box2df A , geometry B )
;
The &&
operator returns TRUE
if the 2D bounding box A intersects the cached 2D bounding box of geometry B, using float precision. This means that if A is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)
![]() | |
This operand is intended to be used internally by BRIN indexes, more than by users. |
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
&&(box2df,box2df) — Returns TRUE
if two 2D float precision bounding boxes (BOX2DF) intersect each other.
boolean &&(
box2df A , box2df B )
;
The &&
operator returns TRUE
if two 2D bounding boxes A and B intersect each other, using float precision. This means that if A (or B) is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)
![]() | |
This operator is intended to be used internally by BRIN indexes, more than by users. |
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
&&& — Returns TRUE
if A's n-D bounding box intersects B's n-D bounding box.
boolean &&&(
geometry A , geometry B )
;
The &&&
operator returns TRUE
if the n-D bounding box of geometry A intersects the n-D bounding box of geometry B.
![]() | |
This operand will make use of any indexes that may be available on the geometries. |
Disponibilidad: 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) — Returns TRUE
if a geometry's (cached) n-D bounding box intersects a n-D float precision bounding box (GIDX).
boolean &&&(
geometry A , gidx B )
;
The &&&
operator returns TRUE
if the cached n-D bounding box of geometry A intersects the n-D bounding box B, using float precision. This means that if B is a (double precision) box3d, it will be internally converted to a float precision 3D bounding box (GIDX)
![]() | |
This operator is intended to be used internally by BRIN indexes, more than by users. |
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
This function supports 3d and will not drop the z-index.
&&&(gidx,geometry) — Returns TRUE
if a n-D float precision bounding box (GIDX) intersects a geometry's (cached) n-D bounding box.
boolean &&&(
gidx A , geometry B )
;
The &&&
operator returns TRUE
if the n-D bounding box A intersects the cached n-D bounding box of geometry B, using float precision. This means that if A is a (double precision) box3d, it will be internally converted to a float precision 3D bounding box (GIDX)
![]() | |
This operator is intended to be used internally by BRIN indexes, more than by users. |
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
This function supports 3d and will not drop the z-index.
&&&(gidx,gidx) — Returns TRUE
if two n-D float precision bounding boxes (GIDX) intersect each other.
boolean &&&(
gidx A , gidx B )
;
The &&&
operator returns TRUE
if two n-D bounding boxes A and B intersect each other, using float precision. This means that if A (or B) is a (double precision) box3d, it will be internally converted to a float precision 3D bounding box (GIDX)
![]() | |
This operator is intended to be used internally by BRIN indexes, more than by users. |
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
This function supports 3d and will not drop the z-index.
&< — Returns TRUE
if A's bounding box overlaps or is to the left of B's.
boolean &<(
geometry A , geometry B )
;
The &<
operator returns TRUE
if the bounding box of geometry A overlaps or is to the left of the bounding box of geometry B, or more accurately, overlaps or is NOT to the right of the bounding box of geometry B.
![]() | |
This operand will make use of any indexes that may be available on the geometries. |
SELECT tbl1.column1, tbl2.column1, tbl1.column2 &< tbl2.column2 AS overleft FROM ( VALUES (1, 'LINESTRING(1 2, 4 6)'::geometry)) AS tbl1, ( VALUES (2, 'LINESTRING(0 0, 3 3)'::geometry), (3, 'LINESTRING(0 1, 0 5)'::geometry), (4, 'LINESTRING(6 0, 6 1)'::geometry)) AS tbl2; column1 | column1 | overleft ---------+---------+---------- 1 | 2 | f 1 | 3 | f 1 | 4 | t (3 rows)
&<| — Returns TRUE
if A's bounding box overlaps or is below B's.
boolean &<|(
geometry A , geometry B )
;
The &<|
operator returns TRUE
if the bounding box of geometry A overlaps or is below of the bounding box of geometry B, or more accurately, overlaps or is NOT above the bounding box of geometry B.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
![]() | |
This operand will make use of any indexes that may be available on the geometries. |
SELECT tbl1.column1, tbl2.column1, tbl1.column2 &<| tbl2.column2 AS overbelow FROM ( VALUES (1, 'LINESTRING(6 0, 6 4)'::geometry)) AS tbl1, ( VALUES (2, 'LINESTRING(0 0, 3 3)'::geometry), (3, 'LINESTRING(0 1, 0 5)'::geometry), (4, 'LINESTRING(1 2, 4 6)'::geometry)) AS tbl2; column1 | column1 | overbelow ---------+---------+----------- 1 | 2 | f 1 | 3 | t 1 | 4 | t (3 rows)
&> — Returns TRUE
if A' bounding box overlaps or is to the right of B's.
boolean &>(
geometry A , geometry B )
;
The &>
operator returns TRUE
if the bounding box of geometry A overlaps or is to the right of the bounding box of geometry B, or more accurately, overlaps or is NOT to the left of the bounding box of geometry B.
![]() | |
This operand will make use of any indexes that may be available on the geometries. |
SELECT tbl1.column1, tbl2.column1, tbl1.column2 &> tbl2.column2 AS overright FROM ( VALUES (1, 'LINESTRING(1 2, 4 6)'::geometry)) AS tbl1, ( VALUES (2, 'LINESTRING(0 0, 3 3)'::geometry), (3, 'LINESTRING(0 1, 0 5)'::geometry), (4, 'LINESTRING(6 0, 6 1)'::geometry)) AS tbl2; column1 | column1 | overright ---------+---------+----------- 1 | 2 | t 1 | 3 | t 1 | 4 | f (3 rows)
<< — Returns TRUE
if A's bounding box is strictly to the left of B's.
boolean <<(
geometry A , geometry B )
;
The <<
operator returns TRUE
if the bounding box of geometry A is strictly to the left of the bounding box of geometry B.
![]() | |
This operand will make use of any indexes that may be available on the geometries. |
SELECT tbl1.column1, tbl2.column1, tbl1.column2 << tbl2.column2 AS left FROM ( VALUES (1, 'LINESTRING (1 2, 1 5)'::geometry)) AS tbl1, ( VALUES (2, 'LINESTRING (0 0, 4 3)'::geometry), (3, 'LINESTRING (6 0, 6 5)'::geometry), (4, 'LINESTRING (2 2, 5 6)'::geometry)) AS tbl2; column1 | column1 | left ---------+---------+------ 1 | 2 | f 1 | 3 | t 1 | 4 | t (3 rows)
<<| — Returns TRUE
if A's bounding box is strictly below B's.
boolean <<|(
geometry A , geometry B )
;
The <<|
operator returns TRUE
if the bounding box of geometry A is strictly below the bounding box of geometry B.
![]() | |
This operand will make use of any indexes that may be available on the geometries. |
SELECT tbl1.column1, tbl2.column1, tbl1.column2 <<| tbl2.column2 AS below FROM ( VALUES (1, 'LINESTRING (0 0, 4 3)'::geometry)) AS tbl1, ( VALUES (2, 'LINESTRING (1 4, 1 7)'::geometry), (3, 'LINESTRING (6 1, 6 5)'::geometry), (4, 'LINESTRING (2 3, 5 6)'::geometry)) AS tbl2; column1 | column1 | below ---------+---------+------- 1 | 2 | t 1 | 3 | f 1 | 4 | f (3 rows)
= — Returns TRUE
if the coordinates and coordinate order geometry/geography A are the same as the coordinates and coordinate order of geometry/geography B.
boolean =(
geometry A , geometry B )
;
boolean =(
geography A , geography B )
;
The =
operator returns TRUE
if the coordinates and coordinate order geometry/geography A are the same as the coordinates and coordinate order of geometry/geography B. PostgreSQL uses the =, <, and > operators defined for geometries to perform internal orderings and comparison of geometries (ie. in a GROUP BY or ORDER BY clause).
![]() | |
Only geometry/geography that are exactly equal in all respects, with the same coordinates, in the same order, are considered equal by this operator. For "spatial equality", that ignores things like coordinate order, and can detect features that cover the same spatial area with different representations, use ST_OrderingEquals or ST_Equals |
![]() | |
This operand will NOT make use of any indexes that may be available on the geometries. For an index assisted exact equality test, combine = with &&. |
Changed: 2.4.0, in prior versions this was bounding box equality not a geometric equality. If you need bounding box equality, use ~= instead.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
SELECT 'LINESTRING(0 0, 0 1, 1 0)'::geometry = 'LINESTRING(1 1, 0 0)'::geometry; ?column? ---------- f (1 row) SELECT ST_AsText(column1) FROM ( VALUES ('LINESTRING(0 0, 1 1)'::geometry), ('LINESTRING(1 1, 0 0)'::geometry)) AS foo; st_astext --------------------- LINESTRING(0 0,1 1) LINESTRING(1 1,0 0) (2 rows) -- Note: the GROUP BY uses the "=" to compare for geometry equivalency. SELECT ST_AsText(column1) FROM ( VALUES ('LINESTRING(0 0, 1 1)'::geometry), ('LINESTRING(1 1, 0 0)'::geometry)) AS foo GROUP BY column1; st_astext --------------------- LINESTRING(0 0,1 1) LINESTRING(1 1,0 0) (2 rows) -- In versions prior to 2.0, this used to return true -- SELECT ST_GeomFromText('POINT(1707296.37 4820536.77)') = ST_GeomFromText('POINT(1707296.27 4820536.87)') As pt_intersect; --pt_intersect -- f
>> — Returns TRUE
if A's bounding box is strictly to the right of B's.
boolean >>(
geometry A , geometry B )
;
The >>
operator returns TRUE
if the bounding box of geometry A is strictly to the right of the bounding box of geometry B.
![]() | |
This operand will make use of any indexes that may be available on the geometries. |
SELECT tbl1.column1, tbl2.column1, tbl1.column2 >> tbl2.column2 AS right FROM ( VALUES (1, 'LINESTRING (2 3, 5 6)'::geometry)) AS tbl1, ( VALUES (2, 'LINESTRING (1 4, 1 7)'::geometry), (3, 'LINESTRING (6 1, 6 5)'::geometry), (4, 'LINESTRING (0 0, 4 3)'::geometry)) AS tbl2; column1 | column1 | right ---------+---------+------- 1 | 2 | t 1 | 3 | f 1 | 4 | f (3 rows)
@ — Returns TRUE
if A's bounding box is contained by B's.
boolean @(
geometry A , geometry B )
;
The @
operator returns TRUE
if the bounding box of geometry A is completely contained by the bounding box of geometry B.
![]() | |
This operand will make use of any indexes that may be available on the geometries. |
SELECT tbl1.column1, tbl2.column1, tbl1.column2 @ tbl2.column2 AS contained FROM ( VALUES (1, 'LINESTRING (1 1, 3 3)'::geometry)) AS tbl1, ( VALUES (2, 'LINESTRING (0 0, 4 4)'::geometry), (3, 'LINESTRING (2 2, 4 4)'::geometry), (4, 'LINESTRING (1 1, 3 3)'::geometry)) AS tbl2; column1 | column1 | contained ---------+---------+----------- 1 | 2 | t 1 | 3 | f 1 | 4 | t (3 rows)
@(geometry,box2df) — Returns TRUE
if a geometry's 2D bounding box is contained into a 2D float precision bounding box (BOX2DF).
boolean @(
geometry A , box2df B )
;
The @
operator returns TRUE
if the A geometry's 2D bounding box is contained the 2D bounding box B, using float precision. This means that if B is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)
![]() | |
This operand is intended to be used internally by BRIN indexes, more than by users. |
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
@(box2df,geometry) — Returns TRUE
if a 2D float precision bounding box (BOX2DF) is contained into a geometry's 2D bounding box.
boolean @(
box2df A , geometry B )
;
The @
operator returns TRUE
if the 2D bounding box A is contained into the B geometry's 2D bounding box, using float precision. This means that if B is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)
![]() | |
This operand is intended to be used internally by BRIN indexes, more than by users. |
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
@(box2df,box2df) — Returns TRUE
if a 2D float precision bounding box (BOX2DF) is contained into another 2D float precision bounding box.
boolean @(
box2df A , box2df B )
;
The @
operator returns TRUE
if the 2D bounding box A is contained into the 2D bounding box B, using float precision. This means that if A (or B) is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)
![]() | |
This operand is intended to be used internally by BRIN indexes, more than by users. |
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
|&> — Returns TRUE
if A's bounding box overlaps or is above B's.
boolean |&>(
geometry A , geometry B )
;
The |&>
operator returns TRUE
if the bounding box of geometry A overlaps or is above the bounding box of geometry B, or more accurately, overlaps or is NOT below the bounding box of geometry B.
![]() | |
This operand will make use of any indexes that may be available on the geometries. |
SELECT tbl1.column1, tbl2.column1, tbl1.column2 |&> tbl2.column2 AS overabove FROM ( VALUES (1, 'LINESTRING(6 0, 6 4)'::geometry)) AS tbl1, ( VALUES (2, 'LINESTRING(0 0, 3 3)'::geometry), (3, 'LINESTRING(0 1, 0 5)'::geometry), (4, 'LINESTRING(1 2, 4 6)'::geometry)) AS tbl2; column1 | column1 | overabove ---------+---------+----------- 1 | 2 | t 1 | 3 | f 1 | 4 | f (3 rows)
|>> — Returns TRUE
if A's bounding box is strictly above B's.
boolean |>>(
geometry A , geometry B )
;
The |>>
operator returns TRUE
if the bounding box of geometry A is strictly above the bounding box of geometry B.
![]() | |
This operand will make use of any indexes that may be available on the geometries. |
SELECT tbl1.column1, tbl2.column1, tbl1.column2 |>> tbl2.column2 AS above FROM ( VALUES (1, 'LINESTRING (1 4, 1 7)'::geometry)) AS tbl1, ( VALUES (2, 'LINESTRING (0 0, 4 2)'::geometry), (3, 'LINESTRING (6 1, 6 5)'::geometry), (4, 'LINESTRING (2 3, 5 6)'::geometry)) AS tbl2; column1 | column1 | above ---------+---------+------- 1 | 2 | t 1 | 3 | f 1 | 4 | f (3 rows)
~ — Returns TRUE
if A's bounding box contains B's.
boolean ~(
geometry A , geometry B )
;
The ~
operator returns TRUE
if the bounding box of geometry A completely contains the bounding box of geometry B.
![]() | |
This operand will make use of any indexes that may be available on the geometries. |
SELECT tbl1.column1, tbl2.column1, tbl1.column2 ~ tbl2.column2 AS contains FROM ( VALUES (1, 'LINESTRING (0 0, 3 3)'::geometry)) AS tbl1, ( VALUES (2, 'LINESTRING (0 0, 4 4)'::geometry), (3, 'LINESTRING (1 1, 2 2)'::geometry), (4, 'LINESTRING (0 0, 3 3)'::geometry)) AS tbl2; column1 | column1 | contains ---------+---------+---------- 1 | 2 | f 1 | 3 | t 1 | 4 | t (3 rows)
~(geometry,box2df) — Returns TRUE
if a geometry's 2D bonding box contains a 2D float precision bounding box (GIDX).
boolean ~(
geometry A , box2df B )
;
The ~
operator returns TRUE
if the 2D bounding box of a geometry A contains the 2D bounding box B, using float precision. This means that if B is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)
![]() | |
This operand is intended to be used internally by BRIN indexes, more than by users. |
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
~(box2df,geometry) — Returns TRUE
if a 2D float precision bounding box (BOX2DF) contains a geometry's 2D bonding box.
boolean ~(
box2df A , geometry B )
;
The ~
operator returns TRUE
if the 2D bounding box A contains the B geometry's bounding box, using float precision. This means that if A is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)
![]() | |
This operand is intended to be used internally by BRIN indexes, more than by users. |
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
~(box2df,box2df) — Returns TRUE
if a 2D float precision bounding box (BOX2DF) contains another 2D float precision bounding box (BOX2DF).
boolean ~(
box2df A , box2df B )
;
The ~
operator returns TRUE
if the 2D bounding box A contains the 2D bounding box B, using float precision. This means that if A is a (double precision) box2d, it will be internally converted to a float precision 2D bounding box (BOX2DF)
![]() | |
This operand is intended to be used internally by BRIN indexes, more than by users. |
Availability: 2.3.0 support for Block Range INdexes (BRIN) was introduced. Requires PostgreSQL 9.5+.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
~= — Returns TRUE
if A's bounding box is the same as B's.
boolean ~=(
geometry A , geometry B )
;
The ~=
operator returns TRUE
if the bounding box of geometry/geography A is the same as the bounding box of geometry/geography B.
![]() | |
This operand will make use of any indexes that may be available on the geometries. |
Availability: 1.5.0 changed behavior
This function supports Polyhedral surfaces.
![]() | |
This operator has changed behavior in PostGIS 1.5 from testing for actual geometric equality to only checking for bounding box equality. To complicate things it also depends on if you have done a hard or soft upgrade which behavior your database has. To find out which behavior your database has you can run the query below. To check for true equality use ST_OrderingEquals or ST_Equals. |
<-> — Returns the 2D distance between A and B.
double precision <->(
geometry A , geometry B )
;
double precision <->(
geography A , geography B )
;
The <->
operator returns the 2D distance between two geometries. Used in the "ORDER BY" clause provides index-assisted nearest-neighbor result sets. For PostgreSQL below 9.5 only gives centroid distance of bounding boxes and for PostgreSQL 9.5+, does true KNN distance search giving true distance between geometries, and distance sphere for geographies.
![]() | |
This operand will make use of 2D GiST indexes that may be available on the geometries. It is different from other operators that use spatial indexes in that the spatial index is only used when the operator is in the ORDER BY clause. |
![]() | |
Index only kicks in if one of the geometries is a constant (not in a subquery/cte). e.g. 'SRID=3005;POINT(1011102 450541)'::geometry instead of a.geom |
Refer to PostGIS workshop: Nearest-Neighbor Searching for a detailed example.
Enhanced: 2.2.0 -- True KNN ("K nearest neighbor") behavior for geometry and geography for PostgreSQL 9.5+. Note for geography KNN is based on sphere rather than spheroid. For PostgreSQL 9.4 and below, geography support is new but only supports centroid box.
Changed: 2.2.0 -- For PostgreSQL 9.5 users, old Hybrid syntax may be slower, so you'll want to get rid of that hack if you are running your code only on PostGIS 2.2+ 9.5+. See examples below.
Availability: 2.0.0 -- Weak KNN provides nearest neighbors based on geometry centroid distances instead of true distances. Exact results for points, inexact for all other types. Available for PostgreSQL 9.1+
SELECT ST_Distance(geom, 'SRID=3005;POINT(1011102 450541)'::geometry) as d,edabbr, vaabbr FROM va2005 ORDER BY d limit 10; d | edabbr | vaabbr ------------------+--------+-------- 0 | ALQ | 128 5541.57712511724 | ALQ | 129A 5579.67450712005 | ALQ | 001 6083.4207708641 | ALQ | 131 7691.2205404848 | ALQ | 003 7900.75451037313 | ALQ | 122 8694.20710669982 | ALQ | 129B 9564.24289057111 | ALQ | 130 12089.665931705 | ALQ | 127 18472.5531479404 | ALQ | 002 (10 rows)
Then the KNN raw answer:
SELECT st_distance(geom, 'SRID=3005;POINT(1011102 450541)'::geometry) as d,edabbr, vaabbr FROM va2005 ORDER BY geom <-> 'SRID=3005;POINT(1011102 450541)'::geometry limit 10; d | edabbr | vaabbr ------------------+--------+-------- 0 | ALQ | 128 5541.57712511724 | ALQ | 129A 5579.67450712005 | ALQ | 001 6083.4207708641 | ALQ | 131 7691.2205404848 | ALQ | 003 7900.75451037313 | ALQ | 122 8694.20710669982 | ALQ | 129B 9564.24289057111 | ALQ | 130 12089.665931705 | ALQ | 127 18472.5531479404 | ALQ | 002 (10 rows)
If you run "EXPLAIN ANALYZE" on the two queries you would see a performance improvement for the second.
For users running with PostgreSQL < 9.5, use a hybrid query to find the true nearest neighbors. First a CTE query using the index-assisted KNN, then an exact query to get correct ordering:
WITH index_query AS ( SELECT ST_Distance(geom, 'SRID=3005;POINT(1011102 450541)'::geometry) as d,edabbr, vaabbr FROM va2005 ORDER BY geom <-> 'SRID=3005;POINT(1011102 450541)'::geometry LIMIT 100) SELECT * FROM index_query ORDER BY d limit 10; d | edabbr | vaabbr ------------------+--------+-------- 0 | ALQ | 128 5541.57712511724 | ALQ | 129A 5579.67450712005 | ALQ | 001 6083.4207708641 | ALQ | 131 7691.2205404848 | ALQ | 003 7900.75451037313 | ALQ | 122 8694.20710669982 | ALQ | 129B 9564.24289057111 | ALQ | 130 12089.665931705 | ALQ | 127 18472.5531479404 | ALQ | 002 (10 rows)
|=| — Returns the distance between A and B trajectories at their closest point of approach.
double precision |=|(
geometry A , geometry B )
;
The |=|
operator returns the 3D distance between two trajectories (See ST_IsValidTrajectory). This is the same as ST_DistanceCPA but as an operator it can be used for doing nearest neighbor searches using an N-dimensional index (requires PostgreSQL 9.5.0 or higher).
![]() | |
This operand will make use of ND GiST indexes that may be available on the geometries. It is different from other operators that use spatial indexes in that the spatial index is only used when the operator is in the ORDER BY clause. |
![]() | |
Index only kicks in if one of the geometries is a constant (not in a subquery/cte). e.g. 'SRID=3005;LINESTRINGM(0 0 0,0 0 1)'::geometry instead of a.geom |
Availability: 2.2.0. Index-supported only available for PostgreSQL 9.5+
-- Save a literal query trajectory in a psql variable... \set qt 'ST_AddMeasure(ST_MakeLine(ST_MakePointM(-350,300,0),ST_MakePointM(-410,490,0)),10,20)' -- Run the query ! SELECT track_id, dist FROM ( SELECT track_id, ST_DistanceCPA(tr,:qt) dist FROM trajectories ORDER BY tr |=| :qt LIMIT 5 ) foo; track_id dist ----------+------------------- 395 | 0.576496831518066 380 | 5.06797130410151 390 | 7.72262293958322 385 | 9.8004461358071 405 | 10.9534397988433 (5 rows)
<#> — Returns the 2D distance between A and B bounding boxes.
double precision <#>(
geometry A , geometry B )
;
The <#>
operator returns distance between two floating point bounding boxes, possibly reading them from a spatial index (PostgreSQL 9.1+ required). Useful for doing nearest neighbor approximate distance ordering.
![]() | |
This operand will make use of any indexes that may be available on the geometries. It is different from other operators that use spatial indexes in that the spatial index is only used when the operator is in the ORDER BY clause. |
![]() | |
Index only kicks in if one of the geometries is a constant e.g. ORDER BY (ST_GeomFromText('POINT(1 2)') <#> geom) instead of g1.geom <#>. |
Availability: 2.0.0 -- KNN only available for PostgreSQL 9.1+
SELECT * FROM ( SELECT b.tlid, b.mtfcc, b.geom <#> ST_GeomFromText('LINESTRING(746149 2948672,745954 2948576, 745787 2948499,745740 2948468,745712 2948438, 745690 2948384,745677 2948319)',2249) As b_dist, ST_Distance(b.geom, ST_GeomFromText('LINESTRING(746149 2948672,745954 2948576, 745787 2948499,745740 2948468,745712 2948438, 745690 2948384,745677 2948319)',2249)) As act_dist FROM bos_roads As b ORDER BY b_dist, b.tlid LIMIT 100) As foo ORDER BY act_dist, tlid LIMIT 10; tlid | mtfcc | b_dist | act_dist -----------+-------+------------------+------------------ 85732027 | S1400 | 0 | 0 85732029 | S1400 | 0 | 0 85732031 | S1400 | 0 | 0 85734335 | S1400 | 0 | 0 85736037 | S1400 | 0 | 0 624683742 | S1400 | 0 | 128.528874268666 85719343 | S1400 | 260.839270432962 | 260.839270432962 85741826 | S1400 | 164.759294123275 | 260.839270432962 85732032 | S1400 | 277.75 | 311.830282365264 85735592 | S1400 | 222.25 | 311.830282365264 (10 rows)
<<->> — Returns the n-D distance between the centroids of A and B bounding boxes.
double precision <<->>(
geometry A , geometry B )
;
The <<->>
operator returns the n-D (euclidean) distance between the centroids of the bounding boxes of two geometries. Useful for doing nearest neighbor approximate distance ordering.
![]() | |
This operand will make use of n-D GiST indexes that may be available on the geometries. It is different from other operators that use spatial indexes in that the spatial index is only used when the operator is in the ORDER BY clause. |
![]() | |
Index only kicks in if one of the geometries is a constant (not in a subquery/cte). e.g. 'SRID=3005;POINT(1011102 450541)'::geometry instead of a.geom |
Availability: 2.2.0 -- KNN only available for PostgreSQL 9.1+
<<#>> — Returns the n-D distance between A and B bounding boxes.
double precision <<#>>(
geometry A , geometry B )
;
The <<#>>
operator returns distance between two floating point bounding boxes, possibly reading them from a spatial index (PostgreSQL 9.1+ required). Useful for doing nearest neighbor approximate distance ordering.
![]() | |
This operand will make use of any indexes that may be available on the geometries. It is different from other operators that use spatial indexes in that the spatial index is only used when the operator is in the ORDER BY clause. |
![]() | |
Index only kicks in if one of the geometries is a constant e.g. ORDER BY (ST_GeomFromText('POINT(1 2)') <<#>> geom) instead of g1.geom <<#>>. |
Availability: 2.2.0 -- KNN only available for PostgreSQL 9.1+
ST_3DIntersects — Tests if two geometries spatially intersect in 3D - only for points, linestrings, polygons, polyhedral surface (area)
boolean ST_3DIntersects(
geometry geomA , geometry geomB )
;
Overlaps, Touches, Within all imply spatial intersection. If any of the aforementioned returns true, then the geometries also spatially intersect. Disjoint implies false for spatial intersection.
![]() | |
This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available on the geometries. |
Changed: 3.0.0 SFCGAL backend removed, GEOS backend supports TINs.
Availability: 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 |
Performed by the GEOS module
Enhanced: 2.3.0 Enhancement to PIP short-circuit extended to support MultiPoints with few points. Prior versions only supported point in polygon.
![]() | |
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. |
Performed by the GEOS module.
Availability: 1.4.0
![]() | |
Enhanced: 3.0.0 enabled support for |
![]() | |
Do not use this function with invalid geometries. You will get unexpected results. |
--a circle within a circle SELECT ST_ContainsProperly(smallc, bigc) As smallcontainspropbig, ST_ContainsProperly(bigc,smallc) As bigcontainspropsmall, ST_ContainsProperly(bigc, ST_Union(smallc, bigc)) as bigcontainspropunion, ST_Equals(bigc, ST_Union(smallc, bigc)) as bigisunion, ST_Covers(bigc, ST_ExteriorRing(bigc)) As bigcoversexterior, ST_ContainsProperly(bigc, ST_ExteriorRing(bigc)) As bigcontainsexterior FROM (SELECT ST_Buffer(ST_GeomFromText('POINT(1 2)'), 10) As smallc, ST_Buffer(ST_GeomFromText('POINT(1 2)'), 20) As bigc) As foo; --Result smallcontainspropbig | bigcontainspropsmall | bigcontainspropunion | bigisunion | bigcoversexterior | bigcontainsexterior ------------------+------------------+------------------+------------+-------------------+--------------------- f | t | f | t | t | f --example demonstrating difference between contains and contains properly SELECT ST_GeometryType(geomA) As geomtype, ST_Contains(geomA,geomA) AS acontainsa, ST_ContainsProperly(geomA, geomA) AS acontainspropa, ST_Contains(geomA, ST_Boundary(geomA)) As acontainsba, ST_ContainsProperly(geomA, ST_Boundary(geomA)) As acontainspropba FROM (VALUES ( ST_Buffer(ST_Point(1,1), 5,1) ), ( ST_MakeLine(ST_Point(1,1), ST_Point(-1,-1) ) ), ( ST_Point(1,1) ) ) As foo(geomA); geomtype | acontainsa | acontainspropa | acontainsba | acontainspropba --------------+------------+----------------+-------------+----------------- ST_Polygon | t | f | f | f ST_LineString | t | f | f | f ST_Point | t | t | f | f
ST_GeometryType, ST_Boundary, ST_Contains, ST_Covers, ST_CoveredBy, ST_Equals, ST_Relate, ST_Within
ST_CoveredBy — Tests if every point of A lies in B
boolean ST_CoveredBy(
geometry geomA, geometry geomB)
;
boolean ST_CoveredBy(
geography geogA, geography geogB)
;
Returns true
if every point in Geometry/Geography A lies inside (i.e. intersects the interior or boundary of) Geometry/Geography B. Equivalently, tests that no point of A lies outside (in the exterior of) B.
ST_CoveredBy is the converse of ST_Covers. So, ST_CoveredBy(A,B) = ST_Covers(B,A)
.
Generally this function should be used instead of ST_Within, since it has a simpler definition which does not have the quirk that "boundaries are not within their geometry".
![]() | |
This function automatically includes a bounding box comparison
that makes use of any spatial indexes that are available on the geometries. To avoid index use, use the function |
![]() | |
Enhanced: 3.0.0 enabled support for |
![]() | |
Do not use this function with invalid geometries. You will get unexpected results. |
Performed by the GEOS module
Availability: 1.2.2
NOTE: this is the "allowable" version that returns a boolean, not an integer.
Not an OGC standard, but Oracle has it too.
--a circle coveredby a circle SELECT ST_CoveredBy(smallc,smallc) As smallinsmall, ST_CoveredBy(smallc, bigc) As smallcoveredbybig, ST_CoveredBy(ST_ExteriorRing(bigc), bigc) As exteriorcoveredbybig, ST_Within(ST_ExteriorRing(bigc),bigc) As exeriorwithinbig FROM (SELECT ST_Buffer(ST_GeomFromText('POINT(1 2)'), 10) As smallc, ST_Buffer(ST_GeomFromText('POINT(1 2)'), 20) As bigc) As foo; --Result smallinsmall | smallcoveredbybig | exteriorcoveredbybig | exeriorwithinbig --------------+-------------------+----------------------+------------------ t | t | t | f (1 row)
ST_Covers — Tests if every point of B lies in A
boolean ST_Covers(
geometry geomA, geometry geomB)
;
boolean ST_Covers(
geography geogpolyA, geography geogpointB)
;
Returns true
if every point in Geometry/Geography B lies inside (i.e. intersects the interior or boundary of) Geometry/Geography A. Equivalently, tests that no point of B lies outside (in the exterior of) A.
ST_Covers is the converse of ST_CoveredBy. So, ST_Covers(A,B) = ST_CoveredBy(B,A)
.
Generally this function should be used instead of ST_Contains, since it has a simpler definition which does not have the quirk that "geometries do not contain their boundary".
![]() | |
This function automatically includes a bounding box comparison
that makes use of any spatial indexes that are available on the geometries. To avoid index use, use the function |
![]() | |
Enhanced: 3.0.0 enabled support for |
![]() | |
Do not use this function with invalid geometries. You will get unexpected results. |
Performed by the GEOS module
Enhanced: 2.4.0 Support for polygon in polygon and line in polygon added for geography type
Enhanced: 2.3.0 Enhancement to PIP short-circuit for geometry extended to support MultiPoints with few points. Prior versions only supported point in polygon.
Availability: 1.5 - support for geography was introduced.
Availability: 1.2.2
NOTE: this is the "allowable" version that returns a boolean, not an integer.
Not an OGC standard, but Oracle has it too.
Geometry example
--a circle covering a circle SELECT ST_Covers(smallc,smallc) As smallinsmall, ST_Covers(smallc, bigc) As smallcoversbig, ST_Covers(bigc, ST_ExteriorRing(bigc)) As bigcoversexterior, ST_Contains(bigc, ST_ExteriorRing(bigc)) As bigcontainsexterior FROM (SELECT ST_Buffer(ST_GeomFromText('POINT(1 2)'), 10) As smallc, ST_Buffer(ST_GeomFromText('POINT(1 2)'), 20) As bigc) As foo; --Result smallinsmall | smallcoversbig | bigcoversexterior | bigcontainsexterior --------------+----------------+-------------------+--------------------- t | f | t | f (1 row)
Geeography Example
-- a point with a 300 meter buffer compared to a point, a point and its 10 meter buffer SELECT ST_Covers(geog_poly, geog_pt) As poly_covers_pt, ST_Covers(ST_Buffer(geog_pt,10), geog_pt) As buff_10m_covers_cent FROM (SELECT ST_Buffer(ST_GeogFromText('SRID=4326;POINT(-99.327 31.4821)'), 300) As geog_poly, ST_GeogFromText('SRID=4326;POINT(-99.33 31.483)') As geog_pt ) As foo; poly_covers_pt | buff_10m_covers_cent ----------------+------------------ f | t
ST_Crosses — Tests if two geometries have some, but not all, interior points in common
boolean ST_Crosses(
geometry g1, geometry g2)
;
Compares two geometry objects and returns true
if their intersection "spatially cross", that is, the geometries have some, but not all interior points in common. The intersection of the interiors of the geometries must be non-empty and must have dimension less than the maximum dimension of the two input geometries. Additionally, the intersection of the two geometries must not equal either of the source geometries. Otherwise, it returns false
.
In mathematical terms, this is:
Geometries cross if their DE-9IM Intersection Matrix matches:
T*T******
for Point/Line, Point/Area, and Line/Area situations
T*****T**
for Line/Point, Area/Point, and Area/Line situations
0********
for Line/Line situations
For Point/Point and Area/Area situations this predicate returns false
.
The OpenGIS Simple Features Specification defines this predicate only for Point/Line, Point/Area, Line/Line, and Line/Area situations. JTS / GEOS extends the definition to apply to Line/Point, Area/Point and Area/Line situations as well. This makes the relation symmetric.
![]() | |
This function automatically includes a bounding box comparison that makes use of any spatial indexes that are available on the geometries. |
![]() | |
Enhanced: 3.0.0 enabled support for |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s2.1.13.3
This method implements the SQL/MM specification. SQL-MM 3: 5.1.29
The following situations all return true
.
![]()
| ![]()
|
![]()
| ![]()
|
Consider a situation where a user has two tables: a table of roads and a table of highways.
CREATE TABLE roads ( id serial NOT NULL, geom geometry, CONSTRAINT roads_pkey PRIMARY KEY (road_id) );
|
CREATE TABLE highways ( id serial NOT NULL, the_gem geometry, CONSTRAINT roads_pkey PRIMARY KEY (road_id) );
|
To determine a list of roads that cross a highway, use a query similiar to:
SELECT roads.id FROM roads, highways WHERE ST_Crosses(roads.geom, highways.geom);
ST_Disjoint — Tests if two geometries have no points in common
boolean ST_Disjoint(
geometry A , geometry B )
;
Overlaps, Touches, Within all imply geometries are not spatially disjoint. If any of the aforementioned returns true, then the geometries are not spatially disjoint. Disjoint implies false for spatial intersection.
![]() | |
Enhanced: 3.0.0 enabled support for |
Performed by the GEOS module
![]() | |
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)
ST_LineCrossingDirection — Returns a number indicating the crossing behavior of two LineStrings
integer ST_LineCrossingDirection(
geometry linestringA, geometry linestringB)
;
Given two linestrings returns an integer between -3 and 3 indicating what kind of crossing behavior exists between them. 0 indicates no crossing. This is only supported for LINESTRING
s.
The crossing number has the following meaning:
0: LINE NO CROSS
-1: LINE CROSS LEFT
1: LINE CROSS RIGHT
-2: LINE MULTICROSS END LEFT
2: LINE MULTICROSS END RIGHT
-3: LINE MULTICROSS END SAME FIRST LEFT
3: LINE MULTICROSS END SAME FIRST RIGHT
Availability: 1.4
Example: LINE CROSS LEFT and LINE CROSS RIGHT
Blue: Line A; Green: Line B
SELECT ST_LineCrossingDirection(lineA, lineB) As A_cross_B, ST_LineCrossingDirection(lineB, lineA) As B_cross_A FROM (SELECT ST_GeomFromText('LINESTRING(25 169,89 114,40 70,86 43)') As lineA, ST_GeomFromText('LINESTRING (20 140, 71 74, 161 53)') As lineB ) As foo; A_cross_B | B_cross_A -----------+----------- -1 | 1
Example: LINE MULTICROSS END SAME FIRST LEFT and LINE MULTICROSS END SAME FIRST RIGHT
Blue: Line A; Green: Line B
SELECT ST_LineCrossingDirection(lineA, lineB) As A_cross_B, ST_LineCrossingDirection(lineB, lineA) As B_cross_A FROM (SELECT ST_GeomFromText('LINESTRING(25 169,89 114,40 70,86 43)') As lineA, ST_GeomFromText('LINESTRING(171 154,20 140,71 74,161 53)') As lineB ) As foo; A_cross_B | B_cross_A -----------+----------- 3 | -3
Example: LINE MULTICROSS END LEFT and LINE MULTICROSS END RIGHT
Blue: Line A; Green: Line B
SELECT ST_LineCrossingDirection(lineA, lineB) As A_cross_B, ST_LineCrossingDirection(lineB, lineA) As B_cross_A FROM (SELECT ST_GeomFromText('LINESTRING(25 169,89 114,40 70,86 43)') As lineA, ST_GeomFromText('LINESTRING(5 90, 71 74, 20 140, 171 154)') As lineB ) As foo; A_cross_B | B_cross_A -----------+----------- -2 | 2
Example: Finds all streets that cross
SELECT s1.gid, s2.gid, ST_LineCrossingDirection(s1.geom, s2.geom) FROM streets s1 CROSS JOIN streets s2 ON (s1.gid != s2.gid AND s1.geom && s2.geom ) WHERE ST_LineCrossingDirection(s1.geom, s2.geom) > 0;
ST_OrderingEquals — Tests if two geometries represent the same geometry and have points in the same directional order
boolean ST_OrderingEquals(
geometry A, geometry B)
;
ST_OrderingEquals compares two geometries and returns t (TRUE) if the geometries are equal and the coordinates are in the same order; otherwise it returns f (FALSE).
![]() | |
This function is implemented as per the ArcSDE SQL specification rather than SQL-MM. http://edndoc.esri.com/arcsde/9.1/sql_api/sqlapi3.htm#ST_OrderingEquals |
This method implements the SQL/MM specification. SQL-MM 3: 5.1.43
SELECT ST_OrderingEquals(ST_GeomFromText('LINESTRING(0 0, 10 10)'), ST_GeomFromText('LINESTRING(0 0, 5 5, 10 10)')); st_orderingequals ----------- f (1 row) SELECT ST_OrderingEquals(ST_GeomFromText('LINESTRING(0 0, 10 10)'), ST_GeomFromText('LINESTRING(0 0, 0 0, 10 10)')); st_orderingequals ----------- t (1 row) SELECT ST_OrderingEquals(ST_Reverse(ST_GeomFromText('LINESTRING(0 0, 10 10)')), ST_GeomFromText('LINESTRING(0 0, 0 0, 10 10)')); st_orderingequals ----------- f (1 row)
ST_Overlaps — Tests if two geometries have the same dimension and intersect, but each has at least one point not in the other
boolean ST_Overlaps(
geometry A, geometry B)
;
Returns TRUE if geometry A and B "spatially overlap". Two geometries overlap if they have the same dimension, their interiors intersect in that dimension. and each has at least one point inside the other (or equivalently, neither one covers the other). The overlaps relationship is symmetric and irreflexive.
![]() | |
This function automatically includes a bounding box comparison
that makes use of any spatial indexes that are available on the geometries. To avoid index use, use the function |
Performed by the GEOS module
![]() | |
Enhanced: 3.0.0 enabled support for |
NOTE: this is the "allowable" version that returns a boolean, not an integer.
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s2.1.1.2 // s2.1.13.3
This method implements the SQL/MM specification. SQL-MM 3: 5.1.32
ST_Overlaps
returns TRUE
in the following situations:
![]()
| ![]()
| ![]()
|
A Point on a LineString is contained, but since it has lower dimension it does not overlap or cross.
SELECT ST_Overlaps(a,b) AS overlaps, ST_Crosses(a,b) AS crosses, ST_Intersects(a, b) AS intersects, ST_Contains(b,a) AS b_contains_a FROM (SELECT ST_GeomFromText('POINT (100 100)') As a, ST_GeomFromText('LINESTRING (30 50, 40 160, 160 40, 180 160)') AS b) AS t overlaps | crosses | intersects | b_contains_a ---------+----------------------+-------------- f | f | t | t
A LineString that partly covers a Polygon intersects and crosses, but does not overlap since it has different dimension.
SELECT ST_Overlaps(a,b) AS overlaps, ST_Crosses(a,b) AS crosses, ST_Intersects(a, b) AS intersects, ST_Contains(a,b) AS contains FROM (SELECT ST_GeomFromText('POLYGON ((40 170, 90 30, 180 100, 40 170))') AS a, ST_GeomFromText('LINESTRING(10 10, 190 190)') AS b) AS t; overlap | crosses | intersects | contains ---------+---------+------------+-------------- f | t | t | f
Two Polygons that intersect but with neither contained by the other overlap, but do not cross because their intersection has the same dimension.
SELECT ST_Overlaps(a,b) AS overlaps, ST_Crosses(a,b) AS crosses, ST_Intersects(a, b) AS intersects, ST_Contains(b, a) AS b_contains_a, ST_Dimension(a) AS dim_a, ST_Dimension(b) AS dim_b, ST_Dimension(ST_Intersection(a,b)) AS dim_int FROM (SELECT ST_GeomFromText('POLYGON ((40 170, 90 30, 180 100, 40 170))') AS a, ST_GeomFromText('POLYGON ((110 180, 20 60, 130 90, 110 180))') AS b) As t; overlaps | crosses | intersects | b_contains_a | dim_a | dim_b | dim_int ----------+---------+------------+--------------+-------+-------+----------- t | f | t | f | 2 | 2 | 2
ST_Relate — Tests if two geometries have a topological relationship matching an Intersection Matrix pattern, or computes their Intersection Matrix
boolean ST_Relate(
geometry geomA, geometry geomB, text intersectionMatrixPattern)
;
text ST_Relate(
geometry geomA, geometry geomB)
;
text ST_Relate(
geometry geomA, geometry geomB, integer boundaryNodeRule)
;
These functions allow testing and evaluating the spatial (topological) relationship between two geometries, as defined by the Dimensionally Extended 9-Intersection Model (DE-9IM).
The DE-9IM is specified as a 9-element matrix indicating the dimension of the intersections between the Interior, Boundary and Exterior of two geometries. It is represented by a 9-character text string using the symbols 'F', '0', '1', '2' (e.g. 'FF1FF0102'
).
A specific kind of spatial relationship can be tested by matching the intersection matrix to an intersection matrix pattern. Patterns can include the additional symbols 'T' (meaning "intersection is non-empty") and '*' (meaning "any value"). Common spatial relationships are provided by the named functions ST_Contains, ST_ContainsProperly, ST_Covers, ST_CoveredBy, ST_Crosses, ST_Disjoint, ST_Equals, ST_Intersects, ST_Overlaps, ST_Touches, and ST_Within. Using an explicit pattern allows testing multiple conditions of intersects, crosses, etc in one step. It also allows testing spatial relationships which do not have a named spatial relationship function. For example, the relationship "Interior-Intersects" has the DE-9IM pattern T********
, which is not evaluated by any named predicate.
For more information refer to Section 5.1, “Determining Spatial Relationships”.
Variant 1: Tests if two geometries are spatially related according to the given intersectionMatrixPattern
.
![]() | |
Unlike most of the named |