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

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

  • Python 2.7.6 (should be included with QGIS itself)

  • IBM Java 8 JDK

  • IBM Eclipse Neon 4.6.0 or higher

  • Eclipse PyDev 5.5.0

  • Google 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:

  1. Log in or register to our website using your e-mail address and password.

  2. Hover the mouse pointer on the SUPPORT tab at the top.

  3. Click on Code Downloads & Errata.

  4. Enter the name of the book in the Search box.

  5. Select the book for which you're looking to download the code files.

  6. Choose from the drop-down menu where you purchased this book from.

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

  • Zipeg / iZip / UnRarX for Mac

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