PostGIS é uma extensão para o sistema de banco de dados objeto-relacional PostgreSQL que permite que objetos SIG (Sistema de Informação Geográfica) sejam armazenados em banco de dados. O PostGIS inclui suporte a índices espaciais baseado em GiST R-Tree, e funções para analise e processamento de objetos SIG.
Este é o manual para a versão 3.4.0dev
Este trabalho esta licenciado sobre a Creative Commons Attribution-Share Alike 3.0 License. Sinta-se livre para utilizar este material como quiser, mas pedimos que você atribua o crédito ao projeto PostGIS e sempre que possível cite o link http://www.postgis.org.
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.
O Comitê Diretor do Projeto PostGIS (PSC - Project Steering Comitee, em inglês) é responsável pela direção geral, ciclos de lançamento, documentação e os esforços para o projeto. Além disso, o comitê dá suporte ao usuário comum, aceita e aprova novas melhorias da comunidade e vota em questões diversas envolvendo o PostGIS, como por exemplo, uma permissão de commit direta, novos membros do comitê e mudanças significativas da API (Application Programming Interface).
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.
Melhorias em funções de distância (incluindo suporte a distância 3D e funções de relacionamento), Tiny WKB (TWKB) (em desenvolvimento) e suporte ao usuário geral.
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.
Desenvolvimento Raster, suporte do driver GDAL e importador.
Funções para entrada e saída de XML (KML, GML)/GeoJSon, suporte a 3D e correção de bugs.
Antigo membro do comitê. Desenvolvimento em geral, manutenção do website e buildbot, gerente da incubação na OSGeo.
Suporte CMake para o PostGIS, criou o carregador raster original em Python e funções de baixo nível da API raster
Ex PSC. Documentação e suporte a ferramentas de documentação, suporte e manutenção do builbot, suporte avançado de usuários em listas de discussão e melhorias em funções do PostGIS
Desenvolvedor original e co-fundador do PostGIS. Dave escreveu os objetos do servidor, chamadas de índices e muitas das funcionalidades analíticas presentes no servidor.
Desenvolvedor original do importador/exportador de shapefiles. Atual representante do Dono do Projeto.
Manutenção e desenvolvimento de funções do núcleo. Melhorias para o suporte a curvas e no importador GUI.
Architect of PostGIS raster implementation. Raster overall architecture, prototyping, programming support
Desenvolvimento raster (funções analíticas de álgebra de mapas)
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 são entidades corporativas que contribuiram com horas home, hospedagem ou suporte monetário direto ao projeto PostGIS
Crowd funding campaigns - Campanhas de financiamento de multidões são campanhas que executamos para obter os recursos que queremos para financiar um projeto por um grande número de pessoas. Cada campanha é especificamente focada em um recurso ou conjunto de recursos específicos. Cada patrocinador utiliza uma fração pequena do financiamento necessário e com o número suficiente de pessoas / organizações contribuindo, temos os fundos para pagar o trabalho que vai ajudar muitos. Se você tiver uma idéia de um recurso que você acha que muitos outros estariam dispostos a co-financiar, por favor, postar para o newsgroup PostGIS suas ideias, e juntos podemos fazer isso acontecer.
A versão 2.0.0 foi a primeira em que testamos esta estratégia. Utilizamos o PledgeBank e conseguimos realizar duas campanhas bem sucedidas.
postgistopology - 10 patrocinadores, cada um contribuiu com USD $250,00 para a construção da função toTopoGeometry e melhorias gerais no suporte a topologia da versão 2.0.0. Aconteceu!
postgis64windows - 20 patrocinadores, contribuiram com $100 USD cada, para pagar para a compilação do PostGIS no Windows 64bits. Aconteceu. Agora temos uma versão 64-bits do PostGIS 2.0.1 disponível na PostgreSQL Stack Builder.
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 último, mas não menos importante, o PostgreSQL DBMS, o gigante sobre qual o PostGIS se apóia. Muito da velocidade e flexibilidade do PostGIS não seria possível sem a extensibilidade, um grande analisador de consultas, índice GIST e uma variedade de funcionalidades SQL dadas pelos PostgreSQl.
Este capítulo detalha os passos necessários para instalar o PostGIS.
Para compilar, assumindo que você tem todas as dependências em seu caminho de busca (search path):
tar xvfz postgis-3.4.0dev.tar.gz cd postgis-3.4.0dev ./configure make make install
Assim que o PostGIS esteja instalado, ele precisa ser habilitado em cada banco de dados que você deseje utilizá-lo.
![]() | |
Muitos sistemas operacionas agora incluem pacotes pré-compilados para PostgreSQL / PostGIS. Em muitos casos, a compilação só é necessário se você quiser as versões ponta ou você é um mantenedor do pacote. 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 Se você é um usuário windows, você pode obter builds estáveis via Stackbuilder PostGIS Windows download site Também builds experimentais para windows são builds lançadadas geramente uma ou duas vezes por semana ou sempre que algo emocionante acontece. Você pode usá-los para experimentar os lançamentos em progresso 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 funcionalidade da GEOS, quando você instalar o PostgreSQL você pode ter que linkar explicitamente o PostgreSQL contra a biblioteca padrão C++: LDFLAGS=-lstdc++ ./configure [SUAS OPÇÕES AQUI] Isto é uma forma de contornar as exceções falso-positivas da interação do C++ com ferramentas de desenvolvimento mais antigas. Se você experimentar problemas estranho (backend fechando de forma inesperada ou coisas similares), tente este truque. Isto irá requerir que você compile o PostgreSQL do zero, claro. |
Os passos a seguir demonstram a configuração e compilação dos fontes do PostGIS. Eles são escritos para usuários de Linux e não funcionarão em Windows ou Mac.
Obtenha o fonte do PostGIS através da seção de downloads do 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
Isto irá criar um diretório chamado postgis-3.4.0dev
no diretório de trabalho atual.
Outra alternativa ,é o checkout da fonte do svn repository http://svn.osgeo.org/postgis/trunk/ .
git clone https://git.osgeo.org/gitea/postgis/postgis.git postgis cd postgis sh autogen.sh
Mude para o recém criado postgis-3.4.0dev
diretório para continuar a instalação.
./configure
PostGIS tem os seguintes requisitos para a construção e uso:
Necessário
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
). Alguns outros compiladores ANSI C podem ser utilizados para compilar o PostGIS, mas nós encontramos menos problemas ao compilar com gcc
.
GNU Make (gmake
ou make
). Para varios sistemas, GNU make
é a versão padrão do make. Verifique a versão invocando make -v
. Outras versões do make
pode não processar o PostGIS Makefile
corretamente.
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, versão 0.9 ou maior. JSON-C é atualmente utilizado para importar GeoJSON através da função ST_GeomFromGeoJson. JSON-C está disponível para download em 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.
Este parâmetro está atualmente sem funcionalidade, já que o pacote somente irá instalar na localização do PostgreSQL. Visite http://trac.osgeo.org/postgis/ticket/635 para acompanhar este bug.
Opcional
Certifique-se também de ativar os dispositivos que deseja usar como está descrito em Section 2.1, “Versão Reduzida”.
GTK (requer GTK+2.0, 2.8+) para compilar o shp2pgsql-gui para formar o carregador de arquivo. 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 Funções”. 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/.
Com a intenção de construir o Section 14.1, “Padronizador de endereço” você também irá precisar do PCRE http://www.pcre.org (que normalmente já está instalado nos sistemas nix). Regex::Assemble
o pacote perl CPAN só é necessário se quiser reconstruir os dados encoded em parseaddress-stcities.h
. Section 14.1, “Padronizador de endereço” vai automaticamente ser construída se ele detectar uma biblioteca PCRE, ou você passa em um válido --with-pcre-dir=/path/to/pcre
durante a configuração.
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
). Isto é necessário para o teste de regressão. http://cunit.sourceforge.net/
DocBook (xsltproc
)é necessário para a construção da documentação. Docbook esta disponível em http://www.docbook.org/ .
DBLatex (dblatex
) é necessário para a construção da documentação em formato PDF. DBLatex está disponível em http://dblatex.sourceforge.net/ .
ImageMagick (convert
) é necessário para gerar as imagens usadas na documentação. ImageMagick está disponível em http://www.imagemagick.org/ .
Como a maior parte das instalações Linux, o primeiro passo é gerar o Makefile que será utilizado para construção do código fonte. Isto é feito utilizando o script shell
./configure
Sem parâmetros adicionais, este comando tentará automaticamente localizar os componentes necessários e bibliotecas para construção do fonte do PostGIS em seu sistema. Embora esta é a forma comum de uso do ./configure, o script aceita diversos parâmetros para aqueles que tem as bibliotecas e programas necessários em localizações do sistema operacional que não são padrão.
A lista a seguir mostra apenas os parâmetros comumente utilizados. Para uma lista completa, utilize os parâmetros --help ou --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 é a localização onde as bibliotecas do PostGIS e scripts SQL serão instalados. Por padrão, esta localização é a mesma detectada pela instalação do PostgreSQL.
![]() | |
Este parâmetro está atualmente sem funcionalidade, já que o pacote somente irá instalar na localização do PostgreSQL. Visite http://trac.osgeo.org/postgis/ticket/635 para acompanhar este bug. |
O PostgreSQL oferece um utilitário chamado pg_config para habilitar extensões como o PostGIS a localizar a instalação do PostgreSQL. Use o parâmetro (--with-pgconfig=/path/to/pg_config para especificar manualmente uma instalação específica do PostgreSQL que será usada pelo PostGIS.
GDAL, uma biblioteca requerida, provê funcionalidades necessárias para o suporte a raster. Use o comando gdal-config para localizar o diretório de instalação da GDAL. Use este parâmetro (--with-gdalconfig=/path/to/gdal-config) para manualmente especificar uma instalação em particular da GDAL que o PostGIS irá utilizar.
GEOS é uma biblioteca requerida, dá um utilitário chamado geos-config para localizar o diretório de instalação da GEOS. Use este parâmetro (--with-geosconfig=/path/to/geos-config) para especificar manualmente uma instalação da GEOS que o PostGIS irá utilizar.
LibXML é a biblioteca exigida para fazer os processos GeomFormKML/GML. É encontrada normalmente se você tem o libxml instalado, mas se não tiver ou quiser uma versão específica usada, você precisará apontar o PosGIS para um confi file xml2-config
específico para ativar as instalações de software para localizar a lista de instalação do LibXML. Use esse parâmetro (
>--with-xml2config=/path/to/xml2-config) para especificar manualmente uma instalação do LibXML que o PostGIS irá construir contra.
A Proj4 é uma bilbioteca pra reprojeção de coordenadas, na qual o PostGIS depende. Use este parâmetro (--with-projdir=/path/to/projdir para especificar manualmente uma instalação do Proj4 que o PostGIS irá utilizar para compilação.
Diretório onde o iconv esta instalado.
JSON-C é uma biblioteca MIT-licensed JSON exigida pelo suporte PostGIS ST_GeomFromJSON . Use esse parâmetro (--with-jsondir=/path/to/jsondir) para especificar manualmente uma instalação do JSON-C que o PostGIS irá construir contra.
PCRE é uma biblioteca BSD-licensed Perl Compatible Regular Expression requerida pela extensão address_standardizer. Use esse parâmetro (--with-pcredir=/path/to/pcredir) para especificar manualmente uma instalação do PCRE que o PostGIS irá construir contra.
Compile a interface de usuário para importação de dados (requer GTK+2.0). Isto irá criar a ferramenta de interface gráfica shp2pgsql-gui para o utilitário shp2pgsql.
Instalar suporte a raster
Disable topology support. There is no corresponding library as all logic needed for topology is in postgis-3.4.0dev library.
Por padrão o PostGIS vai tentar detectar o suporte gettext e compilar com ele, porém se você tiver problemas incompatíveis que causem dano de carregamento, você pode o desabilitar com esse comando. Referir-se ao ticket http://trac.osgeo.org/postgis/ticket/748 para um exemplo de problema resolvido configurando com este. NOTA: que você não está perdendo muito desligando isso. É usado para ajuda internacional para o carregador GUI que ainda não está documentado e permanece experimental.
Por padrão PostGIS não tentará instalar com suporte sfcgal sem esta mudança. PATH
é um argumento opcional que permite especificar um PATH alternativo para sfcgal-config.
Disable updating postgis_revision.h to match current HEAD of the git repository.
![]() | |
Se conseguiu o PostGIS do SVN depósito , o primeiro passo é fazer funcionar o script ./autogen.sh Este script gera a configurar script que na volta é usada para personalizar a instalação do PostGIS. Se em vez de conseguir o PostGIS como tarball, rodando ./autogen.sh não é necessariamente como configurar já foi gerado. |
Uma vez que o Makefile tenha sido gerado, compilar o PostGIS é simples como rodar o comando
make
A última linha da saída deve ser "PostGIS was built successfully. Ready to install.
."
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.
fazer comentários
Apresentado ao PostGIS 2.0. Isto gera html cheat sheets adequadas para referências rápidas ou para handouts dos estudantes. Exige xsltproc para construir e vai gerar 4 arquivos no folder do documento topology_cheatsheet.html
, tiger_geocoder_cheatsheet.html
, raster_cheatsheet.html
, postgis_cheatsheet.html
Você pode baixar alguns pre-construídos disponíveis em html e pdf de PostGIS / PostgreSQL Study Guides
faça anotações
As extensões do PostGIS são contruídas e instaladas automaticamente se você estiver usando PostgreSQL 9.1 ou superior.
Se você está compilando do repositório, você precisa de compilar a função de descrições primeiro. Estas são compiladas se você possui o docbook instalado. Você pode também construir manualmente com o comando:
fazer comentários
Construir a documentação não é necessário se você está construindo de uma versão de lançamento no formato tar ball, já que estas são empacotadas pré-construídas com o tar ball.
Se você está construindo o PostGIS contra o PostgreSQL 9.1, as extensão devem ser automaticamente construídas como parte do processo de make. Você pode, contudo, se necessário, construir das pastas de extensões ou copiar os arquivos se você precisar dos mesmos em um 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
![]() | |
|
Os arquivos de extensões sempre serão os mesmos para a mesma versão do PostGIS, independente do Sistemas Operacional, então é fácil copiar os arquivos de extensão de um sistema operacional para outro, desde que você tenha os binários do PostGIS instalados em seus servidores.
Se você deseja instalar as extensões manualmente em um servidor diferente, do seu servidor de desenvolvimento, você precisará copiar os seguintes arquivos da pasta de extensões para a pastaPostgreSQL /share/extension
da sua instalação do PostgreSQL, bem como os binários necessários para o PostGIS, se você não os tem ainda no servidor de destino.
Existe arquivos de controle que denotam informações como a versão da extensão a ser instalada, caso não seja especificada. postgis.control, postgis_topology.control
.
Todos os arquivos na pasta /sql de cada extensão. Note que estes precisam ser copiados para a raiz da pasta share/extension do PostgreSQL extensions/postgis/sql/*.sql
, extensions/postgis_topology/sql/*.sql
Quando você finalizar este processo, você deverá ver postgis
, postgis_topology
como extensões disponíveis no PgAdmin -> Extensões.
Se você está utilizando psql, pode verificar quais estensões estão instaladas executando essa query:
SELECT name, default_version,installed_version FROM pg_available_extensions WHERE name LIKE 'postgis%' or name LIKE 'address%'; name | default_version | installed_version ------------------------------+-----------------+------------------- address_standardizer | 3.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)
Se você tem a extensão instalada no banco de dados de seu interesse, você a verá mencionada na coluna installed_version
. Se você não receber nenhum registro de volta, significa que você não tem extensões do PostGIS instaladas no servidor. PgAdmin III 1.14+ também irá lhe dar esta informação na seção extensions
do navegador de banco de dados e até permitirá o upgrade ou a desinstação utilizando o clique com o botão direito.
Se você tem extensões disponíveis, pode instalar a extensão postgis no seu database escolhido usando a interface da extensão pgAdmin ou rodando esses comandos sql:
CREATE EXTENSION postgis; CREATE EXTENSION postgis_sfcgal; CREATE EXTENSION fuzzystrmatch; --needed for postgis_tiger_geocoder --optional used by postgis_tiger_geocoder, or can be used standalone CREATE EXTENSION address_standardizer; CREATE EXTENSION address_standardizer_data_us; CREATE EXTENSION postgis_tiger_geocoder; CREATE EXTENSION postgis_topology;
No psql você pode ver quais versões foram instaladas e qual esquema eles estão instalando.
\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_tiger_geocoder Version | 3.4.0dev Schema | tiger Description | PostGIS tiger geocoder and reverse geocoder -[ RECORD 3 ]------------------------------------------------- - Name | postgis_topology Version | 3.4.0dev Schema | topology Description | PostGIS topology spatial types and functions
![]() | |
Extensões table |
Se você instalou 3.4.0dev sem usar nosso sistema de extensão maravilhoso, você pode mudar para uma extensão baseada em primeiro atualizando para a última micro versão rodando as scripts atualizadas:
postgis_upgrade_22_minor.sql
,raster_upgrade_22_minor.sql
,topology_upgrade_22_minor.sql
.
CREATE EXTENSION postgis FROM unpackaged; CREATE EXTENSION postgis_topology FROM unpackaged; CREATE EXTENSION postgis_tiger_geocoder FROM unpackaged;
Se desejar testar o PostGIS, rode
make check
O comando acima irá rodar através de várias verificações e testes de regressão usando a biblioteca gerada contra o database do PostreSQL atual.
![]() | |
Se você configurou o PostGIS usando o não padronizado PostgreSQL, GEOS, ou Proj4 localizações, talvez você precise adicionar a biblioteca de localizações deles à LD_LIBRARY_PATH variável de ambiente. |
![]() | |
Atualmente, o faz verificação confia nas variáveis de ambiente |
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
As extensões postgis_tiger_geocoder
and address_standardizer
, atualmente só suportam o modelo PostgreSQL installcheck. Para testá-los use abaixo. Nota: fazer a instalação não é necessária se você já instalou na raiz do folder code do PostGIS.
Para address_standardizer:
cd extensions/address_standardizer make install make installcheck
Saída deve parecer com:
============== 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. =====================
Para o geocoder tiger, certifique-se que você tem extensões portgis e fuzzystratch disponíveis no seu PostgreSQL. Os testes address_standardizer também irão desprezar se seus postgis construídos com address_standardizer suportar:
cd extensions/postgis_tiger_geocoder make install make installcheck
saída deve parecer com:
============== 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 o PostGIS, digite
make install
Isso irá copiar a instalação dos arquivos do PostGIS para suas subdireções específicas pelo --prefix parâmetro de configuração. Particularmente:
Os binários do carregador e do dumper estão instalados no [prefix]/bin
.
Os arquivos SQL, como postgis.sql
, estão instalados em [prefix]/share/contrib
.
As bibliotecas do PostGIS estão instaladas em [prefix]/lib
.
Se anteriormente você rodou o comando make comments para gerar o arquivo postgis_comments.sql
, raster_comments.sql
, instale o arquivo sql para executar
make comments-install
![]() | |
|
A extensão address_standardizer
era usada para ser um pacote separado que requeria download separado. Do PostGIS 2.2 em diante é compactado. Para mais informações sobre o address_standardize, o que ele faz e como fazer sua configuração, referir-se Section 14.1, “Padronizador de endereço”.
O padronizador pode ser usado em conjunção com a extensão tiger geocoder PostGIS compactada como uma reposição para a Normalize_Address discutida. Para usar como reposição Section 2.4.2, “Usando Padronizador de Endereço com Tiger Geocoder”. Você também pode utilizar como um building block para seu próprio geocoder ou como padronizar seu endereço para uma comparação de endereços mais fácil.
O padronizador de endereço confia no PCRE que já está instalado na maioria dos sistemas Nix, mas você pode baixar a última versão em: http://www.pcre.org. Se durante Section 2.2.3, “Configuração”, o PCRE é encontrado, então a extensão do padronizador de endereço será automaticamente construída. Se você tem um pcre personalizado que queira usar, passe a configurar --with-pcredir=/path/to/pcre
onde /path/to/pcre
é a pasta root para o seu pcre incluso e lista lib.
Para usuários do Windows, o pacote PostGIS 2.1+ já está compactado com o address_standardizer, então não precisa compilar podendo seguir direto para o passo CREATE EXTENSION
.
Uma vez que instalou, você pode conectar no seu banco de dados e rodar o SQL:
CRIAR EXTENSÃO address_standardizer;
O teste seguinte não requere tables rules, gaz ou lex.
SELECT num, street, city, state, zip FROM parse_address('1 Devonshire Place PH301, Boston, MA 02109');
Saída deve ser
num | street | city | state | zip -----+------------------------+--------+-------+------- 1 | Devonshire Place PH301 | Boston | MA | 02109
Perl Regex:Assemble não é mais necessário para a compilação extensão address_standardizer desde que os arquivos que ele gera são parte da fonte três. Entretanto se precisar editar o usps-st-city-orig.txt
ou usps-st-city-orig.txt usps-st-city-adds.tx
, você precisa reconstruir parseaddress-stcities.h
que exige Regex:Assemble.
cpan Regexp::Montar
ou se estiver no Ubuntu / Debian talvez você precise fazer
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.
Primeiramente obtenha binários para PostGIS 2.1+ ou compile e instale como de costume. Isso deverá instalar os arquivos de extensão necessários bem como para o geocoder.
Conecte ao seu banco de dados vis psql ou pgAdmin ou qualquer outra ferramenta e execute os comandos SQL seguintes. Note que se você está instalando em um banco de dados que já possui o postgis, você não precisa fazer o primeiro passo. Se você já tem a extensão fuzzystrmatch
instalada, não é preciso fazer o segundo passo também.
CREATE EXTENSION postgis; CREATE EXTENSION fuzzystrmatch; CREATE EXTENSION postgis_tiger_geocoder; --this one is optional if you want to use the rules based standardizer (pagc_normalize_address) CREATE EXTENSION address_standardizer;
Se você já tem a extensão postgis_tiger_geocoder instalada e só quer atualizar para a última versão, execute:
ALTER EXTENSION postgis UPDATE; ALTER EXTENSION postgis_tiger_geocoder UPDATE;
Se você fez entradas personalizadas ou alterações nos tiger.loader_platform
e tiger.loader_variables
, talvez você precisará atualizar estes.
Para confirmar que sua instalação está funcionando corretamente, execute esse sql no seu banco de dados:
SELECT na.address, na.streetname,na.streettypeabbrev, na.zip FROM normalize_address('1 Devonshire Place, Boston, MA 02109') AS na;
Qual deve sair
address | streetname | streettypeabbrev | zip ---------+------------+------------------+------- 1 | Devonshire | Pl | 02109
Criar um novo registro na table tiger.loader_platform
com os paths dos seus executáveis e servidor.
Então, por exemplo, para criar um perfil chamado debbie que segue a convenção sh
, você deveria fazer:
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';
E então, edite os paths na coluna declare_sect para aqueles que servem ao pg, unzip, shp2pgsql, psql, etc da Debbie.
Se você não editou essa table loader_platform
, ela só irá conter casos comuns de localizações de itens e você terá que editar a script gerada depois que ela for gerada.
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.
Criar uma pasta chamada gisdata
na raiz do servidor ou do seu computador local, se você tem uma rede de conexão rápida com o servidor. Essa pasta está onde os arquivos tiger serão baixados e processados. Se não estiver satisfeito em ter a pasta na raiz do servidor ou, simplesmente, quiser alterar para uma outra pasta para representação, edite o campo staging_fold
na table tiger.loader_variables
.
Criar uma pasta chamada temp na pasta gisdata
ou onde designar a staging_fold
. Esta será a pasta onde o carregador extrai os dados tiger baixados.
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
Executar as scripts commandlines geradas
cd /gisdata sh ma_load.sh
Depois que terminar de carregar todos os dados ou estiver parado em um ponto, é bom analisar todas as tiger tables para atualizar as estatísticas (incluindo as estatísticas herdadas)
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;
Uma das maiores queixas das pessoas é a função normalizador de endereços Normalize_Address que normaliza um endereço para preparação antes da geocoding. O normalizador está longe da perfeição e tentar corrigir suas imperfeições demanda um grande número de recursos. Como tal nós integramos com outro projeto que tem um mecanismo de padronizador de endereços muito melhor. Para usar esse novo address_standardizer, você compila a extensão como está descrito em Section 2.3, “Instalando e usando o padronizador de endereço” e instala como uma extensão no seu banco de dados.
Uma vez que você instala essa extensão no mesmo banco de dados que instalou postgis_tiger_geocoder
, então o Pagc_Normalize_Address pode ser usado ao invés do Normalize_Address. Essa extensão é avessa ao tiger, logo pode ser usada com outras fontes de dados como: endereços internacionais. A extensão tiger geocoder vem compactada com suas próprias versões personalizadas de mesa de regras ( tiger.pagc_rules
) , gaz table (tiger.pagc_gaz
), e lex table (tiger.pagc_lex
). Essas você pode adicionar e atualizar para melhorar sua experiência com o padronizador de acordo com suas necessidades.
O carregador processa dados de downloads do site de censo para os respectivos arquivos de nação, solicitações de estados, extrai os arquivos e carrega cada estado para seu grupo separado de state tables. Cada state table herda das tables definidas no esquema tiger
sendo suficiente apenas para pesquisar aquelas tables para acessar todos os dados e derrubar um conjunto de state tables a qualquer momento usando o Drop_State_Tables_Generate_Script se quiser recarregar um estado ou não precisa de um estado mais.
Para ser capaz de carregar dados, você vai precisar das seguintes ferramentas:
Uma ferramenta para descompactar os arquivos compactados do site de censo.
Para Unix como sistemas: executável unzip
que é instalado, normalmente, na maioria dos Unix como plataformas.
Para Windows, 7-zip é uma ferramenta comprimir/descomprimir grátis que você pode baixar no http://www.7-zip.org/
shp2pgsql
commandline que é instalada por padrão quando você instala o PostGIS.
wget
que é uma ferramente grabber da internet, instalada na maioria dos sistemas Unix/Linux.
Se você está no Windows, você pode obter binários pre compilados do 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.
Para carregar dados do estado referir-se a Loader_Generate_Script para gerar uma script de dados de carregamento para sua plataforma para os estados que deseja. Note que você pode instalar estes gradativamente. Você não precisa carregar todos os estados de uma só vez. Pode carregá-los à medida que for precisando deles.
Depois que os estados desejados forem carregados, certifique-se de executar o:
SELECT install_missing_indexes();
como está descrito em Install_Missing_Indexes.
Para testar que está tudo funcionando normalmente, tente executar um geocode em um endereço no seu estado, usando Geocode
First upgrade your postgis_tiger_geocoder extension as follows:
ALTER EXTENSION postgis_tiger_geocoder UPDATE;
Em seguida, derrube todas as nation tables e carregue as novas. Gere uma drop script com essa declaração SQL, como está detalhado em Drop_Nation_Tables_Generate_Script
SELECT drop_nation_tables_generate_script();
Execute as declarações geradas drop SQL.
Gere uma script que carrega uma nação com SELECIONAR como está detalhado em Loader_Generate_Nation_Script
Para windows
SELECT loader_generate_nation_script('windows');
Para unix/linux
SELECT loader_generate_nation_script('sh');
Para instruções de como executar a script gerada use: 4. Isso só precisa ser feito uma 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. |
Existem várias coisas para averiguar quando a instalação ou atualização não saem como o esperado.
Certifique-se que instalou o PostgreSQL 12 ou mais novo e que você está compilando contra a mesma versão da fonte PostgreSQL assim como a versão do PostgreSQL que está sendo executada. Confusões podem acontecer quando sua distribuição (Linux) já instalou o PostgreSQL, ou você instalou o PostgreSQL antes e se esqueceu disso. PostGIS só irá funcionar com o PostgreSQL 12 ou mais novo, e mensagens estranhas e inesperadas de erro aparecerão se você usar uma versão mais antiga. Para verificar a versão PostgreSQL que está sendo executada, conecte ao banco de dados usando psql e faça essa consulta:
SELECT version();
Se você está usando uma distribuição baseada em RPM, você pode confirmar a existência de pacotes pre instalados utilizando o comando rpm como segue: rpm -qa | grep postgresql
Se sua atualização falhar, certifique-se que você está restaurando em um banco de dados que já possui o PostGIS instalado.
SELECT postgis_full_version();
Também certifique que a configuração detectou a localização e versão corretas do PostgreSQL, da biblioteca do Proj4 e da biblioteca do GEOS.
A saída da configuração foi usada para gerar o arquivo postgis_config.h
. Verifique que as variáveis POSTGIS_PGSQL_VERSION
, POSTGIS_PROJ_VERSION
e POSTGIS_GEOS_VERSION
foram configuradas corretamente.
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, “Grandes Variáveis Unificadas Personalizadas do PostGIS (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.
Default: 8
Sets the maximum number of background processes that the system can support. This parameter can only be set at server start.
work_mem - sets the size of memory used for sort operations and complex queries
Default: 1-4MB
Adjust up for large dbs, complex queries, lots of RAM
Adjust down for many concurrent users or low RAM.
If you have lots of RAM and few developers:
SET work_mem TO '256MB';
maintenance_work_mem - the memory size used for VACUUM, CREATE INDEX, etc.
Default: 16-64MB
Generally too low - ties up I/O, locks objects while swapping memory
Recommend 32MB to 1GB on production servers w/lots of RAM, but depends on the # of concurrent users. If you have lots of RAM and few developers:
SET maintenance_work_mem TO '1GB';
max_parallel_workers_per_gather
This setting is only available for PostgreSQL 9.6+ and will only affect PostGIS 2.3+, since only PostGIS 2.3+ supports parallel queries. If set to higher than 0, then some queries such as those involving relation functions like ST_Intersects
can use multiple processes and can run more than twice as fast when doing so. If you have a lot of processors to spare, you should change the value of this to as many processors as you have. Also make sure to bump up max_worker_processes
to at least as high as this number.
Default: 0
Sets the maximum number of workers that can be started by a single Gather
node. Parallel workers are taken from the pool of processes established by max_worker_processes
. Note that the requested number of workers may not actually be available at run time. If this occurs, the plan will run with fewer workers than expected, which may be inefficient. Setting this value to 0, which is the default, disables parallel query execution.
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, “Grandes Variáveis Unificadas Personalizadas do PostGIS (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, “The SPATIAL_REF_SYS Table and 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(0 0,1 1,1 2)
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.
CIRCULARSTRING(0 0, 4 0, 4 4, 0 4, 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(((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)))
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( ((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( ((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.
![]() | |
Todos as comparações de pontos flutuantes dentro da implementação SQL-MM são representadas com uma tolerância específica, atualmente 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, 4 0, 4 4, 0 4, 0 0)
Uma curva composta é uma curva única e contínua que tem segmentos curvados (circulares) e lineares. Isto significa que, além de ter componentes bem formados, o ponto final de cada componente (exceto o último) deve ser coincidente com o ponto inicial do componente seguinte.
COMPOUNDCURVE(CIRCULARSTRING(0 0, 1 1, 1 0),(1 0, 0 1))
Um POLÍGONOCURVO é como um polígono, com um anel externo e zero ou mais anéis internos. A diferença é que um anel pode obter a forma de uma string circular, linear ou composta.
Assim como o PostGIS 1.4, o PostGIS suporta curvas compostas em um 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
Exemplo de curva composta em um polígono curvo: 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 MULTICURVA é uma coleção de curvas, que podem incluir strings lineares, circulares e compostas.
MULTICURVE( (0 0, 5 5), CIRCULARSTRING(4 0, 4 4, 8 4) )
A especificação OpenGIS define dois caminhos padrão de expressar objetos espaciais: o Well-Known Text (WKT) e o Well-Known Binary (WKB). Ambos incluem informação sobre o tipo do objeto e as coordenadas que os formam.
A representação bem conhecida de texto do sistema de referência espacial. Um exemplo de uma representação WKT SRS é:
POINT(0 0)
POINT(0 0)
POINT(0 0)
POINT EMPTY
LINESTRING(0 0,1 1,1 2)
LINESTRING
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((0 0),(1 2))
MULTIPOINT
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
Input and output of WKT is provided by the functions ST_AsText and ST_GeomFromText:
bytea WKB = ST_AsBinary(geometry); text WKT = ST_AsText(geometry); geometry = ST_GeomFromWKB(bytea WKB, SRID); geometry = ST_GeometryFromText(text WKT, SRID);
Por exemplo, uma declaração inserida válida para criar e inserir um objeto espacial OGC seria:
INSERT INTO geotable ( the_geom, the_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:
POINT(0 0)
WKB: 0101000000000000000000F03F000000000000F03
LINESTRING(0 0,1 1,1 2)
WKB: 0102000000020000000000000000000040000000000000004000000000000022400000000000002240
Input and output of WKB is provided by the functions ST_AsBinary and ST_GeomFromWKB:
bytea WKB = ST_AsBinary(geometry); text WKT = ST_AsText(geometry); geometry = ST_GeomFromWKB(bytea WKB, SRID); geometry = ST_GeometryFromText(text WKT, SRID);
Por exemplo, uma declaração inserida válida para criar e inserir um objeto espacial OGC seria:
INSERT INTO geotable ( the_geom, the_name ) VALUES ( ST_GeomFromText('POINT(-126.4 45.32)', 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 Tipo de geometria 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, Referência do 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". |
A especificação OpenGIS também requer que o formato do armazenamento interno dos objetos espacias incluam um identificador de sistema de referência espacial (SRID). O SRID é fundamental na criação de objetos espaciais para a inserção no banco de dados.
To make querying geometry efficient PostGIS defines various kinds of spatial indexes, and spatial operators to use them. See Section 4.9, “Construindo índidces” 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 (1 row)
PostGIS EWKT output has a few differences to OGC WKT:
For 3DZ geometries the Z qualifier is omitted:
POINT(0 0)
POINT(0 0)
For 3DM geometries the M qualifier is included:
POINT(0 0)
POINT(0 0)
For 4D geometries the ZM qualifier is omitted:
POINT(0 0)
POINT(0 0)
EWKT avoids over-specifying dimensionality and the inconsistencies that can occur with the OGC/ISO format, such as:
POINT(0 0)
POINT(0 0)
POINT(0 0)
![]() | |
Os formatos estendidos do PostGIS estão atualmente superset de OGC (cada WKB/WKT válido é um EWKB/EWKT válido), mas isto pode airar no futuro, especificamente se OGC sai com um novo formato conflitando com nossas extensões. Assim, você NÃO DEVE confiar neste aspecto! |
A seguir, exemplos das representações de textos (WKT) dos objetos espaciais das características:
POINT(0 0 0) -- XYZ
SRID=32632;POINT(0 0) -- XY with SRID
POINTM(0 0 0) -- XYM
POINT(0 0 0 0) -- XYZM
SRID=4326;MULTIPOINTM(0 0 0,1 2 1) -- XYM with SRID
MULTILINESTRING((0 0 0,1 1 0,1 2 1),(2 3 1,3 2 1,5 4 1))
POLYGON((0 0 0,4 0 0,4 4 0,0 4 0,0 0 0),(1 1 0,2 1 0,2 2 0,1 2 0,1 1 0))
MULTIPOLYGON(((0 0 0,4 0 0,4 4 0,0 4 0,0 0 0),(1 1 0,2 1 0,2 2 0,1 2 0,1 1 0)),((-1 -1 0,-1 -2 0,-2 -2 0,-2 -1 0,-1 -1 0)))
GEOMETRYCOLLECTIONM( POINTM(2 3 9), LINESTRINGM(2 3 4, 3 4 5) )
MULTICURVE( (0 0, 5 5), CIRCULARSTRING(4 0, 4 4, 8 4) )
POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )
TRIANGLE ((0 0, 0 9, 9 0, 0 0))
TIN( ((0 0 0, 0 0 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 0 0 0)) )
Entrada/Saída destes formatos estão disponíveis usando as seguintes interfaces:
bytea EWKB = ST_AsEWKB(geometry); text EWKT = ST_AsEWKT(geometry); geometry = ST_GeomFromEWKB(bytea EWKB); geometry = ST_GeomFromEWKT(text EWKT);
Por exemplo, uma declaração inserida válida para criar e inserir um objeto espacial seria:
INSERT INTO geotable ( the_geom, the_name ) VALUES ( ST_GeomFromEWKT('SRID=312;POINTM(-126.4 45.32 15)'), 'A Place' )
O tipo de geografia fornece suporte natural para características representadas nas coordenadas"geográficas" (às vezes chamadas de coordenadas "geodéticas", ou "lat/lon", ou 'lon/lat"). As coordenadas geográficas são coordenadas esféricas expressadas em unidades angulares (graus).
A base para a geometria PostGIS é um plano. O menor caminho entre dois pontos no plano é uma linha. Isso quer dizer que cálculos em geometrias (áreas, distâncias, cumprimentos, interseções etc) podem ser feitos usando matemática cartesiana e vetores de linhas.
A base para a geometria PostGIS é um plano. O menor caminho entre dois pontos no plano é uma linha. Isso quer dizer que cálculos em geometrias (áreas, distâncias, cumprimentos, interseções etc) podem ser feitos usando matemática cartesiana e vetores de linhas.
Devido à matemática fundamental ser muito mais complicada, existem poucas funções definidas pela geografia em vez da geometria. Ao longo do tempo, à media que os algorítimos forem adicionados, as capacidades da geografia serão expandidas.
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, “The SPATIAL_REF_SYS Table and 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:
Os valores permitidos para o modificador de tipo são: PONTO, LINESTRING, POLÍGONO, MULTIPONTO, MULTILINESTRING, MULTIPOLÍGONO. O modificador também suporta restrições de dimensionalidade através de sufixos: Z, M, e ZM. Então, por exemplo, um modificador de 'LINESTRINGM' só permitiria line strings com três dimensões, e trataria a terceira dimensão como uma medida. Da mesma forma, 'PONTOZM' esperaria dados de quatro dimensões.
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:
-- See the contents of the metadata view SELECT * FROM geography_columns;
Criar um índice funciona da mesma forma que uma GEOMETRIA. O PostGIS irá notar que o tipo de coluna é GEOGRAFIA e criará um índice baseado em esfera apropriado em vez do de costume usado para GEOMETRIA.
-- 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.
=# SELECT 'SRID=4;POINT(0 0)'::geometry; geometry ---------------------------------------------------- 01010000200400000000000000000000000000000000000000 (1 row)
=# SELECT 'SRID=4;POINT(0 0)'::geometry; geometry ---------------------------------------------------- 01010000200400000000000000000000000000000000000000 (1 row)
-- 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.
As funções de consulta e medida usam unidades em metros. Então, os parâmetros de distância deveriam ser esperados em metros (ou metros quadrados 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).
O tipo GEOGRAFIA calcula a verdadeira menor distância sobre a esfera entre Reykjavik e o grande caminho de voo circular entre Seattle e Londres.
-- 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
Great Circle mapper A GEOMETRIA calcula a distância cartesiana insignificante entre Reykjavik e o caminho direto de Seattle para Londres marcado em um mapa. As unidades nominais do resultado podem ser chamadas de "graus", mas o resultado não corresponde a nenhuma diferença angular verdadeira entre os pontos, então, chamá-las de "graus" é incoerente.
-- 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.
O tipo que você escolheu deveria ser condicionado da área de trabalho esperada da aplicação que você está construindo. Seus dados irão abranger o globo ou uma grande área continental, ou é local para um estado, condado ou município?
Se seus dados estiverem contidos em uma pequena área, talvez perceba que escolher uma projeção apropriada e usar GEOMETRIA é a melhor solução, em termos de desempenho e funcionalidades disponíveis.
Se seus dados são globais ou cobrem uma região continental, você pode perceber que GEOGRAFIA permite que você construa uma sistema sem ter que se preocupar com detalhes de projeção. Você armazena seus dados em longitude/latitude, e usa as funções que foram definidas em GEOGRAFIA.
Se você não entende de projeções, não quer aprender sobre elas e está preparado para aceitar as limitações em funcionalidade disponíveis em GEOGRAFIA, então pode ser mais fácil se usar GEOGRAFIA em vez de GEOMETRIA. Simplesmente carregue seus dados como longitude/latitude e comece a partir daqui.
Recorra a Section 15.11, “PostGIS Function Support Matrix” para uma comparação entre o que é suportado pela Geografia vs. Geometria. Para uma breve lista e descrição das funções da Geografia, recorra a Section 15.4, “PostGIS Geography Support Functions”
4.3.4.1. | Você calcula na esfera ou esferoide? |
Por padrão, todos os cálculos de distância e área são feitos no esferoide. Você irá encontrar que os resultados dos cálculos nas áreas locais combinam com os resultados locais planares em boas projeções locais. Em grandes áreas, os cálculos esferoidais são mais precisos que os feitos em um plano projetado. Todas as funções de geografia têm a opção de usar um cálculo esférico, configurando um parâmetro booleano final para 'FALSO'. isto irá acelerar os cálculos, particularmente para casos onde as geometrias são bem simples. | |
4.3.4.2. | E a linha de data e os pólos? |
Nenhum cálculo possui a compreensão de linha de data ou polos, as coordenadas são esféricas (longitude/latitude), então uma forma que cruza a linha de data não é, de um ponto de cálculo de view, diferente de nenhuma outra forma. | |
4.3.4.3. | Qual é o maior arco que pode ser processado? |
Nós usamos grandes arcos círculos como a "linha de interpolação" entre dois pontos. Isso significa que quaisquer dois pontos estão de fato juntaram-se de duas maneiras, depende qual direção você vá no grande círculo. Todo o nosso código assume que os pontos estão juntos pelo *menor* dos dois caminhos ao longo do grande círculo. Como consequência, formas que têm arcos de mais de 180 graus não serão modeladas corretamente. | |
4.3.4.4. | Por que é tão lento para calcular a área da Europa / Rússia / insira uma grande região geográfica aqui ? |
Porque o polígono é muito grande! Grandes áreas são ruins por duas razões: seus limites são grandes, logo o índice tende a puxar o traço, não importa qual consulta você execute; o número de vértices é enorme, e testes (distância, contenção) têm que atravessar a lista de vértices pelo meno uma vez e algumas vezes, N vezes (com N sendo o número de vértices em outra característica candidata). 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.
Um POINT
é herdado simple como um objeto geométrico 0-dimensional.
MULTIPOINT
s são simple se nenhuma de duas coordenadas (POINT
s) forem iguais (tenham o valor de coordenadas idêntico).
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(the_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.
A tabela SPATIAL_REF_SYS
de definição está como segue:
CREATE TABLE spatial_ref_sys ( srid INTEGER NOT NULL PRIMARY KEY, auth_name VARCHAR(256), auth_srid INTEGER, srtext VARCHAR(2048), proj4text VARCHAR(2048) )
As opções da commandline são:
Um valor inteiro que só identifica o Sistema de Referenciação Espacial (SRS) dentro do banco de dados.
O nome do corpo padrão ou corpos padrẽos que estão sendo citados por este sistema de referência. Por exemplo, "EPSG" seria um AUTH_NAME
válido.
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.
A representação bem conhecida de texto do sistema de referência espacial. Um exemplo de uma representação WKT SRS é:
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.
O PostGIS usa a biblioteca Proj4 para fornecer capacidades de transformação de coordenada. A coluna PROJ4TEXT
contém a string de definição da coordenada Proj4 para um SRID específico. Por exemplo:
+proj=utm +zone=10 +ellps=clrk66 +datum=NAD27 +units=m
Para maiores informações a respeito, veja o website do Proj4 http://trac.osgeo.org/proj/. O arquivo spatial_ref_sys.sql
contém as definições SRTEXT
e PROJ4TEXT
para todas as projeções EPSG.
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.
Uma ótima fonte para encontrar sistemas de referência espacial não definidos na configuração central é http://spatialreference.org/
Alguns dos sistemas de referência espacial mais comumente usados são: 4326 - WGS 84 Long Lat, 4269 - NAD 83 Long Lat, 3395 - WGS 84 World Mercator, 2163 - US National Atlas Equal Area, Spatial reference systems para cadaNAD 83, WGS 84 UTM zona - zonas UTM são as mais ideais para medição, mas só cobrem 6-graus regiões.
Vários estados dos EUA no sistema de referência espacial (em metros ou pés) - normalmente um ou 2 existem por estado. A maioria dos que estão em metros estão no centro, mas muitos dos que estão em pés ou foram criados por ESRI precisarão de 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 global_points ( id SERIAL PRIMARY KEY, name VARCHAR(64), location GEOGRAPHY(POINT,4326) );
The geometry
type supports two optional type modifiers:
Os valores permitidos para o modificador de tipo são: PONTO, LINESTRING, POLÍGONO, MULTIPONTO, MULTILINESTRING, MULTIPOLÍGONO. O modificador também suporta restrições de dimensionalidade através de sufixos: Z, M, e ZM. Então, por exemplo, um modificador de 'LINESTRINGM' só permitiria line strings com três dimensões, e trataria a terceira dimensão como uma medida. Da mesma forma, 'PONTOZM' esperaria dados de quatro dimensões.
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:
ALTER TABLE roads ADD COLUMN geom2 geometry(LINESTRINGZ,4326);
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);
O OpenGIS "Especificação de Características Simples para SQL" define tipos padrão de objetos GIS, as funções requeridas para manipulá-los e um conjunto de tabelas de metadados. Querendo certificar-se de que os metadados permaneçam consistentes, operações como criar e remover uma coluna espacial são carregadas para fora dos procedimentos especiais definido pelo OpenGIS.
\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) |
As opções da commandline são:
O nome completo da tabela de característica que contém a coluna geométrica. Note que os termos "catálogo" e "esquema" são Oracle. Não existe um análogo do "catálogo" PostgreSQL, logo a coluna é deixada em branco -- para "esquema" o nome do esquema PostgreSQL é usado (public
é o padrão).
O nome da coluna geométrica na tabela característica.
A dimensão espacial (2, 3 ou 4 dimensões) da coluna.
A ID do sistema de referência espacial usada pela coordenada nesta coluna. É uma referência de chave estrangeira para SPATIAL_REF_SYS
.
O tipo do objeto espacial. Para restringir a coluna espacial a um tipo só, use um dos: PONTO, LINESTRING, POLÍGONO, MULTIPONTO, MULTILINESTRING, MULTIPOLÍGONO, GEOMETRYCOLLECTION ou versões correspondentes XYM PONTOM, LINESTRINGM, POLÍGONOM, MULTIPOINTM, MULTILINESTRINGM, MULTIPOLÍGONOM, GEOMETRYCOLLECTIONM. Para coleções heterogêneas (do tipo mistas), você pode usar "GEOMETRIA" como o 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);
Se executarmos em psql
\d pois_ny;
Observamos que elas são definidas de maneira diferente -- uma é typmod, outra é restrição
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)
Nas geometry_columns, elas registram corretamente
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
Entretanto -- se se quiséssemos criar uma view como essa
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';
A coluna baseada em typmod registra corretamente, mas a baseada em restrições não.
f_table_name | f_geometry_column | srid | type ------------------+-------------------+------+---------- vw_pois_ny_parks | geom | 4326 | POINT vw_pois_ny_parks | geom_2160 | 0 | GEOMETRY
Isto pode modificar as versões futuras do PostGIS, mas por enquanto para forçar a restrição baseada em coluna view registrar corretamente, precisamos fazer isto:
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
Uma vez que tenha criado uma tabela espacial, você está pronto para atualizar os dados GIS no banco de dados. No momento, existe duas formas de colocar os dados no banco de dados PostGIS/PostgreSQL: usando as declarações SQL ou usando o shape file loader/dumper.
Se você puder converter seus dados para uma representação de texto, então usar SQL formatado pode ser mais fácil de colocar seus dados no PostGIS. Como com o Oracle e outros banco de dados SQL, dados só podem ser carregados em volume canalizando um grande arquivo de texto cheio de declarações SQL "INSERT" dentro do monitor SQL.
Um arquivo de atualização de dados (roads.sql
por exemplo) deve se parecer com:
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;
O arquivo de dados pode ser canalizado para PostgreSQL facilmente usando o "psql" SQL monitor terminal:
psql -d [database] -f roads.sql
O carregador de dados shp2pgsql
converte ESRI Shape files em SQL adequado para inserção dentro de um banco de dados PostGIS/PostgreSQL, seja em formato de geometria ou geografia. O carregador possui vários modos de operação distinguidos pelas linhas de bandeiras de comando:
Juntamente com o comando carregador shp2pgsql, existe uma interface shp2pgsql-gui
gráfica com a maioria das opções como o carregador, mas pode ser mais fácil de usar para um carregamento único non-scripted ou se você é novo no PostGIS. Pode ser configurado como um plugin do PgAdminIII.
Cria uma tabela nova e popula do shapefile. Este é o modo padrão.
Anexa dados do shapefile dentro do banco de dados da tabela. Note que para usar esta opção para carregar vários arquivos, eles devem ter os mesmos atributos e tipos de dados.
Derruba a tabela do banco de dados, criando uma nova tabela com os dados do shapefile.
Produz somente a criação da tabela do código SQL, sem adicionar nenhum dado de fato. Isto pode ser usado se você precisar separar completamente a tabela de criação e os passos de carregamento de dados.
Exibir tela de ajuda.
Use o formato PostgreSQL "dump" para os dados de saída. Pode ser combinado com -a, -c e -d. É muito mais rápido para carregar que o formato padrão "insert" SQL. Use isto para dados muito grandes.
Cria e popula as tabelas de geometria com o SRID específico. Especifica, opcionalmente, que o shapefile de entrada usa o FROM_SRID dado, caso em que as geometrias serão reprojetadas para o SRID alvo. FROM_SRID não pode ser especificado com -D.
Mantém identificadores (coluna, esquema e atributos). Note que os atributos no shapefile estão todos em CAIXAALTA.
Coage todos os inteiros para 32-bit integers padrão, não cria 64-bit bigints, mesmo se a assinatura DBF parecer justificar ele.
Cria um índice GiST na coluna geométrica.
-m a_file_name
Especifica um arquivo contendo um conjunto de mapas de nomes (longos) de colunas para nomes de colunas DBF com 10 caracteres. O conteúdo deste arquivo é uma ou mais linhas de dois nomes separados por um espaço branco e seguindo ou liderando espaço. Por exemplo:
COLUMNNAME DBFFIELD1 AVERYLONGCOLUMNNAME DBFFIELD2
Gera geometrias simples em vez de MULTI geometrias. Só irá ter sucesso se todas as geometrias forem de fato únicas (ex.: um MULTIPOLÍGONO com uma única shell, ou um MULTIPONTO com um único vértice).
Força a geometria de saída a ter dimensionalidade especificada. Use as strings seguintes para indicar a dimensionalidade: 2D, 3DZ, 3DM, 4D.
Se a entrada tiver poucas dimensões especificadas, a saída terá essas dimensões cheias com zeros. Se a entrada tiver mais dimensões especificadas, as que indesejadas serão tiradas.
Gera o formato WKT em vez do WKB. Note que isto pode introduzir impulsos de coordenadas para perda de precisão.
Execute cada declaração por si mesma, sem usar uma transação. Isto permite carregar a maioria dos dados bons quando existem geometrias ruins que geram erros. Note que não pode ser usado com a bandeira -D como o formato "dump" sempre usa a transação.
Especifica codificação dos dados de entrada (arquivo dbf). Quando usado, todos os atributos do dbf são convertidos da codificação especificada para UTF8. A saída SQL resultante conterá um comando SET CLIENT_ENCODING to UTF8
, então o backend será capaz de reconverter do UTF8 para qualquer codificação que o banco de dados estiver configurado para usar internamente.
Políticas para lidar com geometrias NULAS (insert*,skip,abort)
-n Só importa arquivo DBF. Se seus dados não possuem shapefile correspondente, ele irá trocar automaticamente para este modo e carregar só o dbf. Então, só é necessário configurar esta bandeira se você tiver um shapefile completo, e se quiser os dados atributos e nenhuma geometria.
Use geografia em vez de geometria (requer dados long/lat) em WGS84 long lat (SRID=4326)
Especifica o espaço para a nova tabela. Os índices continuarão usando espaço padrão a menos que o parâmetro -X também seja usado. A documentação PostgreSQL tem uma boa descrição quando usa espaços personalizados.
Especifica o espaço para os novos índices da tabela. Isto se aplica ao primeiro índice chave, e o índice GIST espacial, se -I também for usado.
When used, this flag will prevent the generation of ANALYZE
statements. Without the -Z flag (default behavior), the ANALYZE
statements will be generated.
Uma seção exemplo usando o carregador para criar um arquivo de entrada e atualizando ele pode parecer com:
# shp2pgsql -c -D -s 4269 -i -I shaperoads.shp myschema.roadstable > roads.sql # psql -d roadsdb -f roads.sql
Uma conversão e um upload podem ser feitos em apenas um passo usando encadeamento UNIX:
# shp2pgsql shaperoads.shp myschema.roadstable | psql -d roadsdb
Os dados podem ser extraídos do banco da dados usando o SQL ou o Shape file loader/dumper. Na seção do SQL discutiremos alguns dos operadores disponíveis para comparações e consultas em tabelas espaciais.
O mais simples significa extrair os dados do banco de dados, é usar uma consulta SQL para reduzir o número de RELATOS e COLUNAS retornados e abandonar as colunas resultantes dentro de um arquivo de texto analisável:
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)
Entretanto, às vezes algum tipo de restrição será necessária para cortar o número de campos retornados. No caso de restrições baseadas em atributos, só use a mesma sintaxe SQL como normal com uma tabela não espacial. No caso de restrições espaciais, os operadores seguintes são úteis/disponíveis:
This function tells whether two geometries share any space.
Isto testa se duas geometrias são geometricamente iguais. Por exemplo, se 'POLYGON((0 0,1 1,1 0,0 0))' é o mesmo que 'POLYGON((0 0,1 1,1 0,0 0))' (é).
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;
A consulta acima retornaria um único relato da tabela "ROADS_GEOM"na qual a geometria era igual ao 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.
Usando o operador "&&" , você pode especificar uma CAIXA3D como uma caracetrística de comparação ou uma GEOMETRIA. Entretanto, quando você especifica uma GEOMETRIA, a caixa delimitadora dela será usada para a comparação.
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);
Observe o uso do SRID 312, para especificar a projeção do envelope.
A tabela dumper pgsql2shp
conecta diretamente ao banco de dados e converte uma tabela (possivelmente definida por uma consulta) em um shapefile. A sintaxe básica é:
pgsql2shp [<options>] <database> [<schema>.]<table>
pgsql2shp [<options>] <database> <query>
As opções da commandline são:
Atribui a saída a um filename específico.
O hospedeiro do banco de dados para se conectar.
A porta para conectar no hospedeiro do banco de dados.
A senha para usar quando conectar ao banco de dados.
O nome de usuário para usar quando conectado ao banco de dados.
No caso de tabelas com várias colunas geométricas, a coluna para usar quando atribuindo o shapefile.
Use um cursor binário. Isto tornará a operação mais rápida, mas não funcionará se qualquer atributo NÃO-geométrico na tabela necessitar de um cast para o texto.
Modo cru. Não derruba o campo gid
, ou escapa o nome das colunas.
filename
Remapeia os identificadores para nomes com dez caracteres. O conteúdo do arquivo é linhas de dois símbolos separados por um único espaço branco e nenhum espaço seguindo ou à frente: 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 Trees) dissolvem dados em "coisas de um lado", "coisas que sobrepõem", "coisas que estão dentro" e pode ser usado em vários tipos de dados, incluindo dados GIS. O PostGIS usa o índice R-Tree implementado no topo do GiST para classificar dados GIS.
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 significa "Árvores de Pesquisa Generalizada" e é uma forma genérica de classificar. Além disso, ele é usado para acelerar pesquisas em todos os tipos de estruturas de dados irregulares (arranjos inteiros, dados espectrais etc) que não são agradáveis à classificação normal B-Tree.
Uma vez que uma tabela de dados GIS excede pouco mais de mil filas, você irá querer construir um índice para acelerar pesquisas espaciais dos dados (a menos que suas pesquisas sejam baseadas em atributos, você vai querer construir um índice normal nos campos de atributo).
A sintaxe para construir um índice GiST em uma coluna "geométrica" é a seguinte:
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;
A sintaxe para construir um índice GiST em uma coluna "geométrica" é a seguinte:
CREATE INDEX [indexname] ON [tablename] USING GIST ( [geometryfield] );
The above syntax builds a 2D index. To build a 3D-dimensional index, use this syntax:
CREATE INDEX [indexname] ON [tablename] USING GIST ([geometryfield] gist_geometry_ops_nd);
You can also get a 4D-dimensional index using the 4D operator class:
CREATE INDEX [indexname] ON [tablename] USING GIST ([geometryfield] gist_geometry_ops_nd);
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 GIST ([geometryfield] gist_geometry_ops_nd);
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 GIST ( [geometryfield] );
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.
Se você achar que seus índices não estão sendo usados (ou seus atributos) há algumas coisas que pode fazer:
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, “Construindo índidces”). 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)
Versões atuais do PostgreSQL (incluindo a 8.0) sofrem de um problem no otimizador de queries quando falamos de tabelas TOAST. As tabelas TOAST são extensões utilizadas para armazenamento de grandes valores (no sentido de tamanho do dado) que não cabem normalmente nas páginas de dados (grandes blocos de texto, imagens ou geometrias complexas com muitos vértices, veja a documentação oficial para maiores informações).
Este problema ocorre se você possui tabelas com geometrias grandes, mas não muitas linhas (uma tabela dos limites todos os países europeus em alta resolução). A tabela em si, é pequena, mas utiliza muito espaço TOAST. Em nosso exemplo, a tabela em si possuía apenas 80 linhas e utilizava apenas 3 páginas de dados, mas a tabela TOAST utilizava 8225 páginas de dados.
Emita uma pesquisa onde você utiliza o operador && para pesquisa por um retângulo envolvente que bate com poucas dessas linhas. O otimizador de pesquisas ve esta tabela contendo apenas 3 páginas e 80 linhas. Como a tabela é pequena, ele estima que um scan sequencial em uma tabela tão pequena será mais rápida do que utilizar um índice, ignorando o mesmo. Geralmente esta estimativa é correta, mas em nosso caso o operador && tem que buscar todas as geometrias em disco para comparação dos retângulos envolventes, lendo todas as páginas TOAST também.
Para visualizar se você sofre com este bug, utilize um "EXPLAIN ANALYZE" na pesquisa em questão. Para maiores informações e detalhes técnicos, você pode recorrer a lista do postgres sobre desempenho: 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
O pessoal responsável pelo PostgreSQL está tentando resolver esta questão por transformar o otimizador de pesquisas ciente das tabelas TOAST. Por enquanto, existem duas soluções:
A primeira solução é forçar o estimador de pesquisar a utilizar o índice. Emita um comando "SET enable_seqscan TO off" ao servidor antes de emitir a pesquisa. Isto força o estimador a evitar scans sequenciais sempre que possível, utilizando o índice GIST como de costume. Mas esta flag deve ser setada para cada conexão e causa o estimador a decidir mal em outros casos, portanto, você deve habilitar "SET enable_seqscan TO on;" após a pesquisa.
A segunda solução é fazer a pesquisa sequencial tão rápida quanto o estimador imagina. Isto pode ser feito criando uma coluna adicional que cacheia o retângulo envolvente e realizando as pesquisas em cima desta coluna. Em nosso exemplo, os comandos são:
SELECT AddGeometryColumn('myschema','mytable','bbox','4326','GEOMETRY','2'); UPDATE mytable SET bbox = ST_Envelope(ST_Force2D(the_geom));
Altere sua query para usar o operador && contra o retângulo envolvente ao invés da colunas geométrica, assim:
SELECT geom_column FROM mytable WHERE bbox && ST_SetSRID('BOX3D(0 0,1 1)'::box3d,4326);
Claro, se você alterar ou adicionar colunas a mytable, você deve manter o retângulo envolvente em sincronia. A forma mais transparente de fazer isto seria através de triggers, mas você também querer modificar sua aplicação para manter a coluna do retângulo envolvente atualizada or executar a query de UPDATE após cada modificação.
Para tabelas que são basicamente somente-leitura, e onde um único índice é utilizado pela maioria das queries, PostgreSQL oferece o comando CLUSTER. Este comando fisicamente reordena todas as linhas da tabela assim como as do índice, assim possibilitando duas melhorias de desempenho: primeiro, para pesquisas de intervalo de índice, o número de pesquisas na tabela de dados é dramaticamente reduzido. Segundo, se seu conjunto de trabalho concentra-se em pequenos intervalos nos índices, você tem um cache mais eficiente, pois todas as informações estão divididas em poucas páginas de dados. (Sinta se convidado para ler a documentação do comando CLUSTER do manual do PostgreSQL.)
Contudo, atualmente o Postgresql não permite a clusterização de índices geométricos GIST, pois estes índices simplesmente ignoram valores nulos, retornando um erro como:
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 a HINT da mensagem te diz, você pode adicionar uma constraint "not null" na tabela para contornar o problema.
lwgeom=# ALTER TABLE my_table ALTER COLUMN the_geom SET not null; ALTER TABLE
Claro, isto não vai funcionar se você de fato precisa de valores NULL em sua coluna geométrica. Adicionalmente, você deve usar o método acima para adicionar a constraint. Utilizar uma constraint do tipo CHECK como "ALTER TABLE blubb ADD CHECK (geometry is not null);" não irá funcionar.
Algumas vezes, você tem dados que são 3D ou 4D em sua tabela, mas sempre acessa-os usando métodos OpenGIS, como ST_AsText() ou ST_AsBinary(), que somente funcionam em geometrias 2D. Eles fazem isso internamente chamando a função ST_Force2D(), que introduza um gasto extra para grandes geometrias. Para evitar este gasto extra, pode ser viável dropar essas dimensões adicionais para sempre:
UPDATE mytable SET the_geom = ST_Force2D(the_geom); VACUUM FULL ANALYZE mytable;
Note que se você adicionou sua coluna geométrica utilizando o método AddGeometryColumn(), existirá uma constraint na dimensão da geometria. Para contornar isto, você precisará dropar a constraint também. Lembre-se de atualizar a entrada na tabela geometry_columns e recriar a constraint posteriormente.
No caso de grandes tabelas, pode ser sábio dividir este UPDATE em porções menores, restringindo o UPDATE a pequenas partes da tabela com o uso de uma cláusula WHERE sobre sua PRIMARY KEY ou outro critério, rodando um VACUUM, entre os UPDATEs. Isto reduz drasticamente a necessidade de espaço em disco temporário. Adicionalmente, se você tem geometrias de dimensões mistas, restrigir o UPDATE por "WHERE dimension(the_geom)>2" pula as geometrias que já estão em 2D.
O MapServer de Minnesota é um servidor de mapas web que esta em conformidade com a especificação do OpenGIS Web Mapping Server.
A página do MapServer esta em http://mapserver.org.
A especificação OpenGIS Web Map encontra-se em http://www.opengeospatial.org/standards/wms.
Para utilizar o PostGIS com o MapServer, você precisa saber como configurar o MapServer, o que esta além do escopo desta documentação. Esta seção ira cobrir questões relativas ao PostGIS, além de detalhes de configuração.
Para utilizar o PostGIS com o MapServer, você vai precisar:
Versão 0.6 ou mais recente do PostGIS.
Versão 3.5 ou mais recente do MapServer.
O MapServer acessa os dados do PostGIS/PostgreSQL como qualquer outro cliente PostgreSQL -- utilizando a interface libpq
. Isso significa que o MapServer pode ser instalado em qualquer máquina com acesso à rede para o servidor do PostGIS, e usar o POstGIS como uma fonte de dados. Quanto mais rápida a conexão entre os sistemas, melhor.
Compile e instale o MapServer, com quaisquer opções que desejar, incluindo a opção de configuração "--with-postgis".
No seu arquivo de mapeamento do MapServer, adicione uma camada PostGIS. Por exemplo:
LAYER CONNECTIONTYPE postgis NAME "widehighways" # Connect to a remote spatial database CONNECTION "user=dbuser dbname=gisdatabase host=bigserver" PROCESSING "CLOSE_CONNECTION=DEFER" # Get the lines from the 'geom' column of the 'roads' table DATA "geom from roads using srid=4326 using unique gid" STATUS ON TYPE LINE # Of the lines in the extents, only render the wide highways FILTER "type = 'highway' and numlanes >= 4" CLASS # Make the superhighways brighter and 2 pixels wide EXPRESSION ([numlanes] >= 6) STYLE COLOR 255 22 22 WIDTH 2 END END CLASS # All the rest are darker and only 1 pixel wide EXPRESSION ([numlanes] < 6) STYLE COLOR 205 92 82 END END END
No exemplo acima, as instruções específicas do PostGIS estão como segue:
Para camadas PostGIS, este é sempre "postgis".
A conexão do banco de dados é governada pela "string conexão" que é uma configuração padrão de chaves e valores como essa (com os valores padrões em <>):
user=<username> password=<password> dbname=<username> hostname=<server> port=<5432>
Uma string de conexão vazia continua válida, e quaisquer outros valores/chaves podem ser omitidos. No mínimo você fornece o nome e nome de usuário para o banco de dados para conectar.
Para formar esse parâmetro é "<geocolumn> de <tablename> using srid=<srid> usando único <primary key>" onde a coluna é a coluna espacial para ser reproduzida no mapa, a SRID é SRID usada pela coluna e a chave primária é a chave primária da table (ou qualquer outra coluna de valor único com um index).
Você pode omitir as orações "using srid" e "using unique" e o MapServer irá determinar automaticamente os valores possíveis se possível, mas ao custo de executar algumas pesquisas extras no servidor para cada desenho de mapa.
Colocando em um CLOSE_CONNECTION=DEFER se você tem múltiplas camadas reutilizando conexões existentes ao invés de fechar elas. Isso melhora a velocidade. Para informações mais detalhadas vá para: MapServer PostGIS Performance Tips.
O filtro deve ser uma string SQL válida correspondente à normalidade lógica seguindo aa palavra-chave "ONDE" em uma consulta SQL. Então, por exemplo, para representar caminhos com 6 ou mais pistas, use um filtro de "num_lanes >= 6".
No seu banco de dados espacial, certifique-se que tenha indexes espaciais (GiST) construídos para qualquer uma das camadas que você irá desenhar.
CREATE INDEX [indexname] ON [tablename] USING GIST ( [geometrycolumn] );
Se você irá consultar suas camadas usando o MapServer, você também vai precisar usar a oração "using unique" no sua declaração de DADOS.
O MapServer requer identificadores únicos para cada registro espacial quando fazem-se consultas, e o módulo do PostGIS do MapServer usa o único valor que você especifica a fim de fornecer esse identificadores. Utilizar a chave primária da table é a melhor prática.
A pseudo oração SQL USING
é usada para adicionar algumas informações para ajudar o mapserver a entender os resultados de pesquisas mais avançadas. Mais especificamente, quando uma view ou uma subselect são usadas como a source table (a coisa para a direita do "DE" em uma definição DATA
) é mais difícil para o mapserver determinar automaticamente um identificador único para cada fila e também a SRID para a table. A oração USING
pode fornecer o mapserver com essas duas informações:
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"
O MapServer requer uma id única para cada fila a fim de identificar a linha quando estiver fazendo consultas de mapa. Normalmente, ele identifica a chave primária do sistema de tables. Contudo, as views e subselects não têm automaticamente uma coluna única conhecida. Se você quiser usar a funcionalidade pesquisa do MapServer, você precisa certificar-se que sua view ou subselect inclui uma única coluna com valor, e declare isso com: USING UNIQUE
. Por exemplo, você poderia explicitamente selecionar o nascimento dos valores da chave primária da table para esse propósito, ou qualquer outra coluna que se garante ser única para o resultado estabelecido.
![]() | |
"Pesquisando um Mapa" é a ação de clicar em um mapa para perguntar sobre informações sobre as características naquela localização. Não confunda "mapa pesquisa" com a pesquisa SQL em uma definição |
O PostGIS precisa saber qual sistema de referenciação espacial está sendo utilizado pelas geometrias a fim de retornar os dados corretos para o MapServer. Normalmente, é possível encontrar essa informação na table "geometry_columns" no banco de dados do PostGIS, porém, não é possível para as tables que são criadas rapidamente como subselects e views. Então, a opção USING SRID=
permite a SRID correta ser especificada na definição DATA
.
Vamos começar com um exemplo simples e trabalhar com ele. Considere a seguinte definição de camada 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
Essa camada irá expor todas as geometrias de rua nas roads tables como linhas pretas.
Agora, digamos que queremos mostrar somente as estradas antes de aproximarmos para uma escala 1:100000 - as próximas duas camadas irão alcançar esse efeito:
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
A primeira camada é usada quando a escala é maior que 1:100000, e exibe apenas as ruas do tipo "estrada" como linhas pretas. A opção FILTRO
faz com que apenas as ruas do tipo "estradas" sejam exibidas.
A segunda camada é usada quando a escala é menor que 1:100000, e irá exibir estradas como duas linhas vermelhas grossas, e outras ruas como linhas pretas normais.
Portanto, fizemos algumas coisas interessantes utilizando apenas a funcionalidade MapServer, mas nossa declaração SQL DATA
continuou simples. Suponha que o nome da rua está guardado em outra table (por alguma razão) e precisamos ingressar para pegar ele e etiquetar nossas ruas.
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
Essa camada de comentário adiciona etiquetas verdes a todas as ruas quando a escala fica abaixo de 1:20000 ou menor que isso. Ela também demonstra como usar um ingresso SQL em uma definição DATA
.
Os clientes Java podem acessar os objetos "geometria" do PostGIS no banco de dados PostgreSQL diretamente como representações de textos ou usando a extensão JDBC de objetos empacotados com PostGIS. A fim de usar os objetos da extensão, o arquivo "postgis.jar" deve estar no seu CLASSPATH junto com o "postgresql.jar" do pacote de dispositivos JDBC.
import java.sql.*; import java.util.*; import java.lang.*; import org.postgis.*; public class JavaGIS { public static void main(String[] args) { java.sql.Connection conn; try { /* * Load the JDBC driver and establish a connection. */ Class.forName("org.postgresql.Driver"); String url = "jdbc:postgresql://localhost:5432/database"; conn = DriverManager.getConnection(url, "postgres", ""); /* * Add the geometry types to the connection. Note that you * must cast the connection to the pgsql-specific connection * implementation before calling the addDataType() method. */ ((org.postgresql.PGConnection)conn).addDataType("geometry",Class.forName("org.postgis.PGgeometry")); ((org.postgresql.PGConnection)conn).addDataType("box3d",Class.forName("org.postgis.PGbox3d")); /* * Create a statement and execute a select query. */ Statement s = conn.createStatement(); ResultSet r = s.executeQuery("select geom,id from geomtable"); while( r.next() ) { /* * Retrieve the geometry as an object then cast it to the geometry type. * Print things out. */ PGgeometry geom = (PGgeometry)r.getObject(1); int id = r.getInt(2); System.out.println("Row " + id + ":"); System.out.println(geom.toString()); } s.close(); conn.close(); } catch( Exception e ) { e.printStackTrace(); } } }
O objeto "PGgeometry" é um objeto wrapper que contém um objeto específico de geometria topológica (subclasse da classe abstrata "Geometria") dependendo do tipo: Ponto, LineString, Polígono, MultiPonto, MultiLineString, MultiPolígono.
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()); } } }
O JavaDoc para os objetos de extensão fornece uma referência para os dados variados das funções accessor nos objetos geométricos.
...
As funções descritas abaixo são as que um usuário do PostGIS devem precisar. Existem outras funções que são necessárias para suportar os objetos PostGIS mas que não são de uso comum pelo usuário.
![]() | |
O PostGIS iniciou uma transição da convenção de nomenclatura existente para uma convenção em torno do SQL-MM. Como resultado, a maioria das funções que você conhece e ama foram renomeadas usando o padrão de tipo espacial (com o prefixo ST). As funções anteriores ainda existem, porém não são listadas nesta documentação onde as funções atualizadas são equivalentes. As funções que não possuem prefixo ST_ não listadas nesta documentação estão obsoletas e serão removidas em futuros lançamentos, então PAREM DE UTILIZÁ-LAS. |
Essa seção lista os tipos de dados PostgreSQL instalados pelo PostGIS. Note que descrevemos que o comportamento desses é muito importante , especialmente quando designando suas próprias funções.
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.
a caixa3d é um tipo de dados postgis usados para representar a caixa enclosing de um ageometria ou conjunto de geometrias. A ST_3DExtent retorna um objeto caixa3d.
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.
a caixa3d é um tipo de dados postgis usados para representar a caixa enclosing de um ageometria ou conjunto de geometrias. A ST_3DExtent retorna um objeto caixa3d.
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 — geografia é um tipo de dado espacial usado para representar uma característica no sistema de coordenada da terra-redonda.
geografia é um tipo de dado espacial usado para representar uma característica no sistema de coordenada da terra-redonda.
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.
geografia — The type representing spatial features with geodetic (ellipsoidal) coordinate systems.
geografia é um tipo de dado espacial usado para representar uma característica no sistema de coordenada da terra-redonda.
Spatial operations on the geography type provide more accurate results by taking the ellipsoidal model into account.
AddGeometryColumn — Remove uma coluna geometria de uma spatial table.
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)
;
Adiciona uma coluna geometria à uma table de atributos. O schema_name
é o nome da table esquema. O srid
deve ser um valor de referência inteiro para uma entrada na table SPATIAL_REF_SYS. O tipo
deve ser uma string correspondente ao tipo da geometria, por exemplo: 'POLÍGONO' ou 'MULTILINSTRING'. Um erro é descartado se o esquema não existe (ou não é visível no search_path atual) ou a SRID especificada, tipo de geometria ou dimensão é inválida.
![]() | |
Alterado: 2.0.0 Essa função não atualiza mais a geometry_columns desde que ela é a view que lê dos catálogos de sistema. Por padrão, isso não cria restrições, mas usa a construção no comportamento do tipo modificador do PostgreSQL. Então, por exemplo, construir uma coluna wgs84 POINT com essa função é equivalente a: Alterado: 2.0.0 Se você exige o comportamento antigo de restrições use o padrão |
![]() | |
Alterações: 2.0.0 Views não podem ser registradas manualmente mais em geometry_columns, porém as views construídas contra as geometrias typmod tables e usadas sem as funções wrapper irão se registrar corretamente, porque elas herdam um comportamento typmod da table column mãe. As views que usam funções geométricas que fazem outras geometrias saírem, precisarão de ser lançadas para as geometrias typmod, para essas colunas serem registradas corretamente em geometry_columns. Use Section 4.6.3, “Registrando manualmente as colunas geométricas em 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
Melhorias: 2.0.0 argumento use_typmod introduzido. Padrões para criar colunas de geometria typmod ao invés das baseadas em obstáculos.
-- Create schema to hold data CREATE SCHEMA my_schema; -- Create a new simple PostgreSQL table CREATE TABLE my_schema.my_spatial_table (id serial); -- Describing the table shows a simple table with a single "id" column. postgis=# \d my_schema.my_spatial_table Table "my_schema.my_spatial_table" Column | Type | Modifiers --------+---------+------------------------------------------------------------------------- id | integer | not null default nextval('my_schema.my_spatial_table_id_seq'::regclass) -- Add a spatial column to the table SELECT AddGeometryColumn ('my_schema','my_spatial_table','geom',4326,'POINT',2); -- Add a point using the old constraint based behavior SELECT AddGeometryColumn ('my_schema','my_spatial_table','geom_c',4326,'POINT',2, false); --Add a curvepolygon using old constraint behavior SELECT AddGeometryColumn ('my_schema','my_spatial_table','geomcp_c',4326,'CURVEPOLYGON',2, false); -- Describe the table again reveals the addition of a new geometry columns. \d my_schema.my_spatial_table addgeometrycolumn ------------------------------------------------------------------------- my_schema.my_spatial_table.geomcp_c SRID:4326 TYPE:CURVEPOLYGON DIMS:2 (1 row) Table "my_schema.my_spatial_table" Column | Type | Modifiers ----------+----------------------+------------------------------------------------------------------------- id | integer | not null default nextval('my_schema.my_spatial_table_id_seq'::regclass) geom | geometry(Point,4326) | geom_c | geometry | geomcp_c | geometry | Check constraints: "enforce_dims_geom_c" CHECK (st_ndims(geom_c) = 2) "enforce_dims_geomcp_c" CHECK (st_ndims(geomcp_c) = 2) "enforce_geotype_geom_c" CHECK (geometrytype(geom_c) = 'POINT'::text OR geom_c IS NULL) "enforce_geotype_geomcp_c" CHECK (geometrytype(geomcp_c) = 'CURVEPOLYGON'::text OR geomcp_c IS NULL) "enforce_srid_geom_c" CHECK (st_srid(geom_c) = 4326) "enforce_srid_geomcp_c" CHECK (st_srid(geomcp_c) = 4326) -- geometry_columns view also registers the new columns -- SELECT f_geometry_column As col_name, type, srid, coord_dimension As ndims FROM geometry_columns WHERE f_table_name = 'my_spatial_table' AND f_table_schema = 'my_schema'; col_name | type | srid | ndims ----------+--------------+------+------- geom | Point | 4326 | 2 geom_c | Point | 4326 | 2 geomcp_c | CurvePolygon | 4326 | 2
DropGeometryColumn — Remove uma coluna geometria de uma spatial table.
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)
;
Remove uma coluna geometria de uma table espacial. Note que o schema_name precisará combinar com o campo f_table_schema da fila da table na table geometry_columns.
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
![]() | |
Alterações: 2.0.0 Essa função é fornecida para compatibilidade atrasada. Desde que geometry_columns é uma view contra os sistemas catalogados, você pode derrubar uma coluna geométrica como qualquer outra table column usando |
SELECT DropGeometryColumn ('my_schema','my_spatial_table','geom'); ----RESULT output --- dropgeometrycolumn ------------------------------------------------------ my_schema.my_spatial_table.geom effectively removed. -- In PostGIS 2.0+ the above is also equivalent to the standard -- the standard alter table. Both will deregister from geometry_columns ALTER TABLE my_schema.my_spatial_table DROP column geom;
DropGeometryTable — Derruba uma table e todas suas referências em geometry_columns.
boolean DropGeometryTable(
varchar table_name)
;
boolean DropGeometryTable(
varchar schema_name, varchar table_name)
;
boolean DropGeometryTable(
varchar catalog_name, varchar schema_name, varchar table_name)
;
Derruba uma table e todas as suas referências em geometry_columns. Nota: use current_schema() nas instalações schema-aware pgsql se o esquema não for fornecido.
![]() | |
Alterações: 2.0.0 Essa função é fornecida para compatibilidade atrasada. Desde que geometry_columns é uma view contra os sistemas catalogados, você pode derrubar uma table com colunas geométricas como qualquer outra table usando |
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)
;
Assegura que as colunas geométricas são definidas com modificadores de tipo ou têm obstáculos espaciais apropriados. Isso garante que serão registrados corretamente na view geometry_columns
. Por padrão, irá converter todas as colunas geométricas com nenhum modificador de tipo para os que têm o modificador. para obter esse comportamento antigo use use_typmod=false
Para compatibilidades atrasadas e necessidades espaciais como a herança das tables, onde cada table child talvez tenha um tipo geométrico diferente, a última verificação do comportamento ainda é suportada. Se você precisar do último comportamento, você tem de passar o novo argumento opcional como falso use_typmod=false
. Quando isso for feito, as colunas geométricas serão criadas sem modificadores de tipo, mas terão 3 obstáculos definidos. Isso significa que cada coluna geométrica pertencente a uma table tem, pelo menos, três obstáculos:
enforce_dims_the_geom
- assegura que toda geometria tenha a mesma dimensão (veja ST_NDims)
enforce_geotype_the_geom
- assegura que toda geometria seja do mesmo tipo (veja Tipo de geometria)
enforce_srid_the_geom
- assegura que toda geometria tenha a mesma projeção (veja ST_SRID)
Se uma table oid
é fornecida, essa função tenta determinar a srid, a dimensão e o tipo geométrico de todas as colunas geométricas na table, adicionando restrições se necessário. Se for bem-sucedido, uma fila apropriada é inserida na table geometry_columns, senão, a exceção é pega e uma notificação de erro surge, descrevendo o problema.
Se o oid
de uma view é fornecido, como com uma table oid, essa função tenta determinar a srid, dimensão e tipo de todas as geometrias na view, inserindo entradas apropriadas na table geometry_columns
, mas nada é feito para executar obstáculos.
A variante sem parâmetro é um simples wrapper para a variante parametrizada que trunca primeiro e repopula a table geometry_columns para cada table espacial e view no banco de dados, adicionando obstáculos espaciais para tables onde são apropriados. Isso retorna um resumo do número de colunas geométricas detectadas no banco de dados e o número que foi inserido na table geometry_columns
. A versão parametrizada retorna, simplesmente, o número de filas inseridas na table geometry_columns
.
Disponibilidade: 1.4.0
Alterações: 2.0.0 Por padrão, utilize modificadores de tipo ao invés de verificar restrições para restringir os tipos de geometria. Você pode verificar restrições de comportamento ao invés de usar o novo use_typmod
e configurá-lo para falso.
Melhorias: 2.0.0 use_typmod
argumento opcional foi introduzido, permitindo controlar se as colunas forem criadas com modificadores de tipo ou com verificação de restrições.
CREATE TABLE public.myspatial_table(gid serial, geom geometry); INSERT INTO myspatial_table(geom) VALUES(ST_GeomFromText('LINESTRING(1 2, 3 4)',4326) ); -- This will now use typ modifiers. For this to work, there must exist data SELECT Populate_Geometry_Columns('public.myspatial_table'::regclass); populate_geometry_columns -------------------------- 1 \d myspatial_table Table "public.myspatial_table" Column | Type | Modifiers --------+---------------------------+--------------------------------------------------------------- gid | integer | not null default nextval('myspatial_table_gid_seq'::regclass) geom | geometry(LineString,4326) |
-- This will change the geometry columns to use constraints if they are not typmod or have constraints already. --For this to work, there must exist data CREATE TABLE public.myspatial_table_cs(gid serial, geom geometry); INSERT INTO myspatial_table_cs(geom) VALUES(ST_GeomFromText('LINESTRING(1 2, 3 4)',4326) ); SELECT Populate_Geometry_Columns('public.myspatial_table_cs'::regclass, false); populate_geometry_columns -------------------------- 1 \d myspatial_table_cs Table "public.myspatial_table_cs" Column | Type | Modifiers --------+----------+------------------------------------------------------------------ gid | integer | not null default nextval('myspatial_table_cs_gid_seq'::regclass) geom | geometry | Check constraints: "enforce_dims_geom" CHECK (st_ndims(geom) = 2) "enforce_geotype_geom" CHECK (geometrytype(geom) = 'LINESTRING'::text OR geom IS NULL) "enforce_srid_geom" CHECK (st_srid(geom) = 4326)
UpdateGeometrySRID — Updates the SRID of all features in a geometry column, and the table metadata.
text UpdateGeometrySRID(
varchar table_name, varchar column_name, integer srid)
;
text UpdateGeometrySRID(
varchar schema_name, varchar table_name, varchar column_name, integer srid)
;
text UpdateGeometrySRID(
varchar catalog_name, varchar schema_name, varchar table_name, varchar column_name, integer srid)
;
Atualiza a SRID de todas as características em uma coluna geométrica, atualizando restrições e referências na geometry_columns. Nota: use current_schema() nas instalações schema-aware pgsql se o esquema não for fornecido.
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) \.
Isso irá alterar a srid das roads tables para 4326 de qualquer coisa que tenha sido antes
SELECT UpdateGeometrySRID('roads','geom',4326);
O exemplo anterior é equivalente a esta declaração DDL
ALTER TABLE roads ALTER COLUMN geom TYPE geometry(MULTILINESTRING, 4326) USING ST_SetSRID(geom,4326);
Se você obteve a projeção errada (ou comprou como desconhecido) no carregamento e quer transformar para mercartor, tudo de uma vez, você pode fazer isso com DDL, mas não existe uma função de gestão equivalente do PostGIS.
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. |
Disponibilidade: 1.4.0 - ST_MakeLine(geomarray) foi introduzida. A ST_MakeLine agrega funções que foram melhoradas para lidar com mais pontos mais 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 — Cria uma linestring de um multiponto geométrico.
geometria ST_LineFromMultiPoint(
geometria ummultiponto)
;
Cria uma LineString de uma geometria MultiPointo.
Use ST_MakeLine to create lines from Point or LineString inputs.
This function supports 3d and will not drop the z-index.
ST_MakeEnvelope — Cria um polígono retangular formado a partir dos mínimos e máximos dados. Os valores de entrada devem ser em SRS especificados pelo SRID.
geometry ST_MakeEnvelope(
double precision xmin, double precision ymin, double precision xmax, double precision ymax, integer srid=unknown)
;
Cria um polígono retangular formado a partir do mínimo e máximo, pela dada shell. Os valores de entradas devem ser SRS especificados pelo SRID. Se nenhum SRID for especificado o sistema de referência espacial desconhecido é assumido
Disponibilidade: 1.5
Melhorias: 2.0: Habilidade para especificar um pacote sem especificar um SRID foi introduzida.
ST_MakeLine — Cria uma Linestring de ponto, multiponto ou linha das geometrias.
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.0.0 - Suporte para elementos de entrada linestring foi introduzido
Disponibilidad: 2.0.0 - Suporte para elementos de entrada linestring foi introduzido
Disponibilidade: 1.4.0 - ST_MakeLine(geomarray) foi introduzida. A ST_MakeLine agrega funções que foram melhoradas para lidar com mais pontos mais 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)); --Making a 3d line with 3 3-d points SELECT ST_AsEWKT(ST_MakeLine(ARRAY[ST_MakePoint(1,2,3), ST_MakePoint(3,4,5), ST_MakePoint(6,6,6)])); st_asewkt ------------------------- LINESTRING(1 2 3,3 4 5,6 6 6)
Cria uma CAIXA2D definida pelos pontos 2 3D dados das geometrias.
SELECT ST_AsEWKT( ST_MakeLine(ST_MakePoint(1,2,3), ST_MakePoint(3,4,5) )); st_asewkt ------------------------- LINESTRING(1 2 3,3 4 5)
Cria uma Linestring de ponto, multiponto ou linha das geometrias.
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)); --Making a 3d line with 3 3-d points SELECT ST_AsEWKT(ST_MakeLine(ARRAY[ST_MakePoint(1,2,3), ST_MakePoint(3,4,5), ST_MakePoint(6,6,6)])); st_asewkt ------------------------- LINESTRING(1 2 3,3 4 5,6 6 6)
Esse exemplo pega uma sequência de pontos do GPS e cria um relato para cada torre gps onde o campo geométrico é uma line string composta com os pontos do gps na ordem da viagem.
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.
geometria 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)
;
Cria uma CAIXA2D definida pelos pontos dados das geometrias.
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.
--Return point with unknown SRID SELECT ST_MakePoint(-71.1043443253471, 42.3150676015829); --Return point marked as WGS 84 long lat SELECT ST_SetSRID(ST_MakePoint(-71.1043443253471, 42.3150676015829),4326); --Return a 3D point (e.g. has altitude) SELECT ST_MakePoint(1, 2,1.5); --Get z of point SELECT ST_Z(ST_MakePoint(1, 2,1.5)); result ------- 1.5
ST_MakePointM — Cria um ponto com uma coordenada x y e medida.
geometry ST_MakePointM(
float x, float y, float m)
;
Cria um ponto com uma coordenada x y e 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)
Cria um ponto com uma coordenada x y e 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)
;
Cria uma polígono formado pela dada shell. As geometrias de entrada devem ser LINESTRINGS fechadas.
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.
![]() | |
Essa função não aceitará uma MULTILINESTRING. Use ST_LineMerge ou ST_Dump para gerar line strings. |
This function supports 3d and will not drop the z-index.
Cria uma LineString de uma string Encoded Polyline.
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;
Cria uma LineString de uma string Encoded Polyline.
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))
Construir um donut com um buraco de formiga
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.
![]() | |
A construção CASE é usada porque sustentar uma coleção de nulos em ST_MakePolygon resulta em NULO. |
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; --Same example above but utilizing a correlated subquery --and PostgreSQL built-in ARRAY() function that converts a row set to an 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.
geometria 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) Como geografia);
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)
;
Retorna uma ST_Point com os valores de coordenada dados. Heterônimo OGC para ST_MakePoint.
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)
;
Retorna uma ST_Point com os valores de coordenada dados. Heterônimo OGC para ST_MakePoint.
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)
;
Retorna uma ST_Point com os valores de coordenada dados. Heterônimo OGC para ST_MakePoint.
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.
![]() | |
Essa função não aceitará uma MULTILINESTRING. Use ST_LineMerge ou ST_Dump para gerar line strings. |
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.
Melhorias: 2.0.0 parâmetro opcional padrão srid adicionado.
Disponibilidade: 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.
geometria 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.
Disponibilidade: 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.
Disponibilidade: 2.1.0
ST_SquareGrid — Returns a set of grid squares and cell indices that completely cover the bounds of the geometry argument.
geometria 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.
Disponibilidade: 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.
Disponibilidade: 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.
Disponibilidade: 2.1.0
geometry_dump
rows for the components of a geometry.geometry_dump
rows for the exterior and interior rings of a Polygon.VERDADEIRO
se os pontos de começo e fim da LINESTRING
são coincidentes. Para superfície poliédrica está fechada (volumétrica). Tipo de geometria — Retorna o tipo de geometria de valor ST_Geometry.
texto GeometryType(
geometria geomA)
;
Retorna o tipo de geometria como uma string. Exemplos: 'LINESTRING', 'POLÍGONO', 'MULTIPOINT', etc.
OGC SPEC s2.1.1.1 - Retorna o nome do sub tipo ocasional da geometria da qual essa geometria ocasiona é um membro. O nome do sub tipo ocasional retorna como uma string.
![]() | |
Essa função também indica se a geometria é medida, retornando uma string da forma 'POINTM'. |
Melhorias: 2.0.0 suporte para superfícies poliédricas, triângulos e TIN introduzido.
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 — Retorna o encerramento da borda combinatória dessa geometria.
geometria ST_Boundary(
geometria geomA)
;
Retorna o encerramento do limite combinatório dessa geometria. O limite combinatório é definido com descrito na seção 3.12.3.2 do OGC SPEC. Porque o resultado dessa função é um encerramento, e por isso topologicamente fechado, o limite resultante pode ser representado usando geometrias primitivas representacionais como foi discutido no OGC SPEC, seção 3.12.2.
Desempenhado pelo módulo GEOS
![]() | |
Anterior a 2.0.0, essa função abre uma exceção se usada com |
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.
Melhorias: 2.1.0 suporte para Triângulo foi introduzido
Changed: 3.2.0 support for TIN, does not use geos, does not linearize curves
![]() Linestring com pontos de limite cobertos
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))
| ![]() furos de polígono com multilinestring limite
SELECT ST_Boundary(geom) FROM (SELECT 'POLYGON (( 10 130, 50 190, 110 190, 140 150, 150 80, 100 10, 20 40, 10 130 ), ( 70 40, 100 50, 120 80, 80 110, 50 90, 70 40 ))'::geometry As geom) As f;
-- ST_AsText output MULTILINESTRING((10 130,50 190,110 190,140 150,150 80,100 10,20 40,10 130), (70 40,100 50,120 80,80 110,50 90,70 40))
|
SELECT ST_AsText(ST_Boundary(ST_GeomFromText('LINESTRING(1 1,0 0, -1 1)'))); st_astext ----------- MULTIPOINT((1 1),(-1 1)) SELECT ST_AsText(ST_Boundary(ST_GeomFromText('POLYGON((1 1,0 0, -1 1, 1 1))'))); st_astext ---------- LINESTRING(1 1,0 0,-1 1,1 1) --Using a 3d polygon SELECT ST_AsEWKT(ST_Boundary(ST_GeomFromEWKT('POLYGON((1 1 1,0 0 1, -1 1 1, 1 1 1))'))); st_asewkt ----------------------------------- LINESTRING(1 1 1,0 0 1,-1 1 1,1 1 1) --Using a 3d multilinestring SELECT ST_AsEWKT(ST_Boundary(ST_GeomFromEWKT('MULTILINESTRING((1 1 1,0 0 0.5, -1 1 1),(1 1 0.5,0 0 0.5, -1 1 0.5, 1 1 0.5) )'))); st_asewkt ---------- MULTIPOINT((-1 1 1),(1 1 0.75))
ST_BoundingDiagonal — Retorna a diagonal da geometria fornecida da caixa limitada.
geometria ST_BoundingDiagonal(
geometria geom, booleana fits=false)
;
Retorna a diagonal da geometria fornecida da caixa limitada em linestring. Se a entrada da geometria está vazia, a linha diagonal também está, caso contrário é uma linestring de 2-pontos com valores mínimos de cada dimensão no ponto de início e com valores máximos no ponte de fim.
O parâmetro fits
especifica se o que se encaixa melhor é necessário. Se negativo, a diagonal de uma caixa limitadora de alguma forma pode ser aceita (é mais rápido obter para geometrias com muitos vértices). De qualquer forma, a caixa limitadora da linha diagonal retornada sempre cobre a geometria de entrada.
A linestring da geometria retornada sempre retém SRID e dimensionalidade (Z e M presentes) da geometria de entrada.
![]() | |
Em casos degenerados (um único vértice na entrada) a linestring retornada será topologicamente inválida (sem interior). Isso não não torna o retorno semanticamente inválido. |
Disponibilidade: 2.2.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_CoordDim — Retorna a dimensão da coordenada do valor ST_Geometry.
inteiro ST_CoordDim(
geometria geomA)
;
Retorna a dimensão da coordenada do valor ST_Geometry.
Esse é o pseudônimo condescendente do MM para ST_NDims
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3: 5.1.3
This method supports Circular Strings and Curves
This function supports 3d and will not drop the z-index.
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
ST_Dimension — Retorna a dimensão da coordenada do valor ST_Geometry.
inteiro ST_Dimension(
geometria g)
;
A dimensão herdada desse objeto geométrico, que deve ser menor que ou igual à dimensão coordenada. OGC SPEC s2.1.1.1 - retorna 0 para PONTO
, 1 para LINESTRING
, 2 para POLÍGONO
, e a dimensão mais larga dos componentes de uma COLEÇÃODEGEOMETRIA
. Se desconhecida (geometria vazia) nula é retornada.
This method implements the SQL/MM specification. SQL-MM 3: 5.1.2
Melhorias: 2.0.0 suporte para superfícies poliédricas e TINs foi introduzido. Não abre mais exceção se uma geometria vazia é dada.
![]() | |
Anterior à 2.0.0, essa função abre uma exceção se usada com uma geometria vazia. |
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.
geometria ST_Envelope(
geometria 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.
Melhorias: 2.0.0 suporte para superfícies poliédricas, triângulos e TIN introduzido.
Availability: PostGIS 1.0.0RC1. Requires PostgreSQL 7.3 or higher.
![]() | |
Anteriores a 1.3.4, essa função falha se usada com geometrias que contêm CURVAS. Isso é consertado em 1.3.4+ |
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
This function supports 3d and will not drop the z-index.
SELECT sometable.field1, sometable.field1, (ST_Dump(sometable.geom)).geom AS geom FROM sometable; -- Break a compound curve into its constituent linestrings and circularstrings SELECT ST_AsEWKT(a.geom), ST_HasArc(a.geom) FROM ( SELECT (ST_Dump(p_geom)).geom AS geom FROM (SELECT ST_GeomFromEWKT('COMPOUNDCURVE(CIRCULARSTRING(0 0, 1 1, 1 0),(1 0, 0 1))') AS p_geom) AS b ) AS a; st_asewkt | st_hasarc -----------------------------+---------- CIRCULARSTRING(0 0,1 1,1 0) | t LINESTRING(1 0,0 1) | f (2 rows)
-- Polyhedral surface example -- Break a Polyhedral surface into its faces SELECT 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 — Retorna um texto resumo dos conteúdos da geometria.
geometria ST_Points(
geometria 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.
Melhorias: 2.0.0 suporte para superfícies poliédricas, triângulos e TIN introduzido.
Disponibilidade: 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 — Retorna um texto resumo dos conteúdos da geometria.
geometria ST_Points(
geometria 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).
Retorna VERDADEIRO
se essa LINESTRING
for fechada e simples.
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.
Disponibilidade: 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.
geometria 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.
![]() | |
Isso não funcionará para MULTIPOLÍGONOS. Use em conjunção com ST_Dump para MULTIPOLÍGONOS. |
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 — Retorna o número de pontos em um valor ST_LineString ou ST_CircularString.
geometria ST_Points(
geometria geom )
;
Retorna ao último ponto de uma LINESTRING
ou CIRCULARLINESTRING
geometria como um PONTO
ou NULO
se o parâmetro de entrada não é uma LINESTRING
.
This method implements the SQL/MM specification. SQL-MM 3: 7.1.4
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
![]() | |
Alterações: 2.0.0 não funciona mais com geometrias de multilinestrings. Em verões mais antigas do PostGIS -- uma linha multilinestring sozinha trabalharia normalmente com essa função e voltaria o ponto de início. Na 2.0.0 ela retorna NULA como qualquer outra multilinestring. O antigo comportamento não foi uma característica documentada, mas as pessoas que consideravam que tinham seus dados armazenados como uma LINESTRING, agora podem experimentar essas que retornam NULAS em 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)
Retorna o número de pontos em um valor ST_LineString ou 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 — Retorna uma geometria representando a precisão da dobrada (float8) da caixa limitada da geometria fornecida.
geometria ST_Envelope(
geometria g1)
;
Retorna o limite mínimo da caixa float8 para a geometria fornecida, com uma geometria. O polígono é definido pelos pontos de canto da caixa limitada ((MINX
, MINY
), (MINX
, MAXY
), (MAXX
, MAXY
), (MAXX
, MINY
), (MINX
, MINY
)). (PostGIS irá adicionar uma ZMIN
/ZMAX
coordenada também).
Casos degenerados (linhas verticais, pontos) irão retornar como uma geometria de dimensão menor que POLÍGONO
, ie. PONTO
ou LINESTRING
.
Disponibilidade: 1.5.0 comportamento alterado para saída de precisão dupla ao invés 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 — Retorna o número de anéis interiores de um polígono.
geometria ST_ExteriorRing(
geometry a_polygon)
;
Retorna uma line string representando o anel exterior da geometria POLÍGONO
. Retorna NULA se a geometria não for um polígono.
![]() | |
Isso não funcionará para MULTIPOLÍGONOS. Use em conjunção com ST_Dump para MULTIPOLÍGONOS. |
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.
--If you have a table of polygons SELECT gid, ST_ExteriorRing(the_geom) AS ering FROM sometable; --If you have a table of MULTIPOLYGONs --and want to return a MULTILINESTRING composed of the exterior rings of each polygon SELECT gid, ST_Collect(ST_ExteriorRing(the_geom)) AS erings FROM (SELECT gid, (ST_Dump(the_geom)).geom As the_geom FROM sometable) As foo GROUP BY gid; --3d Example SELECT ST_AsEWKT( ST_ExteriorRing( ST_GeomFromEWKT('POLYGON((0 0 1, 1 1 1, 1 2 1, 1 1 1, 0 0 1))') ) ); st_asewkt --------- LINESTRING(0 0 1,1 1 1,1 2 1,1 1 1,0 0 1)
ST_GeometryN — Retorna o tipo de geometria de valor ST_Geometry.
geometria ST_GeometryN(
geometria geomA, inteiro n)
;
Retorna a geometria de 1-base Nth se a geometria é uma GEOMETRYCOLLECTION, (MULTI)POINT, (MULTI)LINESTRING, MULTICURVE ou (MULTI)POLYGON, POLYHEDRALSURFACE. Senão, retorna NULA.
![]() | |
O Index é 1-base como para OGC specs desde a versão 0.8.0. Versões anteriores implementaram isso como 0-base. |
![]() | |
Se você quiser extrair todas as geometrias, de uma geometria, ST_Dump é mais eficiente e também funcionará para geometrias singulares. |
Melhorias: 2.0.0 suporte para superfícies poliédricas, triângulos e TIN introduzido.
Alterações: 2.0.0. Versões anteriores voltariam NULAS para geometrias únicas. Isso foi alterado para volrtar a geometria para o caso ST_GeometryN(..,1).
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1.
This method implements the SQL/MM specification. SQL-MM 3: 9.1.5
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
--Extracting a subset of points from a 3d multipoint SELECT n, ST_AsEWKT(ST_GeometryN(geom, n)) As geomewkt FROM ( VALUES (ST_GeomFromEWKT('MULTIPOINT((1 2 7), (3 4 7), (5 6 7), (8 9 10))') ), ( ST_GeomFromEWKT('MULTICURVE(CIRCULARSTRING(2.5 2.5,4.5 2.5, 3.5 3.5), (10 11, 12 11))') ) )As foo(geom) CROSS JOIN generate_series(1,100) n WHERE n <= ST_NumGeometries(geom); n | geomewkt ---+----------------------------------------- 1 | POINT(1 2 7) 2 | POINT(3 4 7) 3 | POINT(5 6 7) 4 | POINT(8 9 10) 1 | CIRCULARSTRING(2.5 2.5,4.5 2.5,3.5 3.5) 2 | LINESTRING(10 11,12 11) --Extracting all geometries (useful when you want to assign an id) SELECT gid, n, ST_GeometryN(geom, n) FROM sometable CROSS JOIN generate_series(1,100) n WHERE n <= ST_NumGeometries(geom);
-- Polyhedral surface example -- Break a Polyhedral surface into its faces SELECT ST_AsEWKT(ST_GeometryN(p_geom,3)) As geom_ewkt FROM (SELECT ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )') AS p_geom ) AS a; geom_ewkt ------------------------------------------ POLYGON((0 0 0,1 0 0,1 0 1,0 0 1,0 0 0))
-- TIN -- SELECT ST_AsEWKT(ST_GeometryN(geom,2)) as wkt FROM (SELECT ST_GeomFromEWKT('TIN ((( 0 0 0, 0 0 1, 0 1 0, 0 0 0 )), (( 0 0 0, 0 1 0, 1 1 0, 0 0 0 )) )') AS geom ) AS g; -- result -- wkt ------------------------------------- TRIANGLE((0 0 0,0 1 0,1 1 0,0 0 0))
ST_GeometryType — Retorna o tipo de geometria de valor ST_Geometry.
texto ST_GeometryType(
geometria g1)
;
Retorna o tipo da geometria como uma string. EX: 'ST_LineString', 'ST_Polygon','ST_MultiPolygon' etc. Essa função difere de GeometryType(geometria) no caso da string e ST na frente que é retornada, bem como o fato que isso não indicará se a geometria é medida.
Melhorias: 2.0.0 suporte a superfícies poliédricas foi introduzido.
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)')); --result ST_LineString
SELECT ST_GeometryType(ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )')); --result ST_PolyhedralSurface
SELECT ST_GeometryType(ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )')); --result ST_PolyhedralSurface
SELECT ST_GeometryType(geom) as result FROM (SELECT ST_GeomFromEWKT('TIN ((( 0 0 0, 0 0 1, 0 1 0, 0 0 0 )), (( 0 0 0, 0 1 0, 1 1 0, 0 0 0 )) )') AS geom ) AS g; result -------- ST_Tin
ST_HasArc — Tests if a geometry contains a circular arc
booleana ST_IsEmpty(
geometria geomA)
;
Retorna verdadeiro se essa geometria é uma coleção vazia, polígono, ponto etc.
Disponibilidade: 1.2.2
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
ST_InteriorRingN — Retorna o número de anéis interiores de um polígono.
geometria ST_InteriorRingN(
geometria a_polygon, inteiro n)
;
Retorna o anel linestring Nth interior do polígono. Retorna NULO se a geometria não for um polígono ou o dado N está fora da extensão.
![]() | |
Isso não funcionará para MULTIPOLÍGONOS. Use em conjunção com ST_Dump para MULTIPOLÍGONOS. |
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 — Retorna VERDADEIRO
se os pontos de começo e fim da LINESTRING
são coincidentes. Para superfície poliédrica está fechada (volumétrica).
booleana ST_IsClosed(
geometria g)
;
Retorna VERDADEIRO
se os pontos de começo e fim da LINESTRING
são coincidentes. Para superfícies poliédricas, isso lhe diz se a superfície é territorial (aberta) ou volumétrica (fechada).
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 o resultado do |
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
Melhorias: 2.0.0 suporte a superfícies poliédricas foi introduzido.
This function supports Polyhedral surfaces.
postgis=# SELECT ST_IsClosed('LINESTRING(0 0, 1 1)'::geometry); st_isclosed ------------- f (1 row) postgis=# SELECT ST_IsClosed('LINESTRING(0 0, 0 1, 1 1, 0 0)'::geometry); st_isclosed ------------- t (1 row) postgis=# SELECT ST_IsClosed('MULTILINESTRING((0 0, 0 1, 1 1, 0 0),(0 0, 1 1))'::geometry); st_isclosed ------------- f (1 row) postgis=# SELECT ST_IsClosed('POINT(0 0)'::geometry); st_isclosed ------------- t (1 row) postgis=# SELECT ST_IsClosed('MULTIPOINT((0 0), (1 1))'::geometry); st_isclosed ------------- t (1 row)
-- A cube -- SELECT ST_IsClosed(ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )')); st_isclosed ------------- t -- Same as cube but missing a side -- SELECT ST_IsClosed(ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)) )')); st_isclosed ------------- f
ST_IsCollection — Retorna verdadeiro se essa geometria é uma coleção vazia, polígono, ponto etc.
booleana ST_IsCollection(
geometria g)
;
Retorna VERDADEIRO
se o tipo da geometria do argumento é:
COLEÇÃO DE GEOMETRIA
MULTI{PONTO, POLÍGONO, LINESTRING, CURVA, SUPERFÍCIE}
CURVA COMPOSTA
![]() | |
Essa função analisa o tipo da geometria. Isso significa que vai retornar |
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.
booleana ST_IsEmpty(
geometria geomA)
;
Retorna verdadeiro se essa geometria se é vazia. Se verdadeira, ela representa uma coleção vazia, polígono, ponto etc.
![]() | |
SQL-MM define o resultado da ST_IsEmpty(NULA) para ser 0, enquanto o PostGIS retorna NULO. |
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
![]() | |
Alterações: 2.0.0 Nas versões anteriores do PostGIS ST_GeomFromText('GEOMETRYCOLLECTION(EMPTY)') era permitido. Agora isso é ilegal no PostGIS 2.0.0 para se adequar aos padrões SQL/MM. |
SELECT ST_IsEmpty(ST_GeomFromText('GEOMETRYCOLLECTION EMPTY')); st_isempty ------------ t (1 row) SELECT ST_IsEmpty(ST_GeomFromText('POLYGON EMPTY')); st_isempty ------------ t (1 row) SELECT ST_IsEmpty(ST_GeomFromText('POLYGON((1 2, 3 4, 5 6, 1 2))')); st_isempty ------------ f (1 row) SELECT ST_IsEmpty(ST_GeomFromText('POLYGON((1 2, 3 4, 5 6, 1 2))')) = false; ?column? ---------- t (1 row) SELECT ST_IsEmpty(ST_GeomFromText('CIRCULARSTRING EMPTY')); st_isempty ------------ t (1 row)
ST_IsPolygonCCW — Tests if Polygons have exterior rings oriented counter-clockwise and interior rings oriented clockwise.
boolean ST_IsPolygonCCW (
geometry geom )
;
Returns true if all polygonal components of the input geometry use a counter-clockwise orientation for their exterior ring, and a clockwise direction for all interior rings.
Returns true if the geometry has no polygonal components.
![]() | |
Closed linestrings are not considered polygonal components, so you would still get a true return by passing a single closed linestring no matter its orientation. |
![]() | |
If a polygonal geometry does not use reversed orientation for interior rings (i.e., if one or more interior rings are oriented in the same direction as an exterior ring) then both ST_IsPolygonCW and ST_IsPolygonCCW will return false. |
Disponibilidade: 2.2.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_IsPolygonCW — Tests if Polygons have exterior rings oriented clockwise and interior rings oriented counter-clockwise.
boolean ST_IsPolygonCW (
geometry geom )
;
Returns true if all polygonal components of the input geometry use a clockwise orientation for their exterior ring, and a counter-clockwise direction for all interior rings.
Returns true if the geometry has no polygonal components.
![]() | |
Closed linestrings are not considered polygonal components, so you would still get a true return by passing a single closed linestring no matter its orientation. |
![]() | |
If a polygonal geometry does not use reversed orientation for interior rings (i.e., if one or more interior rings are oriented in the same direction as an exterior ring) then both ST_IsPolygonCW and ST_IsPolygonCCW will return false. |
Disponibilidade: 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.
booleana ST_IsRing(
geometria g)
;
Retorna VERDADEIRO
se essa LINESTRING
for ST_IsClosed (ST_StartPoint(
g
)~=
ST_Endpoint(
) e ST_IsSimple (não cruzar consigo mesma).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 o resultado do |
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 — Retorna (VERDADEIRA) se essa geometria não tem nenhum ponto irregular, como auto intersecção ou tangenciação.
booleana ST_IsSimple(
geometria geomA)
;
Retorna verdadeira se essa geometria não tem nenhum ponto geométrico irregular, como auto intersecção ou tangenciação. Para maiores informações na definição OGC da simplicidade e validade das geometrias, use "Ensuring OpenGIS compliancy of geometries"
![]() | |
SQL-MM define o resultado da ST_IsSimple(NULA) para ser 0, enquanto o PostGIS retorna NULO. |
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(
geometria a_point)
;
Retorna a coordenada M do ponto, ou NULA se não estiver disponível. Entrada deve ser um ponto.
![]() | |
Isso não faz parte (ainda) do OGC spec, mas está listado aqui para completar a função lista do ponto coordenado extrator. |
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 — Retorna o tipo de geometria de valor ST_Geometry.
inteiro ST_NRings(
geometria geomA)
;
Retorna o tipo de geometria de valor 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 — Retorna a dimensão da coordenada do valor ST_Geometry.
integer ST_NDims(
geometria g1)
;
Retorna a dimensão coordenada da geometria. O PostGIS suporta 2 - (x,y) , 3 - (x,y,z) ou 2D com medida - x,y,m, e 4 - 3D com espaço de medida x,y,z,m
This function supports 3d and will not drop the z-index.
ST_NPoints — Retorna o número de pontos (vértices) em uma geometria.
inteiro ST_NPoints(
geometria g1)
;
Retorna o número de pontos em uma geometria. Funciona para todas as geometrias.
Melhorias: 2.0.0 suporte a superfícies poliédricas foi introduzido.
![]() | |
Anteriores a 1.3.4, essa função falha se usada com geometrias que contêm CURVAS. Isso é consertado em 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 — Retorna o número de anéis interiores de um polígono.
inteiro ST_NRings(
geometria geomA)
;
Se a geometria for um polígono ou multi polígono, retorna o número de anéis. Diferente do NumInteriorRings, esse conta os anéis de fora também.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
ST_NumGeometries — Retorna o número de pontos em uma geometria. Funciona para todas as geometrias.
inteiro ST_NumGeometries(
geometria geom)
;
Retorna o número de geometrias. Se a geometria é uma GEOMETRYCOLLECTION (ou MULTI*), retorna o número de geometria, para geometrias únicas retornará 1, senão retorna NULO.
Melhorias: 2.0.0 suporte para superfícies poliédricas, triângulos e TIN introduzido.
Alterações: 2.0.0 Em versões anteriores retornaria NULO se a geometria não fosse do tipo coleção/MULTI. 2.0.0+ agora retorna 1 para geometrias únicas ex: POLÍGONO, LINESTRING, PONTO.
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 — Retorna o número de anéis interiores de um polígono.
inteiro ST_NumInteriorRings(
geometria a_polygon)
;
Retorna o número de anéis interiores de um polígono. Retorna NULO se a geometria não for um polígono.
This method implements the SQL/MM specification. SQL-MM 3: 8.2.5
Alterações: 2.0.0 - nas versões anteriores isso permitiria um MULTIPOLÍGONO, retornando o número de anéis interiores do primeiro POLÍGONO.
--If you have a regular polygon SELECT gid, field1, field2, ST_NumInteriorRings(the_geom) AS numholes FROM sometable; --If you have multipolygons --And you want to know the total number of interior rings in the MULTIPOLYGON SELECT gid, field1, field2, SUM(ST_NumInteriorRings(the_geom)) AS numholes FROM (SELECT gid, field1, field2, (ST_Dump(the_geom)).geom As the_geom FROM sometable) As foo GROUP BY gid, field1,field2;
ST_NumInteriorRing — Retorna o número de anéis interiores de um polígono na geometria. Sinônimo para ST_NumInteriorRings.
inteiro ST_NumInteriorRing(
geometria a_polygon)
;
ST_NumPatches — Retorna o número de faces em uma superfícies poliédrica. Retornará nulo para geometrias não poliédricas.
inteiro ST_NumPatches(
geometria g1)
;
Retorna o número de faces em uma superfície poliédrica. Retornará nulo para geometrias não poliédricas. Isso é um heterônimo para ST_NumGeometries para suportar a nomeação MM. É mais rápido utilizar ST_NumGeometries se você não se importa com a convenção MM.
Disponibilidade: 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 — Retorna o número de pontos em um valor ST_LineString ou ST_CircularString.
inteiro ST_NumPoints(
geometria g1)
;
Retorna o número de pontos em um valor ST_LineString ou ST_CircularString. Anteriores a 1.4 só funcionam com Linestrings como as specs declaram. A partir de 1.4 isso é um heterônimo para ST_NPoints, que retorna o número de vértices apenas para as line strings. Considere utilizar ST_NPoints que tem vários objetivos e funciona com vários tipos de geometrias.
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 — Retorna o tipo de geometria de valor ST_Geometry.
geometria ST_PatchN(
geometria geomA, inteiro n)
;
> Retorna a geometria (face) de 1-base Nth se a geometria é POLYHEDRALSURFACE, POLYHEDRALSURFACEM. Senão, retorna NULA. Retorna a mesma resposta como ST_GeometryN para superfícies poliédricas. Utilizar ST_GemoetryN é mais rápido.
![]() | |
Index é 1-base. |
![]() | |
Se você quiser extrair todas as geometrias, de uma geometria, ST_Dump é mais eficiente. |
Disponibilidade: 2.0.0
This method implements the SQL/MM specification. SQL-MM ISO/IEC 13249-3: 8.5
This function supports 3d and will not drop the z-index.
This function supports Polyhedral surfaces.
--Extract the 2nd face of the polyhedral surface SELECT ST_AsEWKT(ST_PatchN(geom, 2)) As geomewkt FROM ( VALUES (ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )')) ) As foo(geom); geomewkt ---+----------------------------------------- POLYGON((0 0 0,0 1 0,1 1 0,1 0 0,0 0 0))
ST_PointN — Retorna o número de pontos em um valor ST_LineString ou ST_CircularString.
geometria ST_PointN(
geometria a_linestring, inteiro n)
;
Retorna o ponto Nth na primeira linestring ou linestring circular na geometria. Valores negativos são contados tardiamente do fim da linestring, tornando o ponto -1 o último ponto. Retorna NULA se não há uma linestring na geometria.
![]() | |
O Index é 1-base como para OGC specs desde a versão 0.8.0. Indexing atrasado (negativo) não está nas versões OGC anteriores implementadas com 0-base. |
![]() | |
Se você quiser o ponto nth de cada line string em uma multilinestring, utilize em conjunção com 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
![]() | |
Alterações: 2.0.0 não funciona mais com geometrias multilinestrings únicas. Em verões mais antigas do PostGIS -- uma única linha multilinestring trabalharia normalmente e retornaria o ponto inicial. Na 2.0.0 só retorna NULA como qualquer outra multilinestring. Alterações: 2.3.0 : indexing negativo disponível (-1 é o último ponto) |
-- Extract all POINTs from a LINESTRING SELECT ST_AsText( ST_PointN( column1, generate_series(1, ST_NPoints(column1)) )) FROM ( VALUES ('LINESTRING(0 0, 1 1, 2 2)'::geometry) ) AS foo; st_astext ------------ POINT(0 0) POINT(1 1) POINT(2 2) (3 rows) --Example circular string SELECT ST_AsText(ST_PointN(ST_GeomFromText('CIRCULARSTRING(1 2, 3 2, 1 2)'),2)); st_astext ---------- POINT(3 2) SELECT st_astext(f) FROM ST_GeometryFromtext('LINESTRING(0 0 0, 1 1 1, 2 2 2)') as g ,ST_PointN(g, -2) AS f -- 1 based index st_astext ---------- "POINT Z (1 1 1)"
ST_Points — Retorna uma multilinestring contendo todas as coordenadas de uma geometria.
geometria ST_Points(
geometria 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.
Disponibilidade: 2.3.0
ST_StartPoint — Returns the first point of a LineString.
geometria ST_StartPoint(
geometria geomA)
;
Retorna ao último ponto de uma LINESTRING
ou CIRCULARLINESTRING
geometria como um PONTO
ou NULO
se o parâmetro de entrada não é uma LINESTRING
.
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. Alterações: 2.0.0 não funciona mais com geometrias de multilinestrings. Em verões mais antigas do PostGIS -- uma linha multilinestring sozinha trabalharia normalmente com essa função e voltaria o ponto de início. Na 2.0.0 ela retorna NULA como qualquer outra multilinestring. O antigo comportamento não foi uma característica documentada, mas as pessoas que consideravam que tinham seus dados armazenados como uma LINESTRING, agora podem experimentar essas que retornam NULAS em 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)
Retorna o número de pontos em um valor ST_LineString ou 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 — Retorna um texto resumo dos conteúdos da geometria.
texto ST_Summary(
geometria g)
;
text ST_Summary(
geografia g)
;
Retorna um texto resumo dos conteúdos da geometria.
As bandeiras mostraram colchetes depois do tipo de geometria ter o seguinte significado:
M: tem ordenada M
Z: tem ordenada Z
B: tem uma caixa limitante salva
G: é geodésico (geografia)
S: tem um sistema de referência espacial
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
Disponibilidade: 1.2.2
Melhorias: 2.0.0 suporte para geografia adicionado
melhorias: 2.1.0 Bandeira S para indicar se existe um sistema de referência espacial conhecido
Melhorias: 2.2.0 Suporte para TIN e Curvas adicionado
=# 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(
geometria a_point)
;
Retorna a coordenada X do ponto, ou NULA se não estiver disponível. Entrada deve ser um ponto.
![]() | |
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(
geometria a_point)
;
Retorna a coordenada Y do ponto, ou NULA se não estiver disponível. Entrada deve ser um ponto.
![]() | |
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(
geometria a_point)
;
Retorna a coordenada Z do ponto, ou NULA se não estiver disponível. Entrada deve ser um ponto.
![]() | |
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 — Retorna a dimensão da coordenada do valor ST_Geometry.
smallint ST_Zmflag(
geometria geomA)
;
Retorna a dimensão da coordenada do valor 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 — Adicione um ponto para uma LineString.
geometry ST_AddPoint(
geometry linestring, geometry point)
;
geometry ST_AddPoint(
geometry linestring, geometry point, integer position = -1)
;
Adds a point to a LineString before the index position
(using a 0-based index). If the position
parameter is omitted or is -1 the point is appended to the end of the LineString.
Disponibilitade: 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. |
Disponibilidade: 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)
;
Dada uma coleção geométrica, retorna a representação mais simples de seu conteúdo.
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. |
Disponibilidade: 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).
Disponibilidade: 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 — Força a geometria para o modo de 2 dimensões.
geometry ST_Force2D(
geometry geomA)
;
Força a geometria a possuir apenas duas dimensões, para que todas saídas tenham apenas as coordenadas X e Y. Esta função é útil para forçar geometrias de acordo a norma OGC (a OGC apenas especifica geometrias de duas dimensões).
Melhorias: 2.0.0 suporte a superfícies polihédricas foi introduzido.
Alterado: 2.1.0. Até versão 2.0.x isto era chamado de 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 — Força a geometria para um modo XYZ. Este é um apelido para a função ST_Force_3DZ.
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.
Melhorias: 2.0.0 suporte a superfícies polihédricas foi introduzido.
Alterado: 2.1.0. Até versão 2.0.x isto era chamado de 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 acontece com uma geometria que já é 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 — Força as geometrias para o 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.
Melhorias: 2.0.0 suporte a superfícies polihédricas foi introduzido.
Alterado: 2.1.0. Até versão 2.0.x isto era chamado de ST_Force_3DZ.
Changed: 3.1.0. Added support for supplying a non-zero Z value.
This function supports Polyhedral surfaces.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
--Nothing happens to an already 3D geometry SELECT ST_AsEWKT(ST_Force3DZ(ST_GeomFromEWKT('CIRCULARSTRING(1 1 2, 2 3 2, 4 5 2, 6 7 2, 5 6 2)'))); st_asewkt ----------------------------------------------- CIRCULARSTRING(1 1 2,2 3 2,4 5 2,6 7 2,5 6 2) SELECT ST_AsEWKT(ST_Force3DZ('POLYGON((0 0,0 5,5 0,0 0),(1 1,3 1,1 3,1 1))')); st_asewkt -------------------------------------------------------------- POLYGON((0 0 0,0 5 0,5 0 0,0 0 0),(1 1 0,3 1 0,1 3 0,1 1 0))
ST_Force3DM — Força as geometrias para o 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
Alterado: 2.1.0. Até a versão 2.0.x esta função era chamada de ST_Force_3DM.
Changed: 3.1.0. Added support for supplying a non-zero M value.
This method supports Circular Strings and Curves
--Nada ocorre com uma geometria já 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 — Força as geometrias para o 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.
Alterado: 2.1.0. Até a versão 2.0.x esta função era chamada 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 ocorre com uma geometria já 4D. SELECT ST_AsEWKT(ST_Force4D(ST_GeomFromEWKT('CIRCULARSTRING(1 1 2, 2 3 2, 4 5 2, 6 7 2, 5 6 2)'))); st_asewkt --------------------------------------------------------- CIRCULARSTRING(1 1 2 0,2 3 2 0,4 5 2 0,6 7 2 0,5 6 2 0) SELECT ST_AsEWKT(ST_Force4D('MULTILINESTRINGM((0 0 1,0 5 2,5 0 3,0 0 4),(1 1 1,3 1 1,1 3 1,1 1 1))')); st_asewkt -------------------------------------------------------------------------------------- MULTILINESTRING((0 0 0 1,0 5 0 2,5 0 0 3,0 0 0 4),(1 1 0 1,3 1 0 1,1 3 0 1,1 1 0 1))
ST_ForcePolygonCCW — Orients all exterior rings counter-clockwise and all interior rings clockwise.
geometry ST_ForcePolygonCCW (
geometry geom )
;
Forces (Multi)Polygons to use a counter-clockwise orientation for their exterior ring, and a clockwise orientation for their interior rings. Non-polygonal geometries are returned unchanged.
Availability: 2.4.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_ForceCollection — Converte a geometria para um GEOMETRYCOLLECTION.
geometry ST_ForceCollection(
geometry geomA)
;
Converte a geometria em um GEOMETRYCOLLECTION. Isto é útil para simplificar a representação WKB.
Melhorias: 2.0.0 suporte a superfícies polihédricas foi introduzido.
Disponibilidade: 1.2.2, antes da versão 1.3.4 esta função irá reportar um erro com curvas. Resolvido na versão 1.3.4+.
Alterado: 2.1.0. Até a versão 2.0.x esta função era chamada de 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)
-- exemplo 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 — Orients all exterior rings clockwise and all interior rings counter-clockwise.
geometry ST_ForcePolygonCW (
geometry geom )
;
Forces (Multi)Polygons to use a clockwise orientation for their exterior ring, and a counter-clockwise orientation for their interior rings. Non-polygonal geometries are returned unchanged.
Availability: 2.4.0
This function supports 3d and will not drop the z-index.
This function supports M coordinates.
ST_ForceSFS — Força as geometrias a utilizarem os tipos disponíveis na especificação SFS 1.1.
geometry ST_ForceSFS(
geometry geomA)
;
geometry ST_ForceSFS(
geometry geomA, text version)
;
ST_ForceRHR — Força a orientação dos vértices em um polígono a seguir a regra da mão direita.
geometry ST_ForceRHR(
geometry g)
;
Forces the orientation of the vertices in a polygon to follow a Right-Hand-Rule, in which the area that is bounded by the polygon is to the right of the boundary. In particular, the exterior ring is orientated in a clockwise direction and the interior rings in a counter-clockwise direction. This function is a synonym for ST_ForcePolygonCW
![]() | |
The above definition of the Right-Hand-Rule conflicts with definitions used in other contexts. To avoid confusion, it is recommended to use ST_ForcePolygonCW. |
Melhorias: 2.0.0 suporte a superfícies polihédricas foi introduzido.
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 — Converte para cima uma geometria para seu tipo curvo, se aplicável.
geometry ST_ForceCurve(
geometry g)
;
Transforma uma geometria em sua representação curva, se aplicável. linhas se transformar em compoundcurves, multi-linhas se transformam em multicurves, polígonos em curvepolygons, multi-polígonos em multisurfaces. Se a entrada já é do tipo curvo, a função retorna a mesma entrada·
Disponibilidade: 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 — Restitui a geometria como uma MULTI* geometria.
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 — Retorna a geometria na sua forma canônica.
geometry ST_Normalize(
geometry geom)
;
Retorna a geometria na sua forma normalizada/canônica. Talvez rearranja vértices em anéis de polígonos, anéis em um polígono, elementos em um complexo de multi-geometria.
Mais usada para teste (comparando resultados obtidos e esperados).
Disponibilidade: 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
Disponibilitade: 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
Disponibilidade: 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 — Retorna a geometria com a ordem dos vértices revertida.
geometry ST_Reverse(
geometry g1)
;
ST_Segmentize — Retorna uma geometria/geografia alterada não tendo nenhum segmento maior que a distância dada.
geometry ST_Segmentize(
geometry geom, float max_segment_length)
;
geography ST_Segmentize(
geography geog, float max_segment_length)
;
Retorna a geometria alterada não tendo nenhum segmento maior que o dado max_segment_length
. O cáculo de distância é efetuado somente no 2o dia. Para geometria, unidades de comprimento estão em unidades de referência espacial. Para geografia, unidades estão em metros.
Disponibilidade: 1.2.2
Enhanced: 3.0.0 Segmentize geometry now uses equal length segments
Enhanced: 2.3.0 Segmentize geography now uses equal length segments
Melhorias: 2.1.0 suporte para geografia foi introduzido.
Alteração: 2.1.0 Como um resultado da introdução do suporte de geografia: A construção SELECT ST_Segmentize('LINESTRING(1 2, 3 4)',0.5);
irá resultar em uma função de erro ambíguo. Você precisa ter o objeto propriamente digitado ex. uma coluna geometria/geografia, use ST_GeomFromText, ST_GeogFromText or SELECT ST_Segmentize('LINESTRING(1 2, 3 4)'::geometry,0.5);
![]() | |
Isso só irá aumentar segmentos. Não irá alongar segmentos menores que o comprimento máximo |
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 — Substitui ponto de uma linestring com um dado ponto.
geometry ST_SetPoint(
geometry linestring, integer zerobasedposition, geometry point)
;
Substitui ponto N de linstring com um dado ponto. Index é de base 0. Index negativo são contados atrasados, logo -1 é o último ponto. Isso é especialmente usado em causas tentando manter relações juntas quando um vértice se move.
Disponibilitade: 1.1.0
Atualizado 2.3.0: indexing negativo
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 impediu de funcionar para MULTIPONTO. 1.3.4+ funciona com MULTIPONTO também. |
This function supports 3d and will not drop the z-index.
Melhorias: 2.0.0 suporte para superfícies poliédricas e TIN foi introduzido.
NOTA: esta função foi renomeada da "ST_Shift_Longitude" em 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 — Envolve uma geometria em torno de um valor X.
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.
![]() | |
Isto é útil para "recenter" entrada de long-lat para ter características de interesse não gerados de um lado para o outro. |
Availability: 2.3.0 requires GEOS
This function supports 3d and will not drop the z-index.
ST_SnapToGrid — Rompe todos os pontos da geometria de entrada para uma rede 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)
;
Variante1,2,3: Rompe todos os pontos da geometria de entrada para a rede definida por sua origem e tamanho da célula. Remove pontos consecutivos caindo na mesma célula, finalmente retornando NULO se os pontos de saída não são suficientes para definir uma geometria do tipo dado. Geometrias colapsadas em uma coleção são desguarnecidas disso. Útil para reduzi a precisão.
Variante4: Introduzido 1.1.0 - Rompe todos os pontos da geometria de entrada para a rede definida por sua origem (o segundo argumento deve ser um ponto) e tamanhos de células. Especifica 0 como um tamanho para qualquer dimensão que você não quer romper para uma rede.
![]() | |
A geometria de retorno pode perder sua simplicidade (veja ST_IsSimple). |
![]() | |
Antes de lançar 1.1.0, essa função sempre retornou uma geometria 2d. Começando em 1.1.0 a geometria de retorno terá a mesma dimensionalidade da entrada com maiores valores intocados de dimensão. Use a versão pegando um segundo argumento de geometria para definir todas as dimensões de rede. |
Disponibilidade: 1.0.0RC1
Disponibilidade: 1.1.0 - suporte a Z e 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 — Rompe segmentos e vértices de geometria de entrada para vértices de uma geometria de referência.
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.
Romper uma geometria para outra pode melhorar robusteza para operações de cobertura eliminando limites quase coincidentes (os quais causam problemas durante o sinal e cálculo de intersecção).
Romper muito pode resultar na criação de topologia inválida, então o número e localização dos vértices rompidos são decididos usando heurísticos para determinar quando é seguro romper. Entretanto, isso pode resultar em alguns rompimentos potencialmente omitidos.
![]() | |
A geometria devolvida pode perder sua simplicidade (veja ST_IsSimple) e validade (veja ST_IsValid). |
Desempenhado pelo módulo GEOS.
Disponibilidade: 2.0.0
![]() Um multi polígono apresentado com uma linestring (antes de qualquer rompimento) | |
![]() Um multi polígono rompido para linestring para tolerância: 1.01 de distância. O novo multi polígono é mostrado com linestring de referência
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))) | ![]() Um multi polígono rompido para linestring para tolerância: 1.25 de distância. O novo multi polígono é mostrado com linestring de referência
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))) |
![]() A linestring rompida para o multi polígono original em tolerância de 1.01 de distância. As nova linestring é mostrada com multi polígono de referência
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)
| ![]() A linestring rompida para o polígono original de tolerância 1.25 de distância. A nova linestring é mostrada com multi polígono de referência
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 — Retorna uma versão da geometria dada com os valores ordenados dados trocados.
geometry ST_SwapOrdinates(
geometry geom, cstring ords)
;
Retorna uma versão da geometria dada com as ordenadas dadas trocadas.
O parâmetro ords
é uma string de 2-caracteres nomeando as ordenadas para trocar. Os nomes válidos são: x,y,z e m.
Disponibilidade: 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, “The SPATIAL_REF_SYS Table and 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 — Constrói um polígono dada uma coleção arbitrária de linestrings fechadas como uma representação de texto de uma multilinestring bem conhecida.
geometria ST_BdPolyFromText(
texto WKT, inteiro srid)
;
Constrói um polígono dada uma coleção arbitrária de linestrings fechadas como uma representação de texto de uma multilinestring bem conhecida.
![]() | |
Lança um erro se WKT não é uma MULTILINESTRING. Lança um erro se a saída não é um MULTIPOLÍGONO; use ST_BdMPolyFromText nesse caso, ou veja ST_BuildArea() para uma aproximação postgis-specific. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.6.2
Desempenhado pelo módulo GEOS.
Disponibilidade: 1.1.0
ST_BdMPolyFromText — Constrói um polígono dada uma coleção arbitrária de linestrings fechadas como uma representação de texto de uma multilinestring bem conhecida.
geometria ST_BdMPolyFromText(
text WKT, inteiro srid)
;
Constrói um um polígono dada uma coleção arbitrária de linestrings, polígonos, multilinestrings fechados como uma representação de texto bem conhecida.
![]() | |
Lança um erro se WKT não é uma MULTILINESTRING. Força a saída MULTIPOLÍGONO mesmo quando o resultado não é composto somente por um POLÍGONO único; use ST_BdPolyFromText se você tem certeza de que um único POLÍGONO irá resultar de uma operação, ou veja ST_BuildArea() para uma aproximação postgis-specific. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.6.2
Desempenhado pelo módulo GEOS.
Disponibilidade: 1.1.0
ST_GeogFromText — Retorna um valor de geografia específico de uma representação bem conhecida de texto ou estendida (WKT).
geografia ST_GeogFromText(
texto EWKT)
;
Retorna um objeto de geografia de um texto bem conhecido ou representação estendida bem conhecida. SRID 4326 é suposta se não for especificada. Isso é um heterônimo para ST_GeographyFromText. Os pontos são sempre expressados em uma forma long lat.
--- converting lon lat coords to geography ALTER TABLE sometable ADD COLUMN geog geography(POINT,4326); UPDATE sometable SET geog = ST_GeogFromText('SRID=4326;POINT(' || lon || ' ' || lat || ')'); --- specify a geography point using EPSG:4267, NAD27 SELECT ST_AsEWKT(ST_GeogFromText('SRID=4267;POINT(-77.0092 38.889588)'));
ST_GeographyFromText — Retorna um valor de geografia específico de uma representação bem conhecida de texto ou estendida (WKT).
geografia ST_GeographyFromText(
texto EWKT)
;
ST_GeomCollFromText — Makes a collection Geometry from collection WKT with the given SRID. If SRID is not given, it defaults to 0.
geometria ST_GeomCollFromText(
text WKT, inteiro srid)
;
geometria ST_GeomCollFromText(
texto WKT)
;
Makes a collection Geometry from the Well-Known-Text (WKT) representation with the given SRID. If SRID is not given, it defaults to 0.
OGC SPEC 3.2.6.2 - opção SRID é de uma suíte de conformação
Retorna nula se a WKT não for uma GEOMETRYCOLLECTION
![]() | |
se você não tem total certeza de que todas suas geometrias WKT são coleções, não use essa função. Ela é mais devagar que a ST_GeomFromText, já que adiciona um passo de validação adicional. |
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 — Retorna um valor ST_Geometry especifico da representação de texto estendida bem conhecida (EWKT).
geometria ST_GeomFromEWKT(
texto EWKT)
;
Constrói um objeto PostGIS ST_Geometry da representação de texto estendida bem conhecida OGC (EWKT).
![]() | |
O formato EWKT não é um padrão OGC, mas um formato específico PostGIS que inclui o identificador de sistema de referência espacial (SRID). |
Melhorias: 2.0.0 suporte para superfícies poliédricas e TIN foi introduzido.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
SELECT ST_GeomFromEWKT('SRID=4269;LINESTRING(-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932)'); SELECT ST_GeomFromEWKT('SRID=4269;MULTILINESTRING((-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932))'); SELECT ST_GeomFromEWKT('SRID=4269;POINT(-71.064544 42.28787)'); SELECT ST_GeomFromEWKT('SRID=4269;POLYGON((-71.1776585052917 42.3902909739571,-71.1776820268866 42.3903701743239, -71.1776063012595 42.3903825660754,-71.1775826583081 42.3903033653531,-71.1776585052917 42.3902909739571))'); SELECT ST_GeomFromEWKT('SRID=4269;MULTIPOLYGON(((-71.1031880899493 42.3152774590236, -71.1031627617667 42.3152960829043,-71.102923838298 42.3149156848307, -71.1023097974109 42.3151969047397,-71.1019285062273 42.3147384934248, -71.102505233663 42.3144722937587,-71.10277487471 42.3141658254797, -71.103113945163 42.3142739188902,-71.10324876416 42.31402489987, -71.1033002961013 42.3140393340215,-71.1033488797549 42.3139495090772, -71.103396240451 42.3138632439557,-71.1041521907712 42.3141153348029, -71.1041411411543 42.3141545014533,-71.1041287795912 42.3142114839058, -71.1041188134329 42.3142693656241,-71.1041112482575 42.3143272556118, -71.1041072845732 42.3143851580048,-71.1041057218871 42.3144430686681, -71.1041065602059 42.3145009876017,-71.1041097995362 42.3145589148055, -71.1041166403905 42.3146168544148,-71.1041258822717 42.3146748022936, -71.1041375307579 42.3147318674446,-71.1041492906949 42.3147711126569, -71.1041598612795 42.314808571739,-71.1042515013869 42.3151287620809, -71.1041173835118 42.3150739481917,-71.1040809891419 42.3151344119048, -71.1040438678912 42.3151191367447,-71.1040194562988 42.3151832057859, -71.1038734225584 42.3151140942995,-71.1038446938243 42.3151006300338, -71.1038315271889 42.315094347535,-71.1037393329282 42.315054824985, -71.1035447555574 42.3152608696313,-71.1033436658644 42.3151648370544, -71.1032580383161 42.3152269126061,-71.103223066939 42.3152517403219, -71.1031880899493 42.3152774590236)), ((-71.1043632495873 42.315113108546,-71.1043583974082 42.3151211109857, -71.1043443253471 42.3150676015829,-71.1043850704575 42.3150793250568,-71.1043632495873 42.315113108546)))');
--3d circular string SELECT ST_GeomFromEWKT('CIRCULARSTRING(220268 150415 1,220227 150505 2,220227 150406 3)');
--Polyhedral Surface example SELECT ST_GeomFromEWKT('POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)), ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)), ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)), ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)), ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )');
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 — Retorna um valor ST_Geometry especifico da representação de texto estendida bem conhecida (EWKT). Isso é um heterônimo para ST_GeomFromText
geometria ST_GeometryFromText(
texto WKT)
;
geometria ST_GeometryFromText(
texto WKT, inteiro 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 — Retorna um valor ST_Geometry específico da representação de texto bem conhecida (WKT).
geometria ST_GeomFromText(
texto WKT)
;
geometria ST_GeomFromText(
texto WKT, inteiro srid)
;
Constrói um objeto PostGIS ST_Geometry de uma representação de texto bem conhecida OGC.
![]() | |
Existem duas variantes da função ST_GeomFromText. A primeira não pega nenhuma SRID e retorna uma geometria com um sistema de referência espacial indefinido (SRID=0). A segunda pega uma SRID como o segundo argumento e retorna uma geometria que inclui essa SRID como parte dos seus metadados. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.6.2 - opção SRID é da suíte de conformidade.
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. |
![]() | |
Alterações: 2.0.0 Nas primeiras versões do PostGIS, ST_GeomFromText('GEOMETRYCOLLECTION(EMPTY)') foi permitida. Ela agora é ilegal no PostGIS 2.0.0 para melhor se adequar aos padrões SQL/MM. Ela deverá se escrita 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 — Faz uma geometria de uma representação WKT com a SRID dada. Se a SRID não for dada, isso leva a 0.
geometria ST_LineFromText(
texto WKT)
;
geometria ST_LineFromText(
texto WKT, inteiro srid)
;
Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0. If WKT passed in is not a LINESTRING, then null is returned.
![]() | |
OGC SPEC 3.2.6.2 - opção SRID é de uma suíte de conformação. |
![]() | |
Se você sabe que todas as suas geometrias são LINESTRINGS, é mais eficiente usar somente ST_GeomFromText. Isso só convida a ST_GeomFromText e adiciona validação extra que ela retorna uma 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 — Retorna um valor específico ST_MultiLineString de uma representação WKT.
geometria ST_MLineFromText(
texto WKT, integer srid)
;
geometria ST_MLineFromText(
texto WKT)
;
Makes a Geometry from Well-Known-Text (WKT) with the given SRID. If SRID is not given, it defaults to 0.
OGC SPEC 3.2.6.2 - opção SRID é de uma suíte de conformação
Retorna nulo se o WKT não é uma MULTILIINESTRING
![]() | |
Se você tem total certeza de que todas suas geometrias WKT são pontos, não use essa função. Ela é mais devagar que a ST_GeomFromText, já que adiciona um passo de validação adicional. |
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 — Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.
geometry ST_MPointFromText(
text WKT, integer srid)
;
geometry ST_MPointFromText(
text WKT)
;
Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.
OGC SPEC 3.2.6.2 - opção SRID é de uma suíte de conformação
Retorna nulo se o WKT não é um MULTIPONTO
![]() | |
Se você tem total certeza de que todas suas geometrias WKT são pontos, não use essa função. Ela é mais devagar que a ST_GeomFromText, já que adiciona um passo de validação adicional. |
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 — Makes a MultiPolygon Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.
geometria ST_MPolyFromText(
text WKT, inteiro srid)
;
geometria ST_MPolyFromText(
texto WKT)
;
Makes a MultiPolygon from WKT with the given SRID. If SRID is not given, it defaults to 0.
OGC SPEC 3.2.6.2 - opção SRID é de uma suíte de conformação
Descarta um erro se o WKT não for um MULTIPOLÍGONO
![]() | |
Se você tem total certeza de que todas suas geometrias WKT são multipolígonos, não use essa função. Ela é mais devagar que a ST_GeomFromText, já que adiciona um passo de validação adicional. |
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 — Faz um ponto de um WKT com o SRID dado. Se o SRID não for dado, isso leva a desconhecido.
geometry ST_PointFromText(
texto WKT)
;
geometria ST_PointFromText(
texto WKT, inteiro srid)
;
Constructs a PostGIS ST_Geometry point object from the OGC Well-Known text representation. If SRID is not given, it defaults to unknown (currently 0). If geometry is not a WKT point representation, returns null. If completely invalid WKT, then throws an error.
![]() | |
Existem 2 variantes da função ST_PointFromText, a primeira não pega nenhuma SRID e retorna uma geometria sem sistema de referência espacial definido. A segunda, pega uma id referência espacial como o segundo argumento e retorna uma ST_Geometry que inclui esse srid como parte dos seus metadados. O srid deve ser definido na spatial_ref_sys table. |
![]() | |
Se você tem total certeza de que todas suas geometrias WKT são pontos, não use essa função. Ela é mais devagar que a ST_GeomFromText, já que adiciona um passo de validação adicional. Se você está construindo pontos de coordenadas long lat e se importa mais com apresentação e precisão do que com concordância OGC, use: ST_MakePoint ou ST_Point. |
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.6.2 - opção SRID é da suíte de conformidade.
This method implements the SQL/MM specification. SQL-MM 3: 6.1.8
ST_PolygonFromText — Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0.
geometry ST_PolygonFromText(
text WKT)
;
geometry ST_PolygonFromText(
text WKT, integer srid)
;
Makes a Geometry from WKT with the given SRID. If SRID is not given, it defaults to 0. Returns null if WKT is not a polygon.
OGC SPEC 3.2.6.2 - opção SRID é de uma suíte de conformação
![]() | |
Se você tem total certeza de que todas suas geometrias WKT são polígonos, não use essa função. Ela é mais devagar que a ST_GeomFromText, já que adiciona um passo de validação adicional. |
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
de uma WKB com o SRID dadoST_GeogFromWKB — Cria uma ocasião geografia de uma geometria binária bem conhecida (WKB) ou binário estendido bem conhecido (EWKB).
geografia ST_GeogFromWKB(
bytea wkb)
;
A função ST_GeogFromWKB
, pega uma representação binária bem conhecida (WKB) de uma geometria ou WKB estendida do POstGIS e cria uma ocasião do tipo de geografia apropriado. Essa função cumpre o papel da Fábrica de Geometria em SQL.
Se a SRID não está especificado, isso leva a 4326 (WGS 84 long lat).
This method supports Circular Strings and Curves
--Although bytea rep contains single \, these need to be escaped when inserting into a table SELECT ST_AsText( ST_GeogFromWKB(E'\\001\\002\\000\\000\\000\\002\\000\\000\\000\\037\\205\\353Q\\270~\\\\\\300\\323Mb\\020X\\231C@\\020X9\\264\\310~\\\\\\300)\\\\\\217\\302\\365\\230C@') ); st_astext ------------------------------------------------------ LINESTRING(-113.98 39.198,-113.981 39.195) (1 row)
ST_GeomFromEWKB — Retorna um valor ST_Geometry especifico da representação binária estendida bem conhecida (EWKB).
geometria ST_GeomFromEWKB(
bytea EWKB)
;
Constrói um objeto PostGIS ST_Geometry da representação binária estendida bem conhecida OGC (EWKT).
![]() | |
O formato EWKB não é um padrão OGC, mas um formato específico PostGIS que inclui o identificador de sistema de referência espacial (SRID). |
Melhorias: 2.0.0 suporte para superfícies poliédricas e TIN foi introduzido.
This function supports 3d and will not drop the z-index.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
This function supports Triangles and Triangulated Irregular Network Surfaces (TIN).
line string binary rep 0f LINESTRING(-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932) in NAD 83 long lat (4269).
![]() | |
NOTA: Mesmo que os byte arrays seja delimitados com \ e talvez tenham ', precisamos escapar ambos com \ e " se as standard_conforming_strings estão deligadas. então, isso não parece exatamente como uma representação 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@');
![]() | |
In PostgreSQL 9.1+ - standard_conforming_strings is set to on by default, where as in past versions it was set to off. You can change defaults as needed for a single query or at the database or server level. Below is how you would do it with standard_conforming_strings = on. In this case we escape the ' with standard ansi ', but slashes are not escaped |
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 — Criar uma geometria exemplo de um representação bem conhecida de geometria binária (WKB) e SRID opcional.
geometria ST_GeomFromWKB(
bytea geom)
;
geometry ST_GeomFromWKB(
bytea geom, inteiro srid)
;
A função ST_GeomFromWKB
, pega uma representação binária bem conhecida de uma geometria e um sistema de referência espacial ID (SRID
) e cria um exemplo do tipo apropriado de geometria. Essa função cumpre o papel da Fábrica de Geometria na SQL. Isso é um nome alternativo para ST_WKBToSQL.
Se o SRID não for especificado, leva a 0 (desconhecido).
This method implements the OGC Simple Features
Implementation Specification for SQL 1.1. s3.2.7.2 - o SRID opcional é da suíte de conformidade.
This method implements the SQL/MM specification. SQL-MM 3: 5.1.41
This method supports Circular Strings and Curves
--Although bytea rep contains single \, these need to be escaped when inserting into a table -- unless standard_conforming_strings is set to on. SELECT ST_AsEWKT( ST_GeomFromWKB(E'\\001\\002\\000\\000\\000\\002\\000\\000\\000\\037\\205\\353Q\\270~\\\\\\300\\323Mb\\020X\\231C@\\020X9\\264\\310~\\\\\\300)\\\\\\217\\302\\365\\230C@',4326) ); st_asewkt ------------------------------------------------------ SRID=4326;LINESTRING(-113.98 39.198,-113.981 39.195) (1 row) SELECT ST_AsText( ST_GeomFromWKB( ST_AsEWKB('POINT(2 5)'::geometry) ) ); st_astext ------------ POINT(2 5) (1 row)
ST_LineFromWKB — Faz uma LINESTRING
de uma WKB com o SRID dado
geometria ST_LineFromWKB(
bytea WKB)
;
geometria ST_LineFromWKB(
bytea WKB, inteiro srid)
;
A função ST_LineFromWKB
, pega uma representação binária bem conhecida de geometria e um sistema de referência espacial ID (SRID
) e cria um exemplo do tipo apropriado de geometria - nesse caso, uma geometria LINESTRING
. Essa função cumpre o papel da Fábrica de Geometria SQL.
Se um SRID não estiver especificado, isso leva a 0. Retorna NULA
se a entrada bytea
não representa uma LINESTRING
.
![]() | |
OGC SPEC 3.2.6.2 - opção SRID é de uma suíte de conformação. |
![]() | |
Se você sabe que todas suas geometrias são |
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 — Faz uma geometria de uma WKB com o SRID dado.
geometry ST_LinestringFromWKB(
bytea WKB)
;
geometry ST_LinestringFromWKB(
bytea WKB, integer srid)
;
A função ST_LinestringFromWKB
, pega uma representação binária bem conhecida de geometria e um sistema de referência espacial ID (SRID
) e cria um exemplo do tipo apropriado de geometria - nesse caso, uma geometria LINESTRING
. Essa função cumpre o papel da Fábrica de Geometria SQL.
Se um SRID não estiver especificado, isso leva a 0. Retorna NULA
se a entrada bytea
não representa uma geometria LINESTRING
. Isso é um heterônimo para ST_LineFromWKB.
![]() | |
OGC SPEC 3.2.6.2 - o SRID opcional é da suíte de conformação. |
![]() | |
Se você sabe que todas suas geometrias são |
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 — Faz uma geometria a partir de um WKB com o SRID dado
geometria ST_GeomFromWKB(
bytea geom)
;
geometry ST_GeomFromWKB(
bytea geom, inteiro srid)
;
A função ST_PointFromWKB
, pega uma representação binária bem conhecida de geometria e um sistema de referência espacial ID (SRID
) e cria um exemplo do tipo apropriado de geometria - nesse caso, uma geometria PONTO
. Essa função cumpre o papel da Fábrica de Geometria SQL.
Se uma SRID não for especificada, leva a 0. NULO
é retornado se a entrada bytea
não representar uma PONTO
geometria.
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 — Retorna uma CAIXA2D de uma string GeoHash.
box2d ST_Box2dFromGeoHash(
text geohash, integer precision=full_precision_of_geohash)
;
Retorna uma CAIXA2D de uma string GeoHash.
If no precision
is specified ST_Box2dFromGeoHash returns a BOX2D based on full precision of the input GeoHash string.
Se a precisão
é especificada, a ST_Box2dFromGeoHash irá usar aqueles vários caracteres do GeoHash para criar a CAIXA2D. Valores de precisão mais baixos resultam em CAIXAS2D maiores e valores maiores aumentam a precisão.
Disponibilidade: 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 — Retorna uma geometria de uma string GeoHash.
geometria ST_GeomFromGeoHash(
texto geohash, inteiro precision=full_precision_of_geohash)
;
Retorna uma geometria de uma string GeoHash. A geometria será um polígono representando os limites GeoHash.
Se nenhuma precisão
for especificada, a ST_GeomFromGeoHash retorna um polígono baseado na precisão completa da string de entrada GeoHash.
Se a precisão
for especificada, a ST_GeomFromGeoHash irá usar aqueles vários caracteres do GeoHash para criar o polígono.
Disponibilidade: 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 — Utiliza como entrada uma representação GML de geometria e como saída um objeto de geometria PostGIS
geometria ST_GeomFromGML(
text geomgml)
;
geometria ST_GeomFromGML(
texto geomgml, inteiro srid)
;
Constrói um objeto PostGIS ST_Geometry de uma representação OGC GML.
A ST_GeomFromGML funciona apenas para fragmentos da geometria GML. Ela descarta um erro, se você tentar usá-la em um documento inteiro GML.
OGC GML versions supported:
GML 3.2.1 Namespace
GML 3.1.1 Simple Features profile SF-2 (with GML 3.1.0 and 3.0.0 backward compatibility)
GML 2.1.2
OGC GML standards, cf: http://www.opengeospatial.org/standards/gml:
Disponibilidade:1.5, requer libxml2 1.6+
Melhorias: 2.0.0 suporte para superfícies poliédricas e TIN foi introduzido.
Melhorias: 2.0.0 parâmetro opcional padrão srid adicionado.
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 dimensões mescladas (2D e 3D dentro da mesma MultiGeometria, por exemplo). ST_GeomFromGML converte a geometria inteira para 2D se uma dimensão Z perdida for encontrada uma vez, as geometrias do PostGIS não fazem isso.
A GML suporta SRS misturadas dentro da mesma MultiGeometria. As ST_GeomFromGML, reprojetam todas as sub geometrias para o nó raiz da SRS, as geometrias PostGIS não fazem isso. Se nenhum srsNome atribui disponível para o nó raiz GML, a função descarta um erro.
A função ST_GeomFromGML não é afetada sobre um espaço de nome específico GML. Você poderia evitar mencionar ela explicitamente para usos comuns. Mas você precisa dela se quiser usar XLink dentro de GML.
![]() | |
A função ST_GeomFromGML não suporta geometrias SQL/MM curvas. |
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 — Utiliza como entrada uma representação geojson de uma geometria e como saída um objeto de geometria PostGIS
geometry ST_GeomFromGeoJSON(
text geomjson)
;
geometry ST_GeomFromGeoJSON(
json geomjson)
;
geometry ST_GeomFromGeoJSON(
jsonb geomjson)
;
Constrói um objeto de geometria PostGIS de uma representação GeoJSON.
A ST_GeomFromGeoJSON funciona apenas para fragmentos da geometria JSON. Ela descarta um erro se você tentar usá-la em um documento JSON inteiro.
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.
Disponibilidade: 2.0.0 requer - JSON-C >= 0.9
![]() | |
Se você não tem JSON-C ativada, o suporte apresentará uma notificação de erro ao invés de uma saída. Para ativar JSON-C, execute a configuração --with-jsondir=/path/to/json-c. Veja mais detalhes em: Section 2.2.3, “Configuração”. |
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)
-- a 3D linestring SELECT ST_AsText(ST_GeomFromGeoJSON('{"type":"LineString","coordinates":[[1,2,3],[4,5,6],[7,8,9]]}')) As wkt; wkt ------------------- LINESTRING(1 2,4 5,7 8)
ST_GeomFromKML — Utiliza como entrada uma representação KML de geometria e como saída um objeto de geometria PostGIS
geometria ST_GeomFromKML(
texto geomkml)
;
Constrói um objeto PostGIS ST_Geometry de uma representação OGC KML.
A ST_GeomFromKML funciona apenas para fragmentos da geometria KML. Ela descarta um erro, se você tentar usá-la em um documento inteiro KML.
OGC KML versões suportadas:
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.
![]() | |
A função ST_GeomFromKML não suporta geometrias SQL/MM curvas. |
ST_GeomFromTWKB — Cria uma ocasião de uma TWKB ("Tiny Well-Known Binary") representação de geometria.
geometria ST_GeomFromTWKB(
bytea twkb)
;
A função ST_GeomFromTWKB
, pega uma TWKB ("Tiny Well-Known Binary") representação geométrica (WKB) e cria uma ocasião do tipo apropriado de geometria.
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 — Retorna um valor ST_Geometry específico da representação GML. Esse é um heterônimo para ST_GeomFromGML
geometry ST_GMLToSQL(
text geomgml)
;
geometry ST_GMLToSQL(
text geomgml, integer srid)
;
ST_LineFromEncodedPolyline — Cria uma LineString de uma Encoded Polyline.
geometria ST_LineFromEncodedPolyline(
texto polyline, inteiro precision=5)
;
Cria uma LineString de uma string Encoded Polyline.
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.
Veja http://developers.google.com/maps/documentation/utilities/polylinealgorithm
Disponibilidade: 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 — Retorna um ponto de uma string GeoHash.
ponto ST_PointFromGeoHash(
texto geohash, inteiro precision=full_precision_of_geohash)
;
Retorna um ponto de uma string GeoHash. O ponto representa o ponto central do GeoHash.
Se nenhuma precisão
for especificada, a ST_PointFromGeoHash retorna um ponto baseado na precisão completa da string da entrada GeoHash.
Se a precisão
for especificada, a ST_PointFromGeoHash irá usar aqueles vários caracteres do GeoHash para criar o ponto.
Disponibilidade: 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.
geometria ST_BdPolyFromText(
texto WKT, inteiro 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 — Retorna a representação de texto bem conhecida (WKT) da geometria com os meta dados SRID.
text ST_AsEWKT(
geometry g1)
;
text ST_AsEWKT(
geometry g1, integer maxdecimaldigits=15)
;
text ST_AsEWKT(
geography g1)
;
text ST_AsEWKT(
geography g1, integer maxdecimaldigits=15)
;
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.
Melhorias: 2.0.0 suporte para geografia, superfícies poliédricas, triângulos e TIN foi introduzido.
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 — Retorna a representação de texto bem conhecida (WKT) da geometria/geografia sem os meta dados do SRID.
text ST_AsText(
geometry g1)
;
text ST_AsText(
geometry g1, integer maxdecimaldigits = 15)
;
text ST_AsText(
geography g1)
;
text ST_AsText(
geography g1, integer maxdecimaldigits = 15)
;
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 |
Disponibilidade: 1.5 - suporte para geografia foi introduzido.
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. |
Melhorias: 2.0.0 suporte para superfícies poliédricas, triângulos e TINs introduzido.
Melhorias: 2.0.0 suporte para maiores dimensões de coordenadas foi introduzido.
Melhorias: 2.0.0 suporte para edian especificando com geografia foi introduzido.
Disponibilidade: 1.5.0 suporte para geografia foi introduzido.
Alterações: 2.0.0 Entrada para esta função não pode ser desconhecida -- deve ser geometria. Construções como ST_AsBinary('POINT(1 2)')
não são mais válidas e você terá n st_asbinary(desconhecido) não é um erro único
. Códigos assim, precisam ser alterados para ST_AsBinary('POINT(1 2)'::geometry);
. Se não for possível, instale: 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. |
Melhorias: 2.0.0 suporte para superfícies poliédricas, triângulos e TINs introduzido.
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 — Retorna uma geometria no formato HEXEWKB (como texto) usando little-endian (NDR) ou big-endian (XDR) encoding.
text ST_AsHEXEWKB(
geometry g1, text NDRorXDR)
;
text ST_AsHEXEWKB(
geometry g1)
;
Retorna uma geometria no formato HEXEWKB (como texto) usando little-endian (NDR) ou big-endian (XDR) encoding. Se nenhum encoding estiver especificado, então o NDR é usado.
![]() | |
Disponibilidade: 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 — Retorna uma Polilinha Encoded de uma geometria LineString.
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.
Disponibilidade: 2.2.0
Básico
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 em conjunto com a linestring geografia e segmentize geografia, e coloque no 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 irá parecer em algo com isso, onde a variável $ você substitui com o resultado da pesquisa
<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:
Disponibilidade: 1.3.4
Disponibilidade: 1.5.0 suporte para geografia foi introduzido.
Alterações: 2.0.0 suporte padrão args e args nomeados.
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 — Retorna a geometria como uma versão GML com 2 ou 3 elementos.
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 refere-se a versão 2.1.2 , GML 3 para a versão 3.1.1
O argumento "opções" é um bitfield. Ele poderia ser usado para definir o tipo de saída CRS na saída GML, e para declarar dados como lat/lon:
0: GML Short CRS (ex: EPSG:4326), valor padrão
1: GML Long CRS (ex: urn:ogc:def:crs:EPSG::4326)
2: Para GML 3 somente, remove srsDimension atribuída da saída.
4: Para GML 3 somente, use <LineString> em vez de <Curve> tag para linhas.
16: Declara que dados são lat/lon (ex: srid=4326). O padrão é supor que os dados são planos. Esta opção é útil apenas para saída GML 3.1.1, relacionada a ordem do eixo. Então, se você configurá-la, ela irá trocar as coordenadas, deixando a ordem sendo lat lon em vez do banco de dados.
32: Gera a caixa da geometria (envelope).
O argumento 'namespace prefix' pode ser usado para especificar um namespace prefix personalizado ou nenhum prefixo (se vazio). Se nulo ou omitido, o prefixo 'gml' é usado
Disponibilidade: 1.3.2
Disponibilidade: 1.5.0 suporte para geografia foi introduzido.
Melhorias: 2.0.0 prefixo suportado foi introduzido. A opção 4 para o GML3 foi introduzida para permitir a utilização da LineString em vez da tag Curva para linhas. O suporte GML3 para superfícies poliédricas e TINS foi introduzidos. A Opção 32 foi introduzida para gerar a caixa.
Alterações: 2.0.0 use argumentos nomeados por padrão
Melhorias: 2.1.0 suporte para id foi introduzido, para GML 3.
![]() | |
Somente a versão 3+ de ST_AsGML suporta superfícies poliédricas e 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 — Retorna a geometria como uma versão GML com 2 ou 3 elementos.
text ST_AsKML(
geometry geom, integer maxdecimaldigits=15, text nprefix=NULL)
;
text ST_AsKML(
geography geog, integer maxdecimaldigits=15, text nprefix=NULL)
;
Retorna a geometria como um elemento Keyhole Markup Language (KML). Existem muitas variantes desta função. Número máximo de casas decimais usado na saída (padrão 15), versão para 2 e o namespace não tem prefixo.
![]() | |
Using the |
![]() | |
Requer que PostGIS seja compilado com o suporte Porj. Use PostGIS_Full_Version para confirmar que você o suporte proj compilado. |
![]() | |
Disponibilidade: 1.2.2 - variantes futuras que incluem parâmetro versão que veio em 1.3.2 |
![]() | |
Melhorias: 2.0.0 - Adiciona namespace prefixo. O padrão é não ter nenhum prefixo |
![]() | |
Changed: 3.0.0 - Removed the "versioned" variant signature |
![]() | |
A saída AsKML não funcionará com geometrias que não possuem um 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 — Retorna a representação de Graus, Minutos, Segundos do ponto dado.
text ST_AsLatLonText(
geometry pt, text format='')
;
Returns the Degrees, Minutes, Seconds representation of the point.
![]() | |
É suposto que o ponto é uma projeção lat/lon. As coordenadas X (lon) e Y (lat), são normalizadas na saída para o alcance "normal" (-180 to +180 para lon, -90 para +90 para lat). |
O texto parâmetro é um formato string que contém o formato do texto resultante, parecido com uma string de formato data. Tokens válidos são "D" para graus, "M" para minutos, "S" para segundos e "C" para direções cardiais (NSLO). Os tokens DMS podem se repetir para indicar a largura e precisão desejadas ("SSS.SSSS" significa " 1.0023").
"M", "S", e "C" são opcionais. Se "C" estiverem omitidas, os graus são mostrados com um "-" se sul ou oeste. Se "S" estiver omitido, os minutos serão mostrados como decimais com com tanta precisão de dígitos quanto você especificar. Se "M" também estiver omitido, os graus serão mostrados como decimais com tanta precisão de dígitos quanto você especificar.
Se a string formato for omitida (ou tiver tamanho zero) um formato padrão será usado.
Disponibilidade: 2.0
Formato padrão.
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)')); st_aslatlontext ---------------------------- 2°19'29.928"S 3°14'3.243"W
Fornecendo um formato (o mesmo do padrão).
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
Outros caracteres além de D, M, S, C e . são somente passados.
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
Graus assinados em vez de direções cardiais.
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)', 'D°M''S.SSS"')); st_aslatlontext ---------------------------- -2°19'29.928" -3°14'3.243"
Graus decimais.
SELECT (ST_AsLatLonText('POINT (-3.2342342 -2.32498)', 'D.DDDD degrees C')); st_aslatlontext ----------------------------------- 2.3250 degrees S 3.2342 degrees W
Valores excessivamente grandes são normalizados.
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)
;
Retorna a geometria como dados Scalar Vector Graphics (SVG). Use 1 como segundo argumento para ter os dados path implementados em termo de movimentos relacionados, o padrão (ou 0) utiliza movimento absolutos. O terceiro argumento pode ser usado para reduzir o máximo número de dígitos decimais usados na saída (padrão 15). Geometrias pontuais, serão renderizadas como cx/cy quando o argumento 'rel' for 0, x/y quando 'rel' for 1. Geometrias multipontuais são delimitadas por vírgulas (","). As geometrias GeometryCollection são delimitadas por ponto e vírgula (";").
![]() | |
Disponibilidade: 1.2.2. Disponibilidade: 1.4.0 Alterado em PostGIS 1.4.0 para incluir comando L em path absoluto para entrar em conformidade com http://www.w3.org/TR/SVG/paths.html#PathDataBNF |
Alterações: 2.0.0 para usar args padrão e suporta args nomeados
ST_AsTWKB — Retorna a geometria como TWKB, também conhecido como "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)
;
Retorna a geometria no formato TWKB (Tiny Well-Known Binary). TWKB é um compressed binary format com foco em minimizar o tamanho da saída.
Os parâmetros de dígitos decimais controlam quanta precisão está armazenada na saída. Por padrão, valores são arredondados para a unidade mais pŕoxima antes de encoding. Por exemplo: um valor de 1 implica que o primeiro dígito a direita do ponto decimal será preservado.
Os tamanhos e os parâmetros das caixas limitadoras controlam onde as informações opcionais sobre o tamanho do encoding do objeto e os limites do objeto estão incluídas na saída. Por padrão elas não estão. Não as inclua a menos que o software do seu cliente tenha um uso para elas, como elas só ocupa espaço (e economizar espaço é o objeto do TWKB).
A forma arranjo entrada da função é usada para converter uma coleção de geometrias e identificadores únicos em uma coleção TWKB que preserva os identificadores. Isto é útil para clientes que esperam desempacotar uma coleção e acessar informações futuras sobre os objetos que estão dentro. Você pode criar os arranjos usando a função array_agg. Os outros parâmetros funcionam da mesma forma para o formato simples da função.
![]() | |
O formato de especificação está disponível online em https://github.com/TWKB/Specification, e o código para construir um cliente JavaScript pode ser encontrado em https://github.com/TWKB/twkb.js. |
Enhanced: 2.4.0 memory and speed improvements.
Disponibilidade: 2.2.0
SELECT ST_AsTWKB('LINESTRING(1 1,5 5)'::geometry); st_astwkb -------------------------------------------- \x02000202020808
Para criar um objeto TWKB agregado, incluir identificadores agrega as geometrias e objetos desejado primeiro, utilizando "array_agg()", então, utilize a função TWKB apropriada.
SELECT ST_AsTWKB(array_agg(geom), array_agg(gid)) FROM mytable; st_astwkb -------------------------------------------- \x040402020400000202
ST_AsX3D — Retorna uma geometria em X3D nó xml formato do elemento: ISO-IEC-19776-1.2-X3DEncodings-XML
text ST_AsX3D(
geometry g1, integer maxdecimaldigits=15, integer options=0)
;
Retorna uma geometria como um elemento nó formatado X3D xml http://www.web3d.org/standards/number/19776-1. Se maxdecimaldigits
(precisão) não estiver especificada, então, leva para 15.
![]() | |
Existem vários motivos para traduzir as geometrias PostGIS para X3D já que os tipos de geometria X3D não mapeiam diretamente para os tipos de geometria do PostGIS e alguns tipos X3D mais novos, que podem ser os melhores mapeadores que estávamos evitando já que a maioria das ferramentas renderizadoras não suportam eles. Sinta-se livre para postar um comentário se você tiver ideias de como podemos permitir as pessoas a indicarem seus mapeamentos preferidos. Abaixo está como nós mapeamos os tipos 2D/3D do PostGIS para os tipos X3D, no momento |
O argumento 'opções' é um bitfield. Para o PostGIS 2.2+, isto é usado para indicar onde representar as coordenadas atuais com o nó X3D GeoCoordinates Geospatial e, além disso, onde derrubar os eixos x/y. Por padrão, ST_AsX3D
gera na forma de banco de dados (long,lat or X,Y), mas X3D de lat/lon, y/x podem ser preferidos.
0: X/Y na ordem de banco de dados (ex: ling/lat = X,Y é a ordem padrão de banco de dados), valor padrão e coordenadas não-espaciais (somente coordenada tag antiga).
1: Lançar X e Y. Se usado em conjunção com a opção de trocar a geocoordenada, então, a saída será "latitude_first" e as coordenadas serão lançadas também.
2: Gera coordenadas no GeoSpatial GeoCoordinates. Esta opção lançará um erro se as geometrias não estiverem na WGS 84 long lat (srid: 4326). Este é o único tipo GeoCoordinate suportado. Refer to X3D specs specifying a spatial reference system.. Saída padrão será: GeoCoordinate geoSystem='"GD" "WE" "longitude_first"'
. If you prefer the X3D default of GeoCoordinate geoSystem='"GD" "WE" "latitude_first"'
use (2 + 1)
= 3
Tipo PostGIS | Tipo 2D X3D | Tipo 3D X3D |
---|---|---|
LINESTRING | ainda não foi implementado - será PoliLinha2D | LineSet |
MULTILINESTRING | ainda não foi implementado - será PoliLinha2D | IndexedLineSet |
MULTIPONTO | Poliponto2D | PointSet |
PONTO | gera as coordenadas delimitadas pelo espaço | gera as coordenadas delimitadas pelo espaço |
(MULTI) POLÍGONO, SUPERFÍCIE POLIÉDRICA | Marcação X3D inválida | IndexedFaceSet (anéis interiores atualmente gerados como outro faceset) |
TIN | TriangleSet2D (ainda não implementado) | IndexedTriangleSet |
![]() | |
O suporte para geometrias 2D ainda não está completo. Os anéis interiores apenas desenhados como polígonos separados. Estamos trabalhando nisto. |
Lots of advancements happening in 3D space particularly with X3D Integration with HTML5
Existe uma ótima fonte de visualizador X3D que você pode usar para ver as geometrias renderizadas. Free Wrl http://freewrl.sourceforge.net/ binários para Mac, Linux, and Windows. Use FreeWRL_Launcher compactados para visualizar as geometrias.
Also check out PostGIS minimalist X3D viewer that utilizes this function and x3dDom html/js open source toolkit.
Disponibilidade: 2.0.0: ISO-IEC-19776-1.2-X3DEncodings-XML
Melhorias: 2.2.0: Suporte para GeoCoordinates e eixos (x/y, long/lat) lançando. Observe as opções para mais detalhes.
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 — Retorna uma representação GeoHash da geometria.
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.
Disponibilidade: 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
VERDADE
se a caixa limitadora 2D de A intersecta a caixa limitadora 2D de B. 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.VERDADE
se a caixa limitadora n-D de A intersecta a caixa limitadora n-D de B. 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.VERDADE
se a caixa limitadora de A sobrepõe ou está à esquerda de B. VERDADE
se a caixa limitadora de A sobrepõe ou está abaixo de B. VERDADE
se a caixa limitadora de A sobrepõe ou está à direita de B. VERDADE
se uma caixa limitadora de A está estritamente à esquerda da de B.VERDADE
se uma caixa limitadora de A está estritamente abaixo da de B.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.VERDADE
se uma caixa limitadora de A está contida pela de B.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.VERDADE
se a caixa limitadora de A sobrepõe ou está acima de B. VERDADE
se uma caixa limitadora de A está estritamente acima da de B.VERDADE
se uma caixa limitadora de A contém a de B.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).VERDADE
se a caixa limitadora de A é a mesma de B.&& — Retorna VERDADE
se a caixa limitadora 2D de A intersecta a caixa limitadora 2D de B.
boolean &&(
geometry A , geometry B )
;
boolean &&(
geography A , geography B )
;
O operador &&
retorna VERDADE
se a caixa limitadora 2D da geometria A intersecta a caixa limitadora 2D da geometria B.
![]() | |
Esse operador fará uso de qualquer um dos indexes que talvez estejam disponíveis nas geometrias. |
Melhorias: 2.0.0 suporte a superfícies poliédricas foi introduzido.
Disponibilidade: 1.5.0 Suporte para geografia foi introduzido
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.
&&& — Retorna VERDADE
se a caixa limitadora n-D de A intersecta a caixa limitadora n-D de B.
boolean &&&(
geometry A , geometry B )
;
O operador &&&
retorna VERDADE
se a caixa limitadora n-D da geometria A intersecta a caixa limitadora n-D da geometria B.
![]() | |
Esse operador fará uso de qualquer um dos indexes que talvez estejam disponíveis nas geometrias. |
Disponibilidade: 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.
&< — Retorna VERDADE
se a caixa limitadora de A sobrepõe ou está à esquerda de B.
boolean &<(
geometry A , geometry B )
;
O operador &<
retorna VERDADE
se a caixa limitadora da geometria A sobrepõe ou está à esquerda da caixa da geometria B, ou mais precisamente, sobrepõe ou NÃO está à direita da caixa limitadora da geometria B.
![]() | |
Esse operador fará uso de qualquer um dos indexes que talvez estejam disponíveis nas geometrias. |
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)
&<| — Retorna VERDADE
se a caixa limitadora de A sobrepõe ou está abaixo de B.
boolean &<|(
geometry A , geometry B )
;
O operador &<|
retorna VERDADE
se a caixa limitadora da geometria A sobrepõe ou está abaixo da caixa da geometria B, ou mais precisamente, sobrepõe ou NÃO está acima da caixa limitadora da geometria B.
This method supports Circular Strings and Curves
This function supports Polyhedral surfaces.
![]() | |
Esse operador fará uso de qualquer um dos indexes que talvez estejam disponíveis nas geometrias. |
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)
&> — Retorna VERDADE
se a caixa limitadora de A sobrepõe ou está à direita de B.
boolean &>(
geometry A , geometry B )
;
O operador &>
retorna VERDADE
se a caixa limitadora da geometria A sobrepõe ou está à direita da caixa da geometria B, ou mais precisamente, sobrepõe ou NÃO está à esquerda da caixa limitadora da geometria B.
![]() | |
Esse operador fará uso de qualquer um dos indexes que talvez estejam disponíveis nas geometrias. |
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)
<< — Retorna VERDADE
se uma caixa limitadora de A está estritamente à esquerda da de B.
boolean <<(
geometry A , geometry B )
;
O operador <<
retorna VERDADE
se a caixa limitadora da geometria A está estritamente à esquerda da caixa limitadora da geometria B.
![]() | |
Esse operador fará uso de qualquer um dos indexes que talvez estejam disponíveis nas geometrias. |
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)
<<| — Retorna VERDADE
se uma caixa limitadora de A está estritamente abaixo da de B.
boolean <<|(
geometry A , geometry B )
;
O operador <<|
retorna VERDADE
se a caixa limitadora da geometria A está estritamente à esquerda da caixa limitadora da geometria B.
![]() | |
Esse operador fará uso de qualquer um dos indexes que talvez estejam disponíveis nas geometrias. |
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 )
;
O operador >>
retorna VERDADE
se a caixa limitadora da geometria A está estritamente à direita da caixa limitadora da geometria B.
![]() | |
Esse operador fará uso de qualquer um dos indexes que talvez estejam disponíveis nas geometrias. |
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)
@ — Retorna VERDADE
se uma caixa limitadora de A está contida pela de B.
boolean @(
geometry A , geometry B )
;
O operador @
retorna VERDADE
se a caixa limitadora da geometria A estiver completamente contida pela caixa limitadora da geometria B.
![]() | |
Esse operador fará uso de qualquer um dos indexes que talvez estejam disponíveis nas geometrias. |
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.
|&> — Retorna VERDADE
se a caixa limitadora de A sobrepõe ou está acima de B.
boolean |&>(
geometry A , geometry B )
;
O operador |&>
retorna VERDADE
se a caixa limitadora da geometria A sobrepõe ou está acima da caixa da geometria B, ou mais precisamente, sobrepõe ou NÃO está abaixo da caixa limitadora da geometria B.
![]() | |
Esse operador fará uso de qualquer um dos indexes que talvez estejam disponíveis nas geometrias. |
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)
|>> — Retorna VERDADE
se uma caixa limitadora de A está estritamente acima da de B.
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.
![]() | |
Esse operador fará uso de qualquer um dos indexes que talvez estejam disponíveis nas geometrias. |
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)
~ — Retorna VERDADE
se uma caixa limitadora de A contém a de B.
boolean ~(
geometry A , geometry B )
;
O operador ~
retorna VERDADE
se a caixa limitadora da geometria A estiver completamente contida pela caixa limitadora da geometria B.
![]() | |
Esse operador fará uso de qualquer um dos indexes que talvez estejam disponíveis nas geometrias. |
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.
~= — Retorna VERDADE
se a caixa limitadora de A é a mesma de B.
boolean ~=(
geometry A , geometry B )
;
O operador ~
retorna VERDADE
se a caixa limitadora da geometria/geografia A for a mesma da caixa limitadora da geometria/geografia B.
![]() | |
Esse operador fará uso de qualquer um dos indexes que talvez estejam disponíveis nas geometrias. |
Disponibilidade: 1.5.0 comportamento alterado
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. |
<-> — Retorna a distância 2D entre A e B.
double precision <->(
geometry A , geometry B )
;
double precision <->(
geography A , geography B )
;
O operador <->
retorna a distância 2D entre duas geometrias. Usado nas orações "ORDEM" que fornecem configurações de resultado index-assisted nearest-neighbor. Para o PostgreSQL menor que 9.5 somente fornece a distância centroide das caixas limitadoras e para PostgreSQL 9.5+, a verdadeira distância KNN procura dando verdadeiras distâncias entre geometrias, e distância esférica para geografias.
![]() | |
Esse operador fará uso dos indexes 2D GiST que podem estar disponíveis nas geometrias. É diferente de outros operadores que usam indexes espaciais em que eles só são usados quando o operador está na oração ORDEM. |
![]() | |
O index só rejeita se uma das geometrias é uma constante (não em uma subquery/cte). ex. 'SRID=3005;POINT(1011102 450541)'::geometria ao invés de uma .geom |
Vá para OpenGeo workshop: Nearest-Neighbour Searching para um exemplo real.
melhorias: 2.2.0 -- Verdadeiro comportamento KNN ("vizinho mais perto de K") para geometria e geografia para PostgreSQL 9.5+. Note que para geografia o KNN é baseado em esfera ao invés de esferoide. Para o PostgreSQL 9.4 ou menor, o suporte para geografia é novo, mas só suporta caixa centroide.
Alterações: 2.2.0 -- Para usuários do PostgreSQL 9.5, a sintaxe Hybrid antiga pode ser ais lenta, então, você vai querer se livrar daquele hack se você está executando seu código só no PostGIS 2.2+ 9.5+. Veja os exemplos abaixo.
Disponibilidade: 2.0.0 -- O KNN mais fraco fornece vizinho mais próximos baseados em distâncias centroides de geometrias, ao invés de distâncias reais. Resultados corretos para pontos, incorretos para todos os outros tipos. Disponível para 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)
Então, a resposta KNN crua:
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)
Se você executar "ANÁLISE EXPLICATIVA" nas duas pesquisas, você verá uma apresentação melhorada para a segunda.
Para usuários com PostgreSQL < 9.5, use uma pesquisa hybrid para encontrar os vizinhos verdadeiros mais próximos. Primeiro, uma pesquisa CTE usando o index-assisted KNN, e depois, uma pesquisa exata para pegar a ordem certa:
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)
|=| — Retorna a distância entre As trajetórias A e B ao ponto de aproximação mais perto.
double precision |=|(
geometry A , geometry B )
;
O operador |=|
retorna a distância 3D entre duas trajetórias (Veja ST_IsValidTrajectory). Isso é o mesmo que ST_DistanceCPA, mas como um operador pode ser usado para fazer pesquisas de vizinhos próximos usando um index n-dimensional (requer PostgreSQL 9.5.0 ou superior).
![]() | |
Esse operador fará uso dos indexes ND GiST que podem estar disponíveis nas geometrias. É diferente de outros operadores que usam indexes espaciais em que eles só são usados quando o operador está na oração ORDEM. |
![]() | |
O index só rejeita se uma das geometrias é uma constante (não em uma subquery/cte). ex.'SRID=3005;LINESTRINGM(0 0 0,0 0 1)'::geometria ao invés de uma .geom |
Disponibilidade: 2.2.0. Index suportado disponível somente para 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)
<#> — Retorna a distância 2D entre as caixas limitadoras de A e B.
double precision <#>(
geometry A , geometry B )
;
O operador <#>
retorna a distância entre dois pontos flutuantes, possivelmente lendo eles de um index espacial (PostgreSQL 9.1+ requerido). Útil para tornar vizinhos mais próximos aproximar a distância pedida.
![]() | |
Esse operador fará uso dos indexes que podem estar disponíveis nas geometrias. É diferente de outros operadores que usam indexes espaciais em que eles só são usados quando o operador está na oração ORDEM. |
![]() | |
O index só rejeita se uma das geometrias é uma constante ex. ORDER BY (ST_GeomFromText('POINT(1 2)') <#> geom) ao invés de uma g1.geom <#>. |
Disponibilidade: 2.0.0 -- KNN só está disponível para 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)
<<->> — Retorna a distância n-D entre as centroides das caixas limitadoras de A e B.
double precision <<->>(
geometry A , geometry B )
;
O operador <<->>
retorna a distância (euclidiana) n-D entre as centroides das caixas limitadoras de duas geometrias. Útil para para tornar vizinhos mais próximos aproximar a distância perdida.
![]() | |
Esse operador fará uso dos indexes n-D GiST que podem estar disponíveis nas geometrias. É diferente de outros operadores que usam indexes espaciais em que eles só são usados quando o operador está na oração ORDEM. |
![]() | |
O index só rejeita se uma das geometrias é uma constante (não em uma subquery/cte). ex. 'SRID=3005;POINT(1011102 450541)'::geometria ao invés de uma .geom |
Disponibilidade: 2.2.0 -- KNN só está disponível para PostgreSQL 9.1+
<<#>> — Retorna a distância n-D entre as caixas limitadoras de A e B.
double precision <<#>>(
geometry A , geometry B )
;
O operador <<#>>
retorna a distância entre dois pontos flutuantes, possivelmente lendo eles de um index espacial (PostgreSQL 9.1+ requerido). Útil para tornar vizinhos mais próximos aproximar uma distância pedida.
![]() | |
Esse operador fará uso dos indexes que podem estar disponíveis nas geometrias. É diferente de outros operadores que usam indexes espaciais em que eles só são usados quando o operador está na oração ORDEM. |
![]() | |
O index só rejeita se uma das geometrias é ua constante ex. ORDER BY (ST_GeomFromText('POINT(1 2)') <<#>> geom) ao invés de g1.geom <<#>>. |
Disponibilidade: 2.2.0 -- KNN só está disponível para 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 spatial relationship predicates, this does NOT automatically include an index call. The reason is that some relationships are true for geometries which do NOT intersect (e.g. Disjoint). If you are using a relationship pattern that requires intersection, then include the && index call. |
![]() | |
It is better to use a named relationship function if available, since they automatically use a spatial index where one exists. Also, they may implement performance optimizations which are not available with full relate evalation. |
Variant 2: Returns the DE-9IM matrix string for the spatial relationship between the two input geometries. The matrix string can be tested for matching a DE-9IM pattern using ST_RelateMatch.
Variant 3: Like variant 2, but allows specifying a Boundary Node Rule. A boundary node rule allows finer control over whether the endpoints of MultiLineStrings are considered to lie in the DE-9IM Interior or Boundary. The boundaryNodeRule
values are:
1
: OGC-Mod2 - line endpoints are in the Boundary if they occur an odd number of times. This is the rule defined by the OGC SFS standard, and is the default for ST_Relate
.
2
: Endpoint - all endpoints are in the Boundary.
3
: MultivalentEndpoint - endpoints are in the Boundary if they occur more than once. In other words, the boundary is all the "attached" or "inner" endpoints (but not the "unattached/outer" ones).
4
: MonovalentEndpoint - endpoints are in the Boundary if they occur only once. In other words, the boundary is all the "unattached" or "outer" endpoints.
This function is not in the OGC spec, but is implied. see s2.1.13.2
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.25
Performed by the GEOS module
Enhanced: 2.0.0 - added support for specifying boundary node rule.
![]() | |
Enhanced: 3.0.0 enabled support for |
Using the boolean-valued function to test spatial relationships.
SELECT ST_Relate('POINT(1 2)', ST_Buffer( 'POINT(1 2)', 2), '0FFFFF212'); st_relate ----------- t SELECT ST_Relate(POINT(1 2)', ST_Buffer( 'POINT(1 2)', 2), '*FF*FF212'); st_relate ----------- t
Testing a custom spatial relationship pattern as a query condition, with &&
to enable using a spatial index.
-- Find compounds that properly intersect (not just touch) a poly (Interior Intersects) SELECT c.* , p.name As poly_name FROM polys AS p INNER JOIN compounds As c ON c.geom && p.geom AND ST_Relate(p.geom, c.geom,'T********');
Computing the intersection matrix for spatial relationships.
SELECT ST_Relate( 'POINT(1 2)', ST_Buffer( 'POINT(1 2)', 2)); ----------- 0FFFFF212 SELECT ST_Relate( 'LINESTRING(1 2, 3 4)', 'LINESTRING(5 6, 7 8)' ); ----------- FF1FF0102
Using different Boundary Node Rules to compute the spatial relationship between a LineString and a MultiLineString with a duplicate endpoint (3 3)
:
Using the OGC-Mod2 rule (1) the duplicate endpoint is in the interior of the MultiLineString, so the DE-9IM matrix entry [aB:bI] is 0
and [aB:bB] is F
.
Using the Endpoint rule (2) the duplicate endpoint is in the boundary of the MultiLineString, so the DE-9IM matrix entry [aB:bI] is F
and [aB:bB] is 0
.
WITH data AS (SELECT 'LINESTRING(1 1, 3 3)'::geom