How to filter a layer by geometry in QGIS using Python

We’ll perform a spatial operation, using Python, to select all the points that intersect a polygon. Firstly, we need a point layer and a polygon layer:

set

Method 1

Use this method if your layers are not already loaded in QGIS. Otherwise, directly skip to Method 2.

from qgis.core import *

# Load the point layer
points = QgsVectorLayer("C:/.../points.shp","points", "ogr")
# Load the polygon layer
poly = QgsVectorLayer("C:/.../polygon.shp","polygon", "ogr")

QgsMapLayerRegistry.instance().addMapLayers([points,poly])
# Get features and geometry from polygon layer
feats_poly = poly.getFeatures()
for feat in feats_poly:
 geom_poly = feat.geometry()
# Get features from point layer
feats_point =points.getFeatures()

# Select the intersecting features
for feature in feats_point:
    if feature.geometry().intersects(geom_poly):
        points.select(feature.id())

Method 2

Use this method if your layers are already loaded in the Layers Panel in QGIS.

##point_layer=vector
##polygon_layer=vector

from qgis.core import *
import processing

# Load the layers
points = processing.getObject(point_layer)
poly = processing.getObject(polygon_layer)

# Get features and geometry from polygon layer
feats_poly = poly.getFeatures()
for feat in feats_poly:
geom_poly = feat.geometry()

# Get features from point layer
feats_point =points.getFeatures()

# Select the intersecting features
for feature in feats_point:
    if feature.geometry().intersects(geom_poly):
        points.select(feature.id())

Regardless of the method used, this will be the result:

selected

Advertisements

2 thoughts on “How to filter a layer by geometry in QGIS using Python

  1. Hi Marco,

    nice blog. Just a remark – the code only works with one polygon feature.
    The code should be:

    for a_point in points.getFeatures():
    for a_polygon in poly.getFeatures():
    if a_polygon.geometry().intersects(a_point.geometry()):
    points.select(a_point.id())

    Important to note: if your layers do not share the same coordinate system QGIS will not find any intersection.

    Like

    1. Hi Rob, thanks for pointing it. Actually, this is one of my older posts and I never found some time to update it and give it a wider explanation. As it is written by now, I admit it could not be satisfying for an average user and also a bit confusing for a beginner. I will try to edit it once I will have some time! Thanks again for the feedback, I will keep you updated!

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s