- 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)
- Julia機器學習核心編程:人人可用的高性能科學計算
- Java軟件開發基礎
- Kali Linux Wireless Penetration Testing Beginner's Guide(Third Edition)
- C語言程序設計學習指導與習題解答
- Symfony2 Essentials
- 編程數學
- 全棧自動化測試實戰:基于TestNG、HttpClient、Selenium和Appium
- Python Web數據分析可視化:基于Django框架的開發實戰
- 用戶體驗可視化指南
- C++ Application Development with Code:Blocks
- 一步一步跟我學Scratch3.0案例
- PowerDesigner 16 從入門到精通
- Visual Basic程序設計實驗指導及考試指南
- ANSYS FLUENT 16.0超級學習手冊
- Pandas 1.x Cookbook