PostGIS: Substracting Geometries with ST_Difference()


outer

The outer polygon

In a recent PostgreSQL/PostGIS project I was faced with the following problem:

  • given two geometries A and B
  • calculate that part of A that is (spatially) outside of B
  • call this geometry C

Say we have two geometries “outer polygon” and “inner polygon”:
SELECT ST_AsText('POLYGON((0 0, 0 3, 3 3, 3 0, 0 0))'::geometry) AS "outer polygon";
SELECT ST_AsText('POLYGON((1 1, 1 2, 2 2, 2 1, 1 1))'::geometry) AS "inner polygon";

The outer and the inner polygon

The outer and the inner polygon

Using the function ST_Difference() it is easy two get the geometry of outer polygon without the inner polygon (a nice documentatioon about this and other sPatial Functions can be found in the DB2-Documentation):

SELECT ST_Difference(
  'POLYGON((0 0, 0 3, 3 3, 3 0, 0 0))'::geometry,
  'POLYGON((1 1, 1 2, 2 2, 2 1, 1 1))'::geometry
) AS "the difference";

Displayed as Well Known Text (WKT) this is: POLYGON((0 0,0 3,3 3,3 0,0 0),(1 1,2 1,2 2,1 2,1 1))

The resulting geometry as difference of the input geometries

The resulting geometry as difference of the input geometries

To test if the geometry is what we are expecting it to be lets test if the POINT(1.5 1.5) is contained in the resulting geometry… it should not:


SELECT ST_Contains(
  'POINT(1.5 1.5)'::geometry,
  ST_Difference(
    'POLYGON((0 0, 0 3, 3 3, 3 0, 0 0))'::geometry,
    'POLYGON((1 1, 1 2, 2 2, 2 1, 1 1))'::geometry
  )
) AS "Point is contained in difference (expect f)"; 

Update 2008-11-05, added images and links

2 Responses to “PostGIS: Substracting Geometries with ST_Difference()”

  1. Sinned Says:

    Nice Article,

    is there any possibility to do an ST_Difference like operation with Open Layers?

    Regards
    D

  2. selectoid Says:

    hey Sinned, thanks for commenting.
    AFAIK there is no trivial way to compute the spatial difference between geometries with OpenLayers, but I’d love to have this opportunity.
    What I found is this JavaScript function to check for intersections between geometries from within OpenLayers: http://dev.openlayers.org/releases/OpenLayers-2.7/doc/apidocs/files/OpenLayers/Geometry/Polygon-js.html#OpenLayers.Geometry.Polygon.intersects


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: