QGIS Python Programming Cookbook - Joel Lawhead - E-Book

QGIS Python Programming Cookbook 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

Key Features

    Book Description

    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.

    What you will learn

    • Build a library of reusable scripts with ScriptRunner
    • Create, import, and edit geospatial data on disk or in memory
    • Get to know more about dynamic mapping
    • Create and add features to static maps
    • Create a mapbook
    • Reproject a vector layer
    • Geolocate photos on a map
    • Combine multiple rasters into one image

    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. The short, reusable recipes make concepts easy to understand. You can build larger applications that are easy to maintain when they are put together.

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

    EPUB
    MOBI

    Seitenzahl: 363

    Veröffentlichungsjahr: 2015

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

    I want to thank everyone I have worked with. From each one of them, I learned something and without them, I wouldn't be here, contributing to free software and this book.

    A special thanks to my friends and neighbors who helped me with my son during the review of the book.

    I would like to dedicate this work to my partner and especially my son, for having the patience to see me sit in front of the computer for hours without playing with him.

    Hiroaki Sengoku was born in 1987 in Gifu, Japan. He did his BA in environmental information from Keio University in 2009. He completed an MA in environmental studies from the University of Tokyo in 2011 and a PhD in environmental studies from the University of Tokyo in 2014. He is the founder and CEO of Microbase Inc., which he established when he was a PhD student. He is interested in the field of microgeographic simulation and has held many workshops on this. His dream is to create a real SimCity.

    Microbase Inc. is the company that creates microdemographic data in Japan. This company has created simulated urban data, such as people flow or people's lifestyles, using open data. The members of Microbase Inc. aim to create microdemographic data all over the world and a simulation platform, such as SimCity, using this data.

    You can watch a demo movie at https://www.youtube.com/watch?v=kXKRU4CLJro and http://microgeodata.com/.

    I couldn't have reviewed this book without the help of the members of Microbase Inc. I'd like to thank them for their help in the reviewing process. Also, I would like to thank Shipra Chawhan and Paushali Desai, who gave me the chance to review this book. I had an exciting experience and appreciate their efforts.

    www.PacktPub.com

    Support files, eBooks, discount offers, and more

    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://www2.packtpub.com/books/subscription/packtlib

    Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

    Why Subscribe?

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

    Free Access for Packt account holders

    If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.

    Preface

    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.6Python 2.7.6 (should be included with QGIS itself)IBM Java 7 Dev KitEclipse Luna 4.4.xGoogle Earth 7.1.2.2041

    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.

    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.

    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 <[email protected]>, 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 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 all Packt books you have purchased 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.

    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/4985OS_ColoredImages.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 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 http://www.packtpub.com/submit-errata, selecting your book, clicking on the erratasubmissionform 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 http://www.packtpub.com/support.

    Piracy

    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 <[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

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

    Chapter 1. Automating QGIS

    In this chapter, we will cover the following recipes:

    Installing QGIS for developmentUsing the QGIS Python consoleUsing Python's ScriptRunner pluginSetting up your QGIS IDEDebugging QGIS Python scriptsNavigating the PyQGIS APICreating a QGIS 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 configure QGIS for automation using Python. In addition to setting up QGIS, we will also configure the free Eclipse Integrated Development Environment (IDE) with the PyDev plugin to make writing, editing, and debugging scripts easier. We will also learn the basics of different types of QGIS automated Python scripts through the PyQGIS API. Finally, we'll examine some core QGIS plugins that significantly extend the capability of QGIS.

    Installing QGIS for development

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

    In this recipe, we will walk you through the additional steps required beyond the normal QGIS installation to prepare your system for development. The steps for each platform are provided, which also include the different styles of Linux package managers.

    Getting ready

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

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

    How to do it

    On Linux, you have the option to compile from the source or you can just specify the Python QGIS 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 update
    Next, 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 update
    Then, 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 must set the 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 Brighton\bin"
    Next, append QGIS's bin directories to the system's PATH variable:
    set PATH="C:\Program Files\QGIS Brighton\bin";"C:\Program Files\QGIS Brighton\bin\apps\qgis\bin";%PATH%

    Setting the 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/python
    Now, append the QGIS shared library directory to the runtime search path. Note that this location can vary depending on your particular 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 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 QGIS, using a system Python installation on Windows or Linux, it is necessary to set some system variables so that Python can 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 are stored in a different location than in the case of other platforms. To locate the path, you can check the current working directory of the Python console:

    Start QGIS.Select Python Console from the Plugins menu, which appears in the lower-right corner of the QGIS application window, as shown in the following screenshot:Use the os module to get the current working directory:
    import osos.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 platforms besides Windows:

    Start QGIS.Start the QGIS Python Console.Use the sys module to locate the PyQGIS path:
    import syssys.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

    Setting up your QGIS IDE

    The Eclipse IDE with the PyDev plugin is cross-platform, has advanced debugging tools, and is free.

    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 installed system Python installations. On Windows, you must also 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 either package that is supported by your operating system. All platforms besides Windows rely on the system Python interpreter. So, there is an extra step in Windows to add the QGIS Python interpreter.

    How to do it…