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

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.

主站蜘蛛池模板: 桐梓县| 丹棱县| 普安县| 武义县| 泉州市| 勃利县| 吕梁市| 康平县| 定日县| 化德县| 宜川县| 东港市| 田阳县| 延长县| 淮滨县| 眉山市| 西盟| 黔西县| 满洲里市| 司法| 高雄县| 阿拉善盟| 大石桥市| 友谊县| 阜阳市| 湖北省| 海盐县| 珠海市| 井研县| 绥芬河市| 长阳| 阿鲁科尔沁旗| 宾川县| 时尚| 三穗县| 河津市| 吴旗县| 宝山区| 綦江县| 毕节市| 平湖市|