- QGIS Python Programming Cookbook
- Joel Lawhead
- 270字
- 2021-07-23 19:48:55
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:
- Load the layer:
lyr = QgsVectorLayer("/qgis_data/nyc/NYC_MUSEUMS_GEO.shp", "Museums", "ogr")
- Get the features:
fts = lyr.getFeatures()
- Get the first feature in the set:
first = fts.next()
- Now, create the spatial index:
index = QgsSpatialIndex()
- Begin loading the features:
index.insertFeature(first)
- Insert the remaining features:
for f in fts: index.insertFeature(f)
- 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)
- Extending Jenkins
- 程序員面試筆試寶典(第3版)
- 深入理解Bootstrap
- 摩登創(chuàng)客:與智能手機和平板電腦共舞
- Django:Web Development with Python
- Expert Android Programming
- Spring Boot+Vue全棧開發(fā)實戰(zhàn)
- ArcGIS for Desktop Cookbook
- ScratchJr趣味編程動手玩:讓孩子用編程講故事
- 從零開始學(xué)Android開發(fā)
- 零基礎(chǔ)學(xué)C語言(升級版)
- Mastering jQuery Mobile
- Clojure Polymorphism
- NGUI for Unity
- Keil Cx51 V7.0單片機高級語言編程與μVision2應(yīng)用實踐