Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
PostGIS Cookbook
PostGIS Cookbook

PostGIS Cookbook: For web developers and software architects this book will provide a vital guide to the tools and capabilities available to PostGIS spatial databases. Packed with hands-on recipes and powerful concepts

eBook
$22.99 $32.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

PostGIS Cookbook

Chapter 2. Structures that Work

In this chapter, we will cover:

  • Using geospatial views

  • Using triggers to populate a geometry column

  • Structuring spatial data with table inheritance

  • Extending inheritance – table partitioning

  • Normalizing imports

  • Normalizing internal overlays

  • Using polygon overlays for proportional census estimates

Introduction


This chapter focuses on ways to structure data using the functionality provided by the combination of PostgreSQL and PostGIS. These will be useful approaches for structuring and cleaning up imported data, converting tabular data into spatial data "on the fly" as it is entered, and maintaining relationships between tables and datasets using functionality endemic to the powerful combination of PostgreSQL and PostGIS. There are three categories of techniques by which we will leverage these functionalities: automatic population and modification of data using views and triggers, object orientation using PostgreSQL table inheritance, and using PostGIS functions (stored procedures) to reconstruct and normalize problematic data.

Automatic population of data is where this chapter begins. By leveraging PostgreSQL views and triggers, we can create ad hoc and flexible solutions to create connections between and within the tables. By extension, and for more formal or structured cases, PostgreSQL...

Using geospatial views


Views in PostgreSQL allow for ad hoc representation of data and data relationships in alternate forms. In this recipe, we'll be using views to allow for the automatic creation of point data based on tabular inputs. We can imagine a case where the input stream of data is non-spatial, but includes longitude and latitude or some other coordinates. We would like to automatically show this data as points in space.

Getting ready

We can create a view as a representation of spatial data pretty easily. The syntax for creating a view is similar to creating a table; for example:

CREATE VIEW viewname AS
  SELECT...

In the preceding command line, our SELECT query manipulates the data for us. Let's start with a small dataset. In this case, we will start with some random points.

First, we create the table from which the view will be constructed as follows:

–- Drop the table in case it exists
DROP TABLE IF EXISTS chp02.xwhyzed CASCADE; 
CREATE TABLE chp02.xwhyzed
-- This table will contain...

Using triggers to populate a geometry column


In this recipe, we imagine that we have ongoing updates to our database, which needs spatial representation; however, in this case, we want a hard-coded geometry column to be updated each time an INSERT operation takes place on the database, converting our x and y values to geometry as they are inserted in the database.

The advantage of this approach is that the geometry is then registered in the geometry_columns view, and therefore this approach works reliably with more PostGIS client types than creating a geospatial view. This also provides the advantage of allowing for a spatial index that can significantly speed up a variety of queries. The disadvantage for users using PostgreSQL versions lower than Version 9.0 is that, without a WHERE clause within the trigger, every time an insert takes place, the trigger will be calculated on all points to create geometry. This method could be very expensive on large datasets. However, for users of PostgreSQL...

Structuring spatial data with table inheritance


An unusual and useful property of PostgreSQL databases is that they allow for object inheritance models as they apply to tables. This means that we can have parent/child relationships between tables and leverage that to structure out data in meaningful ways. In our example, we will apply this to hydrology data. This data can be points, lines, polygons, or more complex structures, but they have one commonality; they are explicitly linked in a physical sense and inherently related and are all about water. Water/hydrology is an excellent natural system to model this way, as our ways of modeling it spatially can be quite mixed depending on scales, details, the data collection process, and a host of other factors.

Getting ready

The data we will be using is hydrology data that has been modified from engineering "blue lines" (see the following screenshot), that is, hydrologic data that is very detailed and meant to be used at scales approaching 1:600...

Extending inheritance – table partitioning


Table partitioning is an approach specific to PostgreSQL that extends inheritance to model tables that typically do not vary from each other in the available fields, but where the child tables represent logical partitioning of the data based on a variety of factors, be it time, value ranges, classifications, or, in our case, spatial relationships. The advantages of partitioning include improved query performance due to smaller indexes and targeted scans of data, bulk loads, and deletes that bypass the costs of maintenance functions like VACUUM. It can thus be used to put commonly used data on a faster and more expensive storage, and the remaining data on a slower and cheaper storage. In combination with PostGIS, we get the novel power of spatial partitioning, which is a really powerful feature for large datasets.

Getting ready

We could use many examples of large datasets that could benefit from partitioning. In our case, we will use a contour dataset...

Normalizing imports


Often data used in a spatial database is imported from other sources. As such it may not be in a form that is useful for our current application. In such a case, it may be useful to write functions that will aid in transforming the data into a form that is more useful for our application. This is particularly the case when going from flat file formats, such as shapefiles, to relational databases such as PostgreSQL.

Note

A shapefile is a de facto as well as formal standard for the storage of spatial data, and is probably the most common delivery format for vector spatial data. A shapefile, in spite of its name, is never just one file, but a collection of files. It consists of at least *.shp (which contains geometry), *.shx (an index file), and *.dbf (which contains the tabular information for the shapefile). It is a powerful and useful format but, as a flat file, it is inherently nonrelational. Each geometry is associated in a one-to-one relationship with each row in a table...

Normalizing internal overlays


Data from an external source can have not just table structure issues, but also topological issues endemic to the geospatial data itself. Take, for example, the problem of data with overlapping polygons. If our dataset has polygons that overlap with internal overlays, queries for area, perimeter, and other metrics may not produce predictable or consistent results.

There are a few approaches that can solve the problem of polygon datasets with internal overlays. The general approach presented here was originally proposed by Kevin Neufeld of Refractions Research.

Over the course of writing our query, we will also produce a solution for converting polygons to linestrings.

Getting ready

First, we'll load our dataset using the following command:

shp2pgsql -s 3734 -d -i -I -W LATIN1 -g the_geom cm_usearea_polygon chp02.use_area | psql -U me -d postgis_cookbook

How to do it...

Now that the data is loaded into a table in the database, we can leverage PostGIS to flatten and...

Using polygon overlays for proportional census estimates


PostgreSQL functions abound for the aggregation of tabular data, including sum, count, min, max, and so on. PostGIS as a framework does not explicitly have spatial equivalents of these, but this does not prevent us from building functions using the aggregates in concert with PostGIS's spatial functionality.

In this recipe, we will explore spatial summarization with the United States Census data. US Census data, by nature, is aggregated data. This is done intentionally to protect the privacy of citizens. But when it comes to doing analyses with this data, the aggregate nature of the data can become problematic. There are some tricks to disaggregate data. Amongst the simplest of these is the use of a proportional sum based on area, which we will do in this exercise.

Getting ready

The problem at hand is that a proposed trail has been drawn in order to provide services for the public. This example could apply to road construction or even...

Left arrow icon Right arrow icon

What you will learn

  • Import and export geographic data from the PostGIS database using the available tools
  • Structure spatial data using the functionality provided by the combination of PostgreSQL and PostGIS
  • Work with a set of PostGIS functions to perform basic and advanced vector analyses
  • Connect PostGIS with Python
  • Learn to use programming frameworks around PostGIS
  • Maintain, optimize, and finetune spatial data for longterm viability
  • Explore the 3D capabilities of PostGIS, including LiDAR point clouds and point clouds derived from Structure from Motion (SfM) techniques
  • Distribute 3D models through the Web using the X3D standard
  • Use PostGIS to develop powerful GIS web applications using Open Geospatial Consortium web standards
  • Master PostGIS Raster

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jan 24, 2014
Length: 484 pages
Edition :
Language : English
ISBN-13 : 9781849518666
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jan 24, 2014
Length: 484 pages
Edition :
Language : English
ISBN-13 : 9781849518666
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 164.97
GeoServer Beginner's Guide
$54.99
PostGIS Cookbook
$54.99
Learning Geospatial Analysis with Python
$54.99
Total $ 164.97 Stars icon
Banner background image

Table of Contents

11 Chapters
Moving Data In and Out of PostGIS Chevron down icon Chevron up icon
Structures that Work Chevron down icon Chevron up icon
Working with Vector Data – The Basics Chevron down icon Chevron up icon
Working with Vector Data – Advanced Recipes Chevron down icon Chevron up icon
Working with Raster Data Chevron down icon Chevron up icon
Working with pgRouting Chevron down icon Chevron up icon
Into the Nth Dimension Chevron down icon Chevron up icon
PostGIS Programming Chevron down icon Chevron up icon
PostGIS and the Web Chevron down icon Chevron up icon
Maintenance, Optimization, and Performance Tuning Chevron down icon Chevron up icon
Using Desktop Clients Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.6
(12 Ratings)
5 star 66.7%
4 star 25%
3 star 8.3%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Nyall Apr 03, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Full of detailed code examples and guides for solving common geospatial problems in PostGIS. This is a great source of inspiration for exploring a wide variety of functions and techniques which are possible in PostGIS. This book isn't aimed at beginners - it's targeted to readers who are familiar with GIS software and have some experience in using PostGIS. Highly recommended for anyone wanting to take their PostGIS skills to the next level.
Amazon Verified review Amazon
cosimociraci Mar 10, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Il libro parte dalle prime pagine subito in quarta. Meglio così piuttosto che i soliti libri che cominciano con cose banali e lasciano poco spazi agli argomenti più complessi che poi sono quelli più utili sul lavoro.Molto materiale del libro non è possibile trovarlo online quindi non è stato affatto un acquisto superfluo.
Amazon Verified review Amazon
Luigi Pirelli Nov 18, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
a lot of receipt really simple to point out. Every example is very well described and detailed. The sequence of chapter is well designed and the book can be read also to learn postgis in a practical way
Amazon Verified review Amazon
Adrian Casillas Jun 23, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I found this book easy to follow and very useful. The recipes are excellent and build progressively. You will pick up considerable GIS knowledge along the way.Well-written; a good read!
Amazon Verified review Amazon
Daniel Lee Mar 23, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I started reading the PostGIS Cookbook with high expectations. Nonetheless, I was positively surprised by the quality of the book, especially regarding its reread value. Skimming through the book once will give you a good idea of what PostGIS is capable of, and it inspired me to move some important parts of automated postprocessing workflows into the database. Keeping the book around will help you put together projects more quickly and efficiently.The book is composed of several recipes, all of which are fairly concise. You should have a bit of background working with geodata and be fairly comfortable with reading SQL in order to get the most out of it, because theoretical explanations are kept to a minimum. This is great for users at or above the intermediate level, because it's a perfect format for quickly looking up practical examples of how certain things are done without having to dig a lot. If you're looking to move from beginner to intermediate user, the examples also will help you a lot.The chapters cover a broad variety of topics, from importing and exporting data to simple raster and vector analyses. Math algebra, terrain analyses, routing and photogrammetry are covered well, as well as serving the data locally or over a web connection and displaying it in a desktop GIS or a self-made web client. There are also some nice examples and explanations of how to administer, maintain and optimize the database itself, as well as analyzing and optimizing the performance of single queries using Postgres' built in profiler. It's helpful for the more advanced topics if you bring some prior knowledge with, but if you're just getting started in these areas the book contains good tips on where you can find further information. The focus is on practicability and presenting examples that are easy to understand, duplicate, and adapt to your own needs.The only thing that I wish were done better is the code formating. I read the ebook version and in some chapters code blocks were missing line breaks. In the SQL this makes it hard to read, especially because no space was substituted for line breaks, which broke the syntax, but for the Python examples this was even worse because the indentation is semantically significant.Aside from the formating problem, I was extremely pleased with the PostGIS Cookbook and will surely use it in the future often while migrating analysis steps and data storage into a Postgres/PostGIS database.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.