Learning QGIS
Learning QGIS
Anita Graser
BIRMINGHAM - MUMBAI
Learning QGIS 2.0
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.
ISBN 978-1-78216-748-8
www.packtpub.com
Reviewers Proofreader
Werner Macho Paul Hindle
Nathan Woodrow
Indexer
Acquisition Editor Priya Subramani
Kevin Colaco
Graphics
Commissioning Editor Ronak Dhruv
Sharvari Tawde
Production Coordinator
Technical Editor Manu Joseph
Sonali S. Vernekar
Cover Work
Copy Editors Manu Joseph
Aditya Nair
Alfida Paiva
Laxmi Subramanian
About the Author
Anita Graser studied at FH Wr. Neustadt, Austria, where she graduated with a
Master’s degree in Geomatics in 2010. During her studies, she acquired hands-on
experience in the fields of geomarketing and transportation research. Since 2007,
Anita has been working as a geographic information systems (GIS) expert with
the Dynamic Transportation Systems group at the Austrian Institute of Technology,
where she focuses on analyzing and visualizing spatio-temporal data and research
project management. Anita is an OSGeo Charter member and QGIS team member.
She has been working with GIS since 2005, and is writing a popular blog on open
source GIS at anitagraser.com.
Werner Macho completed his Master’s degree at the University of Natural Resources
and Life Sciences, Vienna, Austria. There he spent a long period of time as a scientist
working on a range of topics. Currently, he is completing his second Master’s degree
in GIS Science at the University of Salzburg, Austria, while working at linfiniti.com in
Swellendam, South Africa. Werner has been working with QGIS since 2007, when he
searched for an open source GIS tool to aid in his work on floodwater protection plans.
In the QGIS Project, he holds the position of Translation Team Leader, managing the
translation of more than 45 languages. Werner also banned proprietary stuff from his
computer in 1995, and he strongly believes in the power of coding open source and
the GPL.
Nathan currently works for Digital Mapping Solutions (DMS) Australia, as a Technical
Consultant and QGIS Specialist. At DMS Nathan provides support, training, custom
development, and bug fixing for QGIS.
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.
http://PacktLib.PacktPub.com
Why Subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print and bookmark content
• On demand and accessible via web browser
[ ii ]
Preface
Welcome to Learning QGIS 2.0. This book aims to introduce you to QGIS 2 and how to
perform core geospatial tasks using this popular open source GIS. It takes you through
five chapters, from QGIS installation and setup in the first chapter, to the essentials of
viewing spatial data in the second chapter. The third chapter covers data creation and
editing, followed by the fourth chapter, which offers an introduction to performing
spatial analysis in QGIS. In the final chapter, you will learn how to create great maps
and how to prepare them for print.
Chapter 2, Viewing Spatial Data, covers how to view spatial data from different data
sources. QGIS supports many file and database formats as well as OGC web services.
We will first see how we can load layers from these different data sources. Then, we
will look into the basics of styling both vector and raster layers and will create our
first map. We will finish this chapter with an example for loading background maps
from online services.
Chapter 3, Data Creation and Editing, covers the creation of new vector layers. Then,
we will cover how to select features and take measurements before we continue with
editing feature geometries and attributes. We will then reproject vector and raster
data and learn how to convert between different file formats before we end this
chapter with joining data from text files and spreadsheets to our spatial data.
Preface
Chapter 4, Spatial Analysis, covers raster processing and analysis tasks such as clipping
and terrain analysis. Then, we cover converting between raster and vector formats
before we continue with common vector geoprocessing tasks such as generating
heatmaps and calculating area shares within a region. Finally, we will finish the
chapter with an exercise in automating a geoprocessing workflow using the QGIS
Processing modeler.
Chapter 5, Creating Great Maps, covers important features that enable us to create
great maps. We will go into advanced vector styling, building on what we learned
in Chapter 2, Viewing Spatial Data. Then, we will cover labeling using examples of
labeling point locations as well as creating more advanced road labels with road
shield graphics. We will also cover how to tweak labels manually. Finally, we will
get to know the print composer and how to use it to create printable maps and
map books.
Conventions
In this book, you will find a number of styles of text that distinguish between
different kinds of information. Here are some examples of these styles, and an
explanation of their meaning.
Code words in text are shown as follows: "use [% $now %] to insert the current
time stamp."
[2]
Preface
New terms and important words are shown in bold. Words that you see on the
screen, in menus or dialog boxes for example, appear in the text like this: "clicking
the Next button moves you to the next screen".
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.
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.
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 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 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.
[3]
Preface
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.
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.
[4]
Getting Started with QGIS
In this chapter, we will install and configure the QGIS geographic information
system. We will also get to know the user interface and how to customize it. By the
end of this chapter, you will have QGIS running on your machine and be ready to
start with the tutorials.
Installing QGIS
QGIS runs on Windows, various Linux distributions, Unix, Mac OS X, and Android.
Also, the QGIS Project provides ready-to-use packages as well as instructions for
building from source code on download.qgis.org. We will cover how to install
QGIS on the two most common systems, Windows and Ubuntu, as well as how
to avoid the most common pitfalls.
Like many other open source projects, QGIS offers you a choice between a stable
release version and the cutting-edge developer version, also called master. QGIS
master will contain the latest and greatest developments, but be warned that on
some days, it might not work as reliably as you are used to. For the tutorials in
this book, we will be using the QGIS 2.0 release.
Getting Started with QGIS
Installing on Windows
On Windows, we have two different options to install QGIS: standalone
installer and OSGeo4W installer. The standalone installer is one big download
(approximately of 130 MB), which contains a QGIS release and the Geographic
Resources Analysis Support System (GRASS) GIS in one package. The OSGeo4W
installer is a small, flexible installation tool that makes it possible to download and
install QGIS and many more OSGeo tools with all their dependencies. The main
advantage of this over the standalone installer is that it makes updating QGIS and
its dependencies very easy. You can always have access to both the current release
and the developer version, if you chose so, but of course, you are never forced to
update. That's why I recommend using OSGeo4W. The OSGeo4W installer can be
downloaded from osgeo4w.osgeo.org (or directly from download.osgeo.org/
osgeo4w/osgeo4w-setup.exe). Download it and keep it! In the future, whenever
you want to change or update your system, just run it again.
When the OSGeo4W installer starts, we get to choose between the Express Desktop,
Express Web-GIS, and Advanced installation. To install the QGIS release version,
we can simply select the Express Desktop option and the next dialog will list the
available desktop applications such as QGIS, uDig, and GRASS GIS. We simply
select QGIS, click on Next and download and installation will start automatically.
When the installation has finished, there will be desktop shortcuts and start menu
entries for OSGeo4W and QGIS.
[6]
Chapter 1
If you try to run QGIS and get a pop up saying The procedure entry point <some-
name> could not be located in the dynamic link library <dll-name>.dll, you are
facing a common issue on Windows systems: a DLL conflict. They are easy to fix;
just copy the DLL file mentioned in the error message from C:\OSGeo4W\bin\ to
C:\OSGeo4W\apps\qgis\bin\ (adjust paths if necessary).
[7]
Getting Started with QGIS
Installing on Ubuntu
On Ubuntu, the QGIS project provides packages for both the release and
developer version. Be aware, though, that you can only install one version at
a time. The packages are not listed in the default Ubuntu repositories. Therefore,
we have to add the appropriate repositories to Ubuntu's sources list, which you
can find in /etc/apt/sources.list. You can open the file with any text editor.
Make sure that you have super user rights, as you need them to save your edits.
One option is to use gedit, which is installed on Ubuntu by default. To edit the
sources.list file, use the following command:
Make sure to add only one of the following four package source options to avoid
conflicts due to incompatible packages. The specific lines you have to add to the
source list depend on your Ubuntu version.
The first and default option is to install the current release version. To install the
QGIS release on Precise Penguin, add the following lines to your file:
deb http://qgis.org/debian precise main
deb-src http://qgis.org/debian precise main
If necessary, replace precise with raring, oneiric, natty, or lucid to fit your
system. For an updated list of supported Ubuntu versions, check download.qgis.org.
The second option is to install the QGIS master, which is currently available for
precise, quantal, and raring. Add the following lines to your file:
Therefore, the third option is to install the QGIS release version with updated
dependencies, which are provided by the ubuntugis repository. Add the following
lines to your file:
[8]
Chapter 1
deb http://ppa.launchpad.net/ubuntugis/ubuntugis-unstable/ubuntu
precise main
deb-src http://ppa.launchpad.net/ubuntugis/ubuntugis-unstable/ubuntu
precise main
The fourth option is QGIS master with updated dependencies. Add the following
lines to your file:
deb http://qgis.org/ubuntugis-nightly precise main
deb-src http://qgis.org/ubuntugis-nightly precise main
deb http://ppa.launchpad.net/ubuntugis/ubuntugis-unstable/ubuntu
precise main
After choosing the repository, we add the qgis.org repository public key to our
apt keyring. This will avoid warnings you might otherwise get when installing
from a non-default repository. Run the following command in the terminal:
gpg --keyserver keyserver.ubuntu.com --recv 997D3880
gpg --export --armor 997D3880 | sudo apt-key add –
The key information might have changed since this book went into
print. Please refer to hub.qgis.org/projects/quantum-gis/
wiki/Download#26-Ubuntu for the latest updates.
[9]
Getting Started with QGIS
[ 10 ]
Chapter 1
To make it easier to find specific plugins, we can filter the list of plugins using the
Search input field at the top of the window, which you can see in the following
screenshot:
Next, there are multiple toolbars to explore. If you arranged them as shown in
the previous section, you'll find the following toolbars in the top row:
• File: This toolbar contains tools to create, open, save, and print projects
• Manage Layers: This toolbar contains tools to add layers from vector or
raster files, databases, web services, text files, or create new layers
[ 11 ]
Getting Started with QGIS
The following screenshot shows what the preceding toolbars look like:
The following screenshot shows what the preceding toolbars look like:
• Plugins: This is currently empty, but will be filled by additional Python plugins
• Raster: This toolbar includes histogram stretch, brightness, and
contrast control
The following screenshot shows what the preceding toolbars look like:
• Digitizing: These tools enable editing, basic feature creation, and editing
• Advanced Digitizing: This toolbar contains undo/redo, advanced editing
tools, geometry simplification, and so on
The following screenshot shows what the preceding toolbars look like:
[ 12 ]
Chapter 1
Toolbars and panels can be activated and deactivated via the View menu's Panels
and Toolbars entries as well as by right-clicking on a menu or toolbar, which opens
a context menu with all available toolbars and panels. All toolbar tools can also be
accessed via the menu. If you deactivate the Manage Layers toolbar, for example,
you will still be able to add layers using the Layer menu.
[ 13 ]
Getting Started with QGIS
Summary
In this chapter, we installed QGIS and configured it by selecting useful defaults and
arranging the user interface elements. Finally, we explored the panels, toolbars, and
menus that make up the QGIS user interface, and learned how to customize them to
increase productivity.
[ 14 ]
Viewing Spatial Data
In this chapter, we will cover how to view spatial data from different data sources.
QGIS supports many file and database formats as well as OGC Web Services. We
will first see how we can load layers from these different data sources. We will then
look into the basics of styling both vector and raster layers and will create our first
map, which you can see in the following screenshot. We will finish this chapter with
an example for loading background maps from online services.
Viewing Spatial Data
We can load vector files using the menu entry by going to Layer | Add vector
layer and also by using the Add vector layer toolbar button. If you like shortcuts,
use Ctrl + Shift + V. In the Add vector layer dialog, we find a drop-down list that
allows us to specify the encoding of the input file. This option is important if we
are dealing with files that contain special characters, such as German umlauts or
letters from alphabets other than the default Latin one. The following screenshot
shows the Add vector layer dialog:
What we are most interested in now is the Browse button, which opens the file-
opening dialog. Note the file type filter drop-down list on the bottom-right corner of
the dialog. We can open it to see a list of the supported vector file types. This filter is
useful to find specific files faster by hiding all files of a different type, but be aware that
the filter settings are stored and will be applied again the next time we open the dialog.
[ 16 ]
Chapter 2
This can be a source of confusion if we later try to find a different file and it happens
to be hidden by the filter, so remember to check the filter settings if you are having
trouble locating a file.
We can load more than one file in one go by selecting multiple files at once (holding
down Ctrl on Windows/Ubuntu or Cmd on Mac). Let's give it a try.
There are multiple tricks that make loading data even faster; for
example, you can simply drag and drop files from the operating
system file browser into QGIS. Another way to quickly access your
spatial data is by using QGIS' built-in file browser. If you set up
QGIS as shown in Chapter 1, Getting Started with QGIS, you'll find
the browser on the left-hand side, just below the layer list. Navigate
to your data folder and you can again drag and drop files from the
browser to the map. Additionally, you can mark a folder as favorite
by right-clicking on the folder and selecting Add to favorites. This
way, your data folders will be even faster to access because they are
added in the Favorites section right at the top of the browser list.
Another popular source of spatial data are delimited text (CSV) files. QGIS can load
CSV files using the Add Delimited Text Layer option available via the menu entry
by going to Layers | Add Delimited Text Layer or the corresponding toolbar button.
Click on Browse and select elevp.csv from the sample data. CSVs come with all kinds
of delimiters. As you can see in the following screenshot, the plugin lets you choose
from the most common ones (Comma, Tab, and so on), but you can also specify any
other plain or regular expression delimiter. If your CSV contains quotation marks such
as " or ', you can use the Quote option to have them removed. The Number of header
lines to discard option allows us to skip extra lines at the beginning of the text file.
The following Field options include functionality to trim extra spaces from field
values or to redefine the decimal separator to a comma. The spatial information itself
can be provided either in two columns containing coordinates of points X and Y or
by using the Well known text (WKT) format. A WKT field can contain points, lines,
or polygons.
[ 17 ]
Viewing Spatial Data
After clicking on OK, QGIS will prompt us to specify the layer's coordinate reference
system (CRS). We will talk about handling coordinate reference systems next.
[ 18 ]
Chapter 2
The QGIS Coordinate Reference System Selector offers a filter that makes finding
the CRS easier. It can filter by name or by ID (for example, the EPSG code). Just start
typing and watch how the list of potential CRSs gets shorter. There are actually two
separate lists: the upper one contains the CRSs we have recently used while the
lower list is much longer and contains all available CRSs. For the elevp.csv file,
we select NAD27 / Alaska Albers.
If we want to check a layer's CRS, we can find this information in the layer
properties' General section, which can be accessed by going to Layer | Properties or
by double-clicking on the layer name in the layer list. If you think that QGIS picked
the wrong CRS or you made a mistake specifying the CRS, you can correct the CRS
settings using Specify CRS. Note that this does not change the underlying data or
reproject it. We'll talk about reprojecting vectors and raster files in Chapter 3, Data
Creation and Editing.
In QGIS, we can create a map out of multiple layers even if each dataset is stored
with a different CRS. QGIS handles the necessary reprojections automatically by
enabling a mechanism called on-the-fly reprojection, which can be accessed by
going to Settings | Project Properties as you can see in the following screenshot:
[ 19 ]
Viewing Spatial Data
All layers are reprojected to the project CRS on the fly, which means that QGIS
calculates these reprojections dynamically and only for the purpose of rendering
the map. The underlying data is not changed and spatial analyses are not affected.
In some cases, you might have to specify a CRS that is not available in QGIS' CRS
database. You can add CRS definitions by going to Settings | Custom CRS. Click on
the Add new CRS button to create a new entry, type in a name for the new CRS, and
paste the proj4 definition string. Just close the dialog by clicking on OK when you
are done.
[ 20 ]
Chapter 2
Let's give it a try and load landcover.img from the sample data raster folder.
Similarly, just like vector files, you can load rasters by dragging them into QGIS
from the operating system or the built-in file browser.
• We can create a world file for a raster file without altering the original raster.
• If we have a map image that contains points with known coordinates, we can
set ground control points (GCPs) and enter the known coordinates.
• Finally, if we don't know the coordinates of any points on the map, we still
have the chance to place GCPs manually using a second, already georeferenced
map of the same area. We can use objects that are visible in both maps to pick
points in the map that we want to georeference and work out their coordinates
from the reference map.
After loading a raster into Georeferencer by going to File | Open raster or using the
Open raster toolbar button, we are asked to specify the CRS of the ground control
points we are planning to add. Next, we can start adding ground control points by
going to Edit | Add point. We can use the pan and zoom tools to navigate and we can
place GCPs by clicking on the map. We are then prompted to insert the coordinates of
the new point or pick them from the reference map in the main QGIS window.
After placing the GCPs, we can define the transformation algorithm by going
to Settings | Transformation Settings. Which algorithm you choose depends
on your input data and the level of geometric distortion you want to allow. The
most commonly used algorithms are polynomial 1 to 3. A first-order polynomial
transformation allows scaling, translation, and rotation only.
[ 21 ]
Viewing Spatial Data
The resampling method depends on your input data and the result you want to
achieve. Cubic resampling creates smooth results, but if you don't want to change
the raster values, choose the nearest neighbor method.
Before we can start the georeferencing process, we still have to specify the output
file name and target CRS. Make sure that the Load in QGIS when done option is
active. Then, we can close the Transformation Settings dialog and go to File | Start
Georeferencing. The georeferenced raster will automatically be loaded into the
QGIS main map window.
[ 22 ]
Chapter 2
Like with files, you can select one or more tables from the list and click on Add to
load them into the map. Additionally, you can use Set Filter to load only specific
features.
PostGIS is the spatial extension for the PostgreSQL database system. Installing and
configuring the database is out of the scope of this book, but there are installers for
Windows and packages for many Linux distributions as well as for Mac. To load
data from a PostGIS database, go to Layers | Add PostGIS Layer, use the Add
PostGIS Layer toolbar button, or press Ctrl + Shift + D.
[ 23 ]
Viewing Spatial Data
When using a database for the first time, click on New to establish a new database
connection. In the following dialog, you can specify a Name for the new connection.
Other fields that have to be filled are as follows:
• Host: The server's IP address is inserted in this field. You can use localhost
if PostGIS is running locally.
• Port: The PostGIS default port is 5432.
• Database: This is the name of the PostGIS database you want to connect to.
• Username and Password: For convenience, you can tell QGIS to save them.
The following screenshot shows the dialog to create a new connection to a database
called postgis:
[ 24 ]
Chapter 2
After the connection is established, you can load and filter tables just like we
discussed for SpatiaLite.
You can load WMS layers by going to Layer | Add WMS Layer, by clicking on the
Add WMS Layer button, or by pressing Ctrl + Shift + W. If you know a WMS server,
you can connect to it by clicking on New and filling in a name and the URL. All
other fields are optional. Don't worry if you don't know of any WMS server, because
we can simply click on Add default servers to get access information about servers
whose administrators collaborate with the QGIS project. One of these servers is
called Lizardtech server. Select it, or any of the other servers, from the drop-down
box and click on Connect to see the list of layers available through the server.
From the layer list, you can now select one or more layers for download. It is worth
noting that the order in which you select the layers does matter because the layers
will be combined on the server side, and QGIS will only receive the combined image
as the resultant layer. If you want to be able to use the layers separately, you have to
download them one by one. The data download starts once you click on Add. The
dialog will stay open so that you can add additional layers from the server.
Many WMS servers offer their layers in multiple different CRSs. You can check the
list of available CRSs by clicking on the Change button at the bottom of the dialog.
This will open a CRS selector dialog, which is limited to the WMS server's CRS
capabilities.
Loading data from WCS or WFS servers works in the same way, but public servers
are rare and unreliable, and therefore no recommendation can be provided here.
[ 25 ]
Viewing Spatial Data
Let's start by loading land cover and hillshade from landcover.img and SR_50M_
alaska_nad.tif and then opening the Style section in layer properties (Layer |
Properties or by double-clicking on the layer name). QGIS tries to pick a reasonable
default render type. The hillshade raster, SR_50M_alaska_nad.tif, is loaded with
the Singleband gray render type as you can see in the following screenshot. If we
want to render the hillshade raster in color instead of grayscale, we can change the
render type to Singleband pseudocolor. In pseudocolor mode, we can create color
maps either manually or by selecting one of the premade color ramps. But let's stick
with Singleband gray for hillshade for now.
Below the color settings, we find a section with more advanced options that control
raster resampling, brightness, contrast, saturation, and hue—options you probably
know from image processing software. By default, resampling is set to the fast
Nearest neighbour option. To get nice, smoother results, we can change to the
Bilinear or Cubic method.
Click on Ok or Apply to confirm. In both cases, the map will be redrawn using the
new layer style. If you click on Apply, the Layer Properties dialog stays open and
you can continue to fine-tune the layer style. If you click on Ok, the Layer Properties
dialog is closed.
[ 26 ]
Chapter 2
The landcover.img raster is a good example of a paletted raster. Each cell value
is mapped to a specific color. To change a color, we can simply double-click on the
Color preview and a color picker will open.
[ 27 ]
Viewing Spatial Data
The style section of a paletted raster looks like the following screenshot:
If we want to combine hillshade and land cover into one aesthetically pleasing
background, we can use a combination of the Blending mode and layer Transparency.
Blending modes are another feature commonly found in image-processing software.
The main advantage of blending modes over transparency is that we can avoid the
usually dull, low-contrast look that results from combining rasters using transparency
alone. If you haven't had any experience with blending, take some time to try the
different effects. For this example, I used the Darken blending mode, as highlighted
in the previous screenshot, together with a global layer transparency of 50 %, as shown
in the following screenshot:
[ 28 ]
Chapter 2
• Single Symbol: This is the simplest option. When we use a Single Symbol
style, all points are displayed with the same symbol.
• Categorized: This is the style of choice if a layer contains points of different
categories; for example, a layer containing locations of different animal
sightings.
• Graduated styles: These are great if we want to visualize numerical values;
for example, temperature measurements.
• Rule-based styles: These are the most advanced options. These styles are
very flexible because they allow us to write multiple rules for one layer.
• Point displacement styles: These are only available for point layers. These
styles are useful if you need to visualize point layers with multiple points
at the same coordinates; for example, students of a school living at the
same address.
[ 29 ]
Viewing Spatial Data
Below the drop-down list we find the symbol preview, and below that there is the
list of symbol layers, which shows us the different layers the symbol consists of.
On the right-hand side, we find options for the symbol size and size units, color
and transparency, as well as rotation. Using the Data defined properties button,
we can also tell QGIS to use the feature's attribute values to define symbol shape,
size, color, and so on. Finally, the bottom-right area contains a preview area with
saved symbols.
Point layers are by default displayed using a simple circle symbol. We want to use a
symbol of an airplane instead. To change the symbol, select the Simple marker entry
in Symbol layers. Notice how the right-hand side of the dialog changes. We can now
see the options available for simple markers: Colors, Size, Rotation, Form, and so
on. However, we are not looking for circles, stars, or square symbols—we want an
airplane. That's why we need to change the Symbol layer type option from Simple
marker to SVG marker. Many of the options are similar, but on the bottom we now
find a selection of SVG images that we can choose from. Scroll through the list and
pick the airplane symbol as shown in the following screenshot:
[ 30 ]
Chapter 2
To create such a style, we combine two simple lines. The default symbol is one
simple line. Click on the green + symbol located below the Symbol layers list to
add another simple line. The lower one will be our outline and the upper one will
be the fill. Select the upper simple line and change the color to blue and the width
to 0.3 millimeters. Next, select the lower simple line and change its color to gray and
the width to 0.6 millimeters, slightly wider than the other line. Check the preview
and click on Apply to test how the style looks when applied to the river layer.
You will notice that the style doesn't look perfect yet. That's because each line
feature is drawn separately, one after the other, and this leads to a rather disconnected
appearance. Luckily, that's easy to fix; we only need to enable the so-called symbol
levels. To do that, select the Line entry in the Symbol layers list and tick the checkbox
in the Symbol Levels dialog of the Advanced section (the button in the lower-right
corner of the style dialog) as shown in the following screenshot. Click on Apply to test
the results:
[ 31 ]
Viewing Spatial Data
[ 32 ]
Chapter 2
• Simple fill: These define fill and outline colors as well as basic fill styles
• Centroid fill: These allow us to put point markers at the center of polygons
• Line/Point pattern fill: These support user-defined line and point patterns
with flexible spacing
• SVG fill: These fill the polygon using SVG patterns
• Outline: These make it possible to outline areas using line styles
[ 33 ]
Viewing Spatial Data
To install the OpenLayers plugin, go to Plugins | Manage and Install Plugins | Get
more. Wait until the list of available plugins has finished loading. Use the filter to look
for the OpenLayers Plugin option as shown in the following screenshot. Select it from
the list and click on Install. This is going to take a moment. Once it's done, you will
see a short confirmation message. You can then close the installer and the OpenLayers
Plugin option should be available through the Plugins menu.
Note that you have to be online to use these services. Another fact worth mentioning
is that all these services provide their maps only in Pseudo Mercator (EPSG:3857).
Your project CRS will automatically be changed to Pseudo Mercator when you load
a background map using the OpenLayers plugin option.
[ 34 ]
Chapter 2
If you load the OSM Landscape layer, your map will look like the following screenshot:
Summary
In this chapter, we covered how to load spatial data from files, databases, and web
services. We saw how QGIS handles coordinate reference systems and had a first
introduction to styling vector and raster layers, a topic we will cover in more detail
in Chapter 5, Creating Great Maps. We also installed our first Python plugin, the
OpenLayers plugin, and used it to load background maps into our project.
[ 35 ]
Data Creation and Editing
In this chapter, we will first create some new vector layers and cover how to
select features and take measurements. We will then continue with editing feature
geometries and attributes. Then, we will reproject vector and raster data, and
before we end this chapter, learn how to convert between different file formats
with joining data from text files and spreadsheets to our spatial data.
Let's create a new Shapefile to see how it works. A new Shapefile layer, which can
be accessed by going to Layer | New or Ctrl + Shift + N, opens the New Vector Layer
dialog with options for different geometry types, CRS, and attributes. The process itself
is really fast because all mandatory fields already have default values. By default, it
will create a new point layer with WGS84 CRS (unless specified otherwise in Settings
| Options | CRS) and one integer field called id. We can simply click on OK, specify
a filename, and a new layer appears in the layer list.
Data Creation and Editing
Next, we also create one line and one polygon layer. We'll add some extra fields
to these layers. Besides integer fields, Shapefiles also support text and decimal
values. To add a field, we only need to insert a name, select a type and width, and
click on Add to attributes list. For decimal numbers, we also have to define the
Precision value, which determines the number of digits after the comma. A Width
value of 3 with a Precision value of 1 will allow a value range from -99.9 to + 99.9.
The following screenshot shows the New Vector Layer dialog and the Attributes...
window for my example polygon layer:
[ 38 ]
Chapter 3
All of the new layers are empty so far, but we will create some features now. If we
want to add features to a layer, we first have to enable editing for this layer. Editing
can be turned on and off by selecting Layer | Toggle editing, Toggle editing in
the layer name context menu, or with the Toggle editing button in the Digitizing
toolbar. Notice how the layer's icon in the layer list changes to reflect whether editing
is on or off. When we turn on editing for a layer, QGIS automatically enables the
digitizing tools suitable for the layer's geometry type.
Now, we can use the Add Feature tool in the editing toolbar to create new features.
To place a point, we simply click on the map. We are then prompted to fill out the
attribute form, and once we click on OK the new feature is created. Like with points,
we can create new lines and polygons by placing nodes onto the map. To finish a line
or a polygon, we simply right-click on the map. Create some features in each layer and
then save your changes. We can re-use these test layers in the upcoming exercises.
New features and feature edits are saved permanently only after
clicking on the Save Layer Edits button in the Digitizing toolbar
or once we finish editing and confirm that we want to save.
The first group of tools in the Attributes toolbar allows us to select features on the
map using the mouse, either one at a time or by drawing different shapes such as
rectangles or freehand areas around the features. All features that intersect with
the drawn shape are selected. Holding down Ctrl will add the new selection to an
existing one.
[ 39 ]
Data Creation and Editing
Similarly, holding down Ctrl + Shift will remove the new selection from the existing
selection. The following screenshot shows the tools:
The second type of select tool is called Select by Expression and it is also available
in the Attribute toolbar. It selects features based on expressions that can contain
references and functions using feature attributes and/or geometry. The list of available
functions is pretty long, but we can use the search box to filter the list by name to
find the function we are looking for faster. On the right-hand side of the window, we
find the Selected Function Help, which explains the functionality and how to use
the function in an expression. The Function List also shows the layer attribute fields,
and by clicking on Load all unique values or Load 10 sample values, we can easily
access their content. Like with the mouse tools, we can choose between creating a new
selection or adding to or deleting from an existing selection. Additionally, we can
choose to only select features from within an existing selection. Let's have a look at
some example expressions that you can build on and use in your own work:
• Using the lakes.shp file in our sample data, we can, for example, select
big lakes with an area bigger than 1,000 square miles using a simple attribute
query: "AREA_MI" > 1000.0, or by using geometry functions such as $area
> (1000.0 * 27878400). Note that the lakes.shp CRS uses feet and we
therefore have to multiply by 27,878,400 to convert from square feet to
square miles.
• We can also work with string functions, for example, to find lakes with long
names: length("NAMES") > 12, or lakes with names that contain an "s" or
"S": lower("NAMES") LIKE '%s%', which first converts the names to lower
case and then looks for any appearance of "s". The dialog will look like the
following screenshot:
[ 40 ]
Chapter 3
The third type of tool allows us to select features in one layer based on their location
relative to features in a second layer. These tools can be accessed by going to Vector
| Research Tools | Select by location and Vector | Spatial Query | Spatial Query.
Enable it in Plugin Manager if you cannot find it in the Vector menu. In general, we
want to use the Spatial Query plugin as it supports a variety of spatial operations such
as crosses, equals, intersects, is disjoint, overlaps, touches, and contains depending
on the layer geometry type.
[ 41 ]
Data Creation and Editing
Let's test the Spatial Query plugin using railroads.shp and pipelines.shp from
the sample data. For example, we might want to find all the railroad features that
cross a pipeline; we therefore select the railroads layer, the Crosses operation, and
the pipelines layer. After clicking on Apply, the plugin presents us the query results.
There is a list of IDs of the result features on the right-hand side of the window as
you can see in the following screenshot. Below this list, we can check the Zoom to
item checkbox, and QGIS will zoom to the feature that belongs to the selected ID.
Additionally, the plugin offers buttons to directly save all the resulting features to
a new layer.
[ 42 ]
Chapter 3
The basic Digitizing toolbar contains tools for creating and moving features and
nodes, as well as for deleting, copying, cutting, and pasting features, as follows:
• With the Move Feature(s) tool, it is easy to move one or more features at
once by dragging them to the new location.
• Similarly, the Node Tool feature allows us to move one or more nodes
of the same feature. The first click activates the feature, while the second
click selects the node. Hold the mouse key down to drag the node to its
new location. Instead of moving only one node, we can also move an edge
by clicking and dragging the line. And finally, we can select and move
multiple nodes by holding down Ctrl.
• Delete Selected, Cut Features, and Copy Features are only active if one
or more layer features are selected. Similarly, Paste Features only works
after a feature has been cut or copied.
The Advanced Digitizing toolbar offers very useful Undo and Redo functionalities
as well as additional tools for more involved geometry editing:
[ 43 ]
Data Creation and Editing
• The Offset Curve tool is only available for lines and allows us to displace
a line geometry by a given offset.
• Split Features allows us to cut one or more features along a cut line.
• Merge Selected Features enables us to merge multiple features while
keeping control over which feature's attributes will be available in the
output feature.
• Similarly, Merge Attributes of Selected Features lets us combine the
attributes of multiple features, but without merging them into one feature.
Instead, all original features remain as they were, but the attribute values
are updated.
• Finally, Rotate Point Symbols is only available for point layers with the
Rotation field feature enabled (which we will cover in Chapter 5, Creating
Great Maps).
[ 44 ]
Chapter 3
Editing attributes
There are three main use cases for attribute editing. First, we might want to edit
the attributes of one specific feature, for example, to fix a wrong name. Second,
we might want to edit attributes of a group of features. Or third, we might want
to change the attributes of all the features within a layer. All these use cases are
covered by functionality available through the attribute table. We can access it
by going to Layer | Open Attribute Table, the Open Attribute Table button
present in the Attributes toolbar, or in the layer name context menu.
To change attribute values, we always have to first enable editing. Then we can
double-click on any cell in the attribute table to activate the input mode. Clicking
on Enter confirms the change, but to save the new value permanently, we have to
also click on the Save Edit(s) button or press Ctrl + S. In the bottom-right corner
of the attribute table dialog, we can switch from the table to the form view, as
shown in the following screenshot, and start editing there.
[ 45 ]
Data Creation and Editing
[ 46 ]
Chapter 3
[ 47 ]
Data Creation and Editing
• If we want to get the start or end points of a line, we can use xat(0)
and yat(0) or xat(-1) and yat(-1)
[ 48 ]
Chapter 3
In QGIS, reprojecting a vector or raster layer is done by simply saving it with a new
CRS. We can save a layer using Layer | Save as ... or Save as … in the layer name
context menu. Pick a target file format and file name, and then click on the Browse
button besides the CRS field to pick a new CRS.
Besides changing the CRS, the main use case of the Save vector/raster layer dialog
is to convert between different file formats. For example, we can load a Shapefile
and export it as GeoJSON, Mapinfo MIF, CSV, and so on, or the other way around.
The Save raster layer dialog is also a convenient way to clip/crop rasters by a
bounding box, as we can specify which extent we want to save.
Similarly, for vector layers, there is Save selection as … in both the Layer menu and
the layer name context menu, which will open the same kind of dialog, but it will
only save the selected features.
[ 49 ]
Data Creation and Editing
QGIS will automatically recognize the names and data types of columns in an XLS
table. It's quite easy to tell because numeric values are right-aligned in the attribute
table as shown in the following screenshot:
[ 50 ]
Chapter 3
We can also load tabular data from delimited text files like we saw in Chapter 2,
Viewing Spatial Data, when we loaded a point layer from a delimited text file. To load a
delimited text file that only contains tabular data but no geometry information, we just
need to enable the No geometry (attribute table only) option.
After loading the tabular data from either the spreadsheet or text file, we can continue
to join this non-spatial data to a vector layer. To do that, we go to the vector Layer
Properties | Joins tab. There, we can add a new join by pressing the green plus button.
All we have to do is select the tabular Join layer and Join field fields (of the tabular
layer), which should contain values that match those in the Target field field (of the
vector layer). The page will look like the following screenshot.
The way joins work in QGIS is that the join layer's attributes are
appended to the original layer's attribute table. The number of
features in the original layer is not changed. Whenever there is
a match between the join and the target field, the attribute value
will be filled; otherwise you'll see NULL entries.
Once the join is added, we can see the extended attribute table and use the new
appended attributes for styling and labeling.
[ 51 ]
Data Creation and Editing
Summary
In this chapter, we covered how to create new layers from scratch. We used the tools
to create and edit feature geometries in different ways. Then, we went into editing
feature attributes of single features, feature selections, and whole layers. Next, we
reprojected both vector and raster layers and also learned how to convert between
different file formats. Finally, we finished this chapter on layer creation and editing
by covering tabular data, how it can be loaded into QGIS, and how to join it to our
spatial data.
In the following chapter, we will put our data to good use and learn how to perform
different kinds of spatial analysis on raster and vector data.
[ 52 ]
Spatial Analysis
In this chapter, we will start with raster processing and analysis tasks such as
clipping and terrain analysis. We will cover the essentials of converting between
raster and vector formats, and then continue with common vector geoprocessing
tasks such as generating heatmaps and calculating area shares within a region.
We will finish the chapter with an introduction to automating geoprocessing
workflows using the QGIS Processing modeler.
Clipping rasters
A common task in raster processing is clipping a raster with a polygon. This task
is well covered by the Clipper tool located in Raster | Extraction | Clipper. This
tool supports clipping to a specified extent or clipping using a polygon mask layer,
as follows:
For a quick exercise, we will clip the hillshade raster using the Alaska Shapefile
(both from our sample data) as a mask layer. At the bottom of the window, we can
see the concrete gdalwarp command that QGIS uses to clip the raster. This is very
useful if you also want to learn how to use GDAL.
Spatial Analysis
The default No data value is 0, but we can override it if necessary. Another good
option is to Create an output alpha band, which will set all areas outside the mask
to transparent, as shown in the following screenshot:
The resulting layer will be loaded automatically since we enabled the Load into
canvas when finished option. QGIS should also automatically recognize the alpha
layer we created, and the raster areas that fall outside the Alaska land mass should
be transparent. If, for some reason, QGIS fails to automatically recognize the alpha
layer, we can enable it manually using the Transparency band option in the raster
layer properties' Transparency section. This dialog is also the right place to specify
any No data value we want to be used, as shown in the following screenshot:
[ 54 ]
Chapter 4
[ 55 ]
Spatial Analysis
• Slope: This tool calculates the slope angle for each cell in degrees (based on
the first order derivative estimation)
• Aspect: This tool calculates the exposition (in degrees counter-clockwise,
starting with 0 for north)
• Hillshade: This tool creates a basic hillshade raster with lighted areas and
shadows
• Relief: This tool creates a shaded relief map with varying colors for different
elevation ranges
• Ruggedness Index: This tool calculates the ruggedness index for each cell by
summarizing the elevation changes within a 3 x 3 cell grid
Of course, to use any of these terrain analysis tools, we need an elevation raster.
If you don't have any at hand, you can simply download a dataset from the NASA
Shuttle Radar Topography Mission (SRTM) using http://dwtkns.com/srtm/
or any of the other SRTM download services.
An important element in all terrain analysis tools is the Z factor. The z factor is used
if the x/y units are different from the z (elevation) unit. For example, if we tried to
create a relief from elevation data where x/y are in degrees and z is in meters, the
resulting relief would look grossly exaggerated. The values for the z factor are
as follows:
• If x/y and z are either all in meters or all in feet, use the default z factor 1.0
• If x/y are in degrees and z is in feet, use the z factor 370,400
• If x/y are in degrees and z is in meters, use the z factor 111,120
Since the SRTM rasters are provided in WGS84 EPSG:4326, we need to use a Z factor
of 111120 in our exercise. Let's create a relief! The tool can calculate relief color ranges
automatically; we just need to click on Create automatically, as shown in the following
screenshot. Of course, we can still edit the elevation ranges' upper and lower bounds,
as well as the colors.
[ 56 ]
Chapter 4
While relief maps are three-banded rasters, which are primarily used for
visualization purposes, slope rasters are a common intermediate step in spatial
analysis workflows. We will now create a slope raster, which we can use in our
example workflow through the following sections. The resulting slope raster will
be loaded in grayscale automatically, as shown in the following screenshot:
[ 57 ]
Spatial Analysis
Raster calculator
By going to Raster | Raster Calculator, we can create a new raster layer based
on values in one or more rasters that are loaded in the current QGIS project. All
available raster bands are presented in a list in the top-left corner of the dialog in
the form raster_name@band_number as shown in the following screenshot.
Continuing from our previous exercise in which we created a slope raster, we can,
for example, find areas at elevations above 1,000 meters and with a slope of less
than 5 degrees using the following expression (you might have to adjust the values
depending on the dataset you are using):
srtm_05_01@1 > 1000 AND slope_05_01@1 < 5
Cells that meet both criteria of high elevation and evenness will be assigned a value
of 1 in the resulting raster, while cells that fail to meet a criterion will be set to 0. The
only bigger areas with a value of 1 are found in the southern part of the raster layer.
[ 58 ]
Chapter 4
Another typical use case is reclassifying a raster. For example, we could want to
reclassify the landcover raster in our sample data so that all areas with a landcover
class from 1 to 5 get the value 100, areas from 6 to 10 get 101, and areas over 11 get
a new value of 102. We will use the following code for this:
( landcover@1 > 0 AND landcover@1 <= 6 ) * 100
+ ( landcover@1 >= 7 AND landcover@1 <= 10 ) * 101
+ ( landcover@1 >= 11 ) * 102
The preceding raster calculator expression has three parts, consisting of a check and
a multiplication. For each cell, only one of the three checks can be true, and true is
represented as 1. Therefore, if a landcover cell has a value of 4, the first check will be
true and the expression evaluates to 1*100 + 0*101 + 0*102 = 100.
Polygonize converts a raster into a polygon layer; depending on the size of the raster,
the conversion can take some time. When the process is finished, QGIS will notify
us with a pop up. For a quick test, we can, for example, convert the reclassified
landcover raster to polygons. The resulting vector polygon layer contains multiple
polygon features with a single attribute we called lc, which depends on the original
raster value, as shown in the following screenshot:
[ 59 ]
Spatial Analysis
The Rasterize tool is very similar to the Polygonize tool. The only difference is that
we get to specify the size of the resulting raster in pixels/cells. We can also specify
the attribute field, which will provide input for the raster cell value. The cat attribute
of our alaska.shp dataset is rather meaningless, but you get the idea of how the tool
works, as shown in the following screenshot:
[ 60 ]
Chapter 4
In both the tools, we can easily copy the results using Ctrl + C and paste them into
a text file or spreadsheet. The following screenshots show examples exploring the
contents of our airport sample dataset:
[ 61 ]
Spatial Analysis
[ 62 ]
Chapter 4
Note that the preceding screenshot shows the advanced interface of the toolbox.
You can switch from the simplified interface to the advanced interface using the
drop-down button at the bottom of the toolbox. I prefer using the advanced version
as it exposes all available algorithms and clearly displays how individual tools are
related to the different components such as GDAL/OGR or GRASS.
[ 63 ]
Spatial Analysis
After buffering the airport point locations, the Select by location option selects
all the airport buffers that intersect a river. As a result, 14 out of the 76 airports
are selected. This information is displayed in the information area at the bottom
of the QGIS main window as shown in the following screenshot:
[ 64 ]
Chapter 4
If you ever forget which settings you used or need to check that you
used the correct input layer, you can go to Analysis | history and
log. The ALGORITHM section lists all the algorithms we have been
running as well as the used settings. This is also the right place to
look for error messages in the WARNING section, as shown in the
following screenshot:
The commands listed under ALGORITHM can also be used to call Processing tools
from the QGIS Python console by going to Plugins | Python Console. The Python
commands shown in the following screenshot run the buffer algorithm and load the
result into the map:
[ 65 ]
Spatial Analysis
For this exercise, let's imagine we want to sample the landcover layer at the airport
locations of our sample data. All we have to do is specify the vector layer containing
the sample points and the raster layer that should be sampled. For this example, we
can leave all other settings to their defaults. The tool will not only sample the raster,
it also compares point attributes with the sampled raster value, but we don't need
this comparison in our current example.
[ 66 ]
Chapter 4
[ 67 ]
Spatial Analysis
[ 68 ]
Chapter 4
[ 69 ]
Spatial Analysis
Next, we calculate the size of the strip of land around our river. This can be done using
the Export/Add geometry columns tool, which adds the area and parameter to the
attribute table. Then we can calculate the Intersection field between the area along the
river and the wooded areas in trees.shp, as shown in the following screenshot:
Using the Dissolve tool, we can recombine all areas from the intersection results into
one big polygon representing the total wooded area around the river. Finally, we can
calculate the final share of wooded area using Advanced Python field calculator.
The formula value = $geom.area()/<area> divides the area of the final polygon
($geom.area()) by the value in the "area" attribute (<area>), which we created in a
previous step by running Export/Add geometry columns. The tools will appear as
shown in the following screenshot:
[ 70 ]
Chapter 4
This calculation results in a wood share of 0.31601 for Deciduous and 0.09666
for Mixed trees. Therefore, we can conclude that in total, 41.27 percent of the
land along Susitna River is wooded.
[ 71 ]
Spatial Analysis
Let's create a model that automates the creation of hexagonal heatmaps! By double-
clicking on the Vector layer entry in the Inputs list, we can add an input field for the
point layer. It's a good idea to use descriptive parameter names so we can recognize
which input is first and which is later in the model. It is also useful to restrict the
Shape type field where appropriate. In our example, we restrict the input to Point.
This will enable Processing to prefilter the available layers and present us only with
layers of the correct type. The second input we need is a Number field to specify the
desired hexagonal cell size. The tool will look like the following screenshot:
[ 72 ]
Chapter 4
After adding the inputs, we can now continue creating the model by assembling the
algorithms. In the Algorithms section, we can use the filter at the top to narrow down
our search for the correct algorithm. To add an algorithm to the model, we simply
double-click on the entry in the list of algorithms. This opens the algorithm dialog
where we have to specify the inputs and further algorithm-specific parameters.
In our example, we want to use the point vector layer as the input layer, and the
number input hex cell size as the cellsize parameter. We can access the available
inputs through the drop-down list. Alternatively, it's also possible to hardcode
parameters such as the cell size.
[ 73 ]
Spatial Analysis
To finish the model, we should enter a model name (for example, Create hexagonal
heatmap) and a group name (for example, my models). Processing will use the group
name to organize all the models we create. Once we have picked a name and group,
we can save the model and then run it. After closing the modeler, we can run the saved
models from the toolbox like any other tool. It is even possible to use one model as a
building block in another model.
[ 74 ]
Chapter 4
Another useful feature is that we can specify a layer style, which should be applied to
the processing results automatically. This default style can be set using Edit rendering
styles for outputs in the context menu of the created model in the toolbox, as shown in
the following screenshot:
Summary
In this chapter, we covered various raster and vector geoprocessing and analysis tools
and how to apply them in common tasks. We saw how to use the Processing toolbox
to run individual tools as well as the modeler to create complex geoprocessing models
from multiple tools. Using the modeler, we can automate our workflows and increase
our productivity, especially with respect to reoccurring tasks.
In the following chapter, we will learn how to bring all our knowledge together to
create beautiful maps using advanced styles and map compositioning features.
[ 75 ]
Creating Great Maps
In this chapter, we will cover the important features that enable us to create great
maps. We will first go into advanced vector styling, building on what we learned in
Chapter 2, Viewing Spatial Data. Then, we will learn how to label features by following
examples for point labels as well as more advanced road labels with road shield
graphics. We will also cover how to tweak labels manually. Finally, we will get to
know the print composer and how to use it to create printable maps and map books.
• Natural Breaks (Jenks): This mode uses the Jenks Natural Breaks algorithm
to create classes by taking the distribution of values into account
• Standard Deviation: This mode uses the column values' standard deviation
to create classes
• Pretty Breaks: This mode is the only classification that doesn't strictly create
the specified number of classes, but tries to find pretty class breaks instead
Besides using color to distinguish between the different temperature values, we can
also use size. By setting the Size scale field field in the Advanced tab to T_F_MEAN,
as shown in the following screenshot, all point symbols will be scaled so that
locations with higher mean temperatures are displayed with a bigger symbol.
Using Size scale field, we can make the size of point symbols
or the width of line symbols responsive to a certain attribute
value. Note that we can choose between scaling the area or
the diameter of a point symbol depending on the nature of the
values. Similarly, there is also a Rotation field option, which
allows us to rotate point symbols. The expected input is in
degrees from 0 to 360 with 0 pointing towards the north.
[ 78 ]
Chapter 5
The following screenshot shows the results of using a Graduated renderer option
with four classes using the Pretty Breaks classification mode and a Size scale field
option, as shown in the preceding screenshot:
[ 79 ]
Creating Great Maps
Of course, every symbol is editable and can be customized. Just double-click on the
symbol preview to open the Symbol selector dialog, which allows us to select and
combine different symbols.
Once we click on OK, the style is applied to our trees layer to visualize the
distribution of different tree types in the area. The map will look like the
following screenshot:
[ 80 ]
Chapter 5
[ 81 ]
Creating Great Maps
In the following screenshot, we can see the scale rules in action. While the left-hand
side shows a simplified version with thin grey lines for secondary highways, the
right-hand side version shows wider, white roads with grey outlines.
You can download the symbols used in this style by going to Settings
| Style Manager | Share | Import from. The URL is https://
raw.github.com/anitagraser/QGIS-resources/master/
symbols/osm_symbols.xml. Paste the URL in the Location
textbox, click on Fetch Symbols, then on Select all, and finally on
Import. The dialog will look like the following screenshot:
[ 82 ]
Chapter 5
Labeling
We can activate labeling by going to Layer Properties | Labels, checking Label
this layer with, and selecting the attribute field that we want to use for the labels.
This is all we need to do to display labels with default settings. While default labels
are great for a quick preview, we usually want to customize the labels if we create
visualizations for reports or stand-alone maps.
Using Expressions (the button that is right beside the attribute drop-down list),
we can format the label text to suit our needs. For example, the NAME field in our
sample airports.shp file contains text in uppercase. To display the airport names
in mixed case instead, we can set the expression title(NAME), which will reformat
the name text in title case. We can also use multiple fields to create the label, for
example, combining name and elevation in brackets using the concatenation
operator || as follows:
Note the use of simple quotation marks around text such as ' (' and double
quotation marks around field names such as "ELEV". The dialog will look like
the following screenshot:
[ 83 ]
Creating Great Maps
The big preview area at the top of the dialog titled Text/Buffer sample shows
a preview of the current settings. The background color can be adjusted to test
readability on different backgrounds. Under the preview area, we find the
following different label settings:
• Text: Besides changing the font style, size, color, and transparency, we can
also modify letter and word spacing as well as the blend mode, which works
like the layer blending mode we covered in Chapter 2, Viewing Spatial Data.
Note the column of buttons on the right-hand side of every setting. Clicking
on these buttons allows us to create so-called data-defined overrides. These
can be used, for example, to define different label colors or to vary label size
depending on an individual feature's attribute value or an expression.
• Formatting: Here we can enable multiline labels by specifying which
characters to wrap on. Additionally, we can control line height and
alignment. We can also add a symbol that displays the line's digitizing
direction to the label. Finally, the Formatted numbers option offers a
shortcut to format numeric values to a certain number of decimal places.
• Buffer: We can adjust the buffer size, color and transparency, as well as
the pen join style, and blending mode. With transparency and blending,
we can improve label readability without blocking out the underlying
map too much.
• Background: This allows us to add a background shape in the form of a
rectangle, square, circle, ellipsoid, or an SVG. SVG backgrounds are great
to create effects such as highway shields.
• Shadow: This makes it possible to add a shadow to labels. We can control
everything from shadow direction to color, blur, size, and transparency.
• Placement: The available automatic label placement options depend on the
layer geometry type. For point layers, we can choose between the following:
°° The flexible Around point option tries to find the best position for
labels by distributing them around the points without overlaps.
As you can see in the following screenshot, some labels are put to
the upper-right corner of their point symbol while others appear at
different positions in the lower-left (for example, Anchorage Intl
(129)) or lower-right (for example, Merrill Fld (123)) corners.
°° The Offset from point option forces all labels to a certain position;
for example, all labels can be placed above their point symbol.
[ 84 ]
Chapter 5
For further fine-tuning, we can define whether the label should be placed
Above line, One line, or Below line, and how far above and below using
Label distance.
The following example shows labels with road shields. You can download
a blank road shield SVG from http://upload.wikimedia.org/wikipedia/
commons/c/c3/Blank_shield.svg. Note how only Interstates are labeled.
This can be achieved using the following labeling expression:
CASE WHEN "level" = 'Interstate' THEN name END
The labels are positioned using the Horizontal option. Additionally, Merge
connected lines to avoid duplicate labels (in the Rendering section) and
Suppress labeling of features smaller than are activated; for example, 5 mm
helps to avoid clutter by not labeling pieces of road that are shorter than 5
mm at the current scale.
[ 85 ]
Creating Great Maps
To set up the road shield, go to the Background section and select the
blank shield SVG from the folder you downloaded it to. To make sure
that the label fits nicely inside the shield, we additionally specify the Size
type field as a buffer with a Size of 1 mm, which makes the shield a little
bigger than the label it contains.
If you click on Apply now, you will notice that the labels are not centered
perfectly inside the shields. To fix that, we apply a small Offset in the
Y direction to the shield position, as shown in the following screenshot.
Additionally, I recommend to deactivate the label Buffer as it tends to
block out parts of the shield, and we don't need it anyway.
The following screenshot shows lake labels (lakes.shp) using the Multiple
lines feature wrapping on the empty space character and positioned using
the Free option:
[ 86 ]
Chapter 5
Besides automatic label placement, we also have the option to use data-
defined placement to position labels exactly where we want them to be. In
the labeling toolbar, we find tools to move and rotate labels by hand. They
are only active and available for layers that have data-defined placement for
at least X and Y coordinates set up. To start using the tools, we can simply
add three new columns, label_x, label_y, and label_rot to, for example,
the airports.shp file. Then, we can specify these columns in data-defined
settings by pressing the buttons beside Offset X, Y and Rotation. We don't
have to enter any values in the attribute table right now. The labeling engine
will check for values, and if it finds the attribute fields empty, it will simply
place the labels automatically. By specifying data-defined placement, the
labeling toolbar's tools are now available (note that the editing mode has to
be turned on), and we can use the tools to move and rotate any of the labels
on the map. The changes are written back to the attribute table. Try moving
some labels, especially where they are placed closely together, and watch
how the automatically placed labels adapt to your changes.
[ 87 ]
Creating Great Maps
• A preview area for the map composition displaying a blank page on start
• Panels for configuring the Composition, Item properties, and Atlas
generation, as well as a Command history panel for quick undo and redo
• Toolbars for managing, saving and exporting compositions, navigating in
the preview area, as well as adding and arranging different composer items
The Composition panel gives us access to the paper options such as size, orientation,
and number of pages. It is also the place to configure snapping behavior and output
resolution.
First, we add a map item to the paper using the Add new map button, or by going
to Layout | Add Map and drawing the map rectangle onto the paper. Click on
the paper, keep the mouse button pressed down, and drag the rectangle open. We
can move, resize, and zoom the map using the mouse and the Select/Move item
tools. Alternatively, it is also possible to configure all map settings in the Item
Properties panel.
The Item Properties panel content depends on the currently selected composition
item. If a map item is selected, we can adjust the map's Scale and Extents as well
as the Position and size tool of the map item itself. At a Scale of 10,000,000, we can
more or less fit Alaska on an A4 paper. To move the area that is displayed within
the map item, we can use the Move item content tool.
After the map looks like we want it to, we can add a scale bar using the Add new
scalebar button or by going to Layout | Add Scalebar and clicking on the map.
The Item Properties panel now displays the scalebar's properties similar to what
you can see in the following screenshot. Since we can add multiple map items to
one composition, it is important to specify which map the scale belongs to. The
second main property is the scalebar style, which allows us to choose between
different scalebar types or a Numeric type for a simple textual representation
such as 1:10,000,000. Using the Units properties, we can convert the map units
in feet or meters to something more manageable, such as miles or kilometers.
[ 88 ]
Chapter 5
The Segments properties control the number of segments and the size of a single
segment in the scalebar. Further, the properties control the scalebar's color, font,
background, and so on.
North arrows can be added to a composition using the Add Image button or by
going to Layout | Add image and clicking on the paper. It might take a while for
the Item Properties panel to update while QGIS loads the previews of the images
in the SVG folder. Pick a north arrow from the list of images shipped with QGIS or
select your own SVG. Further map decorations such as arrows or rectangle, triangle,
and ellipse shapes can be added using the appropriate toolbar buttons Add Arrow,
Add Rectangle, and so on.
Maps that show an area close up are often accompanied by a second map that tells
the reader where the area is located in a larger context. To create such an overview
map, we add a second map item and activate its Overview option. By setting the
Overview frame, we can define which detail map's extent should be highlighted.
[ 89 ]
Creating Great Maps
Other common map features are grids and coordinate frames. Grids can be enabled for
any map item. We can choose between a normal Solid grid or Crosses only. Interval
and Offset values have to be specified in map units. Additionally, we can activate a
value of Zebra for the Frame style and Draw coordinates inside or outside the frame,
as shown in the following screenshot:
Legends are another vital map element. We can use the Add new legend button
or go to Layout | Add legend to add a default legend with entries for all currently
visible map layers. Legend entries can be reorganized, edited, and removed in the
Legend items' properties. Using the Wrap text on option, we can split long labels on
multiple rows as shown in the following screenshot. Additionally, the legend in this
example is divided into four columns. By default, QGIS tries to keep all entries of one
layer in a single column, but we can override this behavior be enabling Split layers.
To add text to the map, we can use the Add new label button or go to Layout |
Add label. Simple labels display all text using the same font. By enabling Render
as HTML, we can create more elaborate labels with headers, lists, different colors,
and highlights in bold or italics using the normal HTML notation, for example:
<h1>Alaska</h1>
<p>The name <i>"Alaska"</i> means "the mainland"</p>
<ul><li>one list entry</li><li>another entry</li></ul>
[ 90 ]
Chapter 5
Even more advanced text areas can be added using the Add html frame button.
We can point the item's URL reference to any HTML page on our local machines
or online, and the content will be displayed on the composer page.
To add additional details to the map, the composer also offers the possibility to
add an attribute table to the composition using the Add attribute table button or
by going to Layout | Add attribute table. By enabling Show only visible features,
we can filter the table and display only relevant results. Sorting and renaming of
columns is possible via the Attributes… button.
Finally, the Atlas generation panel enables us to create a series of maps using one
print composition. The tool will create one map for every feature in the Coverage
layer dropdown we define in the atlas configuration. Features in the Coverage layer
can be displayed like regular features or hidden by enabling Hidden coverage layer.
Feature sorting and Feature filtering make it possible to further fine-tune the results.
[ 91 ]
Creating Great Maps
Using the Fixed scale option, all maps will be rendered using the same scale. If
we need more flexible output, we can switch to the Margin around feature option
instead, which zooms to every Coverage layer feature and renders it in addition
to the specified margin surrounding area. The Output field can be one image or
PDF for each Coverage layer feature or a multipage PDF by enabling Single file
export when possible before going to Composer | Export as PDF.
Summary
In this chapter, we had a closer look into how we can create some more complex
maps using advanced vector layer styles such as the categorized or rule-based style.
We also covered the automatic and manual feature labeling options available in QGIS.
This chapter also showed how to create printable maps using print composer, and
introduced the Atlas functionality for creating map books. Congratulations! Over the
previous chapters, you have learned how to install and use QGIS to create, edit, and
analyze spatial data and how to present it in an effective manner.
[ 92 ]
Index
Symbols Attributes... button 91
Attributes toolbar 12, 39, 44
$area function 47 automated geoprocessing
$length function 47 graphical modeler, using with 72-75
$rownum function 47
.prj file 19 B
A Background setting 84
Basics statistics 61
Add attribute table button 91 Buffer setting 84
Add Feature tool 39
Add html frame button 91 C
Add Image button 89
Add new label button 90 cat attribute 60
Add new legend button 90 Categorized option 29
Add new map button 88 categorized style
Add new scalebar button 88 using 79
Add Rings tool 43 cellsize parameter 73
Advanced Digitizing toolbar 12 Centroid fill 33
Add Rings tool 43 Color ramp field 77
Merge Selected Features 44 Column field 77
Offset Curve tool 44 Coordinate Capture plugin 10
Reshape Features 44 coordinate reference system. See CRS
Rotate Feature(s) 43 CRS 11, 18-20
Rotation field feature 44 Curved option 85
Simplify Feature tool 43
Split Features 44 D
airports.shp file 83, 87
alaska.shp 60 data
area shares loading, from databases 22-25
calculating, within region 69-71 loading, from web services 25
Around centroid option 86 databases
Around point option 84 data, loading from 22-25
Aspect tool 56 Database toolbar 12
attributes Data defined properties button 30
editing 45-47
density Equal Intervals mode 77
mapping, with hexagonal grids 68 Natural Breaks (Jenks) mode 78
Digitizing toolbar Pretty Breaks mode 78
about 12, 39, 43 Quantile (Equal Count) mode 77
Copy Features 43 Standard Deviation mode 78
Cut Features 43 Graduated style option 29
Delete Selected 43 graphical modeler
Move Feature(s) tool 43 used, for automated geoprocessing 72-75
Node Tool 43 GRASS tools 66
Dissolve result option 69 ground control points (GCPs) 21
Dissolve tool 70
H
E
heatmap
elevation data about 62
analyzing 55-57 creating, from points 62
elevp.csv file 19 Heatmap Plugin 62
Ellipse marker option 31 Help toolbar 12
Equal Intervals mode 77 hexagonal grids
density, mapping 68
F Hillshade tool 56
Histogram 60
features holes 43
identifying, in proximity of others 64, 65 Horizontal option 85, 86
feature selection tools
working 39-42 I
files
vector data, loading from 16-18 Identify tool 46
File toolbar 11 Intersection field 70
Fixed distance buffer 64 Item Properties 89
Fixed scale option 92
Font marker option 31 J
Formatted numbers option 84
Formatting setting 84 Join field 51
Free option 86 Join layer field 51
fTools plugin 10
L
G labeling 83-87
GdalTools plugin 10 label, settings
gdalwarp command 53 Background setting 84
Geographic Resources Analysis Support Buffer setting 84
System (GRASS) 6 Formatting setting 84
Georeferencer Placement setting 84
use cases 21, 22 Shadow setting 84
Graduated renderer option 79 Text setting 84
graduated style Label toolbar 12
creating, with size-scaling 77-79 lakes.shp file 40
[ 94 ]
landcover.img raster 27 OGR SQL
Layer Properties dialog 60 URL 23
line layers. See also line style Open field calculator button 47
line layers OpenLayers plugin
Curved option 85 installing 34
Horizontal option 85 OSGeo4W installer
Parallel option 85 about 6
Line/Point pattern fill 33 advantages 6
line style URL 6
creating 31, 32 Outline 33
symbol layer types 32 Overview option 89
List unique values 61
Load into canvas when finished option 54 P
Parallel option 85
M pipelines.shp 42
Manage Layers toolbar 11 Placement setting 84
Map Navigation toolbar 12 Plugin
maps about 10-12
loading 34, 35 Coordinate Capture plugin 10
Margin around feature option 92 fTools plugin 10
Marker line option 32 GdalTools plugin 10
master 5 Processing plugin 10
measuring tool Plugin Manager 62
using 44, 45 Point displacement style option 29
Merge Selected Features 44 point layers. See also point style
Metadata 60 point layers
Move Feature(s) tool 43 Around point option 84
Move item content tool 88 Offset from point option 84
point style
N creating 29
symbol layer types 31
NAME field 83 polygon layers. See also polygon style
Natural Breaks (Jenks) mode 78 polygon layers
Natural Earth Around centroid option 86
URL 81 Free option 86
ne_10m_roads.shp file 81 Horizontal option 86
New Vector Layer dialog 38 Offset from centroid option 86
Node Tool 43 Rendering option 87
Number field 72 Using perimeter option 86
Numeric type 88 polygon style
creating 33
O symbol layer types 33
Position and size tool 88
Offset Curve tool 44
PostGIS 23
Offset from centroid option 86
Pretty Breaks mode 78
Offset from point option 84
[ 95 ]
print maps georeferencing 21, 22
designing 88-92 Refine current rules button 81
Processing region
vector, geoprocessing with 63 area shares, calculating 69-71
Processing plugin 10 Relief tool 56
Rendering option 87
Q Reshape Features 44
road layers
QGIS rule-based style, creating for 81, 82
about 50 road shield SVG
CRS, dealing 19, 20 URL 85
installing 5 Rotate Feature(s) 43
installing, on Ubuntu 8, 9 Rotation field feature 44
installing, on Windows 6, 7 Rotation field option 78
running 9, 10 Ruggedness Index tool 56
sample data, URL 16 rule-based style
URL 5 creating, for road layers 81, 82
user interface 11-13 Rule-based style option 29
QGIS, installing Rule properties 81
OSGeo4W installer 6
standalone installer 6 S
QGIS master
installing 6, 7 Save Edit(s) button 45
Quantile (Equal Count) mode 77 Save Layer Edits button 39
Select by Expression 40
R Select by location tool 64
Select/Move item tools 88
railroads.shp 42 Shadow setting 84
Raster Shapefile
about 12 creating 37
and vectors, converting between 59, 60 Shape type field 72
calculator 58, 59 Shuttle Radar Topography Mission.
clipping 53, 54 See SRTM
sampling, at point locations 66 Simple fill 33
raster data Simple line option 32
converting 48-50 Simple marker option 31
reprojecting 48-50 Simplify Feature tool 43
raster file Single Symbol option 29
loading 20 Size scale field option 78, 79
supported format, URL 21 size-scaling
raster layer graduated style, creating with 77-79
styling 26-28 Size type field 86
Raster layer statistics Slope tool 56
accessing 60 spatial data
Histogram 60 viewing 15
Metadata 60 SpatiaLite 22
raster maps Split Features 44
[ 96 ]
Sqlite Attributes toolbar 12
about 22 Database toolbar 12
sample database, URL 22 Digitizing toolbar 12
URL 22 File toolbar 11
SRTM Help toolbar 12
about 56 Label toolbar 12
URL 56 Manage Layers toolbar 11
standalone installer 6 Map Navigation toolbar 12
Standard Deviation mode 78 Vector toolbar 12
SVG fill 33 Web toolbar 12
SVG marker option 31 Transparency band option 54
symbol layer types, line style trees.shp file 79
Marker line option 32
Simple line option 32 U
symbol layer types, point style
Ellipse marker option 31 Ubuntu
Font marker option 31 QGIS, installing 8, 9
Simple marker option 31 ubuntugis repository 8
SVG marker option 31 Units property 88
Vector Field marker option 31 Using perimeter option 86
symbol layer types, polygon style
Centroid fill 33 V
Line/Point pattern fill 33
vector data
Outline 33
converting 48-50
Simple fill 33
loading, from files 16-18
SVG fill 33
reprojecting 48-50
symbols
Vector Field marker option 31
URL 82
vector file
supported format, URL 21
T vector geometries
tabular data editing 43, 44
joining 50, 51 vector layer
Target field 51 creating 37-39
terrain analysis styling 29
Aspect tool 56 vector layer statistics
Hillshade tool 56 accessing 60
Relief tool 56 Basics statistics 61
Ruggedness Index tool 56 List unique values 61
Slope tool 56 vector layer, style options
terrain data Categorized option 29
analyzing 55-57 Graduated style option 29
Text setting 84 Point displacement style option 29
Toggle editing button 39 Rule-based style option 29
toolbars Single Symbol option 29
Advanced Digitizing toolbar 12 vector layer, styling
line styles, creating 31, 32
[ 97 ]
maps, loading 34 W
point styles, creating 29-31
polygon styles, creating 33 web services
vectors data, loading from 25
and rasters, converting between 59, 60 Web toolbar 12
geoprocessing, with Processing 63 Well known text. See WKT
styling 77 Windows
vector, styling QGIS, installing 6, 7
categorized styles, using 79 WKT
graduated style, creating with about 17
size-scaling 77-79 URL 18
rule-based style, creating for Wrap text on option 90
road layers 81, 82
Vector toolbar 12
v.sample 66
[ 98 ]
Thank you for buying
Learning QGIS 2.0
Our books and publications share the experiences of your fellow IT professionals in adapting
and customizing today's systems, applications, and frameworks. Our solution based books
give you the knowledge and power to customize the software and technologies you're using
to get the job done. Packt books are more specific and less general than the IT books you have
seen in the past. Our unique business model allows us to bring you more focused information,
giving you more of what you need to know, and less of what you don't.
Packt is a modern, yet unique publishing company, which focuses on producing quality,
cutting-edge books for communities of developers, administrators, and newbies alike.
For more information, please visit our website: www.packtpub.com.
OpenStreetMap
ISBN: 978-1-847197-50-4 Paperback: 252 pages