39,59 €
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:
Seitenzahl: 407
Veröffentlichungsjahr: 2017
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
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
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.
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.
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.
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!
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.
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.
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.
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.
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:
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.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
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 updateNew 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."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
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 .
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.
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:
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:
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!
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.
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 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.
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.
In this chapter, we will focus on the tools needed to write Python scripts for the PyQGIS framework. We will cover the following recipes:
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.
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.
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.
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.
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.
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.
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.
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:
Perform the following steps to find the path needed for this recipe on all the other platforms:
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.
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:
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.
The Eclipse IDE and the PyDev plugin are cross-platform and free, and they possess advanced debugging tools.
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.
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.
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.
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:
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.
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:
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:
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.