QGIS + Python Part 1

――Since I have just started studying GIS (QGIS), there are many doubts about my understanding.

Execution operation check environment

Preparation

--Select "Python Console" from "Plugins" in the QGIS menu bar --Select the editor display from the Python console icon Image.png ――After that, do not use the interactive console, but write and execute the code with an editor.

Check Python version

test.py


import platform
print(platform.python_version())

--The execution result is displayed on the console → 2.7.5 ――It seems to be Python of 2.x series

Check Python execution path

test.py


import os
print(os.getcwd())

--Execution result → C: \ PROGRA ~ 1 \ QGIS2 ~ 1.18 \ bin - C:\Program Files\QGIS 2.18\bin

Add vector layer

test.py


filePath='C:/Users/xxxx/Documents/GIS DataBase/PyTest/lay01.shp'
iface.addVectorLayer(filePath,'test','ogr')

--First argument: File path --The file path can also be described using "slash" instead of "". --Be careful of escape sequences when using "" --Second argument: The name you want to give to the layer --In the case of the above code, the layer name on QGIS will be "test lay01 Polygon" --Second argument + SP + file name + SP + type - Image2.png --Third argument: Unknown for now ʻogr. providerKey --Don't make it ʻorg.

Get active layer

--Select the layer with the mouse etc. in advance.

test.py


layer=iface.activeLayer()
print('\n'.join(dir(layer)))

--You can get the member list (list of available methods etc.) of xxx object with dir (xxx)

Examine the geometry type of a layer

――It seems that points (points), lines (polylines, lines), and polygons (faces) cannot be mixed in the vector layer of QGIS ?. --Therefore, the type of vector layer can be (probably) point, line, or polygon. - Image3.png

--Points, lines, and polygons are collectively called geometry.

test.py


layer=iface.activeLayer()
type = layer.geometryType()
if type == QGis.Point :
    print('Point')
elif type == QGis.Line :
    print('Line')
elif type == QGis.Polygon:
    print('Polygon')

Output the attributes of the selected feature (selected polygon)

--Assuming that the feature has an attribute column called ʻid`. - Image4.png

--Suppose a feature is selected singularly or multiple times.

test.py


layer=iface.activeLayer()
features = layer.selectedFeatures()

for feature in features:
    print(feature['id'])

--Use layer.getFeatures () if you want to target all features on the active layer, with or without selection.

test.py


layer=iface.activeLayer()
features = layer.getFeatures()

for feature in features:
    print(feature['id'])

Output the vertex coordinates of a feature (polygon)

test.py


# -*- coding: utf-8 -*- 

layer=iface.activeLayer()

if layer is None :
    print(u'There is no active layer.')

if layer.geometryType() != QGis.Polygon:
    print(u'The geometry type of the active layer is not polygon.')

print(u'Active layer{0}Executes the process for.'.format(layer.name()))
print('')

for feature in layer.getFeatures():

    print(u'ID={0}'.format(feature['id']))
    if feature.geometry().isMultipart():
        polygons = feature.geometry().asMultiPolygon()
    else:
        polygons = [ feature.geometry().asPolygon() ]
                
    for polygon in polygons:
        for vertices in polygon:
            for vertex in vertices:
                print('X={0:.9f}  Y={1:.9f}'.format(vertex.x(),vertex.y()))
 
    print('')

--The above vertex is an instance of class'qgis._core.QgsPoint' --For details, see QgsPoint Class Reference

Get the layer's bounding box

--Get the bounding box for all features in the layer --The bounding box is the QgsRectangle class --For details, see QgsRectangle Class Reference

test.py


# -*- coding: utf-8 -*- 
layer=iface.activeLayer()

if layer is None :
    print(u'There is no active layer.')

box = layer.extent()
print('xMinimum={0:.9f}'.format(box.xMinimum()))
print('xMaximum={0:.9f}'.format(box.xMaximum()))
print('yMinimum={0:.9f}'.format(box.yMinimum()))
print('yMaximum={0:.9f}'.format(box.yMaximum()))
print('width={0:.9f}'.format(box.width()))
print('height={0:.9f}'.format(box.height()))

Reference material

-Introduction to QGIS Programming 2016 Osaka Edition

Recommended Posts

QGIS + Python Part 2
QGIS + Python Part 1
Python: Scraping Part 1
Python3 Beginning Part 1
Python: Scraping Part 2
Python basic memorandum part 2
Python basic memo --Part 2
Python basic memo --Part 1
Image processing with Python (Part 2)
Studying Python with freeCodeCamp part1
Python application: Pandas Part 1: Basic
Python application: Pandas Part 2: Series
Scraping with Selenium + Python Part 1
Python: Ship Survival Prediction Part 2
Python
Python: Supervised Learning: Hyperparameters Part 1
Python Basic Grammar Memo (Part 1)
Python: Ship Survival Prediction Part 1
Studying Python with freeCodeCamp part2
Image processing with Python (Part 1)
Solving Sudoku with Python (Part 2)
Image processing with Python (Part 3)
Python: Ship Survival Prediction Part 3
Python: Stock Price Forecast Part 2
UI Automation Part 2 in Python
Python: Supervised Learning: Hyperparameters Part 2
Scraping with Selenium + Python Part 2
Basics of Python × GIS (Part 1)
Python: Stock Price Forecast Part 1
Transpose CSV files in Python Part 1
perl objects and python class part 2.
Python Application: Data Cleansing Part 1: Python Notation
[Automation with python! ] Part 1: Setting file
Python Application: Data Handling Part 3: Data Format
Introduction to Python Hands On Part 1
Studying Python Part.1 Creating an environment
[Blender x Python] Particle Animation (Part 1)
Python application: Numpy Part 3: Double array
Basics of Python x GIS (Part 2)
perl objects and python class part 1.
Automate simple tasks with Python Part0
Python application: data visualization part 1: basic
[Automation with python! ] Part 2: File operation
Excel aggregation with Python pandas Part 1
kafka python
Basic Linear Algebra Learned in Python (Part 1)
Python basics ⑤
python + lottery 6
Python Summary
Built-in python
Python technique
Homebrew Python Part 3-Amazon Product Search Program
Studying python
Python 2.7 Countdown
Python memorandum
GUI creation in python using tkinter part 1
python tips
numpy part 1
AM modulation and demodulation in Python Part 2
Python Application: Data Visualization Part 3: Various Graphs
python function ①