Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Introdução ao PostGIS

30,652 views

Published on

Introdução ao Banco Espacial PostGIS

Published in: Technology
  • DOWNLOAD THE BOOK INTO AVAILABLE FORMAT (New Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://urlzs.com/UABbn } ......................................................................................................................... Download Full EPUB Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... Download Full doc Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... Download PDF EBOOK here { https://urlzs.com/UABbn } ......................................................................................................................... Download EPUB Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... Download doc Ebook here { https://urlzs.com/UABbn } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THE can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THE is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBOOK .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, CookBOOK, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, EBOOK, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THE Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THE the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THE Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (Unlimited) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/qURD } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/qURD } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/qURD } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/qURD } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/qURD } ......................................................................................................................... Download doc Ebook here { https://soo.gd/qURD } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

Introdução ao PostGIS

  1. 1. Introdução ao
  2. 2. AGENDA • Introdução • Geometrias Suportadas • Estrutura dos Dados • Manipulação • Indexação • Funções Espaciais • Exercícios
  3. 3. Introdução • Desenvolvido pela Research Refractions, em 2001; • Adiciona suporte espacial ao banco PostgreSQL; • Segue os padrões de interoperabilidade da OGC.
  4. 4. Introdução • Por padrão o PostgreSQL roda na porta 5432; • Uma instância pode contêr diversos bancos, com diversos schemas e tabelas.
  5. 5. Introdução
  6. 6. Introdução
  7. 7. Instalação • PostgreSQL • PostGIS
  8. 8. Instalação do PostgreSQL
  9. 9. Instalação do PostGIS
  10. 10. Instalação • Diretórios criados durante a instalação: – bin - Executáveis – include – Arquivos para compilação – lib - Bibliotecas – share - Extensões
  11. 11. Geometrias Suportadas • O PostGIS suporta os seguintes tipos de Geometrias especificados pela OGC: – Point; – Linestring; – Polygon; – Multipoint; – Multilinestring; – Multipolygon; – GeometryCollection.
  12. 12. Geometrias Suportadas
  13. 13. Estrutura dos Dados • A estrutura dos dados no PostGIS é definida pela padrão OGC SFS (Simple Feature Specification). GEOMETRY POINT GEOMETRYCOLLECTION LINESTRING MULTIPOINT POLYGON MULTILINESTRING MULTIPOLYGON
  14. 14. Estrutura dos Dados • Duas formas padrões para manipular Objetos Geográficos • Well-Known Text (WKT) e Well-Known Binary (WKB) • Guardam informações sobre tipo e coordenadas do Objeto Geográfico
  15. 15. Estrutura dos Dados • Exemplos: • POINT(0 0) • LINESTRING(0 0,1 1,1 2) • POLYGON((0 0,4 0,4 4,0 4,0 0),(1 1, 2 1, 2 2, 1 2,1 1)) • MULTIPOINT(0 0,1 2) • MULTILINESTRING((0 0,1 1,1 2),(2 3,3 2,5 4)) • MULTIPOLYGON(((0 0,4 0,4 4,0 4,0 0),(1 1,2 1,2 2,1 2,1 1)), ((-1 - 1,-1 -2,-2 -2,-2 -1,-1 -1))) • GEOMETRYCOLLECTION(POINT(2 3),LINESTRING((2 3,3 4)))
  16. 16. Estrutura dos Dados • SRID (Spatial Referencing System Identifier) – Todo Objeto Geográfico deve ter um SRID para ser inserido no banco • Por exemplo: – Considerando a interface GeomFromText • GeomFromText (text WKT, SRID); – Pode-se inserir o seguinte Objeto Geográfico • INSERT INTO SpatialTable (THE_GEOM, THE_NAME) VALUES (GeomFromText('POINT(-126.4 45.32)', 4326), ‘Um Lugar');
  17. 17. Estrutura dos Dados • Para assegurar a consistência dos dados, foram criadas as seguintes tabelas: – GEOMETRY_COLUMNS – SPATIAL_REF_SYS
  18. 18. Estrutura dos Dados • Na tabela Geometry_Columns consistem as informações das tabelas espaciais, da seguinte forma: – F_TABLE_CATALOG; – F_TABLE_SCHEMA; – F_TABLE_NAME; – F_GEOMETRY_COLUMN; – COORD_DIMENSION; – SRID; – TYPE;
  19. 19. Estrutura dos Dados • Na tabela Spatial_Ref_Sys é onde são carregadas as informações dos sistemas de coordenadas utilizados pelo banco: – SRID; – AUTH_NAME; – AUTH_SRID; – SRTEXT; – PROJ4TEXT;
  20. 20. Manipulação dos Dados • Conecte no banco: – Usuário: postgres – Senha: postgres • Crie uma nova base de dados: – Selecione “template_postgis” como template • Verifique se as tabelas espaciais foram criadas
  21. 21. 2.3 – Spatially Enable PostgreSQL
  22. 22. Manipulação dos Dados • Caso o pgsql não esteja instalado, é necessário instalá-lo: createlang plpgsql –d postgis –U postgres psql -f lwpostgis.sql –d postgis –U postgres psql -f spatial_ref_sys.sql –d postgis –U postgres
  23. 23. Manipulação dos Dados • Criando tabelas com dados espaciais: CREATE TABLE distritos ( cod SERIAL, sigla VARCHAR(10), denominacao VARCHAR(50), PRIMARY KEY (cod) ); SELECT AddGeometryColumn('public', 'distritos', 'spatial_data', 4326, 'POLYGON', 2);
  24. 24. Manipulação dos Dados • Inserindo dados espaciais: INSERT INTO distritos (sigla, denominacao, spatial_data) VALUES('CTR', 'Centro', GeometryFromText('Polygon((0 0, 10 0, 10 10, 0 10, 0 0), (5 5, 5 6, 6 6, 6 5, 5 5))', 4326));
  25. 25. Manipulação dos Dados • Recuperando dados espaciais: SELECT sigla, denominacao, spatial_data FROM distritos; SELECT sigla, denominacao, ASTEXT(spatial_data) FROM distritos;
  26. 26. Manipulação dos Dados • Importando shapefiles para o PostGIS – Shapefile – 3 arquivos: • .dbf: Atributos • .shp: Geometria • .shx: Índice – Um shapefile = Uma tabela no banco
  27. 27. Manipulação dos Dados • shp2pgsql [opts] – -D = Use formato Dump – -i = NÃo use bigint para númericos – -s <#> = Use o SRID especificado – -W = Use o charset especificado – -a = Use em modo append – -I = Criar indíce espacial
  28. 28. Manipulação dos Dados • shp2pgsql [opts] shapefile tablename – shp2pgsql –i –s 3005 bc_pubs.shp bc_pubs > bc_pubs.sql
  29. 29. Manipulação dos Dados • shp2pgsql –i -I -s 3005 bc_hospitals.shp bc_hospitals > bc_hospitals.sql • shp2pgsql -i -I -s 3005 bc_municipality.shp bc_municipality > bc_municipality.sql • shp2pgsql -i -I -s 3005 bc_voting_areas.shp bc_voting_areas > bc_voting.sql • shp2pgsql –i -I -s 3005 bc_pubs.shp bc_pubs > bc_pubs.sql • shp2pgsql –i -I -s 3005 bc_roads.shp bc_roads > bc_roads.sql
  30. 30. Manipulação dos Dados • psql –d postgis –U postgres –f bc_data.sql
  31. 31. Manipulação dos Dados • Visualizando os dados no uDig
  32. 32. Manipulação dos Dados • Visualizando os dados no uDig
  33. 33. Manipulação dos Dados • Visualizando os dados no uDig
  34. 34. Manipulação dos Dados • Exportando tabelas do PostGIS para Shapefile – pgsql2shp [<opções>] <nome do banco> <nome da tabela> – <nome do banco> nome do banco de origem – <nome da tabela> nome da tabela geográfica
  35. 35. Manipulação dos Dados • Exportando tabelas do PostGIS para Shapefile – [<opções>] opções de configuração • -d: define o arquivo dump para 3D (padrão = 2D) • -f <filename>: nome do shape file (padrão = nome da tabela). • -h <host>: host onde está o banco de dados (padrão =localhost). • -p <port>: porta de conexão (padrão = 5432). • -P <password>: especifica a senha. • -u <user>: especifica o usuário. • -g <geometry_column> especifica a colunaGeo a ser exportada.
  36. 36. Manipulação dos Dados • Exportando tabelas do PostGIS para Shapefile – Exemplos: • pgsql2shp -u postgres -P postgres postgis bc_hospitals • pgsql2shp -f Hospitals -u postgres -P postgres postgis bc_hospitals • pgsql2shp -f Hospitals -h localhost -p 5432 -u postgres -P postgres postgis bc_hospitals
  37. 37. Manipulação dos Dados • No PostGIS a função ST_IsValid() é utilizada para verificar se a geometria está de acordo com a especificação SFS Válido Inválido
  38. 38. Manipulação dos Dados • Como resolver o problema? Usando um truque… veja:
  39. 39. Indexação • É a ferramenta que possibilita que o banco de dados trabalhe com grandes volumes de informação de uma forma mais eficiente; • O PostgreSQL utiliza 3 tipos de índices: – B-Tree – R-Tree – GiST
  40. 40. Indexação • O GiST é utilizado para acelerar buscas em estruturas irregulares; • É uma boa prática, sempre após a criação de um indíce executar o seguinte comando:
  41. 41. Funções Espaciais • ST_Area: Retorna a área de um polígono
  42. 42. Funções Espaciais • ST_Contains: Retorna verdadeiro se A estiver contido em B (v) (f)
  43. 43. Funções Espaciais • ST_Touches: Retorna verdadeiro se A apenas tocar B. (v) (v)
  44. 44. Funções Espaciais • ST_Intersects: Retorna verdadeiro se houver algum tipo de intersecção
  45. 45. Funções Espaciais • ST_Intersection: Retorna uma geometria que representa o conjunto de pontos de intersecção das geometrias.
  46. 46. Funções Espaciais • ST_Transform: Retorna uma nova geometria com suas coordenadas transformadas para o sistema de referência espacial referenciado pelo parâmetro.
  47. 47. Funções Espaciais • ST_Within: Retorna verdadeiro se a geometria A estiver completamente dentro da geometria B.
  48. 48. Funções Espaciais • ST_DWithin: Retorna verdadeiro se as geometrias estão dentro da distância especificada.
  49. 49. Funções Espaciais • ST_Centroid: Retorna o ponto central da geometria;
  50. 50. Funções Espaciais • ST_Buffer: Cria um buffer, os cálculos são baseados no Sistema de Coordenadas.
  51. 51. Funções Espaciais • ST_Union: Retorna uma geometria com a união das geometrias;
  52. 52. Funções Espaciais • ST_Difference: Retorna geometria de A que não intersecta com B.
  53. 53. Operadores Espaciais • && : Retorna TRUE se houver sobreposição;
  54. 54. Operadores Espaciais • ~ : Retorna TRUE se as geometrias estiver completamente contida na outra;
  55. 55. Operadores Espaciais • ~= : Retorna TRUE se as geometrias foram idênticas;
  56. 56. Exercícios • 1) Qual é o comprimento total das estradas na província do BC em km? • 2) Qual o tamanho da cidade de Prince George, em hectares? • 3) Qual o maior município da Cidade? • 4) Qual o perímetro da cidade de ‘Vancouver’? • 5) Qual é a área total das áreas de votação?
  57. 57. Exercícios • 1) Qual é o comprimento total das estradas na província do BC em km? • SELECT Sum( ST_Length( the_geom ) ) / 1000 AS km_roads FROM bc_roads;
  58. 58. Exercícios • 2) Qual o tamanho da cidade de Prince George, em hectares? • SELECT ST_Area(the_geom)/10000 AS hectares FROM bc_municipality WHERE name = ‘PRINCE GEORGE’;
  59. 59. Exercícios • 3) Qual o maior município da Cidade? • SELECT name, ST_Area(the_geom)/10000 AS hectares FROM bc_municipality ORDER BY hectares DESC LIMIT 1;
  60. 60. Exercícios • 4) Qual o perímetro da cidade de ‘Vancouver’? • SELECT ST_Perimeter(the_geom) FROM bc_municipality WHERE name = 'VANCOUVER';
  61. 61. Exercícios • 5) Qual é a área total das áreas de votação? • SELECT Sum(ST_Area(the_geom))/10000 AS hectares FROM bc_voting_areas;
  62. 62. Exercícios • 1) Criar views para as tabelas importadas via shapefile, setando o SRID para 4326 • CREATE OR REPLACE VIEW vbc_hospitals as ( select gid, id, authority, name, st_transform(the_geom,4326) as the_geom from bc_hospitals );
  63. 63. Exercícios • 2) Inserir as informações em Geometry_columns • INSERT INTO geometry_columns ( f_table_catalog, f_table_schema, f_table_name, f_geometry_column, coord_dimension, srid, type) VALUES ('','public','vbc_hospitals','the_geom',2,4326,'POINT');
  64. 64. Junções Espaciais • Junções normais usam uma chave comum • SELECT a.var1, b.var2 FROM a, b WHERE a.id = b.id • Junções espaciais utilizam a chave universal de localização • SELECT a.var1, b.var2 FROM a, b WHERE ST_Intersects(a.geom, b.geom)
  65. 65. Junções Espaciais • Relacione os bares que estão a 250 metros de um hospital • SELECT bc_hospitals.name, bc_pubs.name FROM bc_hospitals, bc_pubs WHERE ST_DWithin( bc_hospitals.the_geom, bc_pubs.the_geom, 250 );
  66. 66. Junções Espaciais • Crie uma nova tabela com todas as área de votação de Prince George
  67. 67. Junções Espaciais • CREATE TABLE pg_voting_areas AS SELECT ST_Intersection(v.the_geom, m.the_geom) AS intersection_geom, ST_Area(v.the_geom) AS va_area, v.*, m.name FROM bc_voting_areas v, bc_municipality m WHERE ST_Intersects(v.the_geom, m.the_geom) AND m.name = ‘PRINCE GEORGE’;
  68. 68. Projeção de Coordenadas • Veja o SRID utilizando a função ST_SRID • SELECT ST_SRID(the_geom) FROM bc_roads LIMIT 1; • O que é “3005”? • SELECT srtext FROM spatial_ref_sys WHERE srid = 3005; • Ah, é “BC Albers”
  69. 69. Projeção de Coordenadas • PROJCS[“NAD83 / BC Albers", GEOGCS["NAD83", DATUM["North_American_Datum_1983", SPHEROID["GRS 1980",6378137,298.257222101]], PRIMEM["Greenwich",0], UNIT["degree",0.01745329251994328], AUTHORITY["EPSG","4269"]], PROJECTION["Albers_Conic_Equal_Area"], PARAMETER["latitude_of_center",45], PARAMETER["longitude_of_center",-126], PARAMETER["standard_parallel_1",50], PARAMETER["standard_parallel_2",58.5], PARAMETER["false_easting",1000000], PARAMETER["false_northing",0], UNIT["metre",1], AUTHORITY["EPSG","3005"]]
  70. 70. Projeção de Coordenadas • SELECT proj4text FROM spatial_ref_sys WHERE srid = 3005; • +proj=aea +ellps=GRS80 +datum=NAD83 +lat_0=45.0 +lon_0=-126.0 +lat_1=50.0 +lat_2=58.5 +x_0=1000000 +y_0=0 • PROJ4 é a biblioteca de reprojeção usada pelo PostGIS
  71. 71. Projeção de Coordenadas • 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;
  72. 72. Projeção de Coordenadas MULTILINESTRING(( 1004687.04355194 594291.053764096, 1004729.74799931 594258.821943696)) ST_Transform(the_geom) MULTILINESTRING(( -125.9341 50.3640700000001, -125.9335 50.36378))
  73. 73. Exercícios • 1) Qual o tamanho em km de ‘Douglas St’ em Victoria? • 2) Quais os dois bares com mais adeptos do Partido Verde (campo green) no prazo de 500 metros deles? • 3) Qual é a latitude do hospital mais a sul, usando o SRID 4326? • 4) Quantos eleitores NDP vivem a 50 metros de 'Simcoe St' em Vitória? • 5) Listar todas as ruas dentro de Victoria
  74. 74. Exercícios • 1) Qual o tamanho em km de ‘Douglas St’ em Victoria? • SELECT Sum(ST_Length(r.the_geom))/1000 AS kilometers FROM bc_roads r, bc_municipality m WHERE ST_Contains(m.the_geom, r.the_geom) AND r.name = 'Douglas St' AND m.name = 'VICTORIA';
  75. 75. Exercícios • 2) Quais os dois bares com mais adeptos do Partido Verde no prazo de 500 metros deles? • SELECT p.name, p.city, Sum(v.green) AS greens FROM bc_pubs p, bc_voting_areas v WHERE ST_DWithin(v.the_geom, p.the_geom, 500) GROUP BY p.name, p.city ORDER BY greens DESC LIMIT 2;
  76. 76. Exercícios • 3) Qual é a latitude do hospital mais a sul, usando o SRID 4326? • SELECT ST_Y(ST_Transform(the_geom,4326)) AS latitude FROM bc_hospitals ORDER BY latitude ASC LIMIT 1;
  77. 77. Exercícios • 4) Quantos eleitores NDP vivem a 50 metros de 'Simcoe St' em Vitória? • SELECT Sum(v.ndp) AS ndp FROM bc_voting_areas v, bc_municipality m, bc_roads r WHERE ST_DWithin(r.the_geom, v.the_geom, 50) AND ST_Contains(m.the_geom, r.the_geom) AND r.name = 'Simcoe St' AND m.name = 'VICTORIA';
  78. 78. Exercícios • 5) Listar todas as ruas dentro de Victoria • SELECT r.gid, r.the_geom FROM bc_roads r, bc_municipality m WHERE ST_Contains(m.the_geom, r.the_geom) AND m.name = ‘VICTORIA’
  79. 79. Obrigado! Fernando Quadro contato@fernandoquadro.com.br

×