4

I'm creating a set of features and adding them to a QgsSpatialIndex to find the ones closest to a certain location.

Why does nearestNeighbor() always return [0L] instead of the correct feature id?

import random 

index = QgsSpatialIndex()

for i in range(0,10):
    feat = QgsFeature()
    pt = QgsPoint(
        random.randint(0,10),
        random.randint(0,10))
    feat.setGeometry(QgsGeometry.fromPoint(pt))
    index.insertFeature(feat)

nearest = index.nearestNeighbor(QgsPoint(5,5),1)
print nearest 

1 Answer 1

3

Features only get an ID once they are added to a layer, but you can assign an ID manually using QgsFeature.setFeatureId(int) (in QGIS 2.18 and earlier) or QgsFeature.setId(int) (in newer versions) (Thanks to ndawson for the pointer!):

import random 

index = QgsSpatialIndex()

for i in range(0,10):
    feat = QgsFeature()
    pt = QgsPoint(
        random.randint(0,10),
        random.randint(0,10))
    feat.setGeometry(QgsGeometry.fromPoint(pt))
    feat.setFeatureId(int)
    index.insertFeature(feat)

nearest = index.nearestNeighbor(QgsPoint(5,5),1)
print nearest 

Alternatively, you can add the features to a memory layer:

import random 

index = QgsSpatialIndex()

vl = QgsVectorLayer("Point", "temporary_points", "memory")
pr = vl.dataProvider()

for i in range(0,10):
    feat = QgsFeature()
    pt = QgsPoint(
        random.randint(0,10),
        random.randint(0,10))
    feat.setGeometry(QgsGeometry.fromPoint(pt))
    pr.addFeatures([feat]) 

index = QgsSpatialIndex(vl.getFeatures())
nearest = index.nearestNeighbor(QgsPoint(5,5),1)
print nearest 
2
  • 2
    If your features aren't part of a layer you can manually assign feature IDs using QgsFeature.setId.
    – ndawson
    Commented Jan 8, 2017 at 20:35
  • Thanks @ndawson! In 2.18 it seems to be QgsFeature.setFeatureId(int)
    – underdark
    Commented Jan 9, 2017 at 9:15

Your Answer

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

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