spatialthoughts / courses

Code and HTML page repository for courses.spatialthoughts.com
56 stars 18 forks source link

Use spatial index to check fewer features in QGIS Actions Buffer example #103

Closed kannes closed 1 year ago

kannes commented 1 year ago

You can dramatically improve the performance of the https://courses.spatialthoughts.com/qgis-actions.html#select-features-in-a-buffer-zone example by using the option to pass a rectangle to QgsVectorLayer.getFeatures():

line_layer = QgsProject.instance().mapLayer('[% @layer_id %]')
polygon_layer_name = 'buildings'
distance = 20
fid = [% $id %]
line_feature = line_layer.getFeature(fid)
line_buffer = line_feature.geometry().buffer(distance, 5)
polygon_layer = QgsProject.instance().mapLayersByName(polygon_layer_name)[0]
nearby_features = [
    p.id()
    for p in polygon_layer.getFeatures(line_buffer.boundingBox()) 
    if p.geometry().intersects(line_buffer)
]
polygon_layer.selectByIds(nearby_features)

This allows the request to use a spatial index (if exist) to quickly limit the number of features to just the candidates that intersect the rectangle. So the if ... intersects only has to check those remaining buildings. Not much of a noticeable difference in the example data but with bigger datasets it will be a huge speed improvement.

Shout if you'd like it, then I'd make a pull request. Would you like to include both versions for the users to experience and learn?

kannes commented 1 year ago

Ah and this would also save deselection (even if no selection) and resulting map redrawing, takes a while if the project is complex:

if nearby_features:
    polygon_layer.selectByIds(nearby_features)
kannes commented 1 year ago

Performance test with roads and buildings from Noorth-Brabant shapefiles from https://download.geofabrik.de/europe/netherlands.html

:O

spatialthoughts commented 1 year ago

THank you for this. It's very helpful and spatial index makes a big difference for large datasets.

I just updated the code. https://github.com/spatialthoughts/courses/commit/48848ea885c1a9dcc7da35d19b05dc8739be86ac

Will push out the update to the data package and website soon.

kannes commented 1 year ago

Happy to help! Your tutorials continue to be an amazing inspiration.