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

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.

主站蜘蛛池模板: 建德市| 砚山县| 马关县| 恭城| 涪陵区| 东平县| 闽侯县| 屯留县| 图木舒克市| 黔西| 茂名市| 大庆市| 武定县| 济南市| 神木县| 武宁县| 鄄城县| 麟游县| 泰州市| 镇康县| 江源县| 通城县| 岫岩| 龙口市| 阿克苏市| 沁阳市| 合山市| 留坝县| 堆龙德庆县| 虹口区| 鄱阳县| 静乐县| 利辛县| 海伦市| 金寨县| 库伦旗| 图片| 佳木斯市| 海林市| 塔城市| 易门县|