Está en la página 1de 49

Modelando con PostGis

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Historia

La primera versión fue publicada en 2001 por refracciones de


Investigación bajo la Licencia Pública General GNU. Una versión
estable 1.0 fue lanzado el 19 de abril de 2005. En 2006, se
registró PostGIS ajustándose a las normas establecidas por el
Consorcio Geoespacial Abierto OGC, por el uso de SQL. Sigue
las recomendaciones del OpenGIS.
PostGIS almacena la información geográfica en una columna del
tipo GEOMETRY, que es diferente del homónimo "GEOMETRY"
utilizado por PostgreSQL, donde se pueden almacenar la
geometría en formato WKB (Well-Known Binary), aunque hasta la
versión 1.0 se utilizaba la forma WKT (Well-Known Text).

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Introducción

➲ PostGIS es una extensión espacial para


PostgreSQL

➲ Base de datos espacial compatible con


“OpenGIS Simple Features for SQL”

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Por qué PostGIS?

➲ La mejor base de datos espaciales open


source
➲ Bd comerciales costosas
➲ Permite organizar visualizar y analizar la
información.

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Qué es una BD espacial?

Base de datos con características especiales:


➲ Almacenar objetos espaciales
➲ Manipular objetos espaciales como si
fueran objetos de la BD

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Qué es la data espacial ?
(Spatial data)
➲ Data que describes la localización y/o
forma del objeto.

Por ejemplo :
Caminos, ríos, líneas electricas, bosques,
parques, casas, etc.

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Qué es la data espacial ?
(Spatial data)

➲ Abastracción de información.
➲ Representa entidades mediante puntos,
lineas y polígonos.

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Pero porque postgis?

• PostGIS es software libre, tiene licencia GNU


General Public License (GPL).
• Es compatible con los estándares de OGC.
• Soporta tipos de datos espaciales, índices
espaciales y tiene cientos de funciones
espaciales (+ 890 en la versión 2.0).
• Permite importar y exportar datos a través de
varias herramientas conversoras (shp2pgsql,
pgsql2shp, ogr2ogr, dxf2postgis).
• Existe un gran número de clientes SIG de
escritorio para visualizar datos PostGIS
• ….
RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
“Bases de datos” Geográficas
planetarias
Capa base
Objetos vectoriales (WGS84) o fotografías.
Convertidos en tiles (imágenes png).
Capa overlay
Objetos vectoriales (EPSG:3857).
Las más conocidas
Google Maps
Microsoft Bing
ESRI ArcGIS
OpenStreetMap

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Desventajas de las BD espaciales

• El costo de implementación es alto ?


• Incompatibles con algunos paquetes GIS.
• Más lentas que estruturas de datos especializadas.
• Poca gente capacitada e inexperiencia.

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Porque se usó PostgreSQL como base de
datos espacial ?

– Confiabilidad
– Costo 0 (open source)
– Soporta el estandar SQL.
– Permite agregar nuevos tipos de datos
– Este facila agregar nuevas funciones

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Software Cliente
Como me puedo comunicar con PostGIS?
• Usando estandar SQL
• FME (Safe Software): GIS translation/processing
• Mapserver (http://mapserver.gis.umn.edu), an OpenGIS Web
Map Server, GeoServer
• OGR (http://gdal.velocet.ca/projects/opengis/) - open source
GIS reader/writer
• ESRI shapefile reader/writer
• QGIS connection, AutoCAD, Java Viewer, Web Feature Server,
gvSIG, Udig, Kosmos, etc..

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
• Define primitivas geográficas.
• Indicar el SRID de un sistema de
referencia.
• Tipo de primitivas:
• Geográficas: grados WGS84, cálculos
curvos sobre un esferoide.

• Geométricas: metros EPSG:3857, cálculos


rectos sobre un rectángulo.

Formato WKT (Well Known Text) Formato WKB (Well Known


Binary)
"POINT(-34.10 45.245)“
"POINT(-34.10 45.245 458)“ El WKT "SRID=4;POINT(0 0)"
"LINESTRING(0 0, 25.7 34.0, -43.2 se convierte en el WKB
22.1)“ "010100002004000000000000000000
"MULTILINESTRING((0 0,1 1,1 2),(2 00000000000000000000"
3,3 2,5 4))“

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
PostGIS – SQL geográfico
Crear tablas con columnas de tipos Insertar datos a partir de un string WKT:
geográficos
CREATE TABLE roads ( INSERT INTO global_points (name, location)
id INTEGER, VALUES (‘Town’,
road_name VARCHAR(25), ST_GeographyFromText('SRID=4326;POINT
geom GEOMETRY(LINESTRING, 4326) (-110 30)’)
); );

Cargar datos en lote desde un fichero Crear índices sobre columnas


"shapefile" (un formato abierto de fichero geográficas
que guarda primitivasen WKT o WKB),
con opción de convertir la proyección: CREATE INDEX idx_roads_geom_gist
ON roads USING gist(geom);
# shp2pgsql -s 4326:3857 shaperoads.shp
myschema.roadstable | psql -d roadsdb

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Ejercicio 1

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Relaciones espaciales
➲ No solo sirven para almacenar las ubicaciones de
los objetos
➲ Permiten calcular relaciones entre objetos, que son
muy dificiles de modelar sin usar objetos espaciales.
➲ Las relaciones típicas entre objetos son :
• Proximidad : distancia
• Adjacencia : “touching” y “cenectividad”
• Contención : inside/overlapping

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Reaciones espaciales

➲ Podemos responder preguntas como las


siguientes :

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Spatial Relationships

Cual es la distancia entre un terreno que


se desea comprar y una fábrica ?

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Spatial Relationships

Cual es la distancia entre varias oficinas ?

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Spatial Relationships

Con que propiedades se comparte bordes un


lote ?

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Conectividad. Como se relacionan los ríos ?

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Spatial Relationships

Contención: Rios contenidos en regiones

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Spatial Relationships

Adjacencia y contención

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Polígonos originales

Intersección
Union

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Alrededores

Cadena original de ríos

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Advantages of Spatial Databases

Distancias a Tiendas – Donde consigo la cerveza más barata ?


… WHERE distance(<me>,pub_loc) < 1000
SELECT distance(<me>,pub_loc)*$0.01 + beer_cost …
... WHERE touches(pub_loc, street)
… WHERE inside(pub_loc,city_area) and city_name = ...

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Advantages of Spatial Databases

Cual es el valor de un lote ?

Area(<my lot>) * <price per acre>


+ area(intersect(<my log>,<forested area>) ) * <wood value per acre>
- distance(<my lot>, <power lines>) * <cost of power line laying>

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
PostGIS – cálculos geográficos
Calcular la longitud total de una Obtener los puntos de una tabla
carretera cercanos a unas coordenadas

SELECT ST_Length(geom)/1000 AS SELECT the_geom


km_road FROM geom_table
FROM roads WHERE ST_Distance(the_geom,
WHERE road_name = 'M45'; ST_GeomFromText('POINT(100000
200000)', 312)) < 100

Obtener las carreteras dentro del área de un municipio

SELECT ST_Intersection(r.the_geom, m.the_geom) AS intersection_geom,


ST_Length(r.the_geom) AS rd_orig_length, r.*
FROM bc_roads AS r, bc_municipality AS m
WHERE m.name = 'PRINCE GEORGE' AND ST_Intersects(r.the_geom,
m.the_geom);

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Muchas organizaciones utilizan(o pueden usar)
Data espacial
➲ Direcciones Información del clima
➲ Ubicación de clientes Lotes
➲ Ubicación de tiendas Recursos naturales
➲ Tracking y transporte(UPS, Planeamiento de ciudades
DHL, FEDEX, Serpost) Planeamientos ambiental
➲ Estadísticas Visualización de datos
➲ Demografía Detección de amenzas
➲ Cartografía
➲ Epidemólogía
➲ Patrones de crímenes

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Porque colocar data espacial en una Base
de datos relacional(RDBMS)?
➲ Usualemnte se realaciona o tro tipo de información.
Esto permite preparar datos y relaciones más
complejos
➲ Medidores de luz: cuantos se usan, cuantos existen en un área,
última fecha de mantenimiento, a cual cliente se asocia esta cuenta,
etc.
➲ Ríos: flujo, temperaturas, presencia de peces, concentración de
químicos, etc.
➲ Bosques: Áreas, tipos de árboles, vegetación, valor monetario,
dueños de hectáreas, etc.

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Ventajas de las Bases de Datos Espaciales
La data espaciales es tratada como cualquier otro datos de una BD
– Backups
– Integrity checks
– Menor redundancia
– Operaciones básicas son manejadas por la BD
– Soporte Multiusuario.
– Seguridad / Control e Acceso
– Bloqueo

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Ventajas de las Bases de Datos Espaciales
Las tareas complejas son derivadas al motor de Base de
Datos.
– La organicación e indexación son hechas por la BD
– No se tienen que reimplementar operadores
– Tampoco funciones

Disminuye significativamente el tiempo de desarrollo de una


aplicación a medida.

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Ventajas de las Bases de Datos Espaciales
Consultas espaciales usando SQL
– Se usan experesiones SQL simples para determinar relaciones
espaciales.
• distance
• adjacency
• containment
– Se usan expresiones SQL simples para realizar operaciones
espaciales.
• area
• length
• intersection
• union
• buffer

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Ejercicio 2

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Bueno, y el uso cual es?

• Datos espaciales
• Web Mapping
• Sistemas de rutas
• CityGML
• Apps Moviles
• Crisis Mapping with crowdsourcing
• Sistemas de alertas
• ……

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Web Mapping Libraries

Librerías para webMapping


client que soportan postgis:
•Openlayers
•Leafletjs
•GeoExplorer
•Geo-Python Django
•Etc..

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Instant Mapping Applications with
PostGIS and Nodejs

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Smartcity – Postgis CityGML

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Smartcity – Postgis- CityGML

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Smartcity
Postgis CityGML

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Sistema de Rutas

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Apps móviles

Geo localización + levantamiento de información =


Conocimiento, Análisis, Toma Decisiones

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Apps móviles

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Mapping Crisis

The Ushahidi Hait Map in the first 24 hours after the


earthquake. Credit: Ushahidi Haiti Project (UHP).

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Sistemas de Alertas Tempranas

Towards Open Monitoring Data within marine monitoring


projects

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Conclusiones

• PostGIS le proporciona a PostgreSQL características espaciales mediante


objetos, funciones e índices.
• PostGIS es software libre (GPL)
• PostGIS soporta los estándares de OpenGIS Simple Features for SQL
• PostGIS es un componente importante de los Sistemas de Información
Geográficos libres y abiertos.
• PostGIS es un importante componente de futuro proyectos espaciales open
source.

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Demostración

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
Preguntas ?

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/
FIN

RAUL ACEVEDO
GEO - CONSULTOR
rfacevedo@yahoo.com
http://geoportales.blogspot.com/

También podría gustarte