QGIS 2 Cookbook - Alex Mandel - E-Book

QGIS 2 Cookbook E-Book

Alex Mandel

0,0
43,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Become a QGIS power user and master QGIS data management, visualization, and spatial analysis techniques

About This Book

  • Explore and create time-based visualizations and build interactive maps
  • Maximize your use of the QGIS features, plugins and toolbox automation
  • Packed with lots of sample datasets to enable a better understanding of the code

Who This Book Is For

If you are an intermediate GIS user, with either previous experience in QGIS or any other GIS application, this is the book for you. The recipes can be used to learn more advanced techniques in QGIS or to replicate the functionalities equivalent to other GIS platforms. This book assumes that you already have a working QGIS system in place.

What You Will Learn

  • Import and export common tricky spatial data formats
  • Perform classic vector and raster analysis with QGIS
  • Utilize spatial databases and data management tools
  • Use and create geographic web services and maps
  • Explore and create time-based visualizations
  • Perform network building and routing analysis
  • Extend QGIS capabilities with popular plugins and toolbox automation
  • Make beautiful and unique maps with customized cartography

In Detail

QGIS is a user-friendly, cross-platform desktop geographic information system used to make maps and analyze spatial data. QGIS allows users to understand, question, interpret, and visualize spatial data in many ways that reveal relationships, patterns, and trends in the form of maps. This book is a collection of simple to advanced techniques that are needed in everyday geospatial work, and shows how to accomplish them with QGIS. You will begin by understanding the different types of data management techniques, as well as how data exploration works. You will then learn how to perform classic vector and raster analysis with QGIS, apart from creating time-based visualizations. Finally, you will learn how to create interactive and visually appealing maps with custom cartography. By the end of this book, you will have all the necessary knowledge to handle spatial data management, exploration, and visualization tasks in QGIS.

Style and approach

This book covers practical examples, with step-by-step instructions on how to use real world data covering common GIS operations and the different analysis techniques. It provides detailed explanations and applications of QGIS concepts that will allow the user to effectively analyze spatial data.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 400

Veröffentlichungsjahr: 2016

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 2 Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
eBooks, discount offers, and more
Why Subscribe?
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. Data Input and Output
Introduction
Finding geospatial data on your computer
Getting ready
How to do it…
How it works…
There's more…
Adding layers with the Layer menu
Adding a folder to Favorites
Nonfile data sources
Describing data sources
Getting ready
How to do it…
How it works…
There's more…
See also
Importing data from text files
How to do it…
How it works…
There's more…
See also
Importing KML/KMZ files
How to do it…
How it works…
There's more…
Importing DXF/DWG files
How to do it…
How it works…
There's more…
Opening DWG files
Opening a NetCDF file
How to do it…
How it works…
There's more…
The NetCDF Browser plugin
Saving a vector layer
Getting ready
How to do it…
How it works…
There's more…
Fine-tuning the export operation
Opening the layer after creating it
Saving a raster layer
Getting ready
How to do it…
How it works…
There's more…
Reprojecting a layer
Getting ready
How to do it…
How it works…
There's more…
Batch format conversion
Getting ready
How to do it…
How it works…
There's more…
Batch reprojection
How to do it…
How it works…
There's more…
Loading vector layers into SpatiaLite
Getting ready
How to do it…
How it works…
There's more…
See also
Loading vector layers into PostGIS
Getting ready
How to do it…
How it works…
There's more…
See also
2. Data Management
Introduction
Joining layer data
Getting ready
How to do it…
How it works…
There's more…
Cleaning up the attribute table
Getting ready
How to do it…
How it works…
There's more…
See also
Configuring relations
Getting ready
How to do it…
How it works…
Joining tables in databases
Getting ready
How to do it…
How it works…
There's more…
See also
Creating views in SpatiaLite
Getting ready
How to do it…
How it works…
There's more…
See also
Creating views in PostGIS
Getting ready
How to do it…
How it works…
There's more…
See also
Creating spatial indexes
Getting ready
How to do it…
How it works…
There's more…
See also
Georeferencing rasters
Getting ready
How to do it…
How it works…
There's more…
See also
Georeferencing vector layers
Getting ready
How to do it…
How it works…
There's more…
See also
Creating raster overviews (pyramids)
Getting ready
How to do it…
How it works…
There's more…
See also
Building virtual rasters (catalogs)
Getting ready
How to do it…
How it works…
There's more…
See also
3. Common Data Preprocessing Steps
Introduction
Converting points to lines to polygons and back – QGIS
Getting ready
How to do it…
Converting points to lines (or polygons)
Converting lines to polygons
Converting polygons to lines
Converting polygons or lines to points
How it works…
There's more…
Converting points to lines to polygons and back – SpatiaLite
Getting ready
How to do it…
Points to lines
Lines to polygons
How it works…
There's more…
See also
Converting points to lines to polygons and back – PostGIS
Getting ready
How to do it…
Converting points to lines
Converting lines to polygons
Converting lines or polygons to points
How it works…
There's more…
See also
Cropping rasters
Getting ready
How to do it…
How it works…
There's more…
See also
Clipping vectors
Getting ready
How to do it…
How it works…
There's more…
See also
Extracting vectors
Getting ready
How to do it…
How it works…
There's more…
See also
Converting rasters to vectors
Getting ready
How to do it…
How it works…
There's more…
See also
Converting vectors to rasters
Getting ready
How to do it…
How it works…
There's more…
See also
Building DateTime strings
Getting ready
How to do it…
How it works…
There's more…
See also
Geotagging photos
Getting ready
How to do it…
How it works…
There's more…
See also
4. Data Exploration
Introduction
Listing unique values in a column
Getting ready
How to do it…
How it works…
There's more…
Exploring numeric value distribution in a column
Getting ready
How to do it…
How it works...
See also
Exploring spatiotemporal vector data using Time Manager
Getting ready
How to do it…
How it works…
See also
Creating animations using Time Manager
Getting ready
How to do it…
How it works…
Designing time-dependent styles
Getting ready
How to do it…
How it works…
See also
Loading BaseMaps with the QuickMapServices plugin
Getting ready
How to do it…
How it works…
There's more…
See also
Loading BaseMaps with the OpenLayers plugin
Getting ready
How to do it…
How it works…
There's more…
See also
Viewing geotagged photos
Getting ready
How to do it…
Going a little further
How it works…
There's more…
See also
5. Classic Vector Analysis
Introduction
Selecting optimum sites
Getting ready
How to do it…
How it works…
There's more…
Dasymetric mapping
Getting ready
How to do it…
How it works…
Calculating regional statistics
Getting ready
How to do it…
How it works…
Estimating density heatmaps
Getting ready
How to do it…
How it works…
Estimating values based on samples
Getting ready
How to do it…
How it works…
There's more…
See also
6. Network Analysis
Introduction
Creating a simple routing network
Getting ready
How to do it…
How it works…
There's more…
Calculating the shortest paths using the Road graph plugin
Getting ready
How to do it…
How it works…
See also
Routing with one-way streets in the Road graph plugin
Getting ready
How to do it…
How it works…
Calculating the shortest paths with the QGIS network analysis library
Getting ready
How to do it…
How it works…
See also
Routing point sequences
Getting ready
How to do it…
How it works…
There's more…
See also
Automating multiple route computation using batch processing
Getting ready
How to do it…
Matching points to the nearest line
Getting ready
How to do it…
How it works…
Creating a routing network for pgRouting
Getting ready
How to do it…
How it works…
See also
Visualizing the pgRouting results in QGIS
Getting ready
How to do it…
How it works…
See also
Using the pgRoutingLayer plugin for convenience
Getting ready
How to do it…
How it works…
See also
Getting network data from the OSM
Getting ready
How to do it…
How it works…
7. Raster Analysis I
Introduction
Using the raster calculator
Getting ready
How to do it…
How it works…
There's more…
See also
Preparing elevation data
Getting ready
How to do it…
How it works…
There's more…
Calculating a slope
Getting ready
How to do it…
How it works…
There's more…
Using a ratio for elevation values
Other slope algorithms
Calculating the slope
See also
Calculating a hillshade layer
Getting ready
How to do it…
How it works…
There's more…
Enhancing your map view with a hillshade layer
Analyzing hydrology
Getting ready
How to do it…
How it works…
There's more…
Calculating a topographic index
Getting ready
How to do it…
How it works…
There's more…
Automating analysis tasks using the graphical modeler
Getting ready
How to do it…
How it works…
See also
8. Raster Analysis II
Introduction
Calculating NDVI
Getting ready
How to do it…
How it works…
There's more…
Extracting bands
Handling null values
How to do it…
How it works…
There's more…
Controlling the rendering of null values
Setting extents with masks
How to do it…
How it works…
There's more…
Restricting analysis to a given area
Removing superfluous no-data values
Masking using a vector mask
Sampling a raster layer
Getting ready
How to do it…
How it works…
There's more…
Other raster-vector data transfer operations
Visualizing multispectral layers
Getting ready
How to do it…
How it works…
There's more…
See also
Modifying and reclassifying values in raster layers
Getting ready
How to do it…
How it works…
There's more…
Reclassifying into classes of equal amplitude
Reclassifying into classes of equal area
See also
Performing supervised classification of raster layers
Getting ready
How to do it…
How it works…
There's more…
See also
9. QGIS and the Web
Introduction
Using web services
Getting ready
How to do it…
How it works…
There's more…
See also
Using WFS and WFS-T
Getting ready
How to do it…
How it works…
There's more…
Searching CSW
Getting ready
How to do it…
How it works…
There's more…
See also
Using WMS and WMS Tiles
Getting ready
How to do it…
How it works…
There's more…
See also
Using WCS
Getting ready
How to do it…
How it works…
There's more…
Using GDAL
Getting ready
How to do it…
How it works…
There's more…
See also
Serving web maps with the QGIS server
Getting ready
How to do it…
How it works…
There's more…
See also
Scale-dependent rendering
Getting ready
How to do it…
How it works…
There's more…
See also
Hooking up web clients
Getting ready
How to do it…
How it works…
There's more…
See also
Managing GeoServer from QGIS
Getting ready
How to do it…
How it works…
There's more…
Editing a remote style
Support for multiple formats
See also
10. Cartography Tips
Introduction
Using Rule Based Rendering
Getting ready
How to do it…
How it works…
There's more…
Handling transparencies
Getting ready
How to do it…
How it works…
There's more…
Understanding the feature and layer blending modes
Getting ready
How to do it…
How it works…
Saving and loading styles
Getting ready
How to do it…
How it works…
There's more…
Configuring data-defined labels
Getting ready
How to do it…
Example: moving and rotating a label
How it works…
There's more…
Creating custom SVG graphics
Getting ready
How to do it…
How it works…
There's more…
See also
Making pretty graticules in any projection
Getting ready
How to do it…
How it works…
There's more…
See also
Making useful graticules in printed maps
Getting ready
How to do it…
How it works…
There's more…
Creating a map series using Atlas
Getting ready
How to do it…
How it works…
There's more…
11. Extending QGIS
Introduction
Defining custom projections
Getting ready
How to do it…
How it works…
There's more…
See also
Working near the dateline
Getting ready
How to do it…
How it works…
See also
Working offline
Getting ready
How to do it…
How it works…
There's more…
See also
Using the QspatiaLite plugin
Getting ready
How to do it…
How it works…
There's more…
See also
Adding plugins with Python dependencies
Getting ready
How to do it…
How it works…
There's more…
Using the Python console
Getting ready
How to do it…
How it works…
There's more…
See also
Writing Processing algorithms
Getting ready
How to do it…
How it works…
There's more…
See also
Writing QGIS plugins
Getting ready
How to do it…
How it works…
There's more…
Creating plugins with more complex UI elements
Documenting you plugin
Releasing your plugin
Using external tools
Getting ready
How to do it…
GPSBabel
spatialite-gui
pgAdmin
How it works…
There's more…
12. Up and Coming
Introduction
Preparing LiDAR data
Getting ready
How to do it…
How it works…
There's more…
Opening File Geodatabases with the OpenFileGDB driver
Getting ready
How to do it…
How it works…
There's more…
See also
Using Geopackages
Getting ready
How to do it…
How it works…
There's more…
See also
The PostGIS Topology Editor plugin
Getting ready
How to do it…
How it works…
See also
The Topology Checker plugin
Getting ready
How to do it…
How it works…
See also
GRASS Topology tools
Getting ready
How to do it…
How it works…
There's more…
See also
Hunting for bugs
Getting ready
How to do it…
Creating a backtrace under Linux
Capturing debug output with DebugView under Windows
How it works…
There's more…
See also
Reporting bugs
Getting ready
How to do it…
How it works…
There's more…
See also
Index

QGIS 2 Cookbook

QGIS 2 Cookbook

Copyright © 2016 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 authors, 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: April 2016

Production reference: 1250416

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78398-496-1

www.packtpub.com

Credits

Authors

Alex Mandel

Víctor Olaya Ferrero

Anita Graser

Alexander Bruy

Reviewers

Jorge Arévalo

Olivier Dalang

Ben Mearns

Commissioning Editor

Pramila Balan

Acquisition Editor

Vinay Argekar

Content Development Editor

Amey Varangaonkar

Merint Mathew

Technical Editor

Dhiraj Chandanshive

Copy Editor

Priyanka Ravi

Project Coordinator

Suzanne Coutinho

Proofreader

Safis Editing

Indexer

Rekha Nair

Production Coordinator

Aparna Bhagat

Cover Work

Aparna Bhagat

About the Authors

Alex Mandel is a geospatial scientist who has a PhD in geography and more than 12 years of experience in applying GIS to a variety of projects. He has also taught courses on GIS, geospatial programming, and Geoweb.

Víctor Olaya Ferrero is a GIS developer. He is the creator and main developer of the QGIS Processing Framework. He is also the author of Sistemas de Información Geográfica, a free book about the fundamentals of GIS.

I would like to thank my co-authors and everyone else in the QGIS community.

Anita Graser studied geomatics at the University of Applied Sciences Wiener Neustadt, Austria, from where she graduated with a master's degree in 2010. During her study, she gained hands-on experience in the fields of geo-marketing and transportation research. Since 2007, she has been working as a geographic information system (GIS) expert with the dynamic transportation systems group at the Austrian Institute of Technology (AIT), where she focuses on analyzing and visualizing spatio-temporal data.

Anita serves on the OSGeo board of directors and the QGIS project steering committee. She has been working with GIS since 2005, provides QGIS training courses, and writes a popular blog on open source GIS at anitagraser.com.

I would like to thank my family, partner, and coworkers for their support and encouragement. Of course, I also want to thank the whole QGIS community for their continued efforts to provide the best open source GIS experience possible.

Alexander Bruy is a GFOSS advocate and open source developer working on the QGIS project. He has also maintained a collection of his own open source projects. He has been working with QGIS since 2006, and now he is an OSGeo charter member and QGIS core developer. He is also the author of QGIS By Example, Packt Publishing.

Alexander is currently a freelance GIS developer and works for various companies worldwide.

About the Reviewers

Jorge Arévalo is a computer engineer from Universidad Autónoma de Madrid, UAM. He started developing web applications with JS, PHP, and Python in 2007. In 2010, he began collaborating with PostGIS and GDAL projects after participating in GSoC 2009, creating the PostGIS Raster GDAL driver. He currently works as a technology trainer and Python/Django developer. He also organizes hackathons with others at http://hackathonlovers.com/.

Jorge Arévalo has co-written the book Instant Zurb Foundation 4 for Packt Publishing. He has also worked as reviewer for the books PostGIS Cookbook, OpenLayers 3 Beginner's Guide, and Getting Started with Memcached, all of them for Packt Publishing.

I want to thank my wife Elena for her continuous love and support while reviewing this book.

Olivier Dalang completed his master's degree in architecture and urban planning from EPFL, Switzerland. He then worked as an urban planner at Team+ as a volunteer for the NGO urbaMonde, which is active in Senegal, and as a researcher and lecturer at EPFL on the Venice Time Machine project. He got more and more acquainted with QGIS through the different positions he worked in. Being a programmer, he developed a few plugins, of which a few are now in the core.

Ben Mearns lives in Philly, PA, where he consults, teaches, advises, speaks, and creates geographical information. In private practice, he has previously been the lead geospatial information consultant and instructor on GIS for natural resource management at the University of Delaware. He has held other GIS and data positions at the Cartographic Modeling Lab at the University of Pennsylvania, Princeton University, and Macalester College. He is currently writing QGIS Blueprints with Packt Publishing, which will soon be available in the market.

I would like to thank my girlfriend, Catherine Moore, and mother, Raiana Mearns, for their support during the review of this book.

www.PacktPub.com

eBooks, discount offers, and more

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

Preface

Location-based technology is the latest buzzword to explain tools related to spatial knowledge and analysis. For those who work on map making, geospatial science, or any number of other things with spatial data, Geographic Information Systems (GIS), which is the more traditional name for such tools, is a field of study with decades of innovation.

QGIS (previously known as Quantum GIS), a cross-platform, free, and open source software, provides a traditional desktop-based geographic information system. Unlike a traditional system though, it is highly customizable, extendable, and, by design, works in tandem with a ton of other GIS-related tools (more are added all the time).

QGIS is a crossing point of the free and open source geospatial world. While there are a great many tools in QGIS, it is not one massive application that does everything, and it was never really designed to be that from the beginning. It is rather a visual interface to much of the open source geospatial world. You can load data from proprietary and open formats into spatial databases of various flavors and then analyze the data with well-known analytical backends before creating a printed or web-based map to display and interact with your results. What's QGIS's role in all this? It's the place where you check your data along the way, build and queue the analysis, visualize the results, and develop cartographic end products.

If you need to test modify one layer before doing a batch of 1000, use QGIS. Want to make sure the results of that SQL query or script make sense, use QGIS. Need to tinker with alternative methods of displaying your data to find the right colors, lines, and layers to convey your message, use QGIS. Find something QGIS can't do, look at other tools it works with, search the plugin list, write a plugin, or submit a new feature request. With such a mentality, everything is possible—it just takes an understanding of how to get there.

This book is all about showing you how to do all these great things and all the new cool things you didn't know you wanted to do. When QGIS doesn't do what you need or doesn't work with the tools you want to use, we'll show you where to go and who to talk to about making your dream of new functionality a reality.

What this book covers

Over the course of 12 chapters, this book will take you from data input and output, through data management and analysis, to creating print and web output, as well as extending QGIS.

Chapter 1, Data Input and Output, covers loading and saving data with special instructions for trickier formats, batch conversions, and databases.

Chapter 2, Data Management, describes the basic manipulation of attributes, indexes, and queries to make the use of your data more efficient.

Chapter 3, Common Data Preprocessing Steps, deals with converting data into the formats you need for analysis, including vector to and from raster, transitioning through different types of vectors, and cutting your data to just the important areas.

Chapter 4, Data Exploration, explores methods for visualizing and understanding the information in your data.

Chapter 5, Classic Vector Analysis, shows the QGIS way of performing traditional analysis methods of vector layers.

Chapter 6, Network Analysis, dives into the methods for analyzing routes and networks.

Chapter 7, Raster Analysis I, covers raster analysis that is primarily related to topography and hydrology.

Chapter 8, Raster Analysis II, covers common raster analysis methods and introduces more advanced multispectral and classification data handling.

Chapter 9, QGIS and the Web, explores the use of live data from the Web and how to put up your own web map based on a QGIS project.

Chapter 10, Cartography Tips, reveals advanced tips and tricks to get the most out of the cartographic tools in QGIS.

Chapter 11, Extending QGIS, shows you how to take QGIS beyond the out-of-the-box features with plugins, customization, and add-on tools.

Chapter 12, Up and Coming, hints at the future with cutting-edge plugins and how to participate in the future development of QGIS.

What you need for this book

We recommend installing QGIS 2.8 or later; you will need at least QGIS 2.4. During the writing of this book, several new versions were released, approximately every 4 months, and most recently, 2.14 was released. Most of the recipes will work on older versions, but some may require 2.6 or newer. In general, if you can, upgrade to the latest stable release or Long Term Support (LTS) version.

There are also a lot of side interactions with other software throughout many of these recipes, including—but not limited to—Postgis 2+, GRASS 6.4+, SAGA 2.0.8+, and Spatialite 4+. On Windows, most of these can be installed using OSGeo4W; on Mac, you may need some additional frameworks from Kyngchaos, or if you're familiar with Brew, you can use the OSGeo4Mac Tap. For Linux users, in particular Ubuntu and Debian, refer to the UbuntuGIS PPA and the DebianGIS blend.

Does all of this sound a little too complicated? If yes, then consider using a virtual machine that runs OSGeo-Live (http://live.osgeo.org). All the software is preinstalled for you and is known to work together.

Lastly, you will need data. For the most part, we've provided a lot of free and open data from a variety of sources, including the OSGeo Educational dataset (North Carolina), Natural Earth Data, OpenFlights, Wake County, City of Davis, and Armed Conflict Location & Event Data Project (ACLED). A full list of our data sources is provided here if you would like additional data.

We recommend that you try methods with the sample data first, only because we tested it. Feel free to try using your own data to test many of the recipes; however, just remember that you might need to alter the structure to make it work. After all, that's what you'll be working with normally.

The following are the data sources for this book:

OSGeo Educational Data: http://grass.osgeo.org/download/sample-data/Wake County, USA: http://www.wakegov.com/gis/services/pages/data.aspxNatural Earth Data: http://www.naturalearthdata.com/City of Davis, USA: http://maps.cityofdavis.org/libraryStamen Designs: http://stamen.com/Armed Conflict Location & Event Data Project: http://www.acleddata.com/

Who this book is for

This book is for anyone who wants to do more with QGIS. It's aimed at an intermediate to advanced audience that already has some experience using GIS (any). The goal is to master the fundamentals of QGIS and launch you, the reader, to the next level of being a QGIS power user and community member.

Whatever your current level of experience with QGIS, you will find a lot of new ways to put your skills to good use. For those who are new to GIS, this book shows you many of the things that are possible with GIS. For those of you who are new to QGIS, this book is a guide on how to do the things you know from elsewhere with QGIS. For advanced users, this book is a reference and cheat sheet to the common tools you use often but can't quite remember how they work. And for all users, this book is filled with unknown and barely documented aspects of QGIS that you didn't think possible but likely want to use.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).

To give clear instructions on how to complete a recipe, we use these sections as follows:

Getting ready

This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Create a Spatialite database if you don't already have one and name it cookbook.db."

A block of code is set as follows:

geom,id,elevation LINESTRING(0 1, 0 2, 1 3),1,50 LINESTRING(0 -1, 0 -2, 1 -3),2,60 LINESTRING(0 1, 0 3, 5 4),3,70

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

geom,id,elevation LINESTRING(0 1, 0 2, 1 3),1,50 LINESTRING(0 -1, 0 -2, 1 -3),2,60 LINESTRING(0 1, 0 3, 5 4),3,70

Any command-line input or output is written as follows:

-gcp sourceX sourceY destinationX destinationY

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Check the Use visible raster layers checkbox or choose SELECT."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

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/QGIS2Cookbook_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Chapter 1. Data Input and Output

In this chapter, we will cover the following recipes:

Finding geospatial data on your computerDescribing data sourcesImporting data from text filesImporting KML/KMZ filesImporting DXF/DWG filesOpening a NetCDF fileSaving a vector layerSaving a raster layerReprojecting a layerBatch format conversionBatch reprojectionLoading vector layers into SpatiaLiteLoading vector layers into PostGIS

Introduction

If you want to work with QGIS, the first thing you need is spatial data. Whether you want to prepare a nice-looking map layout or perform spatial analysis, you need to open some data to work with. This chapter deals with the basic input and output commands, which will allow you to use data in several different formats and also export to the most convenient format in case you want to use it in different applications or share with others.

Automation is possible for many of the operations that you will see in this cookbook. This chapter contains some recipes that use automation to process a set of input files.

Finding geospatial data on your computer

This recipe shows you how to use the QGIS browser to locate and open spatial data.

Getting ready

Before you start working, make sure that you have copied the sample dataset to your filesystem and you have it located.

How to do it…

There are several ways of locating and opening a data file to open it in QGIS, but the most convenient of these is the QGIS browser:

To enable this, go to the View | Panels menu and enable the Browser checkbox in it. The browser will be shown by default in the left-hand side of the QGIS window, as shown in the following screenshot:

Browser contains a tree with all the available sources of spatial data. This includes data files in your filesystem, databases, and remote services.

Navigate to the folder where you copied the sample dataset, and you will see a list of available data files, as shown in the following screenshot:

Note

Not all files are shown but just the ones that are identified as valid data sources.

To add a file to your project, just right-click on it and select Add Layer:Multiple selections are allowed. In that case, select the Add selected layer menu.

Another way of opening a file is by just dragging it and dropping it into the QGIS canvas. Dragging multiple files is allowed, as well, as shown in the following screenshot:

How it works…

The browser acts as a file explorer that is directly linked to QGIS, which only shows valid data files and can be used to easily add them to a QGIS project.

There's more…

There are a few more things that you need to know that are related to this recipe. They are explained in the following sections.

Adding layers with the Layer menu

As an alternative to the browser, the Layer menu contains a set of entries. Each of them deals with a different type of data. They give you some additional options, and they might allow you to work with formats that are not directly supported by the browser.

Adding a folder to Favorites

Navigating to the folder where your data is located can be tedious. If you use a given folder regularly, you can right-click on it and select Add as favorite. The folder will appear on the Favorites section at the top of the browser tree.

Nonfile data sources

The browser also shows non-file data, such as remote services. Services have to be defined before they appear on the corresponding section in the browser. To add a service, right-click on the service name and select New connection.... A dialog will appear to define the service connection parameters.

As an example, try adding the following WMS service, using the WMS entry in the browser, as shown in the following screenshot:

A new entry will appear, containing the layers offered by the service, as shown in the following screenshot:

Describing data sources

You can get additional information about a data file before opening it. This recipe shows you how to explore the properties of a data origin.

Getting ready

Before you start working, make sure that you have copied the sample dataset to your filesystem and that you have it located.

How to do it…

In the QGIS browser, navigate to the folder with your sample dataset. Select the elev_lid792_1m file and right-click on it. In the context menu, select Properties. A dialog like the one in the following screenshot will appear:

This dialog displays the properties of a raster layer.

Now, let's select a vector layer instead. Select the elev_lid792_randpts.shp file, right-click on it, and select Properties. The information dialog will look like the following:

How it works…

In the upper part of the description window, you will see a field named Provider. Provider defines the type or data origin and who takes care of reading the data and passing it to QGIS. For raster layers, you will see gdal as Provider. For most file-based vector layers, ogr will be the provider that will appear. They refer to the GDAL and OGR libraries, two open-source libraries that are used by many GIS programs to access both raster and vector data.

There's more…

If the data is already loaded in QGIS, you can access the information about it in the Properties section of the layer (right-click on the layer name to select the Properties entry in the context menu). In the sections displayed in the left-hand side, select the Metadata section. You will see a box containing all the information corresponding to the layer data origin:

Functionality provided by the GDAL library, which (mentioned earlier) acts as a provider for raster layers, is also available in the Raster menu. This includes processing and data analysis methods, but it also includes the information tool that is used to describe a raster data source. You will find it by navigating to Raster | Miscellaneous | Info:

See also

This is a more complex way to retrieve properties as you can call the tool by adjusting the parameters with more details to get additional information. To know more, check the gdalinfo help page at http://www.gdal.org/gdalinfo.html.

Importing data from text files

Data can be imported from text files, providing some additional about how the geometry information is stored in the text. This recipe shows you how to create a new points layer, based on a text file.

How to do it…

Select the Add delimited text layer menu entry from the Layer menu. You will see a dialog like the following one:In the upper field, enter the path to the elev_lid792_randpts.csv file in the sample dataset. That file contains a points layer as text.Once you enter the file path or select it in the file browser that can be opened by clicking on the Browse button, the fields in the lower part of the dialog will be filled, as shown in the following screenshot:

Note

We are using a CSV file that has values separated by commas, so you must select the CSV option in the Format field.

The X field and Y field drop-down lists will be populated with the fields that are available, which are described in the first line of the text file. Select X for X field and Y for Y field. Now, QGIS knows how to create the geometries and has enough information to create a new layer from the text file.

Enter a name for the layer in the Layer name field and click on OK. The layer will be added to the QGIS project, as shown in the following screenshot:No information about the CRS is contained in the text file or entered in the parameters dialog, so it must be added manually. In this case, the CRS used is EPSG:3358. To set this as the CRS of the layer, right-click on the layer name and select Set layer CRS:In the CRS selection dialog, select the EPSG:3358 CRS and click on OK. The layer now has the correct CRS.

How it works…

Data is read from the text file and processed to create geometries. All the fields in the table (all data in a row in the text file) are also added, including the ones used to create the geometries, as you will see by right-clicking on the layer and selecting Open attribute table, as shown in the following screenshot:

Along with the CSV file, this file may contains a CSVT file, which describes the types of the fields. This is used by QGIS to set the appropriate type for the attributes table of the layer. If the CSVT file is missing, as in our example's case, QGIS will try to figure out the type based on the values for each field.

There's more…

Layers created from text files are not restricted to point files. Any geometry can be created from the text data. However, if it is not a point, instead of selecting two columns, you must place all the geometry information in a single one and enter a text representation of the geometry. QGIS uses the Well-Known Text (WKT) format, which is a text markup language for vector geometries, to describe geometries as strings. Here is an example of a very simple CSV file with line features and two attributes:

geom,id,elevation LINESTRING(0 1, 0 2, 1 3),1,50 LINESTRING(0 -1, 0 -2, 1 -3),2,60 LINESTRING(0 1, 0 3, 5 4),3,70

See also

To know more about the WKT format, you can go to http://en.wikipedia.org/wiki/Well-known_text

Importing KML/KMZ files

KML and KMZ files are used and produced by Google Earth and are a popular format. This recipe shows you how to open them with QGIS.

How to do it…

To open a KML layer, select Layer/Add vector layer.... In the dialog that opens, click on the Browse button to open the file selector dialog. Select the Keyhole Markup Language (KML) format and then select the file that you want to load. In the example dataset, you can find several KML files. Select the elcontour1m.kml file. Click on OK in the vector layer selector dialog, and the layer will be added to your project, as shown in the following screenshot:

Note

KMZ files can also be opened in QGIS.

Go to Layer | Add vector layer.... In the dialog that opens, click on the Browse button to open the file selector dialog. Select the All files option to view all the files and then select the elcontour1m.kmz file. There is not a KMZ file type defined in QGIS, but QGIS supports it because the underlying OGR library can read KMZ files as well.Click on OK on the open layer dialog to open the selected layer.

From the layers contained in the KMZ file, you must select one of them. In this case, only a layer is contained in the elcontour1m.kmz file, so it is loaded automatically. The layer will be added to your QGIS project.

How it works…

KMZ files are compressed files that contain a set of layers. When you select it, the OGR library will unzip the content of this file and then open the layers that it contains.

If just a single layer is contained, you will not see the layer selection dialog. QGIS will automatically open the only layer in the KMZ file.

There's more…

As KMZ is not recognized as a supported format, the KMZ file will not appear in the QGIS browser. However, the browser supports zipped files, and a KMZ file is actually a zipped file with KML files inside it. Unzip it in a folder and then you will be able to use the QGIS Browser to open the layers it contains.

Importing DXF/DWG files

CAD files, such as DXF and DWG files, can be opened with QGIS. This recipe shows you how to do this.

How to do it…

To open a DXF layer, select Add vector layer... in the Layer menu. In the dialog that opens, click on the Browse button to open the file selector dialog. Select the Autocad DXF format and then the file that you want to load.In the example dataset, you can find several DXF files. Select the Wake_ApproxContour_100.dxf file. Click on OK in the vector layer selector dialog and the layer will be added to your project, as shown in the following screenshot:

How it works…

DXF files are read as normal vector layers although they do not have the same structure as a regular vector layer as they do not allow adding arbitrary attributes to each geometry.

There's more…

The example DXF file that you opened contained just one type of geometry. DXF files can, however, contain several of them: in this case, they cannot be added to QGIS in one layer. When this happens, QGIS will ask you to select the type of geometry that you want to open.

In the sample dataset, you will find a file named CSS-SITE-CIV.dxf. Open it and you will see the following dialog:

Select one of the available geometries, and a layer will be added to your QGIS project.

Opening DWG files

DWG is a closed format of Autodesk. This means that the specification of the format is not available. For this reason, QGIS, like other open source applications, does not support DWG files. To open a DWG file in QGIS, you need to convert it. Converting it to a DXF file is a good option as this will let you open your file in QGIS without any problem. There are many tools to do this. The Teigha converter can be found at http://opendesign.com/guestfiles/TeighaFileConverter and is a popular and reliable option.

Another option is using the free service offered by Autodesk, called Autocad 360, which can be found at https://www.autocad360.com/.

Opening a NetCDF file

The NetCDF data is a data format, which is designed to be used with array-oriented scientific data, and it is frequently used for climate or ocean data, among others. This recipe shows you how to open a NetCDF file in QGIS.

How to do it…

NetCDF files are raster files, and they can be opened using the Add raster layer menu. Select NGMT NetCDF Grid for CDF as the file format in the file selection dialog that you will see, and select the rx5dayETCCDI_yr_MIROC5_rcp45_r2i1p1_2006-2100.nc file from the example dataset. Click on OK.

How it works…

The proposed NetCDF file contains a single variable, which is opened as a regular raster layer.

There's more…

A NetCDF file can contain contain multiple layers. In this case, QGIS will prompt you to select the one that you want to add from the ones contained in the specified file.

When only one layer is available, it is opened directly, as in the previously described example.

The NetCDF Browser plugin

Another way of opening NetCDF files is using the NetCDF Browser plugin. Select the Manage and install plugins... menu to open the plugin manager. Go to the Not installed section and type netcdf in the search field to filter the list of available plugins. Select the NetCDF Browser plugin and click on Install plugin to install it. Close the plugin manager.

The plugin is now installed, and you can open it by selecting NetCDF Browser in the Plugins menu:

Select the NetCDF file in the upper field. The other fields will be updated with the content of the selected file. Select a layer from the available ones and click on Add to add the layer to your QGIS project.

Saving a vector layer

QGIS supports multiple formats, not just to read vector layers but to also save them. This recipe shows you how to export a vector layer, converting it to a different format.

Getting ready

You will use the layer named poi_names_wake.shp in this recipe. Make sure that it is loaded in your QGIS project.

How to do it…

Right-click on the name of the points layer in the QGIS table of contents and select the Save as...