1

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?)

Jochen Schwarze
  • 14,605
  • 7
  • 49
  • 117

1 Answers1

3

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

flags=QgsSpatialIndex.FlagStoreFeatureGeometries

Ex:

rede_agua = QgsProject.instance().mapLayersByName('rede_agua')[0]
idx_rede_agua = QgsSpatialIndex(rede_agua.getFeatures(), flags=QgsSpatialIndex.FlagStoreFeatureGeometries)
Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389