Conociendo PyQGIS
Vanessa Penagos


Somos una comunidad y semillero de investigación que busca generar el interés de las mujeres y niñas en la tecnología, generando espacios que promuevan su participación en este campo mediante el aprendizaje colectivo, compartiendo conocimientos y recursos técnicos con otras comunidades.



GIS
Sistemas de información geográfica


- Ver datos
-
Explorar datos y diseñar mapas
-
Explorar datos y componer mapas
-
Analizar datos
-
Servicios Web
-
Funcionalidades GIS extendidas gracias a
complementos
-
Complementos externos Python


Ejecutar python en QGis
Directorio .qgis2/python
Archivo startup.py
- Archivo de inicio
- Consola de Python


Cargar un proyecto
from qgis.core import QgsProject
project = QgsProject.instance()
print(project.fileName())
project.read('/home/user/projects/my_other_qgis_project.qgs')
print(project.fileName())
>>'/home/user/projects/my_other_qgis_project.qgs'
project.write()
project.write('/home/user/projects/my_new_qgis_project.qgs')
Modificar el proyecto

Capas
import os
from qgis.core import (
QgsVectorLayer
)

- Capas vectoriales
- Capas Raster

Capas vectoriales
-
OGR
- PostGIS
- CSV
- GPX
- SpatiaLite database
- Las geometrias basadas en WKB de MySQL
- Conexión WFS

import os
from qgis.core import (QgsVectorLayer)
path_to_ports_layer = '/home/Escritorio/COL_adm/COL_adm1.shp'
colombia00 = QgsVectorLayer(path_to_ports_layer, "Col01", "ogr")
if not colombia00.isValid():
print("Error al cargar capa!")
QgsMapLayerRegistry.instance().addMapLayer(colombia00)


rlayer = QgsRasterLayer(path_to_tif, "SRTM layer name")
if not rlayer.isValid():
print("Layer failed to load!")
Capas Raster


from PyQt4.QtCore import *
path_layer = '/home/Escritorio/NE1_50M_SR_W/NE1_50M_SR_W.tif'
layer = QgsRasterLayer(path_layer, 'layer01')
QgsMapLayerRegistry.instance().addMapLayer(layer)
if not layer.isValid():
print("Layer failed to load!")


Operaciones sobre capas vectoriales
layers = QgsMapLayerRegistry.instance().mapLayers()
for name, layer in layers.iteritems():
if layer.geometryType() == QGis.Point:
print("Point")
if layer.geometryType() == QGis.Line:
print("Line")
if layer.geometryType() == QGis.Polygon:
print("Polygon")
Iterar sobre una capa vectorial

QgsMapLayerRegistry.instance().addMapLayer(layer)
QgsMapLayerRegistry.instance().removeMapLayer(layer_id)
QgsMapLayerRegistry.instance().mapLayers()

Selección de objetos espaciales
iface.mapCanvas().setSelectionColor(QColor("red"))
layer = iface.activeLayer()
layer.selectByExpression(u'"ID_1" > 10', QgsVectorLayer.SetSelection)
selected_fid = []
for feature in layer.getFeatures():
selected_fid.append(feature.id())
break
layer.select(selected_fid)
layer.removeSelection()
Agregar entidades
Limpiar la selección

selection = layer.selectedFeatures()
print(len(selection))
for feature in selection:
...

-
Agregar nuevas entidades
-
Eliminar entidades
-
Modificar entidades existentes
-
Cambiar valores de atributos
caps = layer.dataProvider().capabilities()
caps_string = layer.dataProvider().capabilitiesString()
QgsVectorDataProvider.AddFeatures
QgsVectorDataProvider.DeleteFeatures
QgsVectorDataProvider.ChangeAttributeValues
QgsVectorDataProvider.ChangeGeometries
- Añadir atributos
-
Cambiar nombre de atriburos
-
Crear indices espaciales y de atributo
-
Acceso rapido mediante ID
-
Cambiar geometrias

if caps & QgsVectorDataProvider.AddFeatures:
feat = QgsFeature(layer.pendingFields())
feat.setAttributes([0, 'hello'])
feat.setAttribute('name', 'hello')
feat.setAttribute(0, 'hello')
feat.setGeometry(QgsGeometry.fromPoint(QgsPoint(123, 456)))
(res, outFeats) = layer.dataProvider().addFeatures([feat])
if caps & QgsVectorDataProvider.DeleteFeatures:
res = layer.dataProvider().deleteFeatures([5, 10])
Añadir y eliminar
objetos espaciales

from PyQt4.QtCore import QVariant
if caps & QgsVectorDataProvider.AddAttributes:
res = layer.dataProvider().addAttributes(
[QgsField("mytext", QVariant.String),
QgsField("myint", QVariant.Int)])
if caps & QgsVectorDataProvider.DeleteAttributes:
res = layer.dataProvider().deleteAttributes([0])
layer.updateFields()
Añadir y eliminar
atributos

layer=iface.activeLayer()
if layer.isEditable():
inlayer.startEditing()
# ...
inlayer.commitChanges()
inlayer.rollBack()
#----------------------------------
beginEditCommand()
endEditCommand())
destroyEditCommand()
Modo edición


index = QgsSpatialIndex()
index.insertFeature(feat)
index = QgsSpatialIndex(layer.getFeatures())
Indices espaciales


Geometría
gPnt = QgsGeometry.fromPointXY(QgsPointXY(1,1))
gLine = QgsGeometry.fromPolyline([QgsPoint(1, 1), QgsPoint(2, 2)])
gPolygon = QgsGeometry.fromPolygonXY([[QgsPointXY(1, 1),
QgsPointXY(2, 2), QgsPointXY(2, 1)]])


for f in features:
geom = f.geometry()
print('Area: ', geom.area())
print('Perimetro: ', geom.length())
..
d = QgsDistanceArea()
d.setEllipsoid('WGS84')
d.setEllipsoidalMode(True)
print "Distancia en metros: ", d.measureLine(QgsPoint(x1,y1),QgsPoint(x2,y2))

- Transformación geométrica: Reproject algorithm
- Distancia y Area usando QgsDistanceArea: Distance matrix algorithm
- Multi-part to single-part algorithm

Lienzo de Mapa
canvas = QgsMapCanvas()
canvas.show()
# Añadir capas al lienzo
canvas.setExtent(layer.extent())
canvas.setLayerSet([QgsMapCanvasLayer(layer)])
canvas.scene().removeItem(element)

-
setMapTool()
-
QgsMapToolPan
-
QgsMapToolZoom
-
QgsRubberBand
-
QgsVertexMarke

Subestaciones eleléctricas


Un ejemplo

Otras cosas...
- Manejo de expresiones
- Manejo de errores
- Sistemas de cordenadas de referencia
- Renderizar mapa
- Configuración de lectura y almacenamiento
- Comunicación con usuario


Fuentes de datos
- 1. Natural Earth
- 2. OpenStreetMap
- 3. Geofabrik
- 4. DIVA-GIS
- 5. GADM
- 6. EuroGlobalMap
- 7. Global Map
- 8. OpenAerialMap
- 9. UNEP GEOData
- 10. Global Climate Monitor
- 11. Centro de Descargas del IGN
- 12. Servicio de Cartografía Digital e Infraestructura de Datos Espaciales de la Universidad de Extremadura
- 13. Infraestructura de Datos Espaciales de las Naciones Unidas (UNSDI_NCO GeoNetwork Portal)



¡Gracias!


- https://docs.qgis.org
- https://mappinggis.com/2012/05/datos-cartograficos/
webgrafia

PyQGIS
By Vanessa Penagos
PyQGIS
- 734