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
About the Author
About the Reviewers


The open source geographic information system, QGIS, at version 2.6 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 combined 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 can understand all of them. Yet, QGIS packages all 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.

However, 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 140 reusable recipes, which you can use to automate workflows in QGIS or to build standalone GIS applications. Most recipes are very compact, and even if you can't find the exact solution that you are looking for, you should be able to get 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 in which you can use Python with QGIS, including the QGIS Python console, standalone applications, plugins, and the Script Runner plugin. This chapter also covers how to set and retrieve application settings and a few other Python-specific features.

Chapter 2, Querying Vector Data, covers how to extract information from vector data without changing the data using Python. The topics covered include measuring, loading data from a database, filtering data, and other related processes.

Chapter 3, Editing Vector Data, introduces the topic of 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 how to combine datasets. This chapter will also teach you how to convert data into different formats, change projections, simplify data, and more.

Chapter 4, Using Raster Data, demonstrates 25 recipes to use and transform raster data in order 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 to control QGIS as a whole in order to control map, project, and application-level settings. It includes recipes to access external web services and build custom map tools.

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

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

Chapter 8, QGIS Workflows, contains more advanced recipes, which 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 the previous chapters. Many of these recipes demonstrate multiple concepts within a single recipe, which you may find useful for a variety of tasks.

What you need for this book

You will need the following software to complete all the recipes in this book; if a specific version is not available, use the most recent version:

  • QGIS 2.6

  • Python 2.7.6 (should be included with QGIS itself)

  • IBM Java 7 Dev Kit

  • Eclipse Luna 4.4.x

  • Google Earth

Who this book is for

If you are a geospatial analyst who wants to learn more about automating everyday GIS tasks or a programmer who is responsible for building GIS applications, this book is for you. Basic knowledge of Python is essential and some experience with QGIS will be an added advantage.

The short, reusable recipes make concepts easy to understand. You can build larger applications that are easy to maintain when they are put together.


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.


In this book, you will find a number of styles of text 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: "In the QGIS Python Console, we'll import the random module."

A block of code is set as follows:

proj = QgsProject.instance()
proj.title("My QGIS Project")
proj.writeEntry("MyPlugin", "splash", "Geospatial Python Rocks!")
proj.readEntry("MyPlugin", "splash", "Welcome!")[0]

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

sudo easy_install PyPDF2

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "Enter information in the form and click on the Send button."


Warnings or important notes appear in a box like this.


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 may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to , and mention the book title via 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 on

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 all Packt books you have purchased from your account at If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you.

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


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 would 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, 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 on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from


Piracy of copyright 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 with a link to the suspected pirated material.

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


You can contact us at if you are having a problem with any aspect of the book, and we will do our best to address it.