## PostGIS: Substracting Geometries with ST_Difference()

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";`

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))`

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)"; ``````

### 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