QGIS Python Programming Cookbook(Second Edition)
上QQ阅读APP看书,第一时间看更新

Creating a spatial index

Until now, the recipes in this book used 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://github.com/GeospatialPython/Learn/raw/master/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 = QgsSpatialIndex() 
    
  6. Insert the remaining features:
            for f in fts: 
                index.insertFeature(f) 
    
  7. Next we add the layer to the canvas:
            QgsMapLayerRegistry.instance().addMapLayers([lyr]) 
    
  8. Now, select the IDs of three 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) 
    
  9. Finally we can select the ids of those features:
            lyr.setSelectedFeatures(hood) 
    
  10. In the following screenshot, the first feature is shown with a star while the nearest three features are selected in lighter yellow:

    How to do it...

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 four points, you must specify 5.