Book Image

QGIS Python Programming Cookbook

Book Image

QGIS Python Programming Cookbook

Overview of this book

Table of Contents (16 chapters)
QGIS Python Programming Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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...