Creating a spatial index

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.

Getting ready

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.

How to do it...

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:

  1. Load the layer:
    lyr = QgsVectorLayer("/qgis_data/nyc/NYC_MUSEUMS_GEO.shp", "Museums", "ogr")
    
  2. Get the features:
    fts = lyr.getFeatures()
    
  3. Get the first feature in the set:
    first = fts.next()
    
  4. Now, create the spatial index:
    index = QgsSpatialIndex()
    
  5. Begin loading the features:
    index.insertFeature(first)
    
  6. Insert the remaining features:
    for f in fts:
      index.insertFeature(f)
    
  7. Now, select the IDs of 3 points nearest to the first point. We use the number 4 because the starting point is included in the output:
    hood = index.nearestNeighbor(first.geometry().asPoint(), 4)
    

How it works...

The index speeds up spatial operations. However, you must add each feature one by one. Also, note that the nearestNeighbor() method returns the ID of the starting point as part of the output. So, if you want 4 points, you must specify 5.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset