About this ebook
- Use Python and QGIS to create and transform data, produce appealing GIS visualizations, and build complex map layouts
- Learn undocumented features of the new QGIS processing module
- A set of user-friendly recipes that can automate the entire geospatial workflows by connecting Python GIS building blocks into comprehensive processes
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. The short, reusable recipes make concepts easy to understand. You can build larger applications that are easy to maintain when they are put together.
Joel Lawhead
Joel Lawhead is a PMI-certified Project Management Professional (PMP), a certified GIS Professional (GISP), and vice president of NVision Solutions, Inc., an award-winning firm specializing in geospatial technology integration and sensor engineering for NASA, FEMA, NOAA, the US Navy, and many other commercial and non-profit organizations. Joel began using Python in 1997 and started combining it with geospatial software development in 2000. He has authored multiple editions of Learning Geospatial Analysis with Python and QGIS Python Programming Cookbook, both from Packt. He is also the developer of the open source Python Shapefile Library (PyShp) and maintains a geospatial technical blog.
Read more from Joel Lawhead
Learning Geospatial Analysis with Python Rating: 5 out of 5 stars5/5QGIS Python Programming Cookbook - Second Edition Rating: 0 out of 5 stars0 ratings
Related to QGIS Python Programming Cookbook
Related ebooks
Practical GIS Rating: 0 out of 5 stars0 ratingsPython Geospatial Analysis Essentials Rating: 0 out of 5 stars0 ratingsQGIS By Example Rating: 3 out of 5 stars3/5Python Geospatial Development Essentials Rating: 0 out of 5 stars0 ratingsInstant OpenLayers Starter Rating: 0 out of 5 stars0 ratingsLearning QGIS 2.0 Rating: 5 out of 5 stars5/5Learning QGIS - Third Edition Rating: 4 out of 5 stars4/5Mapbox Cookbook: Over 35 recipes to design and implement uniquely styled maps using the Mapbox platform Rating: 0 out of 5 stars0 ratingsArcGIS By Example Rating: 1 out of 5 stars1/5Python Geospatial Development - Third Edition Rating: 4 out of 5 stars4/5Python Geospatial Development Rating: 4 out of 5 stars4/5Spatial Analytics with ArcGIS Rating: 0 out of 5 stars0 ratingsBuilding Mapping Applications with QGIS Rating: 0 out of 5 stars0 ratingsMastering QGIS Rating: 5 out of 5 stars5/5PostGIS Cookbook Rating: 0 out of 5 stars0 ratingsLearning D3.js Mapping Rating: 0 out of 5 stars0 ratingsArcPy and ArcGIS – Geospatial Analysis with Python Rating: 0 out of 5 stars0 ratingsMastering PostGIS Rating: 0 out of 5 stars0 ratingsMastering ArcGIS Server Development with JavaScript Rating: 4 out of 5 stars4/5Learning ArcGIS Runtime SDK for .NET Rating: 0 out of 5 stars0 ratingsBuilding Web Applications with ArcGIS Rating: 5 out of 5 stars5/5ArcGIS for Desktop Cookbook Rating: 5 out of 5 stars5/5ArcPy and ArcGIS - Second Edition Rating: 4 out of 5 stars4/5Leaflet.js Essentials Rating: 4 out of 5 stars4/5Mastering GeoServer Rating: 0 out of 5 stars0 ratingsLearning ArcGIS Geodatabases Rating: 5 out of 5 stars5/5GeoServer Cookbook Rating: 0 out of 5 stars0 ratingsProgramming ArcGIS with Python Cookbook - Second Edition Rating: 4 out of 5 stars4/5Google Maps JavaScript API Cookbook Rating: 2 out of 5 stars2/5GeoServer Beginner's Guide Rating: 0 out of 5 stars0 ratings
Programming For You
HTML in 30 Pages Rating: 5 out of 5 stars5/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsPython: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5Python Data Structures and Algorithms Rating: 5 out of 5 stars5/5Microsoft Azure For Dummies Rating: 0 out of 5 stars0 ratingsSQL All-in-One For Dummies Rating: 3 out of 5 stars3/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5Coding with JavaScript For Dummies Rating: 0 out of 5 stars0 ratingsAlgorithms For Dummies Rating: 4 out of 5 stars4/5Spies, Lies, and Algorithms: The History and Future of American Intelligence Rating: 4 out of 5 stars4/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5Coding All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsPYTHON PROGRAMMING Rating: 4 out of 5 stars4/5Learn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 5 out of 5 stars5/5The Absolute Beginner's Guide to Binary, Hex, Bits, and Bytes! How to Master Your Computer's Love Language Rating: 5 out of 5 stars5/5Python for Beginners: A Step by Step Guide on How to Program with Python Rating: 0 out of 5 stars0 ratings
Reviews for QGIS Python Programming Cookbook
0 ratings0 reviews
Book preview
QGIS Python Programming Cookbook - Joel Lawhead
Table of Contents
QGIS Python Programming Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why Subscribe?
Free Access for Packt account holders
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 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 the 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…
Using the Python ScriptRunner plugin
Getting ready
How to do it…
How it works…
Setting up your QGIS IDE
Getting ready
How to do it…
Adding the QGIS Python interpreter on 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 QGIS 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…
Creating 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 spatial database
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 intermediate
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 the distance along a line sample
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...
3. Editing Vector Data
Introduction
Creating a vector layer in memory
Getting ready
How to do it...
How it works...
There's more…
Adding a point feature to a vector layer
Getting ready
How to do it...
How it works...
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...
Moving 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...
Deleting a vector layer feature
Getting ready
How to do it...
How it works...
Deleting a vector layer 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
Getting ready
How to do it...
How it works...
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 shapes
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...
4. Using Raster Data
Introduction
Loading a raster layer
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...
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 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...
Rendering a single band raster using a color ramp algorithm
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…
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...
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 OpenStreetMap service
Getting ready
How to do it...
How it works...
Using the Bing aerial image service
Getting ready
How to do it...
How it works...
Adding real-time weather data from OpenWeatherMap
Getting ready
How to do it...
How it works...
Labeling features
Getting ready
How to do it...
How it works...
Changing 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 the 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 legend to the map
Getting ready
How to do it...
How it works...
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...
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 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...
There's more...
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...
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 heat map
Getting ready
How to do it...
How it works...
There's more...
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...
9. Other Tips and Tricks
Introduction
Creating tiles from a QGIS map
Getting ready
How to do it...
How it works...
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 style 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...
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...
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's points of interest in QGIS
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...
Index
QGIS Python Programming Cookbook
QGIS Python Programming Cookbook
Copyright © 2015 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
Production reference: 1240315
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78398-498-5
www.packtpub.com
Credits
Author
Joel Lawhead
Reviewers
Joshua Arnott
Giuseppe De Marco
Jonathan Gross
Luigi Pirelli
Hiroaki Sengoku
Commissioning Editor
Pramila Balan
Acquisition Editor
Sonali Vernekar
Content Development Editor
Prachi Bisht
Technical Editor
Deepti Tuscano
Copy Editor
Dipti Kapadia
Project Coordinator
Shipra Chawhan
Proofreaders
Safis Editing
Maria Gould
Indexer
Hemangini Bari
Production Coordinator
Nitesh Thakur
Cover Work
Nitesh Thakur
About the Author
Joel Lawhead is a PMI-certified Project Management Professional (PMP) and the Chief Information Officer (CIO) of NVisionSolutions Inc., an award-winning firm that specializes in geospatial technology integration and sensor engineering.
Joel began using Python in 1997 and began combining it with geospatial software development in 2000. He is the author of Learning Geospatial Analysis with Python, Packt Publishing. His Python cookbook recipes were featured in two editions of Python Cookbook, O'Reilly Media. He is also the developer of the widely used, open source Python Shapefile Library (PyShp) and maintains the geospatial technical blog GeospatialPython.com and the Twitter feed @SpatialPython, which discuss the use of the Python programming language 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 algorithm used, allowing developers around the world to create better-integrated and more robust geospatial applications involving shapefiles.
Joel served as the lead architect, project manager, and co-developer for geospatial applications used by US government agencies, including NASA, FEMA, NOAA, the US Navy, and many other commercial and non-profit organizations. In 2002, he 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.
I would like to acknowledge my beautiful family, including my wife, Julie, and four children, Lauren, Will, Lillie, and Lainie, who allowed me to write yet another book in our limited collective free time. I would also like to acknowledge my employers and coworkers at NVisionSolutions.com, a bright team of people dedicated to working together at the exciting bleeding edge of geospatial technology.
About the Reviewers
Joshua Arnott is an environmental scientist with four years of academic and consultancy experience. His expertise lies in environmental modeling, with a focus on hydrology and geoinformatics. He has contributed to a number of GIS-related open source projects, including QGIS and Shapely. He maintains a blog about programming and GIS at snorfalorpagus.net, and he likes cats just as much as everyone else on the Internet.
Giuseppe De Marco was born in 1973 in Ferentino, Italy. He has a high school certificate in humanities and attained a bachelor's degree in agriculture from the University of Pisa. When he was a small boy, he began to use computers and learn programming languages (BASIC, Pascal, Fortran, and so on). At the university, he began to encounter open source software and the Linux OS, and he developed a deep interest in geography and GIS and other programming languages, such as C++ and Python, by first getting in touch with Esri commercial products and later with GRASS and QGIS. Since the QGIS 1.7.4 release, he's been developing plugins for this software, sometimes purely to seek knowledge and at other times for work. In 2008, he began a professional partnership with two colleagues called Pienocampo (open field), and his plugins are hosted on Pienocampo's website and on the QGIS official repository. At the moment, he lives in his hometown Ferentino and works as a freelance agriculture engineer. His work activities include studying geography, surveying, tree risk assessment, landscaping, bioengineering, and farm consulting. In 2014, he also began to teach other colleagues how to use QGIS and other open source software.
I would like to thank my wife, Fabiola; my little daughter, Anna; my mother, Angela; and my colleagues, Marco De Castris, Ettore Arcangeletti, Luca Grande, and Ivan Solinas.
Jonathan Gross is the author of the Open Source GIS blog, http://opensourcegisblog.blogspot.com/. He has a master's of public health degree in epidemiology from the University of Michigan, Ann Arbor, and a graduate certificate in geographic information systems from Johns Hopkins Advanced Academic Programs. He has done graduate coursework in Python and uses Python for programming small tasks. He is currently an epidemiologist at the Baltimore City Health Department, Maryland, where he performs spatial analysis on health and crime data.
Luigi Pirelli is a freelance software analyst and developer with a honors degree in computer science from the University of Bari.
He has worked for 15 years in satellite ground segmentation and direct ingestion systems for the European Space Agency. Since 2006, he has been involved in the GFOSS world, contributing to QGIS, GRASS, and the MapServer core, and developing and maintaining many QGIS plugins. He actively participates in QGIS Hackmeetings.
He is the founder of the OSGEO Italian local chapter GFOSS.it and now lives in Spain, where he contributes to the GFOSS community. During the past few years, he started teaching PyQGIS by organizing trainings, from basic to advanced level, supporting companies to develop their specific QGIS plugins.
He has coauthored Mastering QGIS, Packt Publishing.
He is the founder of the local hackerspace group, Bricolabs.cc that is focused on all things related to open source hardware. He likes to cycle, repair everything, and train groups on conflict resolution.
Other than this book, he has also contributed to the guide, Cycling Italy, Lonely Planet.
A special thanks to the QGIS developer community and core developers because the project is managed in an open way, allowing contribution from