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

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