Você está na página 1de 43

Curso sobre PostGIS básico

Instrutor: Jairo de Almeida


Revisão 03/04/2014
Sumário
O que é o PostGIS?...............................................................................................................................8
Instalando o PostgreSQL com PostGIS Funcionalidade......................................................................9
Criando um banco de dados espacial........................................................................................13
Carregando dados de GIS no banco de dados....................................................................................16
Obter os dados...........................................................................................................................16
Descobrir o SRID dos dados.....................................................................................................17
Carregar os dados......................................................................................................................17
Faça um conjunto de ferramentas PostGIS......................................................................17
Carregar (Comando de importação)..........................................................................................18
A indexação dos dados..............................................................................................................20
Consultando dados..............................................................................................................................21
Visualizando os Dados........................................................................................................................21
O que é SFSQL?.................................................................................................................................22
Algumas consultas comuns................................................................................................................22
Transformação a partir de um sistema de coordenadas para outro...........................................22
Funções de agregação...............................................................................................................22
Extensão...........................................................................................................................22
ST_Union.........................................................................................................................23
Vendo resultados visualmente..........................................................................................23
Consultas de distância...............................................................................................................23
Obtendo distância minima e utilizançao da função ST_Distance.............................................23
Obtendo Média Distância utilizando a função Centroid..................................................24
Obtendo uma lista de objetos que estão dentro de X distância de um outro objeto........24
Tarefa PostGIS....................................................................................................................................25
Exercícios podem ser feitos com dados importados do IBGE para o banco PostgreSQL + PostGIS 25
Referências.........................................................................................................................................26
 Conceitos SIG (Sistema de informações geográfico)
Anatomia SIG, Boas práticas
SIG (Sistema de informação geográfico)
Permitem aos usuários criar consultas interativas, analisar informação espaciais, editar dados
cartográficos. Apresentar os resultados visualmente(mapas) em todas essas operações.

 O que são camadas Camadas


Camadas são formas de podermos organizar dados em um SIG, essas camadas são definidas para
cada tema proposto, e para esses temas teremos as respectivas camadas necessárias para trabalhar
com dados cartográficos
Exemplo:
● Hidrografia (Meio ambiente)
● Rodovias, Ruas (Transporte)
● Zona, Setor, Talhões (Agricultura)
● Setor, Quadra, Lotes (Gestão municipal)
● Gasodutos, Válvulas (Redes Gás)
● Fibra óptica (Telecomunicações)
● Redes de água e esgoto (Saneamento Basino)

 O que é uma feições


Feição pode ser considerada a forma de representação de objetos do um mundo real, para um
ambiente computacional, um conjunto de feições do mesmo tipo pode ser considerado uma camada.
Que por sua vez pode ser do tipo Ponto, Linha, Polígono ....

 Representações geométricas
As representações geométricas mais comuns são as listadas abaixo, essas representações podem ser
para qualquer camada que estiver contida em nosso SIG.
● Point. (Pontual)
● LineString. (Linear)
● LinearRing. (Linear Composta)
● Polygon (with holes). (Polígonos)
● MultiPoint.(Pontual Composta)
● MultiLineString.(Linear Composta)
● MultiPolygon. (Poligonal Composta)
● GeometryCollection. (Feições Mistas)
 Representação em WKT
Esta representação geométrica também pode ser feita na forma de marcação OGC mais comum
WKT(Well Know Text) que ajuda bastante compreender como os objetos gemétricos de um SIG são
representados.
● POINT (100 300)
● LINESTRING (20 380, 60 340, 120 340, 160 280)
● POLYGON( ( 40 320, 60 380, 120 380, 160 300, 100 260, 40 320) )
● MULTIPOINT(40 300, 80 340, 120 280)
● MULTILINESTRING (( 20 360, 60 380, 100 340, 160 360),(40 280, 80 300, 100 280, 160 300))
● MULTIPOLYGON (((80 320, 60 260, 100 280,80 320), (100 340, 140 360, 140 300, 100 340)))

 Representação do mundo real


Como organizar camadas em um padrão adequado para um SIG (Sistema de informações
geográfico)
 Como organizar camadas em um padrão adequado
para um SIG (Sitema de informações geográfico
Boas práticas, O formato ESRI shapefile. Como exemplo de arquivo de exportação temos o arquivo
Shapefile, esse arquivo é um padrão de exportação do SIG ArcGIS da ESRI que foi mundialmente
usado para trabalho com dados cartográficos em todo o mundo, hoje em dia os formatos mais
usados são os padrões abertos da OGC, mas

clientes.shp,
clientes.shx,
clientes.dbf
ruas.shp,
ruas.shx,
ruas.dbf
lotes.shp,
lotes.shx,
lotes.dbf
elevacao.shp,
elevacao.shx,
elevacao.dbf
uso_territorial.shp,
uso_territorial.shp,
uso_territorial.dbf

 Entendendo o formato shapefile


O formato de exportação ESRI shapefile Arquivos de exportação Extensão Descrição
*.shp,*.shp,*.dbf) Arquivos de exportação ArcGIS *.dxf,*.dwg Arquivos de exportação do
AutoCAD *.tab, *.map,*.dat,*.id Arquivos de exportação do MapInfo Mais informações sobre
formatos
http://en.wikipedia.org/wiki/GIS_file_formats
Entendendo um arquivo Shapefile

Importação dos arquivos


Introdução ao PostGIS (PostGIS)
O que é o PostGIS?
PostGIS é uma ferramenta de código fonte aberto, disponível gratuitamente, é um extensor espacial
compatível com os padrões OGC para banco de dados em Sistemas de Gerenciamento para Banco
de Dados PostgreSQL. Em poucas palavras ele adiciona funções espaciais como a distância, área,
união, interseção e de especialidade geometria tipos de dados para o banco de dados. PostGIS é
muito semelhante em funcionalidade ao SQL Server 2008 Spatial apoio, ESRI ArcSDE, Oracle
Spatial, e Spatial Extender DB2. A versão mais recente lançamento agora vem embalado com o
PostgreSQL DBMS é instalado como um add-on opcional. Como desta escrita PostGIS 2.0.0 é a
última versão estável. Há melhorias notáveis esta versão:
Agora pacotes ao longo de novas funções de medição 3D, suporte índice espacial em 3D e tipos de
área de superfície 3D
Suporte integrado análise raster / vetor incluindo um fácil de usar linha de comando para carregar
o raster no banco de dados que suporta vários tipos e pode carregar todas pastas de arquivos raster
com uma instrução de linha de comando e funções de exportação imagem para a saída tanto raster e
geometrias como PNG / TIFF e outros formatos raster.
Apoio topologia SQL / MM
O carregador de gui gráfica, que é embalado com o construtor Stack de aplicativo do Windows e
alguns outros distros para desktop, agora inclui o upload de arquivos em lote, bem como de
exportação. Este recurso pode ser ativado como um plugin no pgAdmin III
Habilidade para instalar usando CREATE EXTENSION postgis, ALTER EXTENSION
postgis ..se você estiver executando 9.1.3
Funcionalidade distância KNN se você estiver executando o PostgreSQL 9.1 +
Ele também inclui como extra: tiger geocoder com carregador para 2010 dados. Você pode esperar
para ver este tiger geocoder atualizar em 2.1.0 para carregar tigre dados de 2011.
A primeira versão do PostGIS que apoia PostgreSQL de 64 bits no Windows
O ambiente windows foi levado em consideração para este tutorial, mas a maior parte do tutorial se
aplica a outras plataformas suportadas, tais como Linux, Unix, BSD, Mac, etc Também estará
usando dados Massachusetts / Boston para estes exemplos. Os usuários de desktop podem instalar
facilmente usando a instalação EnterpriseDB, bem como para Mac / OSX e Linux desktops, por
isso você deve ser capaz de seguir adiante sem muito trabalho.
Instalando o PostgreSQL com PostGIS Funcionalidade
Não vamos entrar em muitos detalhes aqui uma vez que o assistente de instalação é muito bom.
Abaixo estão os passos básicos.
Nota para usuários do Vista, por causa da nova maior segurança no Vista, você pode se deparar com
problemas ao instalar o PostgreSQL. Consulte as dicas do Windows Vista
http://trac.osgeo.org/postgis/wiki/UsersWikiWinVista no wiki PostGIS, se você tiver problemas.
1.Faça o download do instalador para sua plataforma específica do PostgreSQL Binary Download
(http://www.postgresql.org/download/). Como esta versão é o PostgreSQL 9.1.3 e estaremos
assumindo PostGIS 2.0. O PostgreSQL mínimo suporte para PostGIS 2.0.0 é PostgreSQL 8.4 e para
obter os recursos completos, como operadores indexáveis, distância e capacidade de instalar com
extensões, você precisa 9.1. Portanto, use 9.2 de preferência. As opções abaixo segue a sequência
básica do instalador do Windows PostgreSQL.
2.Inicie .exe para instalar o PostgreSQL
3.Se você deseja acessar este servidor que não seja o próprio servidor. Marque a opção "Aceitar
conexão em todos os endereços, e não apenas localhost". NOTA: Você pode alterar isso mais tarde
editando o postgresql.conf -> listen_addresses propriedade e se você não gosta de a porta padrão de
5432 você pode mudar isso também no postgresql.conf -> propriedade porta.
4.Para codificar é preferível usar o encode UTF-8, porque você pode converter para outras
codificações. SQL_ASCII foi o padrão no Windows antes de 8.3 e mais tarde foi substituído por
WIN1252. UTF-8, porém, é agora suportado bem no Windows e, geralmente, o padrão no Linux /
Unix.
5.Uma vez que o PostgreSQL está instalado, inicie Application Stack Builder a partir de
(Iniciar-> Programas-> PostgreSQL 9.1-> Application Stackbuilder.

6.Em seguida escolha a versão do PostgreSQL que você deseja instalar no PostGIS e a
versão do PostGIS para instalar
7.NOTA:. PostGIS 1.5, 2.0.0 podem coexistir no mesmo servidor que você pode instalar, em
2.0.0 (tanto quanto o Windows é em causa, nós mudamos o modelo para
template_postgis20), por isso não vai exigir a substituição com o 1. * do template de banco
de dados template_postgis . O PostgreSQL vai ser substituídos pelos últimos PostGIS
instalados por isso tome cuidado. De um modo geral PostGIS 2.0.0 deve funcionar muito
bem em todos os lugares que você estava usando PostGIS 1.5 antes, mas você pode precisar
instalar olegacy_minimal.sql ou legacy.sql se você tiver aplicativos antigos ou ferramentas
que usam funções antigas (removidos no PostGIS 2.0)

8.Navegue até extensões espaciais e escolha a versão PostGIS 2.0. Baixe e instale.
Atenção, para muitos pacotes de instalação - em particular o windows. Quando você escolhe
PostGIS como uma opção, o sistema irá criar um template_postgis20 (ou template_postgis)
do banco de dados modelo para você que tem funções de PostGIS incluídas.
9.A caixa de seleção para instalação de banco de dados espacial é opcional, ela cria também
um banco de dados exemplo. Ele cria um banco de dados espacial para você experimentar,
mas o template_postgis20 é sempre criada para o windows.

10. Se você estiver executando o PostgreSQL 9.1 +, recomendamos que você não precisa
nem se preocupar com o banco de dados modelo e usar apenas.
CREATE EXTENSION postgis no próprio banco de dados de sua escolha ou usar
pgAdmin extensões de recurso de instalação que vamos abordar neste tutorial.

11. Se seu objetivo é registrar o prompt de GDAL_DATA para PostGIS 2.0. Isto é
necessário a fim de fazer operações que requerem transformações raster ou outro avaliador
deformação / recorte etc, PostGIS utiliza arquivos EPSG GDAL. As janelas constroem uma
cópia local desta pasta no PostgreSQL, instala a pasta \ gdal-data e ao dizer sim sim,
adiciona automaticamente uma variável de ambiente GDAL_DATA colocando este caminho
automaticamente. Se você usar GDAL já (ou você estiver executando o PostGIS 32-bit e 64-
bit, as chances são que você já tem esse conjunto variável de ambiente e você não pode
querer substituí-lo. PostGIS irá trabalhar normalmente com um já existente, mas lembre-se
se você desinstalar o PostGIS 2.0 ou o GDAL, estas funções podem parar de funcionar e
você precisa redefinir a variável de ambiente.
Criando um banco de dados espacial
PostgreSQL vem com uma ferramenta de administração bastante usada pela comunidade, chamado
pgadmin3. Essa ferramenta é muito simples e melhor para criar os objetos de um banco de dados
objeto relacional.
1.No windows pgAdmin III está em Iniciar-> Programas-> PostgreSQL 9.1-> pgAdmin III
2.Entrar com o super usuário "postgres" geralmente e a senha que você escolheu durante a
instalação. Se você esqueceu, então vá em pg_hba.conf (basta abri-lo com um editor como o bloco
de notas ou um editor de programador). Defina a linha
Acolher todos todos 127.0.0.1/32 md5
para

host all all 127.0.0.1/32 trust

Se você está em um Windows mais recentes (digamos 2008 ou Windows 7), você pode ver uma
opção adicional
host all all ::1/128 trust
A opção :: 1/128 é geralmente controladora e é o que localhost resolve em IPV6 para que você vai
querer definir este.
Isso permitirá que qualquer pessoa entrando localmente no computador que o PostgreSQL está
instalado possa acessar todos os bancos de dados sem uma senha.(127.0.0.1/32) significa apenas
localhost (32 é a máscara de bits). Note que você pode adicionar linhas adicionais para este arquivo
ou remover linhas para permitir ou bloquear determinadas faixas de IP. As linhas mais altas no
arquivo têm precedência.

Por exemplo, se você quisesse permitir que todos os usuários o login de acesso, desde que
autenticados com êxito com uma senha md5, então você pode adicionar a linha
host all all 0.0.0.0/0 md5
Você ainda será capaz de se conectar localmente sem uma senha, mas sem conexões locais, vai
precisar de um nome de usuário e senha válidos.
Nota: - As versões mais recentes do pgAdmin III (1.7) permitem editar postgresql.conf e
pg_hba.conf usando a ferramenta pgAdmin III. Estes são acessíveis a partir de Ferramentas-
Configuração do servidor e fornecer um editor de tabela bastante agradável de se trabalhar. Esta
funcionalidade só está disponível se você tiver instalado o adminpack.sql (isso está localizado em
C: \ Program Files \ PostgreSQL \ 9.x \ share \ contrib) (Admin unidades) no banco de
dados Postgres.
No windows o arquivo está localizado em C: \ Program Files \ PostgreSQL \ 9.0 \ share \
contribuições \ adminpack.sql para as versões do PostgreSQL 9.1 abaixo. Ele está localizado na
pasta de compartilhamento no Linux é instalado também. Para instalá-lo --- interruptor ao banco de
dados postgres e executar o script adminpack.sql nesse banco de dados.
Se você estiver executando 9.1, no entanto, não importa qual sistema operacional você está
executando - basta conectar ao seu banco de dados postgres e executar este comando na janela de
sql pgAdmin ou usando o psql:
CREATE EXTENSION adminpack;
(NOTA: você também pode usar o extensões gui de pgAdmin instalada no db postgres)
3.Agora vem a parte divertida - Criar seu banco de dados. Chamá-lo de gisdb ou o que quiser. Se
você estiver executando o PostgreSQL 9.1 abaixo, escolha o banco de dados modelo chamado
template_postgis20. Escolhi este como um modelo. Para o PostgreSQL 9.1 ou +, recomendo para
usar o modelo padrão
4.Geralmente é uma boa ideia criar um usuário, também, que possui o banco de dados criado, você
não precisa usar sua conta de superusuário para acessá-lo.
5.UPDATE: - As etapas restantes desta seção não são necessários se você escolheu
template_postgis20 para o seu novo banco de dados. No entanto, se você está tentando permitir
espacialmente um banco de dados existente ou você não tem a opção template_postgis20. Siga as
etapas restantes.
Para o PostgreSQL 9.1 - expandir a sua base de dados e você deve ver uma seção de extensões

6.Botão direito do mouse clique sobre isso e selecione a opção Nova extensão.
Observe as duas opções - postgis e postgis_topology - .Isto irá funcionar mesmo se o servidor
PostgreSQL não está no Windows.

7.Selecione postgis (isso inclui geometria, geografia e apoio raster). Então, se você quiser usar
topologia, em seguida, repita o passo escolher postgis_topology. Observe também a guia Definição
8.Permite que você instale postgis no esquema não-padrão e também irá permitir-lhe uma maneira
mais fácil de atualizar para PostGIS 2.0.1 , Alterando o número da versão do menu suspenso.
Se você é azarado o suficiente para estar usando PostGIS em pré-9.1 e também não tem um banco
de dados modelo, as coisas são um pouco mais difícil. O pré-PostgreSQL 9.1 caminho - Em seguida
vá para a ferramenta de consulta ferramentas -- em pgAdmin III e navegue até o arquivo de
instalação do PostgreSQL postgis.sql contrib (no Windows, a instalação padrão é Arquivos de
programas \ PostgreSQL \ 8.4 \ share \ contrib \ postgis- . 2.0 Você vai precisar para executar todos
esses scripts:
postgis.sql rtpostgis.sql spatial_ref_sys.sql topology.sql (se vocÊ quiser
suporte a topologia)

Na ferramenta de consulta, verifique se o seu gisdb está selecionado e em seguida, execute os


scripts acima clique na seta verde. Você vai ter um monte de avisos - não se assuste.
A partir de pgAdmin III 1.10 - O ícone Plugin tem PSQL como uma opção e se você respondeu à
mensagem de Sim para o Substituir meus plugins.ini (para 9.1 você não receberá um aviso já que
esses arquivos são armazenados separadamente), você deve ter uma opção adicional PostGIS
Shapefile e DBF Loader.

9.Esta opção deve tornar-se habilitada quando você seleciona um banco de dados e quando você
iniciá-lo, ele vai passar as credenciais ao banco de dados para você inicializar uma conexão PSQL.
Se o botão verde de Plugins está desativado (e não diz nenhuma Plugins instalado), então muito
provavelmente você tem um outra instalação pgAdmin ou PostgreSQL ficando no caminho. Uma
solução fácil é abrir pgAdmin III ir em Opções de arquivo -- e verifique se o caminho bin está
apontando para a localização de seu PostgreSQL/bin (por exemplo C: \ Program Files \
PostgreSQL \ 8.4 \ bin) e clique no .. .ao se ele não aparecer.

Carregando dados de GIS no banco de dados


Agora temos um bom banco de dados GIS completamente funcional sem dados espaciais. Então,
para fazer coisas boas, é preciso obter alguns dados para trabalhar.

Obter os dados
Baixe os dados do site do IBGE.
ftp://geoftp.ibge.gov.br/malhas_digitais/municipio_2010/sp.zip
Para este exercício simples, basta baixar shapefile de Municipios.
Extraia os arquivos em alguma pasta. Nós só vamos usar os arquivos de polígonos para este
exercício.
NOTA: A partir de PostGIS 1.5.0, o importador agora é empacotado com uma interface gráfica do
usuário shp2pgsql. Você também pode baixá-lo separadamente, se você estiver usando uma versão
inferior do PostGIS ou quer carregar dados de uma estação de trabalho separada, que não têm
PostgreSQL instalado descarregue separadamente usado para qualquer versão do PostGIS de 1.2 -
2.0.0 e possibilita abri-lo como um plug-in em pgAdminIII. Confira nosso screencast sobre
configurando o shp2pgsql-gui como pgAdmin III plug-in e usá-lo. ou nosso write-up em registrá-lo

Descobrir o SRID dos dados


Você vai notar um dos arquivos extraídos tem a extensão .prj. Um arquivo PRJ é frequentemente
incluído com os arquivos de forma ESRI e diz-lhe a projeção dos dados. Vamos precisar para
coincidir com esta projeção descritivo para um SRID (o campo id de um registro ref espacial na
tabela spatial_ref_sys) se for necessário reprojetar os dados, também é possível.
Abra o arquivo prj. Num editor de texto.Você verá algo como
GEOGCS["SIRGAS
2000",DATUM["D_SIRGAS2000",SPHEROID["Geodetic_Reference_System_of_1980",637
8137,298.2572221009113]],PRIMEM["Greenwich",0],UNIT["Degree",0.01745329251994
3295]]
Abra sua ferramenta de consulta pgAdmin III e digite a seguinte declaração.
select srid, srtext, proj4text from spatial_ref_sys where
srtext ILIKE '%SIRGAS 2000%'
É necessário pegar o sistema de coordenada geográfico para
representação da américa do sul, ou usar a conversão do
sistema de cordenada para WGS 84 SRID = 4326
E depois clique na seta verde.
Observe o SRID da partida mais próximo. Neste caso, seria 4674.
NOTA: SRID não é apenas um termo PostGIS. É um padrão OGC veremos um monte
SRID mencionado em outros bancos de dados espaciais, webservices e aplicações GIS. A
maioria dos sistemas de referência espacial comuns têm números definidos globalmente.
Então um sistema projetado sempre mapeia para Meters.

Carregar os dados
Os dados mais fáceis de carregar em PostGIS são dados de forma ESRI Shapefile. O PostGIS vem
encorporando com uma ferramenta de linha de comando chamada shp2pgsql, que converte arquivos
ESRI Shape em instruções SQL específicas para o PostGIS, que posteriormente podem ser
carregados em um banco de dados PostGIS.
Este arquivo está localizado na pasta bin PostgreSQL qual o local padrão no Windows é o
Programa Files/PostGreSQL/9.2/bin

Faça um conjunto de ferramentas PostGIS


Uma vez que esses arquivos são tão necessários e as vezes um pouco complicado de encontrar mas,
para criar-se um conjunto de ferramentas de auto-suficiente e portável, copie os seguintes arquivos
da pasta bin em c:\ pgutils:
comerr32.dll krb5_32.dll libeay32.dll
libiconv-2.dll libintl-2.dll libpq.dll pgsql2shp.exe psql.exe
pg_dump.exe pg_restore.exe shp2pgsql.exe ssleay32.dll
Nota: O carregador de GUI é empacotado como uma pasta postgisgui auto-suficiente na pasta bin
em sua instalação do PostgreSQL. Se preferir a interface GUI, podemos copiar essa pasta e executar
o arquivo shp2pgsql-gui.exe de qualquer lugar, até mesmo de um caminho de rede em um arquivo
externo.
Carregar (Comando de importação)
O comendo abaixo seria uma forma via linha de comando de importarmos os dados referêntes a
nossa base baixada dos dados do IBGE

1.Abra um prompt de comando.


2.Cd para a pasta que você extraiu os dados do IBGE
3.Execute o seguinte comando: shp2pgsql.exe -s 4326 35MUE250GC_SIR.shp municipios >
municipios.sql
4.shp2pgsql.exe – Aplicação instalada junto com a extensão PostGIS;
5.-s – Parâmetro usado para setar o sistema de coordenadas geográfico;
6.4326 – Faz referencia ao SRID -(Numero equivalente ao sistema de coordenada geográfico WGS
84);
7.35MUE250GC_SIR.shp – E o nome ‘do arquivo’ shape que iremos importar.
8.municipios – Nome da Tabela que sera criada no banco de dados PostgreSQL/PostGIS.
9.municipios.sql – Arquivo que sera gravado na pasta do exe com a
expressão sql referente a criação da tabela espacial e seus
atributos Interface de importação
10.Carregue no banco de dados com o seguinte comando:
psql -d nomedobanco -h localhost -U postgres -f municipios.sql
Se estivermos em outra máquina diferente do servidor, precisaremos alterar localhost para o nome
do servidor. Além disso, pode ser solicitada uma senha. Para o comando acima usaremos a conta de
superusuário postgres padrão, mas seria melhor usar uma conta normal.
11.Alternativamente, podemos utilizar a versão GUI o "shp2pgsql-gui" para carregar os dados
12.Que é um pouco diferente do PostGIS 1.5 carregador, porque permite fazer upload de vários
arquivos ao mesmo tempo. Podendo também editar qualquer uma das configurações para cada
arquivo, clique na célula e a célula se tornará editável.

13.Este conjunto de dados em particular é apenas polígonos. Podemos substituir o comportamento


de trazer como multipolgons clicando no botão Opções de verificação das gerar geometrias
simples ...
14.Uma coisa que podemos fazer com a versão de linha de comando shp2pgsql incorporada com
PostGIS 2.0, que não podemos fazer com a interface gráfica é fazer uma transformação espacial de
um sistema coordenadas para outro. Então linha de comando, podemos transformar a 4326 (WGS
84) e da carga para o tipo de geografia com um único comando. Depois vamos ver isso na GUI em
PostGIS 2.0.1 ou 2.1.0.

A indexação dos dados


Índices da tabela são muito importantes para acelerar o processamento de a maioria das consultas.
Há também uma desvantagem para índices, são os seguintes:
1.Índices retardão a atualização dos campos indexados.
2.Os índices ocupam espaço. Podemos pensar em um índice como outra mesa com fichas para a
primeira semelhante a um índice de um livro.
1.Nunca coloque índices em campos que você não vai usar.
2.Seja cauteloso ao colocar campos de índice em campos que seão muito atualizados. Por exemplo,
se você tem um campo que é atualizado com frequência e é frequentemente usado para a
atualização, você precisa fazer testes de benchmark para garantir que o índice não causará mais
danos em situações de atualização do que para situações de consulta SELECT. Em geral, se o
número de registros que você está atualizando a qualquer momento para um campo específico é
pequeno, será seguro colocar em um índice.
3.Para uploads em massa de uma tabela - por exemplo, se você estiver carregando uma tabela de
uma forma, seria melhor colocar os índices em vigor após a carga de dados, porque se um índice
está em vigor, o sistema estará fazendo a criação de índices junto com o seu carregamento, que
poderia retardar coisas consideravelmente.
4.Se você sabe que um determinado campo é único em uma tabela, é melhor usar um índice
exclusivo ou principal. A razão para isso é que , uma vez encontrado um já existente, não há
necessidade de procurar outro índice. Ele também impede que alguém acidentalmente insira um
registro duplicado, uma vez que irá lançar um erro.
5.Para índices espaciais - usar um índice. Basicamente armazena a caixa delimitadora da geometria
como o índice. Para grandes geometrias complexas, infelizmente, isso não é muito útil.
As perguntas mais comuns que vamos fazer em esta consulta são consultas espaciais e consultas por
área de município. Então, vamos criar dois índices sobre esses campos.
NOTA: O carregador tem uma opção para criar o índice espacial que aproveitamos, então o índice
espacial é a forma necessária apenas para se manter em um nível de carregamento.
CREATE INDEX idx_municipios_geom ON municipios USING gist(geom);
CREATE INDEX idx_municipios ON municipios USING btree(id);

Consultando dados
Volte para pgAdmin III e atualize a arvore de objetos.
Verifique se você tem um banco de dados com a tabela de municipios agora.
Teste as seguintes consultas a partir da ferramenta de consulta
Para instalações de PostGIS 1.2.2 e acima, os nomes das funções preferiu começar com st_

SELECT ST_Extent(geom) FROM municipios WHERE nm_municip = 'Assis';

SELECT ST_Area(ST_Union(geom)) FROM municipios WHERE nm_municip = 'Marília';

Sintaxe pré PostGIS 1.2.2 - Isso não vai funcionar em PostGIS 1.4 + Se você tem um código antigo
deve alterá-lo para a sintaxe acima. Abaixo o código para demonstrar como mudou.
SELECT Extent(geom) from municipios where nm_municip = 'Assis';

SELECT Area(GeomUnion(geom)) FROM municipios where nm_municip = 'Marília';

A maioria das funções no novo postgis instaladas tem um prefixo ST_ . A outra diferença é que os
operadores relacionais com ST_ agora automaticamente usam operadores de índice, como os ST_
só que você precisa fazer uma chamada adicional &&.
Exemplo:a.geom && b.geom AND Intersects(a.geom,b.geom)pode simplesmente
ser escrita como
ST_Intersects(a.geom, b.geom)
Se o dá-lhe acima exibir um erro, como SRIDs mistos, muito provavelmente você está executando
1.3.2 PostGIS que foi muito danificado. Actualiza para o 1.3.3 na próxima oportunidade. Para
verificar a sua instalação. -
SELECT postgis_full_version();

Visualizando os Dados
Recomendamos usar Quantum GIS para visualização dos atributos SIG. Pode ser usado outros SIGs
como UDIG, GVSIG ... mas o Quantum GIS tem capacidade de exibir dados PostGIS diretamente,
e tem filtros simples sobre para trabalho com os atributos cartográficos, é livre OpenSource, é
multi-plataforma (Linux, Windows, MacOSX, Unix) e é o um dos SIGs que tem mais aceitação
pela comunidade.
Parte 2: Introdução à consultas espaciais e SFSQL com PostGIS

O que é SFSQL?
Uma das grandes coisas sobre Bancos de Dados Relacionais com extensão espacial, é que eles
trazem o SIG para um novo nível, permitindo-lhe aplicar expressões SQL declarativa para o
domínio espacial. Com bancos de dados relacionais com extensões espaciais, você pode facilmente
responder a perguntas como, qual é a renda familiar média de um bloco de bairro. O distrito político
do qual residem dentro de X. Este novo recurso que se casa com SQL com SIG é chamado Simple
Features for SQL (SFSQL. O objetivo de SFSQL é introduzir um novo conjunto de funções e
funções de agregação para a linguagem SQL.

Algumas consultas comuns


Nesta próxima seção, vamos ver algumas consultas comuns, utilizando os dados que baixamos na
Parte 1. Apesar de estarmos usando PostGIS para este exercício, a maioria dos bancos de dados
relacionais espaciais tais como Oracle Spatial, ArcSDE, DB Spatial Extender, tem sintaxe similar.

Transformação a partir de um sistema de coordenadas


para outro
Para usar a reprojeção de coordenadas utiliza-se a função ST_Transform
● SELECT ST_AsText(the_geom) FROM bc_roads LIMIT 1;
● SELECT ST_AsText(ST_Transform(the_geom,4326)) FROM bc_roads LIMIT 1;

Obtendo Latitude e Longitude Centroid


A fim de obter a latitude e longitude de nossos dados, precisamos que o nosso sistema de referência
de coordenadas esteja em alguma latitude e longitude. Para começar, primeiro precisamos
transformar os nossos dados para alguma variante do long lat. Então encontramos o baricentro e, em
seguida, as coordenadas x e y .

SELECT municipios, ST_X(ST_Centroid(ST_Transform(geom, 4326))) as


longitude, ST_Y(ST_Centroid(ST_Transform(geom, 4326))) as
latitude
FROM municipios ST_Y(ST_Centroid(ST_Transform(geom, 4326))) as
latitude
FROM towns

Funções de agregação
Funções agregadas espaciais são muito parecidas com funções regulares de agregação SQL, como o
AVG, SUM, COUNT em que eles trabalham com GROUP BY e HAVING usados para recolher
vários registros em um único registro (agrupamento de valores). Se você não estiver familiarizado
com os termos acima - dê uma olhada no resumo de dados com SQL (Structured Query Language)

Extensão
A função de extensão é uma função de agregação que lhe dá a caixa delimitadora de um conjunto de
geometrias. É especialmente útil para determinar o retângulo delimitador da área que você está
tentando mapear. Por exemplo, se quiséssemos encontrar a caixa delimitadora da área do município
de Assis , poderiamos fazer algo assim.
SELECT nm_municip, ST_Extent(ST_Transform(geom, 4225)) as
the_extent FROM municipios WHERE nm_municip = 'Assis' GROUP BY
nm_municip

ST_Union
A função ST_Union é uma função de agregação que leva um conjunto de geometrias e sintetizar
unir para criar um campo de geometria única. Em versões anteriores ao PostGIS 1.2, este foi
chamado geomunion eo nome antigo foi completamente removido em PostGIS 2.0. Para os nossos
dados de municípios, podemos ter vários registros por cidade. Para obter uma única geometria que
representa a região total de uma cidade, poderíamos usar a função geomunion como no exemplo
abaixo.
select nm_sigla, ST_Union(geom) as thegeom from malha_viaria_principal group by
nm_sigla;
É importante notar que, enquanto a consulta acima lhe dará um registro por nome de rodovia. A
consulta origiinal retornará
select nm_sigla, geom as thegeom from malha_viaria_principal;

Essa consulta retornará vários registros por nome de rodovia se


existe registro múltipla por rodovia(Malha viária).

Vendo resultados visualmente


Para ter uma noção visual do que todas esses diferentes consultas estão exibindo, você pode salvar
as saídas acima como um arquivo de forma ESRI usando a ferramenta pgsql2shp e vê-lo usando um
visualizador forma como QuantumGIS ou Criar uma tabela temporária para ser visualizada
somente.
pgsql2shp -f myshp -h myserver -u apguser -P apgpassword -g
thegeom mygisdb "select nm_sigla, geomunion(geom) as thegeom from
malhas_viarias_principais group by nm_sigla"
É importante ressaltar: o utilitário de carregamento dos dados só pode aceitar campos do tipo de
geometria. Assim, por exemplo, para despejar um tipo bbox como o que é retornado pela função de
extensão, precisaremos lançar a saída como uma geometria, abaixo um exemplo:
SELECT nm_sigla, ST_SetSRID(ST_Extent(ST_Transform(geom, 4225))::geometry,4225)
as theextent FROM malhas_viarias_principais WHERE nm_sigla = 'SP-461' GROUP BY
nm_sigla

Consultas de distância
Obtendo distância minima e utilização da função ST_Distance
Uma pergunta comum feita dentro de um banco de dados espacial é o quão longe um objeto pode
ser do outro. Tanto o PostGIS, como outros bancos de dados espaciais semelhantes tem uma função
chamada distância(ST_DISTANCE), que irá dizer-lhe a distância mínima entre uma geometria a
partir de outra.
Temos um exemplo de tal utilização abaixo. A consulta abaixo irá dizer-lhe quão longe cada registro
é de outro. Neste caso. Distância é sempre medido na métrica do seu sistema de referência espacial.
--Qual a distância entre as cidades de Assis e Campinas
SELECT ST_Distance(ST_Transform(a.geom,4225),
ST_Transform(b.geom,4225)) distancia
FROM principais_cidades a, principais_cidades b
WHERE a.nm_nome = 'Marília' AND b.nm_nome = 'Campinas';
Se as geometrias acima fossem polígonos, então poderíamos estar recebendo a distância mínima a
partir de qualquer ponto em cada polígono para o outro. Para geometrias de ponto, não há distinção
entre uma distância mínima e outras distâncias.

Obtendo Média Distância utilizando a função Centroid


Se não estamos lidando apenas com pontos, então há todos os tipos de distâncias que poderiam ser
pedindo. Por exemplo Se quiséssemos a distância média entre dois polígonos, então nós queremos a
distância entre os centroides. Uma distância média da geometria 1 e da geometria 2, então, seria
assim.

SELECT ST_Distance(ST_Centroid(a.geom)),
ST_Centroid(b.geom)) distancia
FROM principais_cidades a, principais_cidades b
WHERE a.nm_nome = 'Marília' AND b.nm_nome = 'Campinas';

Obtendo uma lista de objetos que estão dentro de X


distância de um outro objeto
Uma pergunta feita freqüentemente é o que está dentro zipcodes x longe da minha zip?. Para isso
seria de pensar que simplesmente fazer uma distância <x seria suficiente.Isso seria suficiente,
exceto que seria lento, uma vez que não está aproveitando índices PostGIS e também porque se as
geometrias que você está comparando são bastante complexos, a busca pode ser exaustiva. Para
escrever a consulta da forma mais eficiente, que incluiria o uso da função Expandir. Assim
comoSELECT z.zipcode FROM zipcode z, zipcode z2 WHERE z2.zipcode =
'02109' AND ST_DWithin(z2.geom_meter, z.geom,3000)
O ST_DWithin leva a caixa delimitadora de uma geometria e se expande para fora X em todas as
direções e, em seguida, faz uma verificação de distância mais exaustiva sobre as geometrias
reais. Portanto, neste caso estaríamos ampliando nossa geometria zip 02109 a 3000 metros.
Ele usa internamente o operador && é o operador interage que retorna true se duas geometrias salto
de caixas cruzam e falsa se não o fizerem. É um muito mais rápido, especialmente se você tem
índices em suas geometrias porque utiliza o índice da caixa delimitadora.
Documentação
PostgreSQL PostGIS Geometry/Geography/Box Types
box2d A box composed of x min, ymin, xmax, ymax. Often used to return the 2d enclosing box of a geometry.
box3d A box composed of x min, ymin, zmin, xmax, ymax, zmax. Often used to return the 3d extent of a geometry or
collection of geometries.
geometry Planar spatial data type.
geometry_dump A spatial datatype with two fields - geom (holding a geometry object) and path[] (a 1-d array holding
the position of the geometry within the dumped object.)
geography Ellipsoidal spatial data type.

Management Functions
AddGeometryColumn2 3d Adds a geometry column to an existing table of attributes. By default uses type modifier to
define rather than constraints. Pass in false for use_typmod to get old check constraint based behavior

1. table_name, column_name, srid, type, dimension, use_typmod=true


2. schema_name, table_name, column_name, srid, type, dimension, use_typmod=true
3. catalog_name, schema_name, table_name, column_name, srid, type, dimension, use_typmod=true

DropGeometryColumn3d Removes a geometry column from a spatial table.

1. table_name, column_name
2. schema_name, table_name, column_name
3. catalog_name, schema_name, table_name, column_name

DropGeometryTable Drops a table and all its references in geometry_columns.

1. table_name
2. schema_name, table_name
3. catalog_name, schema_name, table_name

PostGIS_Full_Version () Reports full postgis version and build configuration infos.


PostGIS_GEOS_Version () Returns the version number of the GEOS library.
PostGIS_LibXML_Version () Returns the version number of the libxml2 library.
PostGIS_Lib_Build_Date () Returns build date of the PostGIS library.
PostGIS_Lib_Version () Returns the version number of the PostGIS library.
PostGIS_PROJ_Version () Returns the version number of the PROJ4 library.
PostGIS_Scripts_Build_Date () Returns build date of the PostGIS scripts.
PostGIS_Scripts_Installed () Returns version of the postgis scripts installed in this database.
PostGIS_Scripts_Released () Returns the version number of the postgis.sql script released with the installed
postgis lib.
PostGIS_Version () Returns PostGIS version number and compile-time options.
Populate_Geometry_Columns2 Ensures geometry columns are defined with type modifiers or have appropriate
spatial constraints This ensures they will be registered correctly in geometry_columns view. By default will convert all geometry
columns with no type modifier to ones with type modifiers. To get old behavior set use_typmod=false

1. use_typmod=true
2. relation_oid, use_typmod=true

UpdateGeometrySRID3d Updates the SRID of all features in a geometry column, geometry_columns metadata and
srid. If it was enforced with constraints, the constraints will be updated with new srid constraint. If the old was enforced by type
definition, the type definition will be changed.

1. table_name, column_name, srid


2. schema_name, table_name, column_name, srid
3. catalog_name, schema_name, table_name, column_name, srid

Geometry Constructors
ST_BdPolyFromText (WKT, srid) Construct a Polygon given an arbitrary collection of closed linestrings as a
MultiLineString Well-Known text representation.
ST_BdMPolyFromText (WKT, srid) Construct a MultiPolygon given an arbitrary collection of closed linestrings as a
MultiLineString text representation Well-Known text representation.

ST_GeogFromTextG (EWKT) Return a specified geography value from Well-Known Text representation or extended
(WKT).

ST_GeographyFromTextG (EWKT) Return a specified geography value from Well-Known Text representation or
extended (WKT).

ST_GeogFromWKBG (geom) Creates a geography instance from a Well-Known Binary geometry representation
(WKB) or extended Well Known Binary (EWKB).

ST_GeomCollFromTextmm Makes a collection Geometry from collection WKT with the given SRID. If SRID is not
give, it defaults to -1.

1. WKT, srid
2. WKT

ST_GeomFromEWKB2 3d (EWKB) Return a specified ST_Geometry value from Extended Well-Known Binary
representation (EWKB).

ST_GeomFromEWKT2 3d (EWKT) Return a specified ST_Geometry value from Extended Well-Known Text
representation (EWKT).

ST_GeometryFromTextmm Return a specified ST_Geometry value from Well-Known Text representation (WKT).
This is an alias name for ST_GeomFromText

1. WKT
2. WKT, srid

ST_GeomFromGML2 3d Takes as input GML representation of geometry and outputs a PostGIS geometry object

1. geomgml
2. geomgml, srid

ST_GeomFromGeoJSON1 3d (geomjson) Takes as input a geojson representation of a geometry and outputs a


PostGIS geometry object

ST_GeomFromKML3d (geomkml) Takes as input KML representation of geometry and outputs a PostGIS geometry
object

ST_GMLToSQL2 mm Return a specified ST_Geometry value from GML representation. This is an alias name for
ST_GeomFromGML

1. geomgml
2. geomgml, srid

ST_GeomFromTextmm Return a specified ST_Geometry value from Well-Known Text representation (WKT).

1. WKT
2. WKT, srid

ST_GeomFromWKBmm Creates a geometry instance from a Well-Known Binary geometry representation (WKB)
and optional SRID.

1. geom
2. geom, srid

ST_LineFromMultiPoint3d (aMultiPoint) Creates a LineString from a MultiPoint geometry.


ST_LineFromTextmm Makes a Geometry from WKT representation with the given SRID. If SRID is not given, it
defaults to -1.

1. WKT
2. WKT, srid

ST_LineFromWKBmm Makes a LINESTRING from WKB with the given SRID

1. WKB
2. WKB, srid

ST_LinestringFromWKBmm Makes a geometry from WKB with the given SRID.

1. WKB
2. WKB, srid

ST_MakeBox2D (pointLowLeft, pointUpRight) Creates a BOX2D defined by the given point geometries.
ST_3DMakeBox3d (point3DLowLeftBottom, point3DUpRightTop) Creates a BOX3D defined by the given 3d point
geometries.

ST_MakeLine1 3d Creates a Linestring from point or line geometries.

1. geoms
2. geom1, geom2
3. geoms_array

ST_MakeEnvelope2 (xmin, ymin, xmax, ymax, srid=unknown) Creates a rectangular Polygon formed from the given
minimums and maximums. Input values must be in SRS specified by the SRID.

ST_MakePolygon3d Creates a Polygon formed by the given shell. Input geometries must be closed LINESTRINGS.
1. linestring
2. outerlinestring, interiorlinestrings

ST_MakePoint3d Creates a 2D,3DZ or 4D point geometry.

1. x, y
2. x, y, z
3. x, y, z, m

ST_MakePointM (x, y, m) Creates a point geometry with an x y and m coordinate.

ST_MLineFromTextmm Return a specified ST_MultiLineString value from WKT representation.

1. WKT, srid
2. WKT

ST_MPointFromTextmm Makes a Geometry from WKT with the given SRID. If SRID is not give, it defaults to -1.

1. WKT, srid
2. WKT

ST_MPolyFromTextmm Makes a MultiPolygon Geometry from WKT with the given SRID. If SRID is not give, it
defaults to -1.

1. WKT, srid
2. WKT

ST_Pointmm (x_lon, y_lat) Returns an ST_Point with the given coordinate values. OGC alias for ST_MakePoint.

ST_PointFromTextmm Makes a point Geometry from WKT with the given SRID. If SRID is not given, it defaults to
unknown.

1. WKT
2. WKT, srid

ST_PointFromWKBmm 3d Makes a geometry from WKB with the given SRID

1. geom
2. geom, srid

ST_Polygonmm 3d (aLineString, srid) Returns a polygon built from the specified linestring and SRID.
ST_PolygonFromTextmm Makes a Geometry from WKT with the given SRID. If SRID is not give, it defaults to -1.
1. WKT
2. WKT, srid

ST_WKBToSQLmm (WKB) Return a specified ST_Geometry value from Well-Known Binary representation (WKB).
This is an alias name for ST_GeomFromWKB that takes no srid

ST_WKTToSQLmm (WKT) Return a specified ST_Geometry value from Well-Known Text representation (WKT). This
is an alias name for ST_GeomFromText

Geometry Accessors
GeometryType2 3d (geomA) Returns the type of the geometry as a string. Eg: 'LINESTRING', 'POLYGON',
'MULTIPOINT', etc.

ST_Boundarymm 3d (geomA) Returns the closure of the combinatorial boundary of this Geometry.
ST_CoordDimmm 3d (geomA) Return the coordinate dimension of the ST_Geometry value.
ST_Dimension2 mm (g) The inherent dimension of this Geometry object, which must be less than or equal to the
coordinate dimension.
mm 3d
ST_EndPoint (g) Returns the last point of a LINESTRING geometry as a POINT.
mm
ST_Envelope (g1) Returns a geometry representing the double precision (float8) bounding box of the supplied
geometry.

ST_ExteriorRingmm 3d (a_polygon) Returns a line string representing the exterior ring of the POLYGON geometry.
Return NULL if the geometry is not a polygon. Will not work with MULTIPOLYGON

ST_GeometryN2 mm 3d (geomA, n) Return the 1-based Nth geometry if the geometry is a GEOMETRYCOLLECTION,
(MULTI)POINT, (MULTI)LINESTRING, MULTICURVE or (MULTI)POLYGON, POLYHEDRALSURFACE Otherwise, return
NULL.

ST_GeometryType2 mm 3d (g1) Return the geometry type of the ST_Geometry value.


ST_InteriorRingNmm 3d (a_polygon, n) Return the Nth interior linestring ring of the polygon geometry. Return NULL if
the geometry is not a polygon or the given N is out of range.

ST_IsClosed2 mm 3d (g) Returns TRUE if the LINESTRING's start and end points are coincident. For Polyhedral
surface is closed (volumetric).

ST_IsCollection3d (g) Returns TRUE if the argument is a collection (MULTI*, GEOMETRYCOLLECTION, ...)
ST_IsEmptymm (geomA) Returns true if this Geometry is an empty geometrycollection, polygon, point etc.
ST_IsRingmm (g) Returns TRUE if this LINESTRING is both closed and simple.
ST_IsSimplemm 3d (geomA) Returns (TRUE) if this Geometry has no anomalous geometric points, such as self
intersection or self tangency.

ST_IsValidmm g3.3 Returns true if the ST_Geometry is well formed.


1. g
2. g, flags

ST_IsValidReason1 g3.3 Returns text stating if a geometry is valid or not and if not valid, a reason why.

1. geomA
2. geomA, flags

ST_IsValidDetail1 g3.3 Returns a valid_detail (valid,reason,location) row stating if a geometry is valid or not and if not
valid, a reason why and a location where.

1. geom
2. geom, flags

ST_Mmm 3d (a_point) Return the M coordinate of the point, or NULL if not available. Input must be a point.
ST_NDims3d (g1) Returns coordinate dimension of the geometry as a small int. Values are: 2,3 or 4.
ST_NPoints2 3d (g1) Return the number of points (vertexes) in a geometry.
ST_NRings3d (geomA) If the geometry is a polygon or multi-polygon returns the number of rings.
ST_NumGeometries2 mm 3d (geom) If geometry is a GEOMETRYCOLLECTION (or MULTI*) return the number of
geometries, for single geometries will return 1, otherwise return NULL.

ST_NumInteriorRingsmm (a_polygon) Return the number of interior rings of the first polygon in the geometry. This
will work with both POLYGON and MULTIPOLYGON types but only looks at the first polygon. Return NULL if there is no
polygon in the geometry.

ST_NumInteriorRingmm (a_polygon) Return the number of interior rings of the first polygon in the geometry.
Synonym to ST_NumInteriorRings.

ST_NumPatches1 mm 3d (g1) Return the number of faces on a Polyhedral Surface. Will return null for non-polyhedral
geometries.

ST_NumPointsmm (g1) Return the number of points in an ST_LineString or ST_CircularString value.


ST_PatchN1 mm 3d (geomA, n) Return the 1-based Nth geometry (face) if the geometry is a POLYHEDRALSURFACE,
POLYHEDRALSURFACEM. Otherwise, return NULL.

ST_PointNmm 3d (a_linestring, n) Return the Nth point in the first linestring or circular linestring in the geometry. Return
NULL if there is no linestring in the geometry.

ST_SRIDmm (g1) Returns the spatial reference identifier for the ST_Geometry as defined in spatial_ref_sys table.
ST_StartPointmm 3d (geomA) Returns the first point of a LINESTRING geometry as a POINT.
ST_SummaryG Returns a text summary of the contents of the geometry.
1. g
2. g

ST_Xmm 3d (a_point) Return the X coordinate of the point, or NULL if not available. Input must be a point.
ST_XMax3d (aGeomorBox2DorBox3D) Returns X maxima of a bounding box 2d or 3d or a geometry.
ST_XMin3d (aGeomorBox2DorBox3D) Returns X minima of a bounding box 2d or 3d or a geometry.
ST_Ymm 3d (a_point) Return the Y coordinate of the point, or NULL if not available. Input must be a point.
ST_YMax3d (aGeomorBox2DorBox3D) Returns Y maxima of a bounding box 2d or 3d or a geometry.
ST_YMin3d (aGeomorBox2DorBox3D) Returns Y minima of a bounding box 2d or 3d or a geometry.
ST_Zmm 3d (a_point) Return the Z coordinate of the point, or NULL if not available. Input must be a point.
ST_ZMax3d (aGeomorBox2DorBox3D) Returns Z minima of a bounding box 2d or 3d or a geometry.
ST_Zmflag3d (geomA) Returns ZM (dimension semantic) flag of the geometries as a small int. Values are: 0=2d, 1=3dm,
2=3dz, 3=4d.
3d
ST_ZMin (aGeomorBox2DorBox3D) Returns Z minima of a bounding box 2d or 3d or a geometry.

Geometry Editors
3d
ST_AddPoint Adds a point to a LineString before point (0-based index).

1. linestring, point
2. linestring, point, position

ST_Affine2 3d Applies a 3d affine transformation to the geometry to do things like translate, rotate, scale in one step.

1. geomA, a, b, c, d, e, f, g, h, i, xoff, yoff, zoff


2. geomA, a, b, d, e, xoff, yoff

ST_Force_2D2 3d (geomA) Forces the geometries into a "2-dimensional mode" so that all output representations will
only have the X and Y coordinates.

ST_Force_3D2 3d (geomA) Forces the geometries into XYZ mode. This is an alias for ST_Force_3DZ.
ST_Force_3DZ2 3d (geomA) Forces the geometries into XYZ mode. This is a synonym for ST_Force_3D.
ST_Force_3DM (geomA) Forces the geometries into XYM mode.
ST_Force_4D3d (geomA) Forces the geometries into XYZM mode.
ST_Force_Collection2 3d (geomA) Converts the geometry into a GEOMETRYCOLLECTION.
ST_ForceRHR2 3d (g) Forces the orientation of the vertices in a polygon to follow the Right-Hand-Rule.
ST_LineMerge (amultilinestring) Returns a (set of) LineString(s) formed by sewing together a MULTILINESTRING.
ST_CollectionExtract (collection, type) Given a (multi)geometry, returns a (multi)geometry consisting only of
elements of the specified type.

ST_CollectionHomogenize1 (collection) Given a geometry collection, returns the "simplest" representation of the
contents.
ST_Multi (g1) Returns the geometry as a MULTI* geometry. If the geometry is already a MULTI*, it is returned unchanged.
ST_RemovePoint3d (linestring, offset) Removes point from a linestring. Offset is 0-based.
ST_Reverse (g1) Returns the geometry with vertex order reversed.
ST_Rotate2 3d Rotate a geometry rotRadians counter-clockwise about an origin.
1. geomA, rotRadians
2. geomA, rotRadians, x0, y0
3. geomA, rotRadians, pointOrigin

ST_RotateX2 3d (geomA, rotRadians) Rotate a geometry rotRadians about the X axis.


ST_RotateY2 3d (geomA, rotRadians) Rotate a geometry rotRadians about the Y axis.
ST_RotateZ2 3d (geomA, rotRadians) Rotate a geometry rotRadians about the Z axis.
ST_Scale2 3d Scales the geometry to a new size by multiplying the ordinates with the parameters. Ie: ST_Scale(geom,
Xfactor, Yfactor, Zfactor).

1. geomA, XFactor, YFactor, ZFactor


2. geomA, XFactor, YFactor

ST_Segmentize (geomA, max_length) Return a modified geometry having no segment longer than the given distance.
Distance computation is performed in 2d only.

ST_SetPoint3d (linestring, zerobasedposition, point) Replace point N of linestring with given point. Index is 0-based.
ST_SetSRID (geom, srid) Sets the SRID on a geometry to a particular integer value.
ST_SnapToGrid3d Snap all points of the input geometry to a regular grid.
1. geomA, originX, originY, sizeX, sizeY
2. geomA, sizeX, sizeY
3. geomA, size
4. geomA, pointOrigin, sizeX, sizeY, sizeZ, sizeM

ST_Snap1 g3.3 (input, reference, tolerance) Snap segments and vertices of input geometry to vertices of a reference
geometry.

ST_Transform2 mm (g1, srid) Returns a new geometry with its coordinates transformed to the SRID referenced by the
integer parameter.

ST_Translate3d Translates the geometry to a new location using the numeric parameters as offsets. Ie:
ST_Translate(geom, X, Y) or ST_Translate(geom, X, Y,Z).

1. g1, deltax, deltay


2. g1, deltax, deltay, deltaz

ST_TransScale3d (geomA, deltaX, deltaY, XFactor, YFactor) Translates the geometry using the deltaX and deltaY
args, then scales it using the XFactor, YFactor args, working in 2D only.

Geometry Outputs
ST_AsBinary2 mm G 3d Return the Well-Known Binary (WKB) representation of the geometry/geography without SRID
meta data.

1. g1
2. g1, NDR_or_XDR
3. g1
4. g1, NDR_or_XDR

ST_AsEWKB2 3d Return the Well-Known Binary (WKB) representation of the geometry with SRID meta data.

1. g1
2. g1, NDR_or_XDR

ST_AsEWKT2 G 3d Return the Well-Known Text (WKT) representation of the geometry with SRID meta data.

1. g1
2. g1

ST_AsGeoJSONG 3d Return the geometry as a GeoJSON element.

1. geom, maxdecimaldigits=15, options=0


2. geog, maxdecimaldigits=15, options=0
3. gj_version, geom, maxdecimaldigits=15, options=0
4. gj_version, geog, maxdecimaldigits=15, options=0

ST_AsGML2 G 3d Return the geometry as a GML version 2 or 3 element.

1. geom, maxdecimaldigits=15, options=0


2. geog, maxdecimaldigits=15, options=0
3. version, geom, maxdecimaldigits=15, options=0, nprefix=null
4. version, geog, maxdecimaldigits=15, options=0, nprefix=null

ST_AsHEXEWKB3d Returns a Geometry in HEXEWKB format (as text) using either little-endian (NDR) or big-endian
(XDR) encoding.

1. g1, NDRorXDR
2. g1

ST_AsKML2 G 3d Return the geometry as a KML element. Several variants. Default version=2, default precision=15

1. geom, maxdecimaldigits=15
2. geog, maxdecimaldigits=15
3. version, geom, maxdecimaldigits=15, nprefix=NULL
4. version, geog, maxdecimaldigits=15, nprefix=NULL

ST_AsSVGG Returns a Geometry in SVG path data given a geometry or geography object.

1. geom, rel=0, maxdecimaldigits=15


2. geog, rel=0, maxdecimaldigits=15

ST_AsX3D1 3d (g1, maxdecimaldigits=15, options=0) Returns a Geometry in X3D xml node element format: ISO-IEC-
19776-1.2-X3DEncodings-XML
ST_GeoHash (geom, maxchars=full_precision_of_point) Return a GeoHash representation (geohash.org) of the
geometry.

ST_AsTextmm G Return the Well-Known Text (WKT) representation of the geometry/geography without SRID metadata.

1. g1
2. g1

ST_AsLatLonText1 Return the Degrees, Minutes, Seconds representation of the given point.

1. pt
2. pt, format

Operators
2G
&& Returns TRUE if A's 2D bounding box intersects B's 2D bounding box.

1. A, B
2. A, B

&&&1 3d (A, B) Returns TRUE if A's 3D bounding box intersects B's 3D bounding box.
&< (A, B) Returns TRUE if A's bounding box overlaps or is to the left of B's.
&<| (A, B) Returns TRUE if A's bounding box overlaps or is below B's.
&> (A, B) Returns TRUE if A' bounding box overlaps or is to the right of B's.
<< (A, B) Returns TRUE if A's bounding box is strictly to the left of B's.
<<| (A, B) Returns TRUE if A's bounding box is strictly below B's.
=G Returns TRUE if A's bounding box is the same as B's. Uses double precision bounding box.
1. A, B
2. A, B

>> (A, B) Returns TRUE if A's bounding box is strictly to the right of B's.
@ (A, B) Returns TRUE if A's bounding box is contained by B's.
|&> (A, B) Returns TRUE if A's bounding box overlaps or is above B's.
|>> (A, B) Returns TRUE if A's bounding box is strictly above B's.
~ (A, B) Returns TRUE if A's bounding box contains B's.
~= (A, B) Returns TRUE if A's bounding box is the same as B's.
<->1 (A, B) Returns the distance between two points. For point / point checks it uses floating point accuracy (as opposed to
the double precision accuracy of the underlying point geometry). For other geometry types the distance between the floating
point bounding box centroids is returned. Useful for doing distance ordering and nearest neighbor limits using KNN gist
functionality.

<#>1 (A, B) Returns the distance between bounding box of 2 geometries. For point / point checks it's almost the same as
distance (though may be different since the bounding box is at floating point accuracy and geometries are double precision).
Useful for doing distance ordering and nearest neighbor limits using KNN gist functionality.

Spatial Relationships and Measurements


ST_3DClosestPoint1 3d (g1, g2) Returns the 3-dimensional point on g1 that is closest to g2. This is the first point of
the 3D shortest line.

ST_3DDistance1 mm 3d (g1, g2) For geometry type Returns the 3-dimensional cartesian minimum distance (based on
spatial ref) between two geometries in projected units.

ST_3DDWithin1 mm 3d (g1, g2, distance_of_srid) For 3d (z) geometry type Returns true if two geometries 3d distance
is within number of units.

ST_3DDFullyWithin1 3d (g1, g2, distance) Returns true if all of the 3D geometries are within the specified distance of
one another.

ST_3DIntersects1 mm 3d (geomA, geomB) Returns TRUE if the Geometries "spatially intersect" in 3d - only for points
and linestrings

ST_3DLongestLine1 3d (g1, g2) Returns the 3-dimensional longest line between two geometries
ST_3DMaxDistance1 3d (g1, g2) For geometry type Returns the 3-dimensional cartesian maximum distance (based
on spatial ref) between two geometries in projected units.

ST_3DShortestLine1 3d (g1, g2) Returns the 3-dimensional shortest line between two geometries
ST_Area2 mm G Returns the area of the surface if it is a polygon or multi-polygon. For "geometry" type area is in SRID
units. For "geography" area is in square meters.

1. g1
2. geog, use_spheroid=true

ST_Azimuth2 G Returns the angle in radians from the horizontal of the vector defined by pointA and pointB. Angle is
computed clockwise from down-to-up: on the clock: 12=0; 3=PI/2; 6=PI; 9=3PI/2.

1. pointA, pointB
2. pointA, pointB

ST_Centroidmm (g1) Returns the geometric center of a geometry.


ST_ClosestPoint (g1, g2) Returns the 2-dimensional point on g1 that is closest to g2. This is the first point of the
shortest line.

ST_Containsmm (geomA, geomB) Returns true if and only if no points of B lie in the exterior of A, and at least one point
of the interior of B lies in the interior of A.
ST_ContainsProperly (geomA, geomB) Returns true if B intersects the interior of A but not the boundary (or exterior).
A does not contain properly itself, but does contain itself.

ST_CoversG Returns 1 (TRUE) if no point in Geometry B is outside Geometry A


1. geomA, geomB
2. geogpolyA, geogpointB

ST_CoveredByG Returns 1 (TRUE) if no point in Geometry/Geography A is outside Geometry/Geography B

1. geomA, geomB
2. geogA, geogB

ST_Crossesmm (g1, g2) Returns TRUE if the supplied geometries have some, but not all, interior points in common.
ST_LineCrossingDirection (linestringA, linestringB) Given 2 linestrings, returns a number between -3 and 3
denoting what kind of crossing behavior. 0 is no crossing.

ST_Disjointmm (A, B) Returns TRUE if the Geometries do not "spatially intersect" - if they do not share any space
together.

ST_Distancemm G For geometry type Returns the 2-dimensional cartesian minimum distance (based on spatial ref)
between two geometries in projected units. For geography type defaults to return spheroidal minimum distance between two
geographies in meters.

1. g1, g2
2. gg1, gg2
3. gg1, gg2, use_spheroid

ST_HausdorffDistance Returns the Hausdorff distance between two geometries. Basically a measure of how similar
or dissimilar 2 geometries are. Units are in the units of the spatial reference system of the geometries.

1. g1, g2
2. g1, g2, densifyFrac

ST_MaxDistance (g1, g2) Returns the 2-dimensional largest distance between two geometries in projected units.
ST_Distance_Sphere (geomlonlatA, geomlonlatB) Returns minimum distance in meters between two lon/lat
geometries. Uses a spherical earth and radius of 6370986 meters. Faster than ST_Distance_Spheroid , but less accurate.
PostGIS versions prior to 1.5 only implemented for points.
ST_Distance_Spheroid (geomlonlatA, geomlonlatB, measurement_spheroid) Returns the minimum distance
between two lon/lat geometries given a particular spheroid. PostGIS versions prior to 1.5 only support points.
ST_DFullyWithin (g1, g2, distance) Returns true if all of the geometries are within the specified distance of one another
ST_DWithinG Returns true if the geometries are within the specified distance of one another. For geometry units are in
those of spatial reference and For geography units are in meters and measurement is defaulted to use_spheroid=true
(measure around spheroid), for faster check, use_spheroid=false to measure along sphere.

1. g1, g2, distance_of_srid


2. gg1, gg2, distance_meters
3. gg1, gg2, distance_meters, use_spheroid

ST_Equalsmm (A, B) Returns true if the given geometries represent the same geometry. Directionality is ignored.
ST_HasArc3d (geomA) Returns true if a geometry or geometry collection contains a circular string
ST_Intersectsmm G Returns TRUE if the Geometries/Geography "spatially intersect in 2D" - (share any portion of
space) and FALSE if they don't (they are Disjoint). For geography -- tolerance is 0.00001 meters (so any points that close are
considered to intersect)

1. geomA, geomB
2. geogA, geogB

ST_Lengthmm G Returns the 2d length of the geometry if it is a linestring or multilinestring. geometry are in units of
spatial reference and geography are in meters (default spheroid)

1. a_2dlinestring
2. geog, use_spheroid=true

ST_Length2D (a_2dlinestring) Returns the 2-dimensional length of the geometry if it is a linestring or multi-linestring.
This is an alias for ST_Length

ST_3DLength3d (a_3dlinestring) Returns the 3-dimensional or 2-dimensional length of the geometry if it is a linestring
or multi-linestring.

ST_Length_Spheroid3d (a_linestring, a_spheroid) Calculates the 2D or 3D length of a linestring/multilinestring on an


ellipsoid. This is useful if the coordinates of the geometry are in longitude/latitude and a length is desired without reprojection.
ST_Length2D_Spheroid (a_linestring, a_spheroid) Calculates the 2D length of a linestring/multilinestring on an
ellipsoid. This is useful if the coordinates of the geometry are in longitude/latitude and a length is desired without reprojection.
ST_3DLength_Spheroid3d (a_linestring, a_spheroid) Calculates the length of a geometry on an ellipsoid, taking the
elevation into account. This is just an alias for ST_Length_Spheroid.
ST_LongestLine (g1, g2) Returns the 2-dimensional longest line points of two geometries. The function will only return
the first longest line if more than one, that the function finds. The line returned will always start in g1 and end in g2. The length
of the line this function returns will always be the same as st_maxdistance returns for g1 and g2.

ST_OrderingEqualsmm (A, B) Returns true if the given geometries represent the same geometry and points are in
the same directional order.

ST_Overlapsmm (A, B) Returns TRUE if the Geometries share space, are of the same dimension, but are not
completely contained by each other.

ST_Perimetermm G Return the length measurement of the boundary of an ST_Surface or ST_MultiSurface geometry or
geography. (Polygon, Multipolygon). geometry measurement is in units of spatial reference and geography is in meters.

1. g1
2. geog, use_spheroid=true

ST_Perimeter2D (geomA) Returns the 2-dimensional perimeter of the geometry, if it is a polygon or multi-polygon. This
is currently an alias for ST_Perimeter.

ST_3DPerimeter3d (geomA) Returns the 3-dimensional perimeter of the geometry, if it is a polygon or multi-polygon.
ST_PointOnSurfacemm 3d (g1) Returns a POINT guaranteed to lie on the surface.
ST_Project1 G (g1, distance, azimuth) Returns a POINT projected from a start point using a distance in meters and
bearing (azimuth) in radians.

ST_Relate2 mm Returns true if this Geometry is spatially related to anotherGeometry, by testing for intersections
between the Interior, Boundary and Exterior of the two geometries as specified by the values in the intersectionMatrixPattern. If
no intersectionMatrixPattern is passed in, then returns the maximum intersectionMatrixPattern that relates the 2 geometries.

1. geomA, geomB, intersectionMatrixPattern


2. geomA, geomB
3. geomA, geomB, BoundaryNodeRule

ST_RelateMatch1 g3.3 (intersectionMatrix, intersectionMatrixPattern) Returns true if intersectionMattrixPattern1


implies intersectionMatrixPattern2
ST_ShortestLine (g1, g2) Returns the 2-dimensional shortest line between two geometries
ST_Touchesmm (g1, g2) Returns TRUE if the geometries have at least one point in common, but their interiors do not
intersect.

ST_Withinmm (A, B) Returns true if the geometry A is completely inside geometry B

Geometry Processing
mm G
ST_Buffer (T) For geometry: Returns a geometry that represents all points whose distance from this Geometry is
less than or equal to distance. Calculations are in the Spatial Reference System of this Geometry. For geography: Uses a
planar transform wrapper. Introduced in 1.5 support for different end cap and mitre settings to control shape. buffer_style
options: quad_segs=#,endcap=round|flat|square,join=round|mitre|bevel,mitre_limit=#.#

1. g1, radius_of_buffer
2. g1, radius_of_buffer, num_seg_quarter_circle
3. g1, radius_of_buffer, buffer_style_parameters
4. g1, radius_of_buffer_in_meters

ST_BuildArea (A) Creates an areal geometry formed by the constituent linework of given geometry
ST_Collect3d Return a specified ST_Geometry value from a collection of other geometries.
1. g1field
2. g1, g2
3. g1_array

ST_ConcaveHull1 (geomA, target_percent, allow_holes=false) The concave hull of a geometry represents a possibly
concave geometry that encloses all geometries within the set. You can think of it as shrink wrapping.
ST_ConvexHullmm 3d (geomA) The convex hull of a geometry represents the minimum convex geometry that
encloses all geometries within the set.

ST_CurveToLinemm 3d Converts a CIRCULARSTRING/CURVEDPOLYGON to a LINESTRING/POLYGON


1. curveGeom
2. curveGeom, segments_per_qtr_circle

ST_Differencemm 3d (geomA, geomB) Returns a geometry that represents that part of geometry A that does not
intersect with geometry B.

ST_Dump2 3d (g1) Returns a set of geometry_dump (geom,path) rows, that make up a geometry g1.
ST_DumpPoints2 3d (geom) Returns a set of geometry_dump (geom,path) rows of all points that make up a geometry.
ST_DumpRings3d (a_polygon) Returns a set of geometry_dump rows, representing the exterior and interior rings of a
polygon.

ST_FlipCoordinates1 3d (geom) Returns a version of the given geometry with X and Y axis flipped. Useful for people
who have built latitude/longitude features and need to fix them.

ST_Intersectionmm G (T) Returns a geometry that represents the shared portion of geomA and geomB. The
geography implementation does a transform to geometry to do the intersection and then transform back to WGS84.

1. geomA, geomB
2. geogA, geogB

ST_LineToCurve3d (geomANoncircular) Converts a LINESTRING/POLYGON to a CIRCULARSTRING, CURVED


POLYGON

ST_MakeValid1 3d (input) Attempts to make an invalid geometry valid w/out loosing vertices.
ST_MemUnion3d (geomfield) Same as ST_Union, only memory-friendly (uses less memory and more processor time).
ST_MinimumBoundingCircle (geomA, num_segs_per_qt_circ=48) Returns the smallest circle polygon that can
fully contain a geometry. Default uses 48 segments per quarter circle.
ST_Polygonize Aggregate. Creates a GeometryCollection containing possible polygons formed from the constituent
linework of a set of geometries.

1. geomfield
2. geom_array

ST_Node1 g3.3 3d (geom) Node a set of linestrings.


ST_OffsetCurve1 g3.3 (line, signed_distance, style_parameters='') Return an offset line at a given distance and side
from an input line. Useful for computing parallel lines about a center line

ST_RemoveRepeatedPoints1 3d (geom) Returns a version of the given geometry with duplicated points
removed.

ST_SharedPaths1 g3.3 (lineal1, lineal2) Returns a collection containing paths shared by the two input
linestrings/multilinestrings.

ST_Shift_Longitude2 3d (geomA) Reads every point/vertex in every component of every feature in a geometry, and if
the longitude coordinate is <0, adds 360 to it. The result would be a 0-360 version of the data to be plotted in a 180 centric map
ST_Simplify (geomA, tolerance) Returns a "simplified" version of the given geometry using the Douglas-Peucker
algorithm.
ST_SimplifyPreserveTopology (geomA, tolerance) Returns a "simplified" version of the given geometry using the
Douglas-Peucker algorithm. Will avoid creating derived geometries (polygons in particular) that are invalid.

ST_Split1 (input, blade) Returns a collection of geometries resulting by splitting a geometry.


ST_SymDifferencemm 3d (geomA, geomB) Returns a geometry that represents the portions of A and B that do not
intersect. It is called a symmetric difference because ST_SymDifference(A,B) = ST_SymDifference(B,A).

ST_Unionmm Returns a geometry that represents the point set union of the Geometries.
1. g1field
2. g1, g2
3. g1_array

ST_UnaryUnion1 g3.3 3d (geom) Like ST_Union, but working at the geometry component level.

Linear Referencing
3d
ST_Line_Interpolate_Point (a_linestring, a_fraction) Returns a point interpolated along a line. Second argument
is a float8 between 0 and 1 representing fraction of total length of linestring the point has to be located.
ST_Line_Locate_Point (a_linestring, a_point) Returns a float between 0 and 1 representing the location of the
closest point on LineString to the given Point, as a fraction of total 2d line length.

ST_Line_Substring3d (a_linestring, startfraction, endfraction) Return a linestring being a substring of the input one
starting and ending at the given fractions of total 2d length. Second and third arguments are float8 values between 0 and 1.
ST_LocateAlong (ageom_with_measure, a_measure, offset) Return a derived geometry collection value with elements
that match the specified measure. Polygonal elements are not supported.
ST_LocateBetween (geomA, measure_start, measure_end, offset) Return a derived geometry collection value with
elements that match the specified range of measures inclusively. Polygonal elements are not supported.

ST_LocateBetweenElevations3d (geom_mline, elevation_start, elevation_end) Return a derived geometry


(collection) value with elements that intersect the specified range of elevations inclusively. Only 3D, 4D LINESTRINGS and
MULTILINESTRINGS are supported.

ST_InterpolatePoint1 3d (line, point) Return the value of the measure dimension of a geometry at the point closed to
the provided point.

ST_AddMeasure3d (geom_mline, measure_start, measure_end) Return a derived geometry with measure elements
linearly interpolated between the start and end points. If the geometry has no measure dimension, one is added. If the
geometry has a measure dimension, it is over-written with new values. Only LINESTRINGS and MULTILINESTRINGS are
supported.

Long Transactions Support


AddAuth (auth_token) Add an authorization token to be used in current transaction.
CheckAuth Creates trigger on a table to prevent/allow updates and deletes of rows based on authorization token.
1. a_schema_name, a_table_name, a_key_column_name
2. a_table_name, a_key_column_name

DisableLongTransactions () Disable long transaction support. This function removes the long transaction support
metadata tables, and drops all triggers attached to lock-checked tables.
EnableLongTransactions () Enable long transaction support. This function creates the required metadata tables,
needs to be called once before using the other functions in this section. Calling it twice is harmless.
LockRow Set lock/authorization for specific row in table

1. a_schema_name, a_table_name, a_row_key, an_auth_token, expire_dt


2. a_table_name, a_row_key, an_auth_token, expire_dt
3. a_table_name, a_row_key, an_auth_token

UnlockRows (auth_token) Remove all locks held by specified authorization id. Returns the number of locks released.

Miscellaneous Functions
2 3d
ST_Accum (geomfield) Aggregate. Constructs an array of geometries.
2
Box2D (geomA) Returns a BOX2D representing the maximum extents of the geometry.
Box3D2 3d (geomA) Returns a BOX3D representing the maximum extents of the geometry.
ST_Estimated_Extent Return the 'estimated' extent of the given spatial table. The estimated is taken from the
geometry column's statistics. The current schema will be used if not specified.

1. schema_name, table_name, geocolumn_name


2. table_name, geocolumn_name
ST_Expand2 Returns bounding box expanded in all directions from the bounding box of the input geometry. Uses
double-precision

1. g1, units_to_expand
2. g1, units_to_expand
3. g1, units_to_expand

ST_Extent2 (geomfield) an aggregate function that returns the bounding box that bounds rows of geometries.
ST_3DExtent2 3d (geomfield) an aggregate function that returns the box3D bounding box that bounds rows of
geometries.
Find_SRID (a_schema_name, a_table_name, a_geomfield_name) The syntax is find_srid(db_schema, table,column)
and the function returns the integer SRID of the specified column by searching through the GEOMETRY_COLUMNS table.

ST_Mem_Size3d (geomA) Returns the amount of space (in bytes) the geometry takes.
ST_Point_Inside_Circle (a_point, center_x, center_y, radius) Is the point geometry insert circle defined by center_x,
center_y, radius

Exceptional Functions
PostGIS_AddBBox (geomA) Add bounding box to the geometry.
PostGIS_DropBBox (geomA) Drop the bounding box cache from the geometry.
PostGIS_HasBBox (geomA) Returns TRUE if the bbox of this geometry is cached, FALSE
otherwise.
Tarefa PostGIS
Exercícios podem ser feitos com dados importados do IBGE para o banco PostgreSQL + PostGIS
Camadas importadas em aula: malha_viaria(Linear). principais_cidades(Pontual).
municipios(Poligonal). unidade_federativa(Poligonal).
Alguns dados foram digitalizados utilizando a ferramenta QGIS como o layer de ferrovias
ferrovias(Linear), mancha_urbana(Poligonal)
Sistema de coordenadas ou SRID utilizado 4326 WGS84

1) Quais as rodovias que tocam SP-461 ?


2) Criar tabela para cadastramento e georeferenciamento de ferrovias!
3) Quais são os trechos de rodovias ligadas pelas ferrovias cadastras?
4) Quais municípios fazem divisa com o município de ADAMANTINA ?
5) Adicionar coluna espacial em municípios!
6) Mudar o sistema de coordenadas de uma tabela!
7) Qual a quantidade de vias(malhas_viarias) totalmente contidas no municipio de
ADAMANTINA?
8) Qual o total de vias pavimentadas no município de ROSANA ?
9) Quais são as malhas_viarias em pavimentação do estado de são paulo ?
10) Vendo a projeção cujo SRID é srid = 29101 !
11) Qual a distância entre as cidades de Assis e Campinas ?
12) Qual o resultado das manchas urbanas em hectares?
13) Quais são as 5 cidades mais próximas a cidade de Campinas?
14) Quais são as cidades localizadas num raio de até 50 quilometros do Município de Campinas?
15) Criar um buffer de 200 metros a partir da rodovia SP-461!
16) Criar indice espacial para as tabelas importadas!
17) Identificar qual o cidade por meio da coordenada fornecida = POINT(-63.88186513101888
-8.74772579141916)
18) Quais os municípios cruzados pela SP-461 e qual extensão total dos trechos contidos em cada
um destes municípios?
19) Selecionar o ponto inicial, final e a extensão das ferrovias que formam a Ferrovia1 , nos limites
do município de RIOLÂNDIA?
Referências
http://www.bostongis.com/PrinterFriendly.aspx?content_name=postgis_tut01
http://www.bostongis.com/PrinterFriendly.aspx?content_name=postgis_tut02
http://postgis.net/docs/manual-2.0/

Você também pode gostar