You are on page 1of 213

Community

Service with Web-Based GIST

Table of Contents
Introduction

Exploring Spatial Data Models using QGIS

Relational Database Management Systems

PostgreSQL/PostGIS Installation

2.1

Relational Databases

2.2

pgAdmin and PostgreSQL Exercise

2.3

Spatially Enabled Relational Databases

The Idea of Spatial Databases and PostGIS

3.1

Building the IFRI Spatial Relational Database using PostGIS

3.2

Mapping Raster Data

Raster datasets - formats and finding them on the Internet

4.1

Georeferencing a Scanned Paper Map or Image

4.2

Key Postgres and PostGIS steps from Weeks 2 and 3

4.3

Introduction to Web Mapping and Serving Geospatial Data on the Web

Elements of a Webmap

5.1

The Idea of Tiled Maps

5.2

Introduction to Serving Geospatial Vector Data using Geoserver

5.3

Static Data on the World-Wide Web

Web Publishing

6.1

HyperText Markup Language (HTML)

6.2

Cascading Style Sheets (CSS)

6.3

Scalable Vector Graphics (SVG)

6.4

Dynamic Data on the World-Wide Web

Glossary

Community Service with Web-Based GIST

Community Service with Web-Based


Geographic Information Science and
Technology (GIST)
Course Description
Maps on the World-Wide Web are so commonplace that its hard to find a commercial web
site without one, and many sites have mapping as a central focus. Even individuals can put
points on a map relatively easily. But when it comes to full-featured interactive maps that
leverage political boundaries, census data, landscape features, elevation imagery, et al., to
help analyze and evaluate custom information, there is still a significant level of geographic
understanding and programming expertise required to pull it all together important skills
for the twenty-first century.
Geographic Information Science and Technologies (GIST) have been present on the Web
from early on, and now take the form of a spatial data infrastructure that brings together map
servers, databases, and client software with a glue of open protocols for exchanging
information. Commercial products from Google and Esri predominate, but open-source
technologies are available that make it possible to customize the user mapping experience
with little cost. Open-access data is becoming increasingly available, whether from
government, educational institutions, or crowd-sourced. Many nonprofit organizations and
educational institutions in our communities can benefit from inexpensive GIST solutions that
can help illuminate the difficult problems they tackle and facilitate their solutions.
In this course you will work in teams to design and implement a Web-based open-source
GIST project for a community organization or one of the Five Colleges. In the process you
will learn and understand how the World-Wide Web works, the nature of geographic
information and how it is processed and visualized on the Web, and the importance of open
standards, software, and data. In addition you will be able to analyze and evaluate possible
approaches to geospatial problems.

Introduction

Community Service with Web-Based GIST

The course is open to all Five College students with some some background in GIS, such as
NRC 585, Geography 352, or courses offered by one of the other Five Colleges. Computer
programming is helpful but not required.

Learning Goals
Students will understand how the World-Wide Web works, the nature of geographic
information and how it is processed and visualized on the Web, the importance of open
standards, software, and data, the value of teamwork, and how to creatively apply their
knowledge of GIST and Web programming to benefit their community.

Learning Outcomes
Students can create interactive maps on the Web using a spatial data infrastructure,
specifically:
composite geographic layers to facilitate visual analysis;
join tables of information from different sources
build a spatial database and use spatial selections to focus analysis;
Introduction

Community Service with Web-Based GIST

display raster data sets and georeference scanned maps;


transform vector and raster data into more useful representations;
mark up web pages that contain text, imagery, and vector graphics;
programmatically create web pages;
add interactivity to web pages to allow the choice of data to display;
send requests back to web servers for selection and updates of data.

Community Service with Web-Based


Geographic Information Science and Technology (GIST)


Next: 1. Exploring and Understanding
Spatial Data Models

Introduction

Community Service with Web-Based GIST

Chapter 1. Exploring and Understanding


Spatial Data Models
Lesson Goals
Students get an introduction to the desktop geographic information system software QGIS
and learn how to access live data on the Internet using Web Mapping Services (WMS) and
Web Feature Services (WFS).

Lesson Outcomes
Students can:
Use QGIS (the basics)
Connect to external data through WMS and WFS services
Distingush between WMS and WFS
Document Version: 10/17/2015
Revision author: Charles M. Schweik, UMass Amherst, and Andy Anderson, Amherst
College
Attribution:
This material is based on earlier exercises developed by Kurt Menke GISP, Birds Eye View
GIS, and Richard Smith, Ph.D.
Texas A&M University - Corpus Christi and offered through the GeoAcademy educational
portal (http://fossgeo.org/free-qgis-courses/) and the Spatial {Query} Lab at Texas A&M
Corpus Christi.

The development of the original document is funded by the Department of Labor (DOL)
Trade Adjustment Assistance Community College and Career Training (TAACCCT) Grant
No. TC-22525-11-60-A-48; The National Information Security, Geospatial Technologies
Consortium (NISGTC) is an entity of Collin College of Texas, Bellevue College of
Washington, Bunker Hill Community College of Massachusetts, Del Mar College of Texas,
Moraine Valley Community College of Illinois, Rio Salado College of Arizona, and Salt Lake
Community College of Utah. This work is licensed under the Creative Commons Attribution

Exploring Spatial Data Models using QGIS

Community Service with Web-Based GIST

3.0 Unported License. To view a copy of this license, visit


http://creativecommons.org/licenses/by/3.0/ or send a letter to Creative Commons, 444
Castro Street, Suite 900, Mountain View, California, 94041, USA.
This document was original modified from its original form by Kurt Menke and continues to
be modified and improved by generous public contributions.

Generic datasets used (other instructors can utilize their own site specific data by simply
following these naming conventions in your data files):
TOWNS.shp (a polygon shapefile of towns and cities for a US state)
MAJOR_ROADS.shp (a line shapefile of major roads for a US state)
Landsat_image.tif (a Landsat image for the area)

Students: Before proceeding, download and unzip the Week 1 class data from the
Moodle website.

Introduction
In this lab, students will explore and manage geospatial data using QGIS, an example of
Free and Open Source for Geospatial (FOSS4G) software. It comes with two separate
applications, QGIS Browser and QGIS Desktop. The former is an application
analogous to Windows Explorer that is designed to preview and manage geospatial data,
similar to ESRIs ArcCatalog. QGIS Desktop is the companion application used to
perform spatial analysis and make maps, similar to ESRIs ArcMap.
Your Windows installation makes QGIS Desktop and QGIS Browser available with
shortcuts on your desktop, but on Macs QGIS Browser is hidden inside of QGIS
Desktop, which is probably in your folder Applications:
1. Right-click on QGIS.app and in its contextual menu select Show Package Contents.
2. Navigate to Contents/MacOS/bin/QGIS Browser.app .
3. Right-click on QGIS Browser.app and in its contextual menu select Make Alias.
4. Drag the alias into the folder Applications.
While it is sometimes useful to use QGIS Browser, this lab will instead focus on QGIS
Desktop, and use its built-in Browser Panel.

Exploring Spatial Data Models using QGIS

Community Service with Web-Based GIST

For many students, this exercise will be simple and very intuitive, since QGIS operates very
similar to other GIS software they may already be familiar with. This lab includes the
following tasks:
Task 1 Learn to work with QGIS Desktop.
Task 2 Become familiar (or a brief refresher) with some common geospatial data
models.
Task 3 View traditional data stored on your local computer
Task 4 View data available over the Internet through Web Mapping Service and Web
Feature Services using QGIS Desktop.
We are assuming students have some experience with GIS coming into this course. If you
do, you probably have used ESRIs ArcGIS. For interested students, we are providing a
couple of pretty recent links to comparisons done between ArcGIS and QGIS:
http://dragons8mycat.com/2015/02/qgis-v-arcgis/
http://www.xyht.com/spatial-itgis/qgis-v-arcgis-rematch/
http://gisgeography.com/qgis-arcgis-differences/
Most students taking this course will already know that Geographic Information Systems
model the real world with representations of objects such as lakes, roads, and towns.
Geospatial data models are the means used to represent these features. They are
composed to two parts: spatial features and attributes that when combined, create a model
of reality.

Exploring Spatial Data Models using QGIS

Community Service with Web-Based GIST

Two parts of the geospatial data model


And as you also probably know, there are two main geospatial data models: vector and
raster.
Vector Data Model best for modeling discrete objects. Vector data comes in three basic
forms: point, line, and polygon.
Raster Data Model this model is best for modeling continuous objects. A raster is
composed of a matrix of contiguous cells, with each cell (pixel) holding a single numeric
value. Each value might represent reflected color as in a photograph, elevation in feet or
meters, or other data.

Task 1 Familiarize yourself with QGIS Desktop


In this task, you will become familiar with QGIS Desktop. The first step in working on a
project with geospatial datasets is to organize your workspace. It is important that we
organize datasets logically on the computer and make them easy to find. In this task, you will
obtain a copy of the lab data and explore how the data is organized using the Browser
Panel.

Exploring Spatial Data Models using QGIS

Community Service with Web-Based GIST

For this lab, we will explain how to open and use QGIS using the Mac Operating
System and QGIS desktop version 2.8 (Wien).
1. Open QGIS Desktop. The way you open it will vary depending on your operating
system.
2. The QGIS interface is simple and clean, with a large panel to display a map, several
other panels, usually along the left side of the Map Panel, and a set of toolbars, usually
positioned on the top and left.

QGIS Desktop
Any of the panels can be docked to and undocked from the QGIS Desktop window.
To undock a panel, double-click its title bar (outlined in figure below), whence it will pop
out of its location into a new window. You can also click and drag it away from the sides;
when you release your mouse button, the panel will be floating freely.

Area to Double-Click or Drag When Undocking a Panel


To dock a floating panel, double-click its title bar, and the panel will return to its previous
location. You can also drag it to the location where you want it, wait for the other panels
to move out of the way to leave a gray space, and release.
3. To reset the QGIS Desktop window back to the default settings:

Exploring Spatial Data Models using QGIS

10

Community Service with Web-Based GIST

i. Menu Settings > Options;


ii. In the dialog Options, click on the tab

System;

iii. In the section QSettings > Reset user interface to default settings (restart required),
click on the button Reset;
iv. Confirm by clicking the button OK, and QGIS Desktop will restart.
4. One of the panels is labeled Browser Panel. If it is not visible you can display it by
menuing View > Panels > Browser Panel.
Within the Browser Panel, various sources of data are listed, beginning with the current
projects home folder (if youve saved it) and followed by your computers Home folder.
Both can be expanded to show their files and folders by clicking on the buttons / and
/ at the left of each element.
These folders are followed by references to different drives and network drives or
volumes. (NOTE: your machine may have a different set and number of drives listed
here. This is fine.) Below the drives are various kinds of network database connections,
which we will be learning about in next weeks material. There are no connections to
any databases at this point.
5. In the Browser Panel, locate the lab folder where you stored your data (gisdata). Your
browser might look something like the figure below.

Lab Data in QGIS Desktop


Right-click on your data folder and select Add as a favourite, to provide quick access to
it in the Browser Panel.
The

icon indicates that the TOWNS dataset is a vector layer. The other common

icon next to files, , is used to represent raster data but is also used for other files
(such as XML files).

Task 2 - Become familiar with geospatial data models


Exploring Spatial Data Models using QGIS

11

Community Service with Web-Based GIST

Now that you are familiar with the basic layout of QGIS Desktop, we will explore some
geospatial data that is stored on your local computer.
1. Lets take a closer look at the layer

TOWNS.shp currently listed in the Browser

Panel in the data folder. To view its metadata, right click

TOWNS.shp and in its

contextual menu select Properties. The dialog Layer Properties will appear:

Metadata in QGIS Desktop


In addition to data models (vector and raster) we have to understand file formats. Some
file formats are designed to store vector data and others, raster data. Under Storage
type of this layer we can see that it is an ESRI Shapefile, one type of vector file format.
In fact they are (as of this writing) probably the most common vector file format a
proprietary format that has become a defacto-standard because it is so widely used. As
you may know, a shapefile is actually a collection of files on the computer with a
common name, but different extensions.
An individual shapefile can only contain one geometry type (polygon, line, or point). In
this case, there are 611 polygons stored in this shapefile (many of the 351
Massachusetts cities and towns have disjoint islands, each one a separate polygon).

Exploring Spatial Data Models using QGIS

12

Community Service with Web-Based GIST

Also scroll down and note the Layer Spatial Reference System, which QGIS elsewhere
refers to as the Coordinate Reference System (CRS). Although this layer is projected in
NAD83 / Massachusetts State Plane Mainland, QGIS doesnt provide that description,
instead displaying the details of how the projection is constructed. Importantly, the linear
unit is described by the phrase +units=m , meaning it is meters.
2. Now select

MAJOR_ROADS.shp and view its properties. Youll see that this is also

an ESRI Shapefile but that it is a line dataset with 30 features.


3. Now, in the browser, right click on the dataset Landsat_image.tif, and look at its
properties. It is a raster dataset in GeoTiff format, with 30-meter pixel resolution.
4. The QGIS Desktop interface is a little cluttered by default, so close any panels other
than the Layers Panel and the Map Panel.
In particular, close the Browser Panel (which we used in the previous task), by clicking
on the X button (on Windows in the upper right corner, on Macs in the upper left corner).

Close Browser Panel Button


Note: If you want to restore the Browser Panel (or other panels or toolbars), right click
on any open gray space in any toolbar, e.g. to the right of the button What's This, and
a contextual menu will appear.

Exploring Spatial Data Models using QGIS

13

Community Service with Web-Based GIST

Select Browser and it will reappear.


With the QGIS Desktop interface customized, lets add some data.

Task 3 - Viewing geospatial data in QGIS Desktop


Now that you know how geospatial datasets are stored on your computer, lets see what the
data they contain looks like.
1. You should still have QGIS Desktop open. If you dont, invoke it again.

Exploring Spatial Data Models using QGIS

14

Community Service with Web-Based GIST

QGIS Desktop
Note the status information in the lower right corner describing the coordinate reference
system (CRS) that is currently being used by QGIS, by default EPSG: 4326. This is
the WSG 84 geographic CRS, which is one of roughly 2,700 known to QGIS. Its
designation is from one of the two main CRS categorization systems that you will see
referenced by QGIS, the European Petroleum Search Group (EPSG) and the Institut
Gographique National de France (IGNF).
Like other geographic CRS, WSG 84 is displayed with a Plate Carre projection, i.e. x
= longitude and y = latitude .

2. QGIS has Add Data buttons for both vector and raster files, as well as for data sources
such as databases and Internet map servers. These are located, by default, in the
toolbar along the left side of the window.
Click the button Add Vector Layer.
Alternatively, you can menu Layer > Add Layer > Add Vector Layer.

Exploring Spatial Data Models using QGIS

15

Community Service with Web-Based GIST

*Add Vector Layer Dialog*


3. The dialog Add vector layer will now appear. Lets add one of the ESRI shapefiles,
which is a file-based dataset. In the section Source type, click the button File. Then in
the section Source, click the button Browse.
4. The dialog Open an OGR Supported Vector Layer will now appear. Navigate to your
course data folder.
(Note: OGR is a FOSS4G project with the sole purpose to read and write geospatial
vector data files. The meaning of OGR is historical. If you care, it used to stand for
OpenGIS Simple Features Reference Implementation. For more information, you can
read about it at http://trac.osgeo.org/gdal/wiki/FAQGeneral#WhatisthisOGRstuff.)

Exploring Spatial Data Models using QGIS

16

Community Service with Web-Based GIST

Open an OGR Supported Vector Layer


The file list defaults to all files, including several shapefiles in the course data folder.
But take a moment to see the other available file type options by clicking on the filter
menu Files of type:. Did you know there were so many different types of geospatial
data?

OGR Supported Vector Formats


Exploring Spatial Data Models using QGIS

17

Community Service with Web-Based GIST

After reviewing, select ESRI Shapefiles to see just that type of file.
5. Select TOWNS.shp and click the button Open.
6. Now back in the dialog Add vector layer, click the button Open to add the data to
QGIS Desktop (see figure below).

Add vector layer


You will now also see the layer

TOWNS in the Layers Panel and the map features

displayed in the Map Panel. Vector GIS layers will come in with random colors. You will
learn how to change layer styling in a future exercise.
Also note that the displayed CRS has changed to USER: 100000. This is because
QGIS has a default setting to use on-the-fly projection when a first layer is added
whose projection is known. In this case, QGIS interprets the projection information in
the shapefiles .prj file, which is in Well-Known Text format, but doesnt recognize it to be
the same as EPSG 26986, NAD83 / State Plane Massachusetts Mainland (as we noted
previously). It therefore assigns it a User designation.
7. Lets examine the new layers attributes. In the Layers Panel, right-click on the layer
TOWNS. In its contextual menu, select the menu item Open Attribute Table (shown in
figure below).

Exploring Spatial Data Models using QGIS

18

Community Service with Web-Based GIST

Layer Contextual Menu


8. The attribute table opens. If you recall from exploring this dataset with QGIS Browser, it
has 351 features (351 polygons). The attribute table has 351 corresponding records.
The table that appears will look similar to the figure below. As you may know, each row
corresponds to one polygon. The columns are things we know about the polygons such
as town name or its population for a certain year (see figure below).

Exploring Spatial Data Models using QGIS

19

Community Service with Web-Based GIST

Attribute Table
9. Close the Attribute Table by clicking the X button in the upper right hand corner.
As you may know from other GIS software experience, another way to interact with both
the spatial features and the attributes is the Identify button.
10. Click the button Identify
11. Click on one of the features on the map. The Identify results panel (shown in figure
below) shows you the attributes for the feature you clicked on. Note: The Identify results
panel may initially be docked or floating.

Identify Results

Exploring Spatial Data Models using QGIS

20

Community Service with Web-Based GIST

When you double-click on the little table icon under (Actions), it will bring you to the
Feature Attributes window where you can see the attribute data for the feature you
selected.

Identify Feature Attributes window


Now, lets add Raster data to QGIS Desktop.
12. Click the button Add Raster Layer
Alternatively, click Layer | Add Layer | Add Raster Layer.
13. The Open a GDAL Supported Raster Data Source window opens (displayed in figure
below). This is a very similar workflow to adding vector data.

Open a GDAL Supported Raster Data Source

Exploring Spatial Data Models using QGIS

21

Community Service with Web-Based GIST

14. Whereas QGIS used OGR to open vector data files, here it uses another FOSS4G
software library called GDAL. GDAL (sometimes pronounced Gee-dall) stands for
Geospatial Data Abstraction Library is used for reading and writing raster datasets. In
other words, it is a cross platform translator library that supports a variety of raster
formats, such as GeoTIFF, Erdase Imagine, SDTS, ESRI Grids, MrSID, JPG2000,
etc.). It is the primary data access engine for many applications including MapServer,
GRASS, QGIS, and OpenEV. It is also utilized by packages such as OSSIM, Cadcorp
SIS, FME, Google Earth, VTP, Thuban, ILWIS, MapGuide and ArcGIS. (source:
http://www.osgeo.org/gdal_ogr)
15. The windows raster data filter is set to All Files by default, so you see the entire
contents of the folder (Figure below).

[GDAL] All Files


16. Open the files of type filter and see how many formats it will read! More than 50
different raster data formats! In GIS there are many more raster file types than vector.

[GDAL] GeoTiff

Exploring Spatial Data Models using QGIS

22

Community Service with Web-Based GIST

17. Choose the raster dataset Landsat_image.tif and click the button Open.
18. Drag it to the bottom of the layer list and turn the fill color off on the Towns layer. Right
click on TOWNS, Properties, Style, Click on Simple Fill, Fill down arrow, change to
Transparent Fill. Set the Border to red. Hit OK. Your map screen should look similar to
the below.

As you may know, this is an example of a raster dataset in QGIS. Like a photograph, it
is composed of cells. This raster is a Landsat true color satellite image of Western
Massachusetts, Connecticut and extends all the way down to display a portion of Long
Island. The image was taken on July 22, 2002.

Toolbars and Windows Contextual Menu


If you dont have the QGIS Browser panel open, open it (recall you can right click next to the
help icon and select the Browser option. It will reappear). Scroll down the Browser panel and
note the Favourites item.
Data is often stored deep inside a series of folders. It is often tedious and time consuming to
navigate deep inside the folders to gain access to the data. Favourites provide a way to
create a shortcut directly to any folder so that you have one-click access to any folder. Lets
create a favorite to our lab folder for practice.

Exploring Spatial Data Models using QGIS

23

Community Service with Web-Based GIST

1. Navigate to the lab data folder in the Browser panel. Right-click on it and choose Add as
a Favourite (see figure below). Note: Currently this functionality is reserved only for the
Browser tab in QGIS Desktop. However, once it is set it will show up as a Favourite
in QGIS Browser as well.

Add as a Favourite
2. Now expand Favourites and you will see your lab folder listed there. You can remove a
favourite anytime by right-clicking on it and choosing Remove favourite. Note: You can
drag data from the QGIS Browser application to QGIS Desktop as well to add the
data to the map.

Task 4 - View data available over the Internet through Web


Mapping Service and Web Feature Services using QGIS
Desktop.
In the lecture portion of this first class, we discussed Web Feature Services and Web Map
Services (WMS). Recall: A Web Feature Service (WFS) is a standard that allows the
sharing of geographic map data at a feature level (i.e. sharing vector-based data such as
ESRI Shapefiles (.shp)). This standard allows the user to request specified geographic data
from a client and received the requested data via the web.
A Web Map Service (WMS): is a standard where geographic data can be displayed across
the web and multiple platforms. This standard does not provide the actual geospatial data;
instead it just provides a georeferenced image (e.g., PBG, JPEG or GIF) of the data.
Utilizing WMS enables a user to access different geospatial databases without needing the
original source data on local machines.

Exploring Spatial Data Models using QGIS

24

Community Service with Web-Based GIST

A variety of organizations provide live GIS data over the web as these kinds of services. In
our state, the MassGIS organization is an important provider of data, and they offer these
services.
Take a minute to read the overview of MassGIS Web Mapping Services and Applications
page, available at:
https://wiki.state.ma.us/confluence/display/massgis/Overview+of+MassGIS+Web+Mapping+
Services+and+Applications
MassGIS offers their data services through two different servers: (1) the proprietary ArcGIS
Server, and (2) the open source GeoServer. It is the latter that we will use in this course.
Lets try out MassGIS Web Mapping Service (WMS).
1. In the QGIS Browser, scroll down to where WMS is listed, and right click. You should
see a New Connection option appear.

2. Give your WMS connection a name. In this case: MassGIS GeoServer WMS

Exploring Spatial Data Models using QGIS

25

Community Service with Web-Based GIST

3. Add the associated WMS URL. In this case:


http://giswebservices.massgis.state.ma.us/geoserver/wms
Your screen should look like this:

4. Press OK
5. In the QGIS Browser, expand the WMS entry (press the little triangle) and you should
see your new WMS entry listed, similar to the below.

Exploring Spatial Data Models using QGIS

26

Community Service with Web-Based GIST

Click on the triangle next to MassGIS GeoServer WMS and it will attempt to connect to
the MassGIS GeoServer. Eventually, you should see the below:

There are many, many layers you could choose to add to your QGIS map layers.

Exploring Spatial Data Models using QGIS

27

Community Service with Web-Based GIST

Suppose we were interested in identifying the watershed subbasin surrounding the


Quabbin water supply Bostons water supply.
In the QGIS Browser, double click on the Subbasins option. In a few seconds
(hopefully!) the approximately 2300 subbasin polygons will appear at the top of the
Layers table of contents. Polygons will appear, although remember, this is a Web Map
Service. If you look at the properties of this layer, you will see it is singleband color
data this is not a vector layer. It is rather, a picture of the data. Zoom into the area of
the Quabbin as shown in the figure below.

If you right click on the Subbasins raster entry, in the contextual menu you will see that there
isnt an attribute table to use. While the layer looks like a vector polygon layer, it is actually a
raster file served using WMS via a GeoServer server over the Internet that is hosted by the
MassGIS organization.

Now lets try to connect to MassGIS Web Feature Service


(WFS)

Exploring Spatial Data Models using QGIS

28

Community Service with Web-Based GIST

Recall that with a WFS, you are requesting to see the actual geographic features, rather
than a picture of the data. That means you will be able to open the associated attribute table
as well of this vector data.
1. In the QGIS Browser, close the long list of MassGIS data by slecting the triangle next to
WMS. You should see the list go away or get minimized.
2. Right click on WFS in the QGIS Browser to bring up the New Connection contextual
menu.
3. Enter a name such as "MassGIS GeoServer WFS" for name and
"http://giswebservices.massgis.state.ma.us/geoserver/wfs" for the URL. Click OK. Your
QGIS Browser should look similar to the below.

4. Click on the triangle next to the MassGIS GeoServer WFS entry. You will see it expand
as shown in the Figure below:

Exploring Spatial Data Models using QGIS

29

Community Service with Web-Based GIST

5. Scroll down the list and choose Subbasins. This brings up the same data as did our
WMS exercise above, but in this case you are seeing the actual subbasin polygons.
Your QGIS map screen should look something like the below:

Exploring Spatial Data Models using QGIS

30

Community Service with Web-Based GIST

6. If you right click on this entry in the Layers list, you will see the Open Attribute Table
option --

. Click it.

7. Because this is a Web Feature Service, these are vector polygons and its
corresponding attribute table is available. You should see something like the below.

Exploring Spatial Data Models using QGIS

31

Community Service with Web-Based GIST

8. You can click on individual records in the left most column and their individual polygons
will appear. For instance, if you are still zoomed in around the Quabbin Reservoir click
on one of the Chicopee entries and you should see one of those associated subasins
selected.
Note that there are many Web Mapping and Feature Mapping Services available these
days!
For example, try and connect to one or more of the USGS Web Mapping Service
options listed on their Seamless website:
http://seamless.usgs.gov/services.php
It takes some sleuthing to find the correct URL to use for the WMS. For example, try out the
National Land Cover Database 2011 map service. See if you can find this link in the
extensible markup language (XML) file they provide for WMS:
http://isse.cr.usgs.gov/arcgis/services/LandCover/USGS_EROS_LandCover_NLCD/MapSer
ver/WmsServer?
Add that WMS connection and see if you can get it operational in QGIS or try another option,
such as the USGS Geologic Map data. For example, in the Figure below, we are displaying
Massachusetts fault lines via a USGS WFS.

Exploring Spatial Data Models using QGIS

32

Community Service with Web-Based GIST

See this page for more on that available data:


http://mrdata.usgs.gov/geology/state/state.php?state=MA
The specific WMS link is: http://mrdata.usgs.gov/services/ma?
service=WMS&version=1.1.1&request=GetCapabilities
Or, the WFS version: http://mrdata.usgs.gov/services/ma?
service=WFS&version=1.0.0&request=GetCapabilities
If time permits, take some time to see if you can find other WMS or WFS services on the
web for the USA or for Massachusetts specifically and see if you can get it operational on
your QGIS system.

Now lets try to connect to our class Web Mapping Service


(WMS) and our Web Feature Service (WFS)
To finish up this exercise, now lets access our Landsat data and our towns layer using our
own class WMS and WFS. This uses our own Geoserver which we will talk about in a future
class.
Connect to our class WMS and look at the Landsat and towns layer using this service
To do this, you need to create another new WMS connection in your QGIS browser. The
information you need is the following:
Name: UMass WMS URL: http://nrcwg01.eco.umass.edu:8080/geoserver/wms
Once you connect to the above, you should see in your QGIS browser a new entry under
WMS for the UMass WMS server. Below that, you should see an entry for "Landsat_image"
and also for the "Towns".
Click on these and load them into your QGIS map. The Landsat image should look the same
as before other than it is stored on a server instead of your own local hard drive. The Towns
layer should look, maybe, different. How?
With a little sleuthing, you may notice that while it looks like a vector layer, it isnt. It is an
image that displays that vector layer. So you cant change the fill color or make it no fill. You
are stuck with it blanketing over the Landsat image. Thats the difference, again, between a
WMS service and a WFS service.
Connect to our course map server
Now lets try and get the towns layer using our own class servers WFS.
In the QGIS browser, create a new WFS connection.

Exploring Spatial Data Models using QGIS

33

Community Service with Web-Based GIST

To set it up, you need the following information:


Name: UMass URL: http://nrcwg01.eco.umass.edu:8080/geoserver/wfs
Once the connection is made, you should see two layers below the umass WFS:
major_roads and towns.
Click on the towns layer and it should eventually appear in your QGIS map screen. But
change the properties and turn off the fill. Notice you can also open the attribute table.

Do you want more on the specific operations of QGIS?


There is a good set of tutorials available at:
http://docs.qgis.org/2.8/en/docs/training_manual/
We encourage you to do more on your own, especially if you feel you need it!

Task 5 Upload a screenshot of your QGIS screen to


Moodle
To complete this exercise, take a screen shot of your QGIS screen and upload it in Moodle
under Week 1s turn-it-in Exercise 1 option to get credit for this exercise.

Conclusion
In this exercise you explored datasets that use the two common geospatial data models:
vector and raster. You have also used the QGIS Browser to preview datasets and in
particular, you worked with some externally served data using Web Mapping Services and
Feature Mapping Services, often served by an external server called GeoServer.

Chapter 1: Exploring and Understand Spatial Data Models


using QGIS

Previous:
Course Overview

Exploring Spatial Data Models using QGIS

34

Community Service with Web-Based GIST

Next:
2. Introduction

Exploring Spatial Data Models using QGIS

35

Community Service with Web-Based GIST

Chapter 2: Relational Database


Management Systems
Lesson Goals
Students understand fundamental relational database theory and are able to develop
relational databases using the PostgreSQL database engine and the pgAdmin administrative
interface.

Lesson Outcomes
Students understand:
The benefits of using relational databases
The three relationship types found in relational databases
The use of Entity-Relationship diagrams for planning the structure of a relational
database
The role of Primary and Foreign keys in setting up relationships
Understand fundamental Structured Query Language (SQL)
Using pgAdmin, students can:
Create PostgreSQL tables
Use the query tool to run various SQL queries such as create tables or insert data
commands
Use the graphical query builder to do queries and joins between tables to get answers
to questions
To begin the work associated with this chapter, go to the next chapter section.

Chapter 2: Relational Database Management Systems


2. Introduction

Previous:
1. Exploring Spatial Data Models using QGIS

Relational Database Management Systems

36

Community Service with Web-Based GIST

Next:
2.1 PostgreSQL/PostGIS Installation

Relational Database Management Systems

37

Community Service with Web-Based GIST

Chapter 2: Relational Database


Management Systems
2.1 PostgreSQL/PostGIS Installation
PostgreSQL is one of the two major open-source relational database management systems
(RDBMS).
PostgreSQL runs as a server, waiting in the background of your computer for requests for
information from its databases.
The application pgAdmin runs in the foreground of your computer and provides a visual
management console that lets you interactively administer PostgreSQL.
PostGIS is a set of database structures and functions that spatially enable PostgreSQL.

Setting Up Postgres on Macintosh


Postgres.app is an application that lets you easily start and stop PostgreSQL as needed,
and includes PostGIS.
Installing PostgreSQL and PostGIS
1. Download the most recent version of Postgres.app from postgresapp.com.
2. Drag the application to your folder Applications.
3. Double-click Postgres.app.
Its icon wont appear in the Dock like other applications, instead it runs as a background
application and adds the

Postgres menu at the top of the screen. But for easier

startup, you may want to drag Postgres.app into the Dock.


Configuring Postgres.app
1. From the menu

Postgres, select the menu item Preferences.

PostgreSQL/PostGIS Installation

38

Community Service with Web-Based GIST

2. To make Postgres.app somewhat more noticeable when it starts up, check on Show
Welcome Window when Postgres starts.
3. Since youre using your computer for lots of other things, you might want to check off
Start Postgres automatically after login. Youll then have to start it up manually when
you want to work with it.
4. Postgres will store your databases in the Data Directory (username should be your
username, of course). The default location in your hidden Library folder is an OK place
for it as long you know how to find it (click the button Open in Finder).
5. Close this window.
Installing pgAdmin
Once Postgres.app is in place, pgAdmin should be installed and opened:
1. Download the most recent version of pgAdmin from pgadmin.org, which is provided
as a disk image (.dmg).
2. Open the disk image and drag pgAdmin to your folder Applications.
3. You may want to also drag pgAdmin from Applications into your Dock for easy
access (not from the disk image!).
4. Because pgAdmin is from a developer unknown to Apple, the Mac will prevent its use
unless you right-click (control-click) it to open its contextual menu and select the menu
item Open. After this you can also double-click it (or single-click it in the Dock).

Setting Up Postgres on Windows


Determining the Version of Windows
For all Windows software, get the 64-bit version unless you are still running a 32-bit
Windows system. To determine this:

PostgreSQL/PostGIS Installation

39

Community Service with Web-Based GIST

1. Menu Start;
2. Right-click (control-click) Computer to bring up its contextual menu;
3. Select the menu item Properties;
4. In the resulting dialog View basic information about your computer, in the section
System, review the value of System type.
Installing PostgreSQL and pgAdmin
1. Download the most recent version of PostgreSQL from EnterpriseDB.com.
2. Open the installer from wherever it was downloaded and follow its instructions. Use the
default values, but:
i. Note the location of the Data Directory, probably in C:\Program
Files\PostgreSQL\9.5\data ;

ii. Dont start up the StackBuilder application for now.


Installing PostGIS
1. Download the PostGIS executable from OSGeo.org.
2. Open the installer from wherever it was downloaded and follow its instructions. Use all
of the default values.
Starting pgAdmin
1. Menu Start;
2. Click All Programs;
3. Click the folder PostgreSQL;
4. Click pgAdmin.

Postgres Configuration with pgAdmin


The application pgAdmin looks very similar on both Macintosh and Windows computers.
When you open it you should see an object called Server Groups in the left-side pane,
known as the Object Browser.
If you are on Windows, you may also see a PostgreSQL server connection listed. If
necessary, click the disclosure buttons

to the left of the objects Server Groups and

Servers to see it. The server may be called PostgreSQL 9.5 as in the image below.

PostgreSQL/PostGIS Installation

40

Community Service with Web-Based GIST

The server name will be followed by the description (localhost:5432) , which means that
the hostname of the computer where the server is located is localhost, which is your local
computer, and it is communicating over port 5432. If you select this server, this information
and more will appear in the top-right Information Pane in the tab Properties.
One other important bit of information here is the username, here postgres . This is the
superuser, with authority to do anything in the database server, and is a login role that is
created on installation.
Creating a New Connection to the PostgreSQL Server
If you installed the PostgreSQL software on Macintosh, you need to create a new server
connection for the postgres login role:
1. In the toolbar, click the button Add a connection to a server.
2. In the dialog New Server Registration, click the tab Properties:

PostgreSQL/PostGIS Installation

41

Community Service with Web-Based GIST

3. In the text field Name, provide a descriptive name that will distinguish it from other
server connections, e.g. localhost - postgres.
4. In the text field Host, type localhost.
5. In the text field Username, type postgres.
6. Click the button OK.
7. The object localhost - postgres should now appear in the Object Pane. In the future
you can double-click this object to connect to the server with the postgres username.
Connecting to the PostgreSQL Server
To connect to the PostgreSQL server as the user postgres , simply double-click that server
connection in the Object Browser.
If pgAdmin connects correctly, the server icon in the Object Browser should change from
to , and underneath it a number of objects will appear:

PostgreSQL/PostGIS Installation

42

Community Service with Web-Based GIST

Both Macintosh and Windows users will see a database postgres and a login role (aka
user) postgres you may first have to open the objects Databases and Login
Roles, respectively. In addition, Macintosh users will see one of each with their username,
also created on installation.
Creating a Personal User
If you installed the PostgreSQL software on Windows, you should also create a user for your
own work, as you dont want to be postgres for that accidental changes to the postgres
database can be very damaging. But you do need to be postgres to add another user:
1. Right-click (control-click) Login Roles to open its contextual menu.
2. Select the menu item New Login Role.
3. In the dialog New Login Role, click the tab Properties:

4. In the text field Role name, type in your username on your local computer.
5. Now click the tab Role privileges:

PostgreSQL/PostGIS Installation

43

Community Service with Web-Based GIST

6. Check on Superuser. Usually an ordinary user shouldnt have superuser privileges, but
this is necessary to use PostGIS.
7. Check on Can create databases.
8. Click the button OK.
Setting a User Password
The database postgres holds important general information such as which users can log
in, what their privileges are, and what databases they have created. To protect access to this
database, its very important to set a password for the user postgres, and write it down for
future reference!
1. Right-click (control-click) the user postgres to open its contextual menu.
2. Select the menu item Properties.
3. In the dialog Login Role postgres, click the tab Definition.

4. In the text field Password, type in a password, and then type it again. Do not use a %
character in the password!

PostgreSQL/PostGIS Installation

44

Community Service with Web-Based GIST

5. Click the button OK.


The next time you connect to this server with this login role, you will be asked for this
password.
Important: You should repeat this procedure for your personal login role and assign it a
password.
Disconnecting from the PostgreSQL Server
Now that were done with the login role postgres, disconnect it from the server:
1. Right-click (control-click) its name (e.g. PostgreSQL 9.5 or localhost) to open its
contextual menu.
2. Select the menu item Disconnect server.
Creating a New Connection to the PostgreSQL Server
Next, create a new connection for your personal login role:
1. In the toolbar, click the button Add a connection to a server.
2. In the dialog New Server Registration, click the tab Properties:

3. In the text field Name, provide a descriptive name that will distinguish it from your
previous server connection, e.g. localhost - , followed by your username.

PostgreSQL/PostGIS Installation

45

Community Service with Web-Based GIST

4. In the text field Host, type localhost.

5. In the text field Username, type your username.


6. In the text field Password, type your password (if you set one).
7. Click the button OK.
8. The object localhost - your_username should now appear in the Object Pane.
Double-click it to connect to the server.
Remember, the only difference between these two server connections is the login role used!
Creating a Personal Database
If you installed the PostgreSQL software on Windows, you need to create a personal
database for your own work:
1. Right-click (control-click) Databases to open its contextual menu.
2. Select the menu item New Database.
3. In the dialog New Database, click the tab Properties:

4. In the text field Name, type in your username.

PostgreSQL/PostGIS Installation

46

Community Service with Web-Based GIST

5. In the text field Owner, also type in your username.


6. Click the button OK.
Spatially Enabling a Database
To spatially enable your database, you must add the extension PostGIS. In other words,
PostGIS is an optional extension to PostgreSQL that must be enabled in each database
you want to use it in.
1. Select your database and open it to display the tree of objects.
2. Right-click (control-click) Extensions to open its contextual menu.
3. Select the menu item New Extension.
4. In the dialog New Extension, click the tab Properties:

5. In the text field Name, type in postgis. You should also be able to select it from the
menu at the far right of the field.

PostgreSQL/PostGIS Installation

47

Community Service with Web-Based GIST

6. Click the button OK.


7. The extension postgis should now appear in the Object Pane.
SQL Queries

As you
proceeded through the previous steps, you may have noticed various statements whizzing
by in the SQL pane. These are written in the most common database programming
language, Structured Query Language (SQL), which is pronounced either as sequel or by
spelling it out S-Q-L. These statements are built in response to the choices you made, and
in fact appear in the SQL tabs of the dialogs above. They are only executed when you click
OK.

PostgreSQL/PostGIS Installation

48

Community Service with Web-Based GIST

You can write and execute arbitrary SQL queries in pgAdmin. For example, to test that
PostGIS is operational in your database, you can call a function that prints out the version of
PostGIS that is installed:
1. Select the database where you want to run the SQL query, e.g. the one labeled with
your username.
2. In the toolbar, click the button Execute arbitrary SQL queries.
3. In the dialog Query - , click the tab SQL Editor:

4. In the text field below the menu Previous queries, you can paste any SQL command,
e.g. SELECT postgis_full_version(); .
5. Run the query by clicking on the button Execute query.
If PostGIS is operational you should see a description of its version in the Output pane.
Congratulations! You now have a PostgreSQL database with the PostGIS extension and
pgAdmin installed on your system. Proceed to the next set of pre-class material, where you
will learn more about SQL.

Chapter 2: Relational Database Management Systems


2.1 PostgreSQL/PostGIS Installation

Previous:
2. Introduction
Next:
2.2 Relational Databases

PostgreSQL/PostGIS Installation

49

Community Service with Web-Based GIST

Chapter 2: Relational Database


Management Systems
2.2. Relational Databases
Introduction:
In our experience teaching Introduction to GIS courses, it has become clear to us that many
or most students in programs outside of Computer Science have had little exposure to
Databases and, in particular, the idea of Relational Databases or Database Management
Systems. In these assigned readings, we are trying to give you that exposure. Moreover, as
you will see, in many GIS situations the GIS data are stored in relational database systems.
For example, in the proprietary world of ArcGIS, the Geodatabase is a method for storing
geospatial data in a database management system or DBMS. The desktop Geodatabase
uses the relational database package Microsoft Access to store its data. In enterprise,
larger scale GIS situations where multiple users are using the GIS at the same time, other
DBMS packages are used to store the Geodatabase, such as IBM DB2, Microsoft SQL
Server, Oracle or PostgreSQL (the database system you will be using in this course).
For this pre-class assignment, we are asking you to do some readings on Databases,
Database Management Systems, and the idea of Relational Databases.
The readings we are assigning are Open Educational Resources that is, Open Access and
available freely (as in cost) over the Web. You can read the individual chapters online, or can
download the entire book as a pdf and read it on an e-reader.

Assignment:
Read Chapters 1-4, 7-8, 15-16 (approximately 50 pages).
The entire book (pdf) is available at:
Database Design - 2nd Edition by Adrienne Watt and Nelson Eng. 2012. Open Educational
Resource book available at: http://opentextbc.ca/dbdesign01/open/download?
filename=Database-Design-2nd-Edition-1420760605&type=pdf
Individual chapters (web-page versions) are available here:

Relational Databases

50

Community Service with Web-Based GIST

Chapter 1: Before the Advent of Database Systems (pp 1-5)


http://opentextbc.ca/dbdesign01/chapter/chapter-1-before-the-advent-of-database-systems/
Chapter 2: Fundamental Concepts (pp 6-8)
(http://opentextbc.ca/dbdesign01/chapter/chapter-2-fundamental-concepts/
Chapter 3: Characteristics and Benefits of a Database (pp 9-12) http://opentextbc.ca/dbdesign01/chapter/chapter-3-characteristics-and-benefits-of-adatabase/
Chapter 4: Types of Database Models (pp 13-15) http://opentextbc.ca/dbdesign01/chapter/chapter-4-types-of-database-models/
Chapter 7: The Relational Data Model (pp 24-29)
http://opentextbc.ca/dbdesign01/chapter/chapter-7-the-relational-data-model/
Chapter 8: The Entity Relationship Data Model (pp 29-44)
http://opentextbc.ca/dbdesign01/chapter/chapter-8-entity-relationship-model/
Chapter 15: SQL Structured Query Language (pp 83-93)
http://opentextbc.ca/dbdesign01/chapter/sql-structured-query-language/
Chapter 16: SQL Data Manipulation Language (pp 93-112) http://opentextbc.ca/dbdesign01/chapter/chapter-sql-dml/

NOTE: The below are the key terms WE (Charlie, Andy, Jon, Walt) think are most important
for you to understand for the work we are doing in the Web-GIS class. These are useful to
understand for the quiz on these readings.
Chapter 2 key terms
database: a shared collection of related data used to support the activities of a particular
organization
database management system (DBMS): a collection of programs that enables users to
create and maintain databases and control all access to them
table: a combination of fields
Chapter 3: Key terms
concurrency control strategies: features of a database that allow several users access to
the same data item at the same time
data type: determines the sort of data permitted in a field, for example numbers only

Relational Databases

51

Community Service with Web-Based GIST

metadata: defines and describes the data and relationships between tables in the database
view: a subset of the database
Chapter 4: Key terms
relation: another term for table
relational model: represents data as relations or tables
Chapter 7: Key Terms
Attribute: principle storage unit in a database
column: see attribute
field: see attribute
record: contains fields that are related
relation: the technical term for table or file
row: see tuple
structured query language (SQL): the standard database access language table: see
relation
tuple: a technical term for row or record
Chapter 8: Key Terms
candidate key or primary key: a simple or composite key that is unique (no two rows in a
table may have the same value) and minimal (every column is necessary)
composite key: composed of two or more attributes, but it must be minimal
dependent entities: these entities depend on other tables for their meaning
derived attributes: attributes that contain values calculated from other attributes
entity: a thing or object in the real world with an independent existence that can be
differentiated from other objects; tables are entities in a relational database
entity relationship (ER) data model: also called an ER schema, are represented by ER
diagrams. These are well suited to data modeling for use with databases.
entity relationship schema: see entity relationship data model
foreign key (FK): an attribute in a table that references the primary key in another table OR
it can be null

Relational Databases

52

Community Service with Web-Based GIST

key (sometimes called a primary key): an attribute or group of attributes whose values
can be used to uniquely identify an individual entity in an entity set
null: a special symbol, independent of data type, which means either unknown or
inapplicable; it does not mean zero or blank
relationships: the associations or interactions between entities; used to connect related
information between tables
Chapter 15: Key Terms
Structured Query Language (SQL): a database language designed for managing data
held in a relational database management system
Chapter 16: Key Terms
DELETE statement: removes rows from a record set
JOIN: connects two tables on a column with the same data type
INSERT statement: adds rows to a table
SELECT statement: used to query data in the database
UPDATE statement: changes data in existing rows either by adding new data or modifying
existing data
wildcard: allows the user to match fields that contain certain letters.

Chapter 2: Relational Database Management Systems


2.2 Relational Databases

Previous:
2.1 PostgreSQL/PostGIS Installation
Next:
2.3 pgAdmin and PostgreSQL Exercise

Relational Databases

53

Community Service with Web-Based GIST

Chapter 2: Relational Database


Management Systems
2.3 pgAdmin and PostgreSQL Exercise
Introduction
In this exercise we will go through the process of creating a simplified version of the IFRI
database we discussed in class, using PostgreSQL (often called Postgres for short) as the
database engine using the pgAdmin software user interface to Postgres. We will establish
primary and foreign keys to create a one-to-many relationship between tables, enter some
data to test with and then finish by doing a query that joins two tables together.
Note that in this exercise, well consider a research Site in the IFRI database to be a town,
and in our data, Site 1 will be Amherst. The forests in this research visit will be three forest
properties that our university owns.
Lets begin!
1) Connect to your Postgres server
Right click on the PostgrSQL server listed in Object browser of your pgAdmin system.
Select connect Enter your password (should be server) Your pgAdmin screen should look
similar to Figure 1.

pgAdmin and PostgreSQL Exercise

54

Community Service with Web-Based GIST

2) Create the Site table in pgAdmin


Go to Object Browser Go to Databases, click on it to get context menu Select New
Database

4) Enter your database name. In this case, for this exercise, IFRI_DB. Press OK.
5) You should see the IFRI_db listed under the Databases object.

pgAdmin and PostgreSQL Exercise

55

Community Service with Web-Based GIST

6) If you click it, and expand it, you can see that it has some already default objects in
place, such as catalogs, Event Triggers, etc. Well ignore those items for now.

7) Now lets add our tables following the portion of the IFRI database ER design
shown in Figure 5, below.

pgAdmin and PostgreSQL Exercise

56

Community Service with Web-Based GIST

8) To do this, lets select the Tables option under the Schemas, Public option as
shown below.

pgAdmin and PostgreSQL Exercise

57

Community Service with Web-Based GIST

What are Schemas in PostgreSQL? According to the PostgreSQL online manual:


A database contains one or more named schemas, which in turn contain tables. Schemas
also contain other kinds of named objects, including data types, functions, and operators
There are several reasons why one might want to use schemas:
To allow many users to use one database without interfering with each other.
To organize database objects into logical groups to make them more manageable.
Third-party applications can be put into separate schemas so they cannot collide with
the names of other objects.
Schemas are analogous to directories at the operating system level, except that schemas
cannot be nested. (source: http://www.postgresql.org/docs/8.3/static/ddl-schemas.html).
What is the public part of schemas? By default, tables (and other objects) are automatically
put into a schema named "public" in postgres. Every new database contains such a schema.
9) Click Tables, and choose New Table

pgAdmin and PostgreSQL Exercise

58

Community Service with Web-Based GIST

10) Following our ER design (In Step 7, Figure 5), lets create the first table, Site. In
the New Table dialog box, type in its name, Site.

11) For simplicity, lets give the new Site table two columns. Click the Columns table
at the top of the Table window, and press add.

pgAdmin and PostgreSQL Exercise

59

Community Service with Web-Based GIST

12) Add the following three fields:


Field name: SiteID (primary key)
Data Type: serial
(Note: the serial data type allows the field to be automatically incremented every time a new
record is added. Serial is defined in Postgres as an integer field, but uses a sequence
generator to increment the values when new records are added to the table. For more
information on postgresql datatypes, see
http://www.postgresql.org/docs/8.1/static/datatype.html.)
Field name: Site_name
Data Type: character varying, length 30
Field name: Visitdate
Data Type: date
Now go to the Constraints tab. Note at the bottom it shows Primary Key. This allows you
to specify the primary key for the table. Click Add, lets call this pk_siteID

pgAdmin and PostgreSQL Exercise

60

Community Service with Web-Based GIST

Next choose the Columns tab at the top, and associate the pk_siteID primary key with the
column SiteID.

pgAdmin and PostgreSQL Exercise

61

Community Service with Web-Based GIST

Click OK and you should now have these two columns in your Site Table, with SiteID
identified as the primary key through the constraint name pk_siteID.

pgAdmin and PostgreSQL Exercise

62

Community Service with Web-Based GIST

Now that weve established the fields for this table, their data types, and the constraint for
the primary key to avoid duplicate records, click OK again to close the Site table
construction.
13) Follow the same steps as above to add the second table in our design (Figure 5)
the Forest table with four fields:
ForestID, datatype serial (primary key)
SiteID, datatype integer
Forest_name, datatype character varying, length 20

Make sure you set up the constraint and create a constraint called pk_forestID to set
ForestID as a primary key.
Question to ponder: Why would we want this foreign key to be defined as integer and not
serial like it is defined in the Site table? See Answer 1 at the end of this exercise.
14) Now add the third table in our simplified IFRI design, Plots
Plot_number, datatype integer
ForestID Question: what should this datatype be, given it is a foreign key to create the
relationship with the Forest Table? See Answer 2 below.
Tree_count, datatype integer
Like the other fields above, set up a constraint to establish pk_plot_number as the primary
key constraint for field Plot_number. Hit OK.
You should now see three tables in your Postgres database similar to what is shown below.

pgAdmin and PostgreSQL Exercise

63

Community Service with Web-Based GIST

15) Using SQL to do this instead of the GUI


Note that we could have created any one or all of these tables using the SQL. To see this,
lets create a second, duplicate, Site table called site2.

Open up the Query SQL editor by pressing the query icon.


If you need to, clear out any SQL text in the top part of the screen, and enter in (or copy and
paste) the following SQL text (between the lines) into the SQL editor window:

pgAdmin and PostgreSQL Exercise

64

Community Service with Web-Based GIST

CREATE TABLE site2


(
siteID serial,
visitdate date NOT NULL,
CONSTRAINT pk_siteID PRIMARY KEY (siteID)
)
WITH (
OIDS=FALSE
);
ALTER TABLE site2 OWNER TO postgres;

pgAdmin and PostgreSQL Exercise

65

Community Service with Web-Based GIST

Lets not worry about all the syntax above, such as the OIDS=FALSE, but this should
provide a mental connection back to the SQL reading you did prior to this exercise. You
should however be able to interpret the CREATE TABLE and the field definition lines.
Press the run query icon
If the SQL is entered correctly, you should see in the lower Output Pane a message that
says:
Query returned successfully with no result in 98 msec or something similar.
Close the Query window, and right click on your Tables in the Object browser. Choose
Refresh. You should see the duplicate site2 table in your tables on the right.

16) Delete the site2 table we dont need it.


That SQL exercise above was to demonstrate how you do these types of commands using
Structured Query Language (SQL). But our database doesnt need the second site table
(site2). So lets delete it.
Make sure you have Tables chosen under the Object browser, and right click on the site2
table. On the context menu that appears (below), choose Delete/Drop. Say yes when it
asks are you sure you want to delete Public.site?
Your list of Tables should be down to the three we created using the pgAdmin GUI - Site,
Forest and Plot.

pgAdmin and PostgreSQL Exercise

66

Community Service with Web-Based GIST

17) Now lets enter the data below.


Site table:
SiteID

Site_Name

Visitdate

Amherst

06/04/14

Kathmandu

5/5/15

Lowell

5/5/15

Forest table:
ForestID

SiteID

Forest_name

Mt Toby

5/5/15

Savage Hill

To enter the SiteID table data, click on the Site Table in the Object browser, choose View
Data, and choose View Top 100 Rows

pgAdmin and PostgreSQL Exercise

67

Community Service with Web-Based GIST

Enter in the Site data shown above. Notice that if you enter the date in the format above, it
gets converted to a year, month, day format because of its date data type definition (figure
22). Closing the view data window will save your changes. If you need to delete a row of
data, you just right click and a context menu comes up allowing you to choose delete.

pgAdmin and PostgreSQL Exercise

68

Community Service with Web-Based GIST

You can also enter data using the SQL language and pgAdmins Query Tool. For the Forest
table data, lets try this approach.
The SQL command to enter in (or append) is below separated by the lines.
INSERT INTO Forest
VALUES
(1,1,'MtToby'),
(2,1,'Caldwell'),
(3,1,'SavageHill');

Important: The values lists must be in the same order that you created the fields in the
database!
Note the use of single straight quotes around text values; these are required, but not around
numbers. The table name Forest could also be written "Forest" , but this would only be
required if it contained non-alphanumeric characters such as spaces, or if it had the same
name as keywords such as INSERT .
Open up the Query tool, enter the above command (note that the character data such as
MtToby needs to have single quotes around it to work), and press the run query icon (the
little play triangle). If you are successful, your screen should look like below.

pgAdmin and PostgreSQL Exercise

69

Community Service with Web-Based GIST

To double check and view your forest data, click on the Forest table in the Object browser,
choose View Data and the View Top 100 Rows. Your table of data should look like below.

18) Querying data in multiple tables


So up until now, weve created the site and forest tables after designing them to have a 1-tomany relationship and weve entered data following that 1-to-many design. Our data is pretty
limited, with simply one Site (UMass) with its three forest properties (MtToby, Caldwell forest
and SavageHill forest). But to finish this exercise, lets now query these tables together using
the join capacity we have built into our database design.
Before we start a reminder question:
Question3: How did we create or implement that join in our ER model and in our table
creation process? See Answer 3 at the end

pgAdmin and PostgreSQL Exercise

70

Community Service with Web-Based GIST

To query these two we go back to the Query tool. However, rather than using SQL
commands, we will use the Graphical Query Builder.

Suppose we wanted to run this query of the database: Show me all the forest names for the
site 1 (umass).
1. First choose the public Schemas.
2. Expand to see the tables (Forest, Plot and Site).
3. Click and drag the Site table into the open work area to the right.
4. Click on siteID, site_name, and Visitdate for this query. The selected fields should
appear red (note: the figures below do not show site_name).
5. Click and drag the Forest table into the open work area to the right.
6. Click on Forest-name. This field should appear red.
7. Click and grab the primary key, SiteID in the Site table and drag it over the SiteID
foreign key in the Forest table.
8. You should see a line connect between the two table boxes showing the join of the 1-tomany relationship. One site (Umass) has 1 or more forests.

pgAdmin and PostgreSQL Exercise

71

Community Service with Web-Based GIST

9. Compare your screen to below.

10. Now execute the query using the run query option (the little green play triangle). You
should see in the Output Pane at the bottom the results of this query, showing the
SiteID and visit date from the Site table, and the Forest Name from the Forest table
(Figure 27).

pgAdmin and PostgreSQL Exercise

72

Community Service with Web-Based GIST

11. Congrats!
IMPORTANT! Take a snapshot of your final screen, name it "Your Name Week 2" and
upload it to our course management system (upload Week 2) to show evidence that
you completed this assignment.
In conclusion, what you have learned in this exercise is the foundational tools for building a
relational database in PostgreSQL using the pgAdmin interface. Youve learned how to
create tables, how to enter data, and how to run queries.
Up until now, these databases are non spatial. There are no GIS features (points, polygons,
lines, etc.) in these databases. In the upcoming exercises, we will be learning about
PostGIS, which works with PostgreSQL to make data spatially explicit.
If you finish this exercise with time to spare, or for more information specifically about
PostGres, check out the official documentation on Postgres at:
http://www.postgresql.org/docs/current/static/index.html

pgAdmin and PostgreSQL Exercise

73

Community Service with Web-Based GIST

Answers to questions
Answer Question 1: The SiteID in the Forest Table is a foreign key needed to make the 1 to
many connection between the two tables. But remember that in the Forest table it is a
foreign key, meaning that it is not a primary key that needs to be unique. In this database,
any Research Site could have 1 or more forest areas defined by the people who live there.
So if Amherst was Site 1, and Amherst has several different forested areas, then Site 1
could have multiple forested areas going by different names. SiteID in the Forest Table cant
be defined as serial because each of the Amherst forests should have the same SiteID
number associated with Amherst. Consequently, SiteID should be defined as integer rather
than serial. You dont want it to increment every time a new forest record is added.
Answer Question 2: It should be integer, not serial. One forest can have one or more plots.
So you dont want ForestID in the Plots table to increment automatically.
Answer Question 3: We designed it using the primary and foreign keys. SiteID.

Chapter 2: Relational Database Management Systems


2.3 PostgreSQL/PostGIS Installation

Previous:
2.2 Relational Databases
Next:
3. Introduction

pgAdmin and PostgreSQL Exercise

74

Community Service with Web-Based GIST

3: Spatially Enabled Relational Databases


Lesson Goals
Students understand the concept of a spatially explicit relational database and will be
familiar with the use of PostGIS, PostgreSQL and QGIS.
Lesson Outcomes
Students will understand:
How PostGIS is a special extension or use of postgresql tables and functions. How spatial
data is generally represented in PostGIS That there are a number of different formats for
storing geometries including WKT, WKB, GML, KML, GeoJSON, and SVG
Students can:
Convert GIS data stored in external formats and convert them to a PostGIS data layer
Query spatial data attributes stored in a PostGIS database
Utilize basic SQL commands

Chapter 3: Spatially Enabled Relational Databases


Introduction

Previous:
2.3 PostgreSQL/PostGIS Installation
Next:
3.1 The Idea of Spatial Databases

Spatially Enabled Relational Databases

75

Community Service with Web-Based GIST

3: Spatially Enabled Relational Databases


3.1 Pre-Class Readings and Exercise: The Idea of Spatial
Databases
Introduction:
Up until now we have introduced you to the QGIS desktop [http://qgis.osgeo.org], one of the
leading open source desktop or client Geographic Information Systems software packages,
and relational database theory and standard components such as the Structured Query
Language (SQL). You have also become familiar with the use of open source relational
database technologies: the relational database management system (RDBMS) PostgreSQL
and the user interface to it, pgAdmin. What you may not fully appreciate is that PostgreSQL
is a fully functional enterprise level relational database. That is, it can be used to process
large amounts of data and can handle multiple users accessing the database at the same
time.
The material we are covering in this set of readings and exercises focus on a special type of
relational databases: spatial databases. If you are a reader who has experience with the
proprietary GIS package ArcGIS, you may know we actually mentioned this in last weeks
material that the Geodatabase is one example of a relational, spatially explicit database.
In this set of pre-class and in-class readings and exercises, you will get the opportunity to
work with PostGIS a special kind of Postgres relational database.
To begin we are again assigning a set of open access readings to do to help you understand
PostGIS and how it works with Postgres. Like Week 2, there will be a 10-question Moodle
quiz that will follow this material. We encourage you to take some notes on the big ideas in
these readings.
Acknowledgements:
We are grateful to the company Boundless (http://boundlessgeo.com) for providing sets of
reading material on PostGIS under a Creative Commons license. The entire set of materials
can be found at http://workshops.boundlessgeo.com/postgis-intro/. We are providing links to
this material to respect their request that we retain Boundless branding, logos and style.

Assignment:

The Idea of Spatial Databases and PostGIS

76

Community Service with Web-Based GIST

You should have already installed Postgresql, PostGIS, pgAdmin and the pgShapeloader
utility in the first pre-class assignment. With that installed, go through the following
Boundless Workshop Modules.
Before starting, download the Boundless data bundle available with their NYCity data from
here: http://files.boundlessgeo.com/workshopmaterials/postgis-workshop-201401.zip
Now start going through these Boundless tutorials:
Introduction. http://workshops.boundlessgeo.com/postgis-intro/introduction.html
Chapter 4: Creating a Spatial Database. http://workshops.boundlessgeo.com/postgisintro/creating_db.html
Chapter 5: Loading spatial data. http://workshops.boundlessgeo.com/postgisintro/loading_data.html
IMPORTANT! Section 5.3. encourages the reader to try and view their data in QGIS, but
doesnt explain how to do this. To do this:
1. Start up QGIS Desktop.
2. Locate the Browser Panel; if its not open, menu View > Panels > Browser Panel.
3. Right-click the item PostGIS, and in its contextual menu select New Connection.
4. In the window Create a New PostGIS connection:

The Idea of Spatial Databases and PostGIS

77

Community Service with Web-Based GIST

i. In the field Name, enter a name that identifies the server, username, and database
you want to connect to, e.g. localhost your_username nyc.
ii. In the field Host, enter the hostname, e.g. localhost.
iii. In the field Database, enter the name of the database, e.g. nyc.
iv. In the field Username, enter the username you are using to connect, e.g.
your_username.
v. In the field Password, type in the password you set for this account.
vi. Click the button Test Connection and you should see a dialog indicating that The
connection to your database was successful. If you dont, double-check your
parameters.
vii. Click the button OK.
The Idea of Spatial Databases and PostGIS

78

Community Service with Web-Based GIST

5. Click the button / next to PostGIS in QGIS, and you should see your connection
listed, e.g. localhost your_username nyc. Continue expanding. You should see a
screen like below.

6. If you double-click on the nyc data listed, you should see these layers appear in the
map side of QGIS! See below.

The Idea of Spatial Databases and PostGIS

79

Community Service with Web-Based GIST

Success! Youve got a Postgres+PostGIS spatial database with four layers displayed in
QGIS! For many of you this will be the first time displaying data using an open source
enterprise spatially enabled RDBMS!
If you are a bit of a geek, this should be exciting! (and even if you are not, but are interested
in GIS!)
OK, now continue doing the Boundless workshop modules below.
Chapter 6: About our data. http://workshops.boundlessgeo.com/postgisintro/about_data.html
So before you begin reading the Boundless Chapter 7 on simple SQL, here is something to
note on and reflect on. With the successful connection in QGIS, you now have two
mechanisms for working with the data (attribute tables) associated with the PostGIS data
layers.
Probably what youd most likely want to do is do queries using QGIS or open up the attribute
table and check out the data there.
Try that!
Were assuming you have used GIS before, so try and figure out in QGIS how to open the
attribute table for, say, the nyc_neighborhoods data layer to see the different neighborhood
names.
Or how might you query the nye-neighborhood layer to select only the neighborhoods in
Manhattan? If you dont know, look to the bottom of this exercise for one way under Answer
Question 1.
But the other way you could query this data is through the use of pgAdmin and the query
tool there. pgAdmin is another interface to these postgres/postgis tables. In the exercises
that follow, Boundless is providing you a little more information and experience using the
relational database language SQL and the interaction with the Postgresql/PostGIS tables
that make up these spatial data layers in their New York City dataset.
To learn more about SQL and the geometries of PostGIS GIS data layers, go though:
Chapter 7: Simple SQL. http://workshops.boundlessgeo.com/postgis-intro/simple_sql.html
Chapter 8: Simple SQL exercises. http://workshops.boundlessgeo.com/postgisintro/simple_sql_exercises.html
Chapter 9: Geometries. http://workshops.boundlessgeo.com/postgis-intro/geometries.html
Chapter 10: Geometries Exercises. http://workshops.boundlessgeo.com/postgisintro/geometries_exercises.html

The Idea of Spatial Databases and PostGIS

80

Community Service with Web-Based GIST

What the exercises in Chapter 10 reveal is that through the use of the geometry in PostGIS
coupled with functions and the table data, Postgres/PostGIS and SQL become powerful
tools to answer complicated spatial analysis-related questions. This is one of the reasons
the use of a powerful RDBMS is useful for storing geographic data.
You are now done with the Week 3, pre-class assignment!

Answer 1: One way to query only the neighborhoods in Manhattan using QGIS is to right
click on the nyc_neighborhoods under the Layers pane, and choose Properties. Under the
General option, scroll down to the bottom and you will see the Query Builder button. Press
that. This will open up that option, and you can choose boroname (double click on it to
bring that down to the expression box), type =, and the under values select all, and then
double-click on Manhattan. You will see at the bottom:
boroname = Manhattan
Behind the scenes, QGIS is running a select query to select the polygons from
nyc_neighborhoods where boroname = Manhattan
Press OK and you should see only those neighborhoods of Manhattan on the QGIS map
window.

Chapter 3: Spatially Enabled Relational Databases


3.1 The Idea of Spatial Databases

Previous:
3. Introduction
Next:
3.2 Exercises

The Idea of Spatial Databases and PostGIS

81

Community Service with Web-Based GIST

3: Spatially Enabled Relational Databases


3.2 In-Class Exercise: Building the IFRI Spatial Relational
Database using PostGIS
Introduction
In this class exercise, we will turn back to the International Forestry Resources and
Institutions (IFRI) relational database we worked on earlier. But in todays work, we will build
a spatially-explicit relational database using Postgres, PostGIS, and QGIS.
Recall the simple relational database we designed previously (Figure 1).

The overall plan for this in-class exercise will be to do the following:
1. Build a new IFRI QGIS project and connect to our town and landsat image data
2. Import a shapefile polygon of one Forest area (MtToby) into PostGIS to create a
spatially-explicit Forest layer
3. Select out the towns that cover MtToby in QGIS to produce a new Site layer

Building the IFRI Spatial Relational Database using PostGIS

82

Community Service with Web-Based GIST

4. Create a new point layer for the Forest Plots 5. Set up our relational primary and foreign
keys and enter some trial data into the database (attribute tables)
5. Run a multiple-table query to answer a question
6. How could you have queried the forest plots that are in the Mt Toby boundary without
setting up the 1-to-many relationship?
7. Take a screen shot of your final QGIS screen and upload it to Moodle under Week 3 to
document that you completed the exercise.
Lets begin!
To start, create a Week_3 folder on your computer hard disk to store your work.
Task 1) Set up our base QGIS IFRI project
Open up QGIS Project and a new blank map. If you have residual connections to previous
exercise data in your Browser (like the Boundless nyc data), consider removing them (right
click, delete).
Note the Render and the default project coordinate system used at the bottom right of your
QGIS map screen. In our instance, it defaults to EPSG: 4326.
Do a Google Search on EPSG: 4326. Youll find information noting that this is a reference to
WGS84.
Question 1: What does that mean? For the answer, see the end of this exercise.
Question 2: What kind of distortion occurs using that coordinate system discussed in
Question 1?
Heres a little detail that is kind of confusing but relates to the Boundless readings you did
earlier and is important to understand. Recall in the Boundless readings there was a
discussion about SRID it stands for Spatial Reference System Identifier. Recall that the
SRID is a unique value that is associated with a particular spatial coordinate system and
there are thousands of them.
In QGIS, they use EPSG rather than SRID. EPSG stands for the European Petroleum
Survey Group and they have numbers to reference various spatial coordinate systems. So
the EPSG number 4326 references the geographic coordinate system (latitude and
longitude) using WGS84 as its datum and no projection.
On to working with our data.

Building the IFRI Spatial Relational Database using PostGIS

83

Community Service with Web-Based GIST

Add a UMass Web Feature Service (WFS) using our Geoserver. Do you remember how to
do this? We did this in the first exercise Exploring Spatial Data Models using QGIS. The
information you need to make that connection is:
Name: UMass WFS (you can call this whatever you want, actually) URL:
http://nrcwg01.eco.umass.edu:8080/geoserver/massachusetts/wfs
Double-click on the umass WFS towns layer to get it added to your Layers list in QGIS.
Now look at the Render and the coordinate system at the bottom right of your screen. What
does it say now?
By bringing in our first layer (Umass FMS Towns), the project coordinate system took on the
projection used in that layer, EPSG:26986.
Before we move on, check out the QGIS Project Properties (Project menu, Project
Properties). You should see near the bottom that it says Selected CRS (CRS stands for
Coordinate Reference System) and it should be referencing NAD83/Massachusetts
Mainland
Question 3: Can you interpret that? What is that telling you (see the answer below)?
Before we close the Project Properties screen, click on Enable on the fly CRS
transformation (Figure 1A). As you probably know, this will allow QGIS to display or overlay
layers with different coordinate systems on top of each other using a behind-the-scenes
conversion algorithm.

Building the IFRI Spatial Relational Database using PostGIS

84

Community Service with Web-Based GIST

Now lets get the background Landsat image.


Connect to the Umass Web Mapping Service (WMS). Again, we first used this function in the
first exercise referenced above. Like the WFS above, we need the following information to
create the connection:
Name: UMass WMS (again, this can be called whatever you want to call it) URL:
http://nrcwg01.eco.umass.edu:8080/geoserver/wms?
Once the connection is established in your QGIS Browser, double-click on the Landsatimage layer to load it into your QGIS layers. Reorder or move down the Landsat image so
the towns boundaries sit on top of the landsat image. Change the symbology of the towns
layer so the fill color is off and the boundary color is easily seen on top of the Landsat image
(Figure 2).

Building the IFRI Spatial Relational Database using PostGIS

85

Community Service with Web-Based GIST

Save your QGIS project. Call it something like Yourname_IFRI and store it in some
exercise folder on your computer.
Task 2: Import a shapefile polygon boundary of one Forest area (MtToby) into PostGIS
to create a spatially-explicit Forest layer
First, we need to create a boundary layer of the one forest property we will work with in this
exercise: Mt Toby.
Get the MassGIS Openspace layer. We assume youve had some experience with
MassGIS. Go to that website and find the Openspace shapefile and download it to your
exercise folder. Unzip it. In that folder there is an OPENSPACE_POLY.shp. Add that to your
QGIS project and temporarily, turn off the display of the towns and landsat image. Your
QGIS map should look like Figure 3, below.

Building the IFRI Spatial Relational Database using PostGIS

86

Community Service with Web-Based GIST

Using QGIS Select by Expression function (

) to run a query that selects just the

polygons in the OpenSpace _poly layer where


( "SITE_NAME" = 'Mount Toby State Forest' ) OR ( "SITE_NAME" = 'Mt Toby Conservation
Area' )
As shown in Figure 5 below.

Press the Select button. Several polygons will be selected (Figure 6).

Building the IFRI Spatial Relational Database using PostGIS

87

Community Service with Web-Based GIST

Weve now selected the forested areas that are part of our IFRI research study. Lets save
the selected features to an ESRI Shapefile to your exercise folder hard disk.
1. Under the QGIS main menu, Layer option, press Save As.
2. Under Format, choose: ESRI Shapefile but notice all the other format types available,
some of which were discussed in the previous reading (Figure 7).
3. Next to Save as, press the Browse button and save the selected polygons as a new
shapefile called forest (for our Forest Spatial Layer shown in the relational database
design in Figure 1). Save it in your exercise folder on your hard disk.
4. Before you press OK, make sure you select Save only Selected Features and Add
saved file to map (Figure 8).
5. Press OK, and you should see a new shapefile displayed in your QGIS Layers window
called forest (Figure 9).

Building the IFRI Spatial Relational Database using PostGIS

88

Community Service with Web-Based GIST

Building the IFRI Spatial Relational Database using PostGIS

89

Community Service with Web-Based GIST

Open up the Forest attribute table. Note that there are actually 19 polygons that make up the
Mt Toby forest, and there are a number of different owners of various parcels. This simulates
the many forest side of the database design in Figure 1.
Up until now weve been working with either Web Service data or the proprietary data format
Shapefile. Lets now begin to build our IFRI Study PostGIS relational database. Hopefully
you recall the steps from the pre-class reading exercise. See if you can create a database
named IFRI in PostGIS that is spatially enabled. But if you cant see Answer 4 below for the
steps. Remember, you do this part in pgAdmin and not in QGIS!
Once you do that, you should be able to connect to your database with QGIS as described
in Chapter 3.1.
Now, lets work on getting the Forest shapefile imported into this database. QGIS has a
Database Manager that well use to convert the forest shapefile into a PostGIS data set.
1. In QGIS Desktop, menu Database > DB Manager > DB Manager.
2. Open the list item PostGIS.
3. Click on the connection to your database that you created previously.
4. Click on the button Import layer/file.
5. In the dialog Import vector layer, in the menu Input, choose the layer to import from
those already brought into QGIS, e.g. forest (you can also click the button to load
another file);
6. Click the button Update options to copy the Input name to the Table name.
7. Click the button OK.
If you are here, you hopefully were successful importing the forest shapefile into the IFRI
postGIS database. Now, display it in QGIS.
See if you can figure out the steps yourself. If you have trouble, see Answer 5 below.
Hopefully at this point you are successful and you have the forest layer in your PostGIS
database and you are displaying it in QGIS! We have our first component of our IFRI
database the Forest layer!
Task 3: Select out the towns that cover MtToby in QGIS to produce a new Site layer
So now that we have a Forest layer for our IFRI database, now lets create a layer for our
Site component of the database (see Figure 1). In this case, a research site here in the US
well call a town or towns where the forests reside.

Building the IFRI Spatial Relational Database using PostGIS

90

Community Service with Web-Based GIST

Lets use the Umass Towns WFS layer to see what town(s) the Mt Toby property resides in.
Turn off all layers except for the forest layer and the towns layer as shown in Figure 10.

Using QGIS, see if you can can figure out steps to create a new shapefile that includes just
the town boundaries that the Mt Toby forest resides in (the answer should be three
polygons). But for the study site polygon, what we want to produce is ONE polygon
representing the outer boundary of the towns that the Mt Toby forest resides in. So see if you
can, without looking at our answer, figure out the steps to do the following:
select the towns that Mt Toby falls in;
save these selected polygons as a shapefile called mttoby_towns
merge the three polygons to create one larger polygon
Save that as a Site shapefile
Store that new Site shapefile in the IFRI PostGIS database
Add that new PostGIS layer to your QGIS Layers and map.
If you get stuck and need to see one method, we describe our steps below to Answer 6.
If all went as planned, you should now have a single Site polygon that encompasses the
areas taken up by the towns of Montague, Sunderland, and Leverett. At this point, we no
longer need the shapefiles since the Forest and Site layers reside in our IFRI database in
PostGIS. In QGIS, right click and remove the work layers we no longer need: Openspace,
mt_toby_town and the site shapefiles. Your QGIS system should look something like the
future below with the forest and site coming from the PostGIS IFRI database.

Building the IFRI Spatial Relational Database using PostGIS

91

Community Service with Web-Based GIST

Thinking back to our Forest layer and our database design in Figure 1, we now have the
situation where we have one research SITE (made up of the three towns of Montague,
Sunderland and Leverett), and within this SITE we have several FOREST polygons, all of
which are parts of Mt Toby, but are owned by different organizations. Conceptually, we have
a 1 site with many forests situation now.
Task 4) Create a new point layer for the Forest Plots
With two of our three spatial layers in our IFRI PostGIS RDBMS built, we now need to turn to
the third table in our ER diagram (Figure 1): the forest Plots table.
The idea of the Plots table is this: It would be a point layer where biologists would create a
center point with a 10 meter circle and then sample all the vegetation that falls within those
circles or forest plots. These are one method that foresters or biologists use to inventory
vegetation in a forested area.
Right now, we have no forest plots mapped. One way to do this would be to go out and GPS
some random locations or follow some kind of transect sampling method. Another way,
which well do here, would be to have the GIS system create a point layer of randomly
placed points.

Building the IFRI Spatial Relational Database using PostGIS

92

Community Service with Web-Based GIST

See if you can figure out how you can make QGIS create a point layer of randomly placed
points within the Mt Toby Forest polygon with a GID = 10 (Figure 12).

Try to do it yourself. If you cant figure it out, look down at Answer 7 below. (Two Hints: (1)
You need to first select out the polygon with GID = 1 and save it as its own layer; and (2)
there is a QGIS command that will do the random point placement very easily for you. Dont
digitize the points yourself!).
Once you have the random plots shapefile created, go through the process of adding it to
your PostGIS IFRI database and bring that into your QGIS Layers list. Remove the old
shapefile versions.
We now should have all three of our IFRI database layers: Site, Forest and Plots. Your QGIS
map should look similar to the Figure below.

Building the IFRI Spatial Relational Database using PostGIS

93

Community Service with Web-Based GIST

Task 5) Set up our relational primary and foreign keys and enter some trial data into
the database (attribute tables)
So first we need to make up some fake forest plot data. Since you are probably just
learning how to use QGIS (but probably have experience with another GIS package), see if
you can figure out how to edit the Plots table and add these columns (following our simple
ER design in Figure 1):
Plot_number(integer, auto increment)
ForestID
Num_trees (diameter at breast height)
After youve created the fields, enter the following data into your plots attribute table:
plot_num, forestID, Num_trees
1,1,10
2,1,5

Building the IFRI Spatial Relational Database using PostGIS

94

Community Service with Web-Based GIST

3,1,7
4,1,14
5,1,3
6,1,8
7,1,0
8,1,2
9,1,10
If you arent sure how to do this, go down and review Answer 8 below.
So now we have some data in our plots table. Now lets enter the primary and foreign keys
in our Site and Forest table to set up our relational database again. Look back to our design
in Figure 1.
In the Site attribute table enter these two fields:
Site_ID (primary key, integer))
Site_name (text, fixed length, 30)
In the Forest attribute table we need:
Forest_ID (primary key, integer)
Forest_name (text. fixed length, 50)
Site_ID (foreign key, integer)
Follow the same steps you did above to add fields to plot to add the fields in these tables.
Once you have that done, enter the relevant data to set up the relationships:
Site_Id, Site_Name
1, Western MA
In the Forest Table, remember the only forest polygon we are working with is gid = 9. For
THAT ROW ONLY enter this data:
Forest_ID, Forest_Name, Site_ID
1,Mount Toby,1
Save your edits.

Building the IFRI Spatial Relational Database using PostGIS

95

Community Service with Web-Based GIST

In case you didnt read the Answer 8 below, you could have done this portion of the exercise
with either tables in QGIS, or using pgAdmin to work with the tables.
Task 6) Run a multiple-table query to answer a question
So now we are in a position to try and query all of the data associated with Sites, Forests
and Plots. That is, do a relational database join query.
But before we do this, there are too many fields in Forest right now that we dont need. In
QGIS, open up the Forest table, click on the Delete Attributes icon, and delete the middle
10 or so fields that we didnt enter. You need to edit the forest table in order to do this. Turn
editing off when done.
Recall from our Week 2 exercise with pgAdmin that we used the Graphical Query Builder to
run a query that pulled data from multiple tables together.
Run the query: Show me all of the forest plot records for Site 1, Forest 1
If you dont know how to do this, review Answer 9, below.
Task 7) How could you have queried the forest plots that are in the Mt Toby boundary
without setting up the 1-to-many relationship?
See Answer 10 if you arent sure.
Task 8) Take a screen shot of your final QGIS screen, name it your last name Week 3
and upload it in Moodle Week 3 for proof that you completed this exercise.

ANSWERS TO QUESTIONS
Question 1. WGS84 means that the default coordinate system for QGIS is a
Latitude\Longitude coordinate system using the World Geodetic System 1984 which is is the
datum, with a reference ellipsoid. So QGIS defaults to using a world, lat\long system.
Question 2. Mapping in Lat\Long coordinates means that distortion occurs in all four types:
Shape, Area, Distance and Direction.
Question 3. NAD83 is the datum used North American Datum 1983. Massachusetts
Mainland is referring to the State Plane Projection for Massachusetts (the mainland part of
Massachusetts). Hopefully you remember this from earlier GIS classes!
Answer 4. Setting up an IFRI PostGIS database.
First, use pgAdmin, to create the IFRI database.

Building the IFRI Spatial Relational Database using PostGIS

96

Community Service with Web-Based GIST

The steps to do this are described in the Boundless Creating a Spatial Database reading
(http://workshops.boundlessgeo.com/postgis-intro/creating_db.html). But basically they are:
start up pgAdmin
create the ifri database by right clicking on the Databases under postgresql and naming
it IFRI with an owner of postgres
Under the IFRI database, choose use the public schema. Use the SQL query tool to run
the CREATE EXTENSION postgis;
run the SELECT postgis_full_version(); query to verify that it is operational.
Answer 5. Steps to viewing PostGIS layer data in QGIS
In Browser, right click on the PostGIS option
Fill in the following information: Name - postgres (or you could name it something else);
Host - localhost (no quotes); Database - IFRI; Username - postgres; password postgres. Test the connection. Hopefully successful! Click OK. *You should see
postgres or whatever you named the PostGIS connection appear below PostGIS in the
browser. Open up the little triangles and navigate down to the database public. You
should see forest as a layer listed. Click on it, and a QGIS window Coordinate
Reference System Selector will appear. It will have the CRS from the shapefile
(Massachusetts Mainland, NAD83). Hit OK. You should see the PostGIS forest layer
appear in your QGIS Layers window and on the map.
Check out the properties for the forest layer. Look under the General tab. The layer
source will be referring to the PostGIS database and notice the type is a multipolygon.
The previous Boundless readings should be useful here in understanding this. Return
up to the exercise.
Answer 6. Steps to selecting out the towns that contain the Mt Toby forest polygons
using QGIS
To select out the three towns that have the mt toby forest in it and save them to a shapefile:
go to QGIS menu, Vector, Research Tools, Select by Location
Select features in towns, that intersect features in forest. Include input features that
intersect the selection features. Create new selection. OK.
Three towns should be selected. You can see which ones (their names) if you open the
attribute table for towns and press show selected features at the bottom. The towns
are: Montague, Sunderland and Leverett.
Layer menu item, Save as, Format ESRI Shapefile, CRS keep as Mass Mainland.
Browse to store in your exercise folder. Output as mt_toby_towns.shp. Make sure you
choose save only selected features. Press OK.

Building the IFRI Spatial Relational Database using PostGIS

97

Community Service with Web-Based GIST

One way to merge the three polygons to create one larger polygon:
QGIS menu, Vector, Geoprocessing tools, Dissolve
Input vector layer: Mt_toby_towns; Dissolve field: Dissolve all; output to your exercise
folder as site shapefile

Building the IFRI Spatial Relational Database using PostGIS

98

Community Service with Web-Based GIST

The result will be a dissolve of the three polygons into one polygon that contains their area
as shown in the figure below.

Now, to store that new Site shapefile in the IFRI PostGIS database, this is similar to what we
did earlier using the QGIS Shapefile to PostGIS Import (SPIT) utility.
Next, add that new PostGIS layer to your QGIS Layers and map. This is similar to the steps
we did in Answer 6 above, however you already should have the PostGIS connection to the
IFRI database established in your QGIS Browser. So all you have to do is right click on the
Public database under postgres, and click refresh. The site layer should appear. Double
click on that to bring that down to your Layers and to add it to your QGIS map. The CRS
should be the same. Click OK.
Answer 7. Developing a random set of plot points within the mt toby forest boundary
to create the ifri Plot table.
Use the Select by Expression tool to select out from the forest layer the polygon with
GID = 10.
Layer, Save as ESRI Shapefile, Save as study_forest in your exercise folder, make
sure you choose Save only selected features. OK. A new shapefile layer study_forest
should appear in your list of Layers.

Building the IFRI Spatial Relational Database using PostGIS

99

Community Service with Web-Based GIST

Now to create the random plot points


QGIS Main menu, Vector, Research Tools, Random Points. See the parameters we
used in the figure below:

Press OK to run the random points function. Store it as Plots shapefile. Use the SPIT plugin
utility to bring that into your IFRI PostGIS database and then add that layer to your QGIS
Layer and map. Remove the old shapefile.
Answer 8. Add Plot_num (primary key), ForestID (foreign key) and Num_trees to the
Plots table and enter some fake plots data.
Since Plots is a PostGIS layer, stored in a Postgres database, there are two ways you could
do this: (1) in QGIS, or (2) using pgAdmin.
To do this in QGIS:
Select the plots table (highlight it in Layers)
Open up the attribute table (right click on plots, choose open attribute table, or press the
table icon (figure A9.1) in the main icon menu at the top of QGIS)

Building the IFRI Spatial Relational Database using PostGIS

100

Community Service with Web-Based GIST

Click on the edit icon at the top of the table screen

Click on the insert column icon at the top of the table screen

Add your columns using the above approach. All three fields could be defined as small
integer.
Note that we already have a field called gid that could be used as the primary key for the
plot points. But to be consistent with our relational database design, lets create plot_num
instead.
Once you have the columns created, enter some fake data:
plot_num, forestID, Num_trees
1,1,10
2,1,5
3,1,7
4,1,14
5,1,3
6,1,8
7,1,0
8,1,2
9,1,10
Note that all of these plots fall in the same forest, hence they all have the forestID 1.
When done, press the Save Edits icon in the table menu (the little diskette) and then click
the editor icon off. Close the attribute table.
NOTE: You could also have done this using pgAdmin!
Answer 9. Using pgAdmins Graphical Query Builder to query the IFRI database for all
the Site, Forest and Plots records for Site 1
Pull the Site, forest and plots table into the graphical query area
Connect the tables using the primary and foreign keys youve set up to model the 1 to
many relationships (e.g., Primary Site_id key in the Site table, to Site-id foreign key in

Building the IFRI Spatial Relational Database using PostGIS

101

Community Service with Web-Based GIST

the Forest table; also set up the relationship between Forest and Plots).
Select the fields (columns) you want returned in your query: site.site_id,
forest.forestname, and plots.plot_num and plots.Num_trees. They should turn red when
selected. See the below figure.

Now you have to do something you havent used yet in the Graphical Query Builder.
Click on the Criteria tab at the bottom, and there you can enter the select criteria:
Restricted Value: site.site_ID
Operator: =
Value: 1
Your Query screen should look something like the figure below.

Building the IFRI Spatial Relational Database using PostGIS

102

Community Service with Web-Based GIST

Run the query using the run query button (little green play icon). If successful, your
results should look similar to the figure below, with the Site_ID data () from the Site
table, the Forest_name (Mount Toby) from the Forest table, and the num_trees data
from the Plots table.
Notice the SQL language that the Graphical Query Builder built.

Building the IFRI Spatial Relational Database using PostGIS

103

Community Service with Web-Based GIST

Answer 10. How would you be able to list the plots that are in the forest boundary
without using a 1-many relational database query?
In QGIS, use the Vector menu, Research Tools, Select by Location tool:
Select Features in Plots that intersect features in forest, creating new selection. OK.
You should see the plot points selected, and you can open up the plots table to see the
results. If in this IFRI Forest polygon layer we had multiple forest boundaries, each with their
own plots, we would have to do a more sophisticated query, asking first to select the forest
boundary we want, and then doing the select by location query.

Building the IFRI Spatial Relational Database using PostGIS

104

Community Service with Web-Based GIST

Chapter 3: Spatially Enabled Relational Databases


3.2 Exercises

Previous:
3.1 The Idea of Spatial Databases
Next:
4. Introduction to Mapping Raster Data

Building the IFRI Spatial Relational Database using PostGIS

105

Community Service with Web-Based GIST

Chapter 4: Mapping Raster Data

Mapping Raster Data

106

Community Service with Web-Based GIST

4.1. Raster datasets - formats and finding


them on the Internet
Raster datasets are important in Web-based mapping. In this section, we will discuss two
aspects related to Raster datasets: some common formats, and where you might go to find
some already ready made for use in WebGIS projects.

4.1.1. Raster Data Formats


If you search Wikipedia [1] for GIS Data formats, you find the following definition under the
subheading Raster:
A raster data type is, in essence, any type of digital image represented by reducible and
enlargeable grids. Anyone who is familiar with digital photography will recognize the Raster
graphics pixel as the smallest individual grid unit building block of an image, usually not
readily identified as an artifact shape until an image is produced on a very large scale. A
combination of the pixels making up an image color formation scheme will compose details
of an image, as is distinct from the commonly used points, lines, and polygon area location
symbols of scalable vector graphics as the basis of the vector model of area attribute
rendering. While a digital image is concerned with its output blending together its grid based
details as an identifiable representation of reality, in a photograph or art image transferred
into a computer, the raster data type will reflect a digitized abstraction of reality dealt with by
grid populating tones or objects, quantities, cojoined or open boundaries, and map relief
schemas. Aerial photos are one commonly used form of raster data, with one primary
purpose in mind: to display a detailed image on a map area, or for the purposes of rendering
its identifiable objects by digitization. Additional raster data sets used by a GIS will contain
information regarding elevation, a digital elevation model, or reflectance of a particular
wavelength of light, Landsat, or other electromagnetic spectrum indicators.
Raster data type consists of rows and columns of cells, with each cell storing a single value.
Raster data can be images (raster images) with each pixel (or cell) containing a color value.
Additional values recorded for each cell may be a discrete value, such as land use, a
continuous value, such as temperature, or a null value if no data is available. While a raster
cell stores a single value, it can be extended by using raster bands to represent RGB (red,
green, blue) colors, colormaps (a mapping between a thematic code and RGB value), or an
extended attribute table with one row for each unique cell value. The resolution of the raster
data set is its cell width in ground units.

Raster datasets - formats and finding them on the Internet

107

Community Service with Web-Based GIST

As you search for data on the Internet, or if you create your own raster data by using a
digital camera (e.g., such as a camera on an airplane or on a quadcopter to capture
landcover imagery), you need to be familiar and be able to recognize, particular raster data
formats. There is a large list of different formats. Take a moment to see the full list that the
GDAL translation and utility software supports. Visit:
http://www.gdal.org/formats_list.html
There is a lot of raster data formats, isnt there!
Understanding and recognizing at least the commonly used formats is an important skill to
gain. Below, we provide some links to Internet information that describes some of the
common formats you might encounter. Take a moment to familiarize yourself with these.
ESRI Grid. This is a proprietary raster data storage format that is native to the ArcGIS
software package by ESRI. These are made up of a number of different files and are stored
in a file directory or folder, not an individual file.
ESRI ASCII raster format. This is a non-proprieary raster format that is useful for transferring
or importing ESRI GRID data into other raster software packages. These have an extension
name of .asc.
GeoTIFF is a collaborative efforts by many different companies and organizations to
establish an agreed upon TIFF-based interchange format for georeferenced raster imagery.
The coordinate system information can be stored in the GeoTIFF file itself, or sometimes is
accompanied by a Tiff World File (.tfw).
GIF. The Graphical Interchange Format is a raster image format that supports up to 8 bits
per pixel per image, allowing a single raster image to be able to display up to 256 different
colors. It also supports animations. Extension name: .gif.
IMG. While there are several uses of .img, in raster processing we often encounter .img files
that are a proprietary raster format developed for the raster software ERDAS Imagine. For
example, this format is one of the raster data formats provided by the National Map Viewer
for the National Elevation dataset.
JPG. This stands for Joint Photographic Experts Group and is a commons standard for
representing one band (greyscale) or three band (Red, Green, Blue or RGB) datasets. File
extension name is .jpg.
JP2 (JPEG 2000) is an image compression standard that provides some increased
compression performance compared to its predecessor JPG. File extension name is .jp2.

Raster datasets - formats and finding them on the Internet

108

Community Service with Web-Based GIST

KML. Keyhole Markup Language. This is is a data format for storing place locations,
polygons, images and other things for use with Google Earth, formally called Keyhole Earth
Viewer. KML format is an accepted open standard by the OGC. KML files are often
distributed in a .KMZ file, which is a zipped, compressed file format.
PNG. Portable Network Graphics. This is a raster graphics file format that supports lossless
data compression, which means that the digital information is compressed by an algorithm
that allows the original data to be completely reconstructed from the compressed data. This
differs from lossy compression that reconstructs only an approximation of the original
compressed data. PNG was invented as a replacement for another graphics format - GIF.
Extension name .png.
TIF or TIFF. This Tagged Image File Format is a raster file format that has been around for
some time, often used to store raster graphics images that were used in the publishing
industry and by photographers. The extension name is either .tif or .tiff.
There is even a raster format for PostGIS, called PostGIS Raster (formerly called
WKTRaster).
In short, for WebGIS, raster files are a critical component. Youve already seen Web
Mapping Services which transmit raster files. Also, soon we will be discussing the concept of
Tiling or Tiled Maps which use raster images.

References
[1] https://en.wikipedia.org/wiki/GIS_file_formats#Raster_formats

4.1.2. Searching for Raster Data on the Internet


It is really incredible just how much available data these days. There are a variety of webdatabase repositories out there that provides access to GIS data (vector, raster) in general,
and raster data specifically. You may have a lot of experience looking for GIS data on the
Internet already. But if you dont, take a few moments to visit some of the GIS data
repositories in the table below, just to see the kinds of data that are available, and note that
the table below is just a listing of some of the Internet data repositories available.
If you are looking to try out a couple of these sites to see what you can find for an area of
your own interest, wed recommend you try the National Map Viewer or the USGS Earth
Explorer.

Raster datasets - formats and finding them on the Internet

109

Community Service with Web-Based GIST

Name

Description

Website

Mass GIS

Massachusetts
spatial data

http://www.mass.gov/anf/research-and-tech/it-servand-support/application-serv/office-of-geographicinformation-massgis/datalayers/layerlist.html

National Atlas

U.S. spatial
data

http://nationalatlas.gov/atlasftp.html

USGS
Sagemap

Spatial data
for western US

http://sagemap.wr.usgs.gov/GISData.aspx

UMass
facilities

Campus
projects,
facilities &
planning

http://www.umass.edu/cp/maps.htm

National Map

U.S. spatial
data

http://viewer.nationalmap.gov/viewer/

National Gap
Analysis

Species and
Ancillary Data

http://www.gap.uidaho.edu/species_data.html

ArcGIS Open
Data

Contributed
data from the
ESRI GIS
community

https://opendata.arcgis.com/about

GENERAL
RESOURCES

Name

Description

Website

CLIMATE DATA
NOAA National
Weather Service

Current and past weather


events

http://www.nws.noaa.gov/gis/

Worldclim

Global climate data (and


2050 and 2070 projections

http://worldclim.org

Climate Wizard

US or global climate data


(and 2050 projections)

http://www.climatewizard.org/

PRISM

US climate data (download


the 'normals' for average
climate)

http://www.prism.oregonstate.edu/

USGS climate
change
projections

US downscaled climate
projections

http://cida.usgs.gov/gdp/

Name

Description

Website

OTHER
ENVIRONMENTAL

Raster datasets - formats and finding them on the Internet

110

Community Service with Web-Based GIST

DATA
Soil Information for
Environmental
Modeling and
Ecosystem
Management

Various soil
metrics for
the
contiguous
US

http://www.soilinfo.psu.edu/index.cgi?
soil_data&conus&data_cov&poros&datasets

Geospatial Data
Gateway

U.S. Natural
Resources

http://datagateway.nrcs.usda.gov/GDGHome.aspx

US EPA
Ecoregions

Ecoregions
of North
America

http://www.epa.gov/wed/pages/ecoregions/na_eco.htm

Topography (fine
resolution)

Under
datasets ->
Digital
Elevation >SRTM void
filled

http://earthexplorer.usgs.gov/

Topography
(coarse resolution)

30 second
is ~1 km,
2.5 min is ~
5 km download
by tile if you
want only
part of the
globe

http://www.worldclim.org/current

Remotely sensed
imagery

Various select under


datasets

http://earthexplorer.usgs.gov/

Hydrography

watersheds,
catchments
and other
hydrography

http://www.horizonsystems.com/NHDPlus/NHDPlusV2_data.php

Stream Stats watershed


delineation

Generates
watershed
above userdefined
point
location Use Version
3

http://water.usgs.gov/osw/streamstats/

Northeast
terrestrial habitat

habitat
layers that
are
northeast
specific (big
file)

http://conserveonline.org/workspaces/ecs/documents/neterrestrial-habitat-mapping-project

Raster datasets - formats and finding them on the Internet

111

Community Service with Web-Based GIST

Fire

Fire
perimeters
and land
cover data
for US

http://landfire.cr.usgs.gov/viewer/

WUI

Wildland
urban
interface
(USA)

http://silvis.forest.wisc.edu/maps/wui_main

Northeast ocean
data

Variousmarine and
fisheries
data,
climate,
managment,
some
marine fish

http://northeastoceanviewer.org/#

Land cover data

National
Land Cover
Database
(NLCD),
raster

http://www.mrlc.gov/

Name

Description

Website

SPECIES
DATA

VegBank

Percent cover of
plant species in
the US and
Canada

http://vegbank.org/vegbank/index.jsp

Global
biodiversity
information
facility

Global herbaria
& specimen
collections with
location info

http://www.gbif.org/species

Movebank

Animal track
data for a few
species

https://www.datarepository.movebank.org/

EDDMapps

Invasive plant
distribution data
in the US

http://www.eddmaps.org/

IOOS

Integrated
Ocean
Observing
System (takes
some digging)

http://www.ioos.noaa.gov/observing/welcome.html

Raster datasets - formats and finding them on the Internet

112

Community Service with Web-Based GIST

Name

Description

Website

HUMAN &
POLITICAL
TIGER
shapefiles

Census demographic data and


ACS block group data on
economics

http://www.census.gov/geo/mapsdata/data/tiger-data.html

TIGER line
files

Roads and political boundaries

http://www.census.gov/geo/mapsdata/data/tiger.html

Global
anthromes

Anthropogenic land use in global


ecosystems

http://ecotope.org/anthromes/v2

Raster datasets - formats and finding them on the Internet

113

Community Service with Web-Based GIST

4.2. Georeferencing a Scanned Paper Map


or Image (such as an aerial photo)
A note before we begin: We are assuming students in this course are already familiar with
concepts such as map coordinate systems, datums and projections. If that is an incorrect
assumption, we encourage you to read the Understanding Coordinate Systems and Map
Projections available on the course Moodle site under Week 4 content.
While as we noted in Section 4.1, there are many places on the Internet where you can get
already georeferenced digital raster data in a variety of formats, it is sometimes the case
where a project needs raster data but the only available data are in paper form, such as a
paper map, or is in digital form, such as a .jpg, but that jpg file is not georefrenced.
Examples of the former paper maps often occur in projects that are historical in nature.
Suppose, for example, that your project wants to display interactive layers that represent the
change in beach shape or erosion over the last 50 years for some beach area in Cape Cod.
There might be available aerial photographs representing different time points over the last
50 years, but they very well could be printed paper photos. An example of a digital jpg file
might be current day photos taken by a low-end quadcopter, but the imagery is only a jpg file
and not georeferenced, meaning that there is no accompanying coordinate system or
projection file that helps GIS software place that image in some geographically explicit
coordinate space. A jpg image that does not have coordinate or projection information
attached to it, will simply sit in a GIS mapping software like QGIS somewhere around the
0,0 point of a cartesian plane.
This section describes part of the process for getting a paper map or digital raster image that
is not associated with a map coordinate system so that it is georeferenced.
To begin, you must do several things:
First, if you have a paper map that you want to get into GIS, then you must identify the
metadata on this map that tells you what coordinate system or map projection it is in. Look
for information like Projection or Datum.
If the map you want to work with is an aerial photograph on paper, or a jpg or other
scanned raster file of that image, well, that image will likely not have a projection or
coordinate system associated with it (unless this is an already georeferenced raster image
where it has another file with the same first name but with an extension name like .twf
standing for tiff world file which IS its georeferencing information. Recall we discussed
this in Section 4.1.

Georeferencing a Scanned Paper Map or Image

114

Community Service with Web-Based GIST

4.2.1. Georeferencing Step 1. Review your paper map for


needed metadata.
To build on this sections introduction, lets first describe a common scenario where you need
to do this kind of georeferencing. Imagine you are working in a part of the world that doesnt
have easily available digital raster maps, such as USGS topographic maps. In the United
States, scanned, geographic digital rasters of these are sometimes called Digital Raster
Graphics or DRG files, but in many parts of the world the only map data you have available
to you is good old paper hardcopies like the one shown in Figure 4.2.1, below.

The first step toward the digitizing and georefencing this paper map is to review its metadata
data about data. Figure 4.2.2 below is a scan of the metadata that was attached to the
paper map shown in Figure 4.2.1.

Georeferencing a Scanned Paper Map or Image

115

Community Service with Web-Based GIST

Review this metadata and paper map specifically looking for information on its map
coordinate system used (coordinate system and datum) and to see if there are coordinate
system lines (either projection lines or latitude/longitude graticule lines that cross and could
serve as ground control points of GCPs. In Figure 4_2_1, identifying GCPs will be easy
since we have located four of them for you. But look at this map as if those four arent there.
Question 4.2.1: What is the map coordinate system used? What is its datum? What
measurement unit is used? (The answers are at the end of this section).

4.2.2 Georeferencing Step 2. Scan your map to a jpg or tif


file.

Georeferencing a Scanned Paper Map or Image

116

Community Service with Web-Based GIST

In a real world situation, next you need to find a digital scanner. Ideally, for maps, this
would be a larger scanner device. In desperate situations, you might be able to achieve a
usable digital product by, as best you can, flattening your paper map out on a floor or table,
and then carefully taking a picture of it using a digital camera or even a smartphone. But
those techniques are only to be used in times where no other option is possible. Many copyshop businesses have large-bed scanners that can do this job for you.
A very important part of this process is to make a note, prior to scanning, of the ground
control points (GCPs) you will use to georeference this image. Simply put, GCPs are point
locations on the paper map where the coordinates are known. In Figure 4.2.1 above, these
are crosshair lines where the UTM projection lines cross. They indicate the geographic
location of the center of those crosshairs. So as you make the digital scan, you need to
double check the scan output to make sure the GCPs you plan to use to georeference are
visible in the scanned output.
The minimum number of GCPs you need to do georeferencing are 4, and they need to be
well-distributed across the map, meaning covering the broad edges of the map, similar to
the four we highlight in Figure 4.2.1 above. Ideally, you would use more than four GCPs and
distribute them around the map product. For the georeferencing process, the scanned image
gets stretched to fit the new coordinate system you specify using the GCP information,
which is why you need your GCPs distributed widely on the map product. The more GCPs
you have, generally, the more accurate your georeferencing will be, assuming that you place
these GCPs accurately in the georeferencing process (described below).
(Side note: If you are in a situation where the paper map or image (such as an aerial
photograph) does not have coordinate system crosshair lines of them, a different way to get
the GCP information would be to use a tool like Google Earth and zoom in to the area on the
earth depicted in your image, to look for (hopefully) permanent objects that have not shifted
location, such as road crossings, or where a power line crosses a road, etc. Using Google
Earth, you can zoom in to these areas and record the longitude/latitude coordinates of these
locations. In this case your paper maps GCP coordinate system will then be Geographic
(Latitude\Longitude) using the global datum WGS84.)
After considering the above, scan your map to a .jpg output. For this exercise, we have done
that work for you. Simply right-click on Figure 4.2.1 above and choose save as and save
the .jpg figure image to an exercise work folder on your computer. Using Windows Explorer
or Finder (mac) rename that image and call it topomap_scan.

4.2.3. Enable and run the QGIS Georeferencer plug-in.


Start up QGIS.

Georeferencing a Scanned Paper Map or Image

117

Community Service with Web-Based GIST

QGIS has its own georeferencing plugin tool, called the georeferencer. To work with it, you
have to enable it first. On the menu bar, go to Plug-ins, Manage and Install Plugins, and
search for georeferencer as shown in Figure 4.2.3.1 below.

Click on the white box to the left of the Gereferencer GDAL to enable it and close the
Plugins window. By enabling this plugin, the georeferencer tool now is available under the
options under the Raster menu item as shown in Figure 4.2.3.2 below.

Click on Raster, Georeferencer to invoke this tool. The Georeferencer window should
appear.

The plug in is divided into two sections. The top half is where the scanned map image will
appear. The bottom section will be where we work with GCP information.

Georeferencing a Scanned Paper Map or Image

118

Community Service with Web-Based GIST

First, in the georeferncer, open the topomap_scan.jpg you saved earlier by clicking on the
open raster icon and navigating to the folder where you stored that file.

The next window that appears is QGIS Coordinate Reference System Selector window
(Figure 4.2.3.4 below) where you are being asked to specify the coordinate system for the
scanned map you are about to georeference. Recall Question 4.2.1 we asked earlier. What
coordinate system and datum does this scanned map use? (See the answer below if you
have forgotten). Under the filter you can type in the CRS search term and then look through
the list for the one you want. Or, typically you will use some of the same coordinate systems
over and over, so you could keep a list of the EPSG numbers that are associated with these
coordinate systems. For example, in Massachusetts, we tend to use, often, Massachusetts
State Plane, NAD83 or UTM zone 18N NAD27.
But importantly what you enter here needs to be the map coordinate system that is
specified on the map metadata! You cannot just choose the coordinate system you want it to
be! The figure below shows the correct selection for this particular map.

Georeferencing a Scanned Paper Map or Image

119

Community Service with Web-Based GIST

Click OK. Your scanned topo map should appear in the top window of the Georeferencer.

Georeferencing a Scanned Paper Map or Image

120

Community Service with Web-Based GIST

Now we are ready to start entering in our ground control point data to convert the scanned
map .jpg from a coordinate system that has a origin centered around the coordinate (0,0) to
one that is moved into the map coordinate system (in our case, UTM Zone 18). To see what
we mean, in the Georeferencer window, move your cursor to the top left corner of the
scanned map. While doing this, look at the X, Y coordinate numbers shown in the bottom
right of the screen. If you move the cursor to the top left corner of the map, you should see
the following in the bottom right:
Transform: Not Set 0,0 None
The 0,0 (or some small numbers like -2, 3 depending on where your cursor is) shows that
currently your .jpg image is being displayed in a simple X, Y cartesian plane with the origin
at 0,0 in the top left.
Now what we want to do is systematically, tell the computer point locations on the scanned
map (GCPs) and then enter their X, Y values using the map coordinate system. But what
numbers do we need?
If you notice on our scanned image, we have drawn four small red crosshairs with a circle
around them, designating the four GCPs we want to use for this georeferencing exercise.
Each of these four points have associated UTM Zone 18 coordinate numbers associated
with them. We show these coordinates using callouts in the Figure below.

Georeferencing a Scanned Paper Map or Image

121

Community Service with Web-Based GIST

You probably know how we got those coordinates. But in case you dont, let us describe
how, using GCP #4 (bottom right of the above figure) as an example.
In your Georeferencer browser, use the zoom tool (the little magnifier glass with the +) and
zoom into the bottom right corner of the map to get a better look at the lines that intersect at
GCP #4 in the Figure above. After zooming, your screen should look something like the
below:

Georeferencing a Scanned Paper Map or Image

122

Community Service with Web-Based GIST

The coordinates at the crosshair of GCP #4, is


705000E 4695000N
The scan in the figure above is is hard to read the UTM Easting coordinate numbers at the
bottom, but the line that the GCP #4 is on is 705000E and if your eyes are good, you should
be able to read that (except for the very small 7 at the beginning of the number). Note that
these coordinates are different than the Latitude/Longitude coordinates that are also shown
at the bottom right of the figure above. We are going to enter the UTM coordinates, not the
Lat/Long coordinates.
The UTM coordinates for the northing lines (the ones going up the Y axis) can be seen a
little higher up the map on the right boundary, as shown in the figure below.
[Fig_4_2_3_9.png]
It was using those coordinates, that we were able to identify the GCP coordinates for GCP
1,2,3 and 4 in the figure with the callouts shown earlier.
Our task at this juncture is to digitize our selected GCPs and enter their corresponding
coordinates so that QGIS can shift the map from the cartesian coordinates centered
around (0,0) to the map UTM coordinate system that has coordinates roughly around
(703000, 4699000).
It is imperative that you enter the GCPs systematically, and you carefully enter the
coordinate data. Double or even triple-check your entering in of these coordinates. One typo
of a digit will cause big problems!
Our GCP coordinates are as follows:

Georeferencing a Scanned Paper Map or Image

123

Community Service with Web-Based GIST

GCP #1 (bottom left): 703000E, 4695000N GCP #2 (top left): 703000E, 4699000N GCP#3
(top right): 705000E, 4699000N GCP #4 (bottom right): 705000E, 4695000N
To enter the GCPs, there are three icons on the tool bar of the Georeferencer: Add point,
Delete point and Move point. The Add point icon has the small yellow star and is the first on
the left, the delete point has the red x and is the middle, and the move point has the arrow
pointing to the right. These icons are shown below.

Using the Zoom and Pan tool, zoom in to the first GCP location in the bottom left. Your zoom
should enable you to see the crosshair location clearly so you can digitize that location with
minimal spatial error. Zooming in too close will result in a pixelated image making it harder to
locate that crosshair. Once you have a zoom that gives you a clear and accurate look at the
crosshair, click the Add point icon and carefully click on the crosshair location for GCP #1.
The Enter Map Coordinates window appears. Enter GCP #1s Easting (East) and Northing
(North) coordinates. Your screen should look similar to the figure below.

Double check your coordinate typing, and if satisfied, click OK. A red dot will appear where
you entered that coordinate and you will see a row appear in the lower part of the
Georeferencer window (see the Figure below).

Georeferencing a Scanned Paper Map or Image

124

Community Service with Web-Based GIST

The GCP table is describing the location of the point in terms of the original source
cartesian coordinates (srcX, srcY) as well as the new destination UTM coordinates for the
point you just entered (dstX, dstY). Right now, given there is only one GCP entered
remember you need a minimum of 4 so the moving or stretching or the georeferncing
of the image cant be completed yet. The residual(pixels) number at the right will give you an
indication of the goodness of the fit of your coordinates once you have at least four GCPs
recorded. Stay tuned.
Zoom out and move your window to zoom into the second GCP at the top left of the map
image. Follow the same procedure as above: Zoom in to the right view for accuracy, click the
add point icon, carefully add the GCP coordinate data, after double checking your coordinate
input, press OK. After completing, systematically, the four GCPs, your map should have four
points digitized and four records in your GCP table. The Georeferencer will use the
destination coordinates to warp and fit the image to the map coordinate system you have
specified.

Georeferencing a Scanned Paper Map or Image

125

Community Service with Web-Based GIST

Notice that the coordinates in the bottom right are still in the original cartesian plane system
that is has an origin in the top left of (0,0).
Now we are ready to Transform the image from the old coordinate system to the new one.
Select the Transformation Settings icon at the top icon menu

or go to the QGIS

menu and choose Settings, Transformation Settings.


There are a number of different algorithm approaches to transform the image to the map
projection coordinate system.
According to the QGIS documentation on the Georeferencer [1] the following transformation
types are available:

Georeferencing a Scanned Paper Map or Image

126

Community Service with Web-Based GIST

The Linear algorithm is used to create a world file and is different from the other algorithms,
The Helmert transformation performs simple scaling and rotation transformations.

The Polynomial algorithms 1-3 are among the most widely used algorithms introduced to match sour

The Thin Plate Spline (TPS) algorithm is a more modern georeferencing method, which is able to i
The Projective transformation is a linear rotation and translation of coordinates.

The one well use in this exercise is the Polynomial 1 (Polynomial 2 requires at least 6
GCPs which is why we are not using that one).
In the Transformation settings window, Enter the following:
Transformation Type: Polynomial 1 Resampling method: Nearest neighbor Compression:
NONE Output raster: topo_utm (and save it to an exercise work folder on your hard disk). It
will save it as a geotif (.tif) format. Target SRS: NAD27 / UTM Zone 18N (this is the
coordinate system you want it translated to. See the figure below.)

Georeferencing a Scanned Paper Map or Image

127

Community Service with Web-Based GIST

Click OK on the Transformation Settings window.

Georeferencing a Scanned Paper Map or Image

128

Community Service with Web-Based GIST

You will now see some new information in the GCP table with residuals.
The dX and dY columns GCP table report the difference in location between the reference
image and the rectified image in pixels. The residual column reports the residual value for
the control point. Below the GCP table is the transformation (rectification) mean error when
we ran this exercise. Note at the bottom right corner you also have a Transform: Mean
error score.

Ideally, you will work to achieve a residual value less than 0.5 pixel width or less than some
small acceptable tolerance. Additionally, ideally the Transform mean error at the bottom of
the window will be less than 2.0. In our case, it is .126015. Not bad.
Generally, ff the residual is less than 0.5 pixels and/or the mean error is less than 2.0, the
rectified image is probably pretty good. If the residual is greater than 0.5 pixels or the mean
error is greater than 2.0, then delete or readjust the existing GCPsl to reduce the residual

Georeferencing a Scanned Paper Map or Image

129

Community Service with Web-Based GIST

error. Try taking more GCPs and see what effect this has on the residuals and the Mean
error score. If you need to delete a GCP you digitized poorly, use the delete point tool (next
to the add point icon). Or is you need to move one to a better location, use the Move Point
tool.
Small changes and not choosing the exact pixel between the two images can have
dramatic effect on the resulting residuals and hence the quality of the final rectified image
output.
Once you are satisfied with the mean error, we can run the Georeferencing process. In the
Georeferencer window, press the Start Georeferencing (play) icon.

A small window will pop up signaling the processing of the georeferecing process. In our
case, it was very fast. The new georeferenced GeoTif file that we named topo_utm.tif
should be in your work folder on your hard disk.
Close the Georeferencer window. Save the GCP points in case you want to georeference
the image again to adjust for overlay errors you witness later when you try and overlay this
new .tif file with another spatial data layer.

4.2.4. View the new georeferenced topo_utm.tif in QGIS


Open up a new QGIS map (if it isnt already open) and look at the current coordinate
system. It should be a cartesian plane around 0,0.
Add a new raster layer, and choose your topo_utm.tif file.
You should see the new georeferenced image, with the image slightly skewed to the upper
left, which was a result of the transformation process, warping the image to the GCP
coordinates that you entered, as shown in the figure below.

Georeferencing a Scanned Paper Map or Image

130

Community Service with Web-Based GIST

The EPSG at the bottom right should read 26718, which is the number associated with the
projection UTM Zone 18N, NAD27. If you move your cursor over the map, you will see the
coordinates at the bottom change from simple small numbers to the larger numbers
representing the UTM coordinate system.
Finally, you could check the Project menu, Project Properties option, to double-check that
this QGIS map project took on the UTM 18 N, NAD27 map projection or coordinate system.
Congrats! Youve georeferenced a scanned paper map!

4.2.5. Georeferencing other scanned products, such as


digital aerial photographs
Sometimes the GIS Analyst needs to georeference paper or digital products that are not
map products with no coordinate system lines on it. For example, several times in our career
weve had to do this to get historical aerial landcover photos into GIS, or perhaps some very
old paper maps that did not have coordinate lines on them. An example of the latter was a
very old map a student of ours had of the city of Boston during the revolutionary war. All this
paper map (taken from some history book) had on it was roads and beach shore locations.
Georeferencing a Scanned Paper Map or Image

131

Community Service with Web-Based GIST

It can be a challenge, but in these kinds of cases you can do the same process as described
above. The key issue is finding GCP locations and their coordinates. One way to do this in
this modern Internet era is to use a tool like Google Earth to find the lat/long coordinates of
road intersections that you see on the image you are trying to georeference. For aerial
photographs, there might be other objects in the image you could use, like some rock
outcroppings that are visible and appear to not have changed in the Google Earth image.
We discussed this earlier, but again, road crossings, road and electrical line crossings, larger
objects like rock outcroppings are possibly helpful choices for GCPs. Even building corners
might work. You just have to find objects that you can see in the image or map you are trying
to georeference and what you can see in the Google Earth image.
Systematically find the GCP coordinates by comparing the image with Google Earth and
then carefully record the Google Earth Lat/Long location it displays when your cursor is over
the desired location.
Another approach would be to use a GIS layer you already have georeferenced, such as a
roads layer for the area, and in QGIS use the cursor to find the coordinates for road
crossings you see in your, currently, no-georefenced image.
Finally, another rather time-consuming way to get GCPs is to take a GPS and go out to
places that are still identifiable in your old image or map. This assumes you are in the
geographic vicinity of where you are trying to map.
Once you have collected at least four GCPs for this image, you can go through the same
process as described above.

References
[1] https://docs.qgis.org/2.2/en/docs/user_manual/plugins/plugins_georeferencer.html

Answers to questions asked in Section 4.2.


Question 4.2.1. What is the map coordinate system used? What is its datum? What
measurement unit is used?
Universal Transverse Mercator (UTM) map projection. Zone 18. Surprisingly, the metadata
doesnt tell us that this is UTM Zone 18 North, but the map makers probably assumed that
people would know that this area of the world, Massachusetts, is in the northern
hemisphere. 1927 North American Datum (NAD27) Units: meters

Georeferencing a Scanned Paper Map or Image

132

Community Service with Web-Based GIST

If this is confusing to you, that probably means you dont understand map coordinate
systems and projections very well. We encourage you to read the Understanding
Coordinate Systems and Map Projections pdf reading that is available on the course
Moodle site under Week 4 content to brush up on these topics.

Georeferencing a Scanned Paper Map or Image

133

Community Service with Web-Based GIST

Key Postgres and PostGIS steps from


Weeks 2 and 3
Summary of some key steps from Weeks 1-4
We assume you have installed QGIS, pgAdmin, Postgres and PostGIS. Before proceeding
make sure that the Postgres server is running.
1. Create a user account for your Postgres database
In pgAdmin, under your postgres local server, right click and choose "New Object" and
then "New Login Role"
Under the "Properties" tab, Role Name: "user" (or whatever you want)
Under the "Definition" tab, password "user" (or whatever you want as long as you will
remember it!)
Type the password in again
2. To create a new database in Postgres using pgAdmin
In pgAdmin, right click on Databases
Choose New Database
Properties: name your database, and assign it an owner
3. To create a PostGIS database in Postgres using pgAdmin
Right click on Databases under Postgresql, New Database, give a name to your
database with owner postgres.
Find your database under Postgres, Databases
Under your new database, choose the public schema
Use the SQL editor and run the command CREATE EXTENSION postgis; (use the
play button to run that query)
In the SQL Editor, run SELECT postgis_full_version(); to verify that your postgis
database is operational.
In the Object Browser of pgAdmin, right click and refresh. You should see a new table
(spatial-ref-sys) appear and also several new Views that are related to the PostGIS
database structure.
4. To connect to the PostGIS/Postgres database in QGIS
Open up the Browser in QGIS

Key Postgres and PostGIS steps from Weeks 2 and 3

134

Community Service with Web-Based GIST

Choose PostGIS
Right click and create new connection
Name: Give it a name
Host: localhost
Port: 5432
Database: Whatever you named it in Step 1 above
Username: use a user login that you created following the directions under #1
above. Don't user Postgres since that is a superuser account.
Password: use the password for that user login above
Test the connection. Hopefully it works!
Press OK. You should see the new PostGIS entry in your browser
5. Import shapefiles (or other vector formats) into your PostGIS database using DB
Manager
In past material, we suggested using either pgShapeloader or SPIT. But weve found since
then that SPIT is buggy. So below we are suggesting a different way, that seems more
robust, using the DB Manager in the QGIS icon menu. Try these steps next time you want
to import a shapefile into your PostGIS database:
In the Browser Panel, right-click on PostGIS, and select New Connection.
Fill in the parameters of the connection and test it.
Menu Database > DB Manager > DB Manager.
Open the list item PostGIS
Click on the connection you created in step 2.
Click on the button Import layer/file.
In the dialog Import Vector Layer, choose the layer to import;
Click the button Update options to copy the input name to the Table name.
Click the button OK.
Your imported shapefile should appear if you refresh in the QGIS browser.

Key Postgres and PostGIS steps from Weeks 2 and 3

135

Community Service with Web-Based GIST

5: Introduction to Web Mapping and


Serving Geospatial Data on the Web
Lesson Goals
Students understand general elements of a Web map, gain an understanding of the concept
of tiling used in Web mapping applications, and get experience working with their own webmapping server, Geoserver.

Lesson Outcomes
Students understand:
The concepts of Basemaps, Thematic Layers, and Interactive Elements found in Web
Map applications;
The idea of tiling and pyramids of images for use in Web mapping;
The role of a map server, like Geoserver in Web mapping, and in particular, for the
serving of thematic layers.
Using the tools we have used up until now (pgAdmin, QGIS, Postgres, PostGIS) students
can:
Create a PostGIS database with an important shapefile stored in it;
Set up a local geoserver on their own laptop computer and administer it;
Create a WFS using their PostGIS database and their newly running Geoserver;
Access their WFS through QGIS.

Introduction to Web Mapping and Serving Geospatial Data on the Web

136

Community Service with Web-Based GIST

5.1: Elements of a Web Map


Acknowledgments: This material is a slight derivative of a course module written by
Sterling Quinn of the John A. Dutton e-Education Institute, College of Earth and Mineral
Sciences, The Pennsylvania State University, and was produced with permission from the
author. We thank the author, and Penn State for permission to use. The material is licensed
under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.

Building and using web maps is different from working with a desktop GIS for a variety of
reasons:
In a web map, any information you see has to be sent across the wire from the server
to your browser, introducing latency.
In a web map, you may be pulling in information from several different servers. Your
map performance is therefore limited by the availability and speed of all the servers
you're using.
In a web map, performance may be affected by other people using the server at the
same time.
In a web map, you are limited to the display technologies supported by the client
application, which may be a basic web browser.
These considerations can sometimes take people by surprise. For example, if you've only
used ArcMap or QGIS in the past, you may not be accustomed to thinking about broadband
speeds or sharing the machine with other people.
By far, the biggest challenge for new web mappers is understanding the amount of data that
is displayed in their maps and how to get all that information drawn on the screen of a web
user in sub-second speeds. Many people who have worked with desktop GIS packages are
accustomed to adding dozens (or even hundreds) of layers to the map and switching them
on and off as needed. Your powerful desktop machine may be able to handle the drawing of
this kind of map; however, performance will be unacceptably slow if you try to move the map
directly to the web. The server requires precious time to iterate through all those layers,
retrieve the data, draw it, and send the image back to the client.
To address this problem, most web maps break apart the layers into groups that are handled
very differently. Layers whose sole purpose are to provide geographic context are grouped
together and brought into the map as a single tiled basemap. In contrast, thematic layers

Elements of a Webmap

137

Community Service with Web-Based GIST

(the layers that are the focus of the map) are brought in as one or more separate web
services and placed on top of the basemap. You might additionally decide to include a set of
interactive elements such as popups, charts, analysis tools, and so forth.
Let's take a closer look at these three things--basemaps, thematic layers, and interactive
elements--to understand how each is created and displayed.

Basemaps
A basemap provides geographic context for your map. In other words, it is usually not the
main reason people look at your map, but your map would be difficult to interpret without it.
The most common basemaps you've used online are vector road maps and remotely
sensed imagery (consider, for example, the basemaps when youve used Google Maps).
Although a basemap may consist of many sublayers (such as roads, lakes, buildings, and so
forth), these are often fused together into a rasterized set of tiled images and treated as a
single layer in your web map. These tiled maps consist of often thousands or millions of
predrawn images that are saved on the server and passed out to web browsers as people
pan around the map. (A future lesson will explain tiled maps in greater depth.)
Sometimes two tiled layers will work together to form a basemap. For example, you may
have a tiled layer with aerial imagery and a second tiled layer with a vector road overlay that
has been designed to go on top of the imagery. (In Google Maps, this appears when you
check the Labels item). Keeping these two tilesets separate takes less disk space and
makes it easier to update the imagery.

Thematic layers
Thematic layers (also known as business or operational layers) go on top of the basemap.
They're the reason people are coming to visit your map. If placed on the basemap, they
might not be of interest to everybody, but when placed on your focused web map, they are
the main layer of interest. If your map is titled Farmers markets in Philadelphia, then
farmers markets are your thematic layer. If your map is titled Migration patterns of North
American birds, then the migration patterns are your thematic layer.
Like basemaps, thematic layers are sometimes displayed with tiles; however, this may not
always be possible due to the rapidly changing nature of some data. For example, if you
need to display the real time positions of police vans, you cannot rely on predrawn tiles and
must use some other way to draw the data. Web Mapping Services (WMS) are designed to
draw maps on the fly in this way. You can use these for your thematic layers. Another option

Elements of a Webmap

138

Community Service with Web-Based GIST

is to query the server for all the data and use the browser to draw it. This approach lends
itself well to interactive elements such as popups, and well discuss this approach when we
get to the use of Leaflet.
Thematic layers work together with basemap layers to form an effective web map.
Interestingly, the thematic layer is not always the top one. Esri cartographer Charlie Frye
describes a map sandwich approach, wherein a thematic layer (which could be tiled or not)
is placed in between two tiled basemap layers that give geographic context. The bottom
layer has physiographic features and the top layer has labels and boundaries. This is the
bread. The thematic layer in the middle is the meat. A blog post by Charlie Frye contains
a more thorough explanation and a helpful diagram. You can use this approach with FOSS
software.
Your map may include several thematic layers that you allow users to toggle on and off. To
accomplish this, you can use a single web service with multiple sublayers, or multiple web
services that each contain a single layer. However, to keep your app usable and relatively
fast-performing, you should avoid including many thematic layers in your web map.

Interactive elements
Web maps are often equipped with interactive elements that can help you learn more about
the layers in the map. These can be informational popups that appear when you click a
feature, charts and graphs that are drawn in a separate part of the page, slider bars that
adjust the time slice of data displayed in the map, and so forth. Some web maps allow you to
edit GIS data in real time, or submit a geoprocessing (e.g., analytic) job to the server and
see the response drawn on the screen. Others allow you to type a series of stops and view
driving directions between each.
These elements make the map come alive. The key to making an effective web map is to
include the interactive elements that are most useful to your audience, without overwhelming
them with options or making the tasks too complicated. Even a little bit of housekeeping,
such as including user-friendly field aliases in your popups, can go a long way toward
making your map approachable and useful.
Interactive elements are the part of your web map that require the most custom
programming. The amount of interactivity you have the freedom to add may be strongly
correlated with the amount of JavaScript programming that you know how to do. Open web
mapping Application Program Interfaces (APIs; see [1] at bottom) such as OpenLayers and
Leaflet provide convenient methods for doing some of the most common things, such as
opening a popup.

Elements of a Webmap

139

Community Service with Web-Based GIST

Later in this lesson, you'll examine some web maps and discuss the interactive elements
they provide. You'll also revisit this subject later in the course as you begin using the web
mapping APIs to put all your layers together into a web map.

Getting some practice with identifying web map elements


Let's get some practice identifying these elements, we will walk you through several simple
web maps and point out the basemap, the thematic layers, and the interactive elements.
Texas Reservoir Levels
The first map we'll look at is Texas Reservoir Levels, published in the Texas Tribune. This is
a simple but useful map similar in scope to what you will be creating in this course. Take a
minute to open this map and examine it.
The basemap is a tiled map hosted by Mapbox.com, a cloud-based map hosting service
that offers a variety of basemaps for this purpose. The unintrusive light gray color allows
any thematic layers to rise to the top of the visual hierarchy. The basemap contains
roads, states, cities, and a few other feature types that appear as you zoom in.
However, it doesn't contain any obscure types of features that would steal the viewer's
interest away from the thematic layers.
The thematic layer consists of the circles showing reservoir levels. These are drawn by
the web browser. When the map first loads, the geographic locations of the reservoirs
are retrieved from a GeoJSON file (a format for encoding a variety of geographic data
structures - see http://geojson.org/).
The interactive element of this map consists of an informational window in the upper
right corner of the map that changes content when you hover over a feature. When you
add interactive elements to your web maps, you will often add code that "listens" for
particular events, such as clicking, tapping, or hovering over a feature.
Envisioning Development Toolkit - Interactive Income Map
Next, open the Envisioning Development Toolkit - Interactive Income Map of New York City.
This map is made using Flash; therefore, we have a little less visibility into what's going on
behind the scenes. However, the basic elements of the map are easily identifiable.
The basemap again uses a noninstrusive black and white design. Pan around enough,
and you'll notice that it is brought into the web map using tiles.
The thematic layer is a vector outline of New York neighborhoods. Behind this is sitting
some income data from the US Census that has been aggregated to the neighborhood
boundaries. This layer is also designed to be somewhat nondescript, because the map

Elements of a Webmap

140

Community Service with Web-Based GIST

authors really want you to look at the colored blocks representing population at the
different income levels.
The interactive elements are what make this map come alive. Hovering over a
neighborhood causes a subtle highlight, inviting you to click for more information. When
you click, the graph adjusts itself to update the population counts (this is where the
Flash animation comes in handy). Tooltips on hover and an informational window in the
upper right corner provide additional information.
Northern Plains Conservation Network Interactive Web Map
To wrap up this exercise, take a look at the Northern Plains Conservation Network
Interactive Web Map. Get a feel for the map by toggling on and off some of its many layers.
This map appears to be created in JavaScript using elements of the Google Maps API.
The basemap is tiled. It is the "Terrain" layer from the Google Maps API. It is up to you
to decide whether this is helpful (this map does have some connection to topography
since it is a map of the Northern Plains) or distracting (the map is more colorful than the
previous two basemaps we've seen).
Most, if not all, of the thematic layers also seem to be tiled. This makes sense when you
consider that most of these layers are probably not changing on a regular basis;
therefore they can be committed to tiles and brought into the application more rapidly
than a dynamically drawn map.The tiles are being pulled from CartoDB, a cloud-based
map authoring and hosting service. Sometimes it's easiest to use someone else's online
services to design and host your tiles. In an upcoming lesson, you'll get a feel for the
effort it takes to design and host your own tiles (which you may decide to do if you want
to avoid hosting fees). The large number and variety of thematic layers in this map
make it somewhat difficult to determine the purpose and audience of the map.
The interactive elements include the ability to toggle layers, adjust layer transparency,
search for a location, and take a screen capture. You must use the legend to interpret
the data ranges. It appears there is a button for querying the data, but I couldn't
immediately figure out how to use it.
Other maps
Here are a few other maps you can look at if you want to keep practicing. Although some of
these maps have very nice elements, I am recommending them for their variety, not for their
excellence in any particular realm.
Tri-Met Trip Ride Planner
Best of British Unsigned
NIU Campus Webmap
Lethbridge Explorer

Elements of a Webmap

141

Community Service with Web-Based GIST

From this brief exercise, you can begin to see the various approaches that can be used to
put together a web map. Hopefully, you can look at a web map and immediately begin to see
how the layers were broken up into basemap layers and thematic layers. Whenever you see
a web map, you should also think about the interactive elements that are present and decide
whether they are usable and applicable.

[1] An API (application program interface) is a set of routines, protocols, and tools for
building software applications.

Elements of a Webmap

142

Community Service with Web-Based GIST

5.2. The Idea of Tiled Maps


Acknowledgements: This material is a slight derivative of a course module written by Sterling
Quinn of the John A. Dutton e-Education Institute, College of Earth and Mineral Sciences,
The Pennsylvania State University, and was produced with permission from the author. We
thank the author, and Penn State for permission to use. The material is licensed under a
Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.

5.2.1 Introduction to Tiled Maps


The earliest web maps were typically drawn on the fly by the server, no matter how many
layers were available or requested. The symbol sets and labeling choices for this type of
map are relatively limited and complex to work with. In fact, for many years, web
cartographers had to build a map with minimal layer set and simple symbols to avoid
hampering performance (e.g., speed to which the map would be displayed on the client
computers end). In many cases, a cartographer was not even involved; instead, the web
map was made by a server administrator tweaking eXtensible Markup Language (XML) files
that defined the layer order, symbol sizes, and so forth. This was the case with both open
specification web services (like WMS) and proprietary web services (like Esri ArcIMS). Part
of this approach stemmed from early efforts to make web GIS applications look exactly like
their desktop counterparts. Sometimes these are referred to as Swiss Army Knife
applications because they try to do everything (you may know one!). People expected that
in a web GIS they should be able to toggle layer visibility, reorder layers, change layer
symbols on the fly, and do everything else that they were accustomed to doing using
desktop GIS packages. Ironically, this mindset prevailed at a time when web technology was
least suited to accommodate it.
In the mid-2000s, after Google Maps, Microsoft Virtual Earth (now Bing Maps), and other
popular mapping applications hit the web, people started to realize that maybe they didn't
need the ability to tinker with the properties of every single layer. These providers had
started fusing their vector layers together in a single rasterized image that was divided into
256 x 256 pixel images, or tiles. These tiles were pre-generated and stored on disk in the
server for rapid distribution to clients. This was done out of necessity to support hundreds or
thousands of simultaneous users, a burden too great for drawing the maps on the fly.
The figure below shows how a tiled map consists of a "pyramid" of images covering the
extent of the map across various scales. Tiled maps typically come with a level, row, and
column numbering scheme that can be shared across caches to make sure that tile
boundaries match up if you are overlaying two tile sets.

The Idea of Tiled Maps

143

Community Service with Web-Based GIST

Fig 5.2.1 Caption: Tiled web maps take the form of a pyramid where the map is drawn at a
progressive series of scale levels, with the smallest (zoomed out) scales using fewer tiles.
(Figure credit (and much of this readings text) goes to Sterling Quinn, of Penn State and
their e-Education Institute from their Why Tiled Maps reading available at https://www.eeducation.psu.edu/geog585/node/706).
When reviewing Figure 5.2.1 above, and references to larger scale and smaller scale
maps, it is important to remember the terms large and small scale are as geographers define
them. Recall that to a geographer, a large scale map means each tile represents a finer
physical area on the ground, and small scale means the tile represents a broader region on
the ground. You may understand that large and small scale using this terminology is based
on the ratios in map scale. A 1-inch represents 200,000 inches on the map scale
(1:200,000) is a smaller scale map compared to a 1-inch equals 1,000 inches on the map
(1:1,000) because its scale 1:200,000 is a smaller ratio than 1:1,000. So to geographers,
small and large mean the opposite of what some non-geographers might interpret when they
hear large and small scale maps.
Turning back to Figure 5.2.1, the tile at the top of the pyramid is a small scaled tile in that it
covers the same physical area on the ground as the set of 16 tiles at the bottom of the
pyramid. Because the tile at the top of the pyramid covers that entire area at the bottom of
the pyramid (but with courser pixel resolution), it is a smaller-scaled tile in geographers
definition of scale. Alternatively, each tile of the 16 tiles at the bottom of the pyramid,
represent a finer area on the ground, so they are larger spatial scale tiles compared to the
one at the top of the pyramid.

The Idea of Tiled Maps

144

Community Service with Web-Based GIST

Cartographers loved the innovation of tiled maps, because now they could invest all the
tools of their trade into making an aesthetically pleasing web map without worrying about
performance. Once you had created the tiles, you just had a set of images sitting on disk,
and the server could retrieve a beautiful image just as fast as it could retrieve an ugly one.
And because the tiled map images could be distributed so quickly by a web server, Google
and others were able to employ asynchronous JavaScript and XML (AJAX) programming
techniques to retrieve the tiles with no page blink as people panned. (You may still
remember seeing the tiling phenomenon if you have used Google Maps or Earth in the past,
where as you zoom in to a finer area of the Earth you see coarser, sometimes rasterized
images get replaced with finer, clearer images. This is the replacement of smaller scale tiles
with larger ones as one zooms in to the larger scale from the top of the pyramid to the
bottom in Figure 5.1.2.).
This was revolutionary. Which would you rather have: a slippy map [1] with stunning
cartography and no layer control, or a clunky and ugly map with the ability to reorder layers
and adjust the color of a school? Some longtime GIS geeks had to stop to think about this,
but for the common web user, the choice was a no-brainer.
Within a year or two of Google Maps' release, commercial GIS software began offering the
ability to build map tiles. For many, ArcGIS Server was desirable because the map could be
authored using the mature map authoring tools in ArcMap; however, cost was a concern for
some. Arc2Earth was another commercial alternative. The free and open source Mapnik
library could also build tiles, but it wasn't until recent years that projects like TileMill wrapped
a user-friendly GUI around Mapnik.

The Idea of Tiled Maps

145

Community Service with Web-Based GIST

Fig 5.2.2 Caption: Tiles from OpenStreetMap data, rendered by MapQuest.


Tiled maps were the only model that could reasonably work for serving complex web maps
to thousands of simultaneous users. However, they eliminated the ability for users to change
layer order or symbols. People started working around this by serving out their generalpurpose basemap layers as tiles and then overlaying a separate layer with thematic
information. The general-purpose basemap tiles could be re-used in many applications. The
thematic layers could also be tiled if the data didn't change too quickly or cover too broad of
an area at large scales.

5.2.2. Making the Decision to Build and Maintain Tiles


If you want faster navigation of your basemap or you feel that more than a couple of users
will be requesting maps simultaneously from your server, you should create a tile cache of
your basemap. You may also choose to cache thematic layers if their features are not
constantly changing attributes or position. In both cases, be aware that the tile cache
represents a snapshot of your data at the time the cache was created. To put it more bluntly,
your tiles are dumb images that will not automatically update themselves when the back
end raster or vector data they represent change. You are responsible for periodically

The Idea of Tiled Maps

146

Community Service with Web-Based GIST

creating new tiles in order to update the map. With large caches, sometimes server
administrators target the cache updates at just the changed areas rather than rebuilding tiles
for the entire map. This requires keeping some kind of log about which places were edited,
or comparing before and after versions of a dataset. Is there an existing tile cache that
meets your needs?
Building a tiled basemap requires lots of rich data, high-end map authoring software,
cartographic skills, and potentially enormous amounts of time and disk space. You may still
need to do it, which is why we are discussing it. However, because of these challenges,
general-purpose web mashups often use tiles made by somebody else. OpenStreetMap is
an attractive option if you want free tiles with no restrictions. If you want to use Google's,
Microsoft's, or Esri's tiles, you may be able to use them for free or you may have to pay,
depending on the nature of your map (commercial or not for profit) and how many people
use your app. Other companies such as CloudMade and MapBox have marketed their own
versions of tiles using OpenStreetMap data.
If you are going to build your own basemap, it's helpful to have an experienced cartographer
on staff who is experienced with designing at multiple scales. The symbols, colors, and
details must be adjusted appropriately at each of the scales where tiles are created. Tiled
basemaps can quickly get complicated with layer and labeling scale suppression rules.
Cartographers may also need to design one set of tiles to stand on its own and another set
of tiles to overlay satellite imagery, a task that requires very different colors and symbols.
Projection
If you are going to overlay your tiles with any of the tiles from OpenStreetMap, Google,
Microsoft, or Esri (or even just attempt to look like them), you must convert your GIS data
into a modified spherical Mercator projection that was created solely for the convenience of
fitting the world onto a set of square tiles. Mercator has the property of representing angles
more accurately for high latitude locations in the Earth when zoomed in to large (close to the
ground) scales (recall Fig 5.2.1). Since web GIS maps like Google Maps were used most
often by users for finding street-level locations or directions, this was the projection the
Google Maps people decided to use [2]. GIS purists balked at this idea because the
Mercator projection exaggerates areas farther away from the equator (see the discussion in
[2]) and predicted it would fail to achieve mass uptake, but many people (at least at mid
latitudes) now hold their nose and move forward with it. Be aware that Esri, Google, and
other organizations have used other code numbers and variations of this projection in the
past: things can get very confusing if you are using older software or APIs. In the past
couple of years, people seem to have standardized on EPSG:3857 although even the
subparameters of this projection can be interpreted in diverse ways that lead to offsets.

The Idea of Tiled Maps

147

Community Service with Web-Based GIST

Even when you display your maps in EPSG:3857, you do not ever want to perform
measurements in this projection. The results will be largely skewed even at mid latitudes. It's
best to make sure that geometries are projected into a more local coordinate system before
performing any measurements. The Esri blog post Measuring distances and areas when
your map uses the Mercator projection provides a good overview of the problem and an
example solution that uses the ArcGIS API for JavaScript, although the concepts can also
be applied with FOSS APIs (to be discussed later).
Scales
Not only must you match the projection in order to overlay, you must also match the scales.
These are not nice well-rounded numbers; rather, they were derived mathematically from the
starting point of putting the whole world on a 2x2 grid of tiles. For example, one of the scales
is 1:36,111.98 and as you zoom in, the next one is 1:18,055.99. So much for your simple
USGS 1:24000 series! Partly for this reason (and partly because many laypeople don't
understand map scales), the common web map scaleset is often referred to with simple
numbers such as Level 14, Level 15, etc., that increase as you zoom in. You just have to
get a feel for which levels correspond to national scale, provincial scale, city scale,
neighborhood scale, etc. The table in the Bing Maps Tile System article is helpful for this.
To conclude, this reading was included to help you understand conceptually, the idea of tiling
for web mapping, and some of the key issues that are involved. In a future exercise, we will
be working with tiled images and Geoserver. But first, we will just turn to working with
establishing data that are served by Geoserver, building on what you know already related to
Postgres and PostGIS and WMS and WFS.

Footnotes
[1] Slippy map: a term referring to modern web maps which let you zoom and pan around
(the map slips around when you drag the mouse).
http://wiki.openstreetmap.org/wiki/Slippy_Map
[2] See the discussion on this Google forum, especially the response by Joel H.
https://productforums.google.com/forum/#!topic/maps/A2ygEJ5eG-o

The Idea of Tiled Maps

148

Community Service with Web-Based GIST

5.3. Introduction to Serving Geospatial


Vector Data using Geoserver
5.3.1. Introduction
Recall in previous exercises we had you install Postgres as a server on your laptop, and
your laptop was acting both as a server with Postgres, and as a client using pgAdmin and
QGIS.
In this exercise, we now are going to install a Geoserver on your laptop as well (see the
Figure below). Your laptop will be running two servers (Postgres and Geoserver) for your
client application QGIS to access. Simply put, Geoserver (or other similar servers, such as
Mapserver) is a an open source computer server that shares geospatial data. It follows the
open standards established by the Open Geospatial Consortium.

Figure caption: System Architecture for Web Mapping. A derivative of figure developed by
RRZEicons. CC-BY-SA-3.0. and available at Wikimedia Commons. We learned about this
figure from Sterling Quinn and his exercise at https://www.eeducation.psu.edu/geog585/node/684

Introduction to Serving Geospatial Vector Data using Geoserver

149

Community Service with Web-Based GIST

5.3.2 Get some data for this exercise (Mass Biketrails line shapefile) and import it into
a Massbike PostGIS database
Youve built a Postgres/PostGIS database before and have imported shapefiles, but it is
always good to get some more practice. Try to do this by memory, or if you get stuck, go
back and review the Key Postgres and PostGIS steps from Weeks 2 and 3 document. That
document also has new information added to remind you about how to create
groups/userids for your database so you dont log in using the postgres superuser account.
Download and unzip the Biketrails shapefile dataset from MassGIS.
In pgAdmin:
If you need to, first create a new user (call it user maybe?) that is NOT postgres (the
superuser) that you can use to create your postgres/postgis database. (See #1 in Key
Postgres and PostGIS steps from Weeks 2 and 3 for information on that if you dont
know how to do this.)
Create a new Postgres database called Massbike that has an owner user. (See #2 in
Key Postgres and PostGIS steps from Weeks 2 and 3 for information on that if you dont
know how to do this.)
Make the Massbike database a PostGIS database. (See #3 in Key Postgres and
PostGIS steps from Weeks 2 and 3 for information on that if you dont know how to do
this.)
Connect to your Massbike PostGIS database in QGIS and import the Biketrails
shapefile into this Massbike PostGIS database. (See #4 and #5 in Key Postgres and
PostGIS steps from Weeks 2 and 3 for information on that if you dont know how to do
this.)

5.3.3. Install Geoserver on your laptop


Follow Geoserver Install Documentation for your operating system:
http://docs.geoserver.org/stable/en/user/installation/
Choose either
Windows installer
or
Mac OS X installer
Important Notes:

Introduction to Serving Geospatial Vector Data using Geoserver

150

Community Service with Web-Based GIST

GeoServer requires a Java 7 environment (JRE) to be installed on your system. This must
be done prior to installation. The Geoserver install documentation directs you to download
the proper version of the Java Runtime Environment (JRE) if not already on your computer.
Mac: you may have to use ctrl-open on Mac if the application is not recognized as safe to
open.
Under the Geoserver menu, start the server.
You may see some warning about security issues. We will address some of these issues in
the exercise.
The web interface shown at http://localhost:8080/geoserver requires a login before you can
do anything useful. Use the default admin as username and geoserver as password.
To change your admin password in the web interface (see steps 1-6 in images below):
1. Select Users, Groups, Roles
2. Select Users/Group Tab
3. Click on admin under the Username column
4. Change the Password and Confirm
5. Click Save

Introduction to Serving Geospatial Vector Data using Geoserver

151

Community Service with Web-Based GIST

Introduction to Serving Geospatial Vector Data using Geoserver

152

Community Service with Web-Based GIST

You should read through the Web Administration Interface Quickstart. You will be making
some of the changes suggested in this guide (such as Contact Information) once you begin
project work on the server. For now, just read through the options.
5.3.4. Publishing Vector Data (in this case, your Biketrail stored in a PostGIS Table)
We begin with publishing a vector thematic shapefile from our PostGIS Table and will
generally follow the process outlined in the documentation found here:
http://docs.geoserver.org/stable/en/user/gettingstarted/postgis-quickstart/index.html
You should have already loaded your shapefile (biketrails_arc.shp) into PostGIS in the steps
outlined in section 5.3.2 above.
Follow the directions starting with Create a Data Store, but substituting values appropriate
for our data as specified below:
Choose PostGIS - PostGIS Database for the new Vector Data Source (NOT PostGIS
NG)
[Basic Store Info]
Data Source Name: biketrails_arc
Description: Massachusetts Bike Trails
Database: massbike
User: your postgres user you created in Section 5.3.2. above (we chose user)

Introduction to Serving Geospatial Vector Data using Geoserver

153

Community Service with Web-Based GIST

Passwd: your password you selected (we chose user)


The PostGIS data Connection Parameters should reflect which PostGIS database you used
for your biketrails shapefile. Remember that you should refrain from the postgres user if
possible since that is an administrative user that can alter the entire database!
The New Layer window should appear.
Your should see and select the biketrails layer name in the layer dropdown list. (Depending
on the operating system you are using this might look slightly different):
Under Action, click Publish

Type in Massachusetts Bike Trails from MassGIS for the Abstract.


For the Coordinate Reference System (or Declared SRS), click the Find button, and search
for Massachusetts or 26986 and then select the code number (26986). This stands for State
Plane Massachusetts Mainland, NAD83 datum.
Then click the Compute from data and then Compute from Native bounds to fill in the correct
values (see Figure below)

Introduction to Serving Geospatial Vector Data using Geoserver

154

Community Service with Web-Based GIST

Go back to the top of the screen and click the Publishing Tab, and make sure the Default
style is line, given the bike trails is a line vector layer.

Click Save.
You now should have a massbike PostGIS layer that is being served by your local
GeoServer (the one running on your laptop).
You should be able to complete the steps to Preview the Layer. You should also be able to
add this layer to QGIS by establishing a WFS connection similar to what we did in Week 1.
However, you will be connecting to your local computer instead of a server. For example,
http://localhost:8080/geoserver/cite/wfs
When successful, take a screenshot of your QGIS screen displaying your WFS biketrail data
and upload to Moodle under this week's pre-class section.

Introduction to Serving Geospatial Vector Data using Geoserver

155

Community Service with Web-Based GIST

Chapter 6: Static Data on the World-Wide


Web
Lesson Goals
Students are knowledgeable composers of the static languages of the Web: HTML, CSS,
and SVG.

Lesson Outcomes
Students can:
Mark up pages of plain text using HTML
Insert and format images
Style HTML pages with CSS
Design and insert graphics using SVG
Recognize better ways to mark up existing texts

Introduction
The World-Wide Web is a set of computer technologies that publish and view information
over the Internet in a highly interactive manner.
This information, commonly text and images, is structured using the HyperText Markup
Language (HTML) and styled using Cascading Style Sheets (CSS).
Additional types of content can be used with HTML, in particular Scalable Vector Graphics
(SVG) for displaying geometric shapes (similar to Adobe Illustrator).
Geographic data such as basemaps or digital elevation models can be displayed using
images.
Geographic data in the form of points, lines, and polygons can be displayed using SVG.
CSS can be used to properly position and overlay different geographic data sets, assuming
they have the same coordinate system.
In this chapter we will learn about these static languages of the Web and how they form the
foundation of Web-based GIST.

Static Data on the World-Wide Web

156

Community Service with Web-Based GIST

Chapter 6: Static Data on the World-Wide Web


Introduction

Previous:
5.2 The Idea of Tiled Maps
Next:
6.1 Web Publishing

Static Data on the World-Wide Web

157

Community Service with Web-Based GIST

Chapter 6: Static Data on the World-Wide


Web
6.1 Web Publishing
Web publishing, generally speaking, consists of three steps:
1. Edit a web page on your local computer;
2. Review the edited page on your local computer with one or more web browsers and
return to step (1) to correct any issues;
3. Publish the page on a remote web server where others can see it.
4. Link to it so others can find it.

Editing Web Pages


There are a large number of applications that help one edit HTML, CSS, and SVG.
They can be as simple as text editors with syntax highlighting, or they can be What-YouSee-Is-What-You-Get (WYSIWYG) editors, or they can be full-blown Integrated
Development Environments (IDEs).
Since the emphasis in this course will be on general methods, no specific editors are
required.
Here are a few possible open-source editors, one or more of which you should download
and install:
Macintosh:
Aquamacs text editor based on Emacs
Windows:
Notepad++ text editor based on Scintilla
Cross-platform:
Komodo Edit text editor based on the Komodo IDE
BlueGriffon WYSIWYG Web page editor
Eclipse IDE with support for many languages

Reviewing Web Pages


Web Publishing

158

Community Service with Web-Based GIST

Making sure your Web pages accurately display your content and design requires that you
review them with actual Web browsers, even if you are using a WYSIWYG editor like
BlueGriffon or Dreamweaver.
Unfortunately there are variations in how browsers interpret Web languages, so it is
advisable to review your pages in several of them to check for discrepancies.
Older browsers are more likely to have issues, especially with the latest standards, so well
assume users are up-to-date or can get up-to-date if they need to:
Macintosh:
Safari 5.1 or later
Windows:
Internet Explorer 9.0 or later
Cross-platform:
Firefox 20.0 or later
Chrome 26.0 or later
To test for specific capabilities, visit the site caniuse.com.
Static Web pages, as well as many dynamic pages, can remain as files on your personal
computer and be read and displayed properly by your browser alone.
When Web pages become more complex, for example when they are constructed on the fly
after pulling information from a database, its necessary to load them from a Web location
rather than a file, so that a Web server can process them first.
Web servers can run on your local computer to provide a testing environment for your
pages. There are a number of of open source Web servers available, but for this course well
use a relatively new, lightweight server called Node.js.
You can download and install Node.js on most personal computers if they arent too old. If
you arent able to install it, you can use a remote server instead (see the next section).

Publishing Web Pages


For others to see your Web pages, youll need to publish them on a dedicated Web server
that is always on and ready to share your pages with the world.
As part of this course youll have access to a remote server where you can publish your
projects.

Web Publishing

159

Community Service with Web-Based GIST

You can put your web pages where others can see them using Internet protocols such as
Secure File Transfer Protocol (SFTP) or Secure Copy (SCP):
Macintosh:
Terminal.app Mac-supplied command-line interpreter (a shell) that runs sftp and scp
(amongst many other commands), located in /Applications/Utilities
Aquamacs menu Tools > Shell Command to run commands such as sftp and scp
Fugu a graphical SFTP client: make sure you download the Intel-based version at
the bottom of this page!
Windows:
Notepad++ provides an SFTP plug-in
Putty a suite of tools including sftp and scp
You can sometimes also mount a network disk from a remote server using the Common
Internet File System (CIFS) also called System Message Block (SMB). In this case your
disk space on the remote computer will appear on your desktop, and youll simply copy the
edited page over to it as you would move around any other file. This capability is built-in to
most operating systems:
Macintosh:
Switch to the Finder and menu Go > Connect to Server.
Windows:
Menu Start > Computer, and then at the top of the window choose Map Network
Drive.

Chapter 6: Static Data on the World-Wide Web


6.1 Web Publishing

Previous:
Introduction
Next:
6.2 HyperText Markup Language (HTML)

Web Publishing

160

Community Service with Web-Based GIST

Chapter 6: Static Data on the World-Wide


Web
6.2 HyperText Markup Language (HTML)
The HyperText Markup Language (HTML) is designed to give your information semantic
structure that can be understood by both people and computers.
The full specification of HTML 5.0.

Textual Content
Consider the information in Dodges Geography of New England (1912) describing
Massachusetts. Would you understand it as easily if it appeared as one big clump of text, as
follows?

HyperText Markup Language (HTML)

161

Community Service with Web-Based GIST

HyperText Markup Language (HTML)

162

Community Service with Web-Based GIST

Massachusetts Cities and Towns Gain in Population. In Massachusetts (Fig. 104) the
steady drift of the people toward the cities is the most striking feature in the growth and
movement of population. (Fig. 103.) This state has a greater number of large cities than
any other in the Union and of all the states only Rhode Island surpasses it in a greater
proportion of urban to rural population. At the same time the rate of increase in the
number of the people of the cities or urban centers in Massachusetts is less than that of
New York, and is exceeded by that of Rhode Island and Connecticut. In 1910
Massachusetts had twenty-five cities of more than 25,000 people; with this number we
may compare New York with twenty-one and New Jersey with fourteen such centers.
Including only cities having 10,000 or more persons we find that fifty-five cities had
more than four-fifths of all the people living in Massachusetts. Boston (Fig. 107), the
greatest city of New England, beginning as a little settlement on a hilly peninsula jutting
out into Massachusetts Bay, has extended for miles along the shore; has filled and
occupied the adjacent marshes; and has from time to time taken in large areas to the
south and west, until to-day it covers an area of not less than forty-three square miles.
The fifth city in size and the second great commercial center of the Union, its growth is
due to the advantages of its position. Nature endowed it with a fine, deep, and spacious
harbor (Adv. Geog., Fig. 214), and its situation farther inland than that of any other city
north of Cape Cod has attracted a large coastwise and foreign trade. Boston is the
second seaport in the country. New York alone surpasses it in extent of commerce. It is
America's greatest wool market, as well as its greatest market for leather and leather
goods; and it has a large and growing trade in many other imported or domestic
manufactured articles. Railroads (Fig. 107) radiating in all directions connect the city
with every part of New England as well as with New York and the West. Hence it is the
natural outlet for the agricultural and manufactured products of all New England with
the exception of southwestern Connecticut. This last mentioned region finds its most
accessible market in New York City. Lines of elevated and electric railroads aided by a
fine subway in the heart of the city supply means for local transportation. These
connecting with steam roads and trolley lines also afford efficient and rapid
communication with the scores of populous suburbs that fringe the borders of the city
as well as with many other important places. Boston is one of the five great industrial
cities of the United States. Like most large cities it has varied manufactures. It ranks
fourth as a center for the refining of sugar and molasses. A literary as well as an
educational center, it ranks fourth also in printing and publishing. The making of
clothing, of boots and shoes, and of foundry and machine-shop products is also
important. Large quantities of coffee and spices are imported and here prepared for
market.
For millenia, writers have structured their text to make it easier to read, breaking it into
semantic groups with different meanings, such as headings, paragraphs, lists, tables, etc.

HyperText Markup Language (HTML)

163

Community Service with Web-Based GIST

To distinguish these groups of text visually, they would use different styles such as spacing,
typeface, size, italics, color, et al.
For example, in traditional typographic convention, headings are generally in larger type and
in bold face, both headings and paragraphs are usually set off with a margin before and
after, lists have bullets () or numbers in front of each list item, emphasized text is set in
italics, etc.
The HyperText Markup Language (HTML) interpreted by Web browsers provides the same
capabilities, using extra instructions called markup to describe the semantics of the text.
Default styles for HTML markup are defined by Web browsers and generally follow the
above conventions.
HTML markup elements consist of an opening tag and a closing tag surrounding content, in
the format <tag>text</tag> ; for example:
Headings of different importance, used for titles and subtitles:

HyperText Markup Language (HTML)

164

Community Service with Web-Based GIST

<h1>The Geography of New England</h1>


<h2>I. New England as a Whole</h2>
<h3>Size and Location</h3>

HyperText Markup Language (HTML)

165

Community Service with Web-Based GIST

The Geography of New England


I. New England as a Whole
Size and Location

Paragraphs used for long passages of text, commonly in the body of a document:

HyperText Markup Language (HTML)

166

Community Service with Web-Based GIST

HyperText Markup Language (HTML)

167

Community Service with Web-Based GIST

<p>In Massachusetts (Fig. 104) the steady drift of the people toward the cities is the most striking

This state has a greater number of large cities than any other in the Union and of all the states onl

At the same time the rate of increase in the number of the people of the cities or urban centers in M

In 1910 Massachusetts had twenty-five cities of more than 25,000 people; with this number we may comp

Including only cities having 10,000 or more persons we find that fifty-five cities had more than four
</p>

<p>Boston (Fig. 107), the greatest city of New England, beginning as a little settlement on a hilly p

The fifth city in size and the second great commercial center of the Union, its growth is due to the

Nature endowed it with a fine, deep, and spacious harbor (Adv. Geog., Fig. 214), and its situation fa
Boston is the second seaport in the country.
New York alone surpasses it in extent of commerce.

It is America's greatest wool market, as well as its greatest market for leather and leather goods; a
</p>

In Massachusetts (Fig. 104) the steady drift of the people toward the cities is the most
striking feature in the growth and movement of population. (Fig. 103.) This state has a
greater number of large cities than any other in the Union and of all the states only
Rhode Island surpasses it in a greater proportion of urban to rural population. At the
same time the rate of increase in the number of the people of the cities or urban centers
in Massachusetts is less than that of New York, and is exceeded by that of Rhode
Island and Connecticut. In 1910 Massachusetts had twenty-five cities of more than
25,000 people; with this number we may compare New York with twenty-one and New
Jersey with fourteen such centers. Including only cities having 10,000 or more persons
we find that fifty-five cities had more than four-fifths of all the people living in
Massachusetts.
Boston (Fig. 107), the greatest city of New England, beginning as a little settlement on
a hilly peninsula jutting out into Massachusetts Bay, has extended for miles along the
shore; has filled and occupied the adjacent marshes; and has from time to time taken in
large areas to the south and west, until to-day it covers an area of not less than fortythree square miles. The fifth city in size and the second great commercial center of the
Union, its growth is due to the advantages of its position. Nature endowed it with a fine,
deep, and spacious harbor (Adv. Geog., Fig. 214), and its situation farther inland than
that of any other city north of Cape Cod has attracted a large coastwise and foreign
trade. Boston is the second seaport in the country. New York alone surpasses it in
extent of commerce. It is America's greatest wool market, as well as its greatest market
for leather and leather goods; and it has a large and growing trade in many other
imported or domestic manufactured articles.
Lists, both unordered <ul></ul> and ordered <ol></ol> , with <li></li> tags around
each list item:

HyperText Markup Language (HTML)

168

Community Service with Web-Based GIST

HyperText Markup Language (HTML)

169

Community Service with Web-Based GIST

<ol>
<li>Amherst College, Non-sect., Amherst.</li>
<li>Lasell Seminary, Non-sect., Auburndale.</li>
<li>Boston College, R, C., Boston.</li>
<li>Boston University, M, E., Boston.</li>
<li>Simmons College, Non-sect., Boston.</li>
<li>Harvard University, Non-sect., Cambridge.</li>
<li>Radcliffe College, Non-sect., Cambridge.</li>
<li>Tufts College, Univ., Medford.</li>
<li>Smith College, Non-sect., Northampton.</li>
<li>Mount Holyoke College, Non-sect., South Hadley.</li>
<li>American International College, Cong., Springfield.</li>
<li>Wellesley College, Non-sect., Wellesley.</li>
<li>Williams College, Non-sect., Williamstown.</li>
<li>Clark College, Non-sect., Worcester.</li>
<li>Clark University, Non-sect., Worcester.</li>
<li>College of the Holy Cross, R. C., Worcester.</li>
<li>Massachusetts Agricultural College, Amherst.</li>
<li>Massachusetts Institute of Technology, Boston.</li>
<li>Worcester Polytechnic Institute, Worcester.</li>
</ol>

1. Amherst College, Non-sect., Amherst.


2. Lasell Seminary, Non-sect., Auburndale.
3. Boston College, R, C., Boston.
4. Boston University, M, E., Boston.
5. Simmons College, Non-sect., Boston.
6. Harvard University, Non-sect., Cambridge.
7. Radcliffe College, Non-sect., Cambridge.
8. Tufts College, Univ., Medford.
9. Smith College, Non-sect., Northampton.
10. Mount Holyoke College, Non-sect., South Hadley.
11. American International College, Cong., Springfield.
12. Wellesley College, Non-sect., Wellesley.
13. Williams College, Non-sect., Williamstown.
14. Clark College, Non-sect., Worcester.
15. Clark University, Non-sect., Worcester.
16. College of the Holy Cross, R. C., Worcester.
17. Massachusetts Agricultural College, Amherst.
18. Massachusetts Institute of Technology, Boston.
19. Worcester Polytechnic Institute, Worcester.
Tables in a hierarchical structure beginning and ending with <table></table> , with <tr>
</tr> tags around each row, <th></th> tags around each column header, and <td>
</td> tags around each datum (cell) in the row:

HyperText Markup Language (HTML)

170

Community Service with Web-Based GIST

HyperText Markup Language (HTML)

171

Community Service with Web-Based GIST

<table>

<caption>Statistics of the State of Massachusetts by Counties from the Federal Census of 1900 and
<thead>
<tr>
<th rowspan="2">County</th>
<th rowspan="2">Organization</th>
<th rowspan="2">Area</th>
<th colspan="3">Population</th>
<th rowspan="2">County Seat</th>
<th colspan="2">Population</th>
</tr>
<tr>
<th>1910</th>
<th>1900</th>
<th>1890</th>
<th>1900</th>
<th>1910</th>
</tr>
</thead>
<tbody>
...
<tr><td>Franklin</td><td>1811</td><td>697</td><td>43,600</td><td>41,209</td><td>38,610
<tr><td>Hampden</td><td>1812</td><td>636</td><td>231,369</td><td>175,603</td><td>135,713
<tr><td>Hampshire</td><td>1662</td><td>585</td><td>63,327</td><td>58,820</td><td>51,859
...
</tbody>
</table>

Statistics of the State of Massachusetts by Counties from the Federal Census of 1900 and of 1
Population
County

Organization

1910

1900

1890

County
Seat

Area

...
Franklin

1811

697

43,600

41,209

38,610

Greenfield

Hampden

1812

636

231,369

175,603

135,713

Springfield

Hampshire

1662

585

63,327

58,820

51,859

Northampton

...
Phrase elements, which add meaning to small pieces of text, such as whether they are
emphasized (using <em></em> ), are citations (using <cite></cite> ), et al.:

HyperText Markup Language (HTML)

172

Community Service with Web-Based GIST

<p><em>Boston</em> (Fig. 107), the greatest city of New England, beginning as a little settlement on

The fifth city in size and the second great commercial center of the Union, its growth is due to the

Nature endowed it with a fine, deep, and spacious harbor (<cite>Adv. Geog.</cite>, Fig. 214), and its
Boston is the second seaport in the country.
New York alone surpasses it in extent of commerce.

It is America's greatest wool market, as well as its greatest market for leather and leather goods; a
</p>

Boston (Fig. 107), the greatest city of New England, beginning as a little settlement on
a hilly peninsula jutting out into Massachusetts Bay, has extended for miles along the
shore; has filled and occupied the adjacent marshes; and has from time to time taken in
large areas to the south and west, until to-day it covers an area of not less than fortythree square miles. The fifth city in size and the second great commercial center of the
Union, its growth is due to the advantages of its position. Nature endowed it with a fine,
deep, and spacious harbor (Adv. Geog., Fig. 214), and its situation farther inland than
that of any other city north of Cape Cod has attracted a large coastwise and foreign
trade. Boston is the second seaport in the country. New York alone surpasses it in
extent of commerce. It is America's greatest wool market, as well as its greatest market
for leather and leather goods; and it has a large and growing trade in many other
imported or domestic manufactured articles.
Note that HTML ignores multiple spaces, tabs, and newlines in the text, replacing any
contiguous group of such white space with a single space. So, for example, the sentences in
the paragraph above that all begin on separate lines automatically join together.
Different elements are also displayed differently:
Headings, paragraphs, lists, and tables by default have a block-level display, meaning:
they always start a new line;
they have a rectangle of space assigned to them that extends across the page;
they ignore white space at the beginning and end of their content.
Phrase elements by default have an inline display, so that they act like ordinary pieces
of text (though they still fill a rectangular space).

Graphic Content
HTML includes several ways to mix graphic content with text. These elements generally
consist of single tags, in the format <tag /> (note the trailing / ):
Line breaks force new lines at particular points in text:

HyperText Markup Language (HTML)

173

Community Service with Web-Based GIST

<p>
By Lyman R. Allen, formerly Instructor in Geography,
State Normal School, Providence, Rhode Island,<br />
and Alonzo J. Knowlton, Superintendent of Schools, Belfast, Maine.
</p>

By Lyman R. Allen, formerly Instructor in Geography, State Normal School, Providence,


Rhode Island,
and Alonzo J. Knowlton, Superintendent of Schools, Belfast, Maine.
Note: <br /> tags should not be used as a substitute for paragraphs! They provide visual
formatting, but have no inherent meaning themselves. If you are introducing a new
paragraph, use </p><p> instead, since these tags add meaning along with the visual
separation.
Horizontal rules help visually separate blocks of text:
<hr />
<h5>The Leading Educational Institutions of New England</h5>
<hr />

The Leading Educational Institutions of New England

Images can be pulled from any location on the Web by providing an <img /> tag together
with attributes such as src followed by an = and a value between quotation marks:
<p>
The State Capitol at Boston, aka the Massachusetts State House.<br />
<img src="images/chapter6_2/Dodge_s_Geography_of_New_England%2058_Fig_108.jpg"
width="45%"
title="Fig. 108. The State Capitol at Boston."
alt="The Massachusetts State Capitol sits high on a hill overlooking Boston Common."
/>

<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/88/Massachusetts_State_House_-_B
width="45%"
title="Massachusetts State House, Boston, Massachusetts, USA."
alt="The Massachusetts State House in Boston is distinctive due to its golden dome."
/>
</p>

HyperText Markup Language (HTML)

174

Community Service with Web-Based GIST

The State Capitol at Boston, aka the Massachusetts State House.


If attribute values contain spaces, quotes, =, <, or >, then they should be quoted with either
single or double quotes (traditionally the latter, but never the same type as any embedded
quotes).
In both of the above cases the images are in JPEG format. The first is located in a folder
named images that is in the same folder as this web page, i.e. they are siblings. The
second is referenced from elsewhere on the Web.
Images have a particular width and height in pixels, 928716 in the first case and 320240
in the second. But the attributes width and height can be used to set different dimensions
with values that are either numbers (expressing pixels) or as a percent of the page width, as
above (note what happens to the image as you change the page size). If only one of the two
attributes is declared, an image will be scaled proportionately.
The title attribute provides a brief description that will pop up when you point at (not click
on) an image. Try it!
The alt attribute is important for those with visual handicaps, as it will be read aloud by
screen readers and without it the image will be ignored. It should always be included to
provide an extended textual description of what the image shows, if that is not obvious from
the title or included elsewhere in the document (such as in a caption).
Line breaks and images by default have an inline display (like phrase elements), while
horizontal rules by default have a block-level display (like paragraphs).

Hyperlinks
HTML is hypertext because it allows you to mark up specific pieces of text with hyperlinks
to other web pages (which is what makes the World-Wide Web possible).
For example, we can link to the source of Dodges Geography of New England using an
anchor element:

HyperText Markup Language (HTML)

175

Community Service with Web-Based GIST

Read <a href="https://books.google.com/books?id=-DREAQAAMAAJ">Dodges Geography of New England

Like the image element, an anchor takes an attribute href that refers to the other web
page.
Also like an image element, an anchor is displayed inline.
In your browser, this HTML will by default appear in the same font and style as surrounding
text, but underlined:
Read Dodges Geography of New England for more information.
and clicking on it will load the referenced page into your browser. (Note that this document
chooses to color links but only underlines them when you are pointing at or clicking on
them.)

Document Elements
When writing an HTML document, there are a number of elements that should be included
to help define the characteristics of the document. A minimal HTML document is:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
</body>
</html>

The content we have been writing above goes between the <body></body> tags, e.g.

HyperText Markup Language (HTML)

176

Community Service with Web-Based GIST

<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" />
<title>The Geography of New England</title>
<meta name="author" content="Lyman R. Allen" />
<meta name="author" content="Alonzo J. Knowlton" />
<meta name="date" content="1912">
</head>
<body>
<h1>The Geography of New England</h1>
<p>
By Lyman R. Allen, formerly Instructor in Geography,
State Normal School, Providence, Rhode Island,
<br />and Alonzo J. Knowlton, Superintendent of Schools, Belfast, Maine.
</p>
<hr />
<h2>II. Growth and Development of Cities and Towns</h2>
<p>
<img src="images/chapter6_2/Dodge_s_Geography_of_New_England%2058_Fig_108.jpg"
width="100%"
title="Fig. 108. The State Capitol at Boston."
alt="The Massachusetts State Capitol sits high on a hill overlooking Boston Common."
/>
</p>
<h3>Massachusetts Cities and Towns</h3>
<p>

In Massachusetts (Fig. 104) the steady drift of the people toward the cities is the most

This state has a greater number of large cities than any other in the Union and of all th

At the same time the rate of increase in the number of the people of the cities or urban

In 1910 Massachusetts had twenty-five cities of more than 25,000 people; with this number

Including only cities having 10,000 or more persons we find that fifty-five cities had mo
</p>
<p>

<em>Boston</em> (Fig. 107), the greatest city of New England, beginning as a little settl

The fifth city in size and the second great commercial center of the Union, its growth is
Nature endowed it with a fine, deep, and spacious harbor (<cite>Adv. Geog.</cite
Boston is the second seaport in the country.
New York alone surpasses it in extent of commerce.

It is America's greatest wool market, as well as its greatest market for leather and leat
</p>
</body>
</html>

Here we can clearly see the hierarchical structure of an HTML document, with many
elements being containers of content and other elements.
The <head> element contains code that is not intended for display within the main web
page, including:

HyperText Markup Language (HTML)

177

Community Service with Web-Based GIST

<meta> elements providing information about the document itself (known as metadata),

such as:
the character set to use (8-bit Unicode in the above, a way to display every
character you can imagine ).
the author, date created, et al.
A <title> to be displayed as the title of a browser window or tab;
<style> elements for CSS styling instructions (to be discussed later);
<script> elements for JavaScript programming code that doesnt depend on specific

elements defined in the body (also to be discussed later).

HTML Comments
One other important type of nondisplayed data are comments, which are explanatory bits
of text about whats happening in a document. They are single tags with the following format:
<!-- This is an HTML comment. -->

If anything you are writing is more than routine, its a good idea to include a comment to
explain your intentions.

Web Inspectors
Modern web browsers provide a means to inspect both the content and detailed structure of
web pages.
To see the underlying source code as first loaded by a browser:
Safari:
1. If the Develop menu is not visible:
i. Menu Safari > Preferences;
ii. In the dialog that appears, click on the tab Advanced;
iii. Check on Show Develop menu in menu bar.
2. Menu Develop > Show Page Source.
Firefox: Menu Tools > Web Developer > Page Source;
Chrome: Menu View > Developer > View Source;
Internet Explorer:

HyperText Markup Language (HTML)

178

Community Service with Web-Based GIST

1. If the Menu bar is not visible, right-click on the page header, and in the pop-up
menu that appears, select Menu bar.
2. Menu View > Source.
To see the detailed structure of the code as interpreted by the browser, including changes
made by Javascript, open the web inspector:
Safari:
1. If the Develop menu is not visible:
i. Menu Safari > Preferences;
ii. In the dialog that appears, click on the tab Advanced;
iii. Check on Show Develop menu in menu bar.
2. Menu Develop > Show Web Inspector.
Firefox: Menu Tools > Web Developer > Inspector;
Chrome: Menu View > Developer > Developer Tools;
Internet Explorer: Menu Tools > Developer Tools;
In Firefox, the inspector looks like:

HyperText Markup Language (HTML)

179

Community Service with Web-Based GIST

Notice that, as you point at or click on individual elements, they are highlighted in the display
view above the inspector, and you can see the size of their container in pixels.
You can also open and close different parts of the HTML hierarchy by clicking on the buttons
open-branch / and close-branch / at the left of each element.

Exercises

HyperText Markup Language (HTML)

180

Community Service with Web-Based GIST

HyperText Markup Language (HTML)

181

Community Service with Web-Based GIST

HyperText Markup Language (HTML)

182

Community Service with Web-Based GIST

The section of The Geography of New England that describes the Pioneer Valley (before it
was known by that name) begins on p. 67 with Towns of the Connecticut Valley and
continues to p. 69. Turn it into a Web page!
1. With your editor, create an HTML document with appropriate elements in its head.
Name it gne.html .
2. Using the text of these pages found here, mark up the paragraphs so that they have the
same structure as the document shown to the right. (Dont try to put it in two columns,
though that is not easily done!)
3. Add the headings The Geography of New England, II. Growth and Development of
Cities and Towns, and finally Towns of the Connecticut Valley, each at the appropriate
level.
4. Add a hyperlink from the heading The Geography of New England to the online
document.
5. Add these images at the appropriate positions, providing both alt and title
attributes:
Fig. 127. High Street, Holyoke, looking south.
Fig. 128. A group of Smith College buildings, Northampton. To the right may be

HyperText Markup Language (HTML)

183

Community Service with Web-Based GIST

seen Music Hall.


Fig. 129. View of the Chapel and Dormitory, Amherst College, Amherst.
Fig. 130. Old Frary House, Deerfield. This old house, built in 1698 within a
stockade, was the scene of an Indian massacre.
6. Add a hyperlink to each of these images that will open them in a new page. (Hint: try
clicking on the images above for the Massachusetts State House!)
7. Choose one or more of the institutions described in the document that still exist, and
add a hyperlink to their Web page(s). Do the same for any historical events and persons
mentioned, to their Wikipedia page.
8. Create a list of public normal schools in Massachusetts based on p. 51.
9. Create a table of school population of Massachusetts based on p. 87.

Chapter 6: Static Data on the World-Wide Web


6.2 HyperText Markup Language (HTML)
Previous:
6.1 Web Publishing
Next:
6.3 Cascading Style Sheets (CSS)

HyperText Markup Language (HTML)

184

Community Service with Web-Based GIST

Chapter 6: Static Data on the World-Wide


Web
6.3 Cascading Style Sheets (CSS)
Cascading Style Sheets let you assign styles such as font size and typeface, color, borders,
margins, etc. to HTML elements, to classes of elements, or to individual elements. They can
reproduce traditional typesetting styles but can also do much, much more.
The full specification of CSS 2.1.

Style Definitions
Your Web browser makes a set of default choices about the way that different HTML
elements are styled when a page is opened, and you have some ability to control that using
your browsers preferences. But most Web pages design their own styles using CSS.
CSS statements are usually placed in an HTML <style> element in the <head> element of
the document, and include an HTML markup selector followed by a sequence of property:
value pairs within braces, e.g.
<head>
<style>
h1 { color: red; border: solid; }
</style>
</head>

which gives all <h1> elements red text and a solid border.
You can also place styles in external files with a statement in the <head> like
<link href="gne.css" type="text/css" rel="stylesheet"></link>

where a link is made to a file of CSS text whose relationship is that of a stylesheet.
In such a file no <style> element is necessary.
Using external stylesheets is generally a good practice once they become a fairly extensive
set.

Element Selectors
Cascading Style Sheets (CSS)

185

Community Service with Web-Based GIST

CSS provides several ways to select the different pieces of your HTML markup for styling.
The most general CSS statement is for an element selector, where the property-value pairs
are preceded by the name of the element, e.g.
body { background-color: rgb(244, 237, 222); }

which applies the red-green-blue color combination (each on a scale of 0 255) to the
background of a Web page:
<body>
The Geography of New England
</body>

The Geography of New England


A shorthand for such colors uses a number sign # or hash sign followed by three
hexadecimal (base 16) values, which have the digits 0-9 as well as AF to represent the
values 1015. For the decimal scale 0 255, hexadecimal values run from 0 FF, so this
triplet of RGB values can also be written:
body { background-color: #F4EDDE; }

The Element Box Model


Elements containing content such as text and images generally occupy a rectangular space
on the page. The background color fills this space up to its border, which by default is set to
none , but which can be turned on with different stylings such as solid , dashed , dotted ,

etc.:
body {
background-color: rgb(244, 237, 222);
border: solid;
}

<body>
The Geography of New England
</body>

The Geography of New England


Space or padding between the border and the content can be included using different types
of lengths as values, for example using pixels here:

Cascading Style Sheets (CSS)

186

Community Service with Web-Based GIST

body {
background-color: rgb(244, 237, 222);
border: solid;
padding: 10px;
}

<body>
The Geography of New England
</body>

The Geography of New England


The superimposed red dotted line indicates the boundary between the the padding of the
<body> and the content area filled with text.

Many elements such as headings also have, by default, some space or margin around them,
which lies outside their border and is transparent. The CSS box model of elements, shown in
the image to the right, lets you fully control each of these regions and how big they are.
For example, the <h1> element has a preceding and trailing margin that clearly separates it
from the bodys border, but it has no margin on the left or right side (nor any padding):

Cascading Style Sheets (CSS)

187

Community Service with Web-Based GIST

<body>
<h1>The Geography of New England</h1>
</body>

The Geography of New England


The content inside the body is now the entire <h1> element, surrounded by 10 pixels of
body padding as before. The superimposed blue dashed line indicates the border of the
<h1> element, and the area between it and superimposed red dotted line is the margin of

the <h1> . To the right and left there is no margin, so the two lines coincide.
Text Styling

Cascading Style Sheets (CSS)

188

Community Service with Web-Based GIST

Elements that can contain text also have a default font assigned to them; for the <h1>
above it is a sans-serif font, which is commonly used for headings, though not in the case of
Dodges Geography of New England.
A particular font or font family can be specified for the body element, and this will be
inherited by descendant elements like <h1> and <p> :

Cascading Style Sheets (CSS)

189

Community Service with Web-Based GIST

body {
background-color: rgb(244, 237, 222);
border: solid;
padding: 10px;
font-family: Times, TimesNR,
Georgia, serif;
}

<body>
<h1>The Geography of New England</h1>
<p>By Lyman R. Allen, formerly Instructor in Geography,
State Normal School, Providence, Rhode Island,<br />
and Alonzo J. Knowlton, Superintendent of Schools, Belfast, Maine.</p>
</body>

The Geography of New England


By Lyman R. Allen, formerly Instructor in Geography, State Normal School, Providence,
Rhode Island,
and Alonzo J. Knowlton, Superintendent of Schools, Belfast, Maine.
Here the browser looks for specific fonts installed on your computer in sequence, choosing a
default serif font if necessary. (Probably a serif font is already the default for unstyled text in
your browser.)

Cascading Style Sheets (CSS)

190

Community Service with Web-Based GIST

There are a large number of ways to modify the styling of content for particular purposes. To
match the styling used in Dodge, the following CSS rules for the different heading elements
are a start:

Cascading Style Sheets (CSS)

191

Community Service with Web-Based GIST

h1 {
font-weight: normal;
letter-spacing: 0.1em;
}
h2 {
font-weight: normal;
font-style: italic;
font-size: 1.25em;
}
h3 { font-size: medium; }
h4 {
font-size: medium;
margin: 0 0 0 1em;
}
h1, h2, h3 {
text-transform: uppercase;
text-align: center;
}

<h1>The Geography of New England</h1>


....
<h2>I. New England as a Whole</h2>
<h4>Size and Location.</h4>
....
<h2>II. Growth and Development of Cities and Towns</h2>
....
<h3>Massachusetts Cities and Towns</h3>
<h4>Gain in Population.</h4>

Cascading Style Sheets (CSS)

192

Community Service with Web-Based GIST

The Geography of New England


....

I. New England as a Whole


Size and Location.
....

II. Growth and Development of Cities and


Towns
....

Massachusetts Cities and Towns


Gain in Population.
Note the following about these styles and their effects:
Both of the <h1> and <h2> elements would by default be given a font-weight of
bold , but to match Dodge this property is set to normal .

Similarly, the <h2> element is given a font-style of italic .


The letter-spacing property of the <h1> element and the font-size property of the
<h2> element have been specified using an em, which is the width of the letter m in the

current font.
The font-size properties of the <h3> and <h4> elements is set to medium , which
corresponds to the default font size for most text, which is about 1 em in height.
The margin property has size value(s) that are applied in the order toprightbottom
left, repeating earlier items if not all are provided; for the <h4> element it clears the
normal space at the top and bottom and adds space to the left.
A style set can be applied to multiple elements by separating them with a comma, as for
h1, h2, h3 .

Cascading Style Sheets (CSS)

193

Community Service with Web-Based GIST

Nowadays using text-transform: uppercase; would not be considered the best


approach, as all caps is more difficult to read (and sometimes interpreted as shouting).
Besides, there are many other ways to distinguish headings from regular text, in
particular size, font weight, and color.
The default way that browsers indicate the beginning of a paragraph is by automatically
including a top and bottom margin (so you dont have to include a blank line yourself). The
text-indent property implements the other standard paragraph opening seen in Dodge,

indenting just the first line, and with the margins set to zero all the way around the <p>
element:
p { text-indent: 1em; margin: 0; }

<body>
....

<p>The six New England states, with a combined area a little more than one-half that of the Unite
....
</body>

....
The six New England states, with a combined area a little more than one-half that of the
United Kingdom, occupy the extreme northeastern portion of the United States....
....

Class Selectors
Often you will want to distinguish a particular type of content from the more standard formats
provided by HTML elements, for example in Dodge the authors names are in small caps
format rather than lower case, and their credentials are italicized:

You can specify this formatting by creating a class selector that begins with a period or dot,
such as:
.author { font-variant: small-caps; }
.credentials { font-style: italic; }

Cascading Style Sheets (CSS)

194

Community Service with Web-Based GIST

Such classes can be applied to any HTML element by supplying the attribute class="..." .
In this case we want to apply it to just these bits of text, so well use the generic element
<span> , which has no default styling other than being displayed inline:

<p>
By <span class="author">Lyman R. Allen</span>,

<span class="credentials">formerly Instructor in Geography, State Normal School, Providence, Rhod


and <span class="author">Alonzo J. Knowlton<span>,
<span class="credentials">Superintendent of Schools, Belfast, Maine</span>.
</p>

By Lyman R. Allen, formerly Instructor in Geography, State Normal School, Providence,


Rhode Island,
and Alonzo J. Knowlton, Superintendent of Schools, Belfast, Maine.
Styles may be restricted to particular descendancies of elements by listing them in order in
the selector, without a comma separating them, e.g:
p span.credentials { font-style: italic; }

In this case, only span elements that are of class credentials and that are contained within
a paragraph will have this style applied to them.
However, its a best practice to be this specific only when necessary since the class
credentials is not used in a different way in another context, the selector .credentials by

itself is good enough.


In general class names should represent the purpose of the class, as in the examples
above, not the styles that are going to be applied, e.g. red. Then when you decide to
change their style (e.g. to blue), the class name can remain the same because its meaning
is the same.

ID Selectors
Sometimes a style might be applied only once within a document, for example in Dodge the
authors byline is centered and in smaller type than paragraph text.
Its then useful to identify such specific elements using an ID selector, which begins with the
hash or number sign # , possibly because more generic IDs are often numeric:
#byline { font-size: smaller; text-align: center; text-indent: 0; }
hr#titleSeparator { width: 20%; margin-left: 40%; margin-right: 40%; }

Cascading Style Sheets (CSS)

195

Community Service with Web-Based GIST

These selectors will be applied to the first element that has the matching attribute
id="byline" and the first <hr> element with the matching attribute id="titleSeparator"

but none afterward, so dont use them more than once in a document!
<h1>The Geography of New England</h1>
<div id="byline">
By <span class="author">Lyman R. Allen</span>,

<span class="credentials">formerly Instructor in Geography, State Normal School, Providence, Rhod


and <span class="author">Alonzo J. Knowlton<span>,
<span class="credentials">Superintendent of Schools, Belfast, Maine</span>.
</div>
<hr id="titleSeparator" />
<h2>I. New England as a Whole</h2>

The Geography of New England


By Lyman R. Allen, formerly Instructor in Geography, State Normal School, Providence,
Rhode Island,
and Alonzo J. Knowlton, Superintendent of Schools, Belfast, Maine.

I. New England as a Whole


Because the byline is not really a paragraph, and we dont want it to have any margins or
indentation, we can build it from a <div> element, which has no default styling other than a
block-level display.
Note here that for the <hr> element the margins are set in a different way than before,
using individual properties for each one, such as margin-right . Also, margin size has been
specified with a percentage value, which will be calculated using the width of its parent
element here the body of the document. With equal left and right margins, the effect is to
center this block-level element in the middle of the page. Note that a similar effect is
achieved for the byline with text-align: center; , which applies to inline content inside of a
block-level element.
Again, id attributes can be used with any element, whether a paragraph or a phrase
element, but they should be unique within a document. Since there is probably only one
authors paragraph in Dodge, an id selector would be more appropriate than a class
selector, though either would work.
This markup now begins to look similar to the real thing.
Cascading Style Sheets (CSS)

196

Community Service with Web-Based GIST

Style Attributes
An alternative to an ID selector for applying a style to a single element is the style attribute,
which directly lists the style definitions in the HTML:
<hr style="width: 20%; margin-left: 40%; margin-right: 40%;" />

An ID selector is usually a better choice, however, since it lets you place the style definition
togther with other definitions, and allows you to give it a name that can indicate its purpose.

Cascading Styles
When a web browser combines the different rules you define for the style of a particular
element, occasionally they will conflict, as in the above headers where the heading text by
default is bold but may be converted to normal weight but in all capitals.
The general rules for this cascade of styles are three-part:
1) Style applications with the least amount of inheritence take precedence over more distant
styles.
2) Similarly, more specific styles have precedence; from lowest to highest, these are:
browser default, element selector, class selector, id selector, style attribute.
3) When two styles have the same precedence from the first two rules, the one written later
in the code will have priority over the earlier one.
Remembering these three rules will help you understand the styles that appear in your
document, though there can be exceptions that can be unclear.
The web inspector can help you determine which styles apply to a particular element; after
selecting it in the code listing, it will be displayed in the document with its bounding box
visible, while its computed (final) style and the cascade of rules from highest precedence to
lowest are visible in the lower-right pane:

Cascading Style Sheets (CSS)

197

Community Service with Web-Based GIST

Positioning
The various HTML elements that weve discussed have followed normal flow behavior,
where they are displayed one after another in the same order they are written in your
document.
CSS provides two additional types of positioning, allowing elements to float relative to
adjacent elements, as well as being positioned relative to the elements that contain them.
Flow Content
Since by default most content flows normally in an HTML document, the only difference
weve seen in how content is displayed is that some elements like headings, paragraphs,
divs, and horizontal rules have a block-level display, starting and ending with new lines,
while others like text, phrases, spans, and images have inline display, being placed in the
same line as preceding and following inline elements.

Cascading Style Sheets (CSS)

198

Community Service with Web-Based GIST

This behavior can be changed with the property display , for example:
img.standardImage { display: block; width: 50%; margin-left: 25%; margin-right: 25%; }

<img class="standardImage"
src="images/chapter6_2/Dodge_s_Geography_of_New_England%2058_Fig_108.jpg"
title="Fig. 108. The State Capitol at Boston."
alt="The Massachusetts State Capitol sits high on a hill overlooking Boston Common."
/>
<h3>Massachusetts Cities and Towns</h3>
<h4>Gain in Population.</h4>
<p>In Massachusetts (Fig. 104) the steady drift of the
people toward the cities is the most striking feature in
the growth and movement of population. (Fig. 103.) ....</p>

Massachusetts Cities and Towns


Gain in Population.
In Massachusetts (Fig. 104) the steady drift of the people toward the cities is the most
striking feature in the growth and movement of population. (Fig. 103.) ....

Cascading Style Sheets (CSS)

199

Community Service with Web-Based GIST

When the image is given a block-level display, by default it has the whole width of the page
to itself, and like the horizontal rule styled earlier, its width and margin properties are used to
position it in the center of the page.
Floating Content

Cascading Style Sheets (CSS)

200

Community Service with Web-Based GIST

An element can be made to float either to the far left or the far right of the element that
contains or follows it, taking on a block-level display with no margins, similar to what is seen
in Dodge p. 7 to the right.
If the containing or following element has inline display, like text, it will rearrange itself to flow
around the floated element, dynamically readjusting as you narrow or widen the computer
screen.
Non-inline content may be covered over; to avoid this, you can insert a break element before
it that clears the space to the bottom of the floating image, <br clear="all" /> , as follows:

Floating an image adjacent to text is a common task:


img.rightImage { float: right; width: 25%; margin: 0 0 1em 1em; }

<h4>Size and Location.</h4>


<p>
<img class="rightImage"
src="images/chapter6_3/Dodge_s_Geography_of_New_England%2007_Fig_1.jpg"
title="Fig. 1. A relief map of New England."

alt="A relief map of New England, showing the mountainous terrain in the northern part of the
/>

The six New England states, with a combined area a little more than one-half that of the United K
</p>
<p>

The Great Valley which separates the Appalachian Mountains and Piedmont Belt from the Allegheny P
<br clear="all" />
</p>

Size and Location.

Cascading Style Sheets (CSS)

201

Community Service with Web-Based GIST

The six New England states, with a combined area a little more than one-half that of the
United Kingdom, occupy the extreme northeastern portion of the United States. (Fig. 3
and Adv. Geog.,Fig.192.) The states are small, except Maine, which has only a few
square miles less than all the other states taken together. Relatively the three southern
states are densely settled (Figs. 99 and 100), Rhode Island and Massachusetts being
the most densely populated states in the Union.

Cascading Style Sheets (CSS)

202

Community Service with Web-Based GIST

The Great Valley which separates the Appalachian Mountains and Piedmont Belt from
the Allegheny Plateau (Adv. Geog, Fig. 191) is in New York called the HudsonChamplain Valley. East of this valley is an old irregular mountain mass, so old as to be
worn down relatively smooth, so irregular that its relation to the Appalachian Mountains
cannot be clearly distinguished. This area is called the New England Highland....
The image here is given a bit of margin around the bottom and left edges to keep the text
from crowding it.
Any element can be floated, e.g. to put the <h4> subheading in line with the beginning of
the following paragraph, we can make it float left, which pushes the first line of the following
paragraph up and to the right to make room:
h4 { float: left; font-size: medium; margin: 0 0 0 1em; }

<h4>Size and Location.</h4>


<p>

The six New England states, with a combined area a little more than one-half that of the United K
</p>
</p>

Size and Location.


The six New England states, with a combined area a little more than one-half that of the
United Kingdom, occupy the extreme northeastern portion of the United States....
Positioned Content
An element can be precisely positioned by using (x, y) coordinates in reference to a
containing element, called the positioning context, and displayed above other content in any
order.
The CSS property position can be set to one of four possibilities, with static being the
default flowing or floating behavior seen so far:

Cascading Style Sheets (CSS)

203

Community Service with Web-Based GIST

position

positioning context

display

normal flow space

not offset

default
block-level
or inline

occupied

current or following element

marginless
block-level

filled in by following
elements; inline
content will flow around
it

relative

nearest containing block-level


element

default
block-level
or inline

retained (as blank


space when moved)

absolute

nearest containing block-level


element with relative or
absolute positioning

marginless
block-level

filled in by following
elements

fixed

browser viewing pane

marginless
block-level

filled in by following
elements

static

flowing

static

floating

For non-static elements, the properties top , bottom , left , and right let you specify
their offset from any edge of the reference element. As is standard practice in computer
graphics, vertical values are measured from top to bottom rather than upward.
In relative positioning, the element is simply shifted in position, leaving behind a blank
space. The element will appear above and hide other content that it overlaps. It is therefore
not very useful, except as a reference point for absolutely positioned content, and we can
ignore it for now.

Cascading Style Sheets (CSS)

204

Community Service with Web-Based GIST

In absolute positioning, the element is also shifted in position, but the space it leaves behind
is filled in with subsequent content. Again, the element will appear above and hide other
content that it overlaps, so it is commonly moved to where there is designated space for it.
For example, Figure 3 of Dodge is a political map of New England, which could be quite
large and slow to load. But we could break it into tiles that are 256x256 pixels square so that
they load a little bit at a time. Using absolute positioning the twelve pieces in this example

Cascading Style Sheets (CSS)

205

Community Service with Web-Based GIST

can be placed seamlessly within a <div> element designated for them. This element is
given relative positioning to establish it as the reference element, but is not itself given
offsets so that it remains in its normal place.

div#nepm { position: relative; width: 756px; height: 1024px; }


#nepm .nepm11, #nepm .nepm12, #nepm .nepm13, #nepm .nepm21, #nepm .nepm22, #nepm .nepm23,
#nepm .nepm31, #nepm .nepm32, #nepm .nepm33, #nepm .nepm41, #nepm .nepm42, #nepm .nepm43
{ position: absolute; border: solid blue; }
#nepm .nepm11 { top: 0; left: 0; }
#nepm .nepm12 { top: 0; left: 256px; }
#nepm .nepm13 { top: 0; left: 512px; }
#nepm .nepm21 { top: 256px; left: 0; }
#nepm .nepm22 { top: 256px; left: 256px; }
#nepm .nepm23 { top: 256px; left: 512px; }
#nepm .nepm31 { top: 512px; left: 0; }
#nepm .nepm32 { top: 512px; left: 256px; }
#nepm .nepm33 { top: 512px; left: 512px; }
#nepm .nepm41 { top: 768px; left: 0; }
#nepm .nepm42 { top: 768px; left: 256px; }
#nepm .nepm43 { top: 768px; left: 512px; }

<div id="nepm">

<img class="nepm11" src="images/chapter6_3/Dodge_s_Geography_of_New_England%2009_Fig_3/01-01.png"

<img class="nepm12" src="images/chapter6_3/Dodge_s_Geography_of_New_England%2009_Fig_3/01-02.png"

<img class="nepm13" src="images/chapter6_3/Dodge_s_Geography_of_New_England%2009_Fig_3/01-03.png"

<img class="nepm21" src="images/chapter6_3/Dodge_s_Geography_of_New_England%2009_Fig_3/02-01.png"

<img class="nepm22" src="images/chapter6_3/Dodge_s_Geography_of_New_England%2009_Fig_3/02-02.png"

<img class="nepm23" src="images/chapter6_3/Dodge_s_Geography_of_New_England%2009_Fig_3/02-03.png"

<img class="nepm31" src="images/chapter6_3/Dodge_s_Geography_of_New_England%2009_Fig_3/03-01.png"

<img class="nepm32" src="images/chapter6_3/Dodge_s_Geography_of_New_England%2009_Fig_3/03-02.png"

<img class="nepm33" src="images/chapter6_3/Dodge_s_Geography_of_New_England%2009_Fig_3/03-03.png"

<img class="nepm41" src="images/chapter6_3/Dodge_s_Geography_of_New_England%2009_Fig_3/04-01.png"

<img class="nepm42" src="images/chapter6_3/Dodge_s_Geography_of_New_England%2009_Fig_3/04-02.png"

<img class="nepm43" src="images/chapter6_3/Dodge_s_Geography_of_New_England%2009_Fig_3/04-03.png"


</div>

Cascading Style Sheets (CSS)

206

Community Service with Web-Based GIST

Cascading Style Sheets (CSS)

207

Community Service with Web-Based GIST


Each tile is given a blue border so that you can see where it begins and ends; you can also
click on any one of them and drag it to see the ghost of just that tile.
In fixed positioning, elements are positioned relative to the viewing pane of your browser.
This is commonly used to fix headers and navigation bars at the top of the viewing pane, so
they are always available.
For example, we could attach the title information for Dodge at the top of this web page, by
putting it together in a single <div> and fixing that:
div#header { width: 100%; position: fixed; top: 0em; left: 0; z-index: 1000; }

Cascading Style Sheets (CSS)

208

Community Service with Web-Based GIST

<div id="header">
<h1>The Geography of New England</h1>
<div id="byline">
By <span class="author">Lyman R. Allen</span>,

<span class="credentials">formerly Instructor in Geography, State Normal School, Providence,


and <span class="author">Alonzo J. Knowlton<span>,
<span class="credentials">Superintendent of Schools, Belfast, Maine</span>.
</div>
<hr id="titleSeparator" />
</div>

The Geography of New England


By Lyman R. Allen, formerly Instructor in Geography, State Normal School, Providence,
Rhode Island,
and Alonzo J. Knowlton, Superintendent of Schools, Belfast, Maine.

This header element has the positioning property z-index that controls the stacking order
in which elements are drawn, which is important when they overlap. The value 0 is the index
of the positioning context, and the largest value on the page is frontmost and completely
uncovered. Because the course book has a number of positioned elements such as the
table of contents, a very large value is chosen here.
Click this button to see the header appear and disappear: Toggle Header Scroll up and
down a bit to see the effect.
Note the explicit width of 100% assigned to this <div> ; when elements are given absolute
or fixed positioning, they shrink to fit their content, and this value ensures that the element
stretches across the viewing pane.

Exercises
In the Exercises at the end of Chapter 6.2, you created a web page gne.html . Style this
document to match Dodge:
1. Add appropriate styles for headings, paragraphs, and other items.
2. Create a class called towns and use it to style the individual cities and towns
described in the text.
3. Float the images to the left or right, as appropriate, and assign them widths of only half
a page.

Cascading Style Sheets (CSS)

209

Community Service with Web-Based GIST

4. Position these twelve images to create a map (dont put boundaries around them like
above, though):
https://cschweik.gitbooks.io/community-service-with-web-basedgist/content/data/Dodge_s_Geography_of_New_England%2054_Fig_104/0101.png
....
https://cschweik.gitbooks.io/community-service-with-web-basedgist/content/data/Dodge_s_Geography_of_New_England%2054_Fig_104/0304.png
5. Position the book title above the rest of the text, as above.

Chapter 6: Static Data on the World-Wide Web


6.3 Cascading Style Sheets (CSS)
Previous:
6.2 HyperText Markup Language (HTML)
Next:
6.4 Scalable Vector Graphics (SVG)

Cascading Style Sheets (CSS)

210

Community Service with Web-Based GIST

Chapter 6: Static Data on the World-Wide


Web
6.4 Scalable Vector Graphics (SVG)
Scalable Vector Graphics let you draw many different geometric shapes in your documents.
The full specification of SVG 1.1.

Geometric Shapes
SVG statements can be placed anywhere in your HTML, using the <svg> element to
introduce them, and CSS to style them:
svg rect { fill: rgb(200,200,200); stroke: black; }
svg .central { fill: yellow; }
svg #offset { fill: green; opacity: 0.5; }

<svg width="400" height="100">


<rect x="0" y="0" width="400" height="100" />
<circle class="central" cx="200" cy="50" r="40" />
<ellipse id="offset" cx="240" cy="70" rx="60" ry="20" />
<line x1="0" y1="0" x2="400" y2="100" style="stroke: red; stroke-width: 5;" />
</svg>

Note that later elements are drawn on top of earlier ones.


In addition to rectangles, circles, ellipses, and lines, you can draw more general polylines
(sets of points that are connected) and paths (an initial point to moveto followed by lineto
and curveto instructions).
Sets of instructions can also be grouped, and any graphic or graphic group can be
transformed through translation, rotation, etc.
Its generally a good idea to always specify the size of the drawing area, or canvas, or your
browser could choose an unexpected one.

Chapter 6: Static Data on the World-Wide Web


6.4 Scalable Vector Graphics (SVG)
Scalable Vector Graphics (SVG)

211

Community Service with Web-Based GIST

Previous:
6.3 Cascading Style Sheets (CSS)

Scalable Vector Graphics (SVG)

212

Community Service with Web-Based GIST

Glossary
georeference
Stretch a scanned map to match its features to those of a standard reference.
4.2. Georeferencing a Scanned Paper Map or Image 0. Introduction

HTTP
Hypertext Transfer Protocol is a set of rules that computers on the Internet use to transfer
documents from a server computer to a client computer. It is built on top of the low-level
communication protocols [TCP] and [IP].

Glossary

213

You might also like