- 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)
- Practical Data Science Cookbook(Second Edition)
- Internet of Things with Intel Galileo
- Effective Python Penetration Testing
- Mastering Python Networking
- Symfony2 Essentials
- The Complete Coding Interview Guide in Java
- Swift Playgrounds少兒趣編程
- Express Web Application Development
- Node.js開發(fā)指南
- Visual Basic 6.0程序設(shè)計實驗教程
- PHP 7從零基礎(chǔ)到項目實戰(zhàn)
- 深入實踐Kotlin元編程
- 寫給大家看的Midjourney設(shè)計書
- Mastering OAuth 2.0
- Functional Python Programming