Until now, the recipes in this book used the raw geometry for each layer of operations. In this recipe, we'll take a different approach and create a spatial index for a layer before we run operations on it. A spatial index optimizes a layer for spatial queries by creating additional, simpler geometries that can be used to narrow down the field of possibilities within the complex geometry.
If you don't already have the New York City Museums layer used in the previous recipes in this chapter, download the layer from https://geospatialpython.googlecode.com/svn/NYC_MUSEUMS_GEO.zip.
Unzip that file and place the shapefile's contents in a directory named nyc
within your qgis_data
directory, within your root or home directory.
In this recipe, we'll create a spatial index for a point layer and then we'll use it to perform a spatial query, as follows:
lyr = QgsVectorLayer("/qgis_data/nyc/NYC_MUSEUMS_GEO.shp", "Museums", "ogr")
fts = lyr.getFeatures()
first = fts.next()
index = QgsSpatialIndex()
index.insertFeature(first)
for f in fts: index.insertFeature(f)
4
because the starting point is included in the output:hood = index.nearestNeighbor(first.geometry().asPoint(), 4)