QGIS Python Programming Cookbook, Second Edition - Joel Lawhead - E-Book

QGIS Python Programming Cookbook, Second Edition E-Book

Joel Lawhead

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

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.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 407

Veröffentlichungsjahr: 2017

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

QGIS Python Programming Cookbook - Second Edition
Credits
About the Author
About the Reviewer
www.PacktPub.com
Why subscribe?
Customer Feedback
Preface
What this book covers
What you need for this book
Who this book is for
Sections
Getting ready
How to do it…
How it works…
There's more…
See also
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book 
Errata
Piracy
Questions
1. Automating QGIS
Introduction
Installing QGIS 2.18 for development
Getting ready
How to do it...
Installing PyQGIS using the Debian package manager
Installing PyQGIS using the RPM package manager
Setting the environment variables
Setting the environment variables on Windows
Setting environment variables on Linux
How it works...
There's more...
Finding the PyQGIS path on Windows
Finding the location of the QGIS Python installation on other platforms
Using the QGIS Python console for interactive control
How to do it...
How it works...
Automatically starting the Python console
Getting ready
How to do it...
How it works...
Using the Python's Script Runner plugin
Getting ready
How to do it...
How it works...
There's more...
Setting up your QGIS IDE
Getting ready
How to do it...
Adding the Python interpreter to Windows
Adding the PyQGIS module paths to the interpreter
Adding the PyQGIS API to the IDE
Adding environment variables
How it works...
Debugging QGIS Python scripts
How to do it...
Configuring QGIS
Configuring Eclipse
Testing the debugger
How it works...
Navigating the PyQGIS API
Getting ready
How to do it...
How it works...
There's more...
Creating a traditional QGIS plugin
Getting ready
How to do it...
How it works...
There's more...
Creating a Processing Toolbox plugin
Getting ready
How to do it...
How it works...
There's more...
Distributing a plugin
Getting ready
How to do it...
How it works...
Building a standalone application
Getting ready
How to do it...
How it works...
There's more...
Storing and reading global preferences
Getting ready
How to do it...
How it works...
There's more...
Storing and reading project preferences
Getting ready
How to do it...
How it works...
There's more...
Accessing the script path from within your script
Getting ready
How to do it...
How it works...
There's more...
2. Querying Vector Data
Introduction
Loading a vector layer from a file sample
Getting ready
How to do it...
How it works...
Loading a vector layer from a geodatabase
Getting ready
How to do it...
How it works...
Examining vector layer features
Getting ready
How to do it...
How it works...
Examining vector layer attributes
Getting ready
How to do it...
How it works...
There's more...
Filtering a layer by geometry
Getting ready
How to do it...
How it works...
Filtering a layer by attributes
Getting ready
How to do it...
How it works...
Buffering a feature
Getting ready
How to do it...
How it works...
Measuring the distance between two points
Getting ready
How to do it...
How it works...
Measuring distance along a line
Getting ready
How to do it...
How it works...
Calculating the area of a polygon
Getting ready
How to do it...
How it works...
Creating a spatial index
Getting ready
How to do it...
How it works...
Calculating the bearing of a line
Getting ready
How to do it...
How it works...
Loading data from a spreadsheet
Getting ready
How to do it...
How it works...
There's more...
Accessing layer metadata
Getting ready
How to do it...
How it works...
3. Editing Vector Data
Introduction
Creating a vector layer in memory
Getting ready
How to do it...
How it works...
Adding a point feature to a vector layer
Getting ready
How to do it...
How it works...
There's more...
Adding a line feature to a vector layer
Getting ready
How to do it...
How it works...
Adding a polygon feature to a vector layer
Getting ready
How to do it...
How it works...
Adding a set of attributes to a vector layer
Getting ready...
How to do it...
How it works...
Adding a field to a vector layer
Getting ready
How to do it...
How it works...
Joining a shapefile attribute table to a CSV file
Getting ready
How to do it...
How it works...
There's more...
Changing vector layer geometry
Getting ready
How to do it...
How it works...
Changing a vector layer feature's attribute
Getting ready
How to do it...
How it works...
Removing data from a vector layer
Getting ready
How to do it....
How it works...
Deleting a vector layer feature's attribute
Getting ready
How to do it...
How it works...
Reprojecting a vector layer
Getting ready
How to do it...
How it works...
Converting a shapefile to KML or GeoJSON
Getting ready
How to do it...
How it works...
There's more...
Merging shapefiles
Getting ready
How to do it...
How it works...
There's more...
Splitting a shapefile
Getting ready
How to do it...
How it works...
Generalizing a vector layer
Getting ready
How to do it...
How it works...
Dissolving vector features
Getting ready
How to do it...
How it works...
Performing a union on vector shapes
Getting ready
How to do it...
How it works...
Rasterizing a vector layer
Getting ready
How to do it...
How it works...
Exporting a layer to the GeoPackage format
Getting ready
How to do it...
How it works...
4. Using Raster Data
Introduction
Loading a raster layer
Getting ready
How to do it...
How it works...
Loading a NetCDF file
Getting ready
How to do it...
How it works...
Getting the cell size of a raster layer
Getting ready
How to do it...
How it works...
Obtaining the width and height of a raster
Getting ready
How to do it...
How it works...
Counting raster bands
Getting ready
How to do it...
How it works...
Swapping raster bands
Getting ready
How to do it...
How it works...
There's more...
Querying the value of a raster at a specified point
Getting ready
How to do it...
How it works...
Reprojecting a raster
Getting ready
How to do it...
How it works...
There's more...
Creating an elevation hillshade
Getting ready
How to do it...
How it works...
There's more...
Creating vector contours from elevation data
Getting ready
How to do it...
How it works...
Sampling a raster dataset using a regular grid
Getting ready
How to do it...
How it works...
There's more...
Adding elevation data to a line vertices using a digital elevation model
Getting ready
How to do it...
How it works...
There's more...
Creating a common extent for rasters
Getting ready
How to do it...
How it works...
Resampling raster resolution
Getting ready
How to do it...
How it works...
Counting the unique values in a raster
Getting ready
How to do it...
How it works...
Mosaicing rasters
Getting ready
How to do it...
How it works...
Converting a TIFF image to a JPEG image
Getting ready
How to do it...
How it works...
Creating pyramids for a raster
Getting ready
How to do it...
How it works...
Converting a pixel location to a map coordinate
Getting ready
How to do it...
How it works...
Converting a map coordinate to a pixel location
Getting ready
How to do it...
How it works...
Creating a KML image overlay for a raster
Getting ready
How to do it...
How it works...
There's more...
Classifying a raster
Getting ready
How to do it...
How it works...
Converting a raster to a vector
Getting ready
How to do it...
How it works...
Georeferencing a raster from control points
Getting ready
How to do it...
How it works...
Clipping a raster using a shapefile
Getting ready
How to do it...
How it works...
5. Creating Dynamic Maps
Introduction
Accessing the map canvas
Getting ready
How to do it...
How it works...
Changing the map units
Getting ready
How to do it...
How it works...
Iterating over layers
Getting ready
How to do it...
How it works...
Symbolizing a vector layer
Getting ready
How to do it...
How it works...
Setting a transparent layer fill
Getting ready
How to do it...
How it works...
Using a filled marker symbol
Getting ready
How to do it...
Rendering a single band raster using a color ramp algorithm
Getting ready
How to do it...
How it works...
Setting a feature's color using a column in a CSV file
Getting ready
How to do it...
How it works...
Creating a complex vector layer symbol
Getting ready
How to do it...
How it works...
Using icons as vector layer symbols
Getting ready
How to do it...
How it works...
Using an outline for font markers
Getting ready
How to do it...
How it works...
Using arrow symbols
Getting ready
How to do it...
How it works...
Creating a graduated vector layer symbol renderer
Getting ready
How to do it...
How it works...
Creating a categorized vector layer symbol
Getting ready
How to do it...
How it works...
Using live layer effects
Getting ready
How to do it...
How it works...
Creating inverted polygon shapeburst fills
Getting ready
How to do it...
How it works...
Creating a map bookmark
Getting ready
How to do it...
How it works...
Navigating to a map bookmark
Getting ready
How to do it...
How it works...
Setting scale-based visibility for a layer
Getting ready
How to do it...
How it works...
Using SVG for layer symbols
Getting ready
How to do it...
How it works...
Using pie charts for symbols
Getting ready
How to do it...
How it works...
There's more...
Using the 2.5D renderer
Getting ready
How to do it...
How it works...
Using XYZ tiled map services
Getting ready
How to do it...
How it works...
Using Esri ArcGIS map services
Getting Ready
How to do it...
How it works...
Labeling a feature
Getting ready
How to do it...
How it works...
Using null symbols
Getting ready
How to do it...
How it works...
Change map layer transparency
Getting ready
How to do it...
How it works...
Adding standard map tools to the canvas
Getting ready
How to do it...
How it works...
Using a map tool to draw points on the canvas
Getting ready
How to do it...
How it works...
Using a map tool to draw polygons or lines on the canvas
Getting ready
How to do it...
How it works...
Building a custom selection tool
Getting ready
How to do it...
How it works...
Creating a mouse coordinate tracking tool
Getting ready
How to do it...
How it works...
6. Composing Static Maps
Introduction
Creating the simplest map renderer
Getting ready
How to do it...
How it works...
There's more...
Using the Map Composer
Getting ready
How to do it...
How it works...
There's more...
Adding labels to a map for printing
Getting ready
How to do it...
How it works...
Adding a scale bar to a map
Getting ready
How to do it...
How it works...
Adding a North arrow to the map
Getting ready
How to do it...
How it works...
There's more...
Adding a logo to the map
Getting ready
How to do it...
How it works...
Adding a vertical legend to the map
Getting ready
How to do it...
How it works...
Adding a horizontal legend
Getting ready
How to do it...
Adding a custom shape to the map
Getting ready
How to do it...
How it works...
There's more...
Adding a grid to the map
Getting ready
How to do it...
How it works...
Adding a table to the map
Getting ready
How to do it...
How it works...
Adding a world file to a map image
Getting ready
How to do it...
How it works...
Saving a map to a project
Getting ready
How to do it...
How it works...
Loading a map from a project
Getting ready
How to do it...
How it works...
7. Interacting with the User
Introduction
Using log files
Getting ready
How to do it...
How it works...
There's more...
Creating a simple message dialog
Getting ready
How to do it...
How it works...
There's more...
Creating a warning dialog
Getting ready
How to do it...
How it works...
Creating an error dialog
Getting ready
How to do it...
How it works...
Displaying a progress bar
Getting ready
How to do it...
How it works...
There's more...
Creating a simple text input dialog
Getting ready
How to do it...
How it works...
Creating a file input dialog
Getting ready
How to do it...
How it works...
There's more...
Creating a combobox
Getting ready
How to do it...
How it works...
Creating radio buttons
Getting ready
How to do it...
How it works...
Creating checkboxes
Getting ready
How to do it...
How it works...
Creating a dock widget
Getting ready
How to do it...
How it works...
Displaying a message in the status bar
Getting ready
How to do it...
How it works...
Pushing messages to the message bar
Getting ready
How to do it...
How it works...
Pushing widgets to the message bar
Getting ready
How to do it...
How it works...
Creating tabs
Getting ready
How to do it...
How it works...
Stepping the user through a wizard
Getting ready
How to do it...
How it works...
Keeping dialogs on top
Getting ready
How to do it...
How it works...
8. QGIS Workflows
Introduction
Creating an NDVI
Getting ready
How to do it...
How it works...
Geocoding addresses
Getting ready
How to do it...
How it works...
Creating raster footprints
Getting ready
How to do it...
How it works...
There's more...
Performing network analysis
Getting ready
How to do it...
How it works...
There's more...
Routing along streets
Getting ready
How to do it...
How it works...
Tracking a GPS
Getting ready
How to do it...
How it works...
There's more...
Creating a mapbook
Getting ready
How to do it...
How it works...
Finding the least cost path
Getting ready
How to do it...
How it works...
Performing nearest neighbor analysis
Getting ready
How to do it...
How it works...
Creating a DEM from LIDAR
Getting ready
How to do it...
How it works...
Creating a heat map
Getting ready
How to do it...
How it works...
Creating a dot density map
Getting ready
How to do it...
How it works...
Collecting field data
Getting ready
How to do it...
How it works...
Computing road slope using elevation data
Getting ready
How to do it...
How it works...
Geolocating photos on the map
Getting ready
How to do it...
How it works...
There's more...
Image change detection
Getting ready
How to do it...
How it works...
Adjusting imprecise building footprints
Getting ready
How to do it...
How it works...
Visualizing multitemporal data
Getting ready
How to do it...
How it works...
9. Other Tips and Tricks
Introduction
Creating tiles from a QGIS map
Getting ready
How to do it...
How it works...
There's more...
Adding a layer to geojson.io
Getting ready
How to do it...
How it works...
There's more...
Rendering map layers based on rules
Getting ready
How to do it...
How it works...
Creating a layer-definition file
Getting ready
How to do it...
How it works...
Using NULL values in PyQGIS
Getting ready
How to do it...
How it works...
Using generators for layer queries
Getting ready
How to do it...
How it works...
Using alpha values to show data density
Getting ready
How to do it...
How it works...
Using the __geo_interface__ protocol
Getting ready
How to do it...
How it works...
Getting the output file names from processing algorithms
Getting ready
How to do it...
How it works...
Generating points along a line
Getting ready
How to do it...
How it works...
There's more...
Using expression-based labels
Getting ready
How to do it...
How it works...
Creating dynamic forms in QGIS
Getting ready
How to do it...
How it works...
There's more...
Calculating length for all selected lines
Getting ready
How to do it...
How it works...
Using a different status bar CRS than the map
Getting ready
How to do it...
How it works...
Creating HTML labels in QGIS
Getting ready
How to do it...
How it works...
There's more...
Using OpenStreetMap points of interest in QGIS
Getting ready
How to do it...
How it works...
Changing the QGIS web proxy
Getting ready
How to do it...
How it works...
There's more...
Running QGIS scripts as scheduled tasks
Getting ready
How to do it...
How it works...
Visualizing data in 3D with WebGL
Getting ready
How to do it...
How it works...
Visualizing data on a globe
Getting ready
How to do it...
How it works...
Make a globe-like azimuthal orthographic projection
Getting ready
How to do it...
How it works...
Animating a layer
Getting ready
How to do it...

QGIS Python Programming Cookbook - Second Edition

QGIS Python Programming Cookbook - Second Edition

Copyright © 2017 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: March 2015

Second edition: March 2017

Production reference: 1030317

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham 

B3 2PB, UK.

ISBN 978-1-78712-483-7

www.packtpub.com

Credits

Author

Joel Lawhead

Copy Editor

Muktikant Garimella

Reviewer

Joshua Arnott

Project Coordinator

Sheejal Shah

Commissioning Editor

Kunal Parikh

Proofreader

Safis Editing

Acquisition Editor

Chaitanya Nair

Indexer

Francy Puthiry

Content Development Editor

Vikas Tiwari

Graphics

Abhinash Sahu

Technical Editor

Subhalaxmi Nadar

Production Coordinator

Deepika Naik

About the Author

Joel Lawhead is a PMI-certified Project Management Professional (PMP), a certified Geographic Information Systems Professional, and the Chief Information Officer (CIO) for http://www.nvisionsolutions.com/, an award-winning firm specializing in geospatial technology integration and harsh-environment engineering. Joel builds geospatial systems for US government agencies, including NASA, NOAA, the US Department of Homeland Security, and the military. He also works with private organizations, including the National Oceans and Applications Research Center (NOARC) and The Ocean Cleanup. He has authored other books with Packt Publishing, including Learning Geospatial Analysis with Python, QGIS Python Programming Cookbook, and Learning Geospatial Analysis with Python, Second Edition. His cookbook recipes have been featured in two editions of the O’Reilly Python Cookbook. Joel began using Python in 1997 and combined it with geospatial software development in 2000. He is also the developer of the widely used open source Python Shapefile Library (PyShp) and maintains the geospatial technical blog, http://geospatialpython.com/, and Twitter feed, @SpatialPython, discussing the use of Python within the geospatial industry. In 2011, Joel reverse-engineered and published the undocumented shapefile spatial indexing format and assisted fellow geospatial Python developer, Marc Pfister, in reversing the compression algorithm, allowing developers around the world to create better integrated and more robust geospatial applications involving shapefiles. In 2002, Joel received the international Esri Special Achievement in GIS award for his work on the Real-Time Emergency Action Coordination Tool (REACT) for emergency management using geospatial analysis.

This book would not be possible without the support of my beautiful family, including my wife, Julie, and four children, Lauren, Will, Lillie, and Lainie, who inspire everything I do. I would also like to acknowledge my employers and coworkers at http://www.nvisionsolutions.com/, a bright, dynamic team of people dedicated to working together at the exciting bleeding-edge of geospatial technology. And finally, thank you to the excellent reviewers for this and my other books, especially Joshua Arnott, who patiently and faithfully burned clumsy sentences to the ground so that a more technically-correct phoenix could rise up the ranks of the Amazon category Top 100 list.

About the Reviewer

Joshua Arnott is an environmental scientist with over five years of experience working in water management consultancy. His expertise lies in environmental modeling, with a focus on hydrology, water resources, and geoinformatics. He has contributed to several GIS-related open source projects, including QGIS and Shapely. He maintains a blog about programming and GIS at https://snorfalorpagus.net/, and he likes cats just as much as everyone else on the Internet.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Customer Feedback

Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1787124835.

If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

Preface

The open source geographic information system QGIS at version 2 now rivals even the most expensive commercial GIS software in both functionality and usability. It is also a showcase of the best geospatial open source technology available. It is not just a project in itself but the marriage of dozens of open source projects in a single, clean interface. 

Geospatial technology is not just the application of technology to geography. It is a symphony of geography, mathematics, computer science, statistics, physics, and other fields. The underlying algorithms implemented by QGIS are so complex that only a handful of people in the world understand them all.  Yet QGIS packages all of this complexity so well that school children, city managers, disease researchers, geologists, and many other professionals wield this powerful software with ease to make decisions that improve life on Earth.

But this book is about another feature of QGIS that makes it the best choice for geospatial work. QGIS has one of the most deeply integrated and well-designed Python interfaces of any software period. In the latest version, there is virtually no aspect of the program that is off-limits to Python, making it the largest geospatial Python library available. Almost without exception, the Python API, called PyQGIS, is consistent and predictable.

This book exploits the best features of QGIS to demonstrate over 170 reusable recipes that you can use to automate workflows in QGIS or build standalone GIS applications. Most recipes are very compact and have less than 20 lines of code. Even if you can’t find the exact solution you are looking for, you should be able to get very close. This book covers a lot of ground and pulls together fragmented ideas and documentation scattered throughout the Internet as well as the results of many hours of experimenting at the edges of the PyQGIS API.

What this book covers

Chapter 1, Automating QGIS, provides a brief overview of the different ways of using Python with QGIS, including the QGIS Python Console, standalone applications, plugins, and the Script Runner plugin. This chapter also covers setting and retrieving application settings and a few other Python-specific features.

Chapter 2, Querying Vector Data, covers extracting information from vector data without changing the data using Python. Topics include measuring, loading data from a database, filtering data, and other related processes.

Chapter 3, Editing Vector Data, introduces creating and updating data to add new information. It also teaches you how to break datasets apart based on spatial or database attributes as well as combine datasets. This chapter also teaches you how to convert data into different formats, change projections, simplify data, and more.

Chapter 4, Using Raster Data, demonstrates recipes for using and transforming raster data to create derivative products. This chapter highlights the capability of QGIS as a raster-processing engine and not just a vector GIS.

Chapter 5, Creating Dynamic Maps, transitions into recipes for controlling QGIS as a whole to control map, project, and application-level settings. It includes recipes for accessing external web services and building custom map tools.

Chapter 6, Composing Static Maps, shows you how to create printed maps using the QGIS Map Composer. You will learn to place reference elements on a map as well as design elements such as logos.

Chapter 7, Interacting with the User, teaches you to control QGIS GUI elements created by the underlying Qt framework to create interactive input widgets for scripts, plugins, or standalone applications.

Chapter 8, QGIS Workflows, contains more advanced recipes that result in a finished product or an extended capability. These recipes target actual tasks that geospatial analysts or programmers encounter on the job.

Chapter 9, Other Tips and Tricks, contains interesting recipes that fall outside the scope of previous chapters. Many of these recipes demonstrate multiple concepts within a single recipe that you may find useful for a variety of tasks.

What you need for this book

You will need the following software to complete all of the recipes in this book.  If a specific version is not available, use the most recent version.

QGIS 2.18Python 2.7.6 (should be included with QGIS itself)IBM Java 8 JDKIBM Eclipse Neon 4.6.0 or higherEclipse PyDev 5.5.0Google Earth 7.1.7.2602 or higher

Who this book is for

This book is for geospatial analysts or programmers at any experience level who would like to learn more about controlling QGIS using Python.  A basic knowledge of Python is essential and some experience with QGIS is helpful but not required.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).

To give clear instructions on how to complete a recipe, we use these sections as follows:

Getting ready

This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Open the startup.py file you created."

A block of code is set as follows:

import os os.getcwd()

Any command-line input or output is written as follows:

sudo apt-get update

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "From the Window menu, select Preferences."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors .

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/QGIS-Python-Programming-Cookbook-Second-Edition. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book 

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from http://www.packtpub.com/sites/default/files/downloads/QGISPythonProgrammingCookbookSecondEdition_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

Chapter 1. Automating QGIS

In this chapter, we will focus on the tools needed to write Python scripts for the PyQGIS framework. We will cover the following recipes:

Installing QGIS 2.18 for developmentUsing the QGIS Python console for interactive controlAutomatically starting the Python consoleUsing Python's Script Runner pluginSetting up your QGIS IDEDebugging QGIS Python scriptsNavigating the PyQGIS APICreating a traditional QGIS pluginCreating a Processing Toolbox pluginDistributing a pluginBuilding a standalone applicationStoring and reading global preferencesStoring and reading project preferencesAccessing the script path from within your script

Introduction

This chapter explains how to automate QGIS using Python. In addition to setting this up, we will also configure the free Eclipse Integrated Development Environment (IDE) along with the PyDev plugin to make writing, editing, and debugging scripts easier. We will also learn the basics of different types of QGIS Python scripts through the PyQGIS API. Finally, we'll examine some core QGIS plugins that significantly extend its capability.

Installing QGIS 2.18 for development

QGIS has a set of Python modules and libraries that can be accessed from the Python console within it. However, they can also be accessed from outside QGIS to write standalone applications. First, you must make sure that PyQGIS is installed on your platform, then set up some required environment variables.

In this recipe, we will walk you through the additional steps required beyond the normal installation process to prepare your system for development. The steps for each platform are provided, which also include the different styles of Linux package managers. The version of QGIS in your Linux package manager may be older. You can find additional detailed installation instructions at https://www.qgis.org/en/site/forusers/alldownloads.html.

Getting ready

QGIS uses different installation methods for Windows, GNU/Linux, and Mac OS X. The Windows installer installs everything you need for Python development, including Python itself.

However, on both Linux distributions and Mac OS X, you may need to manually install the Python modules to complete the installation process. On Mac OS X, you can download installers for some commonly used Python modules with QGIS; refer to http://www.kyngchaos.com/software/python.

How to do it...

On Linux, you have an option to either compile from the source or just specify the Python interface to be installed through your package manager.

Installing PyQGIS using the Debian package manager

For Linux distributions based on the Debian Linux package manager, which includes Ubuntu and Debian, use the following command in a shell: sudo apt-get updateNext, install the QGIS, PyQGIS, and QGIS GRASS plugins: sudo apt-get install qgis python-qgis qgis-plugin-grass

Installing PyQGIS using the RPM package manager

For Linux distributions based on the Red Hat Package Manager (RPM), first update the package manager as follows: sudo yum updateThen, install the packages for the QGIS, PyQGIS, and QGIS GRASS plugins: sudo yum install qgis qgis-python qgis-grass

Setting the environment variables

Now we need to set PYTHONPATH to the PyQGIS directory. At the same time, append the path to this directory to the PATH variable so that you can use the PyQGIS modules with an external IDE.

Setting the environment variables on Windows

Set the PYTHONPATH variable in a command prompt to the bin directory of the QGIS installation: set PYTHONPATH="C:\Program Files\QGIS 2.18\bin"Next, append QGIS's bin directories to the system's PATH variable: set PATH="C:\Program Files\QGIS 2.18\bin";"C:\Program Files\QGIS 2.18";%PATH%

Setting environment variables on Linux

Set the PYTHONPATH variable in a command prompt to the bin directory of the QGIS installation: export PYTHONPATH=/usr/share/qgis/pythonNow append the QGIS shared library directory to a runtime search path. Note that this location can vary depending on your system configuration: export LD_LIBRARY_PATH=/usr/share/qgis/python

How it works...

The QGIS installation process and package managers set up the Python module's configuration in a way that it becomes internal to QGIS. When you use the Python console inside QGIS, it knows where all the PyQGIS modules are. However, if you want to use the PyQGIS API outside it by using a system Python installation on either Windows or Linux, it would be necessary for you set some system variables so that Python could find the required PyQGIS modules.

There's more...

This recipe uses the default QGIS paths on each platform. If you aren't sure which PyQGIS path is for your system, you can figure this out from the Python console in QGIS.

Finding the PyQGIS path on Windows

The libraries on Windows, as opposed to other platforms, are stored in a different location. To locate the path, you need to check the current working directory of the Python console:

Start QGIS.Select Python Console from the Plugins menu, which will appear in the lower-right corner of the QGIS application window, as shown in the following screenshot. You can also use the keyboard shortcut Control+Alt+P to do this:Use the os module to get the current working directory: import os os.getcwd() Verify that the current working directory of the Python console is returned.

Finding the location of the QGIS Python installation on other platforms

Perform the following steps to find the path needed for this recipe on all the other platforms:

Start QGIS.Start the QGIS Python console.Use the sys module to locate the PyQGIS path import sys sys.path Python will return a list of paths.Find the path that ends in /python, which is the location of the Python installation used by QGIS.

Automatically starting the Python console

As you become familiar with programming QGIS using Python, you'll want the Python console to always be available in QGIS. So, in this recipe, we'll add a Python startup script to QGIS to make sure the console starts when QGIS does.

Getting ready

First, you need the startup.py file, which QGIS will read at startup. You'll be able to use this file to customize different aspects of QGIS:

In your user directory, locate the hidden .qgis2 folder.Your user folder is typically located in ~/.qgis2 on Linux and OSX and C:\Users\<username>\.qgis2 on Windows, which you can also access the %USERPROFILE% environment variable.Create a Python file named startup.py.

How to do it...

Open the startup.py file you created.Add the following lines to it: from console import console console.console_show()

How it works...

When QGIS starts, it looks for a Python script named startup.py in the user's folder and executes any code it finds there. If you have an error in the file, QGIS will display an error dialog and disable Python within QGIS.

Setting up your QGIS IDE

The Eclipse IDE and the PyDev plugin are cross-platform and free, and they possess advanced debugging tools.

Note

You can refer to http://pydev.org/manual_101_install.html in order to install PyDev correctly.

This tool makes an excellent PyQGIS IDE. Eclipse allows you to have multiple Python interpreters configured for different Python environments. When you install PyDev, it automatically finds the Python installations. On Windows, you also need to add the Python interpreter, installed with PyQGIS. On all platforms, you must tell PyDev where the PyQGIS libraries are.

Getting ready

This recipe uses Eclipse and PyDev. You can use the latest version of both the packages supported by your operating system. All platforms, except for Windows, rely on the Python interpreter. This means that there is an extra step in Windows to add the Python interpreter.

How to do it...

The following steps will walk you through the process of adding the QGIS-specific Python interpreter to Eclipse in order to support the running standalone QGIS applications or the debugging of QGIS plugins.

Adding the Python interpreter to Windows

The process used to add a Python interpreter to Eclipse on Windows is different from the process used on Linux. The following steps describe how to set up the interpreter on the Windows version of Eclipse:

Open Eclipse.From the Window menu, select Preferences.In the pane on the left-hand side of the Preferences window, click on the arrow icon next to PyDev.From the list of PyDev preferences, select Interpreters.In the pane labeled Python Interpreters, click on the New button.In the Select interpreter dialog, name the interpreter PyQGIS.Navigate to the location of the Python interpreter called python.exe, placed within the bin folder of the QGIS program folder. On OS X and Linux, you use the system's Python installation. On Windows, Python is included with QGIS. The default location on Windows is C:\Program Files\QGIS2.18\bin\python.exe, as shown in the following screenshot:When you click on the OK button, Eclipse will attempt to automatically add every Python library it finds to the Python path to configure this interpreter. We need to control which libraries are added to prevent conflicts. Click on the Deselect All button and then click on OK:Eclipse will issue a warning dialog because you haven't selected any core libraries. Click on the Proceed anyways button, as shown here:

Adding the PyQGIS module paths to the interpreter

Apart from adding the Python interpreter, you also need to add the module paths needed by PyQGIS, using the following steps. These steps will require you to switch back and forth between QGIS and Eclipse.

Start QGIS.Select Python Console from the Plugins menu.Use the sys module to locate the PyQGIS Python path, as described in the previous recipe, Setting the environment variables: import sys sys.path We also want to add the PyQGIS API so the script has access to all of the QGIS functions within Eclipse. Next, find that path using the QGIS Python Console by typing the following command: qgisFor each path in the returned list, click on the New Folder button in Eclipse's Libraries pane for your QGIS interpreter and browse to that folder until all the paths have been added. If a given folder does not exist on your system, simply ignore it, as shown here:Click on the OK button in the Preferences dialog.

Adding the PyQGIS API to the IDE

To take full advantage of Eclipse's features, including code completion, we will add the QGIS and Qt4 modules to the PyQGIS Eclipse interpreter preferences. The following steps will allow Eclipse to suggest the possible methods and properties of QGIS objects as you type; this feature is known as autocomplete:

In the PyDev preferences for the PyQGIS interpreter, select the Forced Builtins tab, as shown in the following screenshot:Click on the New button.In the Builtin to add dialog, type qgis:Click on the OK button.

Adding environment variables

You will also need to create a PATH variable that points to the QGIS binary libraries, DLLs on Windows, and other libraries needed by QGIS at runtime. And you'll need to create this on all platforms in the following way:

In the PyDev preferences dialog, ensure that the PyQGIS interpreter is selected from the list of interpreters.Select the Environment tab.Click on the New button.In the Name field, enter PATH.For the Value field, add the path to the QGIS program directory and to any QGIS directories that contain binaries separated by a semicolon. The following is an example from a Windows machine: C:\Program Files\QGIS 2.18;C:\Program Files\QGIS 2.18\bin; C:\Program Files\QGIS 2.18\apps\qgis\bin;C:\Program Files\QGIS 2.18\apps\Python27\DLLs

How it works...

Eclipse and PyDev use only the information you provide to run a script in the Eclipse workspace. This approach is very similar to the popular Python tool virtualenv, which provides a clean environment when writing and debugging code to ensure that you don't waste time troubleshooting issues caused by the environment.