Tuesday, September 13, 2011

Spatial Wiki 13 - Testing and Template Modifications

This is lucky post number 13 in setting up a Spatial Wiki and we're pretty much done, just need to do some testing and tweaks to the Coord template.  See also the Extension:SpatialWiki Documentation for details on the options that the extension adds to MediaWiki.  For example, to begin with we'll display a map centered on the FOSS4G Conference in Denver, CO that's 400 pixels wide and 300 pixels tall by adding the following markup to a wiki page:
{{ #SpatialWikiMap: 39.741850 | -104.988790 | 15 | 400px | 300px | true }}

The map in the wiki page will look like this:
















The final "true" parameter in the SpatialWikiMap tag means include points for the spatially referenced articles.  We've not setup a proper spatially referenced article for the FOSS4G meeting, but the point is coming from the test data we loaded into our database.  It's clickable and a popup comes up with the name, but there is not a valid link to an article.

Displaying maps is only part of the problem, the first part was spatially locating an article, writing the coordinates to our spatial database, and displaying a map for that article.  We'll accomplish this by modifying the Template:Coord to look like this:
{{ #SpatialWikiMap:{{{1|12.0}}} | {{{2|20.0}}} | 10 | 507px | 350px | true | true }}

{| border="0" cellpadding="4" cellspacing="0" style="border:0px solid darkgray;"
! width="500px"|
|- 
| valign="top" style="background:#e4f7dd; border-style: solid; border-width: 1px 0 1px 0; border-color:darkgray"| {{PAGENAME}}: Latitude {{{1|0.0}}} Longitude {{{2|0.0}}}, Type {{{3|Undefined}}}
|}

This modified template will do two things, displaying a map for the location of the article with a nicely formatted box below it showing the location details. Let's try it by creating a new article for the Wyknkoop Brewery calling the template with:
{{Coord|39.7534|-104.9985|Test}}

The Wynkoop Brewery page will thus look like:


















Finally, go back to the main page and setup the map insert like this:

{{ #SpatialWikiMap: 12.0 | 20.0 | 2 | 100% | 400px | true }}

The final Spatial Wiki homepage has clickable locations of the spatially referenced articles as shown below. The spatial references as they are added or modified are written in real-time to the backend spatial database via the Extension:SpatialWiki for MediaWiki.

Wednesday, September 7, 2011

Spatial Wiki 12 - Install SpatialWiki Extension

The last part to complete our Spatial Wiki is to install the SpatialWiki Extension for MediaWiki.  This extension has been developed as part of this exercise, and allows you to store spatial references from a wiki page in the PostGIS database, and to display clickable maps of spatial locations in a wiki page.  Install the extension as follows:
cd /var/lib/mediawiki/extensions
sudo apt-get install subversion
sudo svn checkout svn://svn.code.sf.net/p/spatialwiki/code SpatialWiki

This installs the files in the folder /var/lib/mediawiki/extensions/SpatialWiki.  The next step is to add the extension and it's configuration parameters to LocalSettings.php.
sudo vi /etc/mediawiki/LocalSettings.php

Add the following lines at the end:
#
# ----- SpatialWiki Extension
#
require_once("$IP/extensions/SpatialWiki/SpatialWiki.php");
$wgSpatialWikiDebugMessages = false;
$wgSpatialWikiDatabase = "spatialwiki";
$wgSpatialWikiUsername = "postgres";
$wgSpatialWikiPassword = "[your password]";
$wgSpatialWikiPointsTable = "wikipts";
$wgSpatialWikiOpenLayersPath = "http://[your server]/OpenLayers-2.11-rc3";
$wgSpatialWikiWmsPointsUrl = "http://[your server]:80/geoserver/spatialwiki/wms";
$wgSpatialWikiGeoServerPointsLayer = "spatialwiki:view_wikipts";

Modify the parameters to match your installation, then open the wiki in a web browser and goto Special Pages and find the "Version" page to verify that the extension is installed properly. You should see something like this:








With the extension installed go back to the main page of the wiki and edit the page, removing all the custom HTML and JavaScript and replacing it with:
{{ #SpatialWikiMap: }}

This is a tag for the simplest map that can be added to a page, and will produce a page like:

















Goto the next article on Testing and Template Modifications.

Monday, September 5, 2011

Spatial Wiki 11 - MediaWiki Markup and Templates

This is part 11 of a series of blog posts on building a Spatial Wiki.  At this point we have the wiki and parts of the spatial backend in-place, but before we continue it would be good to go through some of the markup and templating capabilities in MediaWiki.  Amongst other things templates allow you to collect and display information in a consistent manner so we'll setup and use a template to manage the geographic reference for an article.  We won't use the official Wikipedia templates, but what we'll do will be based on the standard Coord template in Wikipedia so our information and procedures will be compatible with Wikipedia.  The notes below include some brief (very brief) information on MediaWiki markup, and walk through setting up a Coord template for our use.

A great overall reference for MediaWiki that is great to get started with is MediaWiki (Wikipedia and Beyond) by Daniel Barrett.

Editing in MediaWiki

To edit in MediaWiki just select the "edit" option at the top of the page.  Each page should be thought of as an article in the Wiki and you will be editing the contents of that article.  Editing is typically via a straight-forward text editing window, and you can enter straight text or use special characters for markup to get bold, underlines, larger titles, etc.  There are loads of on-line references for the MediaWiki markup syntax, for example see the MediaWiki article in Text Formatting.  Another great reference is to view the source for an article in Wikipedia, it's all there, and since Wikipedia is powered by MediaWiki the markup is the same.








Note also the "history" tab at the top of each article.  Wiki articles are stored in a database along with a complete version history so you can use the History tab to track changes and go back to previous versions if needed.

Creating a New Article

There are various ways to create a new article, but one of the easiest and best ways is to start with a reference to the new article on an existing page.  A lot of the value in a Wiki is the internal links to related articles so it's a good idea to "ground" anything new with something existing.  References (links) to other articles are enclosed in double square brackets so you might have something like [[Great New Article]] that would be a link to an article titled "Great New Article."  For demonstration purposes I'll create a reference to an article about the Etta Pegmatite which is a somewhat famous (limited circles) mine near Mt. Rushmore in South Dakota.  The article link on the main page is [[Etta Pegmatite]].  It will be displayed in red indicating that it doesn't exist and when I click on it I will be able to create the new article.

Creating a Template

Templates are a special type of page that can be used to display the same information in multiple locations, or to enforce formatting standards for specific information.  In our case we'll create a template called Coord that will manage the spatial reference in a wiki page.  To create the template type Template:Coord in the search box and hit Go.  Since the page doesn't exist MediaWiki will ask it you want to create it ... yes.  This is another way to create new wiki pages.  On the new Template:Coord page add the text/markup:
{| border="0" cellpadding="4" cellspacing="0" style="border:0px solid darkgray;"
! width="600px"|
|- 
| valign="top" style="background:#e4f7dd; border-style: solid; border-width: 1px 0 1px 0; border-color:darkgray"| Latitude {{{1}}} Longitude {{{2}}}, Type {{{3|Undefined}}}
|}

This is markup to create a table that is 600 pixels wide with a green background and a horizontal like along the top and the bottom. The table will contain text for the latitude, longitude, and point type. These are referenced as parameters that are passed into the template, for example {{{2}}} is the second parameter and refers to the longitude.  When you save the template it will look like this:






Using the Coord Template

To use the new Coord template specify the template name and include the parameters latitude, longitude, and point type separated by a | character.  For example in the article on the Etta Pegmatite I have:
The Etta Pegmatite is near Keystone, South Dakota.

{{Coord|43.8810|-103.4165|Pegmatite}}

This will then be displayed as shown on the article:








So far the template is "dumb" and other than display the coordinate reference nicely formatted it doesn't do anything.  In the next article we'll install an extension to extract the geographic reference and add it to the spatial database.

See next article on Installing the SpatialWiki Extension.

Friday, September 2, 2011

Spatial Wiki 10 - Install OpenLayers

This is Part 10 of a series of posts on creating a SpatialWiki.  Previously we Installed GeoServer and started serving a layer of Wiki points.  In this article we'll install OpenLayers and finally put our first map in the Wiki.  OpenLayers in a JavaScript mapping API that will enable us to combine our Wiki points with other layers such as a Google or Bing maps background.

Installing OpenLayers

Installing OpenLayers basically consists of downloading and unzipping the desired version in an appropriate folder.  Download links are here:

http://trac.osgeo.org/openlayers/wiki/HowToDownload

In this example I'm going to download and install OpenLayers in the /var/www (default web) folder, and I'll pull OpenLayers 2.11 rc3 which fixes a nasty issue with a data copyright popup in version 2.10.  The complete sequence to download, uncompress, and clean-up is:
cd /var/www
sudo wget http://openlayers.org/download/OpenLayers-2.11-rc3.tar.gz
sudo tar -zxvf OpenLayers-2.11-rc3.tar.gz
sudo rm OpenLayers-2.11-rc3.tar.gz

Configure MediaWiki for raw HTML

Before we can add a map to a wiki page we need to enable raw HTML (and JavaScript) support in the wiki.  This is done like with most MediaWiki settings by editing the LocalSettings.php file associated with the wiki.  In our case this is /etc/mediawiki/LocalSettings.php so we'll edit it with:
sudo vi /etc/mediawiki/LocalSettings.php

Goto the bottom of the file and add the following lines:
//Allow raw embedded html
$wgRawHtml=true;

Save the file and restart Apache just to be safe.
sudo /etc/init.d/apache2 restart

Adding a Map to a Wiki Page

With OpenLayers installed and the wiki setup to support HTML and JavaScript we just need to add the code to a wiki page to show the map. The formatting is not great, but for example as shown below.  To edit a wiki page just click the Edit menu option at the top of the wiki page.
<html>
<head>
<!-- add OpenLayers and Google Maps APIs -->

<link rel="stylesheet" href="http://[your server address]/OpenLayers-2.11-rc3/theme/default/style.css" type="text/css">
<link rel="stylesheet" href="http://[your server address]/OpenLayers-2.11-rc3/theme/default/google.css" type="text/css"><script src="http://[your server address]/OpenLayers-2.11-rc3/lib/OpenLayers.js"></script><script src="http://maps.google.com/maps/api/js?v=3.5&amp;sensor=false"></script>
<script type="text/javascript">

//
// ----- setup map options, it is VERY important to set the maxExtent to get the GeoServer WMS
//       data to overlay properly
//
var options = {
maxExtent: new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34),
maxResolution: "auto",
projection: new OpenLayers.Projection("EPSG:900913"),
units: 'm'
};
var map;

//
// ----- function to initialize the map
//
function init()
{
//
// ----- create map and add layer switcher control
//
map = new OpenLayers.Map('map', options);
map.addControl(new OpenLayers.Control.LayerSwitcher());
//
// ----- setup Google Maps layers
//
var gphy = new OpenLayers.Layer.Google(
"Google Physical",
{type: google.maps.MapTypeId.TERRAIN}
);
var gmap = new OpenLayers.Layer.Google(
"Google Streets", // the default
{numZoomLevels: 20}
);
var ghyb = new OpenLayers.Layer.Google(
"Google Hybrid",
{type: google.maps.MapTypeId.HYBRID, numZoomLevels: 20}
);
var gsat = new OpenLayers.Layer.Google(
"Google Satellite",
{type: google.maps.MapTypeId.SATELLITE, numZoomLevels: 22}
);
//
// ----- setup wikipts layer, this is coming from our GeoServer server
//
var wikipts = new OpenLayers.Layer.WMS(
"Wiki Points",
"http://[your server address]:80/geoserver/spatialwiki/wms",{layers: 'spatialwiki:wikipts', format: 'image/png', transparent: true},
{isBaseLayer: false}
);
//
// ----- add layers to the map
//
map.addLayers([gphy, gmap, ghyb, gsat, wikipts]);
//
// ----- set map center
//       Google.v3 uses EPSG:900913 as projection, so we have to transform our coordinates  
//       longitude 12.0 latitude 20.0 zoom 2 for decent looking world map
//
map.setCenter(new OpenLayers.LonLat(12.0, 20.0).transform(
new OpenLayers.Projection("EPSG:4326"),
map.getProjectionObject()
), 2);
}

</script>
</head>
<body onload="init()">
<!-- setup space for the map on the page -->
<div id="map" style="width:100%;height:400px;"></div>
</body>
</html>

When complete the wiki page with the imbedded map showing the locations of FOSS4G meetings (test points) should look like the example below. Finally after lots of installation and setup we're starting to get someplace!






















Showing the Current Location (optional)

As the cursor tracks across the map you can add a readout that shows the current latitude-longitude coordinates by adding a mouse event handler to the JavaScript map code and a corresponding <div> section to the HTML.  The <div> is where the coordinate display will be written to.  For example, add to  the JavaScript:
//
// ----- mouse position in lat-long, gets written to the &amp;quot;coords&amp;quot; div in the html file
//
map.events.register(&amp;quot;mousemove&amp;quot;, map, function(e) { 
 var position = this.events.getMousePosition(e);
 var lonlat = map.getLonLatFromPixel(position);
 lonlat = lonlat.transform( 
      new OpenLayers.Projection(&amp;quot;EPSG:900913&amp;quot;), 
      new OpenLayers.Projection(&amp;quot;EPSG:4326&amp;quot;) 
    );
 var longitude = lonlat.lon.toFixed(4);
 var latitude = lonlat.lat.toFixed(4);
 OpenLayers.Util.getElement(&amp;quot;coords&amp;quot;).innerHTML = 'lon=' + longitude + ', lat=' + latitude;
});

Then add the <div> section to the HTML:
<div id="map" style="width:100%;height:400px;"></div>
<div id="coords"></div><p>

In this case the coordinates will be displayed outside the lower-left corner of the map:









See the next article on Editing Wiki Pages.

Spatial Wiki 9 - Add PostGIS Layer to GeoServer

This is Part 9 on building a Spatial Wiki, we've just Installed GeoServer and we're ready to add a new layer in GeoServer that serves up points from our PostGIS Database.

To get started login to the GeoServer web interface with something like:

http://[your server]/geoserver/web

Or if you're operating with port 8080 then use:

http://[your server]:8080/geoserver/web

From the GeoServer main screen use the option to create a new Workspace called "spatialwiki" and associate it with a URI also named spatialwiki.  In general we'll be creating a Workspace that contains a database connection called a Store (data), and a Layer with symbology that references data in a particular  Store.














After creating the Workspace select the option to create a new Store, this will be a connection to our PostGIS database.  Select the PostGIS connection type, just use the regular one, not the JNDI option.  Fill in the connection parameters, changing the workspace to the spatialwiki workspace that we just created. Use the postgres user to connect to the database.  Save the new Data Store.  When you create the data Store you will be forwarded to a screen to create a new layer with the Data Store or you can start a new layer using the Layers menu option on the left.












Either after creating a new Data Store, or via picking the Layers menu option and adding a new resource you can select the newly created spatialwiki:spatialwiki Workspace:Store and publish the view_wikipts view which is our previously created view that contains the points from our wiki.  You can use all the defaults when creating the layer, and you will have to click the options to calculate a native and lat-long bounding box from the data.  If you click the "Publishing" tab you can change the symbology for the points, the default is a small red box.

After creating the Layer select the Layer Preview menu on the left to preview the new layer in OpenLayers, or via KML or GML.  The test points of FOSS4G meeting locations are shown below in an OpenLayers preview.











See the next article on Installing OpenLayers.

Wednesday, August 24, 2011

Spatial Wiki 8 - Install GeoServer

This is part 8 on building a Spatial Wiki, we've setup and configured an Amazon EC2 server with MediaWiki, PostgreSQL, and PostGIS.  We've also setup a simple spatial database and connected to it via Quantum GIS.  Now it's time to install and do some initial testing of GeoServer which we'll use to serve our spatial data out to a webpage via OpenLayers.

If you search the web, and via the couple of installs I've done there are number of ways to install and configure GeoServer.  I'm also honestly not sure what is the best one, the but in general I think we want to be running with the official Oracle version of Java, and we want it running via Tomcat so we'll install and configure both of these before hitting GeoServer.

Installing Oracle Java

The official Oracle Java is in a partner repository so you have to add the repository and then install Java, like this:
sudo vi /etc/apt/sources.list

Add this line to the end:
deb http://archive.canonical.com/ lucid partner

Save the file and then update the list of packages and install Java with:
sudo apt-get update
sudo apt-get install sun-java6-jre sun-java6-plugin sun-java6-fonts

Once Oracle Java is installed you can check the version with:
java -version

You should see something like:
java version "1.6.0_26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03)
Java HotSpot(TM) 64-Bit Server VM (build 20.1-b02, mixed mode)

If you system has different versions of Java installed (i.e. OpenJDK) you can set the "default" version that the system will use with:
sudo update-alternatives --config java

Installing Tomcat

I've just installed Tomcat using the Ubuntu server setup utility, run the following command and tick the option to install Tomcat:
sudo tasksel --section server

Once Tomcat is installed there are two configuration changes per recommendations in this article:

http://leighspersistentthoughts.wordpress.com/2010/06/17/installing-a-headless-geoserver-on-ubuntu-10-4-on-amazon-web-services/

The fist change I think is just formally enabling what are otherwise defaults:

Edit the follwing file:
sudo vi /etc/default/tomcat6

Uncomment the following lines and save the file.
JAVA_OPTS="-Djava.awt.headless=true -Xmx512m"
TOMCAT6_SECURITY=no

Edit this file:
sudo vi /var/lib/tomcat6/conf/tomcat-users.xml

So it looks like this:
<tomcat-users>
<!--
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="tomcat" roles="tomcat"/>
  <user username="both" password="tomcat" roles="tomcat,role1"/>
  <user username="role1" password="tomcat" roles="role1"/>
-->
  <role rolename="admin"/>
  <role rolename="manager"/>
  <role rolename="tomcat"/>
  <user username="tomcat6" password="secret" roles="admin,manager,tomcat"/>
</tomcat-users>

Restart the tomcat server:
sudo /etc/init.d/tomcat6 restart

Install GeoServer

Download the GeoServer Web Archive (.war) file from:

http://geoserver.org/display/GEOS/Stable

Once the file is downloaded launch the Tomcat manager which will be something like:

http://[your server]:8080/manager/html

Important note: Port 8080 needs to be allowed via the AWS security group for the server. Do this in the AWS Management Console.  See the Server Setup post for more information if needed.

Select the WAR file to upload (geoserver.war) and then click Deploy from the Tomcat Web Application Manager. When complete you will see GeoServer running in the Tomcat manager as shown below.



You will be able to launch the GeoServer web administration interface with an address like:

http://[your server]:8080/geoserver/web

The default admin login for GeoServer is username = admin and password = geoserver

To change the login see notes here:

http://docs.geoserver.org/stable/en/user/gettingstarted/web-admin-quickstart/index.html

The GeoServer web interface looks like the figure below.  You can do "Layer Preview" and preview the various default datasets that were installed with GeoServer.

Enabling Port 80 (optional)

Tomcat (and this GeoServer) by default operate over port 8080 which can sometimes be a problem with firewalls, and if nothing else make the URLs a bit messy.  You can get around this by enabling proxy support in Apache and setting up a proxy equating GeoServer on 8080 to a standard port 80 http request.  The first part is REALLY important, Apache2 needs to be configured to allow the proxies. I restarted after each one, but you can live dangerously and just restart after enabling both.
sudo a2enmod proxy
sudo a2enmod proxy_http
sudo /etc/init.d/apache2 restart

Then edit the Apache configuration file:
sudo vi /etc/apache2/sites-enabled/000-default

And add the following lines to the end, but before the closing tag.
ProxyRequests Off
ProxyPreserveHost On
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
ProxyPass /geoserver http://localhost:8080/geoserver
ProxyPassReverse /geoserver http://localhost:8080/geoserver

Finally restart Apache again and you will be able to Access GeoServer via a standard http address like:

http://[your server]/geoserver/web

See the next article on Adding a PostGIS Layer to GeoServer.

Monday, August 22, 2011

Spatial Wiki 7 - Setup the Spatial Database

We've spent a fair bit of time setting up the server, and installing and configuring PostgreSQL and PostGIS. At this point we have a reasonably well configured cloud based geospatial server so it's time to setup the spatial database. The database will be a simple spatially enabled data model to store points and a bit of metadata sourced from the wiki. Not sure if we'll get there, but the objective will be to implement a bit of custom PHP code to keep the spatial database updated in real-time as wiki entries with spatial references are created or modified. So, in thinking about the data model we'll include the following:
  • A spatial reference, a point in lat-long, WGS84 coordinates
  • A link to the wiki article that the point is associated with, this will be the unique article id from MediaWiki, the article title will also be stored
  • A point type that will be validated against a reference table of allowed point types
  • Date/time fields that keep track of when a row is created and when it's modified
Before creating the data model we'll first create a new database.  You create a new PostgreSQL database from the Linux prompt with
    sudo -u postgres createdb spatialwiki
    This creates the database "spatialwiki" with the postgres user.

    Next we'll enable the database to support PL/pgSQL which is required for PostGIS:
    sudo createlang --username=postgres --password plpgsql spatialwiki

    Then run the following SQL scripts to setup PostGIS functions and other objects in the database:
    sudo psql -U postgres -d spatialwiki -f /usr/share/postgresql/8.4/contrib/postgis.sql
    sudo psql -U postgres -d spatialwiki -f /usr/share/postgresql/8.4/contrib/spatial_ref_sys.sql
    sudo psql -U postgres -d spatialwiki -f /usr/share/postgresql/8.4/contrib/postgis_comments.sql

    Note that depending on what version of PostGIS you have installed the path to postgis.sql and spatial_ref_sys.sql may be slightly different.  To find out exactly where they are on your system you can use the find command like:

    sudo find / -name postgis.sql

    When complete you can login to the database and check that PostGIS is installed and setup properly with:
    sudo -u postgres psql spatialwiki

    Then at the PostgreSQL prompt run the SQL query:
    SELECT PostGIS_full_version();

    And with everything setup properly you should see:
    postgis_full_version                                  
    ----------------------------------------------------------------------------------------
     POSTGIS="1.4.0" GEOS="3.1.0-CAPI-1.5.0" PROJ="Rel. 4.7.1, 23 September 2009" USE_STATS
    (1 row)
    


    To exit the PostgreSQL prompt do \q.

    Creating the Database Structure

    With the database "container" in-place we can go ahead and create the database structure. In our case we're just going to build two tables.  The main table will be wikipts and it will contain the spatial references and other information from the wiki articles.  The point_type table will be a reference table containing allowable types for each point.  Following good database design practices there are also sequences to automatically populate the rowids, and a trigger to automatically keep the last modified timestamp current.  The script to create the database is listed below.  The easiest way (or at least one of the ways) to create the database is to write the script to a file (i.e. create_spatialwiki_database.sql) and then run it against the new database as follows:

    sudo psql -U postgres -d spatialwiki -f create_spatialwiki_database.sql
    

    The script looks like this:
    --
    -- PostgreSQL code to setup the spatialwiki database.
    --
    --
    -- drop objects if they exist in the right order
    --
    DROP TABLE IF EXISTS wikipts;
    DROP TABLE IF EXISTS point_type;
    --
    -- create a function to keep the last modified date updated automatically
    --
    CREATE OR REPLACE FUNCTION update_lastmodified_column() 
            RETURNS TRIGGER AS '
      BEGIN
        NEW.timestamp_lastmodified_utc = NOW();
        RETURN NEW;
      END;
    ' LANGUAGE 'plpgsql';
    --
    -- point_type table
    --
    DROP SEQUENCE IF EXISTS point_type_rowid;
    CREATE SEQUENCE point_type_rowid START 1;
    CREATE TABLE point_type
    (
      rowid INTEGER PRIMARY KEY DEFAULT nextval('point_type_rowid'),
      name VARCHAR(254) NOT NULL UNIQUE,
      description VARCHAR(8000),
      timestamp_loaded_utc TIMESTAMP NOT NULL DEFAULT current_timestamp,
      timestamp_lastmodified_utc TIMESTAMP NOT NULL DEFAULT current_timestamp
    );
    --
    -- build wikipts table
    --
    DROP SEQUENCE IF EXISTS wikipts_rowid;
    CREATE SEQUENCE wikipts_rowid START 1;
    CREATE TABLE wikipts
    (
      rowid INTEGER PRIMARY KEY DEFAULT nextval('wikipts_rowid'),
      article_name VARCHAR(2000) NOT NULL UNIQUE,
      article_id INTEGER NOT NULL UNIQUE,
      point_type_fk INTEGER NOT NULL REFERENCES point_type,
      timestamp_loaded_utc TIMESTAMP NOT NULL DEFAULT current_timestamp,
      timestamp_lastmodified_utc TIMESTAMP NOT NULL DEFAULT current_timestamp
    );
    --
    -- add the geometry column
    --
    SELECT AddGeometryColumn('wikipts', 'geom', 4326, 'POINT', 2);
    --
    -- add triggers to keep the last modified date updated automatically
    --
    CREATE TRIGGER update_lastmodified BEFORE UPDATE
      ON point_type FOR EACH ROW EXECUTE PROCEDURE
      update_lastmodified_column();
    CREATE TRIGGER update_lastmodified BEFORE UPDATE
      ON wikipts FOR EACH ROW EXECUTE PROCEDURE
      update_lastmodified_column();

    Note the AddGeometryColumn() section of the script that adds the point geometry column with coordinate system = 4326 which is WGS84 lat-long.

    Adding Test Data

    The short SQL script below can be used to load some test data. Write it to a .sql file and run the script per the example above that was used to create the database structure. Note the ST_GeomFromText() function that is used to load the lat-long values into the geometry column, and the "SELECT rowid FROM point_type..." that is used to load the proper rowid link to the point type which is Test in this case.

    --
    -- point types
    --
    INSERT INTO point_type (name, description) VALUES ('Test', 'Test Points');
    INSERT INTO point_type (name, description) VALUES ('Pegmatite', 'Coarse grained intrusive hosted rare earth or gemstone deposit.');
    INSERT INTO point_type (name, description) VALUES ('Porphyry', 'Intrusive hosted, distinctly textured and zoned mineral deposit.');
    --
    -- test points (FOSS4G meeting locations)
    --
    INSERT INTO wikipts (article_name, article_id, geom, point_type_fk) VALUES (
      'FOSS4G 2011 - Denver', -1,
      ST_GeomFromText('POINT(-104.988790 39.741850)', 4326), 
      (SELECT rowid FROM point_type WHERE name = 'Test')
    );
    INSERT INTO wikipts (article_name, article_id, geom, point_type_fk) VALUES (
      'FOSS4G 2010 - Barcelona', -2,
      ST_GeomFromText('POINT(2.15170 41.37237)', 4326), 
      (SELECT rowid FROM point_type WHERE name = 'Test')
    );
    INSERT INTO wikipts (article_name, article_id, geom, point_type_fk) VALUES (
      'FOSS4G 2009 - Sydney', -3,
      ST_GeomFromText('POINT(151.199158 -33.873375)', 4326), 
      (SELECT rowid FROM point_type WHERE name = 'Test')
    );
    INSERT INTO wikipts (article_name, article_id, geom, point_type_fk) VALUES (
      'FOSS4G 2008 - Cape Town', -4,
      ST_GeomFromText('POINT(18.427470 -33.916017)', 4326), 
      (SELECT rowid FROM point_type WHERE name = 'Test')
    );
    INSERT INTO wikipts (article_name, article_id, geom, point_type_fk) VALUES (
      'FOSS4G 2007 - Victoria', -5,
      ST_GeomFromText('POINT(-123.366856 48.421684)', 4326),
      (SELECT rowid FROM point_type WHERE name = 'Test')
    );
    


    Setup a View

    In order to make our points click-able with the SpatialWiki Extension we're also going to setup a view that contains the right fields in the right order.  The SQL to do this is:
    CREATE OR REPLACE VIEW view_wikipts  AS
    SELECT article_name, article_id, geom, name
    FROM wikipts, point_type
    WHERE wikipts.point_type_fk = point_type.rowid

    The view that's created just needs to contain in-order the article name, the article id, the geometry column, and the point type.


    Viewing the Data in Quantum GIS

    Quantum GIS (QGIS) is a great cross-platform free and open source desktop GIS system that can directly read PostGIS data so we'll use it here to quickly display the test points and verify that everything in the database is working properly.  Start QGIS and setup a new PostGIS database connection similar to the example shown below.





















    Once the connection is setup you can test it and open it.  You should see the new wikipts available to add to the map.  The test points with a simple world outline background are shown in the figure below.  Seems like the FOSS4G meeting in Denver is the first one in history that is not right on the coast!














    See the next article on Installing GeoServer.