The PyQGIS Cookbook explains how to set up the spatial index but it only explains half of its usage:
create spatial index — the following code creates an empty index
index = QgsSpatialIndex()
add features to index — index takes QgsFeature object and adds it to the internal data structure. You can create the object manually or use one from previous call to provider’s nextFeature()
index.insertFeature(feat)
once spatial index is filled with some values, you can do some queries
# returns array of feature IDs of five nearest features
nearest = index.nearestNeighbor(QgsPoint(25.4, 12.7), 5)
What's the most efficient step to get the actual features belonging to the returned feature IDs?
Answer
# assume a list of feature ids returned from index and a QgsVectorLayer 'lyr'
fids = [1, 2, 4]
request = QgsFeatureRequest()
request.setFilterFids(fids)
features = lyr.getFeatures(request)
# can now iterate and do fun stuff:
for feature in features:
print feature.id(), feature
1
2
4
No comments:
Post a Comment