In the PyQGIS documentation for QgsSpatialIndex.nearestNeighbor (https://qgis.org/pyqgis/master/core/QgsSpatialIndex.html#qgis.core.QgsSpatialIndex.nearestNeighbor)

we see the following (!) Warning:

If this QgsSpatialIndex object was not constructed with the FlagStoreFeatureGeometries flag, then the nearest neighbor test is performed based on the feature bounding boxes ONLY, so for non-point geometry features this method is not guaranteed to return the actual closest neighbors.

Neither in the cookbook (https://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/vector.html#using-spatial-index) nor somewhere else on the web I could find an example on the question

How to construct a QgsSpatialIndex with the FlagStoreFeatureGeometries flag in PyQGIS?

(related: Why does QgsSpatialIndex.nearestNeighbor(point, 1) sometimes return 2 lines?)

1 Answer 1


I had this same problem and after some research I came up with the following code:



rede_agua = QgsProject.instance().mapLayersByName('rede_agua')[0]
idx_rede_agua = QgsSpatialIndex(rede_agua.getFeatures(), flags=QgsSpatialIndex.FlagStoreFeatureGeometries)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.