DEV Community

Dr. Azad Rasul
Dr. Azad Rasul

Posted on

13- A Guide to Linking Processing Tasks in PyQGIS

Looking to enhance your skills in PyQGIS? Look no further! This article provides a step-by-step guide on how to chain processes in PyQGIS using real-world data from the city of Erbil in Iraq. Follow along as we show you how to select primary roads, create buffers, find places along those roads, and print their names. By the end of this tutorial, you'll have a solid understanding of how to chain processes in PyQGIS and be able to apply this knowledge to your own projects.

To begin, download the data we'll be using in this tutorial. We'll start by loading shapefiles of roads and places from the city of Erbil in Iraq:

roa = "D:/erbil_data/erbil_data/roads.shp"
pla = "D:/erbil_data/erbil_data/places.shp"
Enter fullscreen mode Exit fullscreen mode

Next, we'll choose only the primary roads from the roads shapefile:

expression = "fclass = 'primary'"

primary_roads = processing.run("native:extractbyexpression",
    {"INPUT":roa, "EXPRESSION":expression,"OUTPUT":"memory:"}
    )["OUTPUT"]
Enter fullscreen mode Exit fullscreen mode

Then, we'll create a buffer around the primary roads:

buffered_primary_roads = processing.run("native:buffer",
    {'INPUT':primary_roads,'DISTANCE':0.01,'SEGMENTS':5,'END_CAP_STYLE':0,
    'JOIN_STYLE':0,'MITER_LIMIT':2,'DISSOLVE':False,'OUTPUT':'memory:'}
    )['OUTPUT']
Enter fullscreen mode Exit fullscreen mode

We can then add the layer of buffered primary roads:

QgsProject.instance().addMapLayer(buffered_primary_roads)
Enter fullscreen mode Exit fullscreen mode

Next, we'll find the places along the primary roads:

places_along_primary_roads = processing.run("native:extractbylocation",
    {"INPUT": pla, "PREDICATE": [0], "INTERSECT":buffered_primary_roads, "OUTPUT": "memory:"}
    )['OUTPUT']
Enter fullscreen mode Exit fullscreen mode

And we'll add the layer of places along the primary roads:

QgsProject.instance().addMapLayer(places_along_primary_roads)
Enter fullscreen mode Exit fullscreen mode

Finally, we'll print the name of each place along the primary roads:

for feature in places_along_primary_roads.getFeatures():
    print(feature["name"])
Enter fullscreen mode Exit fullscreen mode

In conclusion, this article provides a detailed tutorial on how to chain processes in PyQGIS using real-world data from the city of Erbil in Iraq. By following the step-by-step guide, readers can learn how to select primary roads, create buffers, find places along those roads, and print their names. This knowledge can then be applied to their own PyQGIS projects.

If you like the content, please SUBSCRIBE to my channel for the future content

Top comments (0)