QGIS Planet

QGIS – Mapping Election Results, pt 2: Adding and overlaying the data in QGIS

Continuing on from the previous tutorial:-

Return to QGIS. Add the westminster_const_region.shp file if necessary

  1. Press the Add Delimitated Text file button, and select the .csv export of the cleansed electoral data
  2. The two options I changed from the default settings are:-
  • First record contains field names
  • No geometry (attribute only table)
QGIS - Create layer from text file

QGIS – Create layer from text file

Step 3 – Joining the data

Joining the polygons in westminster_const_region.shp to the data imported from the Results_Cleansed spreadsheet will allow the data to be presented in a spatial and visual format which will be much easier to interpret, allow for spatial analysis and also give the viewer an idea of the geographic spread. Using QGIS’ Join function will hopefully save a lot of copying and pasting!

Right click on westminster_const_region.shp and select Properties to open the Properties dialog

  • Select the Joins button from the left panel
  • Join Layer – the layer that you want to join to
  • Join Field – the field that you want to join to
  • Target Field – the field in this layer that contains the matching data
QGIS - Add vector layer

QGIS – Add vector layer

The join will now appear in the layer’s Joins list:-

QGIS layer properties

QGIS layer properties

The attribute table will now show the combined  data for both layers:-

QGIS attribute table

QGIS attribute table

This data can now be used to create a thematic map that colours each constituency according to party that won the seat in 2010.

I won’t go through all the steps of creating a thematic map as an earlier tutorial does this.

I’ve used the same colours that the different parties in the UK use:-

QGIS Layer properties

QGIS Layer properties

The thematic map shows the results across the entire UK. It is easy to identify patterns in the result, for example

  • The Liberal Democrats mostly won seats in Scotland, the North East, Wales and South West.
  • There is strong Labour support in South West Scotland, North West England, West Midlands, South Wales, London, Liverpool and Manchester.
  • The Conservative support covers much of the rest of England, especially South East England, excluding London.
2010 election results map

2010 election results map

Combining skills – Mapping Election Results

I would like to show you how to use QGIS to combine different skills to

  • Import data from Excel or other spreadsheets
  • Analyse the data
  • Present the results as a thematic map
  • Use a feature subset to hide superfluous data

There is a year to go to the next general election. Under the British electoral system, the country is divided into 660 constituencies. The MP for each constituency is elected using the First Past the Post system, where the candidate with the most votes is chosen as MP for that constituency. The party that has the most MPs elected wins the election, and the right to form the nest government.

Parties concentrate their resources on the constituencies that they are most likely to win or lose. These are usually the ones where majority in the previous election was closest.

This project will use QGIS to join fields between OS Boundary line data and the 2010 election results to identify and map these constituencies.

I downloaded the following data sets:-

OS Boundaryline:  https://www.ordnancesurvey.co.uk/opendatadownload/products.html

Election results: http://www.electoralcommission.org.uk/__data/assets/excel_doc/0020/105725/GE2010-constituency-results-website.xls

Step 1 – Examine and prepare the data

I need both data sets to use exactly the same name and formatting in order to In order to add the 2010 election results to the OS Boundary line polygons.

  1. Start QGIS and set the map projection to OSGB.
  2. Use the Add Vector Layer button to add the file westminster_const_region.shp from the OS Boundary line data
  3. Open the attribute table to check the data structure and contents:-

Constituency attribute table

Now to check the GE2010-constituency-results-website.xls



Election results Excel screenshot

Unfortunately the two datasets don’t use exactly the same constituency names! It is fairly easy, but time consuming to match the record from the Election Results dataset to the OS Boundary Line record using Excel or Libre Office.

To export the OS Boundary line polygon names to Excel:-

  1. Right click on the westminster_const_region.shp in the Layers Panel
  2. Select Save As

I prefer to use the .dbf format when exchanging data between GIS and Excel as it is quicker to import than using .csv format.



Both name fields are needed. The first, constituency _name will be used to link to the constituency polygons once the table is imported into QGIS. The second, Results_Table_Name is used by the VLOOKUP query that adds the five columns from the results data.


Excel screenshot showing the cleansed election results matched to constituency names

Save the data as a .csv file when this stage is complete.

Topology in QGIS


Topology rules define the permissible relationships of features within a given GIS layer or between features in two different GIS layers. An example is that features in a road dataset must be connected to other roads at both ends, unless the road is specified as a dead end street.

Advantage of topology over queries

A lot of the checks that topology rules carry out could be achieved using spatial queries. You may have to use queries if the GIS software you’re using doesn’t have a topology feature.

Topology rules have the advantage that they only need be created once and then they can check your work as you go.

Queries would need to be re-created each time they are run. They can be saved, depending on the GIS being used, but this is still more time consuming and it is a task that must be carried out separately at the end of a work session.


QGIS 2.2 topology tool has the following rules pre-defined:-

  • End points must be covered by (e.g. a railway line usually begins and ends at a station)
  • Must contain (e.g. a building polygon must contain at least one address point seed)
  • Must not have dangles (a line must begin and end at another line)
  • Must not have duplicates (each feature should be unique, e.g. postcode areas)
  • Must not have gaps (e.g. administrative area polygons cannot have gaps)
  • Must not have invalid geometries
  • Must not have multi-part geometries (each feature should be a separate entry)
  • Must not overlap (e.g. administrative area polygons cannot overlap each other)
  • Must not overlap with (a feature from layer must not overlap with another layer)

Example 1 – Roads must not have dangles

The following example uses the “Must not have dangles” rule to identify polylines from a roads dataset that are not snapped to other lines. Roads usually begin and end at a junction with another road, so this is a useful rule to identify where lines were not correctly snapped together.

To create and validate a Topology Rule

  • Open the Topology Panel, by selecting Vector menu, Topology Checker, Topology Checker
  • The Topology Panel appears in the lower right corner of the QGIS desktop window


  • Press the Configure button to open the Topology Rule Settings dialog
  • The top of the box will have 2 or 3 pull down boxes depending on the layer and rule that is chosen. Use these to build the rule and then press the Add Rule button.


  • Press OK when done, the dialog box closes and the window returns to the QGIS Desktop.
  • Press either the Validate All or Validate extent, depending on whether you wish to validate the entire dataset or just the current view extent.
  • The errors will be listed. Double click on a row will make the map window zoom and pan to the error.



Re-Projecting Vector Layers in QGIS

QGIS can re-project a layer using both on-the-fly re-projection for the current session; and by saving a copy of the layer with a new Co-ordinate Reference System (CRS) defined.

On the fly

This is useful when a layer only needs to be re-projected for the current session.

Add the layer. If the CRS is known, QGIS will re-project it if necessary.

To check which CRS has been specified for the layer, right click on the layer in the Layers Panel, select Properties, and then select the General tab.

QGIS Layers Property

QGIS Layers Property


To save a new copy

It is a good practice to save a copy of a layer once it has been re-projected. This is to ensure the new CRS and transformations are permanently assigned to it. This avoids transformation errors when it is added to later map documents.

To save a copy:-

  1. Right click on the layer in the Layers Panel , select Save As.
  2. In the Save Vector layer as dialog, specify the filename, plus the new Co-ordinate Reference System. It is possible to add a symbology reference scale and new attributes. It is a good idea to add the new layer to the map to check it is correctly projected.
QGIS Save Vector Layer Dialog

QGIS Save Vector Layer Dialog

QGIS Distance Calculator

I want to find a location that is close to existing industrial areas (red polygons) and away from Sites of Special Scientific Interest (green polygons)

I will do this by using the Proximity (Raster Distance) analysis tool to create distance thematics, then using the Raster calculator to average the distance from each criterion.

Original layers

Original layers

Convert to Raster

The process only works with input files that are in raster format. As our source is in vector format (it’s a polygon .shp file), we need to convert it to a raster file.

It is good practice to add an attribute column, set its value to 1 so the resulting raster has a value of 1 for all the polygons. This can be done using the Field Calculator in the Attribute table.

QGIS Rasterize tool

QGIS Rasterize tool

Change display properties

The raster initially appears as a grey box. Don’t worry, this is normal. I am going to adjust its display properties so I can see the information.

  1. Right click on the layer
  2. Select Properties
  3. Select Stretch to MinMax under Contrast Enhancement
  4. Select the style tab
  5. Tick Invert Colour map. This makes the areas with a value of 1 black and the areas with a value of 0 white
QGIS Layers dialog

QGIS Layers dialog

The colours look quite stark, so I’m going to apply a transparency:-

  1. Select the Transparency tab
  2. In the Transparent Pixel List box, enter 1 under Gray and 50 under % Transparent
QGIS Layers dialog

QGIS Layers dialog

Its appearance is now less over-powering and I can see other layers too:-

QGIS Distance Calculator4

Calculate Proximity/Distance

Now to create a thematic based on the proximity (or distance) between each pixel and the nearest point of a SSSI site:-

  1. Open the Proximity calculator by selecting Raster menu, Analysis, Proximity (Raster Distance)
  2. Select the input raster and output raster (I found it works best if the output file is in .tif format)
Proximity (Raster Distance) calculator dialog

Proximity (Raster Distance) calculator dialog

  • I want to measure the distance to SSSI pixels with a value of 1 (that is what I set to be the value used for areas with SSSI designation)
  • Distance units are Geo (geographical) rather than pixels

The output is initially a grey square. I have made the following adjustments:-

  • Colour map – Puseudo colour
  • Global Transparency – 50%

It is worth exploring the options to invert the colour map and Contrast Enhancement

The SSSI sites are visible as the green polygons, the thematic is red for areas closest to sites and blue for areas furthest away:-

QGIS Distance Calculator Results1

Repeat the process for all the necessary layers:

Proximity Distance Calculator Results

Proximity Distance Calculator Results

Raster Calculator

The raster calculator is a powerful tool that performs mathematical operations on each cell in a raster. Examples of this can be to calculate elevation, distance or density.

In this case, I am going to use it to identify the areas that are greater than 1km from a SSSI site by applying queries to identify matching pixel values.

  1. Open the raster calculator
  2. Enter the following expression SSSI_Distance@1 > 1000

The map units are in metres, so 1,000m = 1km

The resulting raster appears as a grey box. As usual, adjust its display properties (e.g. Contrast Enhancement, Invert Map and Transparency). The areas that are further than 1km from a SSSI site are now highlighted in grey, with the sites visible in green:-

QGIS Distance Calculator5

Combining Raster Calculator with elevations

I want to identify which areas of Chetney Marshes would be flooded by a 2m rise in sea level.  I used LIDAR data in contour format as the elevation data:-

Chetney Marshes map

Chetney Marshes map

Create TIN

I am using the TIN method to create an elevation model as the area is relatively small and the data is supplied as contours. TIN’s are more accurate, especially if the source data isn’t in grid format. However they are slower to process, especially over very large areas.

Select Plugins, Interpolation to open the Interpolation dialogue:-

Raster Calc2

I made the following changes to the display properties:-

  • Colour map – Pusedocolour
  • Transparency – I set global transparency to 50%
Chetney Marsh after colour adjustment

Chetney Marsh after colour adjustment

Raster Calculator

I now have an elevation model of the area. I now use the Raster Calculator to identify each pixel with an elevation of less than 2m. The elevation is stored in the pixel value. The raster calculator will identify each pixel with band value of less than 2.

The expression is elevation < 2

Select Raster, Raster Calculator to open the Raster Calculator:-

Raster Calc4

To change the Display Properties for a layer, Right click on the Layer in the layers panel (Table of Contents) and select Properties. I made the following changes to the display properties so the areas that are less than 2m, and susceptible to flooding appear highlighted in blue:-

  • Style tab: Color map – Colormap
  • Transparency: Global transparency 50%
  • Colormap tab: I added 2 entries:-
    • 0.00 white
    • 1.00 blue
Chetney Marsh showing raster calculation results

Chetney Marsh showing raster calculation results


Raster Data Extraction using QIS

Raster files consist of a grid of cells, each cell contains a numeric value, which is used to determine how to colour each cell.  This value may be based on the elevation of the cell, flood water depth, or soil quality. It is possible to extract this information by point sampling or using a terrain profile. Point sampling copies the cell’s value to the overlying point. A terrain profile tool plots a graph with the cell’s value (elevation) on the Y axis and the distance along the section on the X axis.

Point Sampling Tool

DEM’s are often used to then update the elevation values of overlying points, for example I have used data from DEM’s to update the elevation values of address points and utilities. This isn’t as accurate as surveying each point, but it is a lot quicker! This process is also referred to image extraction, raster/vector conversion.

For this tutorial, you will need:-

  • The Point Sampling tool in QGIS is an optional plugin. You can download it by using the menus to select Plugins, Fetch Python Plugins.
  • Nasa’s srtm data, which you can download from here: http://srtm.csi.cgiar.org/
  • Some point data. If you can’t think of any, then they’re easy to create, for example use the Open Layers plugin to load Open Streetmap or Google Maps of your area, and then create points over a few cities.

I’m going to add the elevation value from the srtm rasters to a selection of UK towns and cities:-

Raster Data Extraction - UK srtm

  1. Use the menus to select Plugins, Analyses, Point Sampling Tool
  2. The Point Sampling Tool dialogue box opens. Select:-
  • The layer that contains the points to be sampled
  • The layer(s) with the field(s)/band(s) to get values from
  • The output (results) file
  • Press OK

Raster Data Extraction - Point sampling tool

The results file just contains the elevations:-

Raster Data Extraction - Elevations

It is possible to add these to the original layer:-

  • Create a buffer around the new points
  • Use the menus to select Vector, Data Management Tools, Join Attributes By location
  • Select the original points as the target and the buffer as the join layer

Another option is to update the x and y co-ordinates for both points using the Field calculator and then to match the rows in Excel on the co-ordinate column.

Raster Based Terrain Analysis Techniques pt2

Continuing from last week’s post, I will show you how to use terrain analysis to calculate:-

  • slope,
  • aspect
  • hillshade
  • ruggedness index


Slope is calculated by comparing the pixel value at a particular location relative to the surrounding 8 pixel values. This gives the steepness of the slope.

The Slope dialogue box is very simple:-

Calculate slope dialogue box

Calculate slope dialogue box

  • Select the elevation layer (this will be the DTM raster)
  • Select the output layer
  • I have left the Ouput format and Z factor as default. If the ground is very flat, then exaggerating the z factor might make the slopes easier to visualise.


The aspect shows the compass bearing of the slope

The raster has been given values from 0-360 depending on the slope aspect. The darker areas with the lower values are the north to north east facing slopes; the lightest areas with the highest values are the west to north west facing slopes.

Aspect shading

Aspect shading


This calculates the amount of sun or shade for a 3D surface. The dialogue box is similar to the previous ones, however there are new options for the sun angle:-

DEM hillshade dialogue box

DEM hillshade dialogue box

This analysis uses a fixed location of the sun to accurately simulate the effects of bare hillside and shaded valleys. I positioned the sun to the south west (200 degrees), the east facing slopes around the River Medina estuary in the north of the island are very shaded, in contrast to the brightly lit west facing slopes on the other side of the river.

A DEM with hillshading

A DEM with hillshading

This is the most visually appealing and easily understood result and so it is often used as a backdrop for maps with other layers added.

Ruggedness Index

The ruggedness index value is calculated for every location, by summarizing the change in elevation within the 3×3 pixel grid.  Ruggedness index values are grouped into categories to describe the different types of terrain.  The classifications are as follows:

Ruggedness Classification

Ruggedness Index Value

Level 0 – 80m
Nearly Level 81 – 116m
Slightly Rugged 117 – 161m
Intermediately Rugged 162 – 239m
Moderately Rugged 240 – 497m
Highly Rugged 498 – 958m
Extremely Rugged 959 – 4397m

The dialogue box for the ruggedness Index is the same as it is for the other types of analysis mentioned above. The IOW is all categorized as level or nearly level in the ruggedness index. This is despite it being quite hilly! I used the Stretch to MinMx contrast enhancement on the layer properties box:-

A DEM with ruggedness index displayed

A DEM with ruggedness index displayed

The result is quite different to the relief and hill shade raster’s. This is because, it doesn’t attempt to show actual slopes, rather it shows the change in elevation categorised as shown in the ruggedness index table. It is still easy to see the line of hills that cross east to west across the island.

Raster Based Terrain Analysis Techniques pt1

In the previous tutorial, I showed you how to create a raster terrain model. This is useful by itself for visualising the relief of an area. However, it can be even more useful when used as the basis of further analysis.

Over the next few tutorials, I will show you how to carry out the following types of analysis:-

  • Slope
  • Aspect
  • Hillshade
  • Ruggedness Index

I am going to use srtm data for the UK, you can download the file for your area from here: http://srtm.csi.cgiar.org/

Displaying the raster, resolving display problems

  • Add the image to the project using the Add Raster Layer button. At first the image opens completely grey, to stretch the black to white gradient to fit between the minimum and maximum values found in the image:-
  • Press the Stretch Histogram to Full Data Set on the Raster toolbar
  • Alternatively, right click on the layer in the Layer Panel, and
    • Select Properties.
    • Select the Style tab.

    At the bottom, change the Contrast Enhancement pull down to Stretch to Min Max.

  • If a grid displays as a continuous grey box, check the Transparency for null cells setting
    • Open the Layer Properties
    • Select the Transparency tab

      QGIS Layer Properties

      QGIS Layer Properties

  • Check that the correct band is selected in the Transparency Band pull down
  • Check the No data value and Percent Transparent entries in the Transparent Pixel list

The DEM Models plugin should appear on the Raster Menu. If it isn’t installed, it can be downloaded by using the menu to select Plugins, fetch Python plugins.

Its operation is similar for all the types of analysis that can be undertaken

  1. Select the input raster layer
  2. Select the output raster layer that will contain the results
  3. Use the pull down to select the analysis:
  • Hillshade
  • Slope
  • Aspect
  • Color Relief
  • Terrain Ruggedness Index
  • Topographic Position Index
  • Roughness
DEM Terrain Module

DEM Terrain Module

Image Analysis Using QGIS


Rasters are created from gridded data. Each pixel is coloured according to an interpolated value, e.g. triangulation (TIN), nearest neighbour analysis.

A raster file is comprised of a pixels arranged in a grid formation. Each pixel contains a colour value that instructs the computer as to what colour to use when displaying it. Raster images tend to be used for grids as they are a more efficient method of showing large areas of coloured pixels than vector maps.

The following illustrates how a raster grid represents terrain, and how the information might be extracted:-

For simplicity’s sake, imagine that we’re back in the days of 256 colours with 1 being white and 255 being black. I tend to display relief with the highest ground as white or red, then to show lower ground as green or blue.

Let’s take a cross section through a hill:

A grid raster image of the terrain would appear similar to below (please note that I have drawn this in Inkscape using a gradient fill to keep the demonstration simple!):-

The numeric values of the raster grid that the computer would see would be similar to this:

5 5 5 5 5
5 100 150 100 5
5 100 250 100 5
5 100 150 100 5
5 5 5 5 5

Note the values are not the actual elevation, just the colour values of the pixels. The elevation that each pixel value corresponds to (the legend) is contained in the accompanying shape file along with image registration (the x, y coordinates).

By analysing the grid and determining the relationship between pixel values and the elevation that they represent the GIS software can accurately model the terrain. Once the terrain has been modelled, it is possible to undertake further analysis such as slope calculation, predicting hill shade or water runoff.

The Image toolbar

Firstly, let’s have a look at QGIS’ image tool bar:-

QGIS image bar

QGIS image bar

This can be added by right clicking on any toolbar and selecting Raster from the short cut menu. The buttons are from left to right:-

  • Stretch Histogram to Full Data Set
  • Local Histogram Stretch
  • Geo-referencer
  • Interpolation
  • Zonal Statistics

QGIS – Modifying a table structure

Modify a table structure

  1. Right click the layer in the Layer’s Panel
  2. Select the Fields tab
  3. It is possible to add/delete columns. It is also possible to change the method of data entry from the default text number cells to specify valid number rangers, selecting pre-set values, tick box, calendar

Updating Fields with Spatial Data

Count within polygons

  • Points: (e.g. levelling points per district). Vector, Analysis tools, Points in Polygon
  • Length :(e.g. road length per district). Vector, Analysis Tools, Sum Line Lengths
  • Area: (e.g. area of land uses per district). Vector, Geo Processing Tools, Union

Calculate Proportional Overlap

  1. Use the Intersect tool to create a new polygon that covers the area of intersection.
  2. Update the area for it and the original regions.
  3. Calculate the area of the new polygon as a % of the area of the original region.

Joining Layers in QGIS

Joining tables allows a layer with the attributes of both source layers to be created. Joins can be based on common attributes or common location (spatial join).

The joined fields are displayed as a new view rather than actually added to the layer. However the join is saved with the project and it will be reloaded each time the project is opened. To permanently add the joined fields to the layer, it must be saved as a new file. To do this, right click on the layer in the Layer Panel and select Save As.

This is because databases are generally designed to be more permanent data repositories than spreadsheets. Therefore their structure shouldn’t be changed for short term projects. Queries can be run and saved without affecting the underlying data.

Join on Common Attributes:-

This method is similar to ArcGIS’ Joins and Relates function. This is done by creating a Vector Join in the layer’s Properties box:-

  1. Right click on the layer in the Layer Panel
  2. Select Properties to open the Properties dialogue box
  3. Select the Join tab
  4. Press the + button to create a new Vector Join:-
Add Vector Join in QGIS

Add Vector Join in QGIS

The Add Vector Join dialogue box opens:-

  • Join Layer – the layer that the join will be to
  • Join Field – the layer in the Join Layer that contains the common attribute
  • Target Field – the field in the currently selected layer that contains the common attribute

Join By Location (Spatial Join)

This function creates a new shapefile containing the geometry of the target layer and the attributes of both layers. The join is based on the Joining layer overlapping or intersecting the target layer:-

  1. Use the menus to select Vector, Data Management Tools; Join Attributes by Location
  2. The Join Attributes by Location box opens, select:-
  • Select the Target vector Layer (the layer to update)
  • Select Join Vector Layer (the layer that will provide the new data)
  • Attribute Summary. This determines the action when a target feature is overlapped by multiple join features:-Take the attributes of the first located feature.
  • Take a summary of intersecting features
  • Output Shapefile – the file that will contain the new data.
Join By Location (Spatial Join) in QGIS

Join By Location (Spatial Join) in QGIS

Updating Attribute Data

Browser Window:

QGIS Browser Window

QGIS Browser Window

Buttons on the bottom from left to right are:-

  • Unselect All
  • Move Selection to Top
  • Invert Selection
  • Copy Selected Rows to Clipboard
  • Zoom Map to the Selected Rows
  • Pan Map to the Selected Rows
  • Toggle Editing
  • Save Edits
  • Delete Selected Features (rows)
  • New Column
  • Delete Column
  • Open Field Calculator
  • Look For (enter search terms) in (use the pull down to select the column to search)

The attribute table has several duplicate rows. To delete them

  1. Press the Toggle Editing to begin an Edit Session
  2. Press the Delete Columns button
  3. Select the column(s) and press OK

To add new columns:

  1. Press the New Column button
  2. Enter the details for the new column
Add column dialog

Add column dialog

Update Columns with the Field Calculator

I want to update the three new columns I’ve added. To update columns:

  1. Right click on the layer in the Layer Panel
  2. Select View Attribute Table
  3. Press the Toggle Editing button to begin an Edit Session
  4. Press the Field Calculator
QGIS Field Calculator

QGIS Field Calculator

  1. Select to either create a new field or to update an existing field. If you’re updating an existing field then use the pull down to select the field
  2. Complete the Expression builder by either double clicking functions or typing the expression.
  3. Functions include:
  • Operators e.g.+-*/ etc
  • Maths e.g. cos, sin etc
  • Conversions e.g. to integer, to string, to decimal
  • Geometry e.g. feature’s length, area, perimeter, x, y
  • Record – Row number or ID
  • Fields and Values

Queries in QGIS pt2 – Spatial Query

In the previous post (Queries in QGIS pt 1 – Attribute Queries), I showed how to select features based on their attribute data, e.g. select shops which have the address entered as London. Now let’s imagine there isn’t an address attribute, or alternatively, we want to select features within flood plains for example, or identify areas of woodland that have high voltage power lines running through them.

Layers for spatial query

Spatial selection selects features in one layer based on their spatial relationship to features in another layer

To begin a spatial query either:

  • Use the menu to select Vector, Spatial Query
  • Press the Spatial Query button

The spatial query dialogue box:

QGIS Spatial Query Dialogue Box

Select Source Features From – this is the table that the selection will be from.

Where the feature – the options will change depending on the exact combination of point, line or region features that are being used for the selection. They include contains (e.g. a region layer may contain points), crosses (e.g. a line layer may cross a region layer), Is Within (e.g. a point layer may be within a region layer), Touches (where one object may touch another but not actually be within it).

Reference Features Of – this is the second layer. It will be used to select features from the first layer, but its features won’t be part of the selection

The selected geometries only will only use features that have already been selected. For example if I wanted to select all the woodland within a particular county I could set up the query to read

  • Select Source Features from Farmland
  • Where the Feature is Within
  • Reference features of County Boundaries (selected features only)

Click OK, the query will run. Once it has completed, the results will appear:-

QGIS Spatial Query Dialogue Box

It is possible to run a further query based on the selection

Press the Create Layer from Selected to add the selection to the map as a new layer:-

Spatial Query Results

Combined Spatial and Attribute Query

Quite often GIS is used to select features that contain a certain attribute within a certain area (e.g. all the A roads and motorways within Greater London).

These queries are carried out by combining the above Spatial and attribute selections. They can be carried out either order depending on which is most logical.

In this example I would overlay the roads and OS Boundary Line features. I would then select all the London Boroughs by clicking on them with the Select Single Feature tool

  • Select Source Features from Roads
  • Where the Feature is Within
  • Reference features of OS Boundaryline (selected features only)
  • Press OK
  • In the Results box, press the Create Layer from Selected to create a new layer
  • Right click on the newly added Selection from Roads layer in the Layer Panel
  • Select Query
  • Use the Query Builder to enter the following SQL “Classification” = ‘A Road’ OR “Classification” = ‘Motorway’
  • Press OK

Queries in QGIS pt 1 – Attribute Queries

Quick Select Tools

The Select Flyout button on the Main toolbar contains tools used to quickly select features:

QGIS Quick Select Tools

QGIS Quick Select Tools

Attribute Queries

One method to select features in a layer is to select features using an attribute query:-

To query a layer by its attribute data,

  1. Right click on the layer’s name in the Layer Panel
  2. Select Query from the short cut menu to open the Query Builder box
QGIS Select by attributes box

QGIS Select by attributes box

  1. It is possible to type the SQL query into the SQL where clause box. Alternatively:-
    1. Click the Field that contains the attributes you wish to base the query on
    2. Select the operator
    3. Press the All under the values box to list all the available values
    4. Double click the value that you wish to select
    5. You will see the query being built in the SQL where clauses box.

Boolean operations (And, Or, Not)

  • And: narrows the search by requiring all the criteria to be present. It is most commonly used when the criteria are in different columns. E.g. Select Business_type = “bank” And City = “London” will select banks with London addresses.
  • Or: broadens the search criteria by requiring just one of several criteria to be true. It is most commonly used to give different options to the same column e.g. select Business_type = “bank” Or Business_type = “shop” will select all the banks and shops within the data set.
  • Not: returns records that do NOT match the criteria e.g. select Business_type = “bank” AND City NOT “London” would return all the banks that do not have a London address. Note that QGIS uses != for not equal to

It is important to be clear about when to use And Or operators.

If the first example was worded Select Business_type = “bank” OR City = “London” this would return all the banks and any property with a London address

If the second example was worded select Business_type = “bank” AND Business_type = “shop” this would return only those business which had bank and shop entered as business type. This would probably be none at all as businesses tend to either be a shop or a bank but rarely both!

Mathematical Operations

It is possible to use mathematical formulae to select from columns that are formatted in a numeric format (e.g. integer):-

>Greater than e.g. Business_type = “shop” AND floor_space > 100

< Less than e.g. Business_type = “shop” AND floor_space < 100

>= greater than or equal to

<= Less than or equal to

!= Does not equal

Geo-Processing in QGIS

I’m going to look at the geo-processing tools. The geo-processing tools are found on the Vector menu under Geo-processing tools. These tools do not edit the input tables; instead you are prompted to create a new layer for the results. Therefore the input layers don’t need to be editable. You can choose to carry out the operation on every feature in the chosen layers, or just the selected features. These functions can be combined with attribute updates and calculations to carry out more complex analysis (e.g. calculate proportional overlap) or to count the address points within set distances of proposed new roads.

I will carry out most of the operations on the green square and red circle shown below:-

QGIS map window

QGIS map window

Intersect creates a new feature based on the area of overlap (the intersection) between the two layers. The attributes from both source layers are copied to the new feature:-

Intersect in QGIS

Intersect in QGIS

To calculate the area of overlap, update the newly created feature’s attribute table with its area.

Union creates a new layer that covers the combined features

Union in QGIS

Symmetrical Difference creates new shapes based on the non overlapping areas of the original features:-

Symmetrical Difference in QGIS

Clip creates a new shape based on the area of the input layer that is overlapped by the clipping layer. It is similar to the intersection but differs in that the attributes of the chosen layer only are copied to the new feature. It is similar to MapInfo’s Erase Outside function.

Clip in QGIS

Difference creates a new feature based on the area of the input layer that isn’t overlapped by the clipping layer. It is similar to MapInfo’s Erase function.

Difference in QGIS

Dissolve breaks apart overlapping regions in the same layer.

Buffer creates a region around each feature in the source layer. I have used buffers to count address points within set distances of new roads, assign address points to local amenity catchment zones etc. In this case I’m going to apply a 100m buffer around overhead electricity lines. These can be downloaded from OS Open Data.:-

Buffer in QGIS

  • Input vector Layer – the layer that contains the source objects
  • Buffer Distance – the distance the buffer will extend from the source objects
  • Buffer Distance Field – alternatively QGIS can use a value from a numeric field, this makes drawing variable width buffers for features in the same layer easy e.g. Sites rated High Sensitivity could be updated with a buffer distance of 1,000m, sites rated Medium Sensitivity could be updated with a buffer distance of 500m.
  • Dissolve Buffer Results. The default is to combine the buffers into one region. Enabling this creates a separate region for each source object.

Editing Vector Features in QGIS

Editing Features

A lot of of GIS work involves editing polygons and polylines as well as calculating the size of any overlapping features. For example when I provided GIS support to a local authority’s planning team, I was regularly asked to calculate what proportion of proposed developments overlapped constraints such as flood zones.

In this tutorial, I first look at the re-shaping features on the Advanced Digitising Toolbar. Then I will go through geo-processing tools such as buffer, union, intersect etc.

Advanced Digitising Tools

QGIS Advanced Digitising Toolbar

QGIS Advanced Digitising Toolbar

From left to right, the tools are:

  • Undo
  • Redo
  • Simplify feature
  • Add ring
  • Add part
  • Delete ring
  • Delete part
  • Reshape features
  • Merge selected features
  • Merge attributes of selected features

To use any of the tools,

  • Begin an edit session, by right click on the layer’s name in the Layer Panel and select toggle editing.
  • Select the feature that you wish to edit
  • Select the tool

This is the polygon at the start of the edit session, I will show a screen shot of each result:

Polygon in QGIS

Polygon in QGIS

Add Ring

is used to subtract a new internal region from the existing polygon. Select the tool and then draw the desired internal polygon:-

Add Ring in QGIS

Add Ring in QGIS

Delete Ring

deletes the selected internal region. Select the tool, and then click on the internal region’s nodes.

Add Part

adds a new external region to the existing region. Select the tool, then draw the new region, ensure it snaps to the existing region:-

Add Part in QGIS

Add Part in QGIS

Delete Part

deletes the selected region. Select the tool, and then click on the region’s nodes.

Reshape Features

draws a temporary region which is then subtracted from the existing region:

Reshape Features in QGIS

Reshape Features in QGIS

Reshape Features in QGIS

Reshape Features in QGIS

Split Features

draws a line through the region. The region is then split along the line

Split Features in QGIS

Split Features in QGIS

Merge Features – merges two or more selected features. Note Ctrl+click is used to select multiple features

Merge Features in QGIS

Merge Features in QGIS

A dialogue box allows you to choose which attributes to keep, discard. It is also possible to carry out mathematical operations such as sum, maximum on numeric fields and to concatenate text fields:-

Attributes in QGIS

Attributes in QGIS

  • Page 1 of 1 ( 17 posts )

Back to Top