官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 林州市| 西宁市| 静安区| 张掖市| 清水县| 敦化市| 南开区| 临江市| 德清县| 淮北市| 溧阳市| 开原市| 开远市| 塘沽区| 普宁市| 邵阳县| 南华县| 澄迈县| 北川| 达拉特旗| 化德县| 海门市| 镇宁| 玉门市| 吴堡县| 安顺市| 隆回县| 马鞍山市| 仪征市| 如皋市| 凌源市| 连南| 余庆县| 德昌县| 阿拉善盟| 家居| 驻马店市| 南和县| 潍坊市| 康马县| 漳州市|