PostGIS Essentials Sample Chapter
PostGIS Essentials Sample Chapter
ee
Sa
PostGIS Essentials m
PostGIS Essentials
pl
e
PostGIS is one of the world's leading spatial databases,
What you will learn from this book
created as a geographic extension for PostgreSQL. With
it, users are able to manipulate and visualize spatial data Install and configure PostGIS and other useful
incredibly effectively and efficiently. open source tools such as QGIS and GDAL
for working with spatial data
PostGIS Essentials introduces you to the fundamentals Create spatial databases and tables from
of PostGIS, giving you easy access to one of the most scratch and develop spatial queries through
popular and powerful spatial databases available today. practical examples
You will begin by learning how to install and successfully
Obtain useful spatial data from public and
set up PostGIS before covering how to create your first free sources and insert and manage this
spatial database. The book will then help you to develop data to be useful with your data tables
your skills further as you will learn how to insert GIS
objects as well as how to select and filter GIS queries Familiarize yourself with the fundamental
concepts in PostGIS and spatial databases
with clear and practical information. You will then learn
how to display GIS data graphically and create effective Visualize the data stored in your tables and C o m m u n i t y E x p e r i e n c e D i s t i l l e d
visualizations. The book concludes with tips, tricks, and combine it with other data sources to create
techniques to help you optimize PostGIS and improve beautiful graphical solutions using QGIS
the performance of your database.
Use the GDAL spatial library to transform
and reproject from a wide range of data
PostGIS Essentials
formats such as vectorial and raster
Who this book is written for geospatial data formats
This book is a quick guide for anyone who wants to
get started with PostGIS and develop their very own GIS Develop a complete GIS application from
scratch by implementing the concepts
Angel Marquez
projects quickly.
learned in the book
When you develop an application, you have to be very clear about who your target
audience is; this means thinking about who the users of your application will be and
the role of this application in an organization. This fact is crucial when you define not
only the application's logic, but also the technology that will support this logic in the
best way. We will split the system into two applications:
We will use the example of the real estate company to illustrate both these approaches;
in this case, we will develop two applications. To provide you with a better
understanding, let's describe the roles of the two actors that we will use in the system:
[ 119 ]
Developing a GIS Web Application
To explain a system's dynamic nature better, take a look at the following figure:
There are a lot of options available when you have to choose the right technology
to develop your project. However, it would be impossible to cover all of them in this
chapter, though, we will try to cover two of the main development environments
you could choose for your application.
We will continue to use open source development tools (such as PHP, JavaScript,
and so on), but the examples shown to you will be crafted in a way that will help
you adapt them in case you want to use any other commercial language or platform.
The purpose of this book isn't to teach you a particular programming language or to
configure any web or desktop platform, therefore, we will focus on the interaction
with spatial data.
[ 120 ]
Chapter 8
[ 121 ]
Developing a GIS Web Application
Once we have the web server running, we must install and configure the PHP
module in order to generate the scripts that will access our database server. In this
case, we choose PHP as a language but you can choose any other and take this
example as a reference.
[ 122 ]
Chapter 8
2. Decompress and save it in the machine folder; in this case, we have saved it
in C:\php.
3. Rename the file from C:\php\php.ini-production to php.in.
4. Edit the php.ini file setting for the following options:
doc_root = c:\apache24\htdocs
extension_dir = c:\php\ext
5. Go to the extension section and remove the ; character from the following
line:
;extension=php_pgsql.dll;
This way, you will able to allow PHP to connect to the database server.
7. Save the file and restart the Apache web server, with this command:
httpd.exe –k restart
8. To probe that everything is working fine, open Notepad and type the
following line:
<?php phpinfo();?>
[ 123 ]
Developing a GIS Web Application
Now that all the underlying services are installed, it's time to install the map
visualization component. We have chosen a component that reunites the features of
simplicity of usage and beautiful presentation; this component is called Leaflet. There
are other powerful options, such as OpenLayers and CesiumJS. Packt Publishing
books, such as OpenLayers Cookbook, Antonio Santiago Perez and OpenLayers 3 Beginner's
Guide, Thomas Gratier, Paul Spencer, Erik Hazzard give you information on these.
Installing Leaflet
Leaflet is a beautiful, light, open source, and free component based on JavaScript;
you can find it at http://leafletjs.com:
Now, we will see how to install it in order to use it to develop our website. To do
this, perform the following steps:
Before we start, let's establish the overall structure of the application that we are
going to make:
1. First, we will connect our script to the spatial database using PHP.
2. Then, we will create a JavaScript object that will contain the map that the
user will see.
[ 124 ]
Chapter 8
3. After this, we will read information on the database and, from it, we will
generate the code that will create the necessary JavaScript objects, which will
represent the positions of the properties.
Now, let's start coding our application. Create a file named index.php in the
C:\Apache24\htdocs folder.
First, we must set up the connection to our database server, specifying the connection
parameters:
// connecting to the database
$dbconnection = pg_connect("host=localhostdbname=Real-Estate
user=postgres password=123456") or die('couldn't connect! :
' . pg_last_error());
Now, let's throw a query to get all the registers saved in the spatial table:
$query = 'SELECT id, town, street, number, ST_X(the_geom),
ST_Y(the_geom) FROM tbl_properties ';
$result = pg_query($query) or die(Query fails!: ' .
pg_last_error());
[ 125 ]
Developing a GIS Web Application
$line = pg_fetch_row($result);
//We save the position of the first register in those two
variables
$longitudeView =$line[4];
$latitudeView=$line[5];
Let's put some extra attention on the ST_X and ST_Y functions; these extract the x and
y values from the geometric object whose values correspond to the longitude and
latitude of our spatial position. The purpose of doing this is to obtain the latitude and
longitude as separate values; this will allow us to store them on separate variables
and then use these variables to create the JavaScript code.
Now, it's time to add the html code of our script. Here, we will add the JavaScript
code that we will need to invoke the map component:
<!DOCTYPE html><html><head>
<title>Real Estate Web Page</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<linkrel="stylesheet" href="leaflet/leaflet.css" />
</head><body>
<div id="map" style="width: 600px; height: 400px"></div>
<scriptsrc="leaflet/leaflet.js"></script>
Here, we add the link to both the leaflet.css and leaflet.js files that our
application will need.
Now, we add the map object; this object will carry one or several layers of
information, and each of these layers gives you different kinds of information
on the piece of terrain that we are seeing:
<script>
var map = L.map('map');
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png',
{ attribution: '© <a
href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
In this case, we have added an OpenStreetMap map layer. Here is some PHP code to
show the property's position as a marker on the map:
<?php $query = 'SELECT id, town, street, number, ST_X(the_geom),
ST_Y(the_geom) FROM tbl_properties';
$result = pg_query($query) or die(The query failed: ' .
pg_last_error());
while ($line =pg_fetch_row($result))
[ 126 ]
Chapter 8
{
$longitude =$line[4];
$latitude=$line[5];
$address=$line[2]." ".$line[3];
echo "L.marker([".$latitude.", ".$longitude."]).addTo(map)";
echo ".bindPopup('<b>".$address."').openPopup();";
} ?>
We have added code that goes through the table, gives you the position of every
piece of property, and generates a market with that position. This market will have
a pop-up frame with the address of the property that will be shown when the user
clicks on the icon. Later, we will put the map's view as the first property on the table
with a zoom level of 16:
map.setView([<?php echo $latitudeView.",".$longitudeView ?>], 16);
</script>
Finally, let's draw a table with the data of the properties in it:
<?php
// Throwing a query to the properties table
$query = 'SELECT id, town, street, number FROM tbl_properties';
$result = pg_query($query) or die('La consultafallo: ' .
pg_last_error());
//Printing the results in a html table
echo "<table>\n";
while ($line = pg_fetch_row($result))
{
echo "\t<tr>\n";
echo "\t\t<td><a
href='index.php?id=".$line[0]."'>".$line[0]."</a></td>\n";
echo "\t\t<td>".$line[1]."</td>\n";
echo "\t\t<td>".$line[2]."</td>\n";
echo "\t\t<td>".$line[3]."</td>\n";
echo "\t</tr>\n";
}
echo "</table>\n";
//Freeing the result set
pg_free_result($result);
//closing the database connection
pg_close($dbconn);
?>
</body>
</html>
[ 127 ]
Developing a GIS Web Application
As you can see, we have added another cell to the table that contains a hyperlink.
This link has the ID of the selected register included as a part of it. This parameter
will help us make modifications to the script where it will zoom to the selected
property when the user clicks on it.
To get all this implemented we will add the following code at the sixth line of
our script:
$where="";
if( isset($_GET['id']))
$where=" where id=".$_GET['id'];
Now, we will have to modify the query in order to add the where clause:
$query = 'SELECT id, town, street, number, ST_X(the_geom),
ST_Y(the_geom) FROM tbl_properties '.$where;
[ 128 ]
Chapter 8
[ 129 ]
Developing a GIS Web Application
Now, we open our favorite web browser and see this result:
This is just a sample. You can easily add more functionality to the application in
case you want to add a private section where you can add extra information for
sales people, such as the price of the property, or you might want to add a picture
of the house in the pop-up.
Summary
Until now, we have learned how to install and configure an Apache web server with
the PHP module enabled and how to use it in conjunction with the Leaflet library to
create a web application, which shows the spatial data graphically to a user. For this,
we read the information that was already stored in the database; however, you might
ask, what if we need to update this information? In the next chapter, we will build a
desktop application for managers who can update this information. To achieve this
objective, we will use a beautiful and, of course, free and open source SDK called
WorldWind, which works with Java.
[ 130 ]
Get more information PostGIS Essentials
www.PacktPub.com
Stay Connected: