39,59 €
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:
Seitenzahl: 363
Veröffentlichungsjahr: 2015
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
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
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.
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.
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.
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.
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.
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.
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:
If you are a geospatial analyst who wants to learn more about automating everyday GIS tasks or a programmer who is responsible for building GIS applications, this book is for you. Basic knowledge of Python is essential and some experience with QGIS will be an added advantage.
The short, reusable recipes make concepts easy to understand. You can build larger applications that are easy to maintain when they are put together.
In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).
To give clear instructions on how to complete a recipe, we use these sections as follows:
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.
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.
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 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.
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.
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 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.
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.
In this chapter, we will cover the following recipes:
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.
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.
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.
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.
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.
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.
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 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:
Perform the following steps to find the path needed for this recipe on all the platforms besides Windows:
The Eclipse IDE with the PyDev plugin is cross-platform, has advanced debugging tools, and is free.
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.
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.