Casi 10 años después, probablemente merezca la pena añadir una actualización a Respuesta de @vinayan :
Al almacenar las geometrías de las características dentro del QgsSpatialIndex()
utilizando QgsSpatialIndex.FlagStoreFeatureGeometries
flag, puede obtener las características más cercanas reales, no sólo las aproximadas por su caja delimitadora. De este modo se soluciona el problema comentario de Håvard Tveite . Además, hoy en día es mucho más eficiente cargar el índice de una sola vez; esto es mucho más rápido que añadir características una a una después de la creación del índice en un bucle. Además, se pueden obtener las geometrías más cercanas directamente del índice, lo que es mucho más rápido que obtener la característica completa mediante un bucle. QgsFeatureRequest()
. Si aún desea obtener toda la función, ahora también puede utilizar directamente .getFeature(id)
que es más corto. Aparte de eso, la sintaxis es ahora para PyQGIS 3. El código:
layer = iface.activeLayer()
# Bulkloading the index is much faster than adding features one by one
# Storing the geometry in the index allows finding the exact nearest neighbor, also for not single-point-features
index = QgsSpatialIndex(layer.getFeatures(), flags=QgsSpatialIndex.FlagStoreFeatureGeometries)
# QgsSpatialIndex.nearestNeighbor(QgsPointXY(), int neighbors)
pt = QgsPointXY(-0.00062201,0.00001746)
nearestIds = index.nearestNeighbor(pt,1) # we need only one neighbour
# Or, not stated in the docs, if you store the geometry in the index as done here, you can also: QgsSpatialIndex.nearestNeighbor(QgsGeometry(), int neighbors)
geom = QgsGeometry.fromPointXY(QgsPointXY(-0.00062201,0.00001746))
nearestIds = index.nearestNeighbor(geom,1)
# note that in reality, if both layers are the same, the nearest feature will always be itself
# in that case you should request 2 nearest neighbors and remove the one with the same id as your current source feature
print(nearestIds)
for nearestId in nearestIds:
# get the geometry of nearest feature efficiently directly from the index without a slow feature request
nearestGeom = index.geometry(nearestId)
print(nearestGeom)
# or get the whole feature via a short getFeature() request
nearestFeat = layer.getFeature(nearestId)
print(nearestFeat)