Book Image

QGIS Python Programming Cookbook, Second Edition - Second Edition

By : Joel Lawhead
Book Image

QGIS Python Programming Cookbook, Second Edition - Second Edition

By: Joel Lawhead

Overview of this book

QGIS is a desktop geographic information system that facilitates data viewing, editing, and analysis. Paired with the most efficient scripting language—Python, we can write effective scripts that extend the core functionality of QGIS. Based on version QGIS 2.18, this book will teach you how to write Python code that works with spatial data to automate geoprocessing tasks in QGIS. It will cover topics such as querying and editing vector data and using raster data. You will also learn to create, edit, and optimize a vector layer for faster queries, reproject a vector layer, reduce the number of vertices in a vector layer without losing critical data, and convert a raster to a vector. Following this, you will work through recipes that will help you compose static maps, create heavily customized maps, and add specialized labels and annotations. As well as this, we’ll also share a few tips and tricks based on different aspects of QGIS.
Table of Contents (16 chapters)
QGIS Python Programming Cookbook - Second Edition
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

Examining vector layer attributes


A true GIS layer contains both spatial geometry and non-spatial attributes. In this recipe, we'll access a vector point layer's attributes in PyQGIS. We'll use a file-based layer from a shapefile, but once a layer is loaded in QGIS, every vector layer works the same way.

Getting ready

Once again, we'll use the same New York City Museums layer from the Loading a vector layer from a file recipe in this chapter. You can download the layer from https://github.com/GeospatialPython/Learn/raw/master/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 the following steps, we'll load the layer, access the features iterator, grab the first feature, and then view the attributes as a Python list:

  1. First, load the shapefile as a vector layer:

            layer = QgsVectorLayer("/qgis_data/nyc/NYC_MUSEUMS_GEO.shp",
                                ...