You are on page 1of 378

JASPA 0.2.

0 Manual

JASPA 0.2.0 Manual


Text is available under the Creative Commons Attribution-ShareAlike 3.0 License.

Contents
1. Introduction ................................................................................................................................. 1 1.1. Overview .......................................................................................................................... 1 1.1.1. Description ............................................................................................................. 1 1.1.2. Features .................................................................................................................. 1 1.1.3. Changes from previous versions. ................................................................................. 1 1.1.4. Versions ................................................................................................................. 1 1.1.4.1. PostgreSQL .................................................................................................. 2 1.1.4.2. H2 .............................................................................................................. 2 1.1.5. Future plans ............................................................................................................ 2 1.1.6. Credits ................................................................................................................... 2 1.1.7. Get Involved ........................................................................................................... 3 1.2. License ............................................................................................................................. 3 1.2.1. JASPA Software ...................................................................................................... 3 1.2.2. JASPA Documentation .............................................................................................. 3 1.3. Libraries and Tools used to create JASPA .............................................................................. 4 1.3.1. Documentation ........................................................................................................ 4 2. Frequently Asked Questions ........................................................................................................... 5 2.1. JASPA Project ................................................................................................................... 5 2.1.1. Why have you created JASPA? .................................................................................. 5 2.1.2. How many versions of JASPA there are? ..................................................................... 5 2.1.3. Who has developed JASPA? ...................................................................................... 5 2.1.4. Does JASPA support the OGC standards? .................................................................... 5 2.1.5. Can I participate in JASPA? ...................................................................................... 5 2.1.6. How can I show my interest in JASPA? ....................................................................... 5 2.1.7. Where can I find a manual or tutorial to learn JASPA? ................................................... 6 2.2. Spatial Data ....................................................................................................................... 6 2.2.1. What software can I use to display the spatial data stored in JASPA? ................................. 6 2.2.2. How can I import my cartography into JASPA? ............................................................ 6 2.2.3. Does JASPA support spatial indexes? .......................................................................... 6 2.3. Errors during the installation ................................................................................................ 6 2.3.1. Starting the H2 server throws an error in the thread "main". org.h2.jdbc.JdbcSQLException: IO Exception: "java.net.UnknownHostException... ...................... 6 2.3.2. ldconfig command does not exist. ............................................................................... 6 2.3.3. When I start or stop the postgres server, it does nothing and it does not return any message ....................................................................................................................................... 6 2.3.4. When installing Jaspa for PostgreSQL, pljavainstall.sql runs seamlessly, but when I run the jaspa.sql file I get an error like: WARNING: java.lang.NoSuchMethodError: Method org.postgresql.pljava.internal.Portal._fetch (JZI): .................................................................... 6 3. Installation ................................................................................................................................... 7 3.1. Install from Binary Distribution ............................................................................................ 7 3.1.1. How to install JASPA for H2 in Windows .................................................................... 7 3.1.1.1. Creating the installation directory ..................................................................... 7 3.1.1.2. Setting up the H2 scripts ................................................................................. 7 3.1.1.3. Starting H2 Server ......................................................................................... 8 3.1.1.4. Creating a new JASPA H2 Spatial Database ....................................................... 8 3.1.1.5. H2 Web Client .............................................................................................. 9 3.1.1.6. Checking that your installation was successful ................................................... 10 3.1.2. How to install JASPA for H2 in Linux ....................................................................... 10 3.1.2.1. Creating the installation directory ................................................................... 10 3.1.2.2. Making links to the bin files .......................................................................... 10 3.1.2.3. Starting H2 Server ....................................................................................... 11 3.1.2.4. A new JASPA H2 Spatial Database ................................................................. 11

iii

JASPA 0.2.0 Manual

3.1.2.5. H2 Web Client ............................................................................................ 3.1.2.6. Checking that your installation was successful ................................................... 3.1.3. How to install JASPA for PostgreSQL in Windows ...................................................... 3.1.3.1. Creating the installation directory ................................................................... 3.1.3.2. Adding Environment Variables to the System Path ............................................. 3.1.3.3. PLJAVA Configuration ................................................................................. 3.1.3.4. Jaspa Template ............................................................................................ 3.1.3.5. A new JASPA for PostgreSQL Spatial Database ................................................ 3.1.3.6. Checking that your installation was successful ................................................... 3.1.4. How to install JASPA for PostgreSQL in Linux ........................................................... 3.1.4.1. Creating the installation directory ................................................................... 3.1.4.2. PLJAVA configuration ................................................................................. 3.1.4.3. JASPA Template ......................................................................................... 3.1.4.4. A new JASPA for PostgreSQL database ........................................................... 3.1.4.5. Checking that your installation was successful ................................................... 3.1.5. Important notes ...................................................................................................... 3.1.5.1. Schemas ..................................................................................................... 3.1.5.2. Importing shape files to JASPA ...................................................................... 3.1.5.3. Spatial Index ............................................................................................... 3.2. Upgrading ....................................................................................................................... 3.2.1. Major Changes (a changes, b and c are the same) ......................................................... 3.2.2. Medium Changes (b changes, a and c are the same) ...................................................... 3.2.3. Minor Changes (c changes, a and b are the same) ......................................................... 3.3. Backup ........................................................................................................................... 3.3.1. Backup for PostgreSQL ........................................................................................... 3.3.2. Backup for H2 ....................................................................................................... 3.4. Compiling from source ...................................................................................................... 3.4.1. Ensure you have Java and Maven .............................................................................. 3.4.2. Copy the JASPA project directory ............................................................................. 3.4.3. Uploading some jars to your local maven repository ..................................................... 3.4.4. Building ................................................................................................................ 3.4.5. Copy the built jar file to the JASPA distribution .......................................................... 3.4.6. Acknowledgement .................................................................................................. 3.5. Configuration of JASPA in Eclipse IDE ............................................................................... 3.5.1. Setting the Eclipse IDE using maven ......................................................................... 3.5.2. Using m2eclipse plugin ........................................................................................... 4. Standards Implementation ............................................................................................................. 4.1. Spatial Standards .............................................................................................................. 4.1.1. OGC .................................................................................................................... 4.1.2. ISO ...................................................................................................................... 4.1.3. JASPA implementation ............................................................................................ 4.2. Standards Disparity ........................................................................................................... 4.2.1. Default SRID ........................................................................................................ 4.2.2. Boolean ................................................................................................................ 5. Spatial Data ............................................................................................................................... 5.1. Geometries ...................................................................................................................... 5.1.1. Types of Geometries ............................................................................................... 5.1.2. Properties .............................................................................................................. 5.1.2.1. Coordinates dimension .................................................................................. 5.1.2.2. Geometric dimension .................................................................................... 5.1.2.3. Interior, Boundary, Exterior ........................................................................... 5.2. Functions Coordinate Dimension ......................................................................................... 5.3. Spatial Relationships ......................................................................................................... 5.4. Formats ...........................................................................................................................

11 12 13 13 13 14 14 14 14 15 15 15 16 16 16 16 16 16 17 17 17 17 18 18 18 19 19 19 20 20 21 21 21 21 21 22 25 25 25 25 26 26 26 26 27 27 27 28 28 28 28 29 31 33

iv

JASPA 0.2.0 Manual

5.4.1. WKB ................................................................................................................... 5.4.2. WKT .................................................................................................................... 5.4.3. EWKB ................................................................................................................. 5.4.4. EWKT .................................................................................................................. 5.4.5. GML .................................................................................................................... 5.4.6. KML .................................................................................................................... 5.5. Metadata tables ................................................................................................................ 5.5.1. Geometry Columns ................................................................................................. 5.5.2. Spatial Reference System ......................................................................................... 5.6. Coordinate System ............................................................................................................ 5.6.1. WKT SRS ............................................................................................................. 5.6.2. Reprojection .......................................................................................................... 5.6.3. WKT Spheroid ...................................................................................................... 5.7. Spatial indexes ................................................................................................................. 5.7.1. Creating spatial indexes ........................................................................................... 5.7.2. Functions using spatial indexes ................................................................................. 5.7.3. Examples .............................................................................................................. 5.8. Connectors ...................................................................................................................... 5.8.1. Mapserver connector (libpq) ..................................................................................... 5.8.2. gvSIG 1.11 ............................................................................................................ 5.8.3. Kosmo .................................................................................................................. 6. Topology ................................................................................................................................... 6.1. Introduction ..................................................................................................................... 6.2. Commands ...................................................................................................................... 6.2.1. Examples .............................................................................................................. 6.3. Steps to create and validate a topology model ........................................................................ 6.3.1. Create a topology model .......................................................................................... 6.3.2. Add layers to the topology model .............................................................................. 6.3.3. Add rules to the topology model ............................................................................... 6.3.4. Validate a topology ................................................................................................ 6.3.5. Obtain information about a topological model .............................................................. 6.3.6. Remove a rule ....................................................................................................... 6.3.7. Remove a layer ...................................................................................................... 6.3.8. Alter a layer .......................................................................................................... 6.3.9. Remove a topological model .................................................................................... 6.3.10. Change the transaction mode .................................................................................. 6.4. Subtypes ......................................................................................................................... 6.4.1. Examples .............................................................................................................. 6.4.2. Restriction on first layer .......................................................................................... 6.4.3. Restriction on second layer ...................................................................................... 6.4.4. Restriction on first and second layer .......................................................................... 6.4.5. Restriction that involves first and second layer at the same time. ..................................... 6.5. Tolerance ........................................................................................................................ 6.5.1. Cluster Tolerance ................................................................................................... 6.5.2. Rules with tolerance (_wt) ....................................................................................... 6.5.3. Search Window ...................................................................................................... 6.6. Topology Rules ................................................................................................................ 6.6.1. Summary of rules ................................................................................................... 6.6.2. Summary of rules in a single layer ............................................................................ 6.6.3. Summary of rules between two layers ........................................................................ 6.6.4. Point rules. Examples .............................................................................................. 6.6.5. Point + Point rules. Examples ................................................................................... 6.6.6. Point +Line rules. Examples ..................................................................................... 6.6.7. Point +Polygon rules. Examples ................................................................................

33 33 34 34 34 35 35 35 36 37 37 37 38 38 38 39 40 40 40 41 42 44 44 44 44 45 45 46 46 47 47 48 48 48 48 48 49 49 50 51 51 52 52 52 52 53 53 54 56 57 58 59 60 60

JASPA 0.2.0 Manual

6.6.8. Line rules. Examples ............................................................................................... 6.6.9. Line + Line rules. Examples .................................................................................... 6.6.10. Line + Polygon rules. Examples .............................................................................. 6.6.11. Polygon rules. Examples ........................................................................................ 6.6.12. Polygon + Point rules. Examples ............................................................................. 6.6.13. Polygon + Line rules. Examples .............................................................................. 6.6.14. Polygon + Polygon rules. Examples ......................................................................... 7. Differences ................................................................................................................................. 7.1. Differences between JASPA and PostGIS ............................................................................. 7.1.1. Box Data Type ...................................................................................................... 7.1.1.1. PostGIS Box Functions ................................................................................. 7.1.1.2. Automatic Cast of PostGIS Box types ............................................................. 7.1.1.3. Examples .................................................................................................... 7.1.2. Coordinate dimensions ............................................................................................ 7.1.2.1. Coordinate Space ......................................................................................... 7.1.2.2. Geometry Outputs ........................................................................................ 7.1.2.3. Mixed Dimension Geometries ........................................................................ 7.1.3. Empty Geometries .................................................................................................. 7.1.4. Dump functions ..................................................................................................... 7.2. Differences between JASPA for PostgreSQL and for H2 .......................................................... 7.2.1. Letter Case ............................................................................................................ 7.2.2. Casts .................................................................................................................... 7.2.2.1. Explicit Casts .............................................................................................. 7.2.2.2. Implicit Casts .............................................................................................. 7.2.3. Arrays .................................................................................................................. 7.2.4. Aggregates ............................................................................................................ 7.2.5. Renamed Functions ................................................................................................ 8. Getting Started ............................................................................................................................ 8.1. Creating a new database .................................................................................................... 8.1.1. PostgreSQL ........................................................................................................... 8.1.2. H2 ....................................................................................................................... 8.1.3. Tutorial ................................................................................................................ 8.1.3.1. PostgreSQL ................................................................................................ 8.1.3.2. H2 ............................................................................................................. 8.2. Creating a table ................................................................................................................ 8.2.1. PostgreSQL ........................................................................................................... 8.2.2. H2 ....................................................................................................................... 8.3. Inserting Data into a Spatial Table ....................................................................................... 8.3.1. OGC Functions ...................................................................................................... 8.3.2. Shp Converter ........................................................................................................ 8.3.2.1. Recommendations shp2jaspah2 ....................................................................... 8.3.2.2. Fields to be included/excluded ....................................................................... 8.3.3. Load data .............................................................................................................. 8.3.4. Tutorial ................................................................................................................ 8.3.5. SHP to SQL .......................................................................................................... 8.3.6. Load SQL files ...................................................................................................... 8.3.7. Jaspa to SHP ......................................................................................................... 8.3.7.1. Example ..................................................................................................... 8.4. Spatial Indexes ................................................................................................................. 8.5. Exercises ......................................................................................................................... 8.5.1. Basis Queries ........................................................................................................ 8.5.2. Store Results in Tables and Views ............................................................................ 8.5.3. Update a table ....................................................................................................... 8.5.4. Intersection ...........................................................................................................

61 63 66 67 68 69 69 72 72 72 72 73 73 74 74 74 75 76 76 78 78 78 78 78 79 80 81 83 83 83 84 85 85 85 86 86 86 87 87 87 88 89 89 89 89 90 91 92 92 92 92 93 94 95

vi

JASPA 0.2.0 Manual

8.5.5. Buffer .................................................................................................................. 97 8.5.6. Dissolution ............................................................................................................ 98 8.5.7. Distance queries ..................................................................................................... 99 8.5.8. Coordinate Projection ............................................................................................ 100 9. Reference ................................................................................................................................. 102 9.1. Management Functions .................................................................................................... 102 9.2. Geometry Constructors ..................................................................................................... 114 9.3. Geometry Accessors ........................................................................................................ 156 9.4. Geometry Editors ............................................................................................................ 192 9.5. Geometry Outputs ........................................................................................................... 233 9.6. Spatial Relationships and Measurements .............................................................................. 242 9.7. Geometry Processing Functions ......................................................................................... 292 9.8. Linear Referencing .......................................................................................................... 330 9.9. Miscellaneous Functions ................................................................................................... 341 10. Functions Clarification .............................................................................................................. 368 10.1. ST_Collect, ST_Force_Collection, ST_MakeGeomColl ........................................................ 368 10.2. ST_Expand for indexable queries ..................................................................................... 369 10.3. ST_Dump, ST_DumpRings, ST_DumpPoints ..................................................................... 370 10.3.1. PostgreSQL ........................................................................................................ 370 10.3.2. H2 .................................................................................................................... 370 A. Jaspa Versions .......................................................................................................................... 371 A.1. Jaspa 0.2.0 .................................................................................................................... 371 A.2. Jaspa 0.1 RC1 ............................................................................................................... 371

vii

Chapter 1. Introduction
1.1. Overview
1.1.1. Description
JASPA (JAva SPAtial) is a spatial extension for relational database systems. JASPA implements the OpenGIS Simple Features for SQL and the SQL/MM standard. JASPA potentially brings around 200 spatial functions to any relational database system that supports a full set of Java stored procedures. In this 0.1 version JASPA is supported by PostgreSQL and H2 databases, and we are already working with HSQLDB. JASPA has a similar functionality as PostGIS 1.4, supporting spatial operators and predicates, arrays of geometries, spatial aggregates, etc. JASPA is written in Java and is easy to extend using Java stored procedures. JASPA is licensed under the GNU GPL.

1.1.2. Features
Fully written in Java Currently uses PostgreSQL and H2 as the backend RDBMS Possibility of migration to other Java databases Implements SFS and SQL-MM standards More than 200 spatial functions available PostGIS compatible Easy-to-extend capabilities using store procedures in Java Use of JTS and GeoTools libraries UMN MapSever as graphical frontend JASPA for PostgreSQL provides spatial indexing based on PostgreSQL Gist Spatial reference systems Support for standard WKT and WKB formats and PostGIS EWKB and EWKT formats Support for SHP, KML and GML as input formats Genuine JASPA topological functions Nodelize, Cleanpolygon, Delaunay triangles, etc.

1.1.3. Changes from previous versions.


In Section A.1, Jaspa 0.2.0 it can be found a list of changes and new features.

1.1.4. Versions
There are different Jaspa distributions to install it depending on the back-end database and the O.S. Jaspa 0.2 can be installed in Linux and Windows as 32-bit or 64-bit application. 32-bit applications can run on a 32-bit or 64-bit version of the O.S. 64-bit applications can only run on a 64-bit version of the O.S.

Introduction

Jaspa installs its own JRE, independently of which is using the OS

1.1.4.1. PostgreSQL
In order to install Jaspa for PostgreSQL, the database PostgreSQL must be previously installed. Jaspa runs with PostgreSQL 8.3, 8.4 or 9.0.

Windows
1. PostgreSQL 8.4 Postgres 32 bits 8.4 Win-32 2. PostgreSQL 9.0 Postgres 32 bits 9.0 Win-32 Postgres 64 bits 9.0 Win-64

Linux
1. PostgreSQL 8.4 Postgres 32 bits 8.4 x86-32 Postgres 64 bits 8.4 x86-64 2. PostgreSQL 9.0 Postgres 32 bits 9.0 x86-32 Postgres 64 bits 9.0 x86-64

1.1.4.2. H2
The only difference between 32 and 64 bit H2 distributions is the JRE used by Jaspa.

Windows
H2 win-32 H2 win-64

Linux
H2 x86-32 H2 x86-64

1.1.5. Future plans


Connectors for map servers and desktop GIS applications (specially for H2 database) Geographical functions based on a spheroid Improve the Cluster/Tolerance system Jaspa for HSQLDB or Oracle Improve 3D/4D methods

1.1.6. Credits
The authors of this project are: Jose C. Martinez-Llario. Developer and project director. (1) Marta Gonzalez-Alcaide. Tester and document builder. (1)

Introduction

(1) Deparment of Cartographic Engineering, Geodesy and Photogrammetry of the Universidad Politecnica de Valencia (Spain). Any contributor is very welcomed to join the JASPA project.

1.1.7. Get Involved


Jaspa is an open source software project. Contributions from users and software developers are very welcomed. Please feel free to let us know your suggestions, comments or questions through the distribution list.

1.2. License
1.2.1. JASPA Software
JASPA is an open source software project. JASPA is released under GNU General Public License. http:// www.gnu.org/copyleft/gpl.html

1.2.2. JASPA Documentation


Text is available under the Creative Commons Attribution-Non Commercial-ShareAlike 3.0 License. This is a human-readable summary of the Legal Code (the full license) [http://creativecommons.org/licenses/by-ncsa/3.0/legalcode]:

You are free:


to Shareto copy, distribute and transmit the work to Remixto adapt the work

Under the following conditions:


AttributionYou must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work.) NoncommercialYou may not use this work for commercial purposes. Share AlikeIf you alter, transform, or build upon this work, you may distribute the resulting work only under the same, similar or a compatible license.

With the understanding that:


WaiverAny of the above conditions can be waived if you get permission from the copyright holder. Other RightsIn no way are any of the following rights affected by the license: your fair dealing or fair use rights; the author's moral rights; and rights other persons may have either in the work itself or in how the work is used, such as publicity or privacy rights. the author's moral rights; and rights other persons may have either in the work itself or in how the work is used, such as publicity or privacy rights. NoticeFor any reuse or distribution, you must make clear to others the license terms of this work. The best way to do that is with a link to http://creativecommons.org/licenses/by-sa/3.0/

Introduction

1.3. Libraries and Tools used to create JASPA


This project has been possible thanks to other open source projects. Besides to take advantage of these projects we have used their mailing lists and they helped us a lot. The JASPA team is very grateful to them:

PostGIS
The mirror which JASPA looks at. http://postgis.refractions.net/

JTS (Java Topology Suite)


JTS Topology Suite is an API of 2D spatial predicates and functions. This library is widely used in JASPA and many open source initiatives bringing the possibility to use spatial analysis to the java open source world.http:// www.vividsolutions.com/jts/jtshome.htm

GeoTools
GeoTools is an open source Java library that provides tools for geospatial data. It is used used for projections, KML support and Shape to JASPA convertershttp://geotools.org/

PostgreSQL and PL/Java


PostgreSQL database http://www.postgresql.org/ PL/Java is a free add-on module that brings Java Stored Procedures to the PostgreSQL backend. http://wiki.tada.se/ index.php/PL/Java

H2 and H2Spatial
A Java database and its spatial extension used at the beginning of JASPA. H2 database http://www.h2database.com/html/main.html

HSQLDB
A Java database which probably will be supported by JASPA in the next release. http://hsqldb.org/

gvSIG
A desktop GIS which we hope it can connect to JASPA soon. http://www.gvsig.org

1.3.1. Documentation DocBook


DocBook (xsltproc) is required for building the documentation. http://www.docbook.org/

Apache FOP
Formatting Object Processor (FOP) is a Java based print formatter based on the XSL-FO standard. http:// xmlgraphics.apache.org/fop/index.html

XML Editor
A visual XML editor. http://www.xmlmind.com/xmleditor/

Chapter 2. Frequently Asked Questions


This is a collection of some Frequently Asked Questions regarding JASPA. Over time more FAQ will be added.

2.1. JASPA Project


2.1.1. Why have you created JASPA?
After working with PostGIS for five years we have had the need to extend it to incorporate new functionalities accessing to GEOS objects and creating new stored procedures in C. The PostGIS source code is not easy to understand especially for users that are not computer science expertise. In many cases PostGIS users are cartographic engineers, geographers, etc. which are really capable to analysis maps, design cartographic models, solve geodesic problems, etc. but as we said before they are not computer science experts, so we wanted to create a spatial database which is easier to extend and to use a programming language which could be easier to understand too. We think that JASPA accomplish that goal and moreover it can be used with other databases besides PostgreSQL. Future plans to developed Jaspa include tolerances, hybrid topology systems, cartographic models and other capacities, which proved difficult to implement in PostGIS. Even though talking about functionality current JASPA and PostGIS 1.4 are similar products, JASPA can walk away from PostGIS in the future. Jaspa does not aim to be a competitor of PostGIS. We think PostGIS is nowadays the best open source spatial database indeed. The current main goal of JASPA is to be a research product which students and faculty can use to teach and experience how to understand a spatial database and to develop their own research algorithms and functionality.

2.1.2. How many versions of JASPA there are?


There are two versions of JASPA. JASPA for PostgreSQL (JASPA4PG) and JASPA for H2 (JASPA4H2). Currently we are working to support H2SQLDB.

2.1.3. Who has developed JASPA?


JASPA has been developed in the department of Cartographic Engineering, Geodesy and Photogrammetry of the Universidad Politecnica de Valencia (Spain) by: Jose C. Martinez-Llario. Developer and project director. Marta Gonzalez-Alcaide. Tester and document builder

2.1.4. Does JASPA support the OGC standards?


Yes, JASPA supports the Simple Features for SQL standard and some of the SQL/MM standard. The conformance is similar to the PostGIS one. Besides that, JASPA implements an extra amount of functions that are not included in these standards but are necessary in a spatial database.

2.1.5. Can I participate in JASPA?


Of course, JASPA is released under a GPL license. Now, we do not have the suitable infrastructure (SVN repository, etc.) but you can get the JASPA source code from the forge and to contribute through the mail list and the feature request (tracker) at http://forge.osor.eu/projects/jaspa/

2.1.6. How can I show my interest in JASPA?


Please, if you are interested in JASPA do not hesitate to subscribe to the mail list. I would be pleased to know that you are using JASPA. http://lists.forge.osor.eu/mailman/listinfo/jaspa-users [http://lists.forge.osor.eu/mailman/listinfo/ jaspa-users]

Frequently Asked Questions Do not worry if your browser throws you a security warning. It is a safe place, trust me.

2.1.7. Where can I find a manual or tutorial to learn JASPA?


You can find the official JASPA manual at http://jaspa.forge.osor.eu/ [http://jaspa.forge.osor.eu/ ] There you will find a full description and examples of every JASPA SQL command, how to install or build it, etc.

2.2. Spatial Data


2.2.1. What software can I use to display the spatial data stored in JASPA?
So far, this is a pretty weak point of JASPA. You just can display the spatial data using UMN MapServer and JASPA4PG. We are talking with several open source desktop GIS and spatial libraries to support JASPA.

2.2.2. How can I import my cartography into JASPA?


You can use the shp2jaspapg and shp2jaspah2 converters.

2.2.3. Does JASPA support spatial indexes?


JASPA4PG supports spatial indexes using Gist in a similar way PostGIS does. JASPA4H2 does not support spatial indexes. We hope the H2 and HSQLDB developers can make it in the future.

2.3. Errors during the installation


2.3.1. Starting the H2 server throws an error in the thread "main". org.h2.jdbc.JdbcSQLException: IO Exception: "java.net.UnknownHostException...
Edit the file /etc/hosts and the hostname of your linux machine. For instance if your machine is called "virtual_machine" add the line: 127.0.1.1 alumno-virtual-machine

2.3.2. ldconfig command does not exist.


Install the ldconfig command from the package manager of your Linux distribution. Usually this command is in the packages glibc or glibc-devel

2.3.3. When I start or stop the postgres server, it does nothing and it does not return any message
Possibly there is at least an active connection (a terminal psql, pgadmin3, a GIS desktop software or any other software). The solution is to end all connections.

2.3.4. When installing Jaspa for PostgreSQL, pljavainstall.sql runs seamlessly, but when I run the jaspa.sql file I get an error like: WARNING: java.lang.NoSuchMethodError: Method org.postgresql.pljava.internal.Portal._fetch (JZI):
Check if there is any file pljava.dll or pljava.jar in the lib folder of the postgres installation directory and delete it.

Chapter 3. Installation
3.1. Install from Binary Distribution
You can download JASPA binaries from http://forge.osor.eu/projects/jaspa/ To install JASPA you must follow the instructions of one of the following sections depending on your backend database (PostgreSQL or H2) and your Operating system (Windows or Linux i386).

3.1.1. How to install JASPA for H2 in Windows 3.1.1.1. Creating the installation directory
Create a new directory c:\jaspa4h2 and extract the jaspa4h2_win.zip file into this new directory. After extracting the file you should see something like: c:\jaspa4h2\lib c:\jaspa4h2\bin c:\jaspa4h2\sql c:\jaspa4h2\doc c:\jaspa4h2\jre

Figure 3.1. jaspa4h2 folder

3.1.1.2. Setting up the H2 scripts


It can be done in two different ways:

a) Copying files in System folder


Copy the files in the path c:\jaspa4h2\bin\ to your windows system directory. If your system directory is c:\windows \system32 then you will have: c:\windows\system32\h2.bat c:\windows\system32\h2console.bat c:\windows\system32\h2script.bat c:\windows\system32\h2runscript.bat

Installation c:\windows\system32\shp2jaspah2.bat c:\windows\system32\jaspah22shp.bat

b) Adding a Directory to the Path


Alternatively, you can setup the system PATH variable to point out to c:\jaspa4h2\bin. To change the system environment variables, follow these steps: 1. Right-click My Computer and click Properties 2. In the System Properties window, click on the Advanced tab. 3. In the Advanced section, click the Environment Variables button. 4. Finally, in the Environment Variables window, select the Path variable in the Systems Variable section and click the Edit button. Each different directory is separated with a semicolon (;). Append the following path to the end of Path variable:
;c:\jaspa4h2\bin

Figure 3.2. A new variable in the System Path

3.1.1.3. Starting H2 Server


Open a command prompt shell and run the following command:
h2

Depending on your firewall configuration, a confirm pop up could ask if you want to allow the connection, click Yes Result of starting the H2 server:

3.1.1.4. Creating a new JASPA H2 Spatial Database


In this step you are going to create a new database (myfirstjapadb) and to execute the file jaspa.sql into it to make it spatial. Open a command prompt shell and run the following command:

Installation

h2runscript -url jdbc:h2:tcp://localhost/~/myfirstjaspadb -user sa -password 123 -script c: \jaspa4h2\sql\jaspa.sql -showResults

3.1.1.5. H2 Web Client


You can use any H2 client. We are going to use the default H2 client. Open a command prompt shell and run the following command:
h2console

An Internet browser should open, and you have to set up the connection parameters with the following values: Parameter Saved settings Setting name Driver Class JDBC URL User Name Password Generic H2 (Server) Generic H2 (Server) org.h2.Driver jdbc:h2:tcp://localhost/~/ myfirstjaspadb;SCHEMA_SEARCH_PATH=PUBLIC,JASPA sa 123 Value

The character ~ is an alias of the user directory. In Linux, it refers to the home directory. In Windows XP, it refers to C:\documents and settings\user\ In Windows Vista and Windows 7, it refers to C:\Users\user\

Figure 3.3. Connection to H2 Web Client

Installation

3.1.1.6. Checking that your installation was successful


Once you have connected to the H2 Web Client, you should see something similar to the next screenshot.

Figure 3.4. H2 Web Client

To check that your installation was successful you can use the following SQL sentence.
SELECT jaspa_full_version(); --Jaspa should return something like that -> JASPA (JAva SPAtial) For H2="0.1 RC1" JTS="1.11.0 forjaspa" GeoTools="2.7-M1" JRE="1.6.0_18"

3.1.2. How to install JASPA for H2 in Linux


This how-to will install the H2 server too. Do not worry, if you have already installed it, it is harmless.

3.1.2.1. Creating the installation directory


For this step you will need root privileges. Create a new directory /opt/jaspa4h2/ . Extract the jaspa4h2_i586.tar.gz file into this new directory. After the extraction, you should see something like: /opt/jaspa4h2/lib /opt/jaspa4h2/bin /opt/jaspa4h2/sql /opt/jaspa4h2/doc /opt/jaspa4h2/jre

3.1.2.2. Making links to the bin files


In a shell (with root privileges), run the following commands:
ln ln ln ln ln ln -s -s -s -s -s -s /opt/jaspa4h2/bin/shp2jaspah2 /usr/bin/shp2jaspah2 /opt/jaspa4h2/bin/jaspah22shp /usr/bin/jaspah22shp /opt/jaspa4h2/bin/h2 /usr/bin/h2 /opt/jaspa4h2/bin/h2console /usr/bin/h2console /opt/jaspa4h2/bin/h2script /usr/bin/h2script /opt/jaspa4h2/bin/h2runscript /usr/bin/h2runscript

10

Installation

3.1.2.3. Starting H2 Server


In a shell run the following command:
h2

3.1.2.4. A new JASPA H2 Spatial Database


In this step, you are going to create a new database (myfirstjapadb) and to execute the file jaspa.sql into it to make it spatial. In a shell run the following command:
h2runscript -url jdbc:h2:tcp://localhost/~/myfirstjaspadb -user sa -password 123 -script /opt/ jaspa4h2/sql/jaspa.sql -showResults

3.1.2.5. H2 Web Client


You can use any H2 client. We are going to use the default H2 client. Open a command prompt shell and run the following command:
h2console

An Internet browser should open, and you have to set up the connection parameters with the following values: Parameter Saved settings Setting name Driver Class JDBC URL User Name Password Generic H2 (Server) Generic H2 (Server) org.h2.Driver jdbc:h2:tcp://localhost/~/ myfirstjaspadb;SCHEMA_SEARCH_PATH=PUBLIC,JASPA sa 123 Value

The character ~ is an alias of the user directory. In Linux, it refers to the home directory. In Windows XP, it refers to C:\documents and settings\user\ In Windows Vista and Windows 7, it refers to C:\Users\user\

11

Installation

Figure 3.5. Connection to H2 Web Client

3.1.2.6. Checking that your installation was successful


Once you have connected to the H2 Web Client, you should see something similar to the next screenshot.

Figure 3.6. H2 Web Client

To check that your installation was successful you can use the following SQL sentence.
SELECT jaspa_full_version(); --Jaspa should return something like that -> JASPA (JAva SPAtial) For H2="0.1 RC1" JTS="1.11.0 forjaspa" GeoTools="2.7-M1" JRE="1.6.0_18"

12

Installation

3.1.3. How to install JASPA for PostgreSQL in Windows


This how-to assume that PostgreSQL is already installed on your computer. If it is not true then proceed to download and install PostgreSQL for windows (the one click installer) from: http://www.postgresql.org/download/windows This installation procedure is a little bit long mainly because you have to install PLJava under PostgreSQL as you can see later. Once PLJava is installed you just have to repeat the short steps 6 and 7 to create a new JASPA spatial database. If you are using Windows VISTA, make sure that User Account Control (UAC) is turned off through user accounts.

3.1.3.1. Creating the installation directory


Create a new directory c:\jaspa4pg . Extract the jaspa zip file into this directory, jaspa4pg8.4_win.zip (if your PostgreSQL version is 8.4) jaspa4pg8.3_win.zip (if your PostgreSQL version is 8.3). After extract the file you should see something like: C:\jaspa4pg\lib C:\jaspa4pg\bin C:\jaspa4pg\sql C:\jaspa4pg\doc C:\jaspa4pg\jre

Figure 3.7. jaspa4pg folder

3.1.3.2. Adding Environment Variables to the System Path


To change the system environment variables, follow these steps: 1. Right-click My Computer and click Properties. 2. In the System Properties window, click on the Advanced tab. 3. In the Advanced section, click the Environment Variables button. 4. Finally, in the Environment Variables window, select the Path variable in the Systems Variable section and click the Edit button. Each different directory is separated with a semicolon (;). Append the followings paths to the end of Path variable:

13

Installation

;C:\jaspa4pg\jre\bin;C:\jaspa4pg\jre\bin\client;c:\jaspa4pg\bin;C:\jaspa4pg\jre\bin\server

You must not delete or overwrite the paths that are already in the Path variable! Also, make sure you don't have an extra "\" at the end of the paths

Figure 3.8. A new variable in the System Path

Optional: if the PostgreSQL/bin path is not included in the Path variable is a good idea to include it too. For that, you have to find out where is PostgreSQL installed on your computer (e.g C:\Program Files\PostgreSQL\8.4\bin or C:\Program Files\PostgreSQL\9.0\bin)

3.1.3.3. PLJAVA Configuration


Locate the file postgresql.conf . It is located under the directory data, on your PostgreSQL cluster installation Example: C:\Program Files\PostgreSQL\8.4\data\postgresql.conf Open the file jaspa4pg/doc/html/pgconf-wint.txt and add its content to the end of the postgresql.conf file. Lines to be added [pgconf-win.txt] Stop and start the PostgreSQL server service to re-read the postgresql.conf file (Start Button / All Programs / Postgresql 8.4 / Stop Service & Start Button / All Programs / Postgresql 8.4 / Start Service)

3.1.3.4. Jaspa Template


Open a command prompt shell Run each of the following commands (the system will ask you the postgresql password):
createdb -U postgres jaspatemplate psql -U postgres -f C:\jaspa4pg\sql\pljavainstall.sql -d jaspatemplate psql -U postgres -f C:\jaspa4pg\sql\jaspa.sql -d jaspatemplate

3.1.3.5. A new JASPA for PostgreSQL Spatial Database


Now you have a jaspa template ready to create easily as many new jaspa spatial database as you want. Let's create our first jaspa spatial database called myfirstjaspadb
createdb -U postgres -T jaspatemplate myfirstjaspadb

3.1.3.6. Checking that your installation was successful


To check everything is fine you can use the following SQL sentence. Connect to the new database using any postgresql client (psql, pgadmin3, etc.) and execute:
SELECT jaspa.jaspa_full_version(); --Jaspa should return something like that -> JASPA (JAva SPAtial) For PostgreSQL="0.1 RC1" JTS="1.11.0 forjaspa" GeoTools="2.7-M1" JRE="1.6.0_18"

14

Installation

3.1.4. How to install JASPA for PostgreSQL in Linux


This how-to assume that PostgreSQL is already installed on your computer. If it is not true then proceed to download and install PostgreSQL from http://www.postgresql.org/download This installation procedure is a little bit long mainly because you have to install PLJAVA under PostgreSQL as you can see later. Once PlJava is installed you just have to repeat the short steps 6 and 7 to create a new jaspa spatial database.

3.1.4.1. Creating the installation directory


For this step you will need root privileges Create a new directory /opt/jaspa4pg . Extract to this new directory the jaspa tar file, jaspa4pg8.4_i586.tar.gz (if your PostgreSQL version is 8.4) or jaspa4pg8.3_i586.tar.gz (if your PostgreSQL version is 8.3). After extracting the file you should see something like: /opt/jaspa4pg/lib /opt/jaspa4pg/bin /opt/jaspa4pg/sql /opt/jaspa4pg/doc /opt/jaspa4pg/jre

3.1.4.2. PLJAVA configuration


Locate the file postgresql.conf. The location of this file depends on your Linux distribution and how your PostgreSQL server is configured. For instance, in OpenSUSE 11.2, it can be found in: /var/lib/pgsql/data/postgresql.conf in Ubuntu (9.10 and 10.04), it can be found in: /etc/postgresql/8.4/main/postgresql.conf Edit the postgresql.conf file, with root privileges, by adding to the end of it the content of the file jaspa4pg/doc/html/ pgconf-i586.txt. Lines to be added [pgconf-i586.txt] Edit the file ld.so.conf , with root user privileges, located in /etc/ld.so.conf and add the following lines at the end of it.
/opt/jaspa4pg/jre/liblink /opt/jaspa4pg/jre/liblink/client /opt/jaspa4pg/jre/liblink/server /opt/jaspa4pg/jre/liblink/native_threads

In a shell, run the following commands:


ldconfig ln -s /opt/jaspa4pg/bin/shp2jaspapg /usr/bin/shp2jaspapg ln -s /opt/jaspa4pg/bin/jaspapg2shp /usr/bin/jaspapg2shp

With root user privileges: Stop and start the PostgreSQL server service: OpenSUSE: open Yast, go to System / System Services (Runlevels) , select the postgresql service and press disable (wait the server to stop) and Press enable (wait the server to start). Ubuntu: System / Administration / BootUp-Manager (if you do not have this tools installed in your ubuntu distribution, you can install it easily using synaptic package manager)

15

Installation Activate the check box about postgresql server. Apply the changes Generic Linux: /etc/init.d/postgresql start /etc/init.d/postgresql stop

3.1.4.3. JASPA Template


Open a command prompt shell Run each of the following commands (the system will ask you the postgres password):
createdb -U postgres jaspatemplate psql -U postgres -f /opt/jaspa4pg/sql/pljavainstall.sql -d jaspatemplate psql -U postgres -f /opt/jaspa4pg/sql/jaspa.sql -d jaspatemplate

3.1.4.4. A new JASPA for PostgreSQL database


Now you have a jaspa template ready to create easily as many new jaspa spatial database as you want. Let's create our first jaspa spatial database called myfirstjapadb.
createdb -U postgres -T jaspatemplate myfirstjaspadb

3.1.4.5. Checking that your installation was successful


To check everything went fine you can enter into the new database using any postgresql client (psql, pgadmin3, etc.) and execute the following sentence:
SELECT jaspa_full_version(); --Jaspa should return something like that -> JASPA (JAva SPAtial) For PostgreSQL="0.1 RC1" JTS="1.11.0 forjaspa" GeoTools="2.7-M1" JRE="1.6.0_18"

3.1.5. Important notes 3.1.5.1. Schemas


JASPA for PostgreSQL and for H2 stores spatial functions and metadata tables into the schema jaspa.

PostgreSQL
In PostgreSQL the schemas to look in is automatically specified in the postgresql.conf file.

H2
In H2 database you can specify the schema to look in with the connection parameter JDBC URL. For instance: JDBC URL jdbc:h2:tcp://localhost/~/myfirstjaspadb;SCHEMA_SEARCH_PATH=PUBLIC,JASPA

If you leave out "SCHEMA_SEARCH_PATH=PUBLIC,JASPA", you have to indicate that jaspa spatial functions are located in the schema jaspa. Example:
SELECT jaspa.ST_IsClosed(jaspa.ST_GeomFromText('LINESTRING (0 0, 10 20, 30 20,0 0)'));

or alternatively, you can set the schema_search_path parameter in each session:


SET SCHEMA_SEARCH_PATH=PUBLIC,JASPA; SELECT ST_IsClosed(ST_GeomFromText('LINESTRING (0 0, 10 20, 30 20,0 0)'));

3.1.5.2. Importing shape files to JASPA


Use the command 'shp2jaspapg' (PostgreSQL) o 'shp2jaspah2' (H2), the same way you use 'shp2pgsql' in PostGIS. Please refer to Section 8.3.2, Shp Converter for further information.

16

Installation

3.1.5.3. Spatial Index


PostgreSQL. The way to create an spatial index is slightly different: use the function ST_PGBox
create index idx_puntos_funcion on puntos using gist (ST_PGBox(geom));

The use of spatial indexes is the same in PostGIS and Jaspa4PG - select count(*) from puntos p1, puntos p2 where (p1.geom && p2.geom); H2 does not support spatial indexes at this moment. Please refer to Section 5.7, Spatial indexes for further information.

3.2. Upgrading
The versioning system is based on 3 values. Jaspa a.b.c version. Depending on the previous and new Jaspa version, the installation process will be different. It explains how to update a spatial database. Although not necessary, it is always advisable to made before a backup.

3.2.1. Major Changes (a changes, b and c are the same)


It is necessary to remove Jaspa intallation directories and install it from scratch. If we have a Jaspa spatial database it is necessaty to update it. If we have a Jaspa template, we must create it again. Update an existing database: 1. Execute the before_upgrading_from_X.X.sql script in your database: psql -U <user> -f before_upgrading_from_a.X.sql <database> The before_upgrading_from_X.X.sql file is located in the folder sql of the installation. That script deletes all the functions except those that are referenced in a check restriction of a tables or a trigger. 2. Execute the after_upgrading_to_X.X.sql script in your database: psql -U <user> -f after_upgrading_to_a.X.sql <database> For instance if we upgrade a database called mydatabase from version 0.2 to 1.1 we must execute:
psql -U postgres -f before_upgrading_from_0.2.sql mydatabase psql -U postgres -f after_upgrading_to_1.1.sql mydatabase

3.2.2. Medium Changes (b changes, a and c are the same)


It is necessary to unzip a patch inside the Jaspa installation directory. It will update the necessary files. If we have a Jaspa template, we must update it or create it again. If we have Jaspa spatial databases it is necessaty to update them. Update an existing database: 1. Execute the before_upgrading_from_X.X.sql script in your database: psql -U <user> -f before_upgrading_from_X.X.sql <database> The before_upgrading_from_X.X.sql file is located in the folder sql of the installation. That script deletes all the functions except those that are referenced in a check restriction of a tables or a trigger. 2. Execute the after_upgrading_to_X.X.sql script in your database: psql -U <user> -f after_upgrading_to_X.X.sql <database> For instance if we upgrade a database called mydatabase from version 0.2 to 0.3 we must execute:
psql -U postgres -f before_upgrading_from_0.2.sql mydatabase psql -U postgres -f after_upgrading_to_0.3.sql mydatabase

17

Installation

3.2.3. Minor Changes (c changes, a and b are the same)


It is only necessary to unzip a patch inside the Jaspa installation directory. It will update the necessary files (usually the jaspa.jar file, or some other files, update documentation, etc.) In any case, there is no need to reinstall or upgrade spatial databases of the previous version.

3.3. Backup
It is always advisable to make backup copies periodically.

3.3.1. Backup for PostgreSQL


Backup files can be created in text or binary format. In this section it is explained how to make a backup of a Jaspa spatial database, and restore the data into a new database:

Text Format
1. Create the backup file: pg_dump -U [user] -b -Fp -N jaspa -N sqlj <database_name> > <backup_file> Example. Backup the database "mydb":
pg_dump -U postgres -b -Fp -N jaspa -N sqlj mydb > /tmp/mydb.backup

2. Optional. Create a new spatial database createdb -U <user> -T <jaspatemplate> <db_name> Example. Create a new spatial db named "mydb2"
createdb -U postgres -T jaspatemplate mydb2

3. Insert the backup file psql -U <user> -f <backup_file> <database_name>


psql -U postgres -f /tmp/mydb.backup mydb2

4. Fill the metadata table GEOMETRY_COLUMNS: select probe_geometry_columns(); Example. Login in the database mydb2, and execute the function probe_geometry_columns():
psql -U postgres mydb2 mydb2=# select probe_geometry_columns();

Binary Format
Alternatively the backup can be created in binary format. Thus, the backup file is smaller but to load it the order pg_restore must be used (instead of psql -f) 1. Create the backup file: pg_dump -U [user] -b -Fc -N jaspa -N sqlj [database_name] > [backup_file] Example backup of the database "mydb":
pg_dump -U postgres -b -Fc -N jaspa -N sqlj mydb > /tmp/mydb.backup

2. Optional. Create a new spatial database createdb -U <user> -T <jaspatemplate> <db_name> Example. Create a new spatial db named "mydb2"
createdb -U postgres -T jaspatemplate mydb2

3. Insert the backup file pg_restore -U <user> -d <database_name> <backup_file>


pg_restore -U postgres -d mydb2 /tmp/mydb.backup

18

Installation 4. Fill the metadata table GEOMETRY_COLUMNS: select Probe_Geometry_Columns(); Example. Login in the database mydb2, and execute the function probe_geometry_columns():
psql -U postgres mydb2 mydb2=# select probe_geometry_columns();

The backup throws errors like:


ERROR: ERROR: ERROR: ERROR: language "java" already exists language "javau" already exists language "plpgsql" already exists schema "topo" already exists

these errors are normal and should be ignored. If the process gives any other error then it should be analyzed.

3.3.2. Backup for H2


1. Create the backup file:
shell> h2script -url <jdbc_url> -user sa -password 123 -script <zip_file> -options compression zip

2. Load the backup file:


shell> h2runscript -url <jdbc_url> -user sa -password 123 -script <zip_file> -options compression zip

The database where we load the script must not be spatially enabled.
h2script -url jdbc:h2:tcp://localhost/~/myfirstjaspadb -user sa -password 123 -script /tmp/ test.zip -options compression zip h2runscript -url jdbc:h2:tcp://localhost/~/u2 -user sa -password 123 -script /tmp/test.zip options compression zip

3.4. Compiling from source


3.4.1. Ensure you have Java and Maven
For building JASPA you will need a build tool called maven. You can get it from: Maven - http://maven.apache.org/ Maven is a build tool that is going to help sort all of this stuff out. You may be used to using ant, or sticking to the safe confines of your IDE. If so, bear with me for a moment as we set up a simple maven project. I think you will find this tool makes things much easier. You can check to see if you have the command line Maven utility installed and, if so, the version as follows:
shell:> mvn -version Apache Maven 2.2.1 (rdebian-1) Java version: 1.6.0_18 Java home: /usr/lib/jvm/java-6-openjdk/jre Default locale: en_US, platform encoding: UTF-8 OS name: "linux" version: "2.6.32-21-generic" arch: "i386" Family: "unix"

I am using Java 1.6 above; and Maven 2.2.1. You can use Java 5 if you like; currently JASPA is developed against Java 1.5.

19

Installation Notes: If you are using the Netbeans IDE for development then the command line Maven utility is optional because there is support for Maven within the IDE. The notes below refer to Netbeans version 6.7.1. Windows and OSX users can download and install maven from apache: http://maven.apache.org/download.html Linux users can install maven using the package managers as Synaptic (ubuntu) or YAST (open suse). Alternatively the Linux users can either download from the maven web site or use apt-get:
apt-get maven

You can find a more detailed maven installation help in the book Maven: By Example. An Introduction to Apache Maven from Sonatype. Chapter 2. This book is licensed under a Creative Commons license and can be downloaded for free from: http://www.sonatype.com/books/mvnex-book/reference/public-book.html

3.4.2. Copy the JASPA project directory


Unpack the file jaspasrc.zip in your user or home directory (actually any directory in which you have write permissions will work). You will get a directory structure as: .../jaspa/distro .../jaspa/srd .../jaspa/pom.properties .../jaspa/pom.xml

3.4.3. Uploading some jars to your local maven repository


Open a console and change the directory to: .../jaspa Run the following commands in order to upload the JTS and pljava jars to your local maven repository:
mvn install:install-file -DgroupId=org.postgresql -DartifactId=pljava -Dversion=1.4.2 Dpackaging=jar -Dfile=distro/source/libsnomvn/pljava.jar mvn install:install-file -DgroupId=com.vividsolutions -DartifactId=jts -Dversion=1.11m Dpackaging=jar -Dfile=distro/source/libsnomvn/jts-1.11m.jar

The first time you run the mvn command, maven will download all the required files to work itself so do not worry if you see a lot of maven messages. After running the mvn commands the last messages should be something like that:
[INFO] -----------------------------------------------------------------------[INFO] Building jaspa [INFO] task-segment: [install:install-file] (aggregator-style) [INFO] -----------------------------------------------------------------------[INFO] [install:install-file {execution: default-cli}] [INFO] Installing /home/alumno/Documents/jaspa/distro/source/libsnomvn/jts-1.11m.jar to /home/ alumno/.m2/repository/com/vividsolutions/jts/1.11m/jts-1.11m.jar [INFO] -----------------------------------------------------------------------[INFO] BUILD SUCCESSFUL [INFO] -----------------------------------------------------------------------[INFO] Total time: < 1 second [INFO] Finished at: Thu Jul 08 09:45:28 PDT 2010 [INFO] Final Memory: 4M/7M [INFO] ------------------------------------------------------------------------

20

Installation

3.4.4. Building
From the same directory run:
mvn clean install

If everything is working well then maven will download all the required jars and will build JASPA. You should get a '[INFO] BUILD SUCCESSFUL' message as before.

3.4.5. Copy the built jar file to the JASPA distribution


Maven will have created a jaspa/target directory where the jaspa jar will be located. You just have to copy this file into the jaspa binaries distribution (c:\jaspa4pg\lib and c:\jaspa4h2\lib in MS Windows; / opt/jaspa4pg/lib and /opt/jaspa4h2/lib in Linux).

3.4.6. Acknowledgement
This document is based on the Geotools QuickStart document. http://docs.geotools.org/stable/userguide/ quickstart.html

3.5. Configuration of JASPA in Eclipse IDE


To use Eclipse IDE with JASPA project you have several alternatives. 1. Using a maven command to prepare the eclipse project. This solution is easier but simple. 2. Using the maven plugin m2eclipse. This solution requires to install a eclipse plugin but it is more complete than the previous one.

3.5.1. Setting the Eclipse IDE using maven


You can set up eclipse to understand the maven jars repository. Eclipse users now need to set things up for the IDE. Run the following command:
.../jaspa mvn eclipse:eclipse

This command will create the files .../jaspa/.classpath and .../jaspa/.project with all the required jars for Eclipse to build the JASPA project. You can now give Eclipse the background information it needs to talk to your maven repository. 1. Start up Eclipse 2. Open up the Windows > Preferences menu 3. Navigate to the Java > Build path > Classpath Variables preferences page 4. Add an M2_REPO classpath variable pointing to your local repository (in your home directory): Windows XP: C:\Documents and Settings\.m2\repository Windows Vista and Windows 7: C:\Users\<your_user>\.m2\repository Linux and Mac: ~/.m2/repository

21

Installation

Figure 3.9. Adding a classpath variable in Eclipse

1. Select the File > Import menu 2. Choose General > Existing Projects into Workspace, and press Next 3. Select the root directory .../jaspa 4. Finish If you change any maven dependency then you should update the .classpath and .project eclipse files. For that, you can regenerate them using the following maven command (do not forget to refresh eclipse to notice the changes):
mvn eclipse:eclipse

3.5.2. Using m2eclipse plugin


You can find a more detailed m2eclipse installation help in the book m2eclipse: Maven integration for Eclipse from Sonatype, chapter 2. This book is licensed under a Creative Commons license and can be downloaded for free from: http://www.sonatype.com/books/m2eclipse-book/reference/ 1. Start up Eclipse 2. Select Help > Install New Software. The install dialog should appear. 3. Press the add button. 4. Now you have to enter the name and location of the m2eclipse repository. name: location: m2eclipse http://m2eclipse.sonatype.org/sites/m2e

5. In the work with Box, it should appear the new repository. Chose the component listed 'Maven Integration for Eclipse (required)'. 6. Click Next. Eclipse will show if there are any issues.

22

Installation 7. Click Next to agree the license. 8. Click Finish to start the installation.

Figure 3.10. Maven Integration for Eclipse Plugin

Now you have to import the Maven Project into the Eclipse IDE. 1. Select File > Import 2. In the import dialog chose: Maven > Existing Maven project 3. Select the directory which jaspa is installed: .../jaspa 4. Eclipse should detect automatically the file /pom.xml 5. Press the Finish button

23

Installation

Figure 3.11. Maven Project Selection pom.xml

24

Chapter 4. Standards Implementation


4.1. Spatial Standards
There are two organizations producing spatial standards of particular importance, the ISO (International Organization for Standardization) and OGC (Open GIS Consortium).

4.1.1. OGC
OGC provides a wide range of Standards and Specifications. The OGC Simple Features Interface Standard (SFS) is specially important. It provides a well-defined and common way for applications to store and access feature data in relational or object-relational databases. There are three versions of this Standard, though the first two ones are deprecated.

OGC SFS Standards


Version 1.1 Document Title OpenGIS Simple Features 99-049 Implementation Specification for SQL OpenGIS Implementation 05-134 Specification for Geographic information - Simple feature access OpenGIS Implementation 06-104r3 Specification for Geographic information - Simple feature access Part 2: SQL option Document

1.1.0

1.2.0

The 1.2.0 specification, appeared in 2006, develops the previous specifications to support "Z" and "M" (measure) coordinates. OGC Specifications can be found in: Simple Feature Access Part 1 - Common Architecture [http://www.opengeospatial.org/standards/sfa] Simple Feature Access Part 2 SQL Options [http://www.opengeospatial.org/standards/sfs] Geography Markup Language [http://www.opengeospatial.org/standards/gml] KML [http://www.opengeospatial.org/standards/kml]

4.1.2. ISO
The ISO/IEC 13249 SQL Multi-Media and Application Packages standard is specially important. This standard, known as SQL/MM, is divided in the following parts: 1. Part 1: Framework 2. Part 2: Full-Text 3. Part 3: Spatial 4. Part 5: Still Image 5. Part 6: Data Mining SQL/MM- Part 3 standardizes spatial types and routines to store, manage and retrieve spatial data using SQL.

25

Standards Implementation

4.1.3. JASPA implementation


In the chapter JASPA Reference, a definition of each function can be found. It includes the section of the spatial standards that are implemented. For instance, the method ST_Area implements the following standard methods:

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.9.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.14.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.12.2 SQL-MM Part 3 8.1.2 - 9.5.3

4.2. Standards Disparity


There are several differences between the spatial specifications and the implementation in JASPA.

4.2.1. Default SRID


Each spatial feature has a spatial reference identifier (SRID). The default SRID for geometry instances in the SQLMM standard is 0, whereas in JASPA the default value is -1. In the following example JASPA sets the ST_GeomCollection SRID to -1, instead of 0 (zero) as stated in SQL-MM. It it done to keep PostGIS compatibility.
SELECT ST_SRID(ST_GeomCollFromText('GEOMETRYCOLLECTION(POINT (5 5))')); st_srid ---------1 (1 row)

4.2.2. Boolean
The return type of boolean methods (e.g. ST_IsValid, ST_IsClosed, ST_Crosses ...) in JASPA differs from the spatial specifications. SQL/MM JASPA for PostgreSQL JASPA for H2 Returns 1 if TRUE, 0 if FALSE or NULL Returns "t" if TRUE, "f" if FALSE, null if the Geometry is NULL. Returns "TRUE" if TRUE, "FALSE" if FALSE, null if the Geometry is NULL.

(1) SELECT ST_IsValid(ST_GeomFromText('POINT (0 0 )')); --JASPA for PostgreSQL st_isvalid -----------t (1 row) --JASPA for H2 TRUE (2) SELECT ST_IsClosed(ST_GeomFromText('POINT EMPTY')); --JASPA for PostgreSQL st_isclosed ------------(1 row) --JASPA for H2 null

26

Chapter 5. Spatial Data


5.1. Geometries
5.1.1. Types of Geometries
Spatial Data is stored in columns with the Geometry data type. The Geometry data type itself is an abstract (noninstantiable) class. It is the root class of the Geometry Type Hierarchy. The geometry hierarchy is defined by the OGC document "OpenGIS Simple Features Specification for SQL". The following figure shows the hierarchy of the Geometry data type and its subtypes.

Figure 5.1. Geometry Type Hierarchy Diagram

Not instantiable types in JASPA are highlighted in blue, these include Geometry, Curve, Surface, MultiSurface and MultiCurve. No constructor functions are defined for these types. Seven members of the hierarchy are instantiable (Point, LineString, Polygon, GeometryCollection, MultiPoint, MultiLineString, and MultiPolygon). So, it is possible to create objects in these instantiable types. The standard SQL-MM adds CircularString, CompoundCurve and CurvePolygon types. The new types extend the OGC geometry class hierarchy with circular arcs as curves and surfaces that have circular arcs as their boundary. JASPA doesn't support these new types, nonetheless PostGIS does in some functions. A summary of the instantiable geometry subtypes and their descriptions is listed in the table below.

Geometry Subtypes
Geometry Subtype Point LineString Polygon MultiPoint MultiLineString MultiPolygon Description A 0-dimensional geometry. It represents a single location in coordinate space. A 1-dimensional geometry. It is a Curve with linear interpolation between points. A 2-dimensional geometry. It is defined by its exterior bounding ring and zero or more interior rings. A 0-dimensional geometry. It represents a collection of Points. A 1-dimensional geometry. It represents a collection of LineStrings. A 2-dimensional geometry. It represents a collection of Polygons.

27

Spatial Data

Geometry Subtype GeometryCollection

Description A 0, 1 or 2-dimensional geometry. It is a collection of one or more geometries.

5.1.2. Properties 5.1.2.1. Coordinates dimension


The OGC specification SFS 1.0 (1999) and SFS 1.1.0 (2005) were based on 2D geometries. The SQL-MM specification extends the SFS spec by defining that features are in the two-dimensional coordinate space (x and y coordinates), and optionally they can have z and m coordinates. Z typically, but not necessarily, represent altitude. The M coordinate represents an arbitrary measurement. The ST_CoordDim function return information about the dimension of a geometry.

5.1.2.2. Geometric dimension


The dimension of a Geometry object is less than or equal to the coordinate dimension. The possible values are: 0 1 2 Point and MultiPoint LineString and MultiLineString. Polygon and MultiPolygon.

The ST_Dimension function return information about the dimension of a geometry.

5.1.2.3. Interior, Boundary, Exterior


Establishing spatial relationships between geometric objects is a major objective of a GIS. Spatial relationships are based on the definitions of the interior, boundary, and exterior of a geometry. The concepts of interior, boundary and exterior are well defined in topology, and are also defined by the OGC Simple Features for SQL.

Interior
The interior of a geometry is the set of points that are left when the boundary points are removed.

Boundary
The boundary of a geometry is a set of geometries of the next lower dimension.

Exterior
The exterior of a geometry is the set of points not in the interior or boundary. In the following table you can find the definition of the Interior, Boundary and Exterior for the different geometry types and also some examples.

Interior, Boundary and Exterior


Geometry types Point, MultiPoint LineString Interior Point itself Boundary Empty set Exterior Points not on the interior or boundary of the geometry. Points not on the interior or boundary of the geometry. Points not on the interior or boundary of the geometry.

Set of Points that are left Two End Points when the end points are removed.

28

Spatial Data

Geometry types LinearRing

Interior All the LinearRing

Boundary Empty set Empty set

Exterior Points not on the interior or boundary of the geometry. Points not on the interior or boundary of the geometry.

MultiLineString

Set of Points that are left Those Points that are in Points not on the interior or when the boundary points the boundaries of an odd boundary of the geometry. are removed. number of its element Curves Points not on the interior or boundary of the geometry.

Points not on the interior or boundary of the geometry.

Polygon

Points within the Rings

The set of Rings

Points not on the interior or boundary of the geometry.

MultiPolygon

Points within the Rings

The set of Rings of its Points not on the interior or Polygons. boundary of the geometry.

5.2. Functions Coordinate Dimension


In the definition of each function in the Chapter 9, Reference, you can find a table similar to the following one. It is used to indicate if the function supports 2D, 3D or measures.

Coordinate Dimensions
2D 3D M

Although in the table we indicate 3D, it should be strictly called 2.5 D as z values are recorded as an attribute for each data vertex (x,y). In some functions even though we put a check mark in the 3D or M cell, the support depends on the configuration of the input geometries. The examples below, of ST_Union, try to illustrate it:

29

Spatial Data

Example 1
In the next example the union of two partially overlaid polygons creates two new vertex with height zero, while the preexistent ones keep their original heights.

SELECT ST_AsEWKT(ST_Union(A,B)) from (SELECT ST_GeomFromText('POLYGON ((40 20 1, 40 100 2, 120 100 3, 120 20 4, 40 20 5))',25830) as A, ST_GeomFromText('POLYGON ((80 60 6, 80 130 7, 170 130 8, 170 60 9, 80 60 10))',25830) as B) as foo; -Result SRID=25830;POLYGON ((40 20 1, 40 100 2, 80 100 0, 80 130 7, 170 130 8, 170 60 9, 120 60 0, 120 20 4, 40 20 5))

Example 2
In the next example the union doesn't create new vertexes. The vertexes of the new Polygon inherit the heights of the orginal vertexes. In case of a spatially common vertex, it would inherit the height of the vertex of either the polygons, it won't be interpolated.

30

Spatial Data

A, B

ST_Union (A,B)

SELECT ST_AsEWKT(ST_Union(A,B)) from (SELECT ST_GeomFromText('POLYGON ((20 10 2, 20 60 4, 90 60 6, 90 10 -2, 20 10 2))') as A, ST_GeomFromText('POLYGON ((90 10 -2, 90 100 -4, 160 100 -6, 160 10 -8, 90 10 -2))') as B) as foo; --Result POLYGON ((20 10 2, 20 60 4, 90 60 6, 90 100 -4, 160 100 -6, 160 10 -8, 90 10 -2, 20 10 2))

Example 3
When an union of two consecutive lines is performed, the vertex height of the firtst line in the forward direction is assigned to the common vertex.

SELECT ST_AsEWKT(ST_Union(A,B)) from (SELECT ST_GeomFromText('LINESTRING (20 10 2, 40 30 4, 70 20 6, 90 40 8)') as A, ST_GeomFromText('LINESTRING (90 40 -5, 120 40 -10)') as B) as foo; --Result MULTILINESTRING ((20 10 2, 40 30 4, 70 20 6, 90 40 8), (90 40 8, 120 40 -10))

5.3. Spatial Relationships


The Dimensionally Extended- 9 Intersection Model (DE-9IM) is a mathematical approach to compare two geometries making pair-wise tests of the intersections between the Interiors, Boundaries and Exteriors of the two geometries, and finally it gives careful consideration to the dimension of the resulting intersections. The DE-9IM, was developed by Clementini et al., which extends the 9 Intersection Model of Egenhofer and Herring.

31

Spatial Data A DE-9IM matrix has the form:

DE-9IM
B A Interior Boundary Exterior Interior dim( I(a) I(b) ) dim( B(a) I(b) ) dim( E(a) I(b) ) Boundary dim( I(a) B(b) ) dim( B(a) B(b) ) dim( E(a) B(b) ) Exterior dim( I(a) E(b) ) dim( B(a) E(b) ) dim( E(a) E(b) )

Each intersection can result in geometries of different dimensions. For instance, a intersection of two polygons can result in a point, a line, another polygon or an empty set. The term "dim(a)" represents the dimension of the geometries intersection as specified by ST_Dimension. The possible pattern values are: 0 1 2 T F * An intersection must exist and its maximum dimension must be 0. (Point Intersection) An intersection must exist and its maximum dimension must be 1. (Line Intersection) An intersection must exist and its maximum dimension must be 2. (Area Intersection) An intersection must exist, the dimension doesn't care. An intersection must not exist. (Intersection is the empty set) It does not matter if an intersection exists or not.

The results returned by the DE-9IM are compared with a pattern matrix that represents the acceptable values for the DE-9IM. The functions that test spatial relationships are:

Spatial Relationships Functions


Spatial Relationships Functions ST_Contains ST_ContainsProperly ST_Covers ST_CoveredBy ST_Crosses [T** *** FF*] [T** FF* FF*] [T** *** FF*] or [*T* *** FF*] or [*** T** FF*] or [*** *T* FF*] [T*F **F ***] or [*TF **F ***] or [**F T*F ***] or [**F *TF ***] [T*T *** ***] (for P/L, P/A, and L/A situations) [T** *** T**] (for L/P, L/A, and A/L situations) [0** *** ***] (for L/L situations) [FF* FF* ***] [T*F **F FF*] [T** *** ***] or [*T* *** ***] or [*** T** ***] or [*** *T* ***] [T*T *** T**] (for P/P and A/A situations) [1*T *** T**] (for L/L situations) [FT* *** ***] or [F** T** ***] or [F** *T* ***] [T*F **F ***] DE-9IM pattern

ST_Disjoint ST_Equals ST_Intersects ST_Overlaps ST_Touches ST_Within

For example, the geometries of the following table have the intersection pattern matrix, [212 F11 FF2]. Therefore Geometry A Contains Geometry B, as they accomplish the ST_Contains pattern matrix [T** *** FF*].

32

Spatial Data

DE-9IM matrix example


B A Interior Boundary Exterior Interior 2 F F Boundary 1 1 F Exterior 2 1 2

The ST_Relate function returns the DE-9IM pattern matrix of two geometries, or it tests the DE-9IM of those geometries correspond to a particular pattern matrix.

5.4. Formats
JASPA supports different types of formats for spatial data. WKB and WKT are defined in the OGC Simple Feature Access specification. EWKB and EWKT are PostGIS formats that add a SRID to WKB and WKT formats.

5.4.1. WKB
The Well-known Binary Representation for Geometry provides a portable representation of a geometric object as a contiguous stream of bytes. You can use the ST_AsBinary function to convert geometries to their WKB representation. Inversely, ST_GeomFromWKB takes a WKB representation of a geometry and, optionally, a SRID as input parameters and returns the corresponding geometry.
binary WKB = ST_AsBinary(geometry); geometry = ST_GeometryFromWKB(binary WKB, SRID); geometry = ST_GeometryFromWKB(binary WKB);

The stream of bytes must be represented in a numeral system. PostgreSQL uses binary numeral system, whereas H2 uses hexadecimal representation.
SELECT ST_GeomfromText('POINT(0 0)'); --Result PostgreSQL: \011 \000\001\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000 --Result H2: 0920000100000000000000000000000000000000

Alternatively, you can use the function ST_AsHEXEWKB to obtain a geometry WKB representation in hexadecimal in both databases.
SELECT ST_AsHEXEWKB(ST_GeomFromText('POINT(1 1 1)',25830)); --Result PostgreSQL & H2: 01010000A0E6640000000000000000F03F000000000000F03F000000000000F03F SELECT ST_AsText('01010000A0E6640000000000000000F03F000000000000F03F000000000000F03F'); --Result POINT (1 1 1)

5.4.2. WKT
The Well-known Text Representation of Spatial Reference Systems provides a standard textual representation for spatial reference system information. Geometry Type Point Example
POINT (0 0 10)

Comment Point with Z coordinate

33

Spatial Data

Geometry Type LineString Polygon MultiPoint

Example
LINESTRING (1 1 2 5, 2 1 4 8, 2 2 6 10) POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1)) MULTIPOINT ((0 0), (1 1))

Comment LineString with Z and M coordinates Polygon MultiPoint

or
MULTIPOINT (0 0, 1 1)

MultiLineString MultiPolygon

MULTILINESTRING ((1 1, 2 1, 2 2), (2 3, 3 3, 3 2)) MULTIPOLYGON (((1 1, 1 3, 3 3, 3 1, 1 1), (1.5 2, 2 2.5, 2.5 2, 1.5 2)), ((4 3, 4 5, 6 5, 6 3, 4 3))) GEOMETRYCOLLECTION (POINT (1 1), LINESTRING (1 3, 2 2, 2 1))

MultiLineString MultiPolygon, first polygon with a hole

GeometryCollection

GeometryCollection composed of a Point and a LineString.

You can use the ST_AsText function to convert geometries to their WKT representation. Inversely, ST_GeomFromText takes a WKT representation of a geometry and, optionally, a SRID as input parameters and returns the corresponding geometry.
text WKT = ST_AsText(geometry); geometry = ST_GeomFromText(text WKT); geometry = ST_GeomFromText(text WKT, SRID);

5.4.3. EWKB
Extended Well-known Binary. This format embeds the SRID to the geometry. You can use the ST_AsEWKB function to convert geometries to their EWKB representation. Inversely, ST_GeomFromEWKB takes a EWKB representation of a geometry and returns the corresponding geometry.
binary EWKB = ST_AsEWKB(geometry); geometry = ST_GeomFromEWKB(binary EWKB);

5.4.4. EWKT
Extended Well-known Text Representation. This format embeds the SRID to the geometry. You can use the ST_AsEWKT function to convert geometries to their EWKT representation. Inversely, ST_GeomFromEWKT takes a EWKT representation of a geometry and returns the corresponding geometry.
text EWKT = ST_AsEWKT(geometry); geometry = ST_GeomFromEWKT(text EWKT);

Example
SRID=25830;POINT(719626 4369131 56.2)

5.4.5. GML
The Geography Markup Language (GML) is the XML grammar defined by the OGC to express geographical features. GML serves as a modeling language for geographic systems as well as an open interchange format for geographic transactions on the Internet. JASPA supports OGC GML standard 2.1.2. OGC GML standards can be found in http://www.opengeospatial.org/standards/gml

34

Spatial Data You can use the ST_AsGML function to convert geometries to their GML representation. Inversely, ST_GeomFromGML takes a GML representation of a geometry and returns the corresponding geometry.
text GML = ST_AsGML(geometry); geometry = ST_GeomFromGML(text GML);

Example
<gml:Point> <gml:coordinates> 1.0,1.0,1.0 </gml:coordinates> </gml:Point>

5.4.6. KML
Keyhole Markup Language (KML) is an XML language focused on geographic visualization. KML was developed for use with Google Earth. In 2008 KML Version 2.2 has been adopted as an OGC implementation standard, which can be found in http://www.opengeospatial.org/standards/kml/ KML uses 3D geographic coordinates: longitude, latitude and altitude. The longitude, latitude components are defined in WGS84. You can use the ST_AsKML function to convert geometries to their KML representation. Inversely, ST_GeomFromKML takes a KML representation of a geometry and returns the corresponding geometry.
text KML = ST_AsKML(geometry); geometry = ST_GeomFromKML(text KML);

Example
<kml:Polygon xmlns:kml="http://earth.google.com/kml/2.1"> <kml:outerBoundaryIs> <kml:LinearRing> <kml:coordinates> -5.850379847879675,43.35970362178223 -5.848336797975651,43.36161117272741 -5.850411866073801,43.36311451294508 -5.853216861450062,43.36175621008758 -5.850379847879675,43.35970362178223 </kml:coordinates> </kml:LinearRing> </kml:outerBoundaryIs> </kml:Polygon>

5.5. Metadata tables


A spatial database has associated metadata tables for describing the existence and properties of geometry columns. Each geometry column will be represented as a row in the GEOMETRY_COLUMNS metadata table. At the same time, every geometry column has associated a Spatial Reference System from the SPATIAL_REF_SYS metadata table. There is an auxiliary table _AVAILABLESRIDS for JASPA internal use which must not be deleted or manually edited.

5.5.1. Geometry Columns


The GEOMETRY_COLUMNS table consists of a row for each geometry column in the database. The columns of this table are:

GEOMETRY_COLUMNS table
FIELD TYPE NO NULL KEY PRIMARY DEFAULT NULL F_TABLE_CATALOGVARCHAR(256)

35

Spatial Data

FIELD F_TABLE_NAME

TYPE NO NO NO NO NO NO VARCHAR(256)

NULL

KEY PRIMARY PRIMARY PRIMARY

DEFAULT NULL NULL NULL NULL NULL NULL

F_TABLE_SCHEMA VARCHAR(256) F_GEOMETRY_COLUMN VARCHAR(256) COORD_DIMENSION INTEGER(10) SRID TYPE INTEGER(10) VARCHAR(30)

F_TABLE_CATALOG, F_TABLE_SCHEMA, F_TABLE_NAME


The fully qualified name of the feature table containing the geometry column. F_Table_Catalog field is unused in JASPA.

F_GEOMETRY_COLUMN
The name of the column in the feature table that is the geometry column.

COORD_DIMENSION
Code for the coordinate dimension. The coordinate_dimension must be an integer (2 for XY coordinates, 3 for XYZ or 4 for XYZM).

SRID
The ID of the spatial reference system used for the coordinate geometry in this table. It is a foreign key reference to the SPATIAL_REF_SYS table.

TYPE
The type must be an uppercase string corresponding to the geometry type (e.g, MULTIPOLYGON,LINESTRING).

5.5.2. Spatial Reference System


The SPATIAL_REF_SYS view stores information on each Spatial Reference System (SRS) in the database. It is prepopulated with SRS and EPSG values. The columns of this table are:

SPATIAL_REF_SYS view
FIELD SRID AUTH_NAME AUTH_SRID SRTEXT TYPE INTEGER(10) VARCHAR(4) INTEGER(10) VARCHAR KEY NULL NULL NULL NULL DEFAULT

SRID
Spatial Reference System Identifier. It constitutes a unique integer key for a Spatial Reference System within a database.

AUTH_NAME
Spatial Reference System Authority Name

AUTH_SRID
Authority Specific Spatial Reference System Identifier

36

Spatial Data

SRTEXT
Well-known Text description of the Spatial Reference System

5.6. Coordinate System


A spatial reference system, also referred to as a coordinate system, is a geographic (latitude-longitude), a projected (X,Y), or a geocentric (X,Y,Z) coordinate system.

5.6.1. WKT SRS


The well-known text representation of spatial reference systems provides a standard textual representation for spatial reference system information. The definition for the string representation of a coordinate system is as follows:
<coordinate system> = <projected cs> | <geographic cs> | <geocentric cs> <projected cs> = PROJCS[<name>, <geographic cs>, <projection>, {<parameter>,}* <linear unit>] <projection> = PROJECTION[<name>] <parameter> = PARAMETER[<name>, <value>] <value> = <number>

This WKT representation of an Spatial Reference System can be found in the SRTEXT column of the SPATIAL_REF_SYS view. As an example, geographic WGS84 is defined as: SRID 4326 AUTH_NAME EPSG 4326 AUTH_SRID SRTEXT GEOGCS["WGS 84", DATUM["World Geodetic System 1984", SPHEROID["WGS 84", 6378137.0, 298.257223563, AUTHORITY["EPSG","7030"]], AUTHORITY["EPSG","6326"]], PRIMEM["Greenwich", 0.0, AUTHORITY["EPSG","8901"]], UNIT["degree", 0.017453292519943295], AXIS["Geodetic latitude", NORTH], AXIS["Geodetic longitude", EAST], AUTHORITY["EPSG","4326"]]

EPSG codes and their WKT representation can be found in http://spatialreference.org/

5.6.2. Reprojection
The function ST_Transform is used to transform a Geometry to a specified spatial reference system. This reprojection is done by means of the GeoTools library. The GeoTools library is used to provide coordinate reprojection support within JASPA. It is done by the EPSG WKT Plugin which stores the SRS definitions in a Java properties file. The EPSG Geodetic Parameter Dataset is a structured dataset of Coordinate Reference Systems and transformations. Transformation between coordinate systems can be carried out by equation-based methods or by grid-based methods: Equation-based methods include Seven-parameter or Molodensky. A coordinate transformation can require and use the parameters of the Ellipsoids associated with the source and target coordinate reference systems, in addition to the parameters explicitly associated with the transformation.

37

Spatial Data Grid-based methods allow you to model the differences between the Coordinate Reference Systems and are potentially the most accurate method.

National Transformation version 2 (NTv2)


The NTv2 method uses a binary distortion Grid File to transform coordinates from one spatial reference system to another. This method is used for accurate datum shifts, instead of using coordinate transformations by parameters. GeoTools does not support NTv2, for this reason JASPA doesn't support it either. GeoTools is also used for the JASPA shp loader in order to read .prj files from shapefiles. For further information about GeoTools, refer to http://www.geotools.org/

5.6.3. WKT Spheroid


An Spheroid is defined by its Name, Semi-major axis, and Flattening.
SPHEROID["GRS_1980",6378137,298.257222101]

The following functions can use the WKT representation of an Spheroid as input parameter. Function ST_Distance_Spheroid ST_Length2D_Spheroid ST_Length3D_Spheroid

5.7. Spatial indexes


Queries on tables with many registers can be slowed down. To improve performance, it is advisable to create an index for your most queried fields, and besides it may be necessary to create spatial indexes. An index allows the database server to find and retrieve specific rows much faster than it could do without an index. Without an index, when a table is queried, the system access to each table row sequentially. An index has disadvantages as well. First, every index increases the amount of storage used, and second, the index must be updated when the data are altered. PostgreSQL 8.4 supports 4 index types: B-tree, Hash, GiST and GIN. GiST index (Generalized Search Trees) is the most suitable index for querying spatial data. This operator classes two-dimensional geometric data as overlapping, or as inside or as at one side. JASPA for PostgreSQL make use of GiST indexes combined with minimum bounding rectangles (also known as bounding boxes) of the geometries. The use of bounding boxes is commonly called R-tree index. Please note that JASPA for H2 database currently doesn't support spatial indexes. This section refers only to PostgreSQL database.

5.7.1. Creating spatial indexes


To create an index use the CREATE INDEX command.
CREATE INDEX <index_name> ON <table_name> USING GIST (ST_PGBOX(<geometry_column_name>));

To remove an index, use the DROP INDEX command.


DROP INDEX <index_name>;

Indexes can be added to and removed from tables at any time. Once an index is created, it is advisable running VACCUM ANALIZE command to rebuild table statistics and calculate the maximum and minimum values. After this, no further intervention is required: the system will update the index when the table is modified.

38

Spatial Data

VACUUM ANALYZE [table_name] ([geometry_column_name]);

The following is an example of creating an index, updating statistics and dropping the index.
CREATE TABLE myspatialtable (id serial); SELECT AddGeometryColumn ('myspatialtable','geom',4326,'POINT',3); Table myspatialtable Column | Type | --------+---------| id | integer | geom | bytea | CREATE INDEX myspatialtable_geom_idx ON myspatialtable USING GIST (ST_PGBOX(geom)); VACUUM ANALYZE myspatialtable(geom); DROP INDEX myspatialtable_geom_idx;

If the name of the geometry column is in upper-case you must call that column with double quotation marks, as shown in the following example:
CREATE TABLE myspatialtable (id serial); SELECT AddGeometryColumn ('myspatialtable','Geom',4326,'POINT',3); CREATE INDEX myspatialtable_geom_idx ON myspatialtable USING GIST (ST_PGBOX("Geom"));

5.7.2. Functions using spatial indexes


Spatial indexes are used in spatial relationships queries. Once the index is built, the system uses it automatically. To avoid index use, call the functions using the prefix _. In particular JASPA use spatial indexes in the following functions:

Functions using spatial indexes


Functions using spatial indexes ST_Contains ST_ContainsProperly ST_Covers ST_CoveredBy ST_Crosses ST_DWithin ST_Intersect ST_Intersects ST_Overlaps ST_Touches ST_Within Functions not using indexes _ST_Contains _ST_ContainsProperly _ST_Covers _ST_CoveredBy _ST_Crosses _ST_DWithin _ST_Intersect _ST_Intersects _ST_Overlaps _ST_Touches _ST_Within

PostgreSQL includes automatically GiST indexes for these spatial operators:

Spatial operators
Operators << Is strictly left of? Meaning

39

Spatial Data

Operators &< &> >> <<| &<| |&> |>> @> <@ ~= &&

Meaning Does not extend to the right of? Does not extend to the left of? Is strictly right of? Is strictly left of? Does not extend above? Does not extend below? Is strictly above? Contains? Contained in or on? Same as? Overlaps?

5.7.3. Examples
The following query would use a spatial index (if it had been created before)
--Find all restaurants within 1 kilometer of the hotels SELECT r.name,h.name FROM restaurant as r,hotel as h WHERE ST_DWithin(r.geom,h.geom,1000);

To avoid the index usage:


SELECT r.name,h.name FROM restaurant as r,hotel as h WHERE _ST_DWithin(r.geom,h.geom,1000);

5.8. Connectors
There are a large number of software products that could use JASPA as spatial database. Any help to develop the JASPA connectors to other third party software will be appreciated. Specially we stand out connectors to servers (Geoserver...), GIS software programs (gvSIG, Quantum GIS, Kosmo, uDig ...) or GIS tools (GeoTools, OGR...).

5.8.1. Mapserver connector (libpq)


Libpq is the C application programmer's interface to PostgreSQL. It is a set of library functions that allow client programs to pass queries to the PostgreSQL backend server and to receive the results of these queries. Mapserver accesses to JASPA for PostgreSQL data using libpq and SQL sentences which are supported by JASPA thanks to its high level of Postgis compatibility. http://mapserver.org/input/vector/postgis.html

Configure MapServer
The CONNECTION parameter is used to specify the parameters to connect to the database. CONNECTION parameters can be in any order. Most are optional. The CONNECTIONTYPE parameter must be set to POSTGIS, dbname is required, user is required, host defaults to localhost, port defaults to 5432 (the standard port for PostgreSQL). The DATA parameter is used to specify the data used to draw the map.
DATA [geometry_column] FROM [table_name|sql_subquery] USING UNIQUE [unique_key] USING srid=[spatial_reference_id]

The using unique and using srid= clauses are optional, but using them improves performance.

40

Spatial Data

CONNECTIONTYPE POSTGIS CONNECTION "host=yourhostname dbname=yourdatabasename user=yourdbusername password=yourdbpassword port=yourpgport" DATA "geometrycolumn from yourtablename using gid"

Mapfile example
LAYER NAME "soils" CONNECTIONTYPE postgis CONNECTION "user=postgres password=postgrespg dbname=tutorial host=localhost" DATA "geom from soils using unique gid" STATUS ON TYPE POLYGON GROUP CARTOINICIAL FILTER "area(geom) > 10000 and soil_code >= 1" CLASS NAME EXPRESSION COLOR OUTLINECOLOR END CLASS NAME EXPRESSION COLOR OUTLINECOLOR END END

"Disponibilidad optima" ([soil_code] = 3) 164 164 164 255 255 255

"Disponibilidad menor" ([soil_code] = 1 or [soil_code] = 2) 192 192 192 255 255 255

Mapserver uses the && operator to limit the search of geometries to a smaller area. Mapserver sends a query to JASPA similar to this one:
SELECT asbinary(force_collection(force_2d(geom)),'NDR'), gid::text FROM suelos WHERE geom && setSRID('BOX3D(4000 4500, 6100 7250)'::BOX3D, find_srid('','soils','geom') )'

5.8.2. gvSIG 1.11


Enable Jaspa for gvSIG 1.11:

41

Spatial Data Copy the patch file "gvsigpatch.zip" into the bin directory of gvSIG installation. -> ... / .../gvsiginstallation/bin Unpack in same directory. Overwrite if it asks. Check that when the gvsigpatch.zip is descompressed, it does not create any folder as gvSIG(2).

To connect to Jaspa, we must choose as Driver: "PostGIS JDBC Driver":

gvSIG does not support editing simple geometries like LineString, Points or Polygons.

5.8.3. Kosmo
Enable Jaspa for Kosmo 2.0.1: Install Kosmo 2.0.1. Download the Jaspa patch "saigjaspa.jar" and rename it as "saig.jar". In the folder bin of your Kosmo distribution, replace the file saig.jar for the file you just downloaded.

42

Spatial Data To connect to Jaspa, we must choose as Database Type: "PostGIS":

43

Chapter 6. Topology
6.1. Introduction
Jaspa implements a rule-based topology based on restrictions. The topological model is two-dimensional. A topological model consists of layers, and rules to be met by layers. To add and remove those elements is necessary to use Section 6.2, Commands. The order to use the commands can be found in Section 6.3, Steps to create and validate a topology model. Topological rules can be applied to a subselection of a layer rather than the full layer. Refer to Section 6.4, Subtypes for further information. The rules can be applied to a single layer (e.g. "Must be valid", "Must not be duplicated"), or between two layers (e.g. "Must be coincident with ","Must be inside"). Section 6.6, Topology Rules includes a description and examples of all Jaspa topological rules. In this version Jaspa incorporates an experimental cluster tolerance. This is set by the SNAP parameter, it should not be used to prevent geometric errors. By default it is disabled (SNAP false). Very large layers can cause an out of memory exception. This issue can be solved by setting the TRANSACTION parameter to false. See Section 6.3.10, Change the transaction mode for further information.

6.2. Commands
SELECT COMMAND(' ');
//TOPOLOGY COMMANDS: CREATE TOPOLOGY toponame DROP TOPOLOGY toponame DROP TOPOLOGY FULL //Layer ADD LAYER schema.name TO ADD LAYER schema.name TO ADD LAYER schema.name TO REMOVE LAYER schema.name

toponame toponame TOLERANCE toleranceUnits toponame [TOLERANCE toleranceUnits] [SNAP True / False] FROM toponame

ALTER LAYER layername ON toponame [TOLERANCE tolerance] [SNAP true/false] //Rules ADD RULE rulename TO toponame USING table1,table2 [TOLERANCE tolerance] [ATTREXP12 atrexp] REMOVE RULE rulenumber FROM toponame //Validate VALIDATE RULE numberRule ON toponame [FULL | UPDATE] VALIDATE TOPOLOGY toponame [FULL | UPDATE] VALIDATE LAYER layer ON toponame [FULL | UPDATE] VALIDATE LAYER layer [FULL | UPDATE] //Show SHOW TOPOLOGIES SHOW LAYERS ON toponame SHOW RULES ON toponame SHOW RULE number ON toponame //Transaction SET TOPOLOGY_TRANSACTION [TRUE | FALSE <password>];

6.2.1. Examples
Example

44

Topology

SELECT command ('create topology t1'); SELECT command ('ADD layer viarialin TO t1 tolerance 0.01'); //Default tolerance 0.001 SELECT command ('ADD layer viariapol TO t1'); --snapping rules SELECT command ('ADD RULE mbs TO t1 using viarialin'); SELECT command ('ADD RULE mbs TO t1 using viariapol'); SELECT command ('ADD RULE mbsw TO t1 using viarialin,viariapol'); SELECT command ('ADD RULE mbsw TO t1 using viariapol,viarialin'); --other rules SELECT command ('ADD RULE mnhd TO t1 using viarialin searchwindow 10'); SELECT command ('ADD RULE mbcbbol TO t1 using viarialin,viariapol attrexp1 {[TABLE1].componen1d like ''B%''}'); SELECT command ('ADD RULE mno TO t1 using viariapol');

6.3. Steps to create and validate a topology model


The process to build a Jaspa topological model constist on creating the model first, second add layers to the model, third add the rules to be satisfied by the layers, and finally validate some rules, some layers or the whole topological model. With the SHOW commands you can display the rules and layers of a topological model, or obtain information about the topological models of a database. Finally, with the REMOVE commands, you can delete rules, layers, a full topological model or even all topological models.

6.3.1. Create a topology model


SELECT COMMAND ('CREATE TOPOLOGY <topologyModelName>');
select command('create topology topo1') Result: "The layers metadata table for the topology topo1 have been created"

Jaspa automatically creates the topo schema in the database (if it still does not exist), and two metadata tables in that schema: layers_<topoName> rules_topoName The table layers_<topoName> stores information about the tables that are part of a topological model. Field schema_name table_name geom_column_name tolerance rank character varying character varying character varying double precision integer Type

The rank column at this version indicates whether to apply layer adjustment or not (values 0 or 1). By default, the system does not apply tolerance adjustment. In future releases this column will mark the hierarchy level for layers adjustment.

45

Topology The table rules_<topoName> stores information about the rules that are part of a topological model. Field gid rule schema1_name table1_name geom_column1_name schema2_name table2_name geom_column2_name tolerance searchwindow lastupdate1 lastupdate2 notvalid attrexp1 attrexp12 serial character varying character varying character varying character varying character varying character varying character varying double precision double precision integer integer integer character varying character varying Type

6.3.2. Add layers to the topology model


SELECT COMMAND ('ADD LAYER <layerSchema>.<layerName1> TO <topologyModelName>');
select command('add layer public.l1 TO topo1'); Result: "The layer public.l1.geom has been added to the topology topo1"

When you add a table to a topology it happens 3 things: 1. The metadata table layers_<topoName> is updated. 2. A temporal table <layerName>_topotmp is added for each layer added to the topological model. 3. A topotime field is added to each layer added to the topological model.

6.3.3. Add rules to the topology model


The SQL sentence to add a rule in which participates a single layer is: SELECT COMMAND ('ADD RULE <ruleShortName> <layerSchema>.<layerName1>'); If the topological rule uses two layers, the SQL sentence is: SELECT COMMAND ('ADD RULE <ruleShortName> <layerSchema>.<layerName1>,<layerSchema>.<layerName2>'); TO <topologyModelName> USING

TO

<topologyModelName>

USING

select command('add rule mbsp TO topo1 using l1'); Result: "GID=1 NAME=mbsp TABLE1=public.l1.geom TOLERANCE=0.0010 SEARCHWINDOW=0.1 ERRORS=0 ATTREXP1=null ATTREXP12=null | The topology rule has been added"

Internally Jaspa updates the metadata table rules_<topoName>.

46

Topology

6.3.4. Validate a topology


There are four ways of validating a topology 1. Validate a rule: SELECT COMMAND ('VALIDATE RULE <numberRule> ON <topologyModelName> [FULL | UPDATE]');
Select command('validate rule 1 ON topo1'); --Result: The rule 1 in the topology topo1 has been validated. Errors [Before:0 After validating:1]

2. Validate fully a topological model SELECT COMMAND ('VALIDATE TOPOLOGY <topologyModelName>');


SELECT COMMAND('validate topology topo1'); --Result: The topology topo1 has been validated.

3. Validate a layer of a specific topological model SELECT COMMAND ('VALIDATE LAYER <layerName> ON <topologyModelName> [FULL/UPDATE]');
SELECT COMMAND('validate layer l1 ON topo1'); --Result: The topology topo1 has been validated.

4. Validate a layer in any topological model SELECT COMMAND ('VALIDATE LAYER <layerName> [FULL/UPDATE]');
SELECT COMMAND('validate layer l1 FULL'); --Result: The layer public.l1.geom has been validated.

Jaspa internally: 1. Updates the metadata table rules_<topoName>. 2. If a rule is validated for the first time, it creates an error table in the topo schema and inserts errors. The name of the error table is topo.r_<serialRuleNumber><topoName>_<LayerName1>_<RuleShortName>_<LayerName2>. Metadata tables (rules_<topoName>, layers_<topoName>), temporal tables (<layerName>_topotmp) or the temporal field topotime must not be updated manually or deleted to ensure proper operation of Jaspa topology.

6.3.5. Obtain information about a topological model


SELECT COMMAND ('SHOW TOPOLOGIES')
SELECT COMMAND ('SHOW TOPOLOGIES'); --Result: t1 |

SELECT COMMAND ('SHOW LAYERS ON toponame')


SELECT COMMAND ('SHOW LAYERS ON topo1'); --Result: public.l1.geom | 0.0010 |

SHOW RULES ON toponame

47

Topology

SELECT COMMAND ('SHOW RULES ON topo1'); --Result: GID=1 NAME=mbsp TABLE1=public.l1.geom TOLERANCE=0.0010 SEARCHWINDOW=0.1 ERRORS=1 ATTREXP1=null ATTREXP12=null |

SHOW RULE number IN toponame


SELECT COMMAND ('SHOW LAYERS ON topo1'); --Result: public.l1.geom | 0.0010 |

6.3.6. Remove a rule


SELECT COMMAND ('REMOVE RULE <rulenumber> FROM <topologyModelName>')
SELECT COMMAND ('REMOVE RULE 1 FROM topo1'); --Result: The topology rule 1 and its asociated geometry error table has been deleted

6.3.7. Remove a layer


SELECT COMMAND ('REMOVE LAYER <layerSchema>.<layerName1> FROM <topologyModelName>')
SELECT COMMAND ('REMOVE LAYER l1 FROM topo1'); --Result: The layer 'public.l1.geom' has been removed from the topology t1

6.3.8. Alter a layer


ALTER LAYER layername ON toponame [TOLERANCE tolerance] [SNAP true/false] This command is useful to disable or enable cluster tolerance of a rule. It can also change the tolerance, but this Jaspa version only allows switching to smaller tolerances for new geometries.

6.3.9. Remove a topological model


Jaspa offers the possibility of eliminating all topological models or one in particular 1. Elimate every topological model SELECT COMMAND ('DROP TOPOLOGY FULL');
SELECT COMMAND ('DROP TOPOLOGY FULL'); --Result: The topology metadata structure has been deleted. Use CREATE TOPOLOGY in order to create it again.

2. Eliminate a particular topological model SELECT COMMAND ('DROP TOPOLOGY <topologyModelName>');


SELECT COMMAND ('DROP TOPOLOGY topo1'); --Result: The topology metadata tables for the topology t1 have been deleted

6.3.10. Change the transaction mode


By default the transaction mode is set to true. If the layers contain a lot of topological errors can cause an out of memory exception. This can be avoided setting the transaction mode to false. If the transaction mode is set to false, the password must also be indicated. 1. Set transaction mode to FALSE SELECT COMMAND ('SET TOPOLOGY_TRANSACTION false <password>');

48

Topology

SELECT COMMAND ('SET TOPOLOGY_TRANSACTION false mypassword'); --Result: command ------------------------------------------------Topology transaction mode has been set to false (1 row)

2. Set transaction mode to TRUE SELECT COMMAND ('SET TOPOLOGY_TRANSACTION true');


SELECT COMMAND ('SET TOPOLOGY_TRANSACTION true'); --Result: command -----------------------------------------------Topology transaction mode has been set to true (1 row)

6.4. Subtypes
Jaspa allows the use of sub-selections in the application of topological rules. This can be done using the sub-selection parameter (ATTREXP12) when a rule is added. If the subselection is appliable only to the first layer in a rule, the parameter ATTREP1 must be used. If the subselection is appliable only to the second layer in a rule or to a combination of the first and second layer, the parameter ATTREP12 must be used. Let's illustrate this with some examples.

6.4.1. Examples
Imagine you want to check that polygons contain one point, but this requirement is only applicable to part of the layer. The rule to use is [Polygon] must contain one [Point].

table_a Gid 1 2 3 4 a1 a2 a3 a4 Type Geom POLYGON((-2 5,-2 9,2 9,2 9,2 5,2 5,-2 5)) POLYGON((3.5 9,3.5 12.3,5.3 12.3,5.3 9,3.5 9)) POLYGON((-2 9,-2 12.3,3.5 12.3,3.5 9,-2 9)) POLYGON((2 5,2 9,5.3 9,5.3 5,2 5))

49

Topology

Gid 5 table_b Gid 1 2 3 4 5 1 2 3 4 5 b

Type

Geom POLYGON((7 8,7 11,9 11,9 8,7 8))

Type POINT(0 11) POINT(4 5) POINT(-1 6) POINT(1 4) POINT(2 10)

Geom

Create the tables and populate date into them:


CREATE TABLE table_a(gid SELECT AddGeometryColumn INSERT INTO table_a(type 5,-2 5))')); INSERT INTO table_a(type 12.3,5.3 9,3.5 9))')); INSERT INTO table_a(type 9,-2 9))')); INSERT INTO table_a(type 5))')); INSERT INTO table_a(type 8))')); CREATE SELECT INSERT INSERT INSERT INSERT INSERT TABLE table_b(gid AddGeometryColumn INTO table_b(type INTO table_b(type INTO table_b(type INTO table_b(type INTO table_b(type serial PRIMARY KEY,type VARCHAR); ('table_a','geom',-1,'POLYGON',2); ,geom) VALUES ('a1',ST_GeomfromText('POLYGON((-2 5,-2 9,2 9,2 9,2 5,2 ,geom) VALUES ('a2',ST_GeomfromText('POLYGON((3.5 9,3.5 12.3,5.3 ,geom) VALUES ('a3',ST_GeomfromText('POLYGON((-2 9,-2 12.3,3.5 12.3,3.5 ,geom) VALUES ('a4',ST_GeomfromText('POLYGON((2 5,2 9,5.3 9,5.3 5,2 ,geom) VALUES ('b',ST_GeomfromText('POLYGON((7 8,7 11,9 11,9 8,7

serial PRIMARY KEY, type int); ('table_b','geom',-1,'POINT',2); ,geom) VALUES (1,ST_GeomfromText('POINT(0 11)')); ,geom) VALUES (2,ST_GeomfromText('POINT(4 5)')); ,geom) VALUES (3,ST_GeomfromText('POINT(-1 6)')); ,geom) VALUES (4,ST_GeomfromText('POINT(1 4)')); ,geom) VALUES (5,ST_GeomfromText('POINT(2 10)'));

Create the topology set and add the geometry tables to it:
SELECT COMMAND ('create topology t1'); SELECT COMMAND('ADD layer table_a TO t1'); SELECT COMMAND('ADD layer table_b TO t1');

6.4.2. Restriction on first layer


Polygons whose type is like a, must contain one point. The rule to use is [Polygon] must contain one [Point]. In this case, as the restriction only applies to first layer the sub-selection parameter to use is ATTREP1.

50

Topology

Fields labeled = type Add the rule:


SELECT COMMAND('ADD RULE mcop TO t1 using table_a,table_b attrexp1 {[TABLE1].type like ''a%''}');

Validate
SELECT COMMAND ('VALIDATE RULE 1 on t1');

6.4.3. Restriction on second layer


Polygons must contain one point whose type is lower than 3

Fields labeled = type Add the rule:


SELECT COMMAND('ADD RULE mcop TO t1 using table_a,table_b attrexp12 {[TABLE2].type < 3}');

6.4.4. Restriction on first and second layer


Polygons whose type is like a must contain one point whose type is lower than 3

Fields labeled = type Add the rule:


SELECT COMMAND('ADD RULE mcop TO t1 using table_a,table_b attrexp1 {[TABLE1].type like ''a%''} attrexp12 {[TABLE2].type < 3}');

51

Topology

6.4.5. Restriction that involves first and second layer at the same time.
Polygons must contain one point whose gid field is higher than the polygon's gid.

Fields labeled = gid Add the rule:


SELECT COMMAND('ADD RULE mcop TO t1 using table_a,table_b attrexp12 {[TABLE1].gid < [TABLE2].gid}');

6.5. Tolerance
6.5.1. Cluster Tolerance
The cluster tolerence is the minimum distance between coordinates to be considered identical. If two lines are at a distance of 5 maps units, and the tolerance is set to 10 map units, the vatidation process will consider that the lines are coincident. Cluster tolerance should be set according to the layer accuracy. It is set with the tolerance parameter when a layer is added to the topology model. ADD LAYER schema.name TO toponame [TOLERANCE toleranceUnits] [SNAP True / False] If this tolerance is active (Snap True) vertices or edges are snapped to become coincident. If it not specified, the default value 0.001 map units is used. The cluster tolerance is also used in the rules with tolerance _wt. (See next section). This parameter is stored in the metadata table layers_<topoName>.
ADD layer <layerName> to <topologyName> tolerance 0.01

Default value 0.001:


ADD layer <layerName> to <topologyName>

6.5.2. Rules with tolerance (_wt)


Some rules use a snapping tolerance, their name finish with the "_WT" suffix. For instance: Must be disjoint with tolerance (mbd_wt).
SELECT command('ADD RULE mbd_wt TO t1 using l16 tolerance 0.1');

If the user does not indicate the tolerance parameter, the layer tolerance is used.
SELECT command('ADD RULE mbd_wt ON t1 using l16');

52

Topology The following example applies the rule "must be disjoint with tolerance" (mbd_wt). We can see that the points on the lower left corner 1 and 3, are disjoint. But if we consider the cluster tolerance they should be considered as coincident and so are marked as errors. Note that the multipoint 3 is composed by two points, and both are marked as errors. Gid 1 2 3 3 Geom MULTIPOINT ((7 13)) MULTIPOINT ((12 17)) MULTIPOINT ((8 12), (7 18)) MULTIPOINT ((12.5 12))

6.5.3. Search Window


This parameter is used for the rule must not have dangles. It is used to indicate the maximum distance to search a geometry near to the dangle.
SELECT command('ADD RULE mnhd TO t1 using <layer> searchwindwow 10');

If the search window parameter is not specified, it uses as default value 100 times the layer tolerance.
SELECT command('ADD RULE mnhd TO t1 using <layer>');

The error layer has a distance field that indicates the distance to the nearest geometry (If there is not a geometry within the search window, it indicates the parameter search window). The gid of the nearest geometry is indicated in the field geomgid2. SearchWindow = 10 Gid 1 2 3 Exc. false false false gid gid dist. geom1 geom2 1 2 2 3 3 3 1.1 0.7 0.2

SearchWindow = 0.1

Gid 1 2 3

Exc. false false false

gid gid dist. geom1 geom2 1 2 2 Null 3 3 0.1 0.7 0.2

6.6. Topology Rules


This section presents a comprehensive list of the available topology rules.

53

Topology

6.6.1. Summary of rules


Geometry Point mbsp mbd mbd_wt mnbd mnbd_wt mnhrp Point + Point mbdw mbdw_wt mbcw mbcw_wt Point + Line Point + Polygon mbi mbpi mbi mbpi mbcbbo Line mbsp mnsi mnioti mnti mni mbd mbd_wt mnbd mno mnhd mnhd_wt mnhp mnhp_wt mnhrp mbc2d_wt mbc3d_wt Alias Rule Must be single Part Must be disjoint Must be disjoint with tolerance Must not be duplicated Must not be duplicated with tolerance Must not have repeated points Must be disjoint with Must be disjoint with, with tolerance Must be coincident with Must be coincident with, with tolerance Must be inside Must be properly inside Must be inside Must be properly inside Must be covered by boundary of Must be single Part Must not self intersect Must not intersect or touch interior Must not touch interior Must not intersect Must be disjoint Must be disjoint, with tolerance Must not be duplicated Must not overlap Must not have dangles Must not have dangles, with tolerance Must not have pseudonodes Must not have pseudonodes, with tolerance Must not have repeated points Must be connected 2D, with tolerance Must be connected 3D, with tolerance

54

Topology

Geometry Line + Line mniotiw mniw mntiw mbdw mbdw_wt mnow mbi mbpi mbcbl mbc2dw_wt mbc3dw_wt mbccw_wt Line + Polygon mbi mbpi mbcbl mbcbbol mbcbbo mbccw_wt Polygon mbsp mbv mbd mbd_wt mnbd mno mnhg mnhrp Polygon + Point mcop mcpop mcp mcpp Polygon + Line Polygon + Polygon bmbcbl mbccw_wt mbdw

Alias

Rule Must not intersect or touch interior with Must not intersect with Must not touch interior with Must be disjoint with Must be disjoint with, with tolerance Must not overlap with Must be inside Must be properly inside Must be covered by layer Must be connected 2D with, with tolerance Must be connected 3D with, with tolerance Must be cross connected with, with tolerance Must be inside Must be properly inside Must be covered by layer Must be covered by boundary of layer Must be covered by boundary of Must be cross connected with, with tolerance Must be single Part Must be valid Must be disjoint Must be disjoint, with tolerance Must not be duplicated Must not overlap Must not have gaps Must not have repeated points Must contain one point Must contain properly one point Must contain points Must contain properly points Boundary must be covered by layer Must be cross connected with Must be disjoint with

55

Topology

Geometry mbdw_wt mnow mbi mbpi mbcbl bmbcbbol mbccw_wt

Alias

Rule Must be disjoint with Must not overlap with Must be inside Must be properly inside Must be covered by layer Boundary must be covered by boundary of layer Must be cross connected with, with tolerance

6.6.2. Summary of rules in a single layer


Point X X X X X X X X X Line X X X X Polygon mbsp mbd mbd_wt mnbd mnbd_wt Alias Rule Must be single Part Must be disjoint Must be disjoint with tolerance Must not be duplicated Must not be duplicated with tolerance Must not have repeated points Must not self intersect Must not intersect or touch interior Must not touch interior Must not intersect Must not overlap Must not have dangles Must not have dangles, with tolerance Must not have pseudonodes Must not have pseudonodes, with tolerance Must be valid

X X X X X X X X

mnhrp mnsi mnioti mnti mni

mno mnhd mnhd_wt

X X

mnhp mnhp_wt

mbv

56

Topology

Point X X

Line X

Polygon mnhg

Alias mbc2d_wt mbc3d_wt

Rule Must not have gaps Must be connected 2d, with tolerance Must be connected 3d, with tolerance

6.6.3. Summary of rules between two layers


Point Point + Point Point + Point Point + Point Point + Point Point + Line Point + Polygon Point + Line Point + Polygon Point + Polygon Line + Line Line + Polygon Line + Line Line + Polygon Line + Polygon Line + Line Line + Line Line + Line Line + Line Line + Line Line + Polygon Line + Polygon Polygon + Point Polygon + Point Polygon + Point Polygon + Point Polygon + Line Polygon + Polygon Polygon + Polygon Polygon + Polygon Polygon + Polygon Line Line + Line Line + Line Polygon Polygon + Polygon Polygon + Polygon mbdw mbdw_wt mbcw mbcw_wt mbi mbpi mbcbbo mniotiw mniw mntiw mnow mbcbl mbcbbol mcop mcpop mcp mcpp bmbcbl Alias Rule Must be disjoint with Must be disjoint with, with tolerance Must be coincident with Must be coincident with, with tolerance Must be inside Must be properly inside Must be covered by boundary of Must not intersect or touch interior with Must not intersect with Must not touch interior with Must not overlap with Must be covered by layer Must be covered by boundary of layer Must contain one point Must contain properly one point Must contain points Must contain properly points Boundary must be covered by layer

57

Topology

Point

Line

Polygon Polygon + Polygon

Alias bmbcbbol

Rule Boundary must be covered by boundary of layer Must be connected 2D with Must be connected 3D with Must be cross connected with, with tolerance

Line + Line Line + Line Line + Line Line + Polygon Polygon + Line Polygon + Polygon

mbc2dw_wt mbc3dw_wt mbccw_wt

6.6.4. Point rules. Examples


Rule Must be single Part (mbsp) Input / Output Input: MultiPoint Output: MultiPoint Description Checks that multigeometries have only one part. Any geometry with more than one part is an error.
MULTIPOINT ((50 MULTIPOINT ((50 60), (90 60), (70 60), (90 60), (70 30)) 30)) MULTIPOINT ((120 90)) MULTIPOINT ((70 100))

Example

Must be disjoint (mbd)

Input: Point Features A point must not coincide with other Output: MultiPoint points of its layer. Errors are created when points interserct. Input: Point Features A point must not coincide with other Output: MultiPoint points of its layer.

Must be disjoint (mbd_wt) Tolerance version

Must not be duplicated (mnbd)

Input: All Output: Same as input

A Geometry must not be spatially equal to another Geometry. (ST_Equals) Note that this method computes topologically

POINT (10 10) POINT (10.08 10) POINT (10 10)

Error POINT (10 10)

58

Topology

Rule

Input / Output

Description equality, not structural or vertexwise equality

Example

Must not be duplicated (mnbd_wt) Tolerance version Must not have repeated points (mnhrp)

Input: Point Output: Point

A point must not be spatially equal or nearly equal (tolerance)

POINT (10 10) POINT (10.08 10) POINT (12 12) Tolerance 0.1 MULTIPOINT ((50 50), (90 60), (50 50))

Error POINT (10 10)

Input: Point Features A vertex must be captured just once. Output: MultiPoint

MULTIPOINT ((50 50))

6.6.5. Point + Point rules. Examples


Rule Input / Output Description A point must not coincide with other points of another layer. Errors are the original non disjoint points. A point must not coincide with other points of its layer. Errors consist of the original non disjoint geometries. Example Must be disjoint with Input 1: Point (mbdw) Features Input 2: Point Features Output: Point Features Must be disjoint with Input 1: Point (mbdw_wt) Features Tolerance version Input 2: Point Features Output: MultiPoint

Must be coincident with (mbcw)

Must be coincident with (mbcw_wt) Tolerance

Input 1: Point Features (just 1 point) Input 2: Point Features Output: Point Features Input 1: Point Features (just 1 point) Input 2: Point Features Output: Point Features

Checks that points of one layer are exactly coincident with points in another layer.

Checks that points of one layer are coincident with points in another layer. Points do not need to be exactly coincident, they can be as close together as the tolerance indicates. Errors consist of the disjoint points.

59

Topology

6.6.6. Point +Line rules. Examples


Rule Input / Output Description A point must be inside a line from another layer. Points can lie at endpoints of a line. A point must be properly inside a line from another layer. Points do not lie endpoints of a line. Errors consist of points that do not lie completely in the interior of a line from another layer. Example

Must be inside (mbi) Input 1: Point Features Input 2: Line Features Output: Point Features Must be properly inside (mbpi) Input 1: Point Features Input 2: Line Features Output: Point Features

6.6.7. Point +Polygon rules. Examples


Rule Input / Output Description A point must be inside a polygon from another layer. Points can lie at edges of polygons. A point must be properly inside of a polygon from another layer. Points do not fall on polygon boundaries. Errors consist of points that do not lie completely in the interior of a polygon. A point must be covered by the boundary of an area layer. Requires that points lie on edge of polygons. Example

Must be inside (mbi) Input 1: Point Features Input 2: Polygon Features Output:Point Features Must be properly inside (mbpi) Input 1: Point Features Input 2: Polygon Features Output:Point Features

Must be covered by boundary of (mbcbbo)

Input 1: Point Features Input 2: Polygon Features Output: Point Features

60

Topology

6.6.8. Line rules. Examples


Rule Must be single Part (mbsp) Input / Output Input: MultiLineString Output: MultiLineString Description Checks that multigeometries have only one part. Any geometry with more than one part is an error.
MULTILINESTRING MULTILINESTRING ((16 -8, 52 9, 93 ((15 13, 54 35), -9)) (101 12, 63 34)) MULTILINESTRING ((15 13, 54 35), (101 12, 63 34))

Example

Errors

Must not self intersect (mnsi)

Input: Line Features Output: MultiPoint

Checks that lines do not cross or overlap themselves. Errors consist of the points where a line intersects itself. Checks that lines do not overlap or interserct (except at endpoints). Errors consist of points if lines intersect, or lines if lines overlap. Checks that an endpoint of a line does not touch another line. Lines can overlap of intersect other lines. Checks that lines do not intersect. Errors consist of points or lines.

Must not intersect or touch interior (mnioti)

Input: Line Features Output: Table without geometry constraint. (Point or LineString)

Must not touch interior (mnti)

Input: Line Features Output: Point

Must not intersect (mni)

Input: Line Features Output: Table without geometry constraint. (Point or LineString) Input: Line Features Output: (Point or LineString geometries)

Must be disjoint (mbd)

A line must not have any part in common with other lines in the same layer. Line errors are created where lines overlap.

61

Topology

Rule

Input / Output

Description Points errors are created where lines cross or touch each other.

Example

Errors

Must be disjoint (mbd_wt) Tolerance version

Input: Line Features Output: MultType

A line must not have any part in common with other lines. Errors consist of the original non disjoint geometries. A Geometry must not be spatially equal to another Geometry. (ST_Equals) Note that this method computes topologically equality, not structural or vertexwise equality A line must not share its interior with lines of the same layer. Lines can cross or share vertices. Errors consist of the intersection of the interiors with linear dimension. Every line endpoint must be connected to a line. This rule detects undershoots and overshoots.
LINESTRING (30 40, Error 60 40) LINESTRING (30 40, LINESTRING (30 40, 60 40) 60 40) LINESTRING (40 50, 60 70)

Must not be duplicated (mnbd)

Input: All Output: Same as input

Must not overlap (mno)

Input 1: Line Features Output: MultiLineString

Must not have dangles (mnhd) SearchWindow

Input: Line Features Output: Point Features

Must not have dangles (mnhd_wt) Tolerance version

Input: Line Features Output: Point

Every line endpoint must be connected to a line. This rule detects undershoots and overshoots. Tolerance

62

Topology

Rule

Input / Output

Description Checks that lines connect at least 2 other lines at endpoints. Pseudones consist of nodes with 2 arcs. Nodes with 2 arcs. Requires that lines connect at al least 2 endpoints.

Example

Errors

Must not have Input: Line Features pseudonodes (mnhp) Output: Point

Must not have pseudonodes (mnhp_wt) Tolerance version

Input: Line Features Output: Point

Must not have repeated points (mnhrp) Must be connected 2d, with tolerance (mbc2d_wt)

Input: Line Features Output: MultiPoint Input: Line Features Output: Point

Checks that the vertices of a line are captured just once. Checks that lines that are closer than the tolerance distance are connected

LINESTRING (0 0 15, 10 10 25, 10 10 25, 20 10 35)

MULTIPOINT ((10 10))

Must be connected 3d, with tolerance (mbc3d_wt)

Input: Line Features Output: Point

Checks that lines that are closer than the tolerance distance are connected vertically

6.6.9. Line + Line rules. Examples


Rule Input / Output Description Checks that lines do not overlap or interserct lines of another layer (except at endpoints) Example

Must not intersect or Input 1: Line touch interior with Features (mniotiw) Input 2: Line Features Output: Table without geometry constraint. (Point or LineString)

63

Topology

Rule Must not intersect with (mniw)

Input / Output

Description Checks that Lines do not intersect with lines of another layer. Errors consist of points or lines.

Example

Input 1: Line Features Input 2: Line Features Output: Table without geometry constraint. (Point or LineString) Must not touch Input 1: Line interior with (mntiw) Features Input 2: Line Features Output: Point

Checks that an endpoint of a line does not touch another line of another layer. Lines can overlap of intersect other lines. Errors consist of points. A line must not have any part in common with lines of another layer. Line errors are created where lines overlap. Points errors are created where lines cross or touch each other. A line must not have any part in common with lines of another layer. Stores the original non disjoint geometries. A line must not share its interior with lines of another layer. Lines can cross or share vertices. Errors consist of the intersection of the interiors with linear dimension.

Must be disjoint with Input 1: Line (mbdw) Features Input 2: Line Features Output: Table without geometry constraint. (Point or LineString)

Must be disjoint with Input 1: Line (mbdw_wt) Features Tolerance version Input 2: Line Features Output: MultiLineString Must not overlap with (mnow) Input 1: Line Features Input 2: Line Features Output: MultiLineString

64

Topology

Rule

Input / Output

Description A line must be contained within the endpoints of a line from another layer.

Example

Must be inside (mbi) Input 1: Line Features Input 2: Line Features Output: Line Features Must be properly inside (mbpi) Input 1: Line Features Input 2: Line Features Output: Line Features

A line must be properly inside a line from another layer. Errors consists of lines that do not lie completely in the interior of a line from another layer. Checks that lines from one layer are covered by the lines of another layer.

Must be covered by layer (mbcbl)

Input 1: Line Features Input 2: Line Features Output: LineString Input: Line Features Output: Point

Must be connected 2d with, with tolerance (mbc2dw_wt)

Checks that lines from one layer that are closer than the tolerance distance to lines of another layer are connected

Must be connected 3d with, with tolerance (mbc3dw_wt)

Input: Line Features Output: Point

Checks that lines from one layer that are closer than the tolerance distance to lines of another layer are connected vertically Checks that lines from one layer that intersect with lines from another layer, are vertically coincident in the intersection points. Errors consist of the instersection points with different 3d coordinate.

Must be cross connected with (mbccw_wt) Tolerance version

Input 1: Line Features Input 2: Line Features Output: Point

65

Topology

6.6.10. Line + Polygon rules. Examples


Rule Input / Output Description A line must be inside a polygon from another layer. Example

Must be inside (mbi) Input 1: Line Features Input 2: Polygon Features Output: Line Features (input 1) Must be properly inside (mbpi) Input 1: Line Features Input 2: Polygon Features Output:LineString / MultiLineString

A line must be properly inside a polygon from another layer. Lines do not cross or share boundary with polygon geometries. Errors consists of lines that do not lie completely in the interior of a polygon. A line must be covered by an area layer.

Must be covered by layer (mbcbl)

Input 1: Line Features Input 2: Polygon Features Output: LineString Input 1: Line Features Input 2: Polygon Features Output: MultiLineString Input 1: Line Features Input 2: Polygon Features Output: Line Features Input 1: Line Features Input 2: Polygon Features Output: Point

Must be covered by boundary of layer (mbcbbol)

A line must be covered by the boundary of an area layer. Requires that lines lie on edge of polygons. Checks that Lines are covered by the boundary of polygon features.

Must be covered by boundary of (mbcbbo)

Must be cross connected with (mbccw_wt) Tolerance version

Checks that lines from one layer that intersect with polygons from another layer, are vertically coincident in the intersection points. Errors consist of the instersection points

(0.0 Z coordinate)

66

Topology

Rule

Input / Output

Description with different 3d coordinate.

Example

6.6.11. Polygon rules. Examples


Rule Must be single Part (mbsp) Input / Output Input: Multipolygon Output: Multipolygon Description Checks that multigeometries have only one part. Any geometry with more than one part is an error. Checks that Polygons are well formed. Returns the polygons that are invalid. Example

Must be valid (mbv)

Input: Polygon Features Output: Polygon Features

Must be disjoint (mbd)

Input: Polygon Features Output: Table without geometry constraint. (Point, LineString or Polygon geometries)

Must be disjoint (mbd_wt) Tolerance version

Input: Polygon Features Output: MultiPolygon

A polygon must not have any part in common with other polygons. Errors are created when polygons interserct. Errors can be polygons, lines or points. A polygon must not have any part in common with other polygons. Errors consist of the original non disjoint geometries. A Geometry must not be spatially equal to another Geometry. (ST_Equals) Note that this method computes topologically equality, not structural or vertexwise equality
POLYGON 40, 40 10 0)) POLYGON 40, 40 10 0)) POLYGON 50 20, 10, 50 ((10 0, 10 Error 40, 40 0, POLYGON ((10 0, 10 40, 40 40, 40 0, ((10 0, 10 10 0)) 40, 40 0, ((50 10, 70 20, 70 10))

Must not be duplicated (mnbd)

Input: All Output: Same as input

67

Topology

Rule Must not overlap (mno)

Input / Output Input: Polygon Features Output: MultiPolygon

Description A polygon must not share its interior with other polygons. But polygons can share lines or vertices. Errors consist of the intersection of the interiors with dimension 2. Polygons must form a continuous surface, without gaps. Exterior rings are always marked as errors. Checks that polygon vertices are captured just once.

Example

Must not have gaps (mnhg)

Input: Polygon Features Output: MultiLineString

Must not have repeated points (mnhrp)

Input: Polygon Features Output: MultiPoint

POLYGON ((21 15, 21 20, 27 20, 27 20, 27 15, 21 15))

MULTIPOINT ((27 20))

6.6.12. Polygon + Point rules. Examples


Rule Must contain one point (mcop) Input / Output Input 1: Polygon Features Input 2: Pointal Output: Polygon Features Input 1: Polygon Features Input 2: Pointal Output: Polygon Features Input 1: Polygon Features Input 2: Pointal Output: Polygon Features Input 1: Polygon Features Input 2: Pointal Output: Polygon Features Description Each polygon must have one point inside it. Points outside polygons are not errors. Each polygon must have one point inside it. Points outside polygons are not errors. Each polygon must have at least one point inside it. Points outside polygons are not errors. Each polygon must have at least one point properly inside it. Example

Must contain properly one point (mcpop)

Must contain points (mcp)

Must contain properly points (mcpp)

68

Topology

Rule

Input / Output

Description Points outside polygons are not errors.

Example

6.6.13. Polygon + Line rules. Examples


Rule Boundary must be covered by layer (bmbcbl) Input / Output Input 1: Polygon Features Input 2: Line Features Output: MultiLineString Input 1: Polygon Features Input 2: Line Features Output: Point Description Checks that each polygon boundary is covered by lines of another layer. Example

Must be cross connected with (mbccw_wt) Tolerance version

Checks that polygons from one layer that intersect with lines from another layer, are vertically coincident in the intersection points. (0.0 Z coordinate) Errors consist of the instersection points with different 3d coordinate.

6.6.14. Polygon + Polygon rules. Examples


Rule Input / Output Description A polygon must not have any part in common with polygons of another layer. Errors are created when polygons interserct. Errors can be polygons, lines or points. Stores the original non disjoint geometries. Example

Must be disjoint with Input 1: Polygon (mbdw) Features Input 2: Polygon Features Output:Table without geometry constraint. (Point or LineString)

Must be disjoint with Input 1: Polygon (mbdw_wt) Features Tolerance version Input 2: Polygon Features Output: MultiPolygon

69

Topology

Rule Must not overlap with (mnow)

Input / Output Input 1: Polygon Features Input 2: Polygon Features Output: MultiPolygon

Description A polygon must not share its interior with polygons of another layer. Polygons can share lines or vertices. Errors consist of the intersection of the interiors with polygonal dimension. A polygon must be inside a polygon from another layer.

Example

Must be inside (mbi) Input 1: Polygon Features Input 2: Polygon Features Output: Polygon Features (input 1) Must be properly inside (mbpi) Input 1: Polygon Features Input 2: Polygon Features Output: Polygon Features

Must be covered by layer (mbcbl)

Input 1: Polygon Features Input 2: Polygon Features Output: Polygon

A polygon must be properly inside a polygon from another layer. Errors consists of polygons that do not lie completely in the interior of a polygon from another layer. Checks that a Polygon in a layer is covered by polygons of another layer.

Boundary must be Input 1: Polygon covered by boundary Features of layer (bmbcbbol) Input 2: Polygon Features Output: MultiLineString Must be cross connected with (mbccw_wt) Tolerance version Input 1: Polygon Features Input 2: Polygon Features Output: Point

Checks that Polygons are covered by the boundary of polygon features of another layer. Checks that polygons from one layer that intersect with polygons from another layer, are vertically coincident in the intersection (0.0 Z coordinate) points. Errors consist of the instersection points

70

Topology

Rule

Input / Output

Description with different 3d coordinate.

Example

71

Chapter 7. Differences
7.1. Differences between JASPA and PostGIS
For the users acquainted with PostGIS, in the following sections the differences between JASPA and PostGIS are exposed.

7.1.1. Box Data Type


PostGIS has a set of box data types to manage the bounding box of a geometry. The set of box types includes the box2d, box3d and box3d_extent types. A box is composed of x_min, y_min, x_max and y_max coordinates. Those data types aren't OGC valid and they don't exist in JASPA. JASPA uses a standard geometry data type instead of using box types.

7.1.1.1. PostGIS Box Functions


In the table below, you can find the functions that use Box types in PostGIS and how JASPA handles them. JASPA geometry ST_Box2D (Geometry); PostGIS box2d Box2D (geometry); Description Returns a Polygon geometry representation of the twodimensional bounding box. Returns a Polygon geometry representation of the threedimensional bounding box (geometry, Expands the Polygon that represents the Bounding Box in all directions. (box2d, (box3d, Returns the minimum bounding box of the specified geometries, that is, a single rectangle that minimally encloses the geometries.

geometry ST_Box3D (Geometry);

box3d Box3D (geometry);

geometry ST_Expand (Geometry, geometry ST_Expand Expand_Units); Expand_Units); box2d ST_Expand units_to_expand); box3d ST_Expand units_to_expand); geometry (Geometry_Aggregate);

ST_Extent box3d ST_Extent (geometry_set);

geometry box3d ST_Extent3D (geometry set); Returns the minimum bounding box ST_Extent3D(Geometry_Aggregate); of the specified geometries. geometry ST_MakeBox2D (point, box2d ST_MakeBox2D Creates a Box2d defined by the lower point); (pointLowLeft, pointUpRight); left point and the upper right point. geometry ST_MakeBox3D (point, box3d ST_MakeBox3D Creates a Box3d defined by the lower point); (pointLowLeft, pointUpRight); left point and the upper right point. double ST_XMax (Geometry); double ST_XMin (Geometry); double ST_YMax (Geometry); double ST_YMin (Geometry); float ST_XMax (box3d); float ST_XMin (box3d); float ST_YMax (box3d); float ST_YMin (box3d); Returns the maximum X of the geometry bounding box. Returns the minimum X of the geometry bounding box. Returns the maximum Y of the geometry bounding box. Returns the minimum Y of the geometry bounding box.

72

Differences

JASPA double ST_ZMax (Geometry); double ST_ZMin (Geometry);

PostGIS float ST_ZMax (box3d); float ST_ZMin (box3d);

Description Returns the maximum Z of the geometry bounding box. Returns the minimum Z of the geometry bounding box.

7.1.1.2. Automatic Cast of PostGIS Box types


JASPA is able to read Boxes types but automatically converts them to geometry types.
SELECT ST_AsText(ST_GeomFromText('BOX(0 0,10 10)')); st_astext ----------------------------------------POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0)) (1 row) SELECT ST_AsText(ST_GeomFromText('BOX3D(0 0 -5,10 10 5)')); st_astext -----------------------------------------------------POLYGON ((0 0 -5, 0 10 5, 10 10 5, 10 0 -5, 0 0 -5)) (1 row) SELECT ST_Area(ST_GeomFromText('BOX(0 0,10 10)')); st_area --------100 (1 row)

7.1.1.3. Examples
The following example shows the different behaviour of JASPA and PostGIS when dealing with Boxes.

JASPA for PostgreSQL


SELECT ST_AsEWKT(ST_MakeBox2D(ST_PointFromText('POINT(0 0)'),ST_PointFromText('POINT(10 10)'))); --Result: POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0)) SELECT ST_MakeBox3D(ST_PointFromText('POINT(0 0 10 2)'),ST_PointFromText('POINT(10 10 10 4)')) As BB; bb ---------------------------------------------------\001\003\000\000\ ... 00\000\000\000\000\000\000\000 (1 row)

JASPA for H2
SELECT ST_AsEWKT(ST_MakeBox2D(ST_PointFromText('POINT(0 0)'),ST_PointFromText('POINT(10 10)'))); --Result: POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0)) SELECT ST_MakeBox3D(ST_PointFromText('POINT(0 0 10 2)'),ST_PointFromText('POINT(10 10 10 4)')) As BB; --Result: BB 0103000080 ... 000000

73

Differences

PostGIS
SELECT ST_AsEWKT(ST_MakeBox2D(ST_GeomFromEWKT('POINT(0 0)'),ST_GeomFromEWKT('POINT(10 10)'))); --Result: st_asewkt -----------------------------------POLYGON((0 0,0 10,10 10,10 0,0 0)) (1 row)

SELECT ST_MakeBox3D(ST_GeomFromEWKT('POINT(0 0 10 2)'),ST_GeomFromEWKT('POINT(10 10 10 4)')) As BB; bb -----------------------BOX3D(0 0 10,10 10 10) (1 row)

7.1.2. Coordinate dimensions


The OGC specifications SFS 1.0 (1999) and SFS 1.1.0 (2005) were 2D with no support for Z coordinate. The OGC 1.2.0 SFS specification, appeared in 2006, develops the previous specifications to support Z and M (measure) coordinates. ISO SQL-MM Part 3 also supports Z and M Coordinates.

7.1.2.1. Coordinate Space


We can find four coordinate spaces: XY: each point or vertex is identified by two coordinates (X,Y) XYZ: each point or vertex is identified by three coordinates (X,Y,Z) XYM: each point or vertex is identified by two coordinates and stores a Measure as well (X,Y,M) XYZM: each point or vertex is identified by three coordinates and stores a Measure as well (X,Y,Z,M) JASPA doesn't support XYM geometries, it automatically converts XYM geometries to XYZM setting Z coordinate to 0. Coordinate Space XY Example Result JASPA Result PostGIS
POINT(1 2)

SELECT ST_AsEWKT( POINT (1 2) ST_GeomFromEWKT('POINT(1 2)')) as ga; SELECT ST_AsEWKT( POINT(1 2 3) ST_GeomFromEWKT('POINT(1 2 3)')) as ga; SELECT ST_AsEWKT( POINT (1 2 0 4) ST_GeomFromEWKT('POINTM(1 2 4)')) as ga; SELECT ST_AsEWKT( POINT (1 2 3 4) ST_GeomFromEWKT('POINT(1 2 3 4)')) as ga;

XYZ

POINT(1 2 3)

XYM

POINTM(1 2 4)

XYZM

POINT(1 2 3 4)

7.1.2.2. Geometry Outputs


PostGIS define ST_AsText() and ST_AsBinary() functions that only output 2D geometries, as stated in OGC SFS 1.0. Unlike PostGIS, JASPA define these functions to support Z and M coordinates. Function ST_AsBinary 4D JASPA 2D PostGIS

74

Differences

Function ST_AsText ST_AsEWKB ST_AsEWKT 4D 4D + SRID 4D + SRID

JASPA 2D 4D + SRID 4D + SRID

PostGIS

JASPA
SELECT ST_AsEWKT(ST_GeomFromText('LINESTRING(-3.52 41.0 20,2.33 48.86 30)',4326)) as ga; --Result ga --------------------------------------------------SRID=4326;LINESTRING (-3.52 41 20, 2.33 48.86 30) (1 row)

SELECT ST_AsText(ST_GeomFromText('LINESTRING(-3.52 41.0 20,2.33 48.86 30)',4326)) as ga; --Result ga ----------------------------------------LINESTRING (-3.52 41 20, 2.33 48.86 30) (1 row)

PostGIS
SELECT ST_AsEWKT(ST_GeomFromText('LINESTRING(-3.52 41.0 20,2.33 48.86 30)',4326)) as ga; --Result WARNING: OGC WKT expected, EWKT provided - use GeomFromEWKT() for this ga ------------------------------------------------SRID=4326;LINESTRING(-3.52 41 20,2.33 48.86 30) (1 row) SELECT ST_AsText(ST_GeomFromText('LINESTRING(-3.52 41.0 20,2.33 48.86 30)',4326)) as ga; --Result WARNING: OGC WKT expected, EWKT provided - use GeomFromEWKT() for this ga --------------------------------LINESTRING(-3.52 41,2.33 48.86) (1 row)

7.1.2.3. Mixed Dimension Geometries


JASPA can handle with mix dimensionality in a geometry. JASPA would associate the coordinate dimension of the first point to the entire geometry. For it, JASPA will drop the unnecessary coordinates or will add zeros to the unknown coordinates. Keep in mind that every vertex in a geometry should have the same dimensionality. This is just a solution for an undesirable mistake. 1st Point Coordinate Space XY Example Result JASPA

SELECT GEOMETRYCOLLECTION (POINT (5 ST_Asewkt( ST_GeomFromText(' 5), GEOMETRYCOLLECTION( LINESTRING (0 0, 0 50) POINT (5 5), LINESTRING (0 0 5, 0 50))')); SELECT ST_Asewkt(ST_GeomFromText(' GEOMETRYCOLLECTION( POINT (5 5 10), LINESTRING (0 0, 0 50))')); GEOMETRYCOLLECTION (POINT (5 5 10), LINESTRING (0 0 0, 0 50 0))

XYZ

75

Differences

1st Point Coordinate Space XYZM

Example
SELECT ST_Asewkt(ST_GeomFromText(' GEOMETRYCOLLECTION( POINT (5 5 10 8), LINESTRING (0 0 2, 0 50))'));

Result JASPA
GEOMETRYCOLLECTION (POINT (5 5 10 8), LINESTRING (0 0 2 0, 0 50 0 0))

PostGIS
SELECT ST_Asewkt( ST_GeomFromText(' GEOMETRYCOLLECTION( POINT (5 5), LINESTRING (0 0 5, 0 50))')); --Result ERROR: can not mix dimensionality in a geometry

7.1.3. Empty Geometries


A geometry is empty if it does not have any points. "POINT EMPTY" or "LINESTRING EMPTY" are examples of empty geometries. JASPA and PostGIS address empty geometries in different ways. While JASPA converts to NULL every empty geometry, PostGIS returns GEOMETRYCOLLECTION EMPTY, regardless of the actual type of input EMPTY geometry.
SELECT ST_AsText(ST_GeomFromText('POINT EMPTY')); --Result JASPA: null --Result PostGIS: GEOMETRYCOLLECTION EMPTY

Functions
In JASPA, if the input geometry is an empty set, any function will always return as result the null value.
SELECT ST_Envelope(ST_GeomFromText('POINT EMPTY')); --Result JASPA: null --Result PostGIS: st_envelope -------------------010700000000000000 (1 row)

Spatial Intersection
Geometries that do not intersect, will return as their intersection an empty geometry. Consequently, as stated before, the result of disjoint intersections will be different in JASPA and PostGIS.
SELECT ST_astext(ST_Intersection ( ST_GeomFromText('POLYGON ((1 3, 1 8, 6 8, 6 3, 1 3))') , ST_GeomFromText('POLYGON((8 8, 6 10, 8 10, 8 8))'))); --Result JASPA: null --Result PostGIS: GEOMETRYCOLLECTION EMPTY

7.1.4. Dump functions


Dump functions include ST_Dump, ST_DumpPoints, ST_DumpRings

76

Differences Whereas JASPA Dump functions return just an array of geometries, PostGIS Dump functions create an array of geometries with an array of integers (path). The following table shows the different behaviour: Database JASPA for PostgreSQL 1st Example 2nd Example

SELECT st_dump(st_geomfromtext( SELECT ST_AsText(ST_Dump 'MULTIPOINT (1 2, 3 4, 5 6)' (ST_GeomFromText('MULTIPOINT )); (1 2, 3 4, 5 6)')) ); --Result: st_dump or --------------------------\001\001\ ... 000\000\000@ SELECT ST_AsText(geom) FROM \001\001\ ... 000\000\020@ ST_Dump(ST_GeomFromText(' \001\001\ ... 000\000\030@ MULTIPOINT (1 2, 3 4, 5 6)')) as geom; --Result: st_Astext ------------POINT (1 2) POINT (3 4) POINT (5 6)

JASPA for H2

SELECT geom from st_dump ('select st_geomfromewkt(' 'MULTIPOINT (1 2, 3 4, 5 6)' ')as geom'); --Result: GEOM 01010000 ... 00000000000040 01010000 ... 00000000001040 01010000 ... 00000000001840

SELECT ST_AsText(geom) from st_dump ('select st_geomfromewkt('' MULTIPOINT (1 2, 3 4, 5 6)'') as geom' ); --Result: JASPA.ST_ASTEXT(GEOM) POINT (1 2) POINT (3 4) POINT (5 6)

PostGIS

SELECT ST_Dump (ST_GeomFromText SELECT ST_AsText(a.geom) FROM ('MULTIPOINT (1 2, 3 4, 5 6)') (SELECT ); (ST_Dump(ST_GeomFromEWKT(' MULTIPOINT (1 2, 3 4, 5 6) --Result: '))).geom ST_Dump AS geom) AS a; -----------------------------({1},01010000 ... 00000000040) or ({2},01010000 ... 00000001040) ({3},01010000 ... 00000001840) SELECT ST_AsText( (ST_Dump(ST_GeomFromText(' MULTIPOINT (1 2, 3 4, 5 6)' ))).geom ); --Result: st_Astext ------------POINT (1 2) POINT (3 4) POINT (5 6)

77

Differences

7.2. Differences between JASPA for PostgreSQL and for H2


7.2.1. Letter Case
H2 database converts to uppercase the names of tables or field unless you enclose them in double quotation marks. By contrary, PostgreSQL database converts to lower case every unquotated letter. For instance, the following SQL sentence would create in PostgreSQL a table test(id), while in H2 the table is named TEST(ID).
create table test (id serial PRIMARY KEY);

This must be considered when you pass table and column names as parameters. The following example shows the different use of the function AddGeometryColumn in PostgreSQL and H2.
--PostgreSQL SELECT AddGeometryColumn ('','public','test','geom_point',4326,'POINT',2); --H2 SELECT AddGeometryColumn ('PUBLIC','TEST','GEOM_POLYGON',25830,'MULTIPOLYGON',4);

Alternatively, this issue could be easily solved using double quotation marks. The result of the following SQL sentence is the same in both databases, the table is named test(id).
create table "test" ("id" serial PRIMARY KEY);

7.2.2. Casts
Casts are used to convert from one data type to another. In PostgreSQL database, it is allowed to define casts in userdefined types like geometries. By contrast, in H2, those casts are not allowed. So, only JASPA for PostgreSQL have defined casts to convert geometry data to others data types. Anyway, it is advisable to avoid using casts and instead use OGC functions to transform from one data type to another. The main reason, as we've already stated, is that casts are not well supported in all databases. This section, explains the casting behaviour for JASPA in PostgreSQL.

7.2.2.1. Explicit Casts


A cast can be invoked in two different ways, CAST(x AS typename) or x::typename.

JASPA for PostgreSQL


PostgreSQL SELECT ST_Length('LINESTRING (1 2,3 5)'::geometry); SELECT ST_Length(CAST('LINESTRING (1 2,3 5)' AS geometry)); --Result st_length -----------------3.60555127546399 (1 row)

7.2.2.2. Implicit Casts


A cast can be done automatically in which case, you do not invoke it by CAST(x AS typename) or x::typename. This is useful when you give an input parameter to a function that only works with other parameter type and there is an automatic cast. Once again, it is wiser to use OGC conversion functions to prevent surprising interpretations and for compatibility with others databases.

78

Differences There are two implicit casts defined for the Geometry type: 1. Text => Geometry
SELECT ST_AsText(ST_MakeBox2D('POINT(0 0)','POINT(10 10)')); st_astext ----------------------------------------POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0)) (1 row)

Standard Conversion with OGC function


SELECT ST_AsText(ST_MakeBox2D(ST_GeomFromText('POINT(0 0)'), ST_GeomFromText('POINT(10 10)')));

2. Bytea => Geometry


SELECT ST_LineFromWKB(ST_AsBinary('LINESTRING (0 0, 4 5,10 10)')); st_linefromwkb -----------------------------------\001\002\000\000\ ... \000\000$@ (1 row)

Standard Conversion with OGC function


SELECT ST_LineFromWKB(ST_GeomFromText('LINESTRING (0 0, 4 5,10 10)'));

7.2.3. Arrays
An array data type is called by appending square brackets ( [ ] ) to the data type name of the array elements. The functions that support geometry arrays indicate it in their definition. For instance ST_MakeLine includes: geometry ST_MakeLine(bytea[] point array); The way to create an array is completely different in PostgreSQL and H2. The following example shows how to construct an array for each database.

PostgreSQL
--(1st Version)-SELECT asewkt(ST_MakeLine(Array[ST_MakePoint(0, 0), ST_MakePoint(10, 10),ST_MakePoint(15, 10)])); --Result asewkt -------------------------------LINESTRING (0 0, 10 10, 15 10) (1 row) --(2nd Version)-SELECT ST_AsText(ST_Makeline(ST_Accum(geom))) as myline FROM (SELECT ST_GeomFromText('SRID=10;POINT(0 0)') as geom union SELECT ST_GeomFromText('SRID=10;POINT(10 10)') union SELECT ST_GeomFromText('SRID=10;POINT(15 15)') ) as geom; --Result myline -----------------------------LINESTRING (15 15, 0 0, 10 10)

79

Differences

H2
To construct an array we make use of the function ST_Accum which constructs an array of geometries from a set of geometries.
--(1st Version)-SELECT ST_AsText(ST_Makeline(st_accumagg(geom))) as myline from (select array_get( ( st_geomfromtext('POINT(0 0)'), st_geomfromtext('POINT(10 10)'), st_geomfromtext('POINT(15 15)') ),x)::binary as geom from (select x from system_range(1,3) as foo) as tabla); --Result MYLINE LINESTRING (0 0, 10 10, 15 15) --(2nd Version)-SELECT ST_AsText(ST_Makeline(ST_Accumagg(geom))) as myline FROM (SELECT ST_GeomFromText('SRID=10;POINT(0 0)') as geom union SELECT ST_GeomFromText('SRID=10;POINT(10 10)') union SELECT ST_GeomFromText('SRID=10;POINT(15 15)') ) as geom; --Result MYLINE LINESTRING (15 15, 0 0, 10 10)

7.2.4. Aggregates
Every aggregate function has been renamed in JASPA for H2 database by adding an "Agg" suffix. In the following table the spatial aggregate functions are listed. PostgreSQL ST_Accum ST_Collect ST_Extent ST_AccumAgg ST_CollectAgg ST_ExtentAgg H2 Description Constructs an array of geometries from a set of geometries. Returns a geometry from collection of others geometries. the

Returns the minimum bounding box of the specified geometries, that is, a single rectangle that minimally encloses the geometries. Returns the minimum bounding box of the specified geometries. Returns the last geometry of a set of geometries. Constructs a GeometryCollection object from a set of Geometries. Creates a LineString from a number of points. Same as ST_Union (aggregate) but memory-friendly (uses less memory and more processor time).

ST_Extent3D ST_Last ST_MakeGeomColl ST_MakeLine ST_MemUnion

ST_Extent3DAgg ST_LastAgg ST_MakeGeomCollAgg ST_MakeLineAgg ST_MemUnionAgg

80

Differences

PostgreSQL ST_Polygonize

H2 ST_PolygonizeAgg

Description Creates a GeometryCollection made up of Polygons from a set of Geometries which contain lines that represents the Polygons edges. Returns a Geometry object that represents the point set union of two Geometries.

ST_Union

ST_UnionAgg

7.2.5. Renamed Functions


H2 database doesn't support homonyms functions with the same number of parameters, even if those parameters have different types. For that reason, several functions have been renamed in H2. They are listed in the following table: Renamed Function ST_MakePolygon PostgreSQL geometry ST_MakePolygon (bytea LineString); geometry ST_MakePolygon (bytea LineString, bytea LineString); geometry ST_MakePolygon (bytea LineString, bytea[] LineString Array); double ST_Distance_Spheroid (bytea PointA, bytea PointB, integer SRID); double ST_Distance_Spheroid (bytea PointA, bytea PointB); double ST_Distance_Spheroid (bytea PointA, bytea PointB, varchar WKT_Spheroid); geometry ST_Length_Spheroid (bytea LineString, varchar Spheroid); geometry ST_Length_Spheroid (bytea LineString, integer SRID); geometry ST_Length_Spheroid (bytea LineString); geometry ST_Length2D_Spheroid (LineString, Spheroid); geometry ST_Length2D_Spheroid (LineString, SRID); geometry ST_Length2D_Spheroid (LineString); geometry ST_Length3D_Spheroid (bytea LineString, varchar Spheroid); geometry ST_Length3D_Spheroid (bytea LineString, integer SRID); geometry ST_Length3D_Spheroid (bytea LineString); H2 geometry ST_MakePolygon (bytea LineString); geometry ST_MakePolygon (bytea LineString, bytea LineString); geometry ST_MakePolygonEx (bytea LineString, bytea[] LineString Array); double ST_Distance_SpheroidEx (bytea PointA, bytea PointB, integer SRID); double ST_Distance_Spheroid (bytea PointA, bytea PointB); double ST_Distance_Spheroid (bytea PointA, bytea PointB, varchar WKT_Spheroid); geometry ST_Length_Spheroid (bytea LineString, varchar Spheroid); geometry ST_Length_SpheroidEx (bytea LineString, integer SRID); geometry ST_Length_Spheroid (bytea LineString); geometry ST_Length2D_Spheroid (LineString, Spheroid); geometry ST_Length2D_SpheroidEx (LineString, SRID); geometry ST_Length2D_Spheroid (LineString); geometry ST_Length3D_Spheroid (bytea LineString, varchar Spheroid); geometry ST_Length3D_SpheroidEx (bytea LineString, integer SRID); geometry ST_Length3D_Spheroid (bytea LineString)

ST_Distance_Spheroid

ST_Length_Spheroid

ST_Length2D_Spheroid

ST_Length3D_Spheroid

81

Differences

Renamed Function ST_Buffer

PostgreSQL geometry ST_Buffer Geometry, double distance); geometry ST_Buffer Geometry, double distance, QuadrantSegments); geometry ST_Buffer Geometry, double distance, Buffer_Parameters);

H2 (bytea geometry ST_Buffer Geometry, double distance); (bytea geometry ST_Buffer integer Geometry, double distance, QuadrantSegments); (bytea geometry ST_BufferEx varchar Geometry, double distance, Buffer_Parameters); (bytea (bytea integer (bytea varchar

Functions without alias


The functions Difference and Expand are already defined in the H2 database. So, if you want to use those JASPA functions, you must always call the functions with the "ST_" prefix. PostgreSQL ST_Difference, Difference ST_Expand, Expand ST_Point ST_Difference ST_Expand ST_Point, Point H2

82

Chapter 8. Getting Started


This chapter provides a tutorial introduction to JASPA. We assume that JASPA is already installed on your machine, if it is not true refer to Chapter 3, Installation. This chapter describes how to create the database and the tables needed, how to enter spatial data and some examples using the spatial data. In order to complete the section Section 8.5, Exercises you should get these sql files located in the folder /doc/ data of the JASPA distribution: H2: soilsh2.sql , usesh2.sql , riversh2.sql PostgreSQL: soilspg.sql , usespg.sql , riverspg.sql

8.1. Creating a new database


8.1.1. PostgreSQL
The database can be created with the SQL command createdb on the command line:
shell> createdb -U <username> <database_name>

The following step is to add the JASPA functionality. It can be avoided if you choose a JASPA template when you create your new database.
shell> createdb -U <username> -T <jaspa_template> <database_name>

However if you are trying to spatially enable an existing database or you didn't have a JASPA template, you should follow these steps: 1. Install PL/Java

Windows
shell> psql -U <username> -f C:\jaspa4pg\sql\pljavainstall.sql -d <database_name>

Linux
shell> psql -U <username> -f /opt/jaspa4pg/sql/pljavainstall.sql -d <database_name>

2. Load the jaspa.sql file

Windows
shell> psql -U <username> -f C:\jaspa4pg\sql\jaspa.sql -d <database_name>

Linux
shell> psql -U <username> -f /opt/jaspa4pg/sql/jaspa.sql -d <database_name>

Accessing to a Database
In order to connect to your database you can run the PostgreSQL interactive terminal program, psql, which allows you to execute SQL commands. Alternatively you can use an existing graphical frontend tool like pgAdmin.
shell> psql -U <user> <database_name>

83

Getting Started To obtain information about the JASPA installed version, you can use the following SQL sentences:
database=# SELECT Jaspa_Full_Version(); database=# SELECT Jaspa_build_date();

Remove an existing PostgreSQL database


You can remove the database simply with:
shell> dropdb [option...] <database_name>

8.1.2. H2
The first step consist of starting the H2 server. Open a command shell and run this command:
shell> h2

The following command will automatically create a new, empty database if it does not exist. The database will be called myfirstjaspadb. Windows
shell> h2runscript -url jdbc:h2:tcp://localhost/~/myfirstjaspadb -user sa -password 123 script c:\jaspa4h2\sql\jaspa.sql -showResults

Linux
shell> h2runscript -url jdbc:h2:tcp://localhost/~/myfirstjaspadb -user sa -password 123 script /opt/jaspa4h2/sql/jaspa.sql -showResults

Connecting to a database
In order to connect to your database you can use the H2 client (a browser). Open a command prompt shell and run the following command:
shell> h2console

A browser window should open, enter there the connection parameters: database URL, user name, password.

84

Getting Started

Figure 8.1. H2 server. Connection parameters

Parameter Saved settings Setting name Driver Class JDBC URL User Name Password Generic H2 (Server) Generic H2 (Server) org.h2.Driver

Value

jdbc:h2:tcp://localhost/~/ <database_name>;SCHEMA_SEARCH_PATH=PUBLIC,JASPA sa 123

8.1.3. Tutorial 8.1.3.1. PostgreSQL


Create the database tutorial
shell> createdb -U postgres -T jaspatemplate tutorial

8.1.3.2. H2
Start the H2 server
shell> h2

Create the database tutorial Windows


shell> h2runscript -url jdbc:h2:tcp://localhost/~/tutorial -user sa -password 123 -script c: \jaspa4h2\sql\jaspa.sql -showResults

85

Getting Started Linux


shell> h2runscript -url jdbc:h2:tcp://localhost/~/tutorial -user sa -password 123 -script / opt/jaspa4h2/sql/jaspa.sql -showResults

8.2. Creating a table


Creating a table using SQL is quite easy. You just need the command CREATE TABLE. If the tables will store spatial data, then you need to use the JASPA function AddGeometryColumn. Though it seems to be rapid, the design of the structure of the database (tables, columns, constraints, relationships...) is an important phase and can take a long time.

8.2.1. PostgreSQL
The first step is to create a normal table:
database=# CREATE TABLE <table_name> (<column_name> <data_type> <column_constraint> ... );

The next step is to add a spatial column to an existing feature table.


database=# SELECT AddGeometryColumn(<schema>, <table>, <column>, <srid>, <type>, <coordinate_dimension>);

To show the tables in the current database use the PostgreSQL command:
database=# \dt

Here is an example
database=# CREATE TABLE hospitals ( code integer PRIMARY KEY, name varchar); database=# SELECT AddGeometryColumn('public','hospitals', 'geom', 25830, 'MULTIPOLYGON', 2 );

8.2.2. H2
The first step is to create a normal table:
CREATE TABLE <table_name> (<column_name> <data_type> <column_constraint> ... );

The next step is to add a spatial column to an existing feature table.


SELECT AddGeometryColumn(<schema>, <table>, <column>, <srid>, <type>, <coordinate_dimension>);

Here is an example
CREATE TABLE hospitals ( code integer PRIMARY KEY, name varchar); SELECT AddGeometryColumn('PUBLIC','HOSPITALS', 'GEOM', 25830, 'MULTIPOLYGON', 2 );

Show the tables in the current database


SHOW TABLES;

Display information about the columns in a given table:


SHOW COLUMNS FROM hospitals;

86

Getting Started

8.3. Inserting Data into a Spatial Table


After you create your tables, you need to populate data into them. You can insert rows of data typing manually SQL statements or loading a SQL file.

8.3.1. OGC Functions


INSERT INTO statement allows you to insert new rows into an existing table. The data inserted in the geometry columns must be a geometry representation. To build spatial values you can use Well-Known Text functions (i.e. ST_GeomFromText, ST_LineFromText) or Well-Known Binary functions (i.e ST_GeomFromWKB, ST_MPointFromText) or JASPA functions (i.e ST_MakePolygon, ST_MakePoint). The following example uses the ST_GeomFromText function to insert a MultiPolygon.
INSERT INTO hospitals VALUES (10, 'A', ST_GeomFromEWKT('SRID=25830;MULTIPOLYGON (((20 20, 50 20, 50 50, 20 50, 20 20)))'));

8.3.2. Shp Converter


shp2jaspapg and shp2jaspah2 are two data converters that can be used to convert ESRI Shape files into SQL suitable for JASPA.

shp2jaspapg /// shp2jaspah2


java Converter [<options>] <shapefile> [<schema>.]<table>

The options of the shp converters are: -s <SRID> (-d|a|c|p) These are mutually exclusive options: Set the SRID field. If it is not specified then try to look for the .prj file. If the .prj does not exists uses -1. -d -a -c -p -g <geocolumn> -k -i -info -I Drops the table, then recreates it and populates it with current shape file data. Appends shape file into current table, must be exactly the same table schema. Creates a new table and populates it, this is the default if you do not specify any options. Prepare mode, only creates the table.

Specify the name of the geometry column Keep shape file column names case. Use int4 type for all integer dbf fields. Print some summarizing information about null geometries, not valid geometries, etc Create a spatial index on the geocolumn.

87

Getting Started -S -f -w -W <encoding> Generate simple geometries instead of MULTI geometries. If a geometry contains 2 or more geometries then takes the first one Fix invalid geometries according to the OGC. Clean and rebuild invalid POLYGONS or MULTIPOLYGONS. Output WKT format. This option guarantee OGC compatibility. Note that this will introduce coordinate drifts Specify the character encoding of Shape's attribute column. (default : "ISO-8859-1") You can find a complete list of supported charsets in http:// www.iana.org/assignments/character-sets NULL geometries handling policy (insert|skip|abort) Only import DBF file. Column to be included in the convertion. Column to be excluded in the convertion. Display the help screen.

-N <policy> -n -co <columnname> -CO <columnname> -?

Notes: The table and geom column names are case sensitive In PostgreSQL the default behaviour is to use lowecase In H2 the default behaviour is to use uppercase Type conversion matching: DBF type precision(p) scale(s) Jaspa SQL type Integer 0 < p <= 4 (length - 1) s = 0 SMALL INT Integer 4 < p <= 9 (length - 1) s = 0 INTEGER Integer 9 < p <= 18 (length - 1) s = 0 BIGINT Integer p > 18 (length - 1) s = 0 NUMERIC (p, 0) Real 0 < p <= 7 (length - 2) s > 0 REAL Real 7 < p <= 14 (length - 2) s > 0 DOUBLE PRECISION Real p > 14 (length - 2) s > 0 NUMERIC (p*2,p) String length (length < 254) VARCHAR (length) note: empty strings are considered null Boolean BOOLEAN Date DATE

A shape file must be specified

The shp converter would create SQL sentences like these:


CREATE SELECT INSERT 7084, INSERT 7001, INSERT 6833, TABLE "rivers" ("GID" IDENTITY PRIMARY KEY, "river_code" INTEGER); addgeometrycolumn ('rivers', 'geom', -1, 'MULTILINESTRING', 2); INTO "rivers" ("geom", "river_code") VALUES (ST_GeomFromText ('MULTILINESTRING ((4260 4131 7030, 4078 6965))', -1), 2); INTO "rivers" ("geom", "river_code") VALUES (ST_GeomFromText ('MULTILINESTRING ((4284 4217 6934, 4168 6860, 4058 6820))', -1), 2); INTO "rivers" ("geom", "river_code") VALUES (ST_GeomFromText ('MULTILINESTRING ((4425 4375 6805, 4334 6792, 4239 6788))', -1), 2);

8.3.2.1. Recommendations shp2jaspah2


It is advisable to call the table and geometry field in capital letters, in order to avoid the use of double quotation marks in SQL sentences. For instance:
shp2jaspah2 -w -g GEOM soils.shp SOILS > soilsh2.sql SELECT geom from soils;

By the contrary, if you call them in lower case letter or you use the option -k in the shp2jaspah2 converter, you should use double quotation marks:

88

Getting Started

shp2jaspah2 -w -g geom soils.shp soils > soilsh2.sql SELECT "geom" from "soils";

8.3.2.2. Fields to be included/excluded


The option -co and -CO are used to include and exclude fields of the shapefiles to be converted to SQL. It supports expression patterns. For instance, -co T.* imports every field starting by T and -CO TTRAM.* excludes the fields that start by TTRAM. The order of executing these options is first -co and then -CO.
shp2jaspapg mishapefile.shp mishapefile -co T.* -CO TTRAM.* -info

8.3.3. Load data


You can load a SQL file from the command line.

PostgreSQL
shell> psql -U <user_name> -f <sql_file> -d <database_name>

H2
shell> h2runscript -url <jdbc_url> -user sa -password 123 -script <sql_file>

8.3.4. Tutorial
We are going to load three shapes into the tutorial database. You can convert ESRI Shapes into SQL files or use instead directly the provided SQL files.

Tutorial data

uses

soils

rivers

8.3.5. SHP to SQL PostgreSQL


Convert ESRI Shape files into SQL files for insertion into a JASPA/PostgreSQL database

Windows
shell> cd C:\jaspa4pg\doc\data shell> shp2jaspapg -w -g geom soils.shp soils >soilspg.sql shell> shp2jaspapg -w -g geom uses.shp uses >usespg.sql shell> shp2jaspapg -w -g geom rivers.shp rivers >riverspg.sql

Linux
shell> cd /opt/jaspa4pg/doc/data shell> shp2jaspapg -w -g geom soils.shp soils >soilspg.sql shell> shp2jaspapg -w -g geom uses.shp uses >usespg.sql shell> shp2jaspapg -w -g geom rivers.shp rivers >riverspg.sql

89

Getting Started

H2
Convert ESRI Shape files into SQL files for insertion into a JASPA/H2 database

Windows
shell> cd C:\jaspa4h2\doc\data shell> shp2jaspah2 -w -g GEOM soils.shp SOILS > soilsh2.sql shell> shp2jaspah2 -w -g GEOM uses.shp USES > usesh2.sql shell> shp2jaspah2 -w -g GEOM rivers.shp RIVERS > riversh2.sql

Linux
shell> cd /opt/jaspa4h2/doc/data shell> shp2jaspah2 -w -g GEOM soils.shp SOILS > soilsh2.sql shell> shp2jaspah2 -w -g GEOM uses.shp USES > usesh2.sql shell> shp2jaspah2 -w -g GEOM rivers.shp RIVERS > riversh2.sql

8.3.6. Load SQL files PostgreSQL


Load data into the tutorial database

Windows
shell> cd C:\jaspa4pg\doc\data --Load shell> shell> shell> data psql -U postgres -f soilspg.sql -d tutorial psql -U postgres -f usespg.sql -d tutorial psql -U postgres -f riverspg.sql -d tutorial

Linux
shell> cd /opt/jaspa4pg/doc/data --Load shell> shell> shell> data psql -U postgres -f soilspg.sql -d tutorial psql -U postgres -f usespg.sql -d tutorial psql -U postgres -f riverspg.sql -d tutorial

H2
Open a Command Prompt, and change the directory to which where the data files are stored Example cd C:\jaspa4h2\doc\data

Windows
shell> cd C:\jaspa4h2\doc\data shell> h2runscript -url jdbc:h2:tcp://localhost/~/tutorial -user sa -password 123 -script soilsh2.sql shell> h2runscript -url jdbc:h2:tcp://localhost/~/tutorial -user sa -password 123 -script usesh2.sql shell> h2runscript -url jdbc:h2:tcp://localhost/~/tutorial -user sa -password 123 -script riversh2.sql

90

Getting Started

Linux
shell> cd /opt/jaspa4h2/doc/data shell> h2runscript -url jdbc:h2:tcp://localhost/~/tutorial -user sa -password 123 -script soilsh2.sql shell> h2runscript -url jdbc:h2:tcp://localhost/~/tutorial -user sa -password 123 -script usesh2.sql shell> h2runscript -url jdbc:h2:tcp://localhost/~/tutorial -user sa -password 123 -script riversh2.sql

8.3.7. Jaspa to SHP jaspapg2shp // jaspah22shp


Jaspa2Shp [<options>] <database> [<schema>.]<table>

The options of the Jaspa2shp converter are: -s <srid> -h <host> -p <port> -P <password> -u <user> -s <srid> -g <geocolumn> -I -info -N <policy> -co <columnname> -CO <columnname> -? Set the SRID for the new shape file. If you have some problem then use -1 to avoid the creation of the prj file look for the .prj file. If the .prj does not exists uses -1. The database host to connect to. 127.0.0.1 by default. The port to connect to on the database host. In H2 this parameter is not used. In PostgreSQL is 5432 by default. The password to use when connecting to the database. The username to use when connecting to the database. Set the SRID field. If it is not specified then try to look for the .prj file. If the .prj does not exists uses -1. Specify the name of the geometry column. Usefull in the case the spatial table has more then one geometry column Create a spatial index on the geocolumn in the shape file Just print some summarizing information about null geometries, not valid geometries, etc. NULL geometries handling policy (insert|skip|abort) Column to be included in the convertion. The column name case should match the original shape file field name. Column to be excluded in the convertion. The column name case should match the original shape file field name. Display the help screen.

91

Getting Started

Type conversion matching: Database type VARCHAR(n) / CHAR(n) SMALL INT INTEGER BIG INT REAL DOUBLE PRECISION NUMERIC (0 < p <= 8, s = 0) NUMERIC (9 < p <= 30, s >= 0) NUMERIC (p > 30, s >=0) DATE TIMESTAMP BOOLEAN

DBF type VARCHAR(n) max 254 INTEGER INTEGER REAL REAL REAL INTEGER REAL VARCHAR(p+2) DATE TEXT TEXT

length n 6 9 21 10 17 9 p+2 p+2 13 29 1

precision 5 8 19 8 15 8 p p

8.3.7.1. Example
Export the jaspa layer soils of the database tutorial to the shape file /tmp/myfile:
jaspapg2shp -f /tmp/myfile -u postgres -P **** tutorial soils

8.4. Spatial Indexes


PostgreSQL
Create spatial indexes in PostgreSQL. For further information about spatial indexes pleaser refer to Section 5.7, Spatial indexes
--soils CREATE INDEX soils_geom_idx ON soils USING GIST (ST_PGBOX(geom)); VACUUM ANALYZE soils(geom); --uses CREATE INDEX uses_geom_idx ON uses USING GIST (ST_PGBOX(geom)); VACUUM ANALYZE uses(geom); --rivers CREATE INDEX rivers_geom_idx ON rivers USING GIST (ST_PGBOX(geom)); VACUUM ANALYZE rivers(geom);

8.5. Exercises
Once you have created the spatial database tutorial and populated data into the database, now you are ready to do some queries.

8.5.1. Basis Queries


Calculate the total area of the table "uses", in hectares:
SELECT Sum(ST_Area(geom))/10000 AS has_uses FROM uses; has_uses ---------583.0708 (1 row)

Calculate the total area, in hectares, of "use_code=300" from the table "uses":

92

Getting Started

SELECT Sum(ST_Area(geom))/10000 AS hectare_uses300 FROM uses WHERE use_code=300; hectare_uses300 ----------------21.23765 (1 row)

Calculate the total length in kilometers of the layer "rivers":


SELECT Sum(ST_Length(geom))/1000 AS km_rivers FROM rivers; km_rivers -----------------21.5916100122125 (1 row)

Calculate which is the longest river:


SELECT gid, ST_Length(geom)/1000 AS length_km FROM rivers ORDER BY length_km DESC LIMIT 1; gid | length_km -----+------------------50 | 0.708044614061041 (1 row)

8.5.2. Store Results in Tables and Views


The first option consist in copying the results in a new table. This option doesn't preserve constraints, indexes... In the following example, you are going to store the centroids of the table soils in a new table.
CREATE TABLE centroid_soils AS SELECT s.gid, s.soil_code as soil_code, ST_Centroid(s.geom) as geom from soils s; \d centroid_soils Table "public.centroid_soils" Column | Type | Modifiers ------------+------------------+----------gid | integer | soil_code | double precision | geom | bytea |

This method doesn't update either the metadata table Geometry_Columns. Though, it can be updated manually as in the next example:
--PostgreSQL INSERT INTO geometry_columns(f_table_catalog, f_table_schema, f_table_name, f_geometry_column, coord_dimension, srid, type) SELECT '', 'public', 'centroid_soils', 'geom', ST_CoordDim(geom), ST_SRID(geom), GeometryType(geom) FROM public.centroid_soils LIMIT 1; --H2 INSERT INTO geometry_columns(f_table_catalog, f_table_schema, f_table_name, f_geometry_column, coord_dimension, srid, type) SELECT '', 'PUBLIC', 'CENTROID_SOILS', 'GEOM', ST_CoordDim(geom), ST_SRID(geom), GeometryType(geom) FROM public.centroid_soils LIMIT 1;

Let's check that the table geometry_columns have effectively updated:

93

Getting Started

SELECT * FROM geometry_columns; f_table |f_table |f_table_name _catalog |_schema | ---------+---------+--------------| public |uses | public |soils | public |rivers | public |centroid_soils (4 rows) | f_geometry |coord | srid | type | _column |_dimension | | +-------------+-----------+------+------------| geom | 2 | -1 |MULTIPOLYGON | geom | 2 | -1 |MULTIPOLYGON | geom | 2 | -1 |MULTILINESTRING | geom | 2 | -1 |POINT

The seconds option (and the most advisable), is to create before a table and use the AddGeometryColumn function to add the geometry field. PostgreSQL
CREATE TABLE centroid_uses (id serial PRIMARY KEY,use_code INTEGER); SELECT AddGeometryColumn ('','centroid_uses','geom',-1,'POINT',2); \d centroid_uses Table "public.centroid_uses" Column | Type | Modifiers -----------+---------+-----------------------------------------------------------id | integer | not null default nextval('centroid_uses_id_seq'::regclass) use_code | integer | geom | bytea | Indexes: "centroid_uses_pkey" PRIMARY KEY, btree (id) Check constraints: "enforce_dims_geom" CHECK (st_coorddim(geom) = 2) "enforce_geotype_geom" CHECK (geometrytype(geom)::text = 'POINT'::text OR geom IS NULL) "enforce_srid_geom" CHECK (st_srid(geom) = (-1))

H2
CREATE TABLE centroid_uses (id serial PRIMARY KEY,use_code INTEGER); SELECT AddGeometryColumn ('','CENTROID_USES','GEOM',-1,'POINT',2);

Once the table has been created, you can populate data into it. In the next example, you are going to store the centroids of the table uses in the new table.
INSERT INTO centroid_uses (id,use_code,geom) SELECT u.gid, u.use_code, ST_Centroid(u.geom) from uses u;

Obtain the properties of use_code = 100 from the table "uses".


SELECT id, use_code, ST_AsText(geom) FROM centroid_uses where use_code=100; id | use_code | st_astext ----+-----------+---------------------------------------------5 | 100 | POINT (4460.753947244907 6733.053149347602) 12 | 100 | POINT (5091.4320242926005 6489.129097560754) 18 | 100 | POINT (5786.198674680554 6099.608164587493) 35 | 100 | POINT (5809.357909244613 5842.222313036371) 26 | 100 | POINT (6084.956622281899 6070.596397001231) 31 | 100 | POINT (6007.7403993855605 5978.360590907605) 41 | 100 | POINT (5905.5774584389965 5695.94539306847) (7 rows)

8.5.3. Update a table


Let's round the point's coordinates of the table "centroid_uses" to the centimeter. To do so, it's necessary to update the geom field.
UPDATE centroid_uses SET geom = ST_SnapToGrid(geom, 0.01); UPDATE 76

94

Getting Started Obtain again the properties of use_code = 100 from the table "uses":
SELECT id, use_code, ST_AsText(geom) FROM centroid_uses where use_code=100; id | use_code | st_astext ----+-----------+------------------------5 | 100 | POINT (4460.75 6733.05) 12 | 100 | POINT (5091.43 6489.13) 18 | 100 | POINT (5786.2 6099.61) 35 | 100 | POINT (5809.36 5842.22) 26 | 100 | POINT (6084.96 6070.6) 31 | 100 | POINT (6007.74 5978.36) 41 | 100 | POINT (5905.58 5695.95) (7 rows)

8.5.4. Intersection
We are going to obtain the types of geometries that result of the intersection of two tables, "uses" and "soils":
SELECT ST_GeometryType(ST_Intersection(s.geom,u.geom)) as typeGeom, count(*) as num FROM soils s, uses u group by typeGeom; typegeom | num -----------------------+-----ST_GeometryCollection | 6 ST_MultiPolygon | 73 ST_Polygon | 182 | 3007 (4 rows)

To reduce the amount of intersections you can add a clause to obtain the intersections just in the case that both tables really intersect:
SELECT ST_GeometryType(ST_Intersection(s.geom,u.geom)) as typeGeom, count(*) as num FROM soils s, uses u WHERE ST_Intersects(s.geom,u.geom) GROUP BY typeGeom; typegeom | num -----------------------+----ST_GeometryCollection | 6 ST_MultiPolygon | 73 ST_Polygon | 182 (3 rows)

So, in the first example Null Geometries represented those intersections that were disjoints. To demonstrate it, now we are going to obtain the types of geometries that result of the intersection of two tables, uses and soils, when they are disjoint:
SELECT ST_GeometryType(ST_Intersection(s.geom,u.geom)) as typeGeom, count(*) as num FROM soils s, uses u WHERE ST_Disjoint (s.geom,u.geom) = 'true' GROUP BY typeGeom; typegeom | num ----------+-----| 3007 (1 row)

The intersection has thrown as result GeometryCollections, MultiPolygons and Polygons. GeometryCollection can be made up of different geometries. We are going to verify which are the constituent geometries of the GeometryCollections of the last example.

95

Getting Started

--PostgreSQL SELECT ST_GeometryType(ST_Dump(i)) as type, count(*) FROM (SELECT ST_Intersection(s.geom,u.geom) as i FROM soils s, uses u) as foo WHERE ST_GeometryType(i)='ST_GeometryCollection' GROUP BY type; type | count ---------------+------ST_Polygon | 42 ST_Point | 3 ST_LineString | 4 (3 rows) --H2 SELECT ST_GeometryType(geom) as type, count(*) from dump('select ST_Intersection(s.geom,u.geom) as geom, ST_Intersection(s.geom,u.geom) as intersection FROM soils s, uses u') WHERE ST_GeometryType(intersection)='ST_GeometryCollection' group by type ; TYPE COUNT(*) ST_Point 3 ST_LineString 4 ST_Polygon 42

If you want to extract a particular type of geometries you can use the ST_Extract function:
SELECT ST_AsText(ST_Extract(ST_Intersection(s.geom,u.geom),0)) as typeGeom, count(*) as num FROM soils s, uses u group by typeGeom; typegeom | num ------------------------------+-----MULTIPOINT ((4214 7240)) | 1 MULTIPOINT ((4346 7061)) | 1 MULTIPOINT ((5495.3 6530.3)) | 1 | 3265 (4 rows)

In order to break up the intersection geometries to obtain individual geometries, we use ST_Dump:
-- PostgreSQL SELECT ST_GeometryType(i) as type, count(*) FROM (SELECT ST_Dump(ST_Intersection(s.geom,u.geom)) as i FROM soils s, uses u) as foo GROUP BY type; type | count ---------------+------ST_Polygon | 452 ST_LineString | 4 ST_Point | 3 (3 rows) --H2 SELECT ST_GeometryType(i) as type, count(*) from dump('select ST_Intersection(s.geom,u.geom) as i FROM soils s, uses u') group by type; TYPE COUNT(*) ST_Point 3 ST_LineString 4 ST_Polygon 452 (3 filas, 2998 ms)

You can use ST_Extract to extract a particular kind of geometries, but be careful it will also return NULL values when there is a geometry different from your specified geometry.

96

Getting Started

--PostgreSQL SELECT ST_GeometryType(i) as type, count(*) FROM (SELECT ST_Extract(ST_Dump(ST_Intersection(s."geom",u."geom")),2) as i FROM "soils" s, "uses" u) as foo GROUP BY type; type | count -----------------+------| 7 ST_MultiPolygon | 452 (2 rows)

--H2 SELECT GeometryType(ST_Extract(i,2)) as type, count(*) from dump('select ST_Intersection(s.geom,u.geom) as i FROM soils s, uses u') GROUP BY type; TYPE COUNT(*) MULTIPOLYGON 452 null 7 (2 filas, 2961 ms)

Finally we are going to create a new table with the intersected geometries, but only if they are Polygons:
--PostgreSQL CREATE TABLE intersection AS SELECT soil_code, use_code, i as geom FROM (SELECT s.soil_code as soil_code, u.use_code as use_code, ST_Dump(ST_Intersection(s.geom,u.geom)) as i FROM soils s, uses u) as foo WHERE ST_GeometryType(i)='ST_Polygon'; --H2 CREATE TABLE intersection as SELECT soil_code, use_code, geom as geom FROM Dump('select ST_Intersection(s.geom,u.geom) as geom, s.soil_code as soil_code, u.use_code as use_code FROM soils s, uses u') as foo WHERE ST_GeometryType(geom)='ST_Polygon'; --Obtain the number of geometries and the total area: SELECT count(*), sum(area(geom)) FROM intersection; COUNT(*) SUM(JASPA.AREA(GEOM)) 452 5829867.916051218 --Obtain 2 polygons with soil_code=2 and use_code=200: SELECT soil_code, use_code, ST_AsText(geom) FROM intersection where soil_code=2 and use_code=200 LIMIT 2; SOIL_CODE USE_CODE JASPA.ST_ASTEXT(GEOM) 2.0 200 POLYGON ((4274.9 6688.9, 4239.9 6679.6, 4169 6693.2, 4046.5 6748.8, 4034.7 6767.3, 4034.9 6788.3, 4058.3 6845.1, 4090.1 6842.7, 4185.7 6782.6, 4260.32562717966 6767.583867701654, 4260 6750, 4282 6729, 4292.361711211682 6729.304756212108, 4288.7 6705.4, 4274.9 6688.9)) 2.0 200 POLYGON ((4449.379631926186 5907.450002480281, 4382.6 5907.9, 4243 5864.8, 4178.1 5859.8, 4115.6 5895, 4087.7 5935.3, 4062.9 6108.3, 4069.2 6191, 4086.8 6241.2, 4147.8 6296.5, 4193.5 6381.6, 4232.1 6409.1, 4272.7256354735455 6422.953633967238, 4272 6421, 4315 6406, 4318.711849456043 6400.555954131138, 4305.4 6357.2, 4302.3 6258.2, 4280.593716741035 6231.251951743513, 4165 6173, 4150 6157, 4188.995980429777 6165.093505372218, 4188.9 6164.8, 4255.158620689655 6124.1577586206895, 4289 6074, 4302 6050, 4306 6025, 4324 5987, 4350 5975, 4383 5978, 4418 5976, 4450 5962, 4486 5947, 4449.379631926186 5907.450002480281))

8.5.5. Buffer
We're going to create an attribute table "riverdistance" to later use it as distance for a buffer.

97

Getting Started

create table riversdistance (river_code integer, dist real); insert into riversdistance values (1,40); insert into riversdistance values (2,20); river_code | dist ------------+-----1 | 40 2 | 20 (2 rows)

Now we can create a Buffer, the buffer distance is read from the "riverdistance" table. The result is stored in the table "buf2" PostgreSQL
create table buf2 (gid serial PRIMARY KEY); select addgeometrycolumn ('','buf2','geom',-1,'MULTIPOLYGON',2); insert into buf2(geom) select multi(buffer(r.geom, d.dist, 16)) from rivers r, riversdistance d where r.river_code = d.river_code;

H2
create table buf2 (gid serial PRIMARY KEY); select addgeometrycolumn ('','BUF2','GEOM',-1,'MULTIPOLYGON',2); insert into buf2(geom) select multi(buffer(r.geom, d.dist, 16)) from rivers r, riversdistance d where r.river_code = d.river_code;

8.5.6. Dissolution Dissolve


We are going to generate a new table "dis1" with the resulting dissolution of the table "buf2"
create table dis1 (gid serial PRIMARY KEY); --PostgreSQL select addgeometrycolumn ('','dis1','geom',-1,'MULTIPOLYGON',2); insert into dis1 (geom) select ST_Union (b.geom) from buf2 b; --H2 select addgeometrycolumn ('','DIS1','GEOM',-1,'MULTIPOLYGON',2); insert into dis1 (geom) select ST_UnionAgg (b.geom) from buf2 b;

98

Getting Started

Dissolve boundaries by Attribute


Now, we are going to dissolve boundaries in the table "soils" by the attribute "soil_code". The result is stored in the table "dis2"
CREATE TABLE dis2 (gid serial PRIMARY KEY, soil_code integer); --PostgreSQL SELECT addgeometrycolumn ('','dis2','geom',-1 ,'MULTIPOLYGON',2); INSERT INTO dis2 (geom,soil_code) SELECT ST_Multi(ST_Union (s1.geom)), s1.soil_code FROM soils AS s1 GROUP BY s1.soil_code; --H2 SELECT addgeometrycolumn ('','DIS2','GEOM',-1 ,'MULTIPOLYGON',2); INSERT INTO dis2 (geom,soil_code) SELECT ST_Multi(ST_UnionAgg (s1.geom)), s1.soil_code FROM soils AS s1 GROUP BY s1.soil_code; SELECT ST_GeometryType(geom) as typeGeom, count(*) as num FROM dis2 group by typeGeom; typegeom | num -----------------+----ST_MultiPolygon | 4 (1 row)

soils

dis2

You can obtain the same result of the dissolution using ST_Collect with ST_Dump. ST_Collect will return a MULTI geom from the single geometries obtained with ST_Dump
--PostgreSQL CREATE TABLE dis3 (gid serial PRIMARY KEY,soil_code integer); --PostgreSQL SELECT addgeometrycolumn ('','dis3','geom',-1 ,'MULTIPOLYGON',2); INSERT INTO dis3(soil_code,geom) SELECT soil_code, (ST_Multi(ST_Collect(foo.the_geom))) as geom FROM (SELECT soil_code, (ST_Dump(geom)) As the_geom FROM soils) As foo GROUP BY soil_code; --H2 SELECT addgeometrycolumn ('','DIS3','GEOM',-1 ,'MULTIPOLYGON',2); INSERT INTO dis3(soil_code,geom) SELECT soil_code, ST_Multi(ST_Collectagg(geom)) FROM dump('SELECT geom as geom, soil_code as soil_code FROM soils') As foo GROUP BY soil_code ;

8.5.7. Distance queries


Obtain the polygons with use_code=300 that are within a distance of 200 meters to the buffer calculated before.

99

Getting Started

SELECT u.gid AS id, u.use_code, ST_Distance(u.geom, dis1.geom) AS distance FROM uses u, dis1 WHERE (ST_DWithin(u.geom, dis1.geom,200) AND u.use_code=300) ORDER BY distance, id; id | use_code | distance ----+----------+-----------------19 | 300 | 0 23 | 300 | 0 29 | 300 | 0 33 | 300 | 0 37 | 300 | 0 47 | 300 | 0 49 | 300 | 0 50 | 300 | 0 54 | 300 | 0 57 | 300 | 0 58 | 300 | 0 61 | 300 | 0 64 | 300 | 0 65 | 300 | 0 71 | 300 | 0 74 | 300 | 0 66 | 300 | 1.89932166720597 28 | 300 | 5.27330754254734 24 | 300 | 12.9027980215524 69 | 300 | 20.0068276577405 56 | 300 | 37.0450602191106 72 | 300 | 61.5356033535093 34 | 300 | 69.8226892487313 70 | 300 | 70.5942141324269 40 | 300 | 90.4315260748462 53 | 300 | 91.4044158396345 (26 rows)

8.5.8. Coordinate Projection


Let's update a Spatial Reference System Identifier of the table "centroid_uses". You can check that the coordinates aren't re-projected.
--PostgreSQL SELECT UpdateGeometrySrid('centroid_uses','geom',25830); --H2 SELECT UpdateGeometrySrid('CENTROID_USES','GEOM',25830);

SELECT ST_AsEWKT(geom) FROM centroid_uses c ORDER BY c.id LIMIT 1; st_asewkt ----------------------------------------------SRID=25830;POINT (5311.9800000000005 6902.99) (1 row)

If you want to re-project a geometry value you should use the ST_Transform function. Re-projection

100

Getting Started

--PostgreSQL SELECT UpdateGeometrySrid('centroid_uses','geom',4326); --H2 SELECT UpdateGeometrySrid('CENTROID_USES','GEOM',4326);

UPDATE centroid_uses SET geom=(ST_Transform(ST_SetSRID(geom,25830),4326)) ; SELECT ST_AsEWKT(geom) FROM centroid_uses c ORDER BY c.id LIMIT 1; st_asewkt -------------------------------------------------------SRID=4326;POINT (-7.441154927102713 0.062264726485138) (1 row)

101

Chapter 9. Reference
9.1. Management Functions
AddGeometryColumn .................................................................................................................... DropGeometryColumn ................................................................................................................... DropGeometryTable ...................................................................................................................... UpdateGeometrySRID .................................................................................................................... Jaspa_Version ............................................................................................................................... Jaspa_Full_Version ........................................................................................................................ Jaspa_Java_Properties .................................................................................................................... Jaspa_Build_Date .......................................................................................................................... Probe_Geometry_Columns .............................................................................................................. 103 106 108 109 110 111 112 113 114

102

Reference

Name
AddGeometryColumn Adds a spatial column to an existing feature table.

Synopsis
varchar AddGeometryColumn(varchar catalogue, varchar schema, varchar table, varchar column, integer srid, varchar type, integer coordinate_dimension); varchar AddGeometryColumn(varchar schema, varchar table, integer srid, varchar type, integer coordinate_dimension); varchar column,

varchar AddGeometryColumn(varchar table, varchar column, integer srid, varchar type, integer coordinate_dimension); Srid could also be varchar. In that case, in H2 call function AddGeometryColumnEx

Description
The AddGeometryColumn method will add a geometry table to the feaure table. ensure that an entry for the SRID exists in the SPATIAL_REFERENCE_SYSTEMS table. add an entry to the GEOMETRY_COLUMNS table that stores the SRID for the geometry column. add a Spatial Reference Check Constraint to the feature table. The catalog, schema and table define the name of the table of attributes (catalog now unused). The SRID must be an integer value that exists in the SPATIAL_REF_SYS table. The type must be an uppercase string corresponding to the geometry type (eg, MULTIPOLYGON,LINESTRING). The coordinate_dimension must be an integer (2 for XY coordinates, 3 for XYZ or 4 for XYZM).

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.3.8 OGC SFS for SQL. 1.1.0 (2005) 6.2.7 OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

103

Reference

Examples
PostgreSQL
create table test (id serial PRIMARY KEY); --Shows Table test properties: \d test Table "public.test" Column | Type | Modifiers --------+---------+--------------------------------------------------id | integer | not null default nextval('test_id_seq'::regclass) Indexes: "test_pkey" PRIMARY KEY, btree (id) -- Adds a geometry column to the table test (3 versions) -- <catalogue>, <schema>, <table>, <column>, <srid>, <type>, <dim> SELECT AddGeometryColumn ('','public','test','geom_point',4326,'POINT',2); -- <schema>, <table>, <column>, <srid>, <type>, <dim> SELECT AddGeometryColumn ('public','test','geom_polygon',25830,'MULTIPOLYGON',4); -- <table>, <column>, <srid>, <type>, <dim> SELECT AddGeometryColumn ('test','geom_line',-1,'LINESTRING',3); --Shows Table test properties (Coordinate Dimension, Geometry Type and SRID Constraints have been added) \d test Table "public.test" Column | Type | Modifiers --------------+---------+--------------------------------------------------id | integer | not null default nextval('test_id_seq'::regclass) geom_point | bytea | geom_polygon | bytea | geom_line | bytea | Indexes: "test_pkey" PRIMARY KEY, btree (id) Check constraints: "enforce_dims_geom_line" CHECK (st_coorddim(geom_line) = 3) "enforce_dims_geom_point" CHECK (st_coorddim(geom_point) = 2) "enforce_dims_geom_polygon" CHECK (st_coorddim(geom_polygon) = 4) "enforce_geotype_geom_line" CHECK (geometrytype(geom_line)::text = 'LINESTRING'::text OR geom_line IS NULL) "enforce_geotype_geom_point" CHECK (geometrytype(geom_point)::text = 'POINT'::text OR geom_point IS NULL) "enforce_geotype_geom_polygon" CHECK (geometrytype(geom_polygon)::text = 'MULTIPOLYGON'::text OR geom_polygon IS NULL) "enforce_srid_geom_line" CHECK (st_srid(geom_line) = (-1)) "enforce_srid_geom_point" CHECK (st_srid(geom_point) = 4326) "enforce_srid_geom_polygon" CHECK (st_srid(geom_polygon) = 25830) --Displays data from the metadata table GEOMETRY_COLUMNS SELECT * FROM geometry_columns; f_table_catalog | f_table_schema | f_table_name | f_geometry_column | coord_dimension | srid | type -----------------+----------------+--------------+-------------------+-----------------+------+-------------| public | test | geom_point | 2 | 4326 | POINT | public | test | geom_polygon | 4 | 25830 | MULTIPOLYGON | public | test | geom_line | 3 | -1 | LINESTRING (3 rows)

104

Reference

H2
create table test (id serial PRIMARY KEY); -- Adds a geometry column to the table test (3 versions) --(1) <catalogue>, <schema>, <table>, <column>, <srid>, <type>, <dim> SELECT AddGeometryColumn ('','PUBLIC','TEST','geom_point',4326,'POINT',2); --(2) <schema>, <table>, <column>, <srid>, <type>, <dim> SELECT AddGeometryColumn ('PUBLIC','TEST','geom_polygon',25830,'MULTIPOLYGON',4); --(3) <table>, <column>, <srid>, <type>, <dim> SELECT AddGeometryColumn ('TEST','geom_line',-1,'LINESTRING',3);

--Displays data from the metadata table GEOMETRY_COLUMNS SELECT * FROM geometry_columns; F_TABLE_CATALOG F_TABLE_SCHEMA F_TABLE_NAME F_GEOMETRY_COLUMN PUBLIC TEST geom_point PUBLIC TEST geom_polygon MULTIPOLYGON PUBLIC TEST geom_line LINESTRING (3 rows, 3 ms) --Displays the fields of the table TEST SHOW COLUMNS FROM test; FIELD TYPE NULL KEY DEFAULT ID BIGINT(19) NO PRI NEXT VALUE FOR PUBLIC.SYSTEM_SEQUENCE_877207D5_53E8_43BC_AAF8_3D14ECD94D4F) geom_point VARBINARY(2147483647) YES NULL geom_polygon VARBINARY(2147483647) YES NULL geom_line VARBINARY(2147483647) YES NULL (4 rows, 17 ms) -- Displays the contraints of the table TEST SELECT CONSTRAINT_TYPE , CONSTRAINT_NAME, CHECK_EXPRESSION INFORMATION_SCHEMA.CONSTRAINTS WHERE TABLE_NAME='TEST';

COORD_DIMENSION 2 4 3

SRID TYPE 4326 POINT 25830 -1

FROM

CONSTRAINT_TYPE CONSTRAINT_NAME CHECK_EXPRESSION CHECK ENFORCE_GEOTYPE_PUBLIC_TEST_geom_polygon (("geom_polygon" IS NULL) OR (GEOMETRYTYPE("geom_polygon") = 'MULTIPOLYGON')) PRIMARY KEY CONSTRAINT_2 null CHECK ENFORCE_GEOTYPE_PUBLIC_TEST_geom_line (("geom_line" IS NULL) OR (GEOMETRYTYPE("geom_line") = 'LINESTRING')) CHECK ENFORCE_DIMS_PUBLIC_TEST_geom_polygon (ST_COORDDIM("geom_polygon") = 4) CHECK ENFORCE_GEOTYPE_PUBLIC_TEST_geom_point (("geom_point" IS NULL) OR (GEOMETRYTYPE("geom_point") = 'POINT')) CHECK ENFORCE_DIMS_PUBLIC_TEST_geom_point (ST_COORDDIM("geom_point") = 2) CHECK ENFORCE_DIMS_PUBLIC_TEST_geom_line (ST_COORDDIM("geom_line") = 3)

Related functions
DropGeometryColumn,DropGeometryTable,Probe_Geometry_Columns

105

Reference

Name
DropGeometryColumn Drops a spatial column from an existing feature table.

Synopsis
varchar DropGeometryColumn(varchar catalogue, varchar schema, varchar table, varchar column); varchar DropGeometryColumn(varchar schema, varchar table, varchar column); varchar DropGeometryColumn(varchar table, varchar column);

Description
The DropGeometryColumn method will : drop the spatial reference Check Constraint on the feature table drop the entry from the GEOMETRY_COLUMNS table drop the geometry column from the feature table

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.3.8 OGC SFS for SQL. 1.1.0 (2005) 6.2.7 OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
PostgreSQL
--(1) <catalogue>, <schema>, <table>, <column>, <srid>, <type>, <dim> SELECT DropGeometryColumn ('','public','test','geom_point'); dropgeometrycolumn --------------------------------------"public.test.geom_point effectively removed." (1 row) --(2) <schema>, <table>, <column>, <srid>, <type>, <dim> SELECT DropGeometryColumn ('public','test','geom_polygon'); dropgeometrycolumn --------------------------------------"public.test.geom_polygon effectively removed." (1 row) --(3) <table>, <column>, <srid>, <type>, <dim> SELECT DropGeometryColumn ('test','geom_line'); dropgeometrycolumn --------------------------------------"public.test.geom_line effectively removed." (1 row)

106

Reference

H2
--(1) <catalogue>, <schema>, <table>, <column>, <srid>, <type>, <dim> SELECT DropGeometryColumn ('','PUBLIC','TEST','geom_point'); --Result PUBLIC.TEST.geom_point effectively removed. --(2) <schema>, <table>, <column>, <srid>, <type>, <dim> SELECT DropGeometryColumn ('PUBLIC','TEST','geom_polygon'); --Result PUBLIC.TEST.geom_polygon effectively removed. --(3) <table>, <column>, <srid>, <type>, <dim> SELECT DropGeometryColumn ('TEST','geom_line'); --Result PUBLIC.TEST.geom_line effectively removed.

Related functions
AddGeometryColumn

107

Reference

Name
DropGeometryTable Drops a spatial table and its references in the metadata table geometry_columns.

Synopsis
varchar DropGeometryTable(varchar catalogue, varchar schema, varchar table); varchar DropGeometryTable(varchar schema, varchar table); varchar DropGeometryTable(varchar table);

Description
Drops a spatial table and its references in the metadata table geometry_columns.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
PostgreSQL
--Drops test Table and all its constraints. SELECT DropGeometryTable ('test');

H2
SELECT DropGeometryTable ('TEST');

Related functions
AddGeometryColumn

108

Reference

Name
UpdateGeometrySRID Updates the SRID of the geometries in a particular geometry column. It also updates the geometry_columns metadata table and the srid table constraint.

Synopsis
varchar UpdateGeometrySRID(varchar catalogue, varchar schema, varchar table, varchar column, integer srid); varchar UpdateGeometrySRID(varchar integer srid); schema, varchar table, varchar column,

varchar UpdateGeometrySRID(varchar table, varchar column, integer srid);

Description
Updates the SRID of the geometries in a particular geometry column. It also updates the geometry_columns metadata table and the srid table constraint. This function does not reproject geometries, it just changes the SRID values.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
create SELECT SELECT SELECT table "test" (id serial PRIMARY KEY); AddGeometryColumn ('test','geom',-1,'MULTIPOINT',3); UpdateGeometrySrid('test','geom',23030); DropGeometryTable ('test');

Related functions
ST_SetSRID

109

Reference

Name
Jaspa_Version Returns Jaspa version number and phase of the release life cycle.

Synopsis
varchar jaspa_version();

Description
Returns Jaspa version number and phase of the release life cycle.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
PostgreSQL
SELECT Jaspa_Version(); --PostgreSQL jaspa_version -------------------------For PostgreSQL-0.2.0 RC7 (1 row) --H2 For H2-0.2.0 RC7

Related functions
Jaspa_Full_Version,Jaspa_Build_Date

110

Reference

Name
Jaspa_Full_Version Returns the version of Jaspa and its libraries.

Synopsis
varchar Jaspa_Full_Version();

Description
Returns Jaspa version and its libraries, these are JTS (Java Topology Suite), GeoTools and JRE (Java Runtime Environment)

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT Jaspa_Full_Version(); --PostgreSQL result jaspa_full_version ---------------------------------------------------------------------------------------------------JASPA (JAva SPAtial) For PostgreSQL="0.2.0 RC7" JTS="1.11.0 forjaspa" GeoTools="2.7.2" JRE="1.6.0_25" (1 row) --H2 result JASPA (JAva SPAtial) For H2="0.2.0 RC7" JTS="1.11.0 forjaspa" GeoTools="2.7.2" JRE="1.6.0_25"

Related functions
Jaspa_Version,Jaspa_Java_Properties

111

Reference

Name
Jaspa_Java_Properties Returns information about the OS and the JVM used.

Synopsis
varchar Jaspa_Java_Properties();

Description
Returns information about the OS and the JVM used such as the version or classpath.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT Jaspa_Java_Properties(); --Result PostgreSQL "Java system properties: os.name="Linux" os.arch="i386" os.version="2.6.35-28-generic" user.dir="/var/lib/postgresql/8.4/main" user.home="/var/lib/postgresql" user.name="postgres" java.vendor="Sun Microsystems Inc." java.version="1.6.0_23" java.home="/opt/jaspa4pg/jre" java.class.path="/opt/jaspa4pg/lib/jaspa-examples.jar: [...]" --H2 result Java system properties: os.name="Linux" os.arch="i386" os.version="2.6.35-28-generic" user.dir="/opt/mavenprojects/jaspa/distro" user.home="/home/alumno" user.name="alumno" java.vendor="Sun Microsystems Inc." java.version="1.6.0_23" java.home="/opt/jaspa4h2/jre" java.class.path="/opt/jaspa4h [...]"

Related functions
Jaspa_Version,Jaspa_Full_Version

112

Reference

Name
Jaspa_Build_Date Returns Jaspa version and build date.

Synopsis
varchar Jaspa_Build_Date();

Description
Returns Jaspa version and build date.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT Jaspa_Build_Date(); --PostgreSQL Jaspa="27-06-2011 16:50" JTS="18-11-2010" --H2 Jaspa="27-06-2011 16:50" JTS="18-11-2010"

Related functions
Jaspa_Version

113

Reference

Name
Probe_Geometry_Columns Explores all tables with Jaspa geometry constraints and adds them to the metadata table GEOMETRY_COLUMNS if they are not already there.

Synopsis
varchar Probe_Geometry_Columns();

Description
Explores all tables with Jaspa geometry constraints and adds them to the metadata table GEOMETRY_COLUMNS if they are not already there.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT Probe_Geometry_Columns(); probe_geometry_columns --------------------------------------------------------------The method has added 5 new rows to the geometry columns table (1 row)

Related functions
AddGeometryColumn

9.2. Geometry Constructors


ST_BdPolyFromText ..................................................................................................................... ST_BdMPolyFromText .................................................................................................................. ST_GeomCollFromText ................................................................................................................. ST_GeomFromEWKB .................................................................................................................... ST_GeomFromEWKT .................................................................................................................... ST_GeomFromText ....................................................................................................................... ST_GeomFromWKB ...................................................................................................................... ST_LineFromMultiPoint ................................................................................................................. ST_LineFromText ......................................................................................................................... ST_LineFromWKB ........................................................................................................................ ST_MakeBox2D ........................................................................................................................... ST_MakeBox3D ........................................................................................................................... ST_MakeLine ............................................................................................................................... ST_MakePolygon .......................................................................................................................... ST_MakePoint .............................................................................................................................. 116 117 118 119 121 122 123 125 126 127 128 129 130 132 134

114

Reference

ST_MakePointM ........................................................................................................................... ST_MLineFromText ...................................................................................................................... ST_MPointFromText ..................................................................................................................... ST_MPolyFromText ...................................................................................................................... ST_Point ...................................................................................................................................... ST_PointFromText ........................................................................................................................ ST_PointFromWKB ....................................................................................................................... ST_Polygon .................................................................................................................................. ST_PolyFromText ......................................................................................................................... ST_WKBToSQL ........................................................................................................................... ST_WKTToSQL ........................................................................................................................... ST_PolyFromWKB ........................................................................................................................ ST_MPointFromWKB .................................................................................................................... ST_MLineFromWKB ..................................................................................................................... ST_MPolyFromWKB ..................................................................................................................... ST_GeomCollFromWKB ................................................................................................................ ST_GeomFromGML ...................................................................................................................... ST_GeomFromKML ...................................................................................................................... ST_MakeGeomColl .......................................................................................................................

135 136 137 138 139 140 141 142 143 144 146 147 148 149 150 151 152 154 155

115

Reference

Name
ST_BdPolyFromText Construct a Polygon given an arbitrary collection of closed linestrings as a MultiLineString text representation.

Synopsis
geometry ST_BdPolyFromText(varchar WKT, integer SRID);

Alias
BdPolyFromText

Description
Returns an ST_Polygon value, which is built from a well-known text representation of an ST_MultiLineString. If the incoming geometry is not a MULTILINESTRING throws an error. If the Multilinestring is not closed, returns NULL. The result can be POLYGON or MULTIPOLYGON.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 3.2.6.2 OGC SFS for SQL. 1.1.0 (2005) 7.2.6 OGC SFS for SQL. 1.2.0 (2006 SQL-MM Part 3 8.3.9

Examples
--Return the EWKT of the build polygon SELECT ST_asewkt(ST_BdPolyFromText('MULTILINESTRING ((0 0, 0 150, 150 150, 150 0, 0 0), (20 20, 50 20, 50 50, 20 50, 20 20))', 23030)); --Result SRID=23030;POLYGON ((0 150, 150 150, 150 0, 0 0, 0 150), (20 20, 50 20, 50 50, 20 50, 20 20)) --Not a closed MultiLineString SELECT ST_asewkt(ST_BdPolyFromText('MULTILINESTRING ((0 0, 0 150, 150 150, 150 0, 20 20))', -1)); --Result: NULL is returned st_asewkt ----------(1 row)

Related functions
ST_BdMPolyFromText

116

Reference

Name
ST_BdMPolyFromText Return a specified ST_MultiPolygon value.

Synopsis
geometry ST_BdMPolyFromText(varchar WKT, integer SRID);

Alias
BdMPolyFromText

Description
Construct a MultiPolygon given an arbitrary collection of closed linestrings as a MultiLineString text representation. An INTEGER value srid is required as input parameter. If the incoming geometry is not a LINESTRING throws an error. If the Multilinestring is not closed, returns NULL.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 3.2.6.2 OGC SFS for SQL. 1.1.0 (2005) 7.2.6.1 OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 9.6.7

Examples
select st_asewkt(ST_BdMPolyFromText('MULTILINESTRING ((0 0 -10, 1 0 -5, 1 1 -5, 0 1 -5, 0 0 10), (2 2 -3, 4 2 -1, 4 4 -1, 2 4 -1, 2 2 -3))', -1)) as MP; ---Result MP MULTIPOLYGON (((2 2 -3, 2 4 -1, 4 4 -1, 4 2 -1, 2 2 -3)), ((0 0 10, 0 1 -5, 1 1 -5, 1 0 -5, 0 0 -10)))

Related functions
ST_BdPolyFromText

117

Reference

Name
ST_GeomCollFromText Return a specified Geometry Collection object.

Synopsis
geometry ST_GeomCollFromText(varchar WKT, integer SRID); geometry ST_GeomCollFromText(varchar WKT);

Alias
GeomCollFromText

Description
Construct a GeometryCollection from a well-known text representation of a Geometry Collection value. If WKT is not a valid geometrycollection, returns null. The spatial reference system identifier is set to -1 if not given.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 3.2.6.2 OGC SFS for SQL. 1.1.0 (2005) 7.2.6.1 OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 9.1.6

Examples
--EWKT of a GeometryCollection, with SRID SELECT ST_asewkt(ST_GeomCollFromText('GEOMETRYCOLLECTION(POINT (5 5 10 -2),LINESTRING (0 0 10 -4, 0 50 10 -4))',25830)) as GC; --Result GC SRID=25830;GEOMETRYCOLLECTION (POINT (5 5 10 -2), LINESTRING (0 0 10 -4, 0 50 10 -4)) --Return the SRID from a GeometryCollection SELECT ST_SRID(ST_GeomCollFromText('GEOMETRYCOLLECTION(POINT (5 5))')); st_srid ---------1 (1 row)

Related functions
ST_GeomFromText

118

Reference

Name
ST_GeomFromEWKB Return a specified Geometry from a Extended Well-Known Binary representation (EWKB)

Synopsis
geometry ST_GeomFromEWKB(bytea EWKB);

Alias
GeomFromEWKB

Description
Return a specified Geometry from a Extended Well-Known Binary representation (EWKB). The EWKB format is a Postgis format that adds the Spatial Reference ID (SRID) to the OGC Well-Known Binary representation (WKB). The reverse function is ST_AsEWKB

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
PostgreSQL
--Get the EWKB SELECT ST_AsEWKB(ST_GeomFromText('POINT(5 5)',25830)); st_asewkb -----------------------------------------------------------------------------------------\001\001\000\000 \346d\000\000\000\000\000\000\000\000\024@\000\000\000\000\000\000\024@ (1 row) --By default, in PostgreSQL we need to add double slashes to the WKB, and use E'' SELECT ST_GeomFromEWKB(E'\\001\\001\\000\\000 \\346d\\000\\000\\000\\000\\000\\000\\000\\000\ \024@\\000\\000\\000\\000\\000\\000\\024@'); --By setting the value "standard_conforming_strings" to on, we can use exactly the AsEWKB representation SET standard_conforming_strings = On; SELECT st_asewkt(ST_GeomFromEWKB('\001\001\000\000 \346d\000\000\000\000\000\000\000\000\024@ \000\000\000\000\000\000\024@'));

119

Reference

H2
--Get the EWKB SELECT ST_AsEWKB(ST_GeomFromText('POINT(5 5)',25830)); 0101000020e664000000000000000014400000000000001440 --Return the Geometry SELECT ST_GeomFromEWKB('0101000020e664000000000000000014400000000000001440'); 092080e66400000100000000000014400000000000001440 --As EWKT SELECT ST_AsEWKT(ST_GeomFromEWKB('092080e66400000100000000000014400000000000001440')); SRID=25830;POINT (5 5)

Related functions
ST_AsEWKB

120

Reference

Name
ST_GeomFromEWKT Return a specified Geometry from a Extended Well-Known Text representation (EWKT)

Synopsis
geometry ST_GeomFromEWKT(varchar EWKT);

Alias
GeomFromEWKT

Description
Return a specified Geometry from a Extended Well-Known Text representation (EWKT). The EWKB format is a Postgis format that adds the Spatial Reference ID (SRID) to the OGC Well-Known Text representation (WKT). The reverse function is ST_AsEWKT

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
PostgreSQL
SELECT ST_GeomFromEWKT('SRID=25830;POINT(5 5)') as Point; --Result point -------------------------------------------------------------------------------------\011 \200\346d\000\000\001\000\000\000\000\000\000\024@\000\000\000\000\000\000\024@ (1 row)

H2
SELECT ST_GeomFromEWKT('SRID=25830;POINT(5 5)') as Point; --Result POINT 092080e66400000100000000000014400000000000001440

Related functions
ST_AsEWKT, ST_GeomFromText

121

Reference

Name
ST_GeomFromText Return a geometric object given its Well-known text Representation.

Synopsis
geometry ST_GeomFromText(varchar WKT, integer SRID); geometry ST_GeomFromText(varchar WKT);

Alias
GeomFromText, ST_GeometryFromText, GeometryFromText

Description
The GeomFromText function takes a geometry textual representation and a Spatial Reference System ID (SRID) and creates an instance of the appropriate Geometry Type. If the SRID is not provides it defaults to -1. The return type of the GeomFromText function is the Geometry supertype. For construction of a geometric object to be stored in columns restricted to a particular subtype, use the type-specific construction function. ST_AsText is the reverse of ST_GeomFromText.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 3.2.6.2 OGC SFS for SQL. 1.1.0 (2005) 7.2.6.1 OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 5.1.40

Examples
SELECT ST_GeometryFromText('POLYGON ((20 20, 50 20, 50 50, 20 50, 20 20))',25830); SELECT ST_GeometryFromText('POLYGON ((20 20, 50 20, 50 50, 20 50, 20 20))'); SELECT ST_GeometryFromText('MULTIPOINT (0 0 0 0, 1 1 1 1)'); SELECT ST_GeometryFromText('POINTM (0 0 -4)');

Related functions
ST_AsText, ST_GeomFromEWKT

122

Reference

Name
ST_GeomFromWKB Construct a geometric object given its Well-known Binary Representation

Synopsis
geometry ST_GeomFromWKB(bytea WKB, integer SRID); geometry ST_GeomFromWKB(bytea WKB);

Alias
GeomFromWKB

Description
The GeomFromWKB function takes a well-known binary representation of geometry and a Spatial Reference System ID (SRID) and creates an instance of the appropriate Geometry Type. If the SRID is not provides it defaults to -1. The return type of the GeomFromText function is the Geometry supertype. For construction of a geometric object to be stored in columns restricted to a particular subtype, use the type-specific construction function. ST_AsBinary is the reverse of ST_GeomFromWKB.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 3.2.7.2 OGC SFS for SQL. 1.1.0 (2005) 7.2.7.1 OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 5.1.41

Examples
PostgreSQL
--Get the WKB SELECT ST_AsBinary(ST_GeomFromText('POINT(5 5)',25830)); st_asbinary -------------------------------------------------------------------------------\001\001\000\000\000\000\000\000\000\000\000\024@\000\000\000\000\000\000\024@ (1 row) --By setting the value "standard_conforming_strings" to on, we can use exactly the WKB representation SET standard_conforming_strings = On; SELECT st_astext(ST_GeomFromWKB('\001\001\000\000\000\000\000\000\000\000\000\024@ \000\000\000\000\000\000\024@')); st_astext ------------POINT (5 5) (1 row)

123

Reference

H2
--Get the WKB SELECT ST_AsEWKB(ST_GeomFromText('POINT(5 5)')); 010100000000000000000014400000000000001440 --Return the Geometry SELECT ST_GeomFromWKB('010100000000000000000014400000000000001440'); --As EWKT SELECT ST_AsEWKT(ST_GeomFromWKB('010100000000000000000014400000000000001440')); POINT (5 5)

Related functions
ST_AsBinary, ST_GeomFromEWKB

124

Reference

Name
ST_LineFromMultiPoint Creates a LineString from a Multipoint.

Synopsis
geometry ST_LineFromMultiPoint(bytea Multipoint);

Alias
LineFromMultiPoint

Description
Creates a LineString from a Multipoint.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
--A 2D Linestring SELECT ST_AsEWKT(ST_LineFromMultiPoint(ST_GeomFromText('MULTIPOINT(5 5, 8 10, 12 10)'))); --Result: LINESTRING (5 5, 8 10, 12 10) --A 3D Linestring with SRID SELECT ST_AsEWKT(ST_LineFromMultiPoint(ST_GeomFromEWKT('SRID=25830;MULTIPOINT(5 5 10, 8 10 15, 12 10 20)'))); --Result: SRID=25830;LINESTRING (5 5 10, 8 10 15, 12 10 20) --LineString from Multipoints with measures (M) SELECT ST_AsEWKT(LineFromMultiPoint(ST_GeomFromEWKT('SRID=25830;MULTIPOINTM(1 1 -2, 2 2 -4)'))); --Result:SRID=25830;LINESTRING (1 1 0 -2, 2 2 0 -4)

Related functions
ST_MakeLine

125

Reference

Name
ST_LineFromText Returns a LineString object given its Well-known text Representation

Synopsis
geometry ST_LineFromText(varchar WKT); geometry ST_LineFromText(varchar WKT, integer SRID);

Alias
LineFromText

Description
Creates a LineString from well-known text representation of a LineString and a Spatial Reference System ID (SRID). If the SRID is not provided it defaults to -1. If WKT passed in is not a LINESTRING, then null is returned.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 3.2.6.2 OGC SFS for SQL. 1.1.0 (2005) 7.2.6.1 OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 7.2.8

Examples
--4D Line SELECT ST_AsEWKT(ST_LineFromText('LINESTRING (0 0 10 8, 0 50 10 18)')); --Result LINESTRING (0 0 10 8, 0 50 10 18) --The input is not a LineString SELECT ST_AsEWKT(ST_LineFromText('MULTILINESTRING ((0 0 10 8, 0 50 10 18))')) as Line; --Result LINE null

Related functions
ST_GeomFromText

126

Reference

Name
ST_LineFromWKB Returns a LineString object given its Well-known text Representation

Synopsis
geometry ST_LineFromWKB(bytea WKB); geometry ST_LineFromWKB(bytea WKB, integer SRID);

Alias
LineFromWKB, ST_LineStringFromWKB, LineStringFromWKB

Description
Creates a LineString from well-known binary representation of a LineString and a Spatial Reference System ID (SRID). If the SRID is not provides it defaults to -1. If WKB passed in is not a LINESTRING, then null is returned.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 3.2.7.2 OGC SFS for SQL. 1.1.0 (2005) 7.2.7.1 OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 7.2.9

Examples
SELECT ST_AsEWKT(ST_LineFromWKB(ST_GeomFromText('LINESTRING (0 0, 4 5, 10 10)'))); --Result LINESTRING (0 0, 4 5, 10 10) --EWKT From a LineString with SRID SELECT ST_AsEWKT(ST_LineStringFromWKB(ST_GeomFromText('LINESTRING (0 0, 4 5, 10 10)'),25830)); --Result SRID=25830;LINESTRING (0 0, 4 5, 10 10) --WKB from a LineString and a Point SELECT LineFromWKB(ST_GeomFromText('LINESTRING (0 0, 4 5, 10 10)'),25830) as line , ST_LineFromWKB(ST_GeomFromText('POINT (0 0)'),25830) as Point; --Result LINE 010200002...

POINT null

Related functions
ST_GeomFromWKB

127

Reference

Name
ST_MakeBox2D Creates a Box2d defined by the lower left point and the upper right point.

Synopsis
geometry ST_MakeBox2D(bytea point, bytea point);

Alias
MakeBox2D

Description
Creates a Box2d defined by the lower left point and the upper right point.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
--EWKT of the Box2D SELECT ST_AsEWKT(ST_MakeBox2D(ST_PointFromText('POINT(0 0)'),ST_PointFromText('POINT(10 10)'))); --Result POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))

Related functions
ST_MakeBox3D

128

Reference

Name
ST_MakeBox3D Creates a Box3d defined by the lower left point and the upper right point.

Synopsis
geometry ST_MakeBox3D(bytea point, bytea point);

Alias
MakeBox3D

Description
Creates a Box3d defined by the lower left point and the upper right point.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsEWKT(ST_MakeBox3D(ST_PointFromText('POINT(0 0 10 2)'),ST_PointFromText('POINT(10 10 10 4)'))) As BB; --Result BB POLYGON ((0 0 10, 0 10 10, 10 10 10, 10 0 10, 0 0 10)) --Using ST_MakePoint SELECT ST_AsText(ST_MakeBox3D(ST_MakePoint(0, 0, 8),ST_MakePoint(10 ,10, 8))) As box3d; --Result BOX3D POLYGON ((0 0 8, 0 10 8, 10 10 8, 10 0 8, 0 0 8))

Related functions
ST_MakeBox2D

129

Reference

Name
ST_MakeLine Creates a LineString from a number of points.

Synopsis
PostgreSQL

geometry ST_MakeLine(bytea point, bytea point); geometry ST_MakeLine(bytea[] point array); geometry ST_MakeLine(bytea Aggregate);
H2

geometry ST_MakeLine(bytea point, bytea point); geometry ST_MakeLine(bytea[] point array); geometry ST_MakeLineAgg(bytea Aggregate);

Alias
MakeLine

Description
Creates a LineString from a number of points. The function works in three ways. The first one, takes two points and builds the linestring. The second one, takes an array. The last one, is the aggregate version that takes a row or a subselect from a table to build the resulting linestring.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
2 points
--2 points SELECT ST_AsEWKT( ST_Makeline(ST_GeomFromEWKT('SRID=25830;POINT(0 0)'), ST_GeomFromEWKT('SRID=25830;POINT(10 10)'))) As myline; --Result SRID=25830;LINESTRING (0 0, 10 10)

130

Reference

Array
--PostgreSQL select asewkt(makeline(Array[ST_MakePoint(0, 0), ST_MakePoint(10, 10),ST_MakePoint(15, 10)])); --Result asewkt -------------------------------LINESTRING (0 0, 10 10, 15 10) (1 row)

--H2 (1st Version)-SELECT ST_AsText(ST_Makeline(st_accumagg(geom))) as myline from (select array_get( ( st_geomfromtext('POINT(0 0)'), st_geomfromtext('POINT(10 10)'), st_geomfromtext('POINT(15 15)') ),x)::binary as geom from (select x from system_range(1,3) as foo) as tabla); --Result MYLINE LINESTRING (0 0, 10 10, 15 15) --H2 (2nd Version)-select ST_AsText(ST_Makeline(st_accumagg(geom))) as myline from (select st_geomfromtext('SRID=10;POINT(0 0)') as geom union select st_geomfromtext('SRID=10;POINT(10 10)') union select st_geomfromtext('SRID=10;POINT(15 15)') ) as geom; MYLINE LINESTRING (15 15, 0 0, 10 10)

Aggregate
--Creates a table and populates data into it create table "gps_points"(id serial PRIMARY KEY); SELECT AddGeometryColumn ('gps_points','geom',-1,'POINT',2); INSERT INTO "gps_points" ("geom") VALUES (ST_GeomfromEWKT('SRID=-1;POINT(0 0)')); INSERT INTO "gps_points" ("geom") VALUES (ST_GeomfromEWKT('SRID=-1;POINT(10 10)')); INSERT INTO "gps_points" ("geom") VALUES (ST_GeomfromEWKT('SRID=-1;POINT(15 15)')); --PostgreSQL select asewkt(ST_Makeline("gps_points"."geom")) from "gps_points"; --H2 select asewkt(ST_MakelineAgg("gps_points"."geom")) from "gps_points"; --Result asewkt -------------------------------LINESTRING (0 0, 10 10, 15 15) (1 row)

select dropgeometrytable('gps_points');

Related functions

131

Reference

Name
ST_MakePolygon Creates a Polygon from a number of LineStrings.

Synopsis
PostgreSQL

geometry ST_MakePolygon(bytea LineString); geometry ST_MakePolygon(bytea LineString, bytea LineString); geometry ST_MakePolygon(bytea LineString, bytea[] LineString Array);

H2

geometry ST_MakePolygon(bytea LineString); geometry ST_MakePolygon(bytea LineString, bytea LineString); geometry ST_MakePolygonEx(bytea LineString, bytea[] LineString Array);

Alias
MakePolygon

Description
Creates a Polygon from a number of LineStrings. The function has three variants. The first one, takes a closed linestring. The second one, takes a closed linestring forming the exterior ring and another closed linestring forming a hole. The last one,takes a closed linestring forming the exterior ring and a set of closed linestring forming interior holes. If the incoming geometry is a MultiLineString, the function just takes the first one LineString.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

132

Reference

Examples
PostgreSQL
--1 SELECT ST_Asewkt(ST_MakePolygon(ST_GeomFromText('LINESTRING (0 0, 0 150, 150 150, 150 0, 0 0)'))); --Result POLYGON ((0 0, 0 150, 150 150, 150 0, 0 0)) --2 SELECT ST_Asewkt( ST_MakePolygon( ST_GeomFromText('LINESTRING (0 0, 0 150, 150 150, 150 0, 0 0)'), ST_GeomFromText('LINESTRING(20 20, 50 20, 50 50, 20 50, 20 20)'))); --Result POLYGON ((0 0, 0 150, 150 150, 150 0, 0 0), (20 20, 50 20, 50 50, 20 50, 20 20))

Array
--PostgreSQL SELECT ST_Asewkt(ST_MakePolygon( ST_GeomFromText('LINESTRING (0 0, 0 150, 150 150, 150 0, 0 0)'), Array[ ST_GeomFromText('LINESTRING(20 20, 50 20, 50 50, 20 50, 20 20)'), ST_GeomFromText('LINESTRING (90 100, 90 80, 110 80, 110 100, 90 100)')])); --H2 SELECT ST_AsText( ST_MakePolygonEx( ST_GeomFromText('LINESTRING (0 0, 0 150, 150 150, 150 0, 0 0)'), st_accumagg(geom))) as mypol from (select array_get( ( st_geomfromtext('LINESTRING(20 20, 50 20, 50 50, 20 50, 20 20)'), st_geomfromtext('LINESTRING (90 100, 90 80, 110 80, 110 100, 90 100)') ),x)::binary as geom from (select x from system_range(1,3) as foo) as tabla);

--Result POLYGON ((0 0, 0 150, 150 150, 150 0, 0 0), (20 20, 50 20, 50 50, 20 50, 20 20), (90 100, 90 80, 110 80, 110 100, 90 100))

Related functions
ST_Polygon

133

Reference

Name
ST_MakePoint Creates a Point given its coordinates.

Synopsis
geometry ST_MakePoint(double precision X, double precision Y); geometry ST_MakePoint(double precision X, double precision Y, double precision Z); geometry ST_MakePoint(double precision X, double precision Y, double precision Z, double precision M);

Alias
MakePoint, ST_Point,Point

Description
Creates a Point given its coordinates. The point can be 2D (X,Y), 3D (X,Y,Z) or 4D (X,Y,Z,M) where M is a measure. The OGC function is ST_PointFromText.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
--2D Poinnt SELECT ST_MakePoint(-3.668421,40.423813); --3D Point SELECT ST_Asewkt(ST_MakePoint(-3.668421,40.423813,510)); --4D Point SELECT ST_Asewkt(ST_MakePoint(-3.668421,40.423813,510,8)); --Set SRID of the created point SELECT ST_SetSRID(MakePoint(-3.668421,40.423813,510),4326);

Related functions
ST_PointFromText, ST_MakePointM

134

Reference

Name
ST_MakePointM Creates a Point given its x,y,m coordinates.

Synopsis
geometry ST_MakePointM(double precision X, double precision Y, double precision Z, double precision M);

Alias
MakePointM

Description
Creates a Point given its coordinates. The point's coordinates obtained will be formatted as XYZM with Z=0. The OGC function is ST_PointFromText.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
--Returns the EWKT Representation of a point. SELECT ST_Asewkt(ST_MakePointM(-3.668421,40.423813,48)); --Result POINT (-3.668421 40.423813 0 48)

Related functions
ST_MakePoint, ST_PointFromText

135

Reference

Name
ST_MLineFromText Constructs a MultiLineString object given its Well-known text Representation

Synopsis
geometry ST_MLineFromText(varchar WKT); geometry ST_MLineFromText(varchar WKT, integer SRID);

Alias
LineFromText

Description
Constructs a MultiLineString object given its Well-known text Representation. If the SRID is not provided it defaults to -1. Returns Null when the WKT is not a MultiLineString or MultiLineStringM.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 3.2.6.2 OGC SFS for SQL. 1.1.0 (2005) 7.2.6.1 OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 9.4.4

Examples
--2D Line SELECT ST_Asewkt(ST_MLineFromText('MULTILINESTRING((10 48,10 21,10 0),(16 0,16 23,16 48))')); --Result MULTILINESTRING ((10 48, 10 21, 10 0), (16 0, 16 23, 16 48)) --EWKT Representation of a 4D MultiLineString. SELECT ST_Asewkt(ST_MLineFromText('MULTILINESTRING((10 48 4 -4,10 21 4 -2,10 0 8 -4),(16 0 6 -5,16 23 6 -7,16 48 8 -9))')); --Result MULTILINESTRING ((10 48 4 -4, 10 21 4 -2, 10 0 8 -4), (16 0 6 -5, 16 23 6 -7, 16 48 8 -9)) --With SRID 25830 SELECT ST_Asewkt(ST_MLineFromText('MULTILINESTRING((10 48,10 21,10 0),(16 0,16 23,16 48))',25830)) as myline; --Result MYLINE SRID=25830;MULTILINESTRING ((10 48, 10 21, 10 0), (16 0, 16 23, 16 48))

Related functions
ST_GeomFromText

136

Reference

Name
ST_MPointFromText Constructs a MultiPoint object given its Well-known text Representation

Synopsis
geometry ST_MPointFromText(varchar WKT); geometry ST_MPointFromText(varchar WKT, integer SRID);

Alias
MPointFromText

Description
Constructs a MultiPoint object given its Well-known text Representation. If the SRID is not provided it defaults to -1. Returns Null when the WKT is not a MultiPoint or MultiPointM.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 3.2.6.2 OGC SFS for SQL. 1.1.0 (2005) 7.2.6.1 OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 9.2.4

Examples
SELECT ST_Asewkt(ST_MPointFromText('MULTIPOINT(5 5 10, 8 10 15, 12 10 20)')); --Result MULTIPOINT (5 5 10, 8 10 15, 12 10 20) --Returns the EWKT Representation of a 4D MultiLineString. SELECT ST_Asewkt(MPointFromText('MULTIPOINT(5 5 10 -20, 8 10 15 -4, 12 10 20 -6)',25830)); --Result SRID=25830;MULTIPOINT (5 5 10 -20, 8 10 15 -4, 12 10 20 -6)

Related functions
ST_GeomFromText

137

Reference

Name
ST_MPolyFromText Constructs a MultiPolygon object given its Well-known text Representation

Synopsis
geometry ST_MPolyFromText(varchar WKT); geometry ST_MPolyFromText(varchar WKT, integer SRID);

Alias
MPolyFromText

Description
Constructs a MultiPolygon object given its Well-known text Representation. If the SRID is not provided it defaults to -1. Returns Null when the WKT is not a MultiPolygon or MultiPolygonM.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 3.2.6.2 OGC SFS for SQL. 1.1.0 (2005) 7.2.6.1 OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 9.6.4

Examples
SELECT ST_MPolyFromText('MULTIPOLYGON (((0 0, 150 150, 150 0, 0 0)),((350 0, 200 0, 350 120, 350 0)))'); SELECT ST_MPolyFromText('MULTIPOLYGON (((0 0, 150 150, 150 0, 0 0)),((350 0, 200 0, 350 120, 350 0)))',25830);

Related functions
ST_GeomFromText

138

Reference

Name
ST_Point Creates a Point given its coordinates. This is an Alias from ST_MakePoint

Synopsis
geometry ST_MakePoint(double precision X, double precision Y); geometry ST_MakePoint(double precision X, double precision Y, double precision Z); geometry ST_MakePoint(double precision X, double precision Y, double precision Z, double precision M);

Alias
Point, ST_MakePoint, MakePoint

Description
Creates a Point given its coordinates. The point can be 2D (X,Y), 3D (X,Y,Z) or 4D (X,Y,Z,M) where M is a measure. This is an Alias from ST_MakePoint

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 6.1.2

Examples
--Return the EWKT from a 4D point SELECT ST_Asewkt(ST_Point(-3.668421,40.423813,510,48)); --Result POINT (-3.668421 40.423813 510 48) --Set the Srid for a Point SELECT ST_Asewkt(ST_SetSrid(ST_Point(-3.668421,40.423813),4326)); --Result SRID=4326;POINT (-3.668421 40.423813)

Related functions
ST_MakePoint , ST_PointFromText

139

Reference

Name
ST_PointFromText Constructs a MultiPoint object given its Well-known text Representation

Synopsis
geometry ST_PointFromText(varchar WKT); geometry ST_PointFromText(varchar WKT, integer SRID);

Alias
PointFromText

Description
Constructs a MultiPoint object given its Well-known text Representation. If the SRID is not provided it defaults to -1. Returns Null when the WKT is not a MultiPoint or MultiPointM.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 3.2.6.2 OGC SFS for SQL. 1.1.0 (2005) 7.2.6.1 OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 6.1.8

Examples
--EWKT Representation of a 3D Point. SELECT ST_Asewkt(ST_PointFromText('POINT(5 5 10)')); --Result MULTIPOINT (5 5 10) --EWKT Representation of a 4D Point. SELECT ST_Asewkt(ST_PointFromText('POINT(5 5 10 -20)',25830)) as mypoint; --Result MYPOINT SRID=25830;POINT (5 5 10 -20)

Related functions
ST_MPointFromTextST_GeomFromText

140

Reference

Name
ST_PointFromWKB Returns a Point object given its Well-known text Representation.

Synopsis
geometry ST_PointFromWKB(varchar WKB); geometry ST_PointFromWKB(varchar WKB, integer SRID);

Alias
PointFromWKB

Description
Creates a Point from well-known binary representation of a Point and a Spatial Reference System ID (SRID). If the SRID is not provides it defaults to -1. If WKB passed in is not a POINT, then null is returned.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 3.2.7.2 OGC SFS for SQL. 1.1.0 (2005) 7.2.7.1 OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 6.1.9

Examples
SELECT ST_AsEWKT(ST_PointFromWKB(ST_GeomFromText('POINT (0 0 2 8)'))); --Result POINT (0 0 2 8) SELECT ST_AsEWKT(ST_PointFromWKB(ST_GeomFromText('POINT (0 0 2 8)'),25830)) As mypoint; --Result MYPOINT SRID=25830;POINT (0 0 2 8)

Related functions
ST_GeomFromText

141

Reference

Name
ST_Polygon Creates a Polygon from a closed LineString and SRID.

Synopsis
geometry ST_Polygon(varchar LineString, integer SRID);

Alias
Polygon

Description
Creates a Polygon from a closed LineString given the Spatial Reference System ID (SRID). If the incoming object is not a LineString or it is not closed throws an error.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 8.3.2

Examples
--Return SELECT ST_Asewkt(ST_Polygon(ST_GeomFromText('LINESTRING (0 0, 0 150, 150 150, 150 0, 0 0)'),-1)); --Result POLYGON ((0 0, 0 150, 150 150, 150 0, 0 0)) --Not a closed LineString SELECT ST_Asewkt(ST_Polygon(ST_GeomFromText('LINESTRING (0 0, 0 150, 150 0, 15 0)'),-1)); --Result, throws an error ERROR: java.lang.IllegalArgumentException: Points of LinearRing do not form a closed linestring

Related functions
ST_MakePolygon

142

Reference

Name
ST_PolyFromText Constructs a Polygon object given its Well-known text Representation

Synopsis
geometry ST_PolygonFromText(varchar WKT); geometry ST_PolygonFromText(varchar WKT, integer SRID);

Alias
PolyFromText, PolygonFromText, ST_PolygonFromText

Description
Constructs a Polygon object given its Well-known text Representation. If the SRID is not provided, it defaults to -1. Returns Null when the WKT is not a Polygon or PolygonM.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 3.2.6.2 OGC SFS for SQL. 1.1.0 (2005) 7.2.6.1 OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 8.3.6

Examples
--Return the geometry from a WKT Polygon SELECT ST_PolyFromText('POLYGON ((20 20 10, 50 20 15, 50 50 15, 20 50 15, 20 20 10))'); --Result PostgreSQL \011 \001\003\001\000\000\000\005\000\000\000\000\000\000 ... --Result H2 0920010301000000050000000000000000003440000000000000344 ... --With SRID SELECT ST_PolygonFromText('POLYGON ((20 20 10, 50 20 15, 50 50 15, 20 50 15, 20 20 10))',4386); --EWKT SELECT ST_Asewkt(ST_PolygonFromText('POLYGON ((20 20 10, 50 20 15, 50 50 15, 20 50 15, 20 20 10))')); --Result POLYGON ((20 20 10, 50 20 15, 50 50 15, 20 50 15, 20 20 10))

Related functions
ST_GeomFromText

143

Reference

Name
ST_WKBToSQL Return a geometric object given its Well-known binary Representation. This is an alias for ST_GeomFromWKB.

Synopsis
geometry ST_WKBToSQL(varchar WKB, integer SRID); geometry ST_WKBToSQL(varchar WKB);

Alias
WKBToSQL

Description
The ST_WKBToSQL function takes a geometry binary representation and a Spatial Reference System ID (SRID) and creates an instance of the appropriate Geometry Type. If the SRID is not provided it defaults to -1.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 5.1.36

Examples
PostgreSQL
--Get the WKB SELECT ST_AsBinary(ST_GeomFromText('POINT(5 5)',25830)); st_asbinary -------------------------------------------------------------------------------\001\001\000\000\000\000\000\000\000\000\000\024@\000\000\000\000\000\000\024@ (1 row) --By setting the value "standard_conforming_strings" to on, we can use exactly the WKB representation SET standard_conforming_strings = On; SELECT ST_WKBToSQL('\001\001\000\000\000\000\000\000\000\000\000\024@ \000\000\000\000\000\000\024@');

H2
--Get the WKB SELECT ST_AsBinary(ST_GeomFromText('POINT(5 5)')); 010100000000000000000014400000000000001440 --Return the Geometry SELECT ST_WKBToSQL('010100000000000000000014400000000000001440'); SELECT ST_WKBToSQL('010100000000000000000014400000000000001440',25830);

144

Reference

Related functions
ST_GeomFromWKB

145

Reference

Name
ST_WKTToSQL Return a geometric object given its Well-known text Representation. This is an alias for ST_GeomFromText.

Synopsis
geometry ST_WKTToSQL(varchar WKT, integer SRID); geometry ST_WKTToSQL(varchar WKT);

Alias
WKTToSQL

Description
The ST_WKTToSQL function takes a geometry textual representation and a Spatial Reference System ID (SRID) and creates an instance of the appropriate Geometry Type. If the SRID is not provided it defaults to -1.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 5.1.34

Examples
SELECT ST_WKTToSQL('POINT (-3.5 41.1)',4326); --Result PostgreSQL \011 \200\346\020\000\000\001\000\000\000\000\000\000\014\300\315\314\314\314\314\214D@ --Result H2 092080e6100000010000000000000cc0cdcccccccc8c4440

Related functions
ST_GeomFromText

146

Reference

Name
ST_PolyFromWKB Returns a LineString object given its Well-known text Representation

Synopsis
geometry ST_PolygonFromWKB(bytea WKB); geometry ST_PolygonFromWKB(bytea WKB, integer SRID);

Alias
PolyFromWKB, ST_PolygonFromWKB, PolygonFromWKB

Description
Creates a Polygon from well-known binary representation of a Polygon and a Spatial Reference System ID (SRID). If the SRID is not provides it defaults to -1. If WKB passed in is not a POLYGON, NULL is returned.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 3.2.7.2 OGC SFS for SQL. 1.1.0 (2005) 7.2.7.1 OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 8.3.7

Examples
SELECT ST_PolygonFromWKB(ST_GeomFromText('POLYGON ((20 20, 50 20, 50 50, 20 50, 20 20))')); --Result PostgreSQL \011 \000\003\001\000\000\000\005\000\000\000\000\000\000\000\000\0004@\000\ ... --Result H2 0920000301000000050000000000000000003440000000000000344000000000000049 ... --With SRID SELECT ST_PolygonFromWKB(ST_GeomFromText('POLYGON ((20 20, 50 20, 50 50, 20 50, 20 20))'),25830);

Related functions
ST_GeomFromWKB

147

Reference

Name
ST_MPointFromWKB Returns a MultiPoint object given its Well-known binary Representation

Synopsis
geometry ST_MPointFromWKB(bytea WKB); geometry ST_MPointFromWKB(bytea WKB, integer SRID);

Alias
MPointFromWKB

Description
Creates a MultiPoint from well-known binary representation of a Point and a Spatial Reference System ID (SRID). If the SRID is not provides it defaults to -1. If WKB passed in is not a MultiPoint, NULL is returned.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 3.2.7.2 OGC SFS for SQL. 1.1.0 (2005) 7.2.7.1 OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 9.2.5

Examples
SELECT ST_AsEWKT(ST_MPointFromWKB(ST_GeomFromText('MULTIPOINT (0 0, 1 1, 2 2)'))); --Result MULTIPOINT (0 0, 1 1, 2 2) SELECT ST_AsEWKT(ST_MPointFromWKB(ST_GeomFromText('MULTIPOINT (0 0, 1 1, 2 2)'),25830)); --Result SRID=25830;MULTIPOINT (0 0, 1 1, 2 2)

Related functions
ST_GeomFromWKB

148

Reference

Name
ST_MLineFromWKB Returns a MultiLineString object given its Well-known binary Representation

Synopsis
geometry ST_MLineFromWKB(bytea WKB); geometry ST_MLineFromWKB(bytea WKB, integer SRID);

Alias
MLineFromWKB

Description
Creates a MultiLineString from well-known binary representation of a MultiLineString and a Spatial Reference System ID (SRID). If the SRID is not provides it defaults to -1. If WKB passed in is not a MultiLineString, NULL is returned.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 3.2.7.2 OGC SFS for SQL. 1.1.0 (2005) 7.2.7.1 OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 9.4.5

Examples
SELECT 23,16 SELECT 23,16 ST_AsEWKT(ST_MLineFromWKB(ST_GeomFromText('MULTILINESTRING((10 48,10 21,10 0),(16 0,16 48))'))); ST_AsEWKT(ST_MLineFromWKB(ST_GeomFromText('MULTILINESTRING((10 48,10 21,10 0),(16 0,16 48))'),25830));

Related functions
ST_GeomFromWKB

149

Reference

Name
ST_MPolyFromWKB Returns a MultiPolygon object given its Well-known binary Representation

Synopsis
geometry ST_MPolyFromWKB(bytea WKB); geometry ST_MPolyFromWKB(bytea WKB, integer SRID);

Alias
MPolyFromWKB, ST_MPolygonFromWKB, MPolygonFromWKB

Description
Creates a MultiPolygon from well-known binary representation of a MultiPolygon and a Spatial Reference System ID (SRID). If the SRID is not provides it defaults to -1. If WKB passed in is not a MultiPolygon, NULL is returned.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 3.2.7.2 OGC SFS for SQL. 1.1.0 (2005) 7.2.7.1 OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 9.6.5

Examples
SELECT ST_MPolyFromWKB(ST_GeomFromText('MULTIPOLYGON (((0 0, 0 150, 150 150, 150 0, 0 0)),((350 0, 230 0, 230 120, 350 120, 350 0)))')); SELECT MPolyFromWKB(ST_GeomFromText('MULTIPOLYGON (((0 0, 0 150, 150 150, 150 0, 0 0)),((350 0, 230 0, 230 120, 350 120, 350 0)))'),25830);

Related functions
ST_GeomFromWKB

150

Reference

Name
ST_GeomCollFromWKB Returns a GeometryCollection object given its Well-known binary Representation

Synopsis
geometry ST_GeomCollFromWKB(bytea WKB); geometry ST_GeomCollFromWKB(bytea WKB, integer SRID);

Alias
GeomCollFromWKB

Description
Creates a GeometryCollection from well-known binary representation of a GeometryCollection and a Spatial Reference System ID (SRID). If the SRID is not provides it defaults to -1. If WKB passed in is not a GeometryCollection, NULL is returned.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 3.2.7.2 OGC SFS for SQL. 1.1.0 (2005) 7.2.7.1 OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 9.1.7

Examples
SELECT ST_GeomCollFromWKB(ST_GeomFromText('GEOMETRYCOLLECTION(POINT (5 5 10),LINESTRING (0 0 10, 0 50 10))'));

Related functions
ST_GeomFromWKB

151

Reference

Name
ST_GeomFromGML Construct a geometric object given its GML Representation

Synopsis
geometry ST_GeomFromGML(varchar GML);

Alias
GeomFromGML, ST_GMLToSQL, GMLToSQL

Description
Construct a geometric object given its GML Representation. It supports OGC GML standard 2.1.2 ST_AsGML is the reverse of ST_GeomFromGML

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 5.1.42 ST_GeomFromGML 5.1.38 ST_GMLToSQL

Examples
SELECT ST_GeomFromGML ( '<gml:Point srsName="EPSG:25830"> <gml:coordinates> 1.0,1.0,1.0 </gml:coordinates> </gml:Point>' ); --Result PostgreSQL \011 \001\001\000\000\000\000\000\000\360?\000\000\000\000\000\000\360? \000\000\000\000\000\000\360? --Result H2 09200101000000000000f03f000000000000f03f000000000000f03f SELECT ST_GeomFromGML ( '<gml:Polygon> <gml:outerBoundaryIs> <gml:LinearRing> <gml:coordinates> 1.0,1.0 1.0,3.0 2.0,4.0 3.0,3.0 1.0,1.0 </gml:coordinates> </gml:LinearRing> </gml:outerBoundaryIs> </gml:Polygon>' );

152

Reference

Related functions
ST_AsGML

153

Reference

Name
ST_GeomFromKML Constructs a geometric object given its KML representation

Synopsis
geometry ST_GeomFromKML(varchar KML);

Alias
GeomFromKML

Description
Constructs a geometric object given its KML representation ST_AsKML is the reverse of ST_GeomFromGML

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_GeomFromKML(' <kml:Polygon xmlns:kml="http://earth.google.com/kml/2.1"> <kml:outerBoundaryIs> <kml:LinearRing> <kml:coordinates> -5.850379847879675,43.35970362178223 -5.848336797975651,43.36161117272741 -5.850411866073801,43.36311451294508 -5.853216861450062,43.36175621008758 -5.850379847879675,43.35970362178223 </kml:coordinates> </kml:LinearRing> </kml:outerBoundaryIs> </kml:Polygon> ');

Related functions
ST_AsKML

154

Reference

Name
ST_MakeGeomColl Constructs a GeometryCollection object from a set of Geometries.

Synopsis
PostgreSQL

geometry ST_MakeGeomColl(bytea Geometry_Array); geometry ST_MakeGeomColl(bytea Geometry_Aggregate);

H2

geometry ST_MakeGeomColl(bytea Geometry_Array); geometry ST_MakeGeomCollAgg(bytea Geometry_Aggregate);

Alias
MakeGeomColl

Description
Constructs a GeometryCollection object from a set of Geometries. The method can take as input argument either a Geometry Array or a set of Geometries.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
Array
PostgreSQL

155

Reference

select asewkt(MakeGeomColl(Array[ST_MakePoint(0, 0), ST_MakePoint(10, 10),ST_MakePoint(15, 10)])); --Result asewkt ---------------------------------------------------------------GEOMETRYCOLLECTION (POINT (0 0), POINT (10 10), POINT (15 10)) (1 row)

SELECT asewkt(ST_MakeGeomColl( Array[ ST_GeomFromText('POINT(0 0 10)'), ST_GeomFromText('LINESTRING(0 0 10, 10 10 10)'), ST_GeomFromText('POLYGON ((2 1, 2 5, 6 5, 6 1, 2 1))') ])); --Result asewkt -----------------------------------------------------------------------GEOMETRYCOLLECTION (POINT (0 0 10), LINESTRING (0 0 10, 10 10 10), POLYGON ((2 1 0, 2 5 0, 6 5 0, 6 1 0, 2 1 0))) (1 row)

H2
SELECT ST_AsText(ST_MakeGeomColl(st_accumagg(geom))) as geomcollect from (select array_get( ( st_geomfromtext('POINT(0 0)'), st_geomfromtext('POINT(10 10)'), st_geomfromtext('POINT(15 15)') ),x)::binary as geom from (select x from system_range(1,3) as foo) as table); --Result GEOMCOLLECT GEOMETRYCOLLECTION (POINT (0 0), POINT (10 10), POINT (15 15))

Aggregate
create SELECT INSERT INSERT INSERT table "points"(id serial PRIMARY KEY); AddGeometryColumn ('points','GEOM',25830,'POINT',2); INTO "points" ("GEOM") VALUES (ST_GeomfromEWKT('SRID=25830;POINT (1 1)')); INTO "points" ("GEOM") VALUES (ST_GeomfromEWKT('SRID=25830;POINT (1 7)')); INTO "points" ("GEOM") VALUES (ST_GeomfromEWKT('SRID=25830;POINT (6 7)'));

--PostgreSQL SELECT ST_AsEWKT(ST_MakeGeomColl("points"."GEOM")) from "points"; --H2 SELECT ST_AsEWKT(ST_MakeGeomCollAgg("points"."GEOM")) from "points"; --Result SRID=25830;GEOMETRYCOLLECTION (POINT (1 1), POINT (1 7), POINT (6 7))

Related functions
ST_Collect, ST_Force_Collection

9.3. Geometry Accessors


GeometryType .............................................................................................................................. ST_Boundary ............................................................................................................................... ST_CoordDim .............................................................................................................................. ST_Dimension .............................................................................................................................. 158 159 161 162

156

Reference

ST_EndPoint ................................................................................................................................ ST_Envelope ................................................................................................................................ ST_ExteriorRing ........................................................................................................................... ST_GeometryN ............................................................................................................................. ST_GeometryType ........................................................................................................................ ST_InteriorRingN .......................................................................................................................... ST_IsClosed ................................................................................................................................. ST_IsEmpty ................................................................................................................................. ST_IsRing .................................................................................................................................... ST_IsSimple ................................................................................................................................. ST_IsValid ................................................................................................................................... ST_IsValidReason ......................................................................................................................... ST_M .......................................................................................................................................... ST_NRings .................................................................................................................................. ST_NumGeometries ....................................................................................................................... ST_NumInteriorRing ...................................................................................................................... ST_NumPoints .............................................................................................................................. ST_PointN ................................................................................................................................... ST_SRID ..................................................................................................................................... ST_StartPoint ............................................................................................................................... ST_Summary ................................................................................................................................ ST_X .......................................................................................................................................... ST_Y .......................................................................................................................................... ST_Z ........................................................................................................................................... ST_ZmFlag .................................................................................................................................. ST_Last ....................................................................................................................................... ST_RepeatedPoints ........................................................................................................................

163 164 165 166 167 168 169 170 171 173 174 175 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191

157

Reference

Name
GeometryType Returns the name of the instantiable subtype of Geometry of which this geometric object is a member, as a string

Synopsis
varchar GeometryType(bytea Geometry);

Alias
-

Description
Returns the name of the instantiable subtype of Geometry of which this geometric object is a member, as a string. E.g. "POLYGON", "LINESTRING", "POINT".

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.1.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.10.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.8.1 SQL-MM Part 3 5.1.4

Examples
SELECT GeometryType(ST_GeomFromText('GEOMETRYCOLLECTION(POINT (5 5 10),LINESTRING (0 0 10, 0 50 10))')); --Result GEOMETRYCOLLECTION SELECT GeometryType(ST_GeomFromText('POLYGON ((20 20, 50 20, 50 50, 20 50, 20 20))')); --Result POLYGON

Related functions
ST_GeometryType

158

Reference

Name
ST_Boundary Returns the closure of the combinatorial boundary of a Geometry

Synopsis
geometry (bytea Geometry);

Alias
Boundary

Description
Returns the closure of the combinatorial boundary of this Geometry. The elements of a boundary shall be smaller in dimension than the original element, exactly the next lower dimension. The boundary of a node is the empty set. The boundary of a line is the empty set if it's closed, otherwise it's the set containing the start and end points. The boundary of a surface is the set of lines that delineate the edge of the surface, including interior and exterior rings. If the input geometry is a GEOMETRYCOLLECTION, it throws an error

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.1.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.10.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.8.1 SQL-MM Part 3 5.1.14

Examples
--Polygon SELECT ST_AsText(ST_Boundary(ST_GeomFromText('POLYGON ((20 20, 50 20, 50 50, 20 50, 20 20))'))); --Result LINESTRING (20 20, 50 20, 50 50, 20 50, 20 20) --LineString SELECT ST_AsText(ST_Boundary(ST_GeomFromText('MULTILINESTRING((10 48,10 21,10 0),(16 0,16 23,16 48))'))); --Result MULTIPOINT (10 0, 10 48, 16 0, 16 48) --4D LineString SELECT ST_AsText(ST_Boundary(ST_GeomFromText('LINESTRING(0 0 2 -4,5 0 8 -4,10 0 6 -2)'))); --Result MULTIPOINT (0 0 2 -4, 10 0 6 -2) --Multipoint SELECT ST_AsText(ST_Boundary(ST_GeomFromText('MULTIPOINT (0 0, 1 1, 2 2)'))); --Result null

159

Reference

Related functions
ST_ExteriorRing

160

Reference

Name
ST_CoordDim Returns the coordinate dimension of the Geometry.

Synopsis
integer ST_CoordDim(bytea Geometry);

Alias
CoordDim, ST_Ndims, Ndims

Description
Returns the coordinate dimension of the Geometry. Values are 2 (X,Y), 3 (X, Y, Z), 4 (X,Y,Z,M) or Null (Empty geometry).

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 5.1.3

Examples
SELECT ST_CoordDim(ST_GeomFromText('POINT (0 0)')); --Result 2 SELECT ST_CoordDim(ST_GeomFromText('POINT (0 0 10)')); --Result 3 SELECT ST_Ndims(ST_GeomFromText('LINESTRING(0 0 2 -4,5 0 8 -4,10 0 6 -2)')); --Result 4 SELECT Ndims(ST_GeomFromText('POINT EMPTY')); --Result null

Related functions
ST_Dimension

161

Reference

Name
ST_Dimension Returns the dimension of the geometric object, which is less than or equal to the dimension of the coordinate space.

Synopsis
geometry ST_Dimension(bytea Geometry);

Alias
Dimension

Description
Returns the dimension of the geometric object, which is less than or equal to the dimension of the coordinate space. Returns 0 for POINT, 1 for LINESTRING, 2 for POLYGON, and the largest dimension of the components of a GEOMETRYCOLLECTION.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.1.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.10.1 OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 5.1.2

Examples
SELECT ST_Dimension(ST_GeomFromText('POINT (0 0)')); --Result 0 SELECT ST_Dimension(ST_GeomFromText('LINESTRING(0 0 2 -4,5 0 8 -4,10 0 6 -2)')); --Result 1 SELECT Dimension(ST_GeomFromText('POLYGON ((20 20, 50 20, 50 50, 20 50, 20 20))')); --Result 2 SELECT ST_Dimension(ST_GeomFromText('GEOMETRYCOLLECTION(POINT (5 5 10),LINESTRING (0 0 10, 0 50 10))')); --Result 1

Related functions
ST_CoordDim

162

Reference

Name
ST_EndPoint Returns a Point containing the last Point of a LineString

Synopsis
geometry ST_EndPoint(bytea Geometry);

Alias
EndPoint

Description
Returns a Point containing the last Point of a LineString. If the input geometry is not a LineString, null is returned. Also works with MultiLineStrings. In this case, returns the last point of the last LineString.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.5.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.12.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.10.1 SQL-MM Part 3 7.1.4

Examples
SELECT ST_AsEWKT(ST_EndPoint(ST_GeomFromText('LINESTRING(0 0 0 -4,5 0 0 -4,10 0 10 -2)'))); --Result POINT (10 0 10 -2) SELECT ST_AsEWKT(ST_EndPoint(ST_GeomFromText('MULTILINESTRING ((10 48, 10 0),(16 0, 16 23, 16 48))'))); --Result POINT (16 48)

Related functions
ST_StartPoint

163

Reference

Name
ST_Envelope Returns a geometry object representing the minimum bounding box for the supplied Geometry.

Synopsis
geometry ST_Envelope(bytea Geometry);

Alias
Envelope

Description
Returns a Polygon that represents the rectangle bounding for the input geometry. This Polygon is defined by the corner points of the bounding box [(MINX, MINY),(MAXX, MINY), (MAXX, MAXY), (MINX, MAXY), (MINX, MINY)]. Jaspa also interpolates Z coordinate.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.1.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.10.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.8.2 SQL-MM Part 3 5.1.15

Examples
--POINT SELECT ST_AsEWKT(ST_Envelope(ST_GeomFromText('POINT (0 0)'))); st_asewkt ------------------------------------POLYGON ((0 0, 0 0, 0 0, 0 0, 0 0)) (1 row) --LINESTRING SELECT ST_AsEWKT(ST_Envelope(ST_GeomFromText('LINESTRING(10 50 50,10 20 55,10 0 50)'))); st_asewkt ----------------------------------------------------------POLYGON ((10 0 50, 10 50 55, 10 50 55, 10 0 50, 10 0 50)) (1 row) --POLYGON SELECT ST_AsEWKT(ST_Envelope(ST_GeomFromText('POLYGON ((20 20 10 10, 50 30 10 10, 20 50 -4 2, 20 20 4 2))'))); st_asewkt -------------------------------------------------------------POLYGON ((20 20 -4, 20 50 10, 50 50 10, 50 20 -4, 20 20 -4)) (1 row)

Related functions
ST_Box2D,ST_Box3D,ST_Extent

164

Reference

Name
ST_ExteriorRing Returns the exteriorRing of a Polygon

Synopsis
geometry ST_ExteriorRing(bytea Polygon);

Alias
ExteriorRing

Description
Returns the exteriorRing of a Polygon as LineString. It also works with Polygon or Multipolygon or GeometryCollection (containing Polygons). If the incoming geometry is a MULTIPOLYGON, it will return a MULTILINESTRING.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.10.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.15.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.13.1 SQL-MM Part 3 8.2.3

Examples
--4D Polygon SELECT ST_AsEWKT(ST_ExteriorRing(ST_GeomFromText('POLYGON ((20 20 10 10, 50 30 10 10, 20 50 -4 2, 20 20 4 2))'))); --Result LINESTRING (20 20 10 10, 50 30 10 10, 20 50 -4 2, 20 20 4 2) --Multipolygon SELECT ST_AsEWKT(ST_ExteriorRing(ST_GeomFromText('MULTIPOLYGON (((0 0, 0 150, 150 150, 150 0, 0 0)), ((350 0, 230 0, 230 120, 350 120, 350 0)))'))); --Result MULTILINESTRING ((0 0, 0 150, 150 150, 150 0, 0 0), (350 0, 230 0, 230 120, 350 120, 350 0)) --Polygon with a hole SELECT ST_AsEWKT(ST_ExteriorRing(ST_GeomFromText('POLYGON ((20 20, 50 20, 50 50, 20 50, 20 20), (30 40, 30 30, 40 30, 40 40, 30 40))'))); --Result LINESTRING (20 20, 50 20, 50 50, 20 50, 20 20) --LineString SELECT ST_ExteriorRing(ST_GeomFromText('LINESTRING(10 50 50,10 20 55,10 0 50)')); --Result ERROR: es.upv.jaspa.exceptions.JASPAException: The geometry must be a Polygon, a MultiPolygon or a GeometryCollection (made of some polygonal element/s): found LineString

Related functions
ST_Boundary,ST_InteriorRingN

165

Reference

Name
ST_GeometryN Returns the Nth geometry object in a Collection.

Synopsis
geometry ST_GeometryN(varchar WKT, integer SRID);

Alias
GeometryN

Description
Returns the Nth geometry object in a Collection. The incoming geometry shall be a collection type like MULTIPOINT, MULTILINESTRING, MULTIPOLYGON or GEOMETRYCOLLECTION. Otherwise, returns NULL. N index starts at 1. If N is less than one or greater than the cardinality of the Interior Rings attribute, then the function returns Null.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.2.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.16.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.15 SQL-MM Part 3 9.1.5

Examples
--Return the 1st geometry SELECT ST_AsEWKT( GeometryN( ST_GeomFromText('GEOMETRYCOLLECTION(POINT (5 5 10),LINESTRING (0 0 10, 0 50 10))'),1 )); --Result POINT (5 5 10) ----Return the 3rd point SELECT ST_AsEWKT( GeometryN( ST_GeomFromText('MULTIPOINT ((2 1), (1 2), (4 4), (2 4), (5 1))'),3 )); --Result POINT (4 4)

Related functions
ST_InteriorRingN

166

Reference

Name
ST_GeometryType Returns the name of the instantiable subtype of Geometry of which the input geometric object is a member, as a string

Synopsis
varchar ST_GeometryType(bytea Geometry);

Alias
-

Description
Returns the name of the instantiable subtype of Geometry of which the input geometric object is a member, as a string. E.g. "ST_POLYGON", "ST_LINESTRING", "ST_POINT".

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.1.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.10.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.8.2 SQL-MM Part 3 5.1.4

Examples
SELECT ST_GeometryType(ST_GeomFromText('GEOMETRYCOLLECTION(POINT (5 5),LINESTRING (0 0, 0 50))')); --Result ST_GeometryCollection SELECT ST_GeometryType(ST_GeomFromText('POLYGON ((20 20, 50 50, 20 50, 20 20))')); --Result ST_Polygon

Related functions
GeometryType

167

Reference

Name
ST_InteriorRingN Returns the Nth interior ring for a Polygon as a LineString.

Synopsis
geometry ST_InteriorRingN(bytea Polygon, integer n);

Alias
InteriorRingN

Description
Returns the Nth interior ring for a Polygon as a LineString. It also supports MultiIPolygons. N index starts at 1. If N is less than one or greater than the cardinality of the Interior Rings attribute, then the function returns Null. Also returns Null, if the incoming geometry is not a Polygon or a MultiPolygon.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.10.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.15.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.13.2 SQL-MM Part 3 8.2.6 , 8.3.5

Examples
SELECT ST_AsEWKT(ST_InteriorRingN(ST_GeomFromText('POLYGON ((20 20, 50 20, 50 50, 20 50, 20 20), (30 40, 30 30, 40 30, 40 40, 30 40),(22 25, 22 22, 25 22, 25 25, 22 25))'),1)); --Result LINESTRING (30 40, 30 30, 40 30, 40 40, 30 40) SELECT ST_AsEWKT(ST_InteriorRingN(ST_GeomFromText('POLYGON ((20 20, 50 20, 50 50, 20 50, 20 20), (30 40, 30 30, 40 30, 40 40, 30 40),(22 25, 22 22, 25 22, 25 25, 22 25))'),2)); --Result LINESTRING (22 25, 22 22, 25 22, 25 25, 22 25) SELECT ST_AsEWKT(ST_InteriorRingN(ST_GeomFromText(' MULTIPOLYGON (((0 0, 0 150, 150 150, 150 0, 0 0),(52 56, 52 95, 86 95, 86 56, 52 56)), ((350 0, 230 0, 230 120, 350 120, 350 0),(298 53, 250 100, 300 100, 298 53, 298 53))) '),2)); --Result LINESTRING (298 53, 250 100, 300 100, 298 53, 298 53)

Related functions
ST_NRings,ST_NumInteriorRing

168

Reference

Name
ST_IsClosed Tests if a LineString is closed.

Synopsis
boolean ST_IsClosed(bytea LineString);

Alias
IsClosed

Description
Tests if a LineString is closed. Returns TRUE if the LineString is closed (StartPoint and EndPoint are the same Point). Returns Null if the incoming geometry is not a LineString or a MultiLineString.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.5.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.12.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.17.2 SQL-MM Part 3 7.1.5 , 9.3.3

Examples
SELECT ST_IsClosed(ST_GeomFromText('LINESTRING (0 0, 10 20, 30 20)')); --Result FALSE SELECT ST_IsClosed(ST_GeomFromText('LINESTRING (0 0, 10 20, 30 20,0 0)')); --Result TRUE SELECT ST_IsClosed(ST_GeomFromText('MULTILINESTRING ((0 0, 10 20, 30 20, 0 0), (100 100, 110 120, 130 120, 108 100))')); --Result FALSE SELECT ST_IsClosed(ST_GeomFromText('POINT(0 0)')); --Result null

Related functions
ST_IsRing

169

Reference

Name
ST_IsEmpty Tests if a Geometry corresponds to the empty set.

Synopsis
boolean ST_IsEmpty(bytea Geometry);

Alias
IsEmpty

Description
Tests if a Geometry corresponds to the empty set. Returns False if the incoming geometry it is not an empty geometry According to Spatial Standards this mehod should return 1 for an empty geometry. Though, JASPA returns NULL because converts to null every empty geometry. See XXXXXXXXX for further information.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.1.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.10.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.8.2 SQL-MM Part 3 5.1.7

Examples
SELECT ST_IsEmpty(ST_GeomFromText('POINT (0 0)')); --Result FALSE SELECT ST_IsEmpty(ST_GeomFromText('POINT EMPTY')); --Result true

Related functions

170

Reference

Name
ST_IsRing Tests if a LineString is a ring

Synopsis
boolean ST_IsRing(bytea LineString);

Alias
IsRing

Description
Tests if an LineString is a ring. Returns TRUE if LineString. It is ring if is closed and simple. Returns null if the input geometry is not a LineString. In a closed LineString the StartPoint and EndPoint are the same Point. A simple LineString does not pass through the same Point more than once.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.5.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.12.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.10.2 SQL-MM Part 3 7.1.6

Examples
SELECT ST_IsRing(G1),ST_IsClosed(G1),ST_IsSimple(G1) FROM (SELECT ST_GeomFromText('LINESTRING (20 20, 50 20, 50 50, 20 50, 20 20)') as G1) as foo; st_isring | st_isclosed | st_issimple -----------+-------------+------------t | t | t (1 row) SELECT ST_IsRing(G2),ST_IsClosed(G2),ST_IsSimple(G2) FROM (SELECT ST_GeomFromText('LINESTRING (20 20, 50 20, 20 50, 50 50, 20 20)') as G2) as foo; st_isring | st_isclosed | st_issimple -----------+-------------+------------f | t | f (1 row)

171

Reference Ring (closed and simple) Not a Ring (Closed but not simple)

Related functions
ST_IsClosed, ST_IsSimple

172

Reference

Name
ST_IsSimple Tests if a Geometry has no anomalous geometric points, such as self intersection or self tangency.

Synopsis
boolean ST_IsSimple(bytea Geometry);

Alias
IsSimple

Description
Tests if a Geometry has no anomalous geometric points, such as self intersection or self tangency. If the Geometry is Simple, then returns TRUE. If the Geometry is an empty set, then returns null. Otherwise return False.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.1.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.10.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.8.2 SQL-MM Part 3 5.1.8

Examples
SELECT ST_IsSimple(ST_GeomFromText('MULTIPOINT(0 0 5, 2 2 8)')); --Result TRUE SELECT ST_IsSimple(ST_GeomFromText('MULTIPOINT(0 0 5, 2 2 8, 0 0 8)')); --Result FALSE SELECT IsSimple(ST_GeomFromText('LINESTRING (0 0, 10 10, 20 10, 10 10)')); --Result FALSE SELECT ST_IsSimple(ST_GeomFromText('POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0), (2 2, 2 4, 4 4, 4 2, 2 2))')); --Result TRUE SELECT ST_IsSimple(ST_GeomFromText('POINT EMPTY')); --Result null

Related functions
ST_IsValid

173

Reference

Name
ST_IsValid Tests if a Geometry is well formed.

Synopsis
geometry ST_IsValid (varchar WKT, integer SRID);

Alias
IsValid

Description
Tests if a Geometry is well formed. If the Geometry is an empty set, then return null. If the Geometry is well formed, then return True. Otherwise, return False.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006)) SQL-MM Part 3 5.1.9

Examples
SELECT ST_IsValid(ST_GeomFromText('LINESTRING (0 0, 10 10, 20 10, 10 10)')); st_isvalid -----------t SELECT ST_IsValid(ST_GeomFromText('POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0),(5 0, 0 5, 5 5, 5 0))')); st_isvalid -----------f SELECT ST_IsValid(ST_GeomFromText('POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0),(20 20, 20 30, 30 30, 30 20, 20 20))')); st_isvalid -----------f

Related functions
ST_IsValidReason

174

Reference

Name
ST_IsValidReason Returns the reason why a geometry is not valid.

Synopsis
varchar ST_IsValidReason(bytea Geometry);

Alias
IsValidReason

Description
Returns the reason why a geometry is not valid. If the Geometry is empty or Valid, it returns "Valid Geometry".

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006)) SQL-MM Part 3

Examples
SELECT ST_IsValid(geom),ST_IsValidReason(geom) FROM (SELECT ST_GeomFromText('LINESTRING (0 0, 10 10, 20 10, 10 10)') as geom) as foo; st_isvalid | st_isvalidreason ------------+-----------------t | Valid Geometry (1 row) SELECT ST_IsValid(geom),ST_IsValidReason(geom) FROM (SELECT ST_GeomFromText('POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0),(5 0, 0 5, 5 5, 5 0))') as geom) as foo; st_isvalid | st_isvalidreason ------------+----------------------------------------------------------f | Interior is disconnected at or near point (0.0, 5.0, NaN) (1 row) SELECT ST_IsValid(geom),ST_IsValidReason(geom) FROM (SELECT ST_GeomFromText('POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0),(20 20, 20 30, 30 30, 30 20, 20 20))') as geom) as foo; st_isvalid | st_isvalidreason ------------+-----------------------------------------------------------f | Hole lies outside shell at or near point (20.0, 20.0, NaN) (1 row) SELECT ST_IsValid(geom),ST_IsValidReason(geom) FROM (SELECT ST_GeomFromText('POINT EMPTY') as geom) as foo; st_isvalid | st_isvalidreason ------------+-----------------| (1 row)

175

Reference

Related functions
ST_IsValid

176

Reference

Name
ST_M Returns the M coordinate of a Point

Synopsis
double ST_M(bytea Point);

Alias
M

Description
Returns the M coordinate of a Point. If the M coordinate is not available, returns Null. Input geometry must be a point, otherwise throws an error.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006)) 7.2.9.2 SQL-MM Part 3 6.1.6

Examples
SELECT ST_M(ST_GeomFromEWKT('POINT(0 0 0 -8)')); --Result--8 SELECT ST_M(ST_GeomFromText('POINT(0 0)')); --Result-null SELECT ST_M(ST_GeomFromEWKT('MULTIPOINT(0 0 0 -8,1 1 1 -4)')); --Result-ERROR: es.upv.jaspa.exceptions.JASPAException: The geometry must be a Point: found MultiPoint

Related functions
ST_X , ST_Y , ST_Z

177

Reference

Name
ST_NRings Returns the number of rings of a Polygon or a MultiPolygon.

Synopsis
integer ST_NRings(bytea Geometry);

Alias
NRings

Description
Returns the number of rings of a Polygon or a MultiPolygon. If the input geometry is different from a Polygon or MultiPolygon, returns null.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006)) SQL-MM Part 3

Examples
SELECT ST_NRings(geom),ST_NumInteriorRings(geom) FROM (SELECT ST_GeomFromText ('POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0),(2 2, 2 4, 4 4, 4 2, 2 2),(6 6,6 8, 8 8,8 6,6 6))') as geom) as foo; st_nrings | st_numinteriorrings -----------+--------------------3 | 2 (1 row)

Related functions
ST_NumInteriorRing

178

Reference

Name
ST_NumGeometries Returns the number of geometries in a GeometryCollection.

Synopsis
integer ST_NumGeometries(bytea Geometry);

Alias
NumGeometries

Description
Returns the number of geometries in a GeometryCollection. If the input Geometry is not a GeometryCollection, Jaspa also counts them, instead of returning Null as specified in SQL-MM.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.2.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.16.1 OGC SFS for SQL. 1.2.0 (2006)) 7.2.15 SQL-MM Part 3 9.1.4

Examples
SELECT ST_NumGeometries(ST_GeomFromText('GEOMETRYCOLLECTION( POINT (5 5),LINESTRING (0 0, 0 50), POLYGON ((20 20, 50 20, 50 50, 20 50, 20 20)))')); --Result 3 --Not a GeometyCollection-SELECT ST_NumGeometries(ST_GeomFromText('LINESTRING (0 0, 10 10, 20 10, 10 10)')); --Result 1

Related functions
ST_GeometryN

179

Reference

Name
ST_NumInteriorRing Returns the number of interior rings in a Polygon or a MultiPolygon.

Synopsis
integer ST_NumInteriorRing(bytea Geometry);

Alias
NumInteriorRing, ST_NumInteriorRings, NumInteriorRings

Description
Returns the number of interior rings in a Polygon or a MultiPolygon. If the input geometry is different from a Polygon or MultiPolygon, return null.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.10.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.15.1 OGC SFS for SQL. 1.2.0 (2006)) 7.2.13.2 SQL-MM Part 3 8.2.5

Examples
SELECT ST_NRings(geom),ST_NumInteriorRings(geom) FROM (SELECT ST_GeomFromText ('POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0),(2 2, 2 4, 4 4, 4 2, 2 2),(6 6,6 8, 8 8,8 6,6 6))') as geom) as foo; st_nrings | st_numinteriorrings -----------+--------------------3 | 2 (1 row)

Related functions
ST_InteriorRingN

180

Reference

Name
ST_NumPoints Returns the number of Points in a LineString

Synopsis
integer ST_NumPoints(bytea Geometry);

Alias
NumPoints, ST_NPoints, NPoints

Description
Returns the number of Points in a LineString If the input Geometry is not a LineString, Jaspa also counts the number of points, instead of returning Null as specified in SQL-MM.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.6.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.13.1 OGC SFS for SQL. 1.2.0 (2006)) 7.2.11.2 SQL-MM Part 3 7.2.4

Examples
SELECT ST_NumPoints(ST_GeomFromText('LINESTRING (0 0, 10 10, 20 10)')); --Result 3 SELECT ST_NumPoints(ST_GeomFromText('MULTILINESTRING ((0 0, 10 10, 20 10),(30 30, 40 40, 50 40))')); --Result 6 SELECT ST_NPoints(ST_GeomFromText('MULTIPOINT (0 0, 10 10, 20 10)')); --Result 3

Related functions
ST_PointN

181

Reference

Name
ST_PointN Returns the specified point N in a Linestring.

Synopsis
geometry ST_PointN(bytea Geometry, integer N);

Alias
PointN

Description
Returns the specified point N in a Linestring. The N index starts at 1. It throws an error if the incoming geometry is not a LineString or a MultiLineString.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.6.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.13.1 OGC SFS for SQL. 1.2.0 (2006)) 7.2.11.2 SQL-MM Part 3 7.2.5 - 7.3.5

Examples
SELECT ST_AsText(ST_PointN(ST_GeomFromText('LINESTRING (0 0 5, 10 10 5, 20 10 5)'),2)); --Result POINT (10 10 5) SELECT ST_AsText(ST_PointN(ST_GeomFromText('MULTILINESTRING ((0 0, 10 10, 20 10),(30 30, 40 40, 50 40))'),4)); --Result POINT (30 30)

Related functions
ST_NumPoints

182

Reference

Name
ST_SRID Returns the Spatial Reference System ID for a geometric object

Synopsis
integer ST_SRID(bytea Geometry);

Alias
SRID

Description
Returns the Spatial Reference System ID for a geometric object.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.1.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.10.1 OGC SFS for SQL. 1.2.0 (2006)) 7.2.8.2 SQL-MM Part 3 5.1.5 - 10.1.5

Examples
SELECT ST_SRID(ST_GeomFromText('POINT(0 0)',25830)); --Result 25830 SELECT ST_SRID(ST_GeomFromText('POINT(0 0)')); --Result -1

Related functions
ST_SetSRID,ST_Transform

183

Reference

Name
ST_StartPoint Returns the start point of a LineString.

Synopsis
geometry ST_StartPoint(bytea Geometry);

Alias
StartPoint

Description
Returns the start point of a LineString or MultilineString. With different geometries returns null.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.5.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.12.1 OGC SFS for SQL. 1.2.0 (2006)) 7.2.10.2 SQL-MM Part 3 7.2.6

Examples
SELECT ST_AsText(ST_StartPoint(ST_GeomFromText('LINESTRING (0 0 15 -2, 10 10 20 -4, 20 10 50 -5)'))); --Result POINT (0 0 15 -2) SELECT ST_AsText(ST_StartPoint(ST_GeomFromText('MULTIPOINT (0 0, 10 10, 20 10)'))); --Result null

Related functions
ST_EndPoint,ST_PointN

184

Reference

Name
ST_Summary Returns a summary of a Geometry object characteristics.

Synopsis
varchar ST_Summary(bytea Geometry);

Alias
Summary

Description
Returns a summary of a geometry object characteristics. This includes kind of Geometry, coordinate dimensions ([B], [ZB],[ZMB]), constituent elements and SRID.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006)) SQL-MM Part 3

Examples
SELECT ST_Summary(ST_GeomFromText('POINT(0 0 15 -2)',25830)); --Result Point [ZMB] [SRID=25830] SELECT ST_Summary(ST_GeomFromText('MULTILINESTRING ((0 0, 10 10, 20 10),(30 30, 50 40))')); --Result MultiLineString [B] with 2 element/s [SRID=-1] Line [B] with 3 points [SRID=-1] Line [B] with 2 points [SRID=-1] SELECT ST_Summary(ST_GeomFromText('POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0),(5 0, 0 5, 5 5, 5 0))',4326)); --Result Polygon [B] with 2 ring/s [SRID=4326] ring 0 has 5 points [SRID=4326] ring 1 has 4 points [SRID=4326]

Related functions

185

Reference

Name
ST_X Returns the x coordinate of a point

Synopsis
double ST_X(bytea Geometry);

Alias
X

Description
Returns the x coordinate of a point. Input geometry must be a point, otherwise throws an error.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.3.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.11.1 OGC SFS for SQL. 1.2.0 (2006)) 7.2.9.2 SQL-MM Part 3 6.1.3

Examples
SELECT ST_X(ST_GeomFromEWKT('POINT(2.5 0 0 -8)')); --Result 2.5 SELECT ST_X(ST_GeomFromText('POINT(4 0)')); --Result 4.0

Related functions
ST_Y,ST_Z,ST_M

186

Reference

Name
ST_Y Returns the y coordinate of a point

Synopsis
double ST_Y(bytea Geometry);

Alias
Y

Description
Returns the y coordinate of a point. Input geometry must be a point, otherwise throws an error.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.3.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.11.1 OGC SFS for SQL. 1.2.0 (2006)) 7.2.9.2 SQL-MM Part 3 6.1.4

Examples
SELECT ST_Y(ST_GeomFromEWKT('POINT(2 5 0 -8)')); --Result 5 SELECT ST_Y(ST_GeomFromText('POINT(4 8)')); --Result 8

Related functions
ST_X , ST_Z , ST_M

187

Reference

Name
ST_Z Returns the z coordinate of a point

Synopsis
double ST_Z(bytea Geometry);

Alias
Z

Description
Returns the Z coordinate of a point. If the Z coordinate is not available, returns Null. Input geometry must be a point, otherwise throws an error.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006)) 7.2.9.2 SQL-MM Part 3 6.1.5

Examples
SELECT ST_Z(ST_GeomFromEWKT('POINT(2 5 0 -8)')); --Result 0

Related functions
ST_X, ST_Y, ST_M

188

Reference

Name
ST_ZmFlag Returns a code that represents the number of coordinated dimensions of a Geometry.

Synopsis
integer ST_ZmFlag(bytea Geometry);

Alias
ZmFlag

Description
Returns a code that represents the number of coordinated dimensions of a Geometry. Code values are 0=2d, 1=3dm, 2=3dz, 3=4d. Jaspa transforms a XYM geometry to a XYZM geometry with Z=0. Therefore, this fuction will never return 1. With a XYM Geometry, Jaspa would return 3, whereas Postgis would return 1.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006)) SQL-MM Part 3

Examples
SELECT ST_ZmFlag(ST_GeomFromText('POINT(4 8)')); --Result 0 SELECT ST_ZmFlag(ST_GeomFromText('LINESTRINGM (0 0 -5, 10 10 -8, 20 10 -10)')); --Result 3 SELECT ST_ZmFlag(ST_GeomFromText('POINT(4 8 7)')); --Result 2 SELECT ST_ZmFlag(ST_GeomFromEWKT('POINT(2 5 0 -8)')); --Result 3

Related functions
ST_CoordDim, ST_CoordDim

189

Reference

Name
ST_Last Returns the last geometry of a set of geometries.

Synopsis
PostgreSQL

geometry ST_Last(bytea Aggregate);


H2

geometry ST_LastAgg(bytea Aggregate);

Alias
Last

Description
Returns the last geometry of a set of geometries.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006)) SQL-MM Part 3

Examples
//Create a table and populate data into it: CREATE TABLE "gps_points"(id serial PRIMARY KEY); SELECT AddGeometryColumn ('gps_points','geom',-1,'POINT',2); INSERT INTO "gps_points" ("geom") VALUES (ST_GeomfromEWKT('POINT(0 0)')); INSERT INTO "gps_points" ("geom") VALUES (ST_GeomfromEWKT('POINT(10 10)')); INSERT INTO "gps_points" ("geom") VALUES (ST_GeomfromEWKT('POINT(15 15)'));

PostgreSQL
select asewkt(ST_Last("gps_points"."geom")) from "gps_points"; --Result POINT (15 15)

H2
select asewkt(ST_LastAgg("gps_points"."geom")) from "gps_points"; --Result POINT (15 15)

Related functions
ST_EndPoint

190

Reference

Name
ST_RepeatedPoints Checks if a geometry has repeated vertices. If any, returns a MultiPoint geometry composed by the points that are duplicated.

Synopsis
geometry ST_RepeatedPoints(bytea Geometry);

Alias
RepeatedPoints

Description
Checks if a geometry has repeated vertices. If any, returns a MultiPoint geometry composed by the points that are duplicated.. If there are not repeated points returns null. Repeated vertices may be a symptom of an error in the capture of the geometries. This function does not eliminate the Z or M coordinates, but it does not consider them. For instance a line as LINESTRING(0 0 5, 0 0 8, 10 10 10), is considered to have the second vertex repeated.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006)) SQL-MM Part 3

Examples
SELECT ST_AsEWKT(ST_RepeatedPoints(ST_GeomFromEWKT('LINESTRING (0 0 15, 10 10 25, 10 10 25, 20 10 35)'))); --Result: st_asewkt ------------------------MULTIPOINT ((10 10 25)) (1 row) SELECT ST_AsEWKT(ST_RepeatedPoints(ST_GeomFromEWKT('LINESTRING (0 0 15, 10 10 25, 10 10 25, 10 10 5, 20 10 35)'))); --Result: st_asewkt -----------------------------------MULTIPOINT ((10 10 25), (10 10 5)) (1 row) SELECT St_ASEWKT(ST_RepeatedPoints(ST_GeomFromEWKT('MULTIPOINT (0 10, 0 20, 20 20, 20 10, 0 10)'))); --Result: MULTIPOINT ((0 10)) SELECT ST_RepeatedPoints(ST_GeomFromEWKT('POLYGON ((0 10, 0 20, 20 20, 20 10, 0 10))')); --Result: null

191

Reference

Related functions

9.4. Geometry Editors


ST_AddPoint ................................................................................................................................ ST_Affine .................................................................................................................................... ST_CollectionExtract ..................................................................................................................... ST_Extract ................................................................................................................................... ST_Force_2D ............................................................................................................................... ST_Force_3D ............................................................................................................................... ST_Force_3DM ............................................................................................................................ ST_Force_4D ............................................................................................................................... ST_Force_Collection ...................................................................................................................... ST_ForceRHR .............................................................................................................................. ST_LineMerge .............................................................................................................................. ST_Multi ..................................................................................................................................... ST_RemovePoint ........................................................................................................................... ST_Reverse .................................................................................................................................. ST_RotateX .................................................................................................................................. ST_RotateY .................................................................................................................................. ST_RotateZ .................................................................................................................................. ST_Scale ..................................................................................................................................... ST_Segmentize ............................................................................................................................. ST_SetPoint ................................................................................................................................. ST_SetSRID ................................................................................................................................. ST_SnapToGrid ............................................................................................................................ ST_Transform ............................................................................................................................... ST_Translate ................................................................................................................................ ST_TransScale .............................................................................................................................. ST_NodeLine ............................................................................................................................... ST_CleanPolygon .......................................................................................................................... ST_Snap ...................................................................................................................................... 193 194 196 198 199 200 201 202 203 204 205 206 207 208 209 211 213 215 217 218 220 221 223 224 225 226 228 232

192

Reference

Name
ST_AddPoint Adds a Point to a LineString before point N.

Synopsis
geometry ST_AddPoint(bytea LineString, bytea Point); geometry ST_AddPoint(bytea LineString, bytea Point, integer N);

Alias
AddPoint

Description
Adds a Point to a LineString before point N. N index starts at 0. The parameter N is optional. If not specified or set to -1, it appends the Point to the end of the Line. Also works with MultiLineStrings and GeometryCollections with Lines

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsEWKT(ST_AddPoint(ST_GeomFromEWKT('LINESTRING (0 0 15, 10 10 25, 20 10 35)'), ST_GeomFromEWKT('POINT (-5 5 15)'))); --Result LINESTRING (0 0 15, 10 10 25, 20 10 35, -5 5 15) SELECT ST_AsEWKT(ST_AddPoint(ST_GeomFromEWKT('LINESTRING (0 0, 10 10, 20 10)'), ST_GeomFromEWKT('POINT (-5 5)'),1)); --Result LINESTRING (0 0, -5 5, 10 10, 20 10) SELECT ST_AsEWKT(AddPoint(ST_GeomFromEWKT('MULTILINESTRING ((0 0, 10 10, 20 10),(30 30, 40 40, 50 40))'), ST_GeomFromEWKT('POINT (-5 5 15 -2)'),3)); --Result MULTILINESTRING ((0 0, 10 10, 20 10), (-5 5, 30 30, 40 40, 50 40))

Related functions
ST_RemovePoint, ST_SetPoint

193

Reference

Name
ST_Affine Applies a 2D or 3D affine transformacion to a geometry. That means a rotation, scale and translate in a single step.

Synopsis
geometry ST_Affine(bytea Geometry, double a, double b, double c, double d, double e, double f, double g, double h, double i, double Tx, double Ty, double Tz); geometry ST_Affine(bytea Geometry, double a, double b, double d, double e, double Tx, double Ty);

Alias
Affine

Description
Applies a 2D or 3D affine transformacion to a geometry. That means a rotation, scale and translate in a single step. In the following table transformation matrices and equations to transform the vertices are shown.

3D Transformation matrix

Equations to transform the vertices

2D Transformation matrix

Equations to transform the vertices

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
--Rotates 90 along Z axis SELECT ST_AsEWKT(ST_Affine(geomA, cos(rotRadians), -sin(rotRadians), 0, sin(rotRadians), cos(rotRadians), 0, 0, 0, 1, 0, 0, 0)) FROM (SELECT ST_GeomFromEWKT('LINESTRING (10 10 15, 5 2 10)') as geomA, pi()/2 as rotRadians) as foo; --Result LINESTRING (-10 10 15, -2 5 10)

194

Reference

Related functions
ST_RotateX, ST_RotateY, ST_RotateZ, ST_Scale, ST_Translate

195

Reference

Name
ST_CollectionExtract Extracts a particular type of geometry from a collection and converts them to MULTI*. The values for the type of geometry are 1=Point, 2=Line, 3=Polygon.

Synopsis
geometry ST_CollectionExtract(bytea Geometry, integer geomDimension);

Alias
CollectionExtract

Description
Extracts a particular type of geometry from a collection and converts them to MULTI*. The values for geomDimension are 1=Point, 2=Line, 3=Polygon

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsText(ST_CollectionExtract(ST_GeomFromText('MULTIPOINT ((1 1), (2 3), (4 1))'),1)); --Result MULTIPOINT ((1 1), (2 3), (4 1)) SELECT ST_AsText(CollectionExtract(ST_GeomFromText( 'GEOMETRYCOLLECTION(GEOMETRYCOLLECTION(LINESTRING (0 0 15, 10 10 25, 20 10 35),POINT(0 0 10)))' ),2)); --Result MULTILINESTRING ((0 0 15, 10 10 25, 20 10 35)) SELECT ST_AsText(ST_CollectionExtract(ST_GeomFromText( 'GEOMETRYCOLLECTION(POLYGON ((0 0 1 1, 10 10 2 2, 10 0 3 3, 0 0 4 4)),POINT(0 0 0 0))') ,3)); --Result MULTIPOLYGON (((0 0 1 1, 10 10 2 2, 10 0 3 3, 0 0 4 4)))

This function if there are no sub-geometries of the right type, returns the full geometry.
SELECT ST_AsText(ST_CollectionExtract(ST_GeomFromText('LINESTRING(1 1,2 3,4 1)'),1)); SELECT ST_AsText(ST_CollectionExtract(ST_GeomFromText('LINESTRING(1 1,2 3,4 1)'),2)); SELECT ST_AsText(ST_CollectionExtract(ST_GeomFromText('LINESTRING(1 1,2 3,4 1)'),3)); --Result: st_astext ---------------------------LINESTRING (1 1, 2 3, 4 1) (1 row)

196

Reference

Related functions
ST_Dump,ST_Collect,ST_Dimension,ST_Extract

197

Reference

Name
ST_Extract Extracts a particular type of geometry from a collection and converts them to MULTI*. The values for the type of geometry are 0=Point, 1=Line, 2=Polygon.

Synopsis
geometry ST_Extract(bytea Geometry, integer geomDimension);

Alias
Extract

Description
Extracts a particular type of geometry from a collection and converts them to MULTI*. The values for geomDimension are 0=Point, 1=Line, 2=Polygon It is similar to applying ST_Dump and then ST_Collect.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsText(ST_Extract(ST_GeomFromText('MULTIPOINT ((1 1), (2 3), (4 1))'),0)); --Result MULTIPOINT ((1 1), (2 3), (4 1)) SELECT ST_AsText(ST_Extract(ST_GeomFromText( 'GEOMETRYCOLLECTION(GEOMETRYCOLLECTION(LINESTRING (0 0 15, 10 10 25, 20 10 35),POINT(0 0 10)))' ),1)); --Result MULTILINESTRING ((0 0 15, 10 10 25, 20 10 35)) SELECT ST_AsText(ST_Extract(ST_GeomFromText( 'GEOMETRYCOLLECTION(POLYGON ((0 0 1 1, 10 10 2 2, 10 0 3 3, 0 0 4 4)),POINT(0 0 0 0))'),2)); --Result MULTIPOLYGON (((0 0 1 1, 10 10 2 2, 10 0 3 3, 0 0 4 4)))

Related functions
ST_Dump,ST_Collect,ST_Dimension,ST_CollectionExtract

198

Reference

Name
ST_Force_2D Forces the incoming geometry to be 2D, so it will only have X,Y coordinates.

Synopsis
geometry ST_Force_2D(bytea Geometry);

Alias
Force_2D

Description
Forces the incoming geometry to be 2D, so it will only have X,Y coordinates.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsEWKT(ST_Force_2D(ST_GeomFromEWKT('LINESTRING (0 0 15, 10 10 25, 20 10 35)'))); --Result LINESTRING (0 0, 10 10, 20 10) SELECT ST_AsEWKT(ST_Force_2D(ST_GeomFromEWKT('GEOMETRYCOLLECTION(POINTM(0 0 -4),POINT(5 5 10 -4))'))); --Result GEOMETRYCOLLECTION (POINT (0 0), POINT (5 5))

Related functions
ST_Force_3D

199

Reference

Name
ST_Force_3D Forces the incoming geometry to be 3D, so it will have X,Y,Z coordinates.

Synopsis
geometry ST_Force_3D(bytea Geometry);

Alias
Force_3D, ST_Force_3DZ, Force_3DZ

Description
Forces the incoming geometry to be 3D, so it will have X,Y,Z coordinates. If the object doesn't have Z coordinate, it is set to 0.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsEWKT(ST_Force_3D(ST_GeomFromEWKT('LINESTRING (0 0, 10 10, 20 10)'))); --Result LINESTRING (0 0 0, 10 10 0, 20 10 0) SELECT ST_AsEWKT(ST_Force_3DZ(ST_GeomFromEWKT('GEOMETRYCOLLECTION(POINTM(0 0 -4),POINT(5 5 10 -4))'))); --Result GEOMETRYCOLLECTION (POINT (0 0 0), POINT (5 5 10))

Related functions
ST_Force_2D, ST_Force_3DM, ST_Force_4D

200

Reference

Name
ST_Force_3DM Forces the incoming geometry to be 3D, with X,Y and M coordinates.

Synopsis
geometry ST_Force_3DM(bytea Geometry);

Alias
Force_3DM

Description
Forces the incoming geometry to be 3D, with X,Y and M coordinates. 0 is set for unknown M coordinate. In any case, Z coordinate is set to 0.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsEWKT(ST_Force_3DM(ST_GeomFromEWKT('LINESTRING (0 0, 10 10, 20 10)'))); --Result LINESTRING (0 0 0 0, 10 10 0 0, 20 10 0 0) SELECT ST_AsEWKT(Force_3DM(ST_GeomFromEWKT('GEOMETRYCOLLECTION(POINTM(0 0 -4),POINT(5 5 10 -4))'))); --Result GEOMETRYCOLLECTION (POINT (0 0 0 -4), POINT (5 5 0 -4))

Related functions
ST_Force_3D

201

Reference

Name
ST_Force_4D Forces the incoming geometries to be XYZM dimensions.

Synopsis
geometry ST_Force_4D(bytea Geometry);

Alias
Force_4D

Description
Forces the incoming geometries to be XYZM dimensions. O is set for unknown Z or M coordinates.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsEWKT(ST_Force_4D(ST_GeomFromEWKT('LINESTRING (0 0 4, 10 10 5, 20 10 6)'))); --Result LINESTRING (0 0 4 0, 10 10 5 0, 20 10 6 0) SELECT ST_AsEWKT(ST_Force_4D(ST_GeomFromEWKT('GEOMETRYCOLLECTION(POINTM(0 0 -4),POINT(5 5 10 -4))'))); --Result GEOMETRYCOLLECTION (POINT (0 0 0 -4), POINT (5 5 10 -4))

Related functions
ST_Force_2D, ST_Force_3DM, ST_Force_4D

202

Reference

Name
ST_Force_Collection Forces the geometry to be a GEOMETRYCOLLECTION.

Synopsis
geometry ST_Force_Collection(bytea Geometry);

Alias
Force_Collection

Description
Forces the geometry to be a GEOMETRYCOLLECTION. The collection classes of geometries (MultiPoint, MultiLineString, Multipolygon) are split into single classes (Point, LineString, Polygon).

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsEWKT(ST_Force_Collection(ST_GeomFromEWKT('POINT(0 0 -4)'))); --Result GEOMETRYCOLLECTION (POINT (0 0 -4)) SELECT ST_AsEWKT(ST_Force_Collection(ST_GeomFromEWKT('MULTILINESTRING ((0 0, 10 10, 20 10),(30 30, 40 40, 50 40))'))); --Result GEOMETRYCOLLECTION (LINESTRING (0 0, 10 10, 20 10), LINESTRING (30 30, 40 40, 50 40)) SELECT ST_AsEWKT(ST_Force_Collection(ST_GeomFromEWKT('MULTIPOINT(0 0 1 -4,1 1 2 -5)'))); --Result GEOMETRYCOLLECTION (POINT (0 0 1 -4), POINT (1 1 2 -5))

Related functions
ST_Collect, ST_MakeGeomColl

203

Reference

Name
ST_ForceRHR Forces the exterior ring's vertices of a Polygon to follow right hand orientation.

Synopsis
geometry ST_ForceRHR(bytea Geometry);

Alias
ForceRHR

Description
Forces the exterior ring's vertices of a Polygon to follow right hand orientation. This function supports MultiPolygons and GeometryCollections

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsText(ST_ForceRHR(ST_GeomFromText('MULTIPOLYGON (((0 0, 10 0, 10 10, 0 10, 0 0)),((2 2, 4 2, 4 4, 2 4, 2 2)))'))); --Result MULTIPOLYGON (((0 0, 0 10, 10 10, 10 0, 0 0)), ((2 2, 2 4, 4 4, 4 2, 2 2))) SELECT ST_AsText(ST_ForceRHR(ST_GeomFromText('GEOMETRYCOLLECTION(POINT(20 20),POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0)))'))); --Result GEOMETRYCOLLECTION (POINT (20 20), POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0)))

Related functions
ST_Reverse

204

Reference

Name
ST_LineMerge Returns a LineString as a result of merging a MultiLineString.

Synopsis
geometry ST_LineMerge(bytea Geometry);

Alias
LineMerge

Description
Returns a LineString as a result of merging a MultiLineString. If the geometry can't be merged, original MultiLineString is returned. This function supports GeometryCollections. If the incoming geometry is a Polygon, it will return its exterior ring.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
--Connected MultiLineString SELECT ST_AsEWKT( ST_LineMerge(ST_GeomFromEWKT('MULTILINESTRING ((0 0, 10 10, 20 10, 30 30),(30 30, 40 40, 50 40))'))); --Result LINESTRING (0 0, 10 10, 20 10, 30 30, 40 40, 50 40) --Unconnected MultiLineString SELECT ST_AsEWKT( ST_LineMerge(ST_GeomFromEWKT('MULTILINESTRING ((0 0, 10 10, 20 10),(30 30, 40 40, 50 40))')) ); --Result MULTILINESTRING ((0 0, 10 10, 20 10), (30 30, 40 40, 50 40)) --GeometryCollection SELECT ST_AsEWKT( ST_LineMerge(ST_GeomFromEWKT(' GEOMETRYCOLLECTION(MULTILINESTRING ((0 0,20 10,30 30),(30 30, 40 40)), POINT(0 0) )'))); --Result LINESTRING (0 0, 20 10, 30 30, 40 40) SELECT ST_AsText(ST_LineMerge(ST_GeomFromText('POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))'))); --Result LINESTRING (0 0, 10 0, 10 10, 0 10, 0 0)

Related functions

205

Reference

Name
ST_Multi Forces a geometry to be MULTI* type. Geometries already Multi, remain unchanged.

Synopsis
geometry ST_Multi(bytea Geometry);

Alias
Multi

Description
Forces a geometry to be MULTI* type. As a result, single classes (Point, LineString, Polygon) are converted into collection classes of geometries (MultiPoint, MultiLineString, Multipolygon). Geometries already Multi or GeometryCollections remain unchanged.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsEWKT(ST_Multi(ST_GeomFromEWKT('POINT(0 0 -4)'))); --Result MULTIPOINT (0 0 -4) SELECT ST_AsEWKT(ST_Multi(ST_GeomFromEWKT('LINESTRING (0 0 4, 10 10 5, 20 10 6)'))); --Result MULTILINESTRING ((0 0 4, 10 10 5, 20 10 6)) SELECT ST_AsText(ST_Multi(ST_GeomFromText('POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0),(5 2, 5 5, 0 5, 5 2))'))); --Result MULTIPOLYGON (((0 0, 0 10, 10 10, 10 0, 0 0), (5 2, 5 5, 0 5, 5 2))) --Incoming geometry Multi, remains unchanged-SELECT ST_AsEWKT(ST_Multi(ST_GeomFromEWKT('MULTILINESTRING ((0 0, 10 10, 20 10),(30 30, 40 40, 50 40))'))); --Result MULTILINESTRING ((0 0, 10 10, 20 10), (30 30, 40 40, 50 40))

Related functions

206

Reference

Name
ST_RemovePoint Removes N th Point from a LineString. N index starts at 0.

Synopsis
varchar ST_RemovePoint(bytea Geometry, integer N);

Alias
RemovePoint

Description
Removes N th Point from a LineString or a MultiLineString. N index starts at 0. GeometryCollection with LineStrings supported

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsEWKT(ST_RemovePoint(ST_GeomFromEWKT('LINESTRING (0 0 15, 10 10 25, 20 10 35)'),0)); --Result LINESTRING (10 10 25, 20 10 35) SELECT ST_AsEWKT(ST_RemovePoint(ST_GeomFromEWKT('LINESTRING (0 0 15 -2, 10 10 25 -8, 20 10 35 -4)'),2)); --Result LINESTRING (0 0 15 -2, 10 10 25 -8) SELECT ST_AsEWKT(ST_RemovePoint(ST_GeomFromEWKT('MULTILINESTRING ((0 0, 10 10, 20 10),(30 30, 40 40, 50 40))'),5)); --Result MULTILINESTRING ((0 0, 10 10, 20 10), (30 30, 40 40)) SELECT ST_AsEWKT( ST_RemovePoint(ST_GeomFromEWKT(' GEOMETRYCOLLECTION(LINESTRING (0 0 15, 10 10 25, 20 10 35),POINT(0 0))'),2)); --Result GEOMETRYCOLLECTION (LINESTRING (0 0 15, 10 10 25), POINT (0 0 0))

Related functions
ST_AddPoint

207

Reference

Name
ST_Reverse Returns the geometry with the vertex order reversed.

Synopsis
geometry ST_Reverse(bytea Geometry);

Alias
Reverse

Description
Returns the geometry with the vertex order reversed.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
--3D LINESTRING SELECT ST_AsEWKT(G) as original, ST_AsEWKT(ST_Reverse(G)) as reverse from (SELECT ST_GeomFromEWKT('LINESTRING (0 0 15, 10 10 25, 20 10 35)') as G) as foo; original | reverse -----------------------------------------+----------------------------------------LINESTRING (0 0 15, 10 10 25, 20 10 35) | LINESTRING (20 10 35, 10 10 25, 0 0 15) --MULTILINESTRING SELECT ST_AsEWKT(Reverse(ST_GeomFromEWKT('MULTILINESTRING ((0 0, 10 10, 20 10),(30 30, 40 40, 50 40))'))); --Result MULTILINESTRING ((50 40, 40 40, 30 30), (20 10, 10 10, 0 0))

--GEOMETRYCOLLECTION SELECT ST_AsEWKT(G) as original, ST_AsEWKT(ST_Reverse(G)) as reverse from (SELECT ST_GeomFromEWKT('GEOMETRYCOLLECTION(POINT(2 2),POLYGON ((2 2, 4 2, 2 4, 2 2)))') as G) as foo; original | reverse ----------------------------------------------------------------+----------------------------------------------------------------GEOMETRYCOLLECTION (POINT (2 2), POLYGON ((2 2, 4 2, 2 4, 2 2))) |GEOMETRYCOLLECTION (POINT (2 2), POLYGON ((2 2, 2 4, 4 2, 2 2)))

Related functions
ST_ForceRHR

208

Reference

Name
ST_RotateX Rotates a geometry, an Angle (in radians), around the X axis.

Synopsis
bytea ST_RotateX(bytea Geometry, double AngleRadians);

Alias
RotateX

Description
Rotates a geometry, an Angle (in radians), around the X axis. In the following table transformation matrices and equations to transform the vertices are shown.

Transformation matrix

Equations to transform the vertices

ST_RotateX (geomA, rotRadians) is an abreviation for the method: ST_Affine(geomA, 1, 0, 0, 0, cos(rotRadians), -sin(rotRadians), 0, sin(rotRadians), cos(rotRadians), 0, 0, 0)

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
--Rotates 180 a 4D Point SELECT ST_AsEWKT(ST_RotateX(ST_GeomFromEWKT('POINT (1 2.5 3 4)'),pi())); --Result POINT (1 -2.5 -3 4) --Rotates 90 SELECT ST_AsEWKT(ST_RotateX(ST_GeomFromEWKT('LINESTRING (10 10 15, 5 2 10)'),pi()/2)); --Result LINESTRING (10 -15 10.000000000000002, 5 -10 2) --Same Rotation with ST_Affine SELECT ST_AsEWKT(ST_Affine(geomA, 1, 0, 0, 0, cos(rotRadians), -sin(rotRadians), 0, sin(rotRadians), cos(rotRadians), 0, 0, 0)) FROM (SELECT ST_GeomFromEWKT('LINESTRING (10 10 15, 5 2 10)') as geomA, pi()/2 as rotRadians) as foo; --Result LINESTRING (10 -15 10.000000000000002, 5 -10 2)

209

Reference

Related functions
ST_Affine, ST_RotateY, ST_RotateZ

210

Reference

Name
ST_RotateY Rotates a geometry, an Angle (in radians), around the Y axis.

Synopsis
bytea ST_RotateY(bytea Geometry, double AngleRadians);

Alias
RotateY

Description
Rotates a geometry, an Angle (in radians), around the Y axis. In the following table transformation matrices and equations to transform the vertices are shown.

Transformation matrix

Equations to transform the vertices

ST_RotateY (geomA, rotRadians) is an abreviation for the method: ST_Affine(geomA, cos(rotRadians), 0, sin(rotRadians), 0, 1, 0, -sin(rotRadians), 0, cos(rotRadians), 0, 0, 0)

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
--Rotates 180 a 4D Point SELECT ST_AsEWKT(ST_RotateY(ST_GeomFromEWKT('POINT (1 2.5 3 4)'),pi())); --Result POINT (-1 2.5 -3 4) --Rotates 90 SELECT ST_AsEWKT(ST_RotateY(ST_GeomFromEWKT('LINESTRING (10 10 15, 5 2 10)'),pi()/2)); --Result LINESTRING (15 10 -9.999999999999998, 10 2 -4.999999999999999) --Same Rotation with ST_Affine SELECT ST_AsEWKT(ST_Affine(geomA, cos(rotRadians), 0, sin(rotRadians), 0, 1, 0, sin(rotRadians), 0, cos(rotRadians), 0, 0, 0)) FROM (SELECT ST_GeomFromEWKT('LINESTRING (10 10 15, 5 2 10)') as geomA, pi()/2 as rotRadians) as foo; --Result LINESTRING (15 10 -9.999999999999998, 10 2 -4.999999999999999)

211

Reference

Related functions
ST_AffineST_RotateXST_RotateZ

212

Reference

Name
ST_RotateZ Rotates a geometry, an Angle (in radians), around the Z axis.

Synopsis
bytea ST_RotateZ(bytea Geometry, double AngleRadians);

Alias
RotateZ, ST_Rotate, Rotate

Description
Rotates a geometry, an Angle (in radians), around the Z axis. In the following table transformation matrices and equations to transform the vertices are shown.

Transformation matrix

Equations to transform the vertices

ST_RotateZ (geomA, rotRadians) is an abreviation for the method: ST_Affine(geomA, cos(rotRadians), -sin(rotRadians), 0, sin(rotRadians), cos(rotRadians), 0, 0, 0, 1, 0, 0, 0)

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
--Rotates 180 a 4D Point SELECT ST_AsEWKT(ST_RotateZ(ST_GeomFromEWKT('POINT (1 2.5 3 4)'),pi())); --Result POINT (-1 -2.5 3 4) --Rotates 90 SELECT ST_AsEWKT(ST_Rotate(ST_GeomFromEWKT('LINESTRING (10 10 15, 5 2 10)'),pi()/2)); --Result LINESTRING (-10 10 15, -2 5 10) --Same Rotation with ST_Affine SELECT ST_AsEWKT(ST_Affine(geomA, cos(rotRadians), -sin(rotRadians), 0, sin(rotRadians), cos(rotRadians), 0, 0, 0, 1, 0, 0, 0)) FROM (SELECT ST_GeomFromEWKT('LINESTRING (10 10 15, 5 2 10)') as geomA, pi()/2 as rotRadians) as foo; --Result LINESTRING (-10 10 15, -2 5 10)

213

Reference

Related functions
ST_Affine, ST_RotateX, ST_RotateY

214

Reference

Name
ST_Scale Scales the geometry to a new size by multiplying the coordinates by the factor of scale of the axis.

Synopsis
geometry ST_Scale(bytea Geometry, double XScale, double YScale, double ZScale); geometry ST_Scale(bytea Geometry, double XScale, double YScale);

Alias
Scale

Description
Scales the geometry to a new size by multiplying the coordinates by the factor of scale of the axis.

Transformation matrix

Equations to transform the vertices

ST_Scale (geomA, XScale, YScale, ZScale) is an abreviation for the method: ST_Affine(geomA, XFactor, 0, 0, 0, YFactor, 0, 0, 0, ZFactor, 0, 0, 0)

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsEWKT(ST_Scale(ST_GeomFromEWKT('POINT (10 10 10 4)'),0.5,1,2)); --Result POINT (5 10 20 4) SELECT ST_AsEWKT(ST_Scale(ST_GeomFromEWKT('LINESTRING (10 10, 5 2)'),2,4)); --Result LINESTRING (20 40, 10 8) --Same Transformation with ST_Affine SELECT ST_AsEWKT(ST_Affine(geomA, XFactor, 0, 0, 0, YFactor, 0, 0, 0, ZFactor, 0, 0, 0)) FROM (SELECT ST_GeomFromEWKT('LINESTRING (10 10, 5 2)') as geomA, 2 as XFactor, 4 as YFactor, 1 as ZFactor) as foo; --Result LINESTRING (20 40, 10 8)

215

Reference

Related functions
ST_Affine

216

Reference

Name
ST_Segmentize Splits a segment of a geometry if it is shorter than a given maximum Length. The distance is computed only in 2D.

Synopsis
geometry ST_Segmentize(bytea Geometry, double MaxLength);

Alias
Segmentize

Description
Splits a segment of a geometry if it is shorter than a given maximum Length. The distance is computed only in 2D. GeometryCollection supported

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsEWKT(ST_Segmentize(ST_GeomFromEWKT('LINESTRING (0 0 2, 0 10 4)'),5)); --Result LINESTRING (0 0 2, 0 5 3, 0 10 4) SELECT ST_AsEWKT(ST_Segmentize(ST_GeomFromEWKT('POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))'),8)); --Result POLYGON ((0 0, 0 8, 0 10, 8 10, 10 10, 10 2, 10 0, 2 0, 0 0))

Related functions
ST_Line_Substring

217

Reference

Name
ST_SetPoint Replaces the Nth Point of a Geometry for a new Point. N index starts at 0.

Synopsis
geometry ST_SetPoint(bytea Geometry, integer N, bytea Point);

Alias
SetPoint

Description
Replaces the Nth Point of a Geometry for a new Point. N index starts at 0. If the N index is out of range, the incoming geometry is returned unchanged.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

218

Reference

Examples
SELECT ST_AsEWKT(Line) as original, ST_AsEWKT(ST_SetPoint(Line,0,Point)) as NewPoint0, ST_AsEWKT(ST_SetPoint(Line,1,Point)) as NewPoint1 FROM (SELECT ST_GeomFromEWKT('LINESTRING (0 0, 10 10, 20 10)') as Line, ST_GeomFromEWKT('POINT (-5 5)') as Point) as foo; original | newpoint0 | newpoint1 --------------------------------+--------------------------------+------------------------------LINESTRING (0 0, 10 10, 20 10) | LINESTRING (-5 5, 10 10, 20 10) | LINESTRING (0 0, -5 5, 20 10)

SELECT ST_AsEWKT(ST_SetPoint(ST_GeomFromEWKT('MULTILINESTRING ((0 0, 10 10, 20 10),(30 30, 40 40, 50 40))'),5,ST_GeomFromEWKT('POINT (-5 5)'))); --Result MULTILINESTRING ((0 0, 10 10, 20 10), (30 30, 40 40, -5 5)) --Polygon SELECT ST_AsEWKT(ST_SetPoint(ST_GeomFromEWKT('POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))'),2,ST_GeomFromEWKT('POINT (-5 5)'))); --Result POLYGON ((0 0, 0 10, -5 5, 10 0, 0 0)) --MultiPoint SELECT ST_AsEWKT(ST_SetPoint(ST_GeomFromEWKT('MULTIPOINT (0 0, 0 10, 10 10, 10 0, 0 0)'),0,ST_GeomFromEWKT('POINT (-5 5)'))); st_asewkt ----------------------------------------------------MULTIPOINT ((-5 5), (0 10), (10 10), (10 0), (0 0)) (1 row)

--N index out of range SELECT ST_AsEWKT(ST_SetPoint(ST_GeomFromEWKT('LINESTRING (0 0, 10 10, 20 10)'),5,ST_GeomFromEWKT('POINT (-5 5)'))); --Result LINESTRING (0 0, 10 10, 20 10)

Related functions
ST_AddPoint

219

Reference

Name
ST_SetSRID Sets the Spatial Reference ID for a geometry,

Synopsis
geometry ST_SetSRID(bytea Geometry, integer SRID);

Alias
SetSRID

Description
Sets the Spatial Reference ID for a geometry, This function does not transform the geometry in any way.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsEWKT(ST_SetSRID(ST_GeomFromEWKT('POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))'),25830)); --Result SRID=25830;POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0)) SELECT ST_SRID(geomA) as origSRID,ST_SRID(ST_SetSRID(geomA,25830)) as newSRID from (SELECT ST_GeomFromEWKT('POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))') as geomA) as foo; origsrid | newsrid ----------+---------1 | 25830 (1 row)

Related functions
ST_SRID, ST_Transform

220

Reference

Name
ST_SnapToGrid Snaps a geometry to a grid defined by its cell size and origin.

Synopsis
geometry ST_SnapToGrid(bytea Geometry, double size); geometry ST_SnapToGrid(bytea Geometry, double sizeX, double sizeY); geometry ST_SnapToGrid(bytea Geometry, double originX, double originY, double sizeX, double sizeY); geometry ST_SnapToGrid(bytea Geometry, bytea OriginPoint, double sizeX, double sizeY, double sizeZ, double sizeM);

Alias
SnapToGrid

Description
Snaps a geometry to a grid defined by its cell size and origin. This method has four versions: First version snaps every coordinate by the same grid size. Second version just snaps X and Y coordinates. Third version defines the origin and size of the grid. It just snaps X and Y coordinates. Fourth version defines the origin by a Point. It snaps X,Y,Z and M coordinates. GeometryCollection supported

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

221

Reference

Examples
SELECT ST_AsEWKT(ST_SnapToGrid(ST_GeomFromEWKT('MULTIPOINT (0 0, 1.7 1.2, 0 10)'),0.5)); --Result MULTIPOINT (0 0, 1.5 1, 0 10) --3D MultiPoint SELECT ST_AsEWKT(ST_SnapToGrid(ST_GeomFromEWKT('MULTIPOINT (0 0 2, 0 10 6)'),5)); --Result MULTIPOINT (0 0 0, 0 10 5) --4D SELECT ST_AsEWKT(ST_SnapToGrid(ST_GeomFromEWKT('MULTIPOINT (0 0 2 2, 0 10 6 8)'),3)); --Result MULTIPOINT (0 0 3 3, 0 9 6 9) SELECT ST_AsEWKT(ST_SnapToGrid(ST_GeomFromEWKT('LINESTRING (0 0, 0 1, 0 2, 0 10)'),5)); --Result LINESTRING (0 0, 0 10) --ST_SnapToGrid(geomA,sizeX,sizeY) SELECT ST_AsEWKT(ST_SnapToGrid(ST_GeomFromEWKT('MULTIPOINT (0 0 2, 1.7 1.2 4, 0 10 4)'),0.5,1)); --Result MULTIPOINT ((0 0 2), (1.5 1 4), (0 10 4)) --ST_SnapToGrid(geom, originX, originY, sizeX, sizeY) SELECT ST_AsEWKT(ST_SnapToGrid(ST_GeomFromEWKT('MULTIPOINT (0 0 2, 1.7 1.2 4, 0 10 4)'), 1,1.4,0.5,1)); --Result MULTIPOINT ((0 0.4 2), (1.5 1.4 4), (0 10.4 4)) --ST_SnapToGrid(geomA, Origin_Point, sizeX, sizeY, sizeZ, SELECT ST_AsEWKT( ST_SnapToGrid( ST_GeomFromEWKT('POINT (0.1111 0.2222 2.5555 3.5555)'), ST_GeomFromEWKT('POINT(1 1 1 1)'), 0.1,0.01,0.001,1)); --Result POINT (0.1 0.22 2.555 4) sizeM)

Related functions
ST_Snap

222

Reference

Name
ST_Transform Returns a Geometry transformed to the specified spatial reference system.

Synopsis
varchar ST_Transform(bytea Geometry, integer SRID);

Alias
Transform

Description
Returns a Geometry transformed to the specified spatial reference system (SRID). This SRID must exist in the SPATIAL_REF_SYS table. The transformation is done through GeoTools library. ST_Transform actually reprojects and thus changes the coordinates of a geometry from one spatial reference system to another, while ST_SetSRID simply changes the SRID of the geometry

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 5.1.6

Examples
--Transform from ETRS89 UTM H30 to WGS84 long-lat SELECT ST_AsText(ST_Transform(ST_GeomFromText('POINT(729006.2060 4373499.8410 27.7760)',25830),4326)); --Result POINT (-0.3374115022027405 39.48063411917513 27.776)

Related functions
ST_SRID, ST_SetSRID

223

Reference

Name
ST_Translate Translates a geometry a certain offset along the axis X,Y,Z

Synopsis
geometry ST_Translate(bytea Geometry, double Tx, double Ty, double Tz); geometry ST_Translate(bytea Geometry, double Tx, double Ty);

Alias
Translate

Description
Translates a geometry a certain offset along the axis X,Y,Z

Transformation matrix

Equations to transform the vertices

ST_Translate (geomA, Tx, Ty, Tz) is an abreviation for the method: ST_Affine(geomA, 1, 0, 0, 0, 0, 1, 0, 0, 1, Tx, Ty, Tz)

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsEWKT(ST_Translate(ST_GeomFromEWKT('LINESTRING (0 0, 1 1, 0 10)'),10,20)); --Result LINESTRING (10 20, 11 21, 10 30) SELECT ST_AsEWKT(ST_Translate(ST_GeomFromEWKT('POINT (1 2 3 4)'),10,20,30)); --Result POINT (11 22 33 4) --Same Translate With ST_Affine SELECT ST_AsEWKT(ST_Affine(geomA, 1, 0, 0, 0, 0, 1, 0, 0, 1, Tx, Ty, Tz)) FROM (SELECT ST_GeomFromEWKT('POINT (1 2 3 4)') as geomA, 10 as Tx, 20 as Ty, 30 as Tz) as foo; --Result POINT (11 22 33 4)

Related functions
ST_Affine

224

Reference

Name
ST_TransScale Translates a geometry, and then scales it.

Synopsis
geometry ST_TransScale(bytea Geometry, double Tx, double Ty, double Tz, double Xscale, double Yscale, double Zscale); geometry ST_TransScale(bytea Geometry, double Tx, double Ty, double Xscale, double Yscale);

Alias
TransScale

Description
Translates a geometry, and then scales it.

Transformation matrix

Equations to transform the vertices

ST_TransScale (geomA, Tx, Ty, Tz, Xscale,Yscale,Zscale) is an abreviation for the method: ST_Affine(geomA, Xscale, 0, 0, 0, Yscale, 0, 0, 0, Zscale, Tx*Xscale, Ty*Yscale, Tz*Zscale)

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsEWKT(ST_TransScale(ST_GeomFromEWKT('POINT (1 1 1 4)'),2,3,4,100,200,300)); --Result POINT (300 800 1500 4)

Related functions
ST_Affine, ST_Scale, ST_Translate

225

Reference

Name
ST_NodeLine Returns a Line split at self intersection points, by adding nodes there.

Synopsis
geometry ST_NodeLine(bytea LineString);

Alias
NodeLine

Description
Returns a LineString split at self intersection points, by adding nodes there. This method supports LineString, MultiLineString or GeometryCollection geometries. In 3d or 4d geometries, new vertices will have Z or M=0.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
--Ex 1 SELECT ST_AsText(ST_NodeLine(ST_GeomFromText('LINESTRING (1 1, 2 3, 2 6, 6 6, 6 2, 0 2, 0 2)'))); --Result MULTILINESTRING ((1 1, 1.5 2), (1.5 2, 2 3, 2 6, 6 6, 6 2, 1.5 2), (1.5 2, 0 2)) --Ex 2 SELECT ST_AsText(ST_NodeLine(ST_GeomFromText('MULTILINESTRING ((2 1 5, 5 5 10), (6 2 2, 2 4 4))'))); --Result MULTILINESTRING ((2 1 5, 3.636363636363636 3.181818181818182 0), (3.636363636363636 3.181818181818182 0, 5 5 10), (6 2 2, 3.636363636363636 3.181818181818182 0), (3.636363636363636 3.181818181818182 0, 2 4 4))

226

Reference

GeomA

ST_Nodeline(GeomA)

GeomA

ST_Nodeline(GeomA)

Related functions
ST_CleanPolygon

227

Reference

Name
ST_CleanPolygon Cleans polygons o multipolygons to be topologically corrects. So, enforces them to be valid geometries.

Synopsis
geometry ST_CleanPolygon(bytea Polygon);

Alias
CleanPolygon

Description
Cleans polygons o multipolygons to be topologically corrects. So, enforces them to be valid geometries (ST_IsValid). OGC states the rules that define valid polygons. It is computed without tolerances.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
POLYGON 1. The Interior of every Polygon should be a connected point set.
SELECT ST_AsText( ST_CleanPolygon(ST_GeomFromText('POLYGON ((2 2, 2 6, 7 6, 7 2, 2 2),(2 2, 6 2, 7 4, 5 3, 6 2, 2 2))'))); --Result POLYGON ((6 2, 2 2, 2 6, 7 6, 7 4, 7 2, 6 2))

GeomA

ST_CleanPolygon(GeomA)

2. The boundary of a Polygon may intersect at a Point but only as a tangent (i.e. not on a line)

228

Reference

SELECT ST_AsText( ST_CleanPolygon(ST_GeomFromText('POLYGON ((2 2, 2 6, 7 6, 7 2, 2 2), (3 2, 3 3, 4 3, 4 2, 3 2))'))); --Result POLYGON ((2 2, 2 6, 7 6, 7 2, 4 2, 3 2, 2 2))

GeomA 3. A Polygon may not have cut lines, spikes or punctures:

ST_CleanPolygon(GeomA)

SELECT ST_AsText( ST_CleanPolygon(ST_GeomFromText('POLYGON ((3 2, 3 6, 7 6, 7 4, 8 4, 7 4, 7 2, 3 2))'))); --Result POLYGON ((3 2, 3 6, 7 6, 7 4, 7 2, 3 2))

GeomA

ST_CleanPolygon(GeomA)

4. Each hole should be a connected component of the Exterior.


SELECT ST_AsText( ST_CleanPolygon(ST_GeomFromText('POLYGON ((1 1, 1 4, 3 4, 3 1, 1 1), (4 2, 4 4, 6 4, 6 2, 4 2))'))); --Result MULTIPOLYGON (((1 1, 1 4, 3 4, 3 1, 1 1)), ((4 2, 4 4, 6 4, 6 2, 4 2)))

GeomA MULTIPOLYGON

ST_CleanPolygon(GeomA)

1. The interiors of 2 Polygons that are elements of a MultiPolygon may not intersect.

229

Reference

SELECT ST_AsText( ST_CleanPolygon(ST_GeomFromText('MULTIPOLYGON (((1 1, 1 4, 4 4, 4 1, 1 1)), ((3 2, 3 5, 6 5, 6 2, 3 2)))'))); --Result POLYGON ((4 2, 4 1, 1 1, 1 4, 3 4, 3 5, 6 5, 6 2, 4 2))

GeomA

ST_CleanPolygon(GeomA)

2. The Boundaries of any 2 Polygons that are elements of a MultiPolygon may not cross and may touch at only a finite number of points. (Note that crossing is prevented by assertion 1 above).
SELECT ST_AsText( ST_CleanPolygon(ST_GeomFromText('MULTIPOLYGON (((1 1, 1 4, 3 4, 3 1, 1 1)), ((3 2, 3 4, 5 4, 5 2, 3 2)))'))); --Result POLYGON ((3 4, 5 4, 5 2, 3 2, 3 1, 1 1, 1 4, 3 4))

GeomA

ST_CleanPolygon(GeomA)

The following example of cleaning a polygon is more complex . There are repeated vertexes, changes of direction etc, The resulting geometry is a MultiPolygon composed of three Polygons.
SELECT ST_AsText( ST_CleanPolygon(ST_GeomFromText('POLYGON ((13 8, 16 8, 13 8, 10 8, 8 6, 6 8, 2 4, 4 4, 4 6, 12 6, 16 8, 13 8), (10 7, 10.5 6, 11.5 7, 10 7))'))); --Result MULTIPOLYGON (((10.5 6, 8 6, 10 8, 13 8, 16 8, 12 6, 10.5 6), (10.5 6, 11.5 7, 10 7, 10.5 6)), ((4 6, 4 4, 2 4, 4 6)), ((4 6, 6 8, 8 6, 4 6)))

230

Reference

GeomA

ST_CleanPolygon(GeomA)

Related functions
ST_IsValid, ST_NodeLine, ST_BuildArea

231

Reference

Name
ST_Snap Snaps the vertices and segments of a Geometry to another Geometry's vertices. A snapping distance tolerance is used to control where snapping is performed.

Synopsis
geometry ST_Snap(bytea GeomA, bytea GeomB, double Tolerance);

Alias
Snap

Description
Snaps the vertices and segments of a Geometry to another Geometry's vertices. Improves robustness for overlay operations, by eliminating nearly parallel edges (which cause problems during noding and intersection calculation).

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
--Ex. 1 SELECT ST_AsText(ST_SNAP(A,B,2)) As C FROM ( SELECT ST_GeomFromText('POLYGON ((1 1, 1 4, 4.5 6.8, 4.6 0.3, 1 1))') As A, ST_GeomFromText('POLYGON ((6 2, 6 3, 8 3, 8 2, 6 2))') As B) as foo; --Result C ------------------------------------------------------POLYGON ((1 1, 1 4, 4.5 6.8, 6 3, 6 2, 4.6 0.3, 1 1)) --Ex. 2 SELECT ST_AsText(ST_SNAP(A,B,2)) As C FROM ( SELECT ST_GeomFromText('POLYGON ((1 1, 1 4, 4 4, 4 1, 1 1))') As A, ST_GeomFromText('POLYGON ((5 0.7, 7 4.8, 8 3, 8 2, 5 0.7))') As B) as foo; --Result: C POLYGON ((1 1, 1 4, 4 4, 5 0.7, 1 1))

232

Reference

Ex. 1 A,B

ST_Snap(A,B,2) as C

Ex. 2 A,B

ST_Snap(A,B,2) as C

Related functions
ST_SnapToGrid

9.5. Geometry Outputs


ST_AsBinary ................................................................................................................................ ST_AsEWKB ............................................................................................................................... ST_AsEWKT ............................................................................................................................... ST_AsHEXEWKB ........................................................................................................................ ST_AsGML .................................................................................................................................. ST_AsKML .................................................................................................................................. ST_AsText ................................................................................................................................... 234 236 237 238 239 240 242

233

Reference

Name
ST_AsBinary Returns the well-known binary (WKB) representation of a Geometry object.

Synopsis
bytea ST_AsBinary(bytea Geometry); bytea ST_AsBinary(bytea Geometry, varchar byteorder XDR/NDR);

Alias
AsBinary, ST_AsWKB, AsWKB

Description
Returns the well-known binary representation of a Geometry object. The byteorder parameter may be either NDR or XDR. If no encoding is specified, the default value is NDR. NDR indicates Network Data Representation, also known as little-endian encoding. XDR represents External Data Representation, also known as big-endian encoding. The WKB format, doesn't store the SRID. For that, use EWKB format The reverse function is ST_GeomFromEWKB

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.1.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.9.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.8.1 SQL-MM Part 3 5.1.37

234

Reference

Examples
PostgreSQL
--Get the WKB SELECT ST_AsBinary(ST_GeomFromText('POINT(5 5 10)',25830)); st_asbinary ----------------------------------------------------------------------------------\001\001\000\000\200\000\000\000\000\000\000\024@\000\000\000\000\000\000\024@ \000\000\000\000\000\000$@ (1 row) SELECT ST_AsBinary(ST_GeomFromText('POINT(5 5 10)'),'XDR'); st_asbinary ---------------------------------------------------------------------------------------------------------\000\200\000\000\001@\024\000\000\000\000\000\000@\024\000\000\000\000\000\000@$ \000\000\000\000\000\000 (1 row) SELECT ST_AsBinary(ST_GeomFromText('POINT(5 5 10)'),'NDR'); st_asbinary ---------------------------------------------------------------------------------------------------------\001\001\000\000\200\000\000\000\000\000\000\024@\000\000\000\000\000\000\024@ \000\000\000\000\000\000$@ (1 row)

H2
SELECT ST_AsBinary(ST_GeomFromText('POINT(1 1 1)',25830)); 0101000080000000000000f03f000000000000f03f000000000000f03f SELECT ST_AsBinary(ST_GeomFromText('POINT(1 1 1)'),'XDR'); 00800000013ff00000000000003ff00000000000003ff0000000000000 SELECT ST_AsBinary(ST_GeomFromText('POINT(1 1 1)'),'NDR'); 0101000080000000000000f03f000000000000f03f000000000000f03f

Related functions
ST_AsEWKB, ST_GeomFromWKB

235

Reference

Name
ST_AsEWKB Returns the Extended Well-Known Binary (EWKB) representation of a Geometry object.

Synopsis
bytea ST_AsEWKB(bytea Geometry); bytea ST_AsEWKB(bytea Geometry, text XDR/NDR);

Alias
AsEWKB

Description
Returns the Extended Well-Known Binary (EWKB) representation of a Geometry object. The EWKB format is a Postgis format that adds the Spatial Reference ID (SRID) to the OGC Well-Known Binary representation (WKB). The reverse function is ST_GeomFromEWKB

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
PostgreSQL
SELECT ST_AsEWKB(ST_GeomFromText('POINT(1 1 1)',25830)); st_asewkb ------------------------------------------------------------------------------------\001\001\000\000\240\346d\000\000\000\000\000\000\000\000\360?\000\000\000\000\000\000\360? \000\000\000\000\000\000\360? (1 row)

H2
SELECT ST_AsEWKB(ST_GeomFromText('POINT(1 1 1)',25830)); --Result 01010000a0e6640000000000000000f03f000000000000f03f000000000000f03f

Related functions
ST_GeomFromEWKB

236

Reference

Name
ST_AsEWKT Returns the Extended Well-Known Text representation (EWKT) from a geometry object.

Synopsis
varchar ST_AsEWKT(bytea Geometry);

Alias
AsEWKT

Description
Returns the Extended Well-Known Text (EWKT) representation of a Geometry object. The EWKT format is a Postgis format that adds the Spatial Reference ID (SRID) to the OGC Well-Known Text representation (WKT). The reverse function is ST_GeomFromEWKT

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsEWKT(ST_GeomFromText('POINT(1 1 1)',25830)); --Result SRID=25830;POINT (1 1 1)

Related functions
ST_GeomFromEWKT, ST_AsText

237

Reference

Name
ST_AsHEXEWKB Returns the Extended Well-Known Binary (EWKB) representation, in hexadecimal, of a Geometry object.

Synopsis
varchar ST_AsHEXEWKB(bytea Geometry); varchar ST_AsHEXEWKB(bytea Geometry, varchar byteorder XDR/NDR);

Alias
AsHEXEWKB

Description
Returns the Extended Well-Known Binary (EWKB) representation, in hexadecimal, of a Geometry object. The byteorder parameter may be either NDR or XDR. If no encoding is specified, the default value is NDR. NDR indicates Network Data Representation, also known as little-endian encoding. XDR represents External Data Representation, also known as big-endian encoding.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsHEXEWKB(ST_GeomFromText('POINT(1 1 1)',25830)); st_ashexewkb -------------------------------------------------------------------01010000A0E6640000000000000000F03F000000000000F03F000000000000F03F (1 row) SELECT ST_AsHEXEWKB(ST_GeomFromText('POINT(1 1 1)',25830),'XDR'); --Result 00A0000001000064E63FF00000000000003FF00000000000003FF0000000000000

Related functions
ST_AsBinary

238

Reference

Name
ST_AsGML Returns the Geography Markup Language (GML) representation of a Geometry object.

Synopsis
varchar ST_AsGML(bytea Geometry);

Alias
AsGML

Description
Returns the GML representation of a Geometry object. The GML supported version is 2. For a full description of GML geometries, refer to http://www.opengeospatial.org/standards/gml [http:// www.opengeospatial.org/standards/gm]

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 5.1.39

Examples
SELECT ST_AsGML(ST_GeomFromText('POINT(1 1 1)',25830)); <gml:Point srsName="EPSG:25830"> <gml:coordinates> 1.0,1.0,1.0 </gml:coordinates> </gml:Point>

SELECT ST_AsGML(ST_GeomFromEWKT('SRID=25830;POLYGON ((1 1, 1 3, 2 4, 3 3, 1 1))')); <gml:Polygon> <gml:outerBoundaryIs> <gml:LinearRing> <gml:coordinates> 1.0,1.0 1.0,3.0 2.0,4.0 3.0,3.0 1.0,1.0 </gml:coordinates> </gml:LinearRing> </gml:outerBoundaryIs> </gml:Polygon>

Related functions
ST_GeomFromGML

239

Reference

Name
ST_AsKML Returns the Keyhole Markup Language (KML) representation of a Geometry object.

Synopsis
varchar ST_AsKML(bytea Geometry); varchar ST_AsKML(double version, bytea Geometry); varchar ST_AsKML(double version, bytea Geometry, integer precision);

Alias
AsKML

Description
Returns the Keyhole Markup Language (KML) representation of a Geometry object. The input geometries must have an SRID. The resulting KML geometry will have SRID 4326 assigned, if it necessary the function ST_Transform is used automatically to convert geometries to EPSG:4326. JASPA only supports KML version 2.1. The optional parameter version must be a number between 2 and 3. Otherwise, it throws an error. The parameter precision is unused in JASPA. It is only mantained for PostGIS compatibility.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

240

Reference

Examples
--3D POINT SELECT ST_AsKML(ST_GeomFromText('POINT(-5.843868 43.360758 250)',4326)); --Result: <kml:Point xmlns:kml="http://earth.google.com/kml/2.1"> <kml:coordinates>-5.843868,43.360758</kml:coordinates> </kml:Point>

--2D POLYGON SELECT ST_AsKML(ST_GeomFromText('POLYGON(( -5.850379847879675 43.35970362178223, -5.848336797975651 43.36161117272741, -5.850411866073801 43.36311451294508, -5.853216861450062 43.36175621008758, -5.850379847879675 43.35970362178223 ))',4326)); --Result: <kml:Polygon xmlns:kml="http://earth.google.com/kml/2.1"> <kml:outerBoundaryIs> <kml:LinearRing> <kml:coordinates>-5.850379847879675,43.35970362178223 -5.848336797975651,43.36161117272741 -5.850411866073801,43.36311451294508 -5.853216861450062,43.36175621008758 -5.850379847879675,43.35970362178223 </kml:coordinates> </kml:LinearRing> </kml:outerBoundaryIs> </kml:Polygon>

Related functions
ST_GeomFromKML

241

Reference

Name
ST_AsText Returns the Well-known Text Representation of a geometric object

Synopsis
varchar ST_AsText(bytea Geometry);

Alias
AsText

Description
Returns the Well-known Text Representation of a geometric object ST_AsText is the reverse of ST_GeomFromText.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.1.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.10.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.8.1 SQL-MM Part 3 5.1.35

Examples
--The following example shows the use of the AsText function to extract the name and textual representation of Geometry of all countries whose names begin with the letter K. SELECT Name, AsText(Location) FROM Countries WHERE Name LIKE K%;

SELECT ST_AsText('01010000A0E6640000000000000000F03F000000000000F03F000000000000F03F'); --Result POINT (1 1 1)

Related functions
ST_GeomFromText

9.6. Spatial Relationships and Measurements


ST_Area ...................................................................................................................................... ST_Azimuth ................................................................................................................................. ST_Centroid ................................................................................................................................. ST_Contains ................................................................................................................................. ST_ContainsProperly ..................................................................................................................... ST_Covers ................................................................................................................................... ST_CoveredBy ............................................................................................................................. 244 245 246 248 250 252 254

242

Reference

ST_Crosses .................................................................................................................................. ST_Disjoint .................................................................................................................................. ST_Distance ................................................................................................................................. ST_HausdorffDistance .................................................................................................................... ST_Distance_Sphere ...................................................................................................................... ST_Distance_Spheroid ................................................................................................................... ST_DWithin ................................................................................................................................. ST_Equals .................................................................................................................................... ST_Intersects ................................................................................................................................ ST_Length ................................................................................................................................... ST_Length3D ............................................................................................................................... ST_Length_Spheroid ...................................................................................................................... ST_Length2D_Spheroid ................................................................................................................. ST_Length3D_Spheroid ................................................................................................................. ST_OrderingEquals ........................................................................................................................ ST_Overlaps ................................................................................................................................. ST_Perimeter ................................................................................................................................ ST_PointOnSurface ....................................................................................................................... ST_Relate .................................................................................................................................... ST_Touches ................................................................................................................................. ST_Within ................................................................................................................................... ST_MultiCentroid .......................................................................................................................... ST_PointOnBoundary ....................................................................................................................

255 258 260 262 264 265 267 268 269 271 272 273 275 277 279 280 282 283 285 286 288 290 291

243

Reference

Name
ST_Area Returns the area of a Polygon or a MultiPolygon.

Synopsis
double ST_Area(bytea Geometry);

Alias
Area

Description
Returns the area of a Polygon or a MultiPolygon. Area units are taken from the spatial reference system of this geometry. The area is calculated in 2D. This function supports GeometryCollection, it will add the area of all polygons.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.9.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.14.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.12.2 SQL-MM Part 3 8.1.2 - 9.5.3

Examples
--2D Polygon SELECT ST_Area(ST_GeomFromText('MULTIPOLYGON (((0 0, 0 10, 10 10, 10 0, 0 0),(2 2, 2 4, 4 4, 4 2, 2 2)))',-1)); --Result: 96.0 --3D Polygon SELECT ST_Area(ST_GeomFromEWKT('SRID=-1;MULTIPOLYGON (((0 0 5, 0 10 8, 10 10 9, 10 0 2, 0 0 5), (2 2 1, 2 4 1, 4 4 1, 4 2 1, 2 2 1)))')); --Result: 96.0 --GEOMETRYCOLLECTION SELECT ST_Area(ST_GeomFromText('GEOMETRYCOLLECTION(POLYGON((0 0, 0 10, 10 10, 10 0, 0 0)),POLYGON((2 2, 2 4, 4 4, 4 2, 2 2)),POINT(5 5))',-1)); --Result: 104.0

Related functions

244

Reference

Name
ST_Azimuth Returns the azimuth between two points.

Synopsis
geometry ST_Azimuth(bytea PointA, bytea PointB);

Alias
Azimuth

Description
Returns the azimuth between two points. Azimuth is defined as a horizontal angle measured clockwise from North to a base direction line. The azimuth angle is returned in radians. Input geometries must be points.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_Azimuth(ST_GeomFromText('POINT(0 0)'),ST_GeomFromText('POINT(5 0)')) as anglerad; anglerad ----------------1.5707963267949 SELECT ST_Azimuth(ST_GeomFromText('POINT(0 0)'),ST_GeomFromText('POINT(5 0)'))*180/pi() as angledegrees; angledegrees -------------90

Related functions

245

Reference

Name
ST_Centroid Returns a point, which is the centroid (geometric center) of a geometry, which may lie outside the geometry

Synopsis
geometry ST_Centroid(bytea Geometry);

Alias
Centroid

Description
Returns the centroid (geometric center) of a geometry, which may lie outside the geometry. The centroid is equal to the centroid of the set of component Geometries of highest dimension (since the lowerdimension geometries contribute zero "weight" to the centroid) The centroid will have the same SRID as the incoming geometry.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.9.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.14.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.12.2 SQL-MM Part 3 8.1.4 - 9.5.5

Examples
SELECT ST_AsEWKT(ST_Centroid(ST_GeomFromText('MULTIPOINT (0 0, 8 0, 5 10, 10 10, 15 20, 10 20)',25830))); --Result SRID=25830;POINT (8 10) SELECT ST_AsEWKT(ST_Centroid(ST_GeomFromText('POLYGON((0 0 2, 0 10 4, 10 10 5, 10 0 5, 0 0 2))'))); --Result POINT (5 5)

MULTIPOINT CENTROID

LINESTRING CENTROID

246

Reference

POLYGON CENTROID

GEOMETRY COLLECTION CENTROID

This example extracts the Centroid of a set of Parcels. The parcels are stored in the parcels table created with a CREATE TABLE statement. The INSERT INTO statements that follow insert each one of the parcels geometries. CREATE TABLE "parcels"(id serial PRIMARY KEY); SELECT AddGeometryColumn ('parcels','geom',-1,'POLYGON',2); INSERT INTO "parcels"("geom") SELECT (ST_GeomFromText('POLYGON((6 14, 7.5 15, 10 11, 8 10, 6 14))')); INSERT INTO "parcels"("geom") SELECT (ST_GeomFromText('POLYGON((7 12, 4 10, 3 12, 6 14, 7 12))')); INSERT INTO "parcels"("geom") SELECT (ST_GeomFromText('POLYGON((5 8, 4 10, 7 12, 8 10, 5 8))')); SELECT ST_AsText(ST_Centroid("geom")) from (SELECT "geom" from "parcels") as foo; SELECT DropGeometryTable('parcels'); --Result st_astext ----------------------------------------------------MULTIPOINT ((7.923423423423424 12.432432432432432)) MULTIPOINT ((5 12)) MULTIPOINT ((6 10))

Parcels

ST_Multicentroid

Related functions
ST_MultiCentroid, ST_PointOnSurface

247

Reference

Name
ST_Contains Tests if a Geometry A spatially contains another Geometry B.

Synopsis
boolean ST_Contains(bytea GeomA, bytea GeomB);

Alias
Contains

Description
Tests if a Geometry A spatially contains another Geometry B, returns TRUE if so. The ST_Contains predicate has the following equivalent definitions: Geometry A contains Geometry B if no points of B lie in the exterior of A, and at least one point of the interior of B lies in the interior of A. ST_Contains is the inverse of ST_Within. a.Contains(b) - b.Within(a) In mathematical terms: a.Contains(b) - (I(a)I(b) ) (E(a)I(b) =) (E(a)B(b) =) ) - a.Relate(b, T*****FF*) The DE-9IM Intersection Matrix for the two geometries matches [T*****FF*] Consequently and subtly, a LineString which is completely contained in the boundary of a Polygon is not considered to be contained in that Polygon because they don't share any interior points. This method does not support GeometryCollection arguments

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.1.2 , 2.1.13.3 OGC SFS for SQL. 1.1.0 (2005) 7.2.19.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.8.1 SQL-MM Part 3 5.1.31

Examples
--Line-Point SELECT ST_Contains(Line,Point) from (SELECT ST_GeomFromText('LINESTRING (0 0, 10 10, 10 5, 15 10)') as Line, ST_GeomFromText('POINT (5 5)') as Point)as foo; --Result TRUE

ST_Contains(A,B) returns True in the following situations

248

Reference

LINESTRING - POINT

LINESTRING - LINESTRING

POLYGON - MULTIPOINT

POLYGON - LINESTRING

POLYGON - POLYGON

ST_Contains(A,B) returns False in the following situations

LINESTRING - POINT

POLYGON - LINESTRING

POLYGON - POLYGON

Related functions
ST_ContainsProperly, ST_Covers, ST_Relate

249

Reference

Name
ST_ContainsProperly Tests if a Geometry A spatially contains properly another Geometry B.

Synopsis
boolean ST_ContainsProperly(bytea GeomA, bytea GeomB);

Alias
ContainsProperly

Description
Tests if a Geometry A spatially contains properly another Geometry B, returns TRUE if so. The ST_ContainsProperly predicate has the following equivalent definitions: Geometry A containsProperly Geometry B iff all points of B lie in the interior of A. The DE-9IM Intersection Matrix for the two geometries matches [T**FF*FF*] This method does not support GeometryCollection arguments

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_Contains(Polygon,Polygon),ST_ContainsProperly(Polygon,Polygon) from (SELECT ST_GeomFromText('POLYGON ((10 30, 0 10, 30 20, 30 30, 20 40, 10 30))') as Polygon) as foo; st_contains | st_containsproperly -------------+--------------------t | f

SELECT ST_ContainsProperly(LineA,LineB) from (SELECT ST_GeomFromText('LINESTRING (40 50, 120 90, 200 90)') as LineA, ST_GeomFromText('LINESTRING (120 90, 180 90)') as LineB) as foo; st_containsproperly --------------------t

ST_ContainsProperly(A,B) returns True in the following situations

250

Reference

LINESTRING - LINESTRING

POLYGON - LINESTRING

POLYGON - POLYGON

ST_ContainsProperly(A,B) returns False in the following situations

POLYGON - POLYGON

POLYGON - LINESTRING

POLYGON - POLYGON

Related functions
ST_Contains, ST_Relate

251

Reference

Name
ST_Covers Tests if a Geometry A spatially covers another Geometry B.

Synopsis
boolean ST_Covers(bytea GeomA, bytea GeomB);

Alias
Covers

Description
Tests if a Geometry A spatially covers another Geometry B, returns TRUE if so. The covers predicate has the following equivalent definitions: Geometry A covers Geometry B iff no points of B lie in the exterior of A. Every point of B is a point of A. The DE-9IM Intersection Matrix for the two geometries is T*****FF* or *T****FF* or ***T**FF* or ****T*FF* The reverse function of ST_Covers is ST_CoveredBy This method does not support GeometryCollection arguments

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_Contains(PolyA,LineB), ST_ContainsProperly(PolyA,LineB),ST_Covers(PolyA,LineB) from (SELECT ST_GeomFromText('POLYGON ((10 30, 6 15, 30 20, 30 30, 20 40, 10 30))') as PolyA, ST_GeomFromText('LINESTRING (10 30, 15 35)') as LineB) as foo; st_contains | st_containsproperly | st_covers -------------+---------------------+----------f | f | t

252

Reference

ST_Contains(PolyA,LineB) FALSE

= ST_ContainsProperly = FALSE

ST_Covers = TRUE

Related functions
ST_Contains,ST_ContainsProperly, ST_CoveredBy, ST_Relate

253

Reference

Name
ST_CoveredBy Tests if a Geometry A is covered by Geometry B.

Synopsis
boolean ST_CoveredBy(bytea GeomA, bytea GeomB);

Alias
CoveredBy

Description
Tests if a Geometry A is covered by Geometry B, returns TRUE if so. Geometry A is covered by Geometry B iff every point of A is a point of B. The DE-9IM Intersection Matrix for the two geometries is [T*F**F***] or [*TF**F***] or [**FT*F***] or [**F*TF***] The reverse function of ST_Covers is ST_CoveredBy [ST_Covers(A,B) =ST_CoveredBy[B,A] This method does not support GeometryCollection arguments

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_CoveredBy(Polygon,Line) as CoveredByPolygon_Line, ST_CoveredBy(Line,Polygon) CoveredByLine_Polygon, ST_Covers(Polygon,Line) as CoversPolygon_Line FROM (SELECT ST_GeomFromText('POLYGON ((10 30, 0 10, 30 20, 30 30, 20 40, 10 30))') as Polygon, ST_GeomFromText('LINESTRING (12 22, 16 25, 13 29, 13 29)') as Line) as foo; coveredbypolygon_line | coveredbyline_polygon | coverspolygon_line -----------------------+-----------------------+-------------------f | t | t

Related functions
ST_Covers, ST_Relate

254

Reference

Name
ST_Crosses Tests if a Geometry A crosses a Geometry B, returns True if so.

Synopsis
boolean ST_Crosses(bytea GeomA, bytea GeomB);

Alias
Crosses

Description
Returns true if Geometry A crosses a Geometry B. The crosses predicate has the following equivalent definitions: The geometries have some but not all interior points in common. In mathematical terms: a.Crosses(b) - (dim(I(a) I(b)) < max(dim(I(a)), dim(I(b)))) (a b a ) (a b b) The DE-9IM Intersection Matrix for the two geometries is: T*T****** (for P/L, P/A, and L/A situations) T*****T** (for L/P, L/A, and A/L situations) 0******** (for L/L situations) For any other combination of dimensions this predicate returns false. The SFS defined this predicate only for P/L, P/A, L/L, and L/A situations. JTS extends the definition to apply to L/P, A/P and A/L situations as well. This makes the relation symmetric. The term P is used to refer to 0 dimensional geometries (Points and MultiPoints), L is used to refer to one-dimensional geometries (LineStrings and MultiLineStrings) and A is used to refer to twodimensional geometries (Polygons and MultiPolygons).

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.1.2 , 2.1.13.3 OGC SFS for SQL. 1.1.0 (2005) 7.2.19.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.8.1 SQL-MM Part 3 5.1.29

255

Reference

Examples
--P/L SELECT ST_Crosses(MPoint,Line) as CrossesPL,ST_Crosses(Line,MPoint) as CrossesLP,ST_Relate(MPoint,Line) from (SELECT ST_GeomFromText('LINESTRING (10 15, 10 27, 20 20, 25 30)') as Line, ST_GeomFromText('MULTIPOINT (10 30, 15 20, 10 20, 20 25, 17 23)') as MPoint) as foo; crossespl | crosseslp | st_relate -----------+-----------+----------t | t | 0F0FFF102 --P/A SELECT ST_Crosses(MPoint,Poly) as CrossesPA,ST_Crosses(Poly,MPoint) as CrossesAP,ST_Relate(MPoint,Poly) from (SELECT ST_GeomFromText('POLYGON ((10 30, 5 10, 30 20, 30 30, 20 40, 10 30))') as Poly, ST_GeomFromText('MULTIPOINT (5 30, 15 20)') as MPoint) as foo; crossespa | crossesap | st_relate -----------+-----------+----------t | t | 0F0FFF212 --L/A SELECT ST_Crosses(Line,Poly) as CrossesLA,ST_Crosses(Poly,Line) as CrossesAL,ST_Relate(Line,Poly) from (SELECT ST_GeomFromText('POLYGON ((10 30, 5 10, 30 20, 30 30, 20 40, 10 30))') as Poly, ST_GeomFromText('LINESTRING (0 20, 15 25, 20 30, 35 25, 35 25)') as Line) as foo; crossesla | crossesal | st_relate -----------+-----------+----------t | t | 101FF0212 --L/L SELECT ST_Crosses(LA,LB) as CrossesLL,ST_Crosses(LB,LA) as CrossesLL2,ST_Relate(LA,LB) from (SELECT ST_GeomFromText('LINESTRING (0 20, 15 25, 20 30, 35 25)') as LA, ST_GeomFromText('LINESTRING (10 35, 5 25, 15 20, 15 10)') as LB) as foo; crossesll | crossesll2 | st_relate -----------+------------+----------t | t | 0F1FF0102

P/L

P/A

L/A

L/L

256

Reference

Related functions
ST_Crosses, ST_Relate

257

Reference

Name
ST_Disjoint Tests if a Geometry is spatially disjoint from another Geometry.

Synopsis
boolean ST_Disjoint(bytea GeomA, bytea GeomB);

Alias
Disjoint

Description
Tests if a Geometry is spatially disjoint from another Geometry, retuns TRUE if so. The disjoint predicate has the following equivalent definitions: The two geometries have no point in common In mathematical terms: a.Disjoint(b) - a b = Expressed in terms of the DE-9IM: a.Disjoint(b) - (I(a)I(b) = ) (I(a) B(b) = ) (B(a) I(b) = ) (B(a) B(b) = ) The DE-9IM Intersection Matrix is: [FF*FF****] This method does not support GeometryCollection arguments

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.1.2 , 2.1.13.3 OGC SFS for SQL. 1.1.0 (2005) 7.2.19.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.8.1 SQL-MM Part 3 5.1.26

Examples
SELECT ST_Disjoint(ga,gb) from (SELECT ST_GeomFromText('POLYGON ((10 30, 0 10, 30 20, 30 30, 20 40, 10 30))') as ga, ST_GeomFromText('POLYGON ((40 30, 40 20, 60 40, 50 40, 40 30))') as gb) as foo; st_disjoint ------------t SELECT ST_Disjoint(ga,gb) from (SELECT ST_GeomFromText('POLYGON ((3 3, 3 8, 8 8, 8 3, 3 3))') as ga, ST_GeomFromText('POLYGON ((1 1, 1 6, 5 6, 5 1, 1 1))') as gb) as foo; st_disjoint ------------f

258

Reference

Related functions
ST_Intersects, ST_Relate

259

Reference

Name
ST_Distance Returns the shortest distance between two geometries.

Synopsis
double ST_Distance(bytea GeomA, bytea GeomB);

Alias
Distance

Description
Returns the shortest distance between two geometries. It is calculated in 2d. The resulting distance will be in the units of the incoming geometries. This function supports GeometryCollections

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.1.3 OGC SFS for SQL. 1.1.0 (2005) 7.2.20.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.8.1 SQL-MM Part 3 5.1.23

Examples
SELECT ST_Distance(ga,gb) from (SELECT ST_GeomFromText('POINT(5 4 2 8)') as ga, ST_GeomFromText('POINT(8 6 10 2)') as gb) as foo; --Result 3.605551275463989 SELECT ST_Distance(ga,gb) from (SELECT ST_GeomFromText('POLYGON ((10 30, 0 10, 30 20, 30 30, 20 40, 10 30))') as ga, ST_GeomFromText('GEOMETRYCOLLECTION (POINT (40 30), LINESTRING (50 40, 70 20, 70 10, 70 10, 70 10))') as gb) as foo; --Result 10.0 --Distance Barcelona-Paris degrees SELECT ST_Distance(Barcelona,Paris) as Dist_degrees from (SELECT ST_GeomFromText('POINT(2.183333 41.383333)',4326) as Barcelona, ST_GeomFromText('POINT(2.350833 48.856667)',4326) as Paris) as foo; dist_degrees -----------------7.47521085492282

--Distance Barcelona-Paris meters (SRID 25831 UTM ETRS89 H31) SELECT ST_Distance(ST_Transform(Barcelona,25831),ST_Transform(Paris,25831)) as Dist_UTM from (SELECT ST_GeomFromText('POINT(2.183333 41.383333)',4326) as Barcelona, ST_GeomFromText('POINT(2.350833 48.856667)',4326) as Paris) as foo; dist_utm -----------------830348.883136392

260

Reference

Related functions
ST_Distance_Sphere,ST_Distance_Spheroid

261

Reference

Name
ST_HausdorffDistance Returns an approximation to the Hausdorff distance between two geometries. It offers a measure of dissimilarity between the geometries.

Synopsis
double ST_HausdorffDistance(bytea GeomA, bytea GeomB); double ST_HausdorffDistance(bytea GeomA, bytea GeomB, double densityFrac);

Alias
HausdorffDistance

Description
This algorithm computes the Hausdorff distance restricted to discrete points for one of the geometries. It is an approximation to the Hausdorff Distance based on a discretization of the input Geometry. The points can be either the vertices of the geometries, or the geometries with line segments densified by a given fraction (if the parameter densityFrac is specified). Fraction must be in range (0.0 - 1.0)

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_HausdorffDistance( ST_GeomFromText('POLYGON ((1.4 1, 2 4, 4 4, 3 1, 1.4 1))'), GeomFromText('POLYGON ((1 1, 2 4, 4 4, 3 2, 1 1))')); --Result 0.8944271909999159 SELECT ST_HausdorffDistance( ST_GeomFromText('POLYGON ((1.5 1.3, 2 3, 4 3, 3 1.3, 1.5 1.3))'), GeomFromText('POLYGON ((1 1.5, 2 5, 4 3, 3 1.6, 1 1.5))'),0.5); --Result 2.0

262

Reference

ST_HausdorffDistance( A, B) = 0.8944

ST_HausdorffDistance( A, B, 0.5 ) = 2

Related functions
ST_Distance, ST_Equals

263

Reference

Name
ST_Distance_Sphere Returns distance between 2 lat/long points. It is the great-circle distance, also known as or orthodromic, which is the shortest distance between any two points on the surface of a sphere measured along a path on the surface of the sphere

Synopsis
double ST_Distance_Sphere(bytea PointA, bytea PointB);

Alias
Distance_Sphere

Description
Returns distance between 2 lat/long points. It is the great-circle distance, also known as or orthodromic, which is the shortest distance between any two points on the surface of a sphere measured along a path on the surface of the sphere. Earth radius 6370986.884258304 Distance is calculated by the harvesine formula. See Wikipedia great circle distance [http://en.wikipedia.org/wiki/ Great-circle_distance] for more information.

Where is the spherical distance, S S are the start point Latitude and Longitude, F F are the final point Latitude and Longitude. And finally to obtain the linear distance, the next equation is applied (r = Earth radius 6370986.884258304):

This function only works with Points

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_Distance_Sphere(Barcelona,Paris) from (SELECT ST_GeomFromText('POINT(2.183333 41.383333)',4326) as Barcelona, ST_GeomFromText('POINT(2.350833 48.856667)',4326) as Paris) as foo; st_distance_sphere -------------------831098.439081409

Related functions
ST_Distance,ST_Distance_Spheroid

264

Reference

Name
ST_Distance_Spheroid Returns the shortest distance between 2 lat/long points, using a particular spheroid

Synopsis
PostgreSQL

double ST_Distance_Spheroid(bytea PointA, bytea PointB, integer SRID); double ST_Distance_Spheroid(bytea PointA, bytea PointB); double ST_Distance_Spheroid(bytea PointA, bytea PointB, varchar WKT_Spheroid);

H2

double ST_Distance_SpheroidEx(bytea PointA, bytea PointB, integer SRID); double ST_Distance_Spheroid(bytea PointA, bytea PointB); double ST_Distance_Spheroid(bytea PointA, bytea PointB, varchar WKT_Spheroid);

Alias
Distance_Spheroid

Description
Returns the shortest distance between 2 lat/long points, using a particular spheroid. This spheroid can be given by the SRID or by the text, if it's not given this function searches at the points SRID. The well-known text representation of spatial reference systems provides a standard textual representation for spatial reference system information.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

265

Reference

Examples
SELECT ST_Distance_Sphere(Barcelona,Paris), ST_Distance_Spheroid(Barcelona,Paris), ST_Distance(ST_Transform(Barcelona,25831),ST_Transform(Paris,25831)) as Dist_UTM from (SELECT ST_GeomFromText('POINT(2.183333 41.383333)',4326) as Barcelona, ST_GeomFromText('POINT(2.350833 48.856667)',4326) as Paris) as foo;

st_distance_sphere | st_distance_spheroid | dist_utm --------------------+----------------------+-----------------831098.439081409 | 830646.42674443 | 830348.883136392

--Calculation of distance in different ellipsoids --H2 SELECT ST_Distance_Spheroid(ga,gb) as distance_hayford1924, ST_Distance_SpheroidEx(ga,gb,25830) as distance_grs80 , ST_Distance_Spheroid(ga,gb,'SPHEROID["WGS 84",6378137,298.257223563]') as distance_wgs84 from (SELECT ST_GeomFromText('POINT(-3.52 41.0)',23030) as ga, ST_GeomFromText('POINT(2.33 48.86)',23030) as gb) as foo; --PostgreSQL SELECT ST_Distance_Spheroid(ga,gb) as distance_hayford1924, ST_Distance_Spheroid(ga,gb,25830) as distance_grs80 , ST_Distance_Spheroid(ga,gb,'SPHEROID["WGS 84",6378137,298.257223563]') as distance_wgs84 from (SELECT ST_GeomFromText('POINT(-3.52 41.0)',23030) as ga, ST_GeomFromText('POINT(2.33 48.86)',23030) as gb) as foo; --Result distance_hayford1924 | distance_grs80 | distance_wgs84 ----------------------+------------------+-----------------987364.755996404 | 987329.984551754 | 987329.984556481

Related functions
ST_Distance,ST_Distance_Sphere

266

Reference

Name
ST_DWithin Tests if two geometries are within a specified distance. Returns True if so, otherwise returns False.

Synopsis
boolean ST_DWithin(bytea GeomA, bytea GeomB, double Distance);

Alias
ST_DWithin

Description
Tests if two geometries are within a specified distance. Returns True if so, otherwise returns False. Distance units are those of the geometries.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_Distance(A,B) as distance, ST_DWithin(A,B,5) as within5 , ST_DWithin(A,B,3) within3 FROM (SELECT ST_GeomFromText('POLYGON ((2 2, 2 6, 4 6, 4 2, 2 2))') as A, ST_GeomFromText('POLYGON ((7 9, 7 11, 10 11, 10 9, 7 9))') as B ) as foo; --Result distance | within5 | within3 ------------------+---------+--------4.24264068711928 | t | f

Related functions
ST_Distance

267

Reference

Name
ST_Equals Tests if a Geometry is spatially equal to another Geometry, returns True if so.

Synopsis
boolean ST_Equals(bytea GeomA, bytea GeomB);

Alias
Equals

Description
Tests if a Geometry is spatially equal to another Geometry, returns True if so. The DE-9IM Intersection Matrix for the two geometries is T*F**FFF* Note that this method computes topologically equality, not structural or vertex-wise equality (use ST_OrderingEquals for that). GeometryCollections are unsupported

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.1.2 , 2.1.13.3 OGC SFS for SQL. 1.1.0 (2005) 7.2.19.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.8.1 SQL-MM Part 3 5.1.24

Examples
SELECT ST_Equals(ga,gb) from (SELECT ST_GeomFromText('LINESTRING (0 0, 10 10, 10 5, 15 10)') as ga, ST_GeomFromText('LINESTRING (15 10, 10 5, 10 10, 5 5, 0 0)') as gb) as foo; --Result TRUE SELECT ST_Equals(ga,gb) from (SELECT ST_GeomFromText('LINESTRING (0 0 8, 10 10 2)') as ga, ST_GeomFromText('LINESTRING (10 10 4, 0 0 2)') as gb) as foo; --Result TRUE

Related functions
ST_OrderingEquals

268

Reference

Name
ST_Intersects Tests if a Geometry spatially intersects another Geometry.

Synopsis
boolean ST_Intersects(bytea GeomA, bytea GeomB);

Alias
Intersects

Description
Tests whether this geometry intersects the specified geometry, returns True if so. The intersects predicate has the following equivalent definitions: The two geometries have at least one point in common Intersects is the inverse of Disjoint a.Intersects(b) - ! a.Disjoint(b) The DE-9IM Intersection Matrix for the two geometries matches [T********] or [*T*******] or [***T*****] or [****T****] GeometryCollections are unsupported

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.1.2 , 2.1.13.3 OGC SFS for SQL. 1.1.0 (2005) 7.2.19.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.8.1 SQL-MM Part 3 5.1.27

Examples
SELECT ST_Intersects(ga,gb) from (SELECT ST_GeomFromText('LINESTRING (40 40, 180 180)') as ga, ST_GeomFromText('LINESTRING (120 120, 20 200) ') as gb) as foo; --Result TRUE SELECT ST_Intersects(ga,gb) from (SELECT ST_GeomFromText('POINT (20 20)') as ga, ST_GeomFromText('POLYGON ((60 120, 60 40, 160 40, 160 120, 60 120))') as gb) as foo; --Result FALSE

269

Reference

ST_Intersects(ga,gb) = TRUE

ST_Intersects(ga,gb) = FALSE

Related functions
ST_Disjoint,ST_Intersection, ST_Relate

270

Reference

Name
ST_Length Returns the 2-dimensional length of a Geometry.

Synopsis
double ST_Length(bytea Geometry);

Alias
Length, ST_Length2D, Length2D, ST_Perimeter, Perimeter

Description
Returns the 2d length of a Geometry. Linear geometries return their length. Areal geometries return their perimeter. Spatial Standards OGC defines the function for LineStrings and MultiLineStrings. Jaspa adds support to areal Geometries. This function supports GeometryCollections.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.5.1 , 2.1.7.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.12.1 , 7.2.17.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.10.2 , 7.2.17.2 SQL-MM Part 3 7.1.2 , 9.3.4 Linear 8.1.3 , 9.5.4 Areal

Examples
SELECT ST_Length(ST_GeomFromText('LINESTRING (0 0, 10 10, 10 5, 15 10)')); --Result 26.213203435596427 SELECT ST_Length2D(ST_GeomFromText('POLYGON((0 0, 0 10, 10 10, 10 0, 0 0))')); --Result 40.0 SELECT ST_Length(ST_GeomFromText('GEOMETRYCOLLECTION (POINT (40 30),LINESTRING (0 0, 10 10, 10 5, 15 10),POLYGON((0 0, 0 10, 10 10, 10 0, 0 0)))')); --Result 66.21320343559643

Related functions
ST_Perimeter,ST_Length3D

271

Reference

Name
ST_Length3D Returns the 3-dimensional length of a Geometry.

Synopsis
double ST_Length3D(bytea Geometry);

Alias
Length3D

Description
Returns the 3d length of a Geometry. Linear geometries return their length. Areal geometries return their perimeter. This function supports GeometryCollections.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_Length3D(ST_GeomFromEWKT('LINESTRING (0 0 8, 10 10 12, 10 5 14, 15 10 16)')); --Result 27.43057249218311 SELECT ST_Length3D(ST_GeomFromEWKT('POLYGON((0 0 5, 0 10 15, 10 10 15, 10 0 5, 0 0 5))')); --Result 48.2842712474619 SELECT ST_Length3D(ST_GeomFromEWKT(' GEOMETRYCOLLECTION (POINT (40 30 0), LINESTRING (0 0 8, 10 10 12, 10 5 14, 15 10 16), POLYGON((0 0 5, 0 10 15, 10 10 15, 10 0 5, 0 0 5)))')); --Result 75.714843739645

Related functions
ST_Length

272

Reference

Name
ST_Length_Spheroid Calculates the 2D or 3D length of a Line represented by its latitude/longitude coordinates.

Synopsis
PostgreSQL

geometry ST_Length_Spheroid(bytea LineString, varchar Spheroid); geometry ST_Length_Spheroid(bytea LineString, integer SRID); geometry ST_Length_Spheroid(bytea LineString);

H2

geometry ST_Length_Spheroid(bytea LineString, varchar Spheroid); geometry ST_Length_SpheroidEx(bytea LineString, integer SRID); geometry ST_Length_Spheroid(bytea LineString);

Alias
Length_Spheroid

Description
Calculates the 2D or 3D length of a Line represented by its latitude/longitude coordinates. Distance is calculated using a particular spheroid. This spheroid can be given by the SRID or by the text, if it's not given this function searches at the geometry SRID. This function supports GeometryCollections.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

273

Reference

Examples
--PostgreSQL SELECT ST_Length_Spheroid(ga) as length_WGS84, ST_Length_Spheroid( ga,'SPHEROID["GRS_1980",6378137,298.257222101]') as length_GRS80, ST_Length_Spheroid(ga,25830) as length2_GRS80 from (SELECT ST_GeomFromText('LINESTRING(-3.52 41.0,2.33 48.86)',4326) as ga) as foo; --H2 SELECT ST_Length_Spheroid(ga) as length_WGS84, ST_Length_Spheroid( ga,'SPHEROID["GRS_1980",6378137,298.257222101]') as length_GRS80, ST_Length_SpheroidEx(ga,25830) as length2_GRS80 from (SELECT ST_GeomFromText('LINESTRING(-3.52 41.0,2.33 48.86)',4326) as ga) as foo; --Result length_wgs84 | length_grs80 | length2_grs80 ------------------+------------------+-----------------987329.984556481 | 987329.984551754 | 987329.984551754

SELECT ST_Length_Spheroid(ga) as length, ST_Length2D_Spheroid(ga) as length2D, ST_Length3D_Spheroid(ga) as length3D from (SELECT ST_GeomFromText('LINESTRING(-3.52 41.0 50,-3.33 41.86 400)',4326) as ga) as foo; --Result length | length2d | length3d ------------------+------------------+-----------------96825.3888661294 | 96824.7562820438 | 96825.3888661294

Related functions
ST_Length,ST_Length2D_Spheroid,ST_Length3D_Spheroid

274

Reference

Name
ST_Length2D_Spheroid Calculates the 2D length of a Line represented by its latitude/longitude coordinates.

Synopsis
PostgreSQL

geometry ST_Length2D_Spheroid(bytea LineString, varchar Spheroid); geometry ST_Length2D_Spheroid(bytea LineString, integer SRID); geometry ST_Length2D_Spheroid(bytea LineString);

H2

geometry ST_Length2D_Spheroid(bytea LineString, varchar Spheroid); geometry ST_Length2D_SpheroidEx(bytea LineString, integer SRID); geometry ST_Length2D_Spheroid(bytea LineString);

Alias
Length_Spheroid

Description
Calculates the 2D or 3D length of a Line represented by its latitude/longitude coordinates. Distance is calculated using a particular spheroid. This spheroid can be given by the SRID or by the text, if it's not given this function searches at the geometry SRID. This function supports GeometryCollections.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

275

Reference

Examples
--PostgreSQL SELECT ST_Length2D_Spheroid(ga) as length_WGS84, ST_Length2D_Spheroid( ga,'SPHEROID["GRS_1980",6378137,298.257222101]') ST_Length2D_Spheroid(ga,25830) as length2_GRS80 from (SELECT ST_GeomFromText('LINESTRING(-3.52 41.0,2.33 48.86)',4326) as ga) --H2 SELECT ST_Length2D_Spheroid(ga) as length_WGS84, ST_Length2D_Spheroid( ga,'SPHEROID["GRS_1980",6378137,298.257222101]') ST_Length2D_SpheroidEx(ga,25830) as length2_GRS80 from (SELECT ST_GeomFromText('LINESTRING(-3.52 41.0,2.33 48.86)',4326) as ga) --Result length_wgs84 | length_grs80 | length2_grs80 ------------------+------------------+-----------------987329.984556481 | 987329.984551754 | 987329.984551754 as length_GRS80, as foo;

as length_GRS80, as foo;

Related functions
ST_Length_Spheroid,ST_Length3D_Spheroid

276

Reference

Name
ST_Length3D_Spheroid Calculates the 3D length of a Line represented by its latitude/longitude coordinates.

Synopsis
PostgreSQL

geometry ST_Length3D_Spheroid(bytea LineString, varchar Spheroid); geometry ST_Length3D_Spheroid(bytea LineString, integer SRID); geometry ST_Length3D_Spheroid(bytea LineString);

H2

geometry ST_Length3D_Spheroid(bytea LineString, varchar Spheroid); geometry ST_Length3D_SpheroidEx(bytea LineString, integer SRID); geometry ST_Length3D_Spheroid(bytea LineString);

Alias
Length_Spheroid

Description
Calculates the 3D length of a Line represented by its latitude/longitude coordinates. Distance is calculated using a particular spheroid. This spheroid can be given by the SRID or by the text, if it's not given this function searches at the geometry SRID. This function supports GeometryCollections.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

277

Reference

Examples
--PostgreSQL SELECT ST_Length3D_Spheroid(ga) as length_WGS84, ST_Length3D_Spheroid( ga,'SPHEROID["GRS_1980",6378137,298.257222101]') ST_Length3D_Spheroid(ga,25830) as length2_GRS80 from (SELECT ST_GeomFromText('LINESTRING(-3.52 41.0 50,2.33 48.86 450)',4326) --H2 SELECT ST_Length3D_Spheroid(ga) as length_WGS84, ST_Length3D_Spheroid( ga,'SPHEROID["GRS_1980",6378137,298.257222101]') ST_Length3D_SpheroidEx(ga,25830) as length2_GRS80 from (SELECT ST_GeomFromText('LINESTRING(-3.52 41.0 50,2.33 48.86 450)',4326) --Result length_wgs84 | length_grs80 | length2_grs80 ------------------+------------------+-----------------987330.065583086 | 987330.065578359 | 987330.065578359 as length_GRS80, as ga) as foo;

as length_GRS80, as ga) as foo;

Related functions
ST_Length_Spheroid,ST_Length2D_Spheroid

278

Reference

Name
ST_OrderingEquals Tests if two Geometries are equal, and the coordinates are in the same order.

Synopsis
boolean ST_OrderingEquals(bytea Geometry, bytea Geometry);

Alias
OrderingEquals

Description
Tests if two Geometries are equal, and the coordinates are in the same order. GeometryCollections are supported

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 5.1.43

Examples
SELECT ST_Equals(a,b) as equalsAB, ST_OrderingEquals(a,b) as OequalsAB,ST_OrderingEquals(a,a) as OequalsAA from (SELECT ST_GeomFromText('LINESTRING (0 0, 10 10, 10 5, 15 10)') as a, ST_GeomFromText('LINESTRING (15 10, 10 5, 10 10, 5 5, 0 0)') as b) as foo; equalsab | oequalsab | oequalsaa ----------+-----------+----------t | f | t SELECT ST_Equals(ga,gb),ST_OrderingEquals(ga,gb) from (SELECT ST_GeomFromText('LINESTRING (0 0 8, 10 10 2)') as ga, ST_GeomFromText('LINESTRING (10 10 4, 0 0 2)') as gb) as foo; st_equals | st_orderingequals -----------+------------------t | f

Related functions
ST_Equals

279

Reference

Name
ST_Overlaps Tests if a Geometry spatially overlaps another Geometry.

Synopsis
boolean ST_Overlaps(bytea Geometry, bytea Geometry);

Alias
Overlaps

Description
The Overlaps relation is defined for A/A, L/L and P/P situations. The overlaps predicate has the following equivalent definitions: The geometries have some but not all points in common, they have the same dimension, and the intersection of the interiors of the two geometries has the same dimension as the geometries themselves. a.Overlaps(b) - (dim(I(a)) = dim(I(b)) = dim(I(a) I(b))) (a b a) (a b b) Expressed in terms of the DE-9IM: Case a P, b P or Case a A, b A: a.Overlaps(b) - (I(a) I(b)) (I(a) E(b)) (E(a) I(b)) - a.Relate(b, T*T***T**) Case a L, b L: a.Overlaps(b) - (dim(I(a) I(b) = 1) (I(a) E(b)) (E(a) I(b)) - a.Relate(b, 1*T***T**) If the geometries are of different dimension this predicate returns false. The term P is used to refer to 0 dimensional geometries (Points and MultiPoints), L is used to refer to one-dimensional geometries (LineStrings and MultiLineStrings) and A is used to refer to twodimensional geometries (Polygons and MultiPolygons). GeometryCollections are unsupported

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.1.2 , 2.1.13.3 OGC SFS for SQL. 1.1.0 (2005) 7.2.19.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.8.1 SQL-MM Part 3 5.1.32

280

Reference

Examples
--Example 1 SELECT ST_Overlaps(PA,PB) from (SELECT ST_GeomFromText('POLYGON ((10 30, 0 10, 30 20, 30 30, 20 40, 10 30))') as PA, ST_GeomFromText('POLYGON ((10 40, 20 40, 20 20, 10 20, 10 40))') as PB) as foo; --Result TRUE --Example 2 SELECT ST_Overlaps(PA,PB) from (SELECT ST_GeomFromText('POLYGON ((10 30, 0 10, 30 20, 30 30, 20 40, 10 30))') as PA, ST_GeomFromText('POLYGON ((-1.5 40, 20 40, 10 30, -1 35, -1.5 40))') as PB) as foo; --Result FALSE

ST_Overlaps(A,B) = ST_Overlaps(B,A) =TRUE

ST_Overlaps(A,B) = FALSE

Related functions
ST_Intersects,ST_Relate, ST_Relate

281

Reference

Name
ST_Perimeter Returns the length measurement of the boundary of a Polygon or a MultiPolygon.

Synopsis
double ST_Perimeter(bytea LineString);

Alias
Perimeter, ST_Length, Length, ST_Length2D, Length2D,

Description
Returns the length measurement of the boundary of a Polygon or a MultiPolygon. Distance units are those of the geometry spatial reference system. SQL-MM defines this function for Polygons and MultiPolygons. But in Jaspa returns the 2d length of any Geometry. Linear geometries return their length. Areal geometries return their perimeter. GeometryCollections are supported

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 8.1.3 , 9.5.4

Examples
SELECT ST_Perimeter(ST_GeomFromText('LINESTRING (0 0, 10 10, 10 5, 15 10)')); --Result 26.2132034355964 SELECT ST_Perimeter(ST_GeomFromText('POLYGON((0 0, 0 10, 10 10, 10 0, 0 0))')); --Result 40 SELECT ST_Perimeter(ST_GeomFromText(' GEOMETRYCOLLECTION(LINESTRING (0 0, 10 10, 10 5, 15 10),POLYGON((0 0, 0 10, 10 10, 10 0, 0 0)))')); --Result 66.21320343559643

Related functions
ST_Length

282

Reference

Name
ST_PointOnSurface Returns a Point guaranteed to lie on the geometry

Synopsis
geometry ST_PointOnSurface(bytea Geometry);

Alias
PointOnSurface

Description
Returns a Point guaranteed to lie on the geometry OGC originally defined this function for Surfaces as MultiSurfaces, Jaspa extends it to any Geometry 3D and M, are not supported for surface geometries.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.9.1 , 2.1.11.1 OGC SFS for SQL. 1.1.0 (2005) 7.2.14.1 , 7.2.18.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.12.2 , 7.2.19.2 SQL-MM Part 3 8.1.5 , 9.5.6

Examples
--MultiPoint SELECT ST_AsText(ST_PointOnSurface(ga)) from (SELECT ST_GeomFromText('MULTIPOINT (-10 30, 0 30, -10 20, -2 24, -7 27, -6 21)') as ga) as foo; --Result POINT (-7 27) --LineString SELECT ST_AsText(ST_PointOnSurface(ga)) from (SELECT ST_GeomFromText('LINESTRING (0 0 0 -2, 10 10 20 -5, 10 5 10 -8, 15 10 20 -4)') as ga) as foo; --Result POINT (10 5 10 -8) --Polygon SELECT ST_AsText(ST_PointOnSurface(ga)) from (SELECT ST_GeomFromText('POLYGON ((10 30 2, 0 10 4, 30 20 6, 30 30 8, 20 40 8, 10 30 2))') as ga) as foo; --Result POINT (18.75 25)

283

Reference

LineString

Polygon

Related functions
ST_PointOnBoundary

284

Reference

Name
ST_Relate 1st Version tests if a Geometry is spatially related to another Geometry as specified by a intersection pattern matrix. 2nd Version returns the DE-9IM (Dimensionally Extended 9 Intersection Model) for two geometries.

Synopsis
boolean ST_Relate(bytea geomA, bytea geomB, varchar varchar ST_Relate(bytea geomA, bytea geomB); PatternMatrix);

Alias
Relate

Description
1st Version Tests if a Geometry is spatially related to another Geometry by testing for intersections between the interior, boundary and exterior of the two Geometries values as specified by the intersection pattern matrix. Returns True if the DE-9IM IntersectionMatrix for the two Geometrys match a given intersection Pattern Matrix. 2nd Version returns the DE-9IM (Dimensionally Extended 9 Intersection Model) for two geometries. Spatial standards define just ST_Relate 1st version. GeometryCollections are unsupported

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.1.2 OGC SFS for SQL. 1.1.0 (2005) 7.2.19.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.8.1 SQL-MM Part 3 5.1.25

Examples
---1st Version --Test if 2 polygons overlap SELECT ST_Relate(PA,PB,'T*T***T**') from (SELECT ST_GeomFromText('POLYGON ((10 30, 0 10, 30 20, 30 30, 20 40, 10 30))') as PA, ST_GeomFromText('POLYGON ((10 40, 20 40, 20 20, 10 20, 10 40))') as PB) as foo; --Result TRUE ---2nd Version SELECT ST_Relate(PA,PB) from (SELECT ST_GeomFromText('POLYGON ((10 30, 0 10, 30 20, 30 30, 20 40, 10 30))') as PA, ST_GeomFromText('POLYGON ((10 40, 20 40, 20 20, 10 20, 10 40))') as PB) as foo; --Result 212101212

Related functions
ST_Disjoint, ST_Touches, ST_Crosses, ST_Within, ST_Overlaps

285

Reference

Name
ST_Touches Tests if a Geometry spatially touches another Geometry.

Synopsis
boolean ST_Touches(bytea GeomA, bytea GeomB);

Alias
Touches

Description
Tests if a Geometry spatially touches another Geometry, returns TRUE if so. The Touches relation between two geometries a and b applies to the A/A, L/L, L/A, P/A and P/L groups of relationships but not to the P/P group (returns False if both Geometries are points). The overlaps predicate has the following equivalent definitions: The geometries have at least one point in common, but their interiors do not intersect. a.Touches(b) - (I(a)I(b) = ) (a b) Expressed in terms of the DE-9IM: FT*******, F**T***** or F***T**** GeometryCollections are unsupported

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.1.2 , 2.1.13.3 OGC SFS for SQL. 1.1.0 (2005) 7.2.19.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.8.1 SQL-MM Part 3 5.1.28

Examples
SELECT ST_Touches(PA,PB) from (SELECT ST_GeomFromText('POLYGON ((10 30, 0 10, 30 20, 30 30, 20 40, 10 30))') as PA, ST_GeomFromText('POLYGON ((-1.5 40, 20 40, 10 30, -1 35, -1.5 40))') as PB) as foo; --Result TRUE

ST_Touches(A,B) returns True in the following situations

286

Reference

Related functions
ST_Relate,ST_Crosses,ST_Intersects

287

Reference

Name
ST_Within Tests if a Geometry is spatially within another Geometry.

Synopsis
boolean ST_Within(bytea GeomA, bytea GeomB);

Alias
Within

Description
Tests if a Geometry is spatially within another Geometry. The within predicate has the following equivalent definitions: Every point of Geometry A is a point of Geometry B, and the interiors of the two geometries have at least one point in common. In mathematical terms: a.Within(b) - (a b = a) (I(a) I(b) ) The DE-9IM Intersection Matrix for the two geometries is T*F**F*** * ST_Within is the inverse of ST_Contains GeometryCollections are unsupported

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.1.2 , 2.1.13.3 OGC SFS for SQL. 1.1.0 (2005) 7.2.19.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.8.1 SQL-MM Part 3 5.1.30

Examples
SELECT ST_Within(PA,PB) as AwithinB, ST_Contains(PB,PA) as BcontainsA, ST_Within(PB,PA) as BwithinA from (SELECT ST_GeomFromText('POLYGON ((3 5, 3 8, 6 8, 6 5, 3 5))') as PA, ST_GeomFromText('POLYGON ((1 1, 1 9, 8 9, 8 1, 1 1))') as PB) as foo; --Result awithinb | bcontainsa | bwithina ----------+------------+---------t | t | f

288

Reference

ST_Within(A,B)=TRUE ST_Within(B,A)=FALSE

Related functions
ST_Contains, ST_Relate

289

Reference

Name
ST_MultiCentroid Returns a centroid for each part of a complex geometry.

Synopsis
geometry MultiCentroid(bytea Geometry);

Alias
MultiCentroid

Description
Returns a centroid for each part of a complex geometry. Thus, a MultiPolygon composed of two Polygons woud have as MultiCentroid a MultiPoint with two Points. GeometryCollections are supported

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsText(ST_MultiCentroid(ST_GeomFromText(' GEOMETRYCOLLECTION (LINESTRING (0 0, 10 10, 10 5, 15 10), MULTIPOLYGON (((-5 20, -5 34, 11 34, 11 20, -5 20)), ( (14 20, 14 29, 23 29, 23 20, 14 20))))') )); --Result MULTIPOINT ((7.976858924576366 6.15123928305091), (3 27), (18.5 24.5))

GeomA

ST_MultiCentroid (GeomA)

Related functions
ST_Centroid

290

Reference

Name
ST_PointOnBoundary Returns a Point guaranteed to lie on the geometry's boundary.

Synopsis
geometry ST_PointOnBoundary(bytea Geometry);

Alias
PointOnBoundary

Description
Returns a Point guaranteed to lie on the geometry's boundary. The boundary of a Point is the empty set, so this fuction will return null for Points. This method does not support GeometryCollection arguments

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
--MULTIPOINT SELECT ST_PointOnBoundary(ga) as ga) as foo; --Result null from (SELECT ST_GeomFromText('MULTIPOINT (-10 30, 0 30, -10 20)')

--LINESTRING SELECT ST_AsText(ST_PointOnBoundary(ga)) from (SELECT ST_GeomFromText('LINESTRING (0 0 20, 10 10 40, 10 5 60, 15 10 80)') as ga) as foo; --Result: POINT (0 0 20) --POLYGON SELECT ST_AsText(ST_PointOnBoundary(ga)) from (SELECT ST_GeomFromText('POLYGON ((10 30, 0 10, 30 20, 30 30, 20 40, 10 30))') as ga) as foo; --Result: POINT (30 20)

291

Reference

LINESTRING

POLYGON

Related functions
ST_PointOnSurface

9.7. Geometry Processing Functions


ST_Buffer .................................................................................................................................... ST_BuildArea ............................................................................................................................... ST_Collect ................................................................................................................................... ST_ConvexHull ............................................................................................................................ ST_Difference .............................................................................................................................. ST_Dump .................................................................................................................................... ST_DumpPoints ............................................................................................................................ ST_DumpRings ............................................................................................................................. ST_Intersection ............................................................................................................................. ST_MemUnion ............................................................................................................................. ST_MinimumBoundingCircle .......................................................................................................... ST_Polygonize .............................................................................................................................. ST_Shift_Longitude ....................................................................................................................... ST_Simplify ................................................................................................................................. ST_SimplifyPreserveTopology ......................................................................................................... ST_SymDifference ........................................................................................................................ ST_Union .................................................................................................................................... ST_DelaunayTriangles ................................................................................................................... ST_SelfIntersection ........................................................................................................................ 293 296 298 302 303 304 307 309 311 313 314 316 318 319 321 323 324 327 329

292

Reference

Name
ST_Buffer Returns a geometry that represents all points whose distance from this Geometry is less than or equal to distance. Calculations are in the Spatial Reference System of that Geometry.

Synopsis
PostgreSQL

geometry ST_Buffer(bytea Geometry, double distance); geometry ST_Buffer(bytea Geometry, double distance, integer QuadrantSegments); geometry ST_Buffer(bytea Geometry, double distance, varchar Buffer_Parameters);
H2

geometry ST_Buffer(bytea Geometry, double distance); geometry ST_Buffer(bytea Geometry, double distance, integer QuadrantSegments); geometry ST_BufferEx(bytea Buffer_Parameters); Geometry, double distance, varchar

Alias
Buffer

Description
Returns a 2D geometry that represents all points whose distance from this Geometry is less than or equal to distance. Calculations are in the Spatial Reference System of the incoming Geometry.

Buffer Parameters
1.
'quad_segs=integer'

QuadrantSegments. Sets the number of line segments in a quarter of a circle. If quad_segs >= 1, joins are round, and qs indicates the number of segments to use to approximate a quarter-circle. If quad_segs = 0, joins are beveled If quad_segs < 0, joins are mitred, and the value of qs indicates the mitre ration limit as mitreLimit = |quad_segs| 2.
'endcap=round|flat|square'

End cap style. Specifies the end cap style of the generated buffer. The styles supported are CAP_ROUND, CAP_FLAT, and CAP_SQUARE. The default is CAP_ROUND. 3.
'join=round|mitre|bevel'

Join style. Sets the join style for outside corners between line segments. Allowable values are JOIN_ROUND (which is the default), JOIN_MITRE and JOIN_BEVEL. 4.
'mitre_limit= double'

Mitre_limit. Limit on the mitre ratio used for very sharp corners. The mitre ratio is the ratio of the distance from the corner to the end of the mitred offset corner. When two line segments meet at a sharp angle, a miter join will extend far beyond the original geometry. To prevent unreasonable geometry, the mitre limit allows controlling the maximum length of the join corner. Corners with a ratio which exceed the limit will be beveled.

293

Reference This function could be used to clean invalid polygons with a 0 radius, ST_Buffer(geom,0). It is, however, advisable to use ST_CleanPolygon function. ST_Buffer is sometimes used to make distance queries. It is not advisable because it's much slower than using ST_DWithin. OGC defines this predicate just as ST_Buffer(geometry, distance)

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
8 Quadrant Segments (Default) 3 Quadrant Segments (integer) 1 Quadrant Segments

SELECT ST_Buffer( ST_GeomFromText('POINT (10 10)'),10);

SELECT ST_Buffer( ST_GeomFromText('POINT (10 10)'),10,3);

--PostgreSQL SELECT ST_Buffer( ST_GeomFromText('POINT (10 10)') ,10,'quad_segs=1'); --H2 SELECT ST_BufferEx( ST_GeomFromText('POINT (10 10)') ,10,'quad_segs=1');

endcap=round (default)

endcap=flat

endcap=square

--PostgreSQL SELECT ST_Buffer( ST_GeomFromText ('LINESTRING (1 1, 3 5, 3 2, 3 2, 5 2)') ,0.5,'endcap=round');

--PostgreSQL SELECT ST_Buffer( ST_GeomFromText ('LINESTRING (1 1, 3 5, 3 2, 3 2, 5 2)') ,0.5,'endcap=flat');

--PostgreSQL SELECT ST_BufferEx( ST_GeomFromText ('LINESTRING (1 1, 3 5, 3 2, 3 2, 5 2)') ,0.5,'endcap=square');

294

Reference

--H2 SELECT ST_BufferEx( ST_GeomFromText ('LINESTRING (1 1, 3 5, 3 2, 3 2, 5 2)') ,0.5,'endcap=round');

--H2 SELECT ST_BufferEx( ST_GeomFromText ('LINESTRING (1 1, 3 5, 3 2, 3 2, 5 2)') ,0.5,'endcap=flat');

--H2 SELECT ST_BufferEx( ST_GeomFromText ('LINESTRING (1 1, 3 5, 3 2, 3 2, 5 2)') ,0.5,'endcap=square');

join=round (default)

join=mitre

join=bevel

--PostgreSQL SELECT ST_Buffer( ST_GeomFromText ('LINESTRING (1 1, 3 5, 3 2, 3 2, 5 2)') ,0.5,'join=round'); --H2 SELECT ST_BufferEx( ST_GeomFromText ('LINESTRING (1 1, 3 5, 3 2, 3 2, 5 2)') ,0.5,'join=round');

--PostgreSQL SELECT ST_Buffer( ST_GeomFromText ('LINESTRING (1 1, 3 5, 3 2, 3 2, 5 2)') ,0.5,'join=mitre'); --H2 SELECT ST_BufferEx( ST_GeomFromText ('LINESTRING (1 1, 3 5, 3 2, 3 2, 5 2)') ,0.5,'join=mitre');

--PostgreSQL SELECT ST_Buffer( ST_GeomFromText ('LINESTRING (1 1, 3 5, 3 2, 3 2, 5 2)') ,0.5,'join=bevel'); --H2 SELECT ST_BufferEx( ST_GeomFromText ('LINESTRING (1 1, 3 5, 3 2, 3 2, 5 2)') ,0.5,'join=bevel');

join=mitre mitre_limit=5

join=mitre mitre_limit=2

join=mitre mitre_limit=0.5

--PostgreSQL SELECT ST_Buffer( ST_GeomFromText ('LINESTRING (1 1, 3 5, 3 2, 3 2, 5 2)') ,0.5,'join=mitre mitre_limit=5'); --H2 SELECT ST_BufferEx( ST_GeomFromText ('LINESTRING (1 1, 3 5, 3 2, 3 2, 5 2)') ,0.5,'join=mitre mitre_limit=5');

--PostgreSQL SELECT ST_Buffer( ST_GeomFromText ('LINESTRING (1 1, 3 5, 3 2, 3 2, 5 2)') ,0.5,'join=mitre mitre_limit=2'); --H2 SELECT ST_BufferEx( ST_GeomFromText ('LINESTRING (1 1, 3 5, 3 2, 3 2, 5 2)') ,0.5,'join=mitre mitre_limit=2');

--PostgreSQL SELECT ST_Buffer (ST_GeomFromText ('LINESTRING (1 1, 3 5, 3 2, 3 2, 5 2)') ,0.5,'join=mitre mitre_limit=0.5'); --H2 SELECT ST_BufferEx (ST_GeomFromText ('LINESTRING (1 1, 3 5, 3 2, 3 2, 5 2)') ,0.5,'join=mitre mitre_limit=0.5');

Related functions
ST_CleanPolygon,ST_DWithin

295

Reference

Name
ST_BuildArea Creates a surface geometry from the lines of the input geometries.

Synopsis
geometry ST_BuildArea(bytea Geometry);

Alias
BuildArea

Description
Creates a surface geometry from the lines of the input geometries. This method supports GeometryCollections

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
CREATE TABLE "lines"(id serial PRIMARY KEY); SELECT AddGeometryColumn ('lines','GEOM',25830,'LINESTRING',2); INSERT INSERT INSERT INSERT INTO INTO INTO INTO "lines" "lines" "lines" "lines" ("GEOM") ("GEOM") ("GEOM") ("GEOM") VALUES VALUES VALUES VALUES (ST_GeomfromEWKT('SRID=25830;LINESTRING (ST_GeomfromEWKT('SRID=25830;LINESTRING (ST_GeomfromEWKT('SRID=25830;LINESTRING (ST_GeomfromEWKT('SRID=25830;LINESTRING (1 (1 (6 (1 1, 7, 7, 1, 1 3 6 4 4, 7, 3, 1, 1 6 6 6 7)')); 7)')); 1)')); 1)'));

--H2 SELECT asewkt(ST_BuildArea(ST_CollectAgg("lines"."GEOM"))) as polygon from "lines"; --PostgreSQL SELECT asewkt(ST_BuildArea(ST_Collect("lines"."GEOM"))) as polygon from "lines"; SELECT DropGeometryTable ('lines'); --Result polygon -------------------------------------------------------------------SRID=25830;POLYGON ((1 7, 3 7, 6 7, 6 3, 6 1, 4 1, 1 1, 1 4, 1 7)) (1 row)

296

Reference

ST_BuildArea(A)

SELECT ST_asewkt(ST_BuildArea(ST_GeomfromText('MULTILINESTRING ((1 1, 1 5, 6 5, 6 1, 1 1), (3 7, 3 3, 8 3, 8 8, 3 8, 3 7))'))); --Result MULTIPOLYGON (((3 7, 3 8, 8 8, 8 3, 6 3, 6 5, 3 5, 3 7)), ((3 5, 3 3, 6 3, 6 1, 1 1, 1 5, 3 5)))

ST_BuildArea(A)

Related functions
ST_Collect,ST_Polygonize

297

Reference

Name
ST_Collect Returns a geometry from the collection of others geometries.

Synopsis
PostgreSQL

geometry ST_Collect(bytea GeomA, bytea GeomB); geometry ST_Collect(bytea[] Geometry_Array); geometry ST_Collect(bytea Aggregate);

H2

geometry ST_Collect(bytea GeomA, bytea GeomB); geometry ST_Collect(bytea[] Geometry_Array); geometry ST_CollectAgg(bytea Aggregate);

Alias
Collect

Description
Returns a geometry from the collection of others geometries. The resulting geometry can be GEOMETRYCOLLECTION or MULTI* type. This function has three versions: 1. Collects 2 geometries. 2. Collect an array of geometries. 3. Collect an aggregate. An aggregate function computes a single result from multiple input rows. ST_Collect function can return invalid geometries

A,B

ST_Collect(A,B) returns Invalid Geometry

298

Reference

SELECT ST_ISValid(a), ST_IsValidReason(a), ST_AsEWKT(a) FROM ST_Collect(ST_GeomFromText('POLYGON ((10 30, 10 70, 60 70, 60 30, 10 30))'), ST_GeomFromText('POLYGON((40 50, 40 80, 70 80, 70 50, 40 50))')) as a; --Result: st_isvalid | st_isvalidreason | ------------+------------------------------------------------------+ f | Self-intersection at or near point (60.0, 50.0, NaN) | st_asewkt --------------------------------------------------------------------------MULTIPOLYGON (((10 30, 10 70, 60 70, 60 30, 10 30)), ((40 50, 40 80, 70 80, 70 50, 40 50))) (1 row)

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
PostgreSQL
ST_Collect(geomA,geomB)
SELECT ST_AsEWKT(ST_Collect(ST_GeomFromText('POINT(5 5 10 8)'), ST_GeomFromText('LINESTRING(0 0 10 8,1 1 1 1)'))); --Result GEOMETRYCOLLECTION (POINT (5 5 10 8), LINESTRING (0 0 10 8, 1 1 1 1))

ST_Collect(geomArray)
SELECT AsEWKT(ST_Collect(Array[ST_MakePoint(0, 0), ST_MakePoint(10, 10),ST_MakePoint(15, 10)])); asewkt -------------------------------------MULTIPOINT ((0 0), (10 10), (15 10)) (1 row)

ST_Collect(Aggregate)

299

Reference

This example creates a collection of points from a set of single points. The single points are stored in the gps_points table. The INSERT INTO statements that follow insert each one of the points geometries. CREATE TABLE "gps_points"(id serial PRIMARY KEY); SELECT AddGeometryColumn ('gps_points','geom',-1,'POINT',2); INSERT INTO "gps_points" ("geom") VALUES (ST_GeomfromEWKT('SRID=-1;POINT(0 0)')); INSERT INTO "gps_points" ("geom") VALUES (ST_GeomfromEWKT('SRID=-1;POINT(10 10)')); INSERT INTO "gps_points" ("geom") VALUES (ST_GeomfromEWKT('SRID=-1;POINT(15 15)')); SELECT asewkt(ST_Collect("gps_points"."geom")) as measures from "gps_points"; SELECT DropGeometryTable ('gps_points'); --Result measures -------------------------------------MULTIPOINT ((0 0), (10 10), (15 15))

H2
ST_Collect(geomA,geomB)
SELECT ST_AsEWKT(ST_Collect(ST_GeomFromText('POINT(5 5 10 8)'),ST_GeomFromText('POINT(0 0 10 8)'))); --Result MULTIPOINT ((5 5 10 8), (0 0 10 8))

ST_Collect(geomArray)
-- (1st Version) SELECT ST_AsText(ST_Collect(st_accumagg(geom))) as mycollection from (SELECT array_get( ( st_geomfromtext('POINT(0 0)'), st_geomfromtext('POINT(10 10)'), st_geomfromtext('POINT(15 15)') ),x)::binary as geom from (select x from system_range(1,3) as foo) as tabla); --Result MULTIPOINT ((0 0), (10 10), (15 15)) --(2nd Version) SELECT ST_AsText(ST_Collect(st_accumagg(geom))) as myline from (SELECT ST_geomfromtext('LINESTRING(0 0,10 10)') as geom union SELECT ST_geomfromtext('LINESTRING(10 10,15 10)') union SELECT ST_geomfromtext('LINESTRING(15 10,20 20)') ) as geom; --Result MULTILINESTRING ((10 10, 15 10), (15 10, 20 20), (0 0, 10 10))

ST_Collect(Aggregate)

300

Reference

CREATE TABLE "gps_points"(id serial PRIMARY KEY); SELECT AddGeometryColumn ('gps_points','geom',-1,'POINT',2); INSERT INTO "gps_points" ("geom") VALUES (ST_GeomfromEWKT('SRID=-1;POINT(0 0)')); INSERT INTO "gps_points" ("geom") VALUES (ST_GeomfromEWKT('SRID=-1;POINT(10 10)')); INSERT INTO "gps_points" ("geom") VALUES (ST_GeomfromEWKT('SRID=-1;POINT(15 15)')); SELECT asewkt(ST_CollectAgg("gps_points"."geom")) as measures from "gps_points"; SELECT DropGeometryTable ('gps_points'); --Result MEASURES MULTIPOINT ((0 0), (10 10), (15 15))

Related functions
ST_Dump

301

Reference

Name
ST_ConvexHull Returns a geometry that represents the convex hull of the given Geometry.

Synopsis
geometry ST_ConvexHull(bytea Geometry);

Alias
ConvexHull

Description
Returns a geometry that represents the convex hull of the given Geometry. The convex hull represents the boundary of the minimal convex set containing a given geometry. It may be easily visualized by imagining an elastic band stretched open to encompass the given object. This method supports GeometryCollections

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.1.3 OGC SFS for SQL. 1.1.0 (2005) 7.2.21.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.8.1 SQL-MM Part 3 5.1.16

Examples
SELECT ST_asewkt(ST_ConvexHull(ST_GeomfromText( 'GEOMETRYCOLLECTION (POINT (2 2), POINT (2 5), POINT(5 3), POINT (6 5),POLYGON ((3 4, 3.2 6, 2.8 7.4, 5.1 7.1, 4.4 4.5, 3 4)))' ))); st_asewkt ------------------------------------------------------POLYGON ((2 2, 2 5, 2.8 7.4, 5.1 7.1, 6 5, 5 3, 2 2)) (1 row)

Related functions
ST_MinimumBoundingCircle

302

Reference

Name
ST_Difference Returns a geometry that represents the point set difference of a Geometry with another Geometry.

Synopsis
geometry ST_Difference(bytea GeomA, bytea GeomB);

Alias
Difference

Description
Returns a geometry that represents the point set difference of a Geometry with another Geometry. This method returns the closure of the resultant Geometry. GeometryCollections are unsupported.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.1.3 OGC SFS for SQL. 1.1.0 (2005) 7.2.21.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.8.1 SQL-MM Part 3 5.1.20

Examples
SELECT ST_AsEWKT(ST_Difference(A,B)) from (SELECT ST_GeomFromText('POLYGON ((40 20, 40 100, 120 100, 120 20, 40 20))',25830) as A, ST_GeomFromText('POLYGON ((80 60, 80 130, 170 130, 170 60, 80 60))',25830) as B) as foo; --Result SRID=25830;POLYGON ((40 20, 40 100, 80 100, 80 60, 120 60, 120 20, 40 20))

ST_Difference (A,B)

ST_Difference (B,A)

Related functions
ST_SymDifference

303

Reference

Name
ST_Dump Splits Multi-geometries and GeometryCollections into a set of single geometries.

Synopsis
geometry[] ST_Dump(bytea Geometry); geometry[] ST_Dump(bytea Geometry, integer GeometryDimension);

Alias
Dump

Description
Splits Multi-geometries and GeometryCollections into a set of single geometries. The type of geometries to extract can be indicated as an integer. Possible values are 0 for Points, 1 for LineStrings, 2 for Polygons. The reverse function of ST_Dump is ST_Collect. GeometryCollections are supported. JASPA ST_Dump function returns just an array of geometries. PostGIS ST_Dump function creates an array of geometries with an array of integers (path).

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
PostgreSQL
ST_Dump(geomA)

304

Reference

SELECT st_dump (st_geomfromtext('MULTIPOINT (1 2, 3 4, 5 6)')); st_dump -------------------------------------------------------------------------------\001\001\000\000\000\000\000\000\000\000\000\360?\000\000\000\000\000\000\000@ \001\001\000\000\000\000\000\000\000\000\000\010@\000\000\000\000\000\000\020@ \001\001\000\000\000\000\000\000\000\000\000\024@\000\000\000\000\000\000\030@ (3 rows) SELECT ST_astext(st_dump (st_geomfromtext('MULTIPOINT (1 2, 3 4, 5 6)'))); st_astext ------------POINT (1 2) POINT (3 4) POINT (5 6) (3 rows) --4D GeometryCollection SELECT ST_astext(st_dump (st_geomfromtext('GEOMETRYCOLLECTION (POINT (2 2 1 8), POINT (2 5 1 9), POLYGON ((3 4 4 5, 3.2 6 8 9, 2.8 7.4 7 2, 5.1 7.1 5 8, 4.4 4.5 4 8, 3 4 4 5)))'))); st_astext -------------------------------------------------------------------------------POINT (2 2 1 8) POINT (2 5 1 9) POLYGON ((3 4 4 5, 3.2 6 8 9, 2.8 7.4 7 2, 5.1 7.1 5 8, 4.4 4.5 4 8, 3 4 4 5)) (3 rows)

ST_Dump(geomA,dim)
--Creates a set from points SELECT ST_astext(st_dump ( st_geomfromtext('GEOMETRYCOLLECTION (POINT (2 2), POINT(5 3), POINT (6 5),POLYGON ((3 4, 3.2 6, 2.8 7.4, 5.1 7.1, 4.4 4.5, 3 4)))') ,0)); --Result st_astext ------------POINT (2 2) POINT (5 3) POINT (6 5) (3 rows) --Creates a set from polygons SELECT ST_astext(st_dump ( st_geomfromtext('GEOMETRYCOLLECTION (POINT (2 2), POINT(5 3), POINT (6 5),POLYGON ((3 4, 3.2 6, 2.8 7.4, 5.1 7.1, 4.4 4.5, 3 4)))') ,2)); --Result st_astext -------------------------------------------------------POLYGON ((3 4, 3.2 6, 2.8 7.4, 5.1 7.1, 4.4 4.5, 3 4)) (1 row)

H2
ST_Dump(geomA)

305

Reference

SELECT * from st_dump ('select st_geomfromewkt(''MULTIPOINT (1 2, 3 4, 5 6)'')'); JASPA.ST_GEOMFROMEWKT('MULTIPOINT (1 2, 3 4, 5 6)') 0101000000000000000000f03f0000000000000040 010100000000000000000008400000000000001040 010100000000000000000014400000000000001840

SELECT ST_AsText(geom) from st_dump ('select st_geomfromewkt(''MULTIPOINT (1 2, 3 4, 5 6)'') as geom'); ST_ASTEXT(GEOM) POINT (1 2) POINT (3 4) POINT (5 6) --4D GeometryCollection SELECT ST_AsText(geom) from st_dump ('select st_geomfromewkt(''GEOMETRYCOLLECTION (POINT (2 2 1 8), POINT (2 5 1 9), POLYGON ((3 4 4 5, 3.2 6 8 9, 2.8 7.4 7 2, 5.1 7.1 5 8, 4.4 4.5 4 8, 3 4 4 5)))'') as geom'); ST_ASTEXT(GEOM) POINT (2 2 1 8) POINT (2 5 1 9) POLYGON ((3 4 4 5, 3.2 6 8 9, 2.8 7.4 7 2, 5.1 7.1 5 8, 4.4 4.5 4 8, 3 4 4 5))

ST_Dump(geomA,dim)
--Creates a set from points SELECT ST_AsText(geom) from st_dump ('select st_geomfromewkt(''GEOMETRYCOLLECTION (POINT (2 2), POINT(5 3), POINT (6 5), POLYGON ((3 4, 3.2 6, 2.8 7.4, 5.1 7.1, 4.4 4.5, 3 4)))'') as geom',0); --Result JASPA.ST_ASTEXT(GEOM) POINT (2 2) POINT (5 3) POINT (6 5) --Creates a set from polygons SELECT ST_AsText(geom) from st_dump ('select st_geomfromewkt(''GEOMETRYCOLLECTION (POINT (2 2), POINT(5 3), POINT (6 5), POLYGON ((3 4, 3.2 6, 2.8 7.4, 5.1 7.1, 4.4 4.5, 3 4)))'')',2); --Result JASPA.ST_ASTEXT(GEOM) POLYGON ((3 4, 3.2 6, 2.8 7.4, 5.1 7.1, 4.4 4.5, 3 4))

Related functions
ST_Collect, ST_Dimension, ST_DumpPoints,ST_DumpRings

306

Reference

Name
ST_DumpPoints Returns the set of points that compose a Geometry.

Synopsis
geometry[] ST_DumpPoints(bytea Geometry);

Alias
DumpPoints

Description
Returns the set of points that compose a Geometry. It includes points, lines vertices and polygons vertices. GeometryCollections are supported. JASPA ST_DumpPoints function returns just an array of geometries. PostGIS ST_DumpPoints function creates an array of geometries with an array of integers (path).

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
PostgreSQL
SELECT ST_AsText(g) FROM (SELECT ST_DumpPoints( st_geomfromtext('GEOMETRYCOLLECTION (POINT (2 2), POINT(5 3), POINT (6 5),POLYGON ((3 4, 3.2 6, 2.8 7.4, 5.1 7.1, 4.4 4.5, 3 4)))') ) as g) as foo; st_astext ----------------POINT (2 2) POINT (5 3) POINT (6 5) POINT (3 4) POINT (3.2 6) POINT (2.8 7.4) POINT (5.1 7.1) POINT (4.4 4.5) POINT (3 4)

307

Reference

H2
SELECT ST_AsText(geom) from st_dumppoints('select st_geomfromewkt(''GEOMETRYCOLLECTION (POINT (2 2), POINT(5 3), POINT (6 5), POLYGON ((3 4, 3.2 6, 2.8 7.4, 5.1 7.1, 4.4 4.5, 3 4)))'') as geom') ; -- Result JASPA.ST_ASTEXT(GEOM) POINT (2 2) POINT (5 3) POINT (6 5) POINT (3 4) POINT (3.2 6) POINT (2.8 7.4) POINT (5.1 7.1) POINT (4.4 4.5) POINT (3 4) (9 filas, 4 ms)

GeomA

ST_DumpPoints(GeomA)

Related functions
ST_Dump,ST_DumpRings

308

Reference

Name
ST_DumpRings Returns a set of geometry rows, representing the exterior and interior rings of a Polygon or a MultiPolygon.

Synopsis
geometry[] ST_DumpRings(bytea Geometry);

Alias
DumpRings

Description
Returns a set of geometry rows, representing the exterior and interior rings of a Polygon or a MultiPolygon. This method supports GeometryCollections JASPA ST_DumpRings function returns just an array of geometries. PostGIS ST_DumpRings function creates an array of geometries with an array of integers (path).

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
PostgreSQL
SELECT ST_astext(geom) as dumprings FROM (SELECT ST_DumpRings(ST_GeomFromText('MULTIPOLYGON (((1 7, 1 1, 6 1, 7 7, 1 7), (2 4, 2 2, 3 2, 3 4, 2 4)), ((6 9, 6 12, 9 12, 9 9, 6 9)))')) as geom ) as foo; dumprings ---------------------------------------LINESTRING (1 7, 1 1, 6 1, 7 7, 1 7) LINESTRING (2 4, 2 2, 3 2, 3 4, 2 4) LINESTRING (6 9, 6 12, 9 12, 9 9, 6 9)

H2
SELECT ST_AsText(rings.geom) as dumprings from (st_dumprings('select st_geomfromewkt(''MULTIPOLYGON (((1 7, 1 1, 6 1, 7 7, 1 7), (2 4, 2 2, 3 2, 3 4, 2 4)), ((6 9, 6 12, 9 12, 9 9, 6 9)))'') as geom') as rings) ; DUMPRINGS LINESTRING (1 7, 1 1, 6 1, 7 7, 1 7) LINESTRING (2 4, 2 2, 3 2, 3 4, 2 4) LINESTRING (6 9, 6 12, 9 12, 9 9, 6 9) (3 filas, 4 ms)

309

Reference

GeomA

ST_DumpRings(GeomA)

Related functions
ST_Dump,ST_DumpPoints

310

Reference

Name
ST_Intersection Returns a 2D geometric object that represents the intersection of two geometric objects.

Synopsis
geometry ST_Intersection(bytea GeomA, bytea GeomB);

Alias
Intersection

Description
Returns a geometric object that represents the intersection of two geometric objects. GeometryCollections are unsupported.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.1.3 OGC SFS for SQL. 1.1.0 (2005) 7.2.21.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.8.1 SQL-MM Part 3 5.1.18

Examples
--2D Geometries SELECT ST_astext(ST_Intersection ( st_geomfromtext('POLYGON ((1 3, 1 8, 6 8, 6 3, 1 3))') , st_geomfromtext('MULTIPOLYGON (((6 8, 6 10, 8 10, 8 8, 6 8)),((6 3, 6 6, 10 6, 10 3, 6 3)))'))); --Result GEOMETRYCOLLECTION (POINT (6 8), LINESTRING (6 6, 6 3)) --3D Geometries SELECT ST_astext(ST_Intersection ( st_geomfromtext('POLYGON ((1 3 2, 1 8 4, 6 8 6, 6 3 4, 1 3 2))') , st_geomfromtext('LINESTRING (4 2 3, 2 4 5, 4 9 6, 4 10 7)'))); --Result LINESTRING (3 3, 2 4, 3.6 8)

Geom A, GeomB

ST_Intersection (GeomA,GeomB)

311

Reference

Geom A, GeomB

ST_Intersection (GeomA,GeomB)

Related functions
ST_Intersects,ST_Difference,ST_SymDifference

312

Reference

Name
ST_MemUnion Same as ST_Union (aggregate) but memory-friendly (uses less memory and more processor time).

Synopsis
PostgreSQL

geometry ST_MemUnion(bytea GeometryAggregate);


H2

geometry ST_MemUnionAgg(bytea GeometryAggregate);

Alias
MemUnion

Description
Same as ST_Union (aggregate) but memory-friendly (uses less memory and more processor time). It works by unioning the geometries one at a time to previous result as opposed to ST_Union aggregate which first creates an array and then unions

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
CREATE TABLE "polygons"(id serial PRIMARY KEY); SELECT AddGeometryColumn ('polygons','GEOM',25830,'POLYGON',2); INSERT INTO "polygons" ("GEOM") VALUES (ST_GeomfromEWKT('SRID=25830;POLYGON ((40 20 10, 40 100 15, 120 100 25, 120 20 30, 40 20 25))')); INSERT INTO "polygons" ("GEOM") VALUES (ST_GeomfromEWKT('SRID=25830;POLYGON ((80 60, 80 130, 170 130, 170 60, 80 60))')); --PostgreSQL SELECT asewkt(ST_MemUnion("polygons"."GEOM")) as union_pol from "polygons"; --H2 SELECT asewkt(ST_MemUnionAgg("polygons"."GEOM")) as union_pol from "polygons"; SELECT DropGeometryTable ('polygons'); --Result UNION_POL SRID=25830;POLYGON ((40 20 10, 40 100 15, 80 100 0, 80 130 0, 170 130 0, 170 60 0, 120 60 0, 120 20 30, 40 20 25))

Related functions
ST_Union

313

Reference

Name
ST_MinimumBoundingCircle Returns the minimum circle polygon that can fully contain a geometry.

Synopsis
geometry ST_MinimumBoundingCircle(bytea Geometry); geometry ST_MinimumBoundingCircle(bytea Geometry, integer QuadrantSegments);

Alias
MinimumBoundingCircle

Description
Returns the minimum circle polygon that can fully contain a geometry. The number of segments in a quarter circle can be indicated, default value is 48. This method supports GeometryCollections

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

314

Reference

Examples
SELECT ST_astext(ST_MinimumBoundingCircle ( st_geomfromtext('GEOMETRYCOLLECTION (POLYGON ((2 3, 2 8, 9 8, 9 3, 2 3)),POINT (12 10))'),12)); --Result POLYGON ((0.8967221921 6.5, 0.9489365799 7.2966376123, 1.1046863404 8.0796445342, 1.3613065521 8.8356233002, 1.714406372 9.5516389039, 2.1579441644 10.21544012, 2.6843308746 10.8156691254, 3.28455988 11.3420558356, 3.9483610961 11.785593628, 4.6643766998 12.1386934479, 5.4203554658 12.3953136596, 6.2033623877 12.5510634201, 7 12.6032778079, 7.7966376123 12.5510634201, 8.5796445342 12.3953136596, 9.3356233002 12.1386934479, 10.0516389039 11.785593628, 10.71544012 11.3420558356, 11.3156691254 10.8156691254, 11.8420558356 10.21544012, 12.285593628 9.5516389039, 12.6386934479 8.8356233002, 12.8953136596 8.0796445342, 13.0510634201 7.2966376123, 13.1032778079 6.5, 13.0510634201 5.7033623877, 12.8953136596 4.9203554658, 12.6386934479 4.1643766998, 12.285593628 3.4483610961, 11.8420558356 2.78455988, 11.3156691254 2.1843308746, 10.71544012 1.6579441644, 10.0516389039 1.214406372, 9.3356233002 0.8613065521, 8.5796445342 0.6046863404, 7.7966376123 0.4489365799, 7 0.3967221921, 6.2033623877 0.4489365799, 5.4203554658 0.6046863404, 4.6643766998 0.8613065521, 3.9483610961 1.214406372, 3.28455988 1.6579441644, 2.6843308746 2.1843308746, 2.1579441644 2.78455988, 1.714406372 3.4483610961, 1.3613065521 4.1643766998, 1.1046863404 4.9203554658, 0.9489365799 5.7033623877, 0.8967221921 6.5))

Related functions
ST_ConvexHull

315

Reference

Name
ST_Polygonize Creates a GeometryCollection made up of Polygons from a set of Geometries which contain lines that represents the Polygons edges.

Synopsis
PostgreSQL

geometry ST_Polygonize(bytea GeometryAggregate); geometry ST_Polygonize(bytea[] Geometry_Array);


H2

geometry ST_PolygonizeAgg(bytea GeometryAggregate); geometry ST_Polygonize(bytea[] Geometry_Array);

Alias
Polygonize

Description
Creates a GeometryCollection made up of Polygons from a set of Geometries which contain lines that represents the Polygons edges. Lines must connect to one another at the endpoint.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
Array PostgreSQL
SELECT ST_AsEWKT(ST_Polygonize( Array[ST_GeomFromEWKT('LINESTRING (4 11, 4 4, 11 4, 11 11, 4 11)'), ST_GeomFromEWKT('LINESTRING (1 9, 1 5, 5 5, 5 9, 1 9)')])); --Result st_asewkt -------------------------------------------------------------------------------GEOMETRYCOLLECTION (POLYGON ((4 11, 11 11, 11 4, 4 4, 4 11)), POLYGON ((1 9, 5 9, 5 5, 1 5, 1 9))) (1 row)

Array H2

316

Reference

SELECT ST_AsText(ST_Polygonize(st_accumagg(geom))) as myline from (select array_get( ( st_geomfromtext('LINESTRING (4 11, 4 4, 11 4, 11 11, 4 11)'), st_geomfromtext('LINESTRING (1 9, 1 5, 5 5, 5 9, 1 9)') ),x)::binary as geom from (select x from system_range(1,2) as foo) as tabla); --Result GEOMETRYCOLLECTION (POLYGON ((4 11, 11 11, 11 4, 4 4, 4 11)), POLYGON ((1 9, 5 9, 5 5, 1 5, 1 9)))

Aggregate
create table "lines"(id serial PRIMARY KEY); SELECT AddGeometryColumn ('lines','GEOM',25830,'LINESTRING',2); INSERT INSERT INSERT INSERT INSERT INSERT INSERT INTO INTO INTO INTO INTO INTO INTO "lines" "lines" "lines" "lines" "lines" "lines" "lines" ("GEOM") ("GEOM") ("GEOM") ("GEOM") ("GEOM") ("GEOM") ("GEOM") VALUES VALUES VALUES VALUES VALUES VALUES VALUES (ST_GeomfromEWKT('SRID=25830;LINESTRING (ST_GeomfromEWKT('SRID=25830;LINESTRING (ST_GeomfromEWKT('SRID=25830;LINESTRING (ST_GeomfromEWKT('SRID=25830;LINESTRING (ST_GeomfromEWKT('SRID=25830;LINESTRING (ST_GeomfromEWKT('SRID=25830;LINESTRING (ST_GeomfromEWKT('SRID=25830;LINESTRING (1 (1 (2 (2 (2 (3 (2 1, 4, 4, 1, 4, 4, 1, 1 2 2 1 3 3 3 4)')); 4)')); 1)')); 1)')); 4)')); 1)')); 1)'));

--PostgreSQL select asewkt(ST_Polygonize("lines"."GEOM")) as polygonizer from "lines"; --H2 select asewkt(ST_PolygonizeAgg("lines"."GEOM")) as polygonizer from "lines"; SELECT DropGeometryTable ('lines'); --Result POLYGONIZER SRID=25830;GEOMETRYCOLLECTION (POLYGON ((2 4, 2 1, 1 1, 1 4, 2 4)), POLYGON ((3 1, 2 1, 2 4, 3 4, 3 1)))

GeomA

ST_Polygonize(GeomA)

GeomA

ST_Polygonize(GeomA)

Related functions
ST_BuildArea

317

Reference

Name
ST_Shift_Longitude Converts geometry longitude values from range [-180,180] to the range [0-360]

Synopsis
geometry ST_Shift_Longitude(bytea Geometry);

Alias
Shift_Longitude

Description
Converts geometry longitude values from range [-180,180] to the range [0-360] This method supports GeometryCollections

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
--2D LineString SELECT ST_AsEWKT(ST_Shift_Longitude(ST_GeomFromText('LINESTRING(-3.52 41.0,2.33 48.86)',4326))); --Result SRID=4326;LINESTRING (356.48 41, 2.33 48.86) --3D MultiPoint SELECT ST_AsEWKT(Shift_Longitude(ST_GeomFromEWKT('SRID=4326;MULTIPOINT(-3.52 41.0 5,2.33 48.86 285)'))); --Result SRID=4326;MULTIPOINT ((356.48 41 5), (2.33 48.86 285))

Related functions

318

Reference

Name
ST_Simplify Simplifies a Geometry using the standard Douglas-Peucker algorithm.

Synopsis
geometry ST_Simplify(bytea Geometry, double Tolerance);

Alias
Simplify

Description
Simplifies a Geometry using the standard Douglas-Peucker algorithm. Ensures that any polygonal geometries returned are valid. Simple lines are not guaranteed to remain simple after simplification (see ST_IsSimple). The Tolerance parameter, sets the distance tolerance for the simplification. All vertices in the simplified geometry will be within this distance of the original geometry. The tolerance value must be positive. Note that in general this method does not preserve topology - e.g. polygons can be split, collapse to lines or disappear, holes can be created or disappear, and lines can cross. To simplify geometry while preserving topology use ST_SimplifyPreserveTopology. This method supports GeometryCollections

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

319

Reference

Examples
--2D Polygon-SELECT ST_AsText(ST_Simplify(geom,2)) as s2, ST_AsText(ST_Simplify(geom,5)) as s5, ST_AsText(ST_Simplify(geom,10)) as s10, ST_AsText(ST_Simplify(geom,15)) as s15 FROM (SELECT ST_Buffer(ST_GeomFromText('POINT(50 50)'), 10) As geom) As foo; --Result S2 POLYGON ((60 50, 57.071067811865476 42.928932188134524, 50 40, 42.928932188134524 42.928932188134524, 40 50.00000000000001, 42.92893218813454 57.07106781186549, 50.00000000000002 60, 57.0710678118655 57.071067811865454, 60 50)) S5 POLYGON ((60 50, 50 40, 40 50.00000000000001, 50.00000000000002 60, 60 50)) S10 POLYGON ((60 50, 50 40, 40 50.00000000000001, 60 50)) S15 null --3D LineString-SELECT ST_AsText(ST_Simplify(geom,7.5)) as s7, ST_AsText(ST_Simplify(geom,10)) as s10 FROM (SELECT ST_GeomFromText('LINESTRING (5 15 10, 11 8 20, 19 22 30, 24 12 25, 38 20 35, 47 14 30, 55 23 20)') As geom) As foo; --Result S7 LINESTRING (5 15 10, 11 8 20, 19 22 30, 24 12 25, 55 23 20) S10 LINESTRING (5 15 10, 55 23 20)

Related functions
ST_SimplifyPreserveTopology

320

Reference

Name
ST_SimplifyPreserveTopology Simplifies a geometry, ensuring that the result is a valid geometry having the same dimension and number of components as the incoming geometries.

Synopsis
varchar ST_SimplifyPreserveTopology(bytea Geometry, double Tolerance);

Alias
SimplifyPreserveTopology

Description
Simplifies a geometry, ensuring that the result is a valid geometry having the same dimension and number of components as the given geometries. The simplification uses a maximum distance difference algorithm similar to the one used in the Douglas-Peucker algorithm. In particular, if the input is an areal geometry ( Polygon or MultiPolygon). The result has the same number of shells and holes (rings) as the input, in the same order The result rings touch at no more than the number of touching point in the input (although they may touch at fewer points) This method supports GeometryCollections

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
--polygon with holes SELECT ST_AsText(ST_Simplify(geom,4)) as s4, ST_AsText(ST_SimplifyPreserveTopology(geom,4)) as preserve4 FROM (SELECT ST_GeomFromText('POLYGON ((16 7, 16 36, 47 36, 47 7, 16 7), (24 16, 24 24, 30 24, 30 16, 24 16), (38 27, 38 31, 43 31, 43 27, 38 27), (36 12, 36 19, 43 19, 43 12, 36 12))') As geom) As foo; --Result: S4 POLYGON ((16 7, 16 36, 47 36, 47 7, 16 7), (24 16, 24 24, 30 24, 30 16, 24 16), (36 12, 36 19, 43 19, 43 12, 36 12)) PRESERVE4 POLYGON ((16 7, 16 36, 47 36, 47 7, 16 7), (24 16, 24 24, 30 24, 30 16, 24 16), (38 27, 38 31, 43 31, 43 27, 38 27), (36 12, 36 19, 43 19, 43 12, 36 12))

321

Reference

GeomA

ST_Simplify(GeomA,4)

ST_SimplifyPreserveTopology (GeomA,4)

Related functions
ST_Simplify

322

Reference

Name
ST_SymDifference Returns a Geometry object that represents the point set symmetric difference of two Geometry objects.

Synopsis
geometry ST_SymDifference(bytea GeomA, bytea GeomB);

Alias
SymDifference

Description
Returns a Geometry object that represents the point set symmetric difference of two Geometry objects. The symmetric difference is a set combining the points in both Geometries that do not intersect. This method does not support GeometryCollections

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.1.3 OGC SFS for SQL. 1.1.0 (2005) 7.2.21.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.8.1 SQL-MM Part 3 5.1.21

Examples
SELECT ST_AsEWKT(ST_SymDifference(A,B)) from (SELECT ST_GeomFromText('POLYGON ((40 20, 40 100, 120 100, 120 20, 40 20))',25830) as A, ST_GeomFromText('POLYGON ((80 60, 80 130, 170 130, 170 60, 80 60))',25830) as B) as foo; --Result SRID=25830;MULTIPOLYGON (((40 20, 40 100, 80 100, 80 60, 120 60, 120 20, 40 20)),((120 60, 120 100, 80 100, 80 130, 170 130, 170 60, 120 60)))

A,B

ST_SymDifference (A,B)

Related functions
ST_Difference,ST_Intersection

323

Reference

Name
ST_Union Returns a Geometry object that represents the point set union of two Geometries.

Synopsis
PostgreSQL

geometry ST_Union(bytea GeomA, bytea GeomB); geometry ST_Union(bytea[] Geometry_Array); geometry ST_Union(bytea GeomAggregate);

H2

geometry ST_Union(bytea GeomA, bytea GeomB); geometry ST_Union(bytea[] Geometry_Array); geometry ST_UnionAgg(bytea GeomAggregate);

Alias
Union

Description
Returns a Geometry object that represents the point set union of two Geometries. The geometries must have the same coordinate dimension This method does not support GeometryCollections

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) 2.1.1.3 OGC SFS for SQL. 1.1.0 (2005) 7.2.21.1 OGC SFS for SQL. 1.2.0 (2006) 7.2.8.1 SQL-MM Part 3 5.1.19

324

Reference

Examples
--2d polygons SELECT ST_AsEWKT(ST_Union(A,B)) from (SELECT ST_GeomFromText('POLYGON ((40 20, 40 100, 120 100, 120 20, 40 20))',25830) as A, ST_GeomFromText('POLYGON ((80 60, 80 130, 170 130, 170 60, 80 60))',25830) as B) as foo; --Result SRID=25830;POLYGON ((40 20, 40 100, 80 100, 80 130, 170 130, 170 60, 120 60, 120 20, 40 20)) -- 3d line & multipoint SELECT ST_AsEWKT(ST_Union(B,A)) from (SELECT ST_GeomFromText('LINESTRING (-4 20 2, 27 51 1, 55 34 0, 87 69 0)',25830) as A, ST_GeomFromText('MULTIPOINT ((30 24 10), (55 60 20))',25830) as B) as foo; --Result SRID=25830;GEOMETRYCOLLECTION (POINT (30 24 10), POINT (55 60 20), LINESTRING (-4 20 2, 27 51 1, 55 34 0, 87 69 0))

Array PostgreSQL
SELECT ST_AsText(ST_Union(Array[A,B,C])) FROM (SELECT ST_GeomFromText('POLYGON ((40 20, 40 100, 120 100, 120 20, 40 20))') as A, ST_GeomFromText('POLYGON ((80 60, 80 130, 170 130, 170 60, 80 60))') as B, ST_GeomFromText('POINT (80 9)') as C ) as foo; --Result: st_astext ----------------------------------------------------------------------------------GEOMETRYCOLLECTION ( POINT (80 9), POLYGON ((40 20, 40 100, 80 100, 80 130, 170 130, 170 60, 120 60, 120 20, 40 20))) (1 row)

Array H2
SELECT ST_AsText(ST_Union(st_accumagg(geom))) as newpolygon from (select array_get(( st_geomfromtext('POLYGON ((40 20, 40 100, 120 100, 120 20, 40 20))'), st_geomfromtext('POLYGON ((80 60, 80 130, 170 130, 170 60, 80 60))')),x)::binary as geom from (select x from system_range(1,2) as foo) as table); --Result NEWPOLYGON POLYGON ((40 20, 40 100, 80 100, 80 130, 170 130, 170 60, 120 60, 120 20, 40 20)) SELECT ST_AsText(ST_Union(st_accumagg(geom))) as mpoints from (select st_geomfromtext('SRID=10;POINT(0 0)') as geom union select st_geomfromtext('SRID=10;POINT(10 10)') union select st_geomfromtext('SRID=10;POINT(15 15)') ) as geom; --Result MPOINTS MULTIPOINT ((0 0), (10 10), (15 15))

325

Reference Aggregate
CREATE TABLE "lines"(id serial PRIMARY KEY); SELECT AddGeometryColumn ('lines','GEOM',25830,'LINESTRING',2); INSERT INSERT INSERT INSERT INTO INTO INTO INTO "lines" "lines" "lines" "lines" ("GEOM") ("GEOM") ("GEOM") ("GEOM") VALUES VALUES VALUES VALUES (ST_GeomfromEWKT('SRID=25830;LINESTRING (ST_GeomfromEWKT('SRID=25830;LINESTRING (ST_GeomfromEWKT('SRID=25830;LINESTRING (ST_GeomfromEWKT('SRID=25830;LINESTRING (1 (1 (6 (1 1, 7, 7, 1, 1 3 6 4 4, 7, 3, 1, 1 6 6 6 7)')); 7)')); 1)')); 1)'));

--PostgreSQL SELECT asewkt(ST_Union("lines"."GEOM")) as lineunion from "lines"; --H2 SELECT asewkt(ST_UnionAgg("lines"."GEOM")) as lineunion from "lines"; SELECT DropGeometryTable ('lines'); --Result SRID=25830;MULTILINESTRING ((1 1, 4 1, 6 1), (1 1, 1 4, 1 7), (6 7, 6 3, 6 1), (1 7, 3 7, 6 7))

Related functions
ST_MemUnion

326

Reference

Name
ST_DelaunayTriangles Returns polygons that represent Delaunay Trianglulations from collections of points.

Synopsis
geometry ST_DelaunayTriangles(bytea Geometry);

Alias
DelaunayTriangles

Description
Returns polygons that represent Delaunay Trianglulations from collections of points. The union of all simplices in the triangulation is the convex hull of the points. This method supports GeometryCollections

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsText( ST_DelaunayTriangles(ST_GeomFromText( 'GEOMETRYCOLLECTION (MULTIPOINT ((2 2), (3 4), (4 2), (2 1)), LINESTRING (5 4, 6 2, 4 3, 3 2, 4 1), POLYGON ((5 5, 5 6, 7 6, 7 5, 5 5)))'))); --Result GEOMETRYCOLLECTION (POLYGON ((2 2, 2 1, 3 2, 2 2)), POLYGON ((2 2, 3 2, 3 4, 2 2)), POLYGON ((3 4, 3 2, 4 3, 3 4)), POLYGON ((3 4, 4 3, 5 4, 3 4)), POLYGON ((3 4, 5 4, 5 5, 3 4)), POLYGON ((3 4, 5 5, 5 6, 3 4)), POLYGON ((5 6, 5 5, 7 5, 5 6)), POLYGON ((5 6, 7 5, 7 6, 5 6)), POLYGON ((4 1, 6 2, 4 2, 4 1)), POLYGON ((4 1, 4 2, 3 2, 4 1)), POLYGON ((4 1, 3 2, 2 1, 4 1)), POLYGON ((3 2, 4 2, 4 3, 3 2)), POLYGON ((4 3, 4 2, 6 2, 4 3)), POLYGON ((4 3, 6 2, 5 4, 4 3)), POLYGON ((5 4, 6 2, 7 5, 5 4)), POLYGON ((5 4, 7 5, 5 5, 5 4)))

327

Reference

GeomA

ST_DelaunayTriangles (geomA)

Related functions
ST_ConvexHull

328

Reference

Name
ST_SelfIntersection Returns the points where a Line intersects itself.

Synopsis
geometry ST_SelfIntersection(bytea Line);

Alias
SelfIntersection

Description
Returns the points where a Line intersects itself. The incoming geometry must be a LineString or MultiLineString. Return Null if there isn't an Intersection This method does not support GeometryCollections

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
--3D LineString SELECT ST_AsEWKT(ST_SelfIntersection(ST_GeomFromText('LINESTRING (1 1 2, 3 3 4, 3 2 3, 2 4 6)'))); --Result POINT (2.666666666666666 2.666666666666666) --2D MultiLineString SELECT ST_AsEWKT(ST_SelfIntersection(ST_GeomFromText('MULTILINESTRING ((1 1, 3 3, 3 2, 2 4), (1 2, 3 4))'))); --Result MULTIPOINT ((2.333333333333334 3.333333333333334), (2.666666666666666 2.666666666666666)) --Line without self-intersection SELECT ST_Issimple(GeomA), ST_AsText(ST_SelfIntersection(GeomA)) FROM (SELECT ST_GeomFromText('LINESTRING (1 2, 3 4)') as geomA) as foo; --Result st_issimple | st_astext -------------+----------t |

329

Reference GeomA ST_SelfIntersection(GeomA)

Related functions
ST_IsSimple

9.8. Linear Referencing


ST_Line_Interpolate_Point .............................................................................................................. ST_Line_Locate_Point ................................................................................................................... ST_Line_Substring ........................................................................................................................ ST_Locate_Along_Measure ............................................................................................................. ST_Locate_Between_Measures ........................................................................................................ ST_Locate_Along_Elevation ........................................................................................................... ST_Locate_Between_Elevations ....................................................................................................... ST_Project_Point ........................................................................................................................... 331 333 335 337 338 339 340 341

330

Reference

Name
ST_Line_Interpolate_Point Returns the Coordinates for the point on the line at the given fraction. This fraction, is applied to the line's total length.

Synopsis
geometry ST_Line_Interpolate_Point(bytea Geometry, double fraction);

Alias
Line_Interpolate_Point

Description
Returns the Coordinates for the point on the line at the given fraction. This fraction, is applied to the line's total length. The Geometry object must be a LineString or MultiLineString. The second parameter represents the fraction of the Line where the point will be located. If the index is out of range[0-1] the first or last point on the line will be returned. The Z and M cooordinates of the computed point will be interpolated from the line segment containing it, if they exist.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
--2D LineString (Point at 80% along Line) SELECT ST_AsEWKT(ST_Line_Interpolate_Point(ST_GeomFromEWKT('SRID=25830;LINESTRING (17 21, 26 39, 44 46)'),0.8)); --Result SRID=25830;POINT (36.64875355835534 43.14118193936041) --3D LineString (Point at 20% along Line) SELECT ST_AsEWKT(ST_Line_Interpolate_Point(ST_GeomFromEWKT('LINESTRING (17 21 15, 26 39 20, 44 46 25)'),0.2)); --Result POINT (20.527425830535137 28.05485166107027 16.959681016963962) --2D LineString (Point at 120% along Line. It returns the last vertex of the line) SELECT ST_AsEWKT(ST_Line_Interpolate_Point(ST_GeomFromText('LINESTRING (17 21, 26 39, 44 46)'),1.2)); --Result POINT (44 46) --2D LineString (Point at 10 meters in Line) SELECT ST_ASEWKT(ST_Line_Interpolate_Point(line,fraction)) FROM (SELECT 10/ST_Length(line) as fraction,line FROM (SELECT ST_GeomFromEWKT('SRID=25830;LINESTRING (17 21, 26 39, 44 46)') as line) as foo) as b; --Result SRID=25830;POINT (21.47213595499958 29.94427190999916)

331

Reference

Point at 80% along Line

Related functions
ST_Line_Locate_Point, ST_Project_Point, ST_Length

332

Reference

Name
ST_Line_Locate_Point Computes de fraction of a Line from the closest point on the line to the given point.

Synopsis
double ST_Line_Locate_Point(bytea Line, bytea Point);

Alias
Line_Locate_Point

Description
Computes de fraction of a Line from the closest point on the line to the given point. The point does not necessarily have to lie precisely on the line. Both geometries must have the same SRID and dimensions.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_Line_Locate_Point(ST_GeomFromEWKT('LINESTRING (29 35, 29 21, 11 21)'),ST_GeomFromEWKT('POINT (20 28)')); --Result 0.71875 -- Using ST_Line_Interpolate_Point (see graphic below) SELECT ST_AsText(ST_Line_Interpolate_Point(line,ST_Line_Locate_Point(line,point))) as interpolate FROM (SELECT ST_GeomFromText('LINESTRING (10 11, 15 26, 29 35)') as line, ST_GeomFromText('POINT (27 27)') as point) as foo; --Result interpolate ----------------------------------------------POINT (23.945848375451263 31.750902527075812) (1 row)

333

Reference

2nd example, finds closest point from a Line to a given point

Related functions
ST_Line_Interpolate_Point, ST_Project_Point

334

Reference

Name
ST_Line_Substring Returns a LineString being a portion of the input one. It will start and end at the given fractions of the total 2D length.

Synopsis
geometry ST_Line_Substring(bytea endFraction); Geometry, double startFraction, double

Alias
Line_Substring

Description
Returns a LineString being a portion of the input one. It will start and end at the given fractions of the total 2D length. The fractions parameters are numbers between 0 and 1. MultiLineStrings are also supported. Jaspa returns a substring of a MultiLineString considering it as a whole, not cliping each of the LineStrings.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
--2D LineString SELECT ST_AsEWKT(ST_Line_Substring(ST_GeomFromEWKT('LINESTRING (17 21, 26 39, 44 46)'),0.2,0.8)); --Result LINESTRING (20.527425830535137 28.05485166107027, 26 39, 36.64875355835534 43.14118193936041) --4D LineString SELECT ST_AsEWKT(ST_Line_Substring(ST_GeomFromEWKT('LINESTRING (17 21 10 -2, 26 39 15 -4, 44 46 20 -2)'),0.2,0.8)); --Result LINESTRING (20.527425830535137 28.05485166107027 11.959681016963964 -2.783872406785585, 26 39 15 -4, 36.64875355835534 43.14118193936041 17.95798709954315 -2.81680516018274) --2D MultiLineString SELECT ST_AsEWKT(ST_Line_Substring(ST_GeomFromEWKT('MULTILINESTRING ((1 1, 1 5), (2 5, 4 5),(5 5, 5 1))'),0.2,0.8)); --Result MULTILINESTRING ((1 3, 1 5), (2 5, 4 5), (5 5, 5 3))

335

Reference

ST_Line_Substring(Line,0.2,0.8)

ST_Line_Substring(MultiLineString,0.2,0.8)

Related functions
ST_Length,ST_Line_Interpolate_Point

336

Reference

Name
ST_Locate_Along_Measure Extracts Points from a Geometry object that have the specified m coordinate value.

Synopsis
geometry ST_Locate_Along_Measure(bytea Geometry, double M);

Alias
ST_Locate_Along_Measure, ST_LocateAlong, LocateAlong

Description
Extracts Points from a Geometry object that have the specified m coordinate value.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 5.1.12 ST_LocateAlong

Examples
SELECT ST_AsEWKT(the_geom) FROM (SELECT ST_Locate_Along_Measure( ST_GeomFromEWKT('MULTILINESTRINGM((1 2 3, 3 4 2, 9 4 3), (1 2 3, 5 4 5))'),3) As the_geom) As foo; --Result GEOMETRYCOLLECTION (MULTIPOINT ((1 2 0 3), (9 4 0 3)), POINT (1 2 0 3))

Related functions
ST_Locate_Between_Measures

337

Reference

Name
ST_Locate_Between_Measures Returns a derived geometry whose measures are in the specified M range.

Synopsis
geometry ST_Locate_Between_Measures(bytea Geometry, double start_M, double end_M);

Alias
Locate_Between_Measures, ST_LocateBetween, LocateBetween

Description
Returns a derived geometry whose measures are in the specified M range.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3 5.1.13 ST_LocateBetween

Examples
SELECT ST_AsEWKT(the_geom) FROM (SELECT ST_Locate_Between_Measures( ST_GeomFromEWKT('MULTILINESTRING((1 1 2 8, 1 5 4 0, 6 5 4 2), (4 3 2 2, 8 3 0 -4, 8 8 0 -6))'),2,8) As the_geom) As foo; --Result GEOMETRYCOLLECTION (GEOMETRYCOLLECTION (LINESTRING (1 1 2 8, 1 4 3.5 2), POINT (6 5 4 2)), POINT (4 3 2 2))

Related functions
ST_Locate_Along_Measure

338

Reference

Name
ST_Locate_Along_Elevation Extracts Points from a Geometry object that have the specified z coordinate value.

Synopsis
geometry ST_Locate_Along_Elevation(bytea Geometry, double Z);

Alias
Locate_Along_Elevation

Description
Extracts Points from a Geometry object that have the specified z coordinate value.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsEWKT(geom) FROM (SELECT ST_Locate_Along_Elevation( ST_GeomFromEWKT('MULTILINESTRING ((1 1 2 8, 2 1 4 0, 3 1 5 2), (4 1 2 2, 5 3 0 -4, 8 8 0 -6))'),2) As geom) As foo; --Result GEOMETRYCOLLECTION (POINT (1 1 2 8), POINT (4 1 2 2))

Geom

ST_Along_Elevation(Geom,2)

Related functions
ST_Locate_Between_Elevations

339

Reference

Name
ST_Locate_Between_Elevations Returns a derived geometry whose elevation are in the specified Z range.

Synopsis
geometry ST_Locate_Between_Elevations(bytea Geometry, double start_Z, double end_Z);

Alias
Locate_Between_Elevations, ST_LocateBetweenElevations, LocateBetweenElevations

Description
Returns a derived geometry whose elevation are in the given Z range.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsEWKT(geom) FROM (SELECT ST_Locate_Between_Elevations( ST_GeomFromEWKT('MULTILINESTRING ((1 1 2 8, 2 1 4 0, 3 1 5 2), (4 1 2 2, 5 3 0 -4, 8 8 0 -6))'),2,4) As geom) As foo; --Result GEOMETRYCOLLECTION (LINESTRING (1 1 2 8, 2 1 4 0, 2 1 4 0), POINT (4 1 2 2))

ST_Locate_Between_Elevations(Geom,2,4)

Geom

Related functions
ST_Locate_Along_Elevation

340

Reference

Name
ST_Project_Point Finds the closest point from a Line to a given point

Synopsis
geometry ST_Project_Point(bytea Line, bytea Point);

Alias
Project_Point

Description
Finds the closest point from a Line to a given point. ST_Project_Point (Line, Point) is a ST_Line_Interpolate_Point(line,ST_Line_Locate_Point(line,point)) shortening of

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsText(ST_Project_Point(line,point)) as interpolate FROM (SELECT ST_GeomFromText('LINESTRING (10 11, 15 26, 29 35)') as line, ST_GeomFromText('POINT (27 27)') as point) as foo; --Result interpolate ----------------------------------------------POINT (23.945848375451263 31.750902527075812) (1 row)

Related functions
ST_Line_Interpolate_Point,ST_Line_Locate_Point

9.9. Miscellaneous Functions


ST_Accum ................................................................................................................................... ST_Box2D ................................................................................................................................... ST_Box3D ................................................................................................................................... ST_Expand .................................................................................................................................. ST_Extent .................................................................................................................................... ST_Extent3D ................................................................................................................................ Find_SRID ................................................................................................................................... 343 345 346 347 348 349 350

341

Reference

ST_Mem_Size .............................................................................................................................. ST_Point_Inside_Circle .................................................................................................................. ST_XMax .................................................................................................................................... ST_XMin ..................................................................................................................................... ST_YMax .................................................................................................................................... ST_YMin ..................................................................................................................................... ST_ZMax .................................................................................................................................... ST_ZMin ..................................................................................................................................... ST_Box ....................................................................................................................................... ST_AsWKTSRS ........................................................................................................................... MinPair ....................................................................................................................................... MaxPair .......................................................................................................................................

351 352 353 354 355 356 357 358 359 360 362 365

342

Reference

Name
ST_Accum Constructs an array of geometries from a set of geometries.

Synopsis
PostgreSQL

geometry[] ST_Accum(bytea Geometry_Aggregate);


H2

geometry[] ST_AccumAgg(bytea Geometry_Aggregate);

Alias
Accum

Description
Constructs an array of geometries from a set of geometries. ST_Accum is an aggregate function that return a single value, calculated from a set of values (a column or a subset of column values).

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
--Creates an example table, and populates data there create table "lines"(id serial PRIMARY KEY); SELECT AddGeometryColumn ('lines','GEOM',25830,'LINESTRING',2); INSERT INTO "lines" ("GEOM") VALUES (ST_GeomfromEWKT('SRID=25830;LINESTRING (1 1, 1 4, 1 7)')); INSERT INTO "lines" ("GEOM") VALUES (ST_GeomfromEWKT('SRID=25830;LINESTRING (1 7, 3 7, 6 7)')); INSERT INTO "lines" ("GEOM") VALUES (ST_GeomfromEWKT('SRID=25830;LINESTRING (6 7, 6 3, 6 1)')); //SELECT DropGeometryTable ('lines');

PostgreSQL
--Return the Array of Geometries SELECT ST_Accum("lines"."GEOM") from "lines"; SELECT c FROM (SELECT ST_Accum("lines"."GEOM") as c from "lines") as foo; --Return a Subset of the Array SELECT c[1:2] FROM (SELECT ST_Accum("lines"."GEOM") as c from "lines") as foo;

343

Reference

H2
--Return the Array of Geometries SELECT (c) FROM (SELECT ST_AccumAgg("lines"."GEOM") as c from "lines") as foo ; --Result (0102000020e66400000300000000 ... 0000000000000f03f0000000000001c40, 0102000020e664000003000000000 ... 000000000000018400000000000001c40, 0102000020e664000003000000000 ... 400000000000001840000000000000f03f) --Return a Subset of the Array select (c) FROM (SELECT ST_AccumAgg("lines"."GEOM") as c from "lines" where id>2) as foo ; --Result (0102000020e664000003000000000 ... 000008400000000000001840000000000000f03f) --Use the array as an argument for ST_MakeGeomColl SELECT ST_AsText(ST_MakeGeomColl(c)) FROM (SELECT ST_AccumAgg("lines"."GEOM") as c from "lines") as foo; --Result GEOMETRYCOLLECTION (LINESTRING (1 1, 1 4, 1 7), LINESTRING (1 7, 3 7, 6 7), LINESTRING (6 7, 6 3, 6 1))

Related functions
ST_Collect

344

Reference

Name
ST_Box2D Returns a Polygon geometry representation of the two-dimensional bounding box.

Synopsis
geometry ST_Box2D(bytea Geometry);

Alias
Box2D

Description
Returns a Polygon geometry representation of the two-dimensional bounding box. The resulting Polygon will have the same SRID and coordinates units of the original geometries.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsText(Box2D(ST_GeomFromText('LINESTRING (1 1, 2 3, 3 2, 4 4)'))); --Result POLYGON ((1 1, 1 4, 4 4, 4 1, 1 1)) SELECT ST_AsEWKT(ST_SetSRID(ST_Box2D(ST_GeomFromText('LINESTRING (1 1, 2 3, 3 2, 4 4)')),25830)); --Result SRID=25830;POLYGON ((1 1, 1 4, 4 4, 4 1, 1 1))

Related functions
ST_Box3D,ST_Box

345

Reference

Name
ST_Box3D Returns a Polygon geometry representation of the three-dimensional bounding box

Synopsis
geometry ST_Box3D(bytea Geometry);

Alias
Box3D

Description
Returns a Polygon geometry representation of the three-dimensional bounding box. The resulting Polygon will have the same SRID and coordinates units of the original geometries.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsText(Box3D(ST_GeomFromText('LINESTRING (1 1 -5, 2 3 10, 3 2 5, 4 4 0)'))); --Result POLYGON ((1 1 -5, 1 4 10, 4 4 10, 4 1 -5, 1 1 -5))

Related functions
ST_Box2D,ST_Box

346

Reference

Name
ST_Expand Expands the Polygon that represents the Bounding Box in all directions.

Synopsis
geometry ST_Expand(bytea Geometry, double Expand_Units);

Alias
Expand

Description
Expands the Polygon that represents the Bounding Box in all directions. A 3d Bounding Box will also be extended in Z direction. The resulting Polygon will have the same SRID and coordinates units of the original geometries.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
--2D LineString SELECT ST_AsText(ST_Box(ST_GeomFromText('LINESTRING (1 1, 2 3, 3 2, 4 4)'))); --Result POLYGON ((1 1, 1 4, 4 4, 4 1, 1 1)) SELECT ST_AsText(ST_Expand(ST_GeomFromText('LINESTRING (1 1, 2 3, 3 2, 4 4)'),1)); --Result POLYGON ((0 0, 0 5, 5 5, 5 0, 0 0))

ST_Box(GeomA)

ST_Expand(GeomA,1)

--3D LineString SELECT ST_AsText(ST_Expand(ST_GeomFromText('LINESTRING (1 1 -5, 2 3 10, 3 2 5, 4 4 0)'),1)); --Result POLYGON ((0 0 -6, 0 5 11, 5 5 11, 5 0 -6, 0 0 -6))

Related functions
ST_Box

347

Reference

Name
ST_Extent Returns the minimum bounding box of the specified geometries, that is, a single rectangle that minimally encloses the geometries.

Synopsis
PostgreSQL

geometry ST_Extent(bytea Geometry_Aggregate);


H2

geometry ST_ExtentAgg(bytea Geometry_Aggregate);

Alias
Extent

Description
Returns the minimum bounding box of the specified geometries, that is, a single rectangle that minimally encloses the geometries. The resulting Polygon will have the same SRID and coordinates units of the original geometries. ST_Extent is an aggregate functions that return a single value, calculated from a set of values (a column or a subset of column values).

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
--Return the extent of the table townships. SELECT ST_Extent(geom) as Extext FROM townships; --Return the extent of each province. SELECT ST_Extent(the_geom) as pextent FROM townships GROUP BY province ORDER BY province; --Return the extent of a single township. SELECT ST_Extent(geom) as Extext FROM townships WHERE town_name = 'Valencia';

Related functions
ST_Extent3D

348

Reference

Name
ST_Extent3D Returns the minimum bounding box of the specified geometries.

Synopsis
PostgreSQL

geometry ST_Extent3D(bytea Geometry_Aggregate);


H2

geometry ST_Extent3DAgg(bytea Geometry_Aggregate);

Alias
Extent3D

Description
Returns the minimum bounding box of the specified geometries, that is, a single rectangle that minimally encloses the geometries, it includes Z coordinate. The resulting Polygon will have the same SRID and coordinates units of the original geometries. ST_Extent is an aggregate functions that return a single value, calculated from a set of values (a column or a subset of column values).

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
--Return the extent of the table townships. SELECT ST_Extent3D(geom) as Extext FROM townships; --Return the extent of each province. SELECT Extent3D(the_geom) as pextent FROM townships GROUP BY province ORDER BY province; --Return the extent of a single township. SELECT ST_Extent3D(geom) as Extext FROM townships WHERE town_name = 'Valencia';

Related functions
ST_Extent

349

Reference

Name
Find_SRID Returns the SRID of the specified geometry column by searching through the metadata GEOMETRY_COLUMNS table.

Synopsis
integer Find_SRID(varchar geometry_field); table_schema, varchar table_name, varchar

integer Find_SRID(varchar table_name, varchar geometry_field);

Alias
-

Description
Returns the SRID of the specified geometry column by searching through the metadata GEOMETRY_COLUMNS table. To obtain a successful result, the geometry column must be properly added with the AddGeometryColumn function The parameters needed are table schema (optional), table name, and geometry column.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
--PostgreSQL SELECT Find_SRID('public', 'mytable', 'geometry_field'); SELECT Find_SRID('mytable', 'geometry_field'); --H2 SELECT Find_SRID('mytable', 'geometry_field'); SELECT Find_SRID('PUBLIC', 'mytable', 'geometry_field');

Related functions
ST_SRID

350

Reference

Name
ST_Mem_Size Returns the amount of space (in bytes) the geometry takes.

Synopsis
integer ST_Mem_Size(bytea Geometry);

Alias
Mem_Size

Description
Returns the amount of space (in bytes) the geometry takes.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_Mem_Size(ST_GeomFromText('LINESTRING (1 1, 2 3, 3 2, 4 4)')); --Result 73

Related functions

351

Reference

Name
ST_Point_Inside_Circle Tests if a point is inside a circle defined by its center coordinates and radius.

Synopsis
boolean ST_Point_Inside_Circle(bytea Point, double Center_X, double Center_Y, double radius);

Alias
Point_Inside_Circle

Description
Tests if a point is inside a circle defined by its center coordinates and radius, returns True if so. Input geometry must be a point.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_Point_Inside_Circle(ST_GeomFromText('POINT(6 2)'), 3, 2, 2); st_point_inside_circle -----------------------f (1 row) SELECT ST_Point_Inside_Circle(ST_Point(3,1), 3, 2, 2); st_point_inside_circle -----------------------t (1 row)

ST_Point_Inside_Circle(ST_Point(6,2), 3, 2, 2)

ST_Point_Inside_Circle(ST_Point(3,1), 3, 2, 2)

Related functions
ST_Point

352

Reference

Name
ST_XMax Returns the maximum X of the geometry bounding box.

Synopsis
double ST_XMax(bytea Geometry);

Alias
XMax

Description
Returns the maximum X of the geometry bounding box.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsText(Box2D(ST_GeomFromText('LINESTRING (1 1, 2 3, 3 2, 4 4)'))); --Result POLYGON ((1 1, 1 4, 4 4, 4 1, 1 1)) SELECT ST_XMax(Box2D(ST_GeomFromText('LINESTRING (1 1, 2 3, 3 2, 4 4)'))); --Result 4.0 SELECT ST_XMax(ST_GeomFromText('LINESTRING (1 1, 2 3, 3 2, 4 4)')); --Result 4.0

Related functions
ST_XMin,ST_YMax,ST_YMin,ST_ZMax,ST_ZMin

353

Reference

Name
ST_XMin Returns the minimum X of the geometry bounding box.

Synopsis
double ST_XMin(bytea Geometry);

Alias
XMin

Description
Returns the minimum X of the geometry bounding box.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsText(Box2D(ST_GeomFromText('LINESTRING (1 1, 2 3, 3 2, 4 4)'))); --Result POLYGON ((1 1, 1 4, 4 4, 4 1, 1 1)) SELECT ST_XMin(Box2D(ST_GeomFromText('LINESTRING (1 1, 2 3, 3 2, 4 4)'))); --Result 1.0 SELECT ST_XMin(ST_GeomFromText('LINESTRING (1 1, 2 3, 3 2, 4 4)')); --Result 1.0

Related functions
ST_XMax,ST_YMax,ST_YMin,ST_ZMax,ST_ZMin

354

Reference

Name
ST_YMax Returns the maximum Y of the geometry bounding box.

Synopsis
double ST_YMax(bytea Geometry);

Alias
YMax

Description
Returns the maximum Y of the geometry bounding box.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsText(Box2D(ST_GeomFromText('LINESTRING (1 1, 2 3, 3 2, 4 6)'))); --Result POLYGON ((1 1, 1 6, 4 6, 4 1, 1 1)) SELECT ST_YMax(Box2D(ST_GeomFromText('LINESTRING (1 1, 2 3, 3 2, 4 6)'))); --Result 6.0 SELECT ST_YMax(ST_GeomFromText('LINESTRING (1 1, 2 3, 3 2, 4 6)')); --Result 6.0

Related functions
ST_XMax,ST_XMin,ST_YMin,ST_ZMax,ST_ZMin

355

Reference

Name
ST_YMin Returns the minimum Y of the geometry bounding box.

Synopsis
double ST_YMin(bytea Geometry);

Alias
YMin

Description
Returns the minimum Y of the geometry bounding box.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsText(Box2D(ST_GeomFromText('LINESTRING (1 0, 2 3, 3 2, 4 4)'))); --Result POLYGON ((1 0, 1 4, 4 4, 4 0, 1 0)) SELECT ST_YMin(Box2D(ST_GeomFromText('LINESTRING (1 0, 2 3, 3 2, 4 4)'))); --Result 0.0 SELECT ST_YMin(ST_GeomFromText('LINESTRING (1 0, 2 3, 3 2, 4 4)')); --Result 0.0

Related functions
ST_XMax,ST_XMin,ST_YMax,ST_ZMax,ST_ZMin

356

Reference

Name
ST_ZMax Returns the maximum Z of the geometry bounding box.

Synopsis
double ST_ZMax(bytea Geometry);

Alias
ZMax

Description
Returns the maximum Z of the geometry bounding box.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsText(Box3D(ST_GeomFromText('LINESTRING (1 1 -5, 2 3 10, 3 2 5, 4 4 0)'))); --Result POLYGON ((1 1 -5, 1 4 10, 4 4 10, 4 1 -5, 1 1 -5)) SELECT ST_ZMax(Box3D(ST_GeomFromText('LINESTRING (1 1 -5, 2 3 10, 3 2 5, 4 4 0)'))); --Result 10.0 SELECT ST_ZMax(ST_GeomFromText('LINESTRING (1 1 -5, 2 3 10, 3 2 5, 4 4 0)')); --Result 10.0

Related functions
ST_XMax,ST_XMin,ST_YMax,ST_YMin,ST_ZMin

357

Reference

Name
ST_ZMin Returns the minimum Z of the geometry bounding box.

Synopsis
double ST_ZMin(bytea Geometry);

Alias
ZMin

Description
Returns the minimum Z of the geometry bounding box.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsText(Box3D(ST_GeomFromText('LINESTRING (1 1 -5, 2 3 10, 3 2 5, 4 4 0)'))); --Result POLYGON ((1 1 -5, 1 4 10, 4 4 10, 4 1 -5, 1 1 -5)) SELECT ST_ZMin(Box3D(ST_GeomFromText('LINESTRING (1 1 -5, 2 3 10, 3 2 5, 4 4 0)'))); --Result -5.0 SELECT ST_ZMin(ST_GeomFromText('LINESTRING (1 1 -5, 2 3 10, 3 2 5, 4 4 0)')); --Result -5.0

Related functions
ST_XMax,ST_XMin,ST_YMax,ST_YMin,ST_ZMax

358

Reference

Name
ST_Box Returns a Polygon geometry representation of the 2D or 3D bounding box

Synopsis
geometry ST_Box(bytea Geometry);

Alias
Box, ST_Box, ST_AsBox

Description
Returns a Polygon geometry representation of the bounding box

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
SELECT ST_AsEWKT(ST_Box(ST_GeomFromText('LINESTRING (1 1, 2 3, 3 2, 4 4)',25830))); --Result SRID=25830;POLYGON ((1 1, 1 4, 4 4, 4 1, 1 1)) SELECT ST_AsEWKT(ST_Box(ST_GeomFromText('LINESTRING (1 1 -5, 2 3 10, 3 2 5, 4 4 0)',25830))); --Result SRID=25830;POLYGON ((1 1 -5, 1 4 10, 4 4 10, 4 1 -5, 1 1 -5))

Related functions
ST_Box2D,ST_Box3D

359

Reference

Name
ST_AsWKTSRS Returns the Well-known Text representation of the Spatial Reference System.

Synopsis
varchar ST_AsWKTSRS(integer SRID);

Alias
AsWKTSRS

Description
Returns the Well-known Text representation of the Spatial Reference System. This function searches the field SRTEXT in the Spatial Reference Systems table, which is named SPATIAL_REF_SYS. If the SRID is not found, it returns a warning.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

360

Reference

Examples
--SRID=25830 SELECT ST_AsWKTSRS(25830); --Result PROJCS["ETRS89 / UTM zone 30N", GEOGCS["ETRS89", DATUM["European Terrestrial Reference System 1989", SPHEROID["GRS 1980", 6378137.0, 298.257222101, AUTHORITY["EPSG","7019"]], TOWGS84[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], AUTHORITY["EPSG","6258"]], PRIMEM["Greenwich", 0.0, AUTHORITY["EPSG","8901"]], UNIT["degree", 0.017453292519943295], AXIS["Geodetic latitude", NORTH], AXIS["Geodetic longitude", EAST], AUTHORITY["EPSG","4258"]], PROJECTION["Transverse Mercator", AUTHORITY["EPSG","9807"]], PARAMETER["central_meridian", -3.0], PARAMETER["latitude_of_origin", 0.0], PARAMETER["scale_factor", 0.9996], PARAMETER["false_easting", 500000.0], PARAMETER["false_northing", 0.0], UNIT["m", 1.0], AXIS["Easting", EAST], AXIS["Northing", NORTH], AUTHORITY["EPSG","25830"]] --SRID=1 (Not Valid) SELECT ST_AsWKTSRS(1); --Result SRS not supported by GeoTools (1): org.opengis.referencing. NoSuchAuthorityCodeException: No code "EPSG:1" from authority "European Petroleum Survey Group" found for object of type "CoordinateReferenceSystem".

Related functions
Find_SRID

361

Reference

Name
MinPair It takes as input parameter an array of two double values, and returns the minimum second value of the array.

Synopsis
Array MinPair(Array [double A , double B]);

Alias
-

Description
It takes as input parameter an array of two double values, and returns the minimum second value of the array. This function can be used to obtain the minimum distance between a set of points, as shown in the following examples. Within PostgreSQL it is used with the spatial index to reduce the search space.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
PostgreSQL
create insert insert insert table a(c1 double precision, c2 double precision); into a values (10,2.456); into a values (5,1.456); into a values (20,2.256);

select minpair(Array[c1,c2]) from a; minpair ----------{5,1.456} (1 row)

H2
create table insert into insert into insert into a(c1 integer, c2 double); a values (10,2.456); a values (5,1.456); a values (20,2.256);

select minpair((c1::double,c2)) from a; --Result MINPAIR((CAST(C1 AS DOUBLE), C2)) (5.0, 1.456)

362

Reference

How to use MinPair to obtain the minimum distance:


Suppose you have a table of points and you want to get which is the closest point to each point and the shortest distance between them.

CREATE TABLE points(gid serial PRIMARY KEY); SELECT AddGeometryColumn ('points','geom',-1,'POINT',2); --H2: SELECT AddGeometryColumn ('POINTS','GEOM',-1,'POINT',2);

INSERT INTO points(geom) VALUES (ST_GeomfromText('POINT (8 10)')); ... gid | st_astext -----+--------------1 | POINT (8 10) 2 | POINT (18 15) 3 | POINT (11 15) 4 | POINT (13 13) 5 | POINT (11 12) 6 | POINT (0 11) 7 | POINT (15 3) 8 | POINT (28 17) 9 | POINT (19 23) 10 | POINT (27 8) 11 | POINT (7 2) 12 | POINT (20 10) 13 | POINT (7 23) (13 rows)

PostgreSQL
SELECT d1.gid, MinPair(ARRAY[d2.gid,distance(d1.geom,d2.geom)]), count(*) FROM points d1, points d2 WHERE (ST_Expand (d1.geom,10) && d2.geom) and distance (d1.geom,d2.geom) > 0 GROUP BY d1.gid; gid | minpair | count -----+-----------------------+------1 | {5,3.60555127546399} | 7 2 | {4,5.3851648071345} | 8 3 | {4,2.82842712474619} | 7 4 | {5,2.23606797749979} | 8 5 | {4,2.23606797749979} | 7 6 | {1,8.06225774829855} | 2 7 | {11,8.06225774829855} | 5 8 | {10,9.05538513813742} | 4 9 | {2,8.06225774829855} | 4 10 | {12,7.28010988928052} | 3 11 | {1,8.06225774829855} | 4 12 | {2,5.3851648071345} | 7 13 | {3,8.94427190999916} | 2 (13 rows)

H2

363

Reference

SELECT d1.gid, MinPair((d2.gid::double,distance(d1.geom,d2.geom))) as minpair, count(*) FROM points d1, points d2 WHERE distance (d1.geom,d2.geom) > 0 GROUP BY d1.gid; GID MINPAIR COUNT(*) 1 (5.0, 3.605551275463989) 12 2 (4.0, 5.385164807134504) 12 3 (4.0, 2.8284271247461903) 12 4 (5.0, 2.23606797749979) 12 5 (4.0, 2.23606797749979) 12 6 (1.0, 8.06225774829855) 12 7 (11.0, 8.06225774829855) 12 8 (10.0, 9.055385138137417) 12 9 (2.0, 8.06225774829855) 12 10 (12.0, 7.280109889280518) 12 11 (1.0, 8.06225774829855) 12 12 (2.0, 5.385164807134504) 12 13 (3.0, 8.94427190999916) 12

Related functions

364

Reference

Name
MaxPair It takes as input parameter an array of two double values, and returns the maximum second value of the array.

Synopsis
Array MaxPair(Array [double A , double B]);

Alias
-

Description
It takes as input parameter an array of two double values, and returns the maximum second value of the array. This function can be used to obtain the maximum distance between a set of points, as shown in the following examples. Within PostgreSQL it is used with the spatial index to reduce the search space.

Coordinate Dimensions
2D 3D M

Spatial Standards Support


OGC SFS for SQL. 1.1 (1999) OGC SFS for SQL. 1.1.0 (2005) OGC SFS for SQL. 1.2.0 (2006) SQL-MM Part 3

Examples
PostgreSQL
create insert insert insert table a(c1 double precision, c2 double precision); into a values (10,2.456); into a values (5,1.456); into a values (20,2.256);

select MaxPair(Array[c1,c2]) from a; maxpair -----------{10,2.456} (1 row)

H2
create insert insert insert table a(c1 integer, c2 double); into a values (10,2.456); into a values (5,1.456); into a values (20,2.256);

select Maxpair((c1::double,c2)) from a; --Result (10.0, 2.456)

How to use MinPair to obtain the maximum distance:


Suppose you have a table of points and you want to get which is the farthest point to each point and the longest distance between them.

365

Reference

CREATE TABLE points(gid serial PRIMARY KEY); SELECT AddGeometryColumn ('points','geom',-1,'POINT',2); --H2: SELECT AddGeometryColumn ('POINTS','GEOM',-1,'POINT',2); INSERT INTO points(geom) VALUES (ST_GeomfromText('POINT (8 10)')); ... gid | st_astext -----+--------------1 | POINT (8 10) 2 | POINT (18 15) 3 | POINT (11 15) 4 | POINT (13 13) 5 | POINT (11 12) 6 | POINT (0 11) 7 | POINT (15 3) 8 | POINT (28 17) 9 | POINT (19 23) 10 | POINT (27 8) 11 | POINT (7 2) 12 | POINT (20 10) 13 | POINT (7 23) (13 rows)

PostgreSQL
SELECT d1.gid, MaxPair(ARRAY[d2.gid,distance(d1.geom,d2.geom)]), count(*) FROM points d1, points d2 WHERE (ST_Expand (d1.geom,30) && d2.geom) and distance (d1.geom,d2.geom) > 0 GROUP BY d1.gid; gid | maxpair | count -----+-----------------------+------1 | {8,21.1896201004171} | 12 2 | {6,18.4390889145858} | 12 3 | {10,17.464249196573} | 12 4 | {8,15.52417469626} | 12 5 | {8,17.7200451466693} | 12 6 | {8,28.6356421265527} | 12 7 | {13,21.540659228538} | 12 8 | {6,28.6356421265527} | 12 9 | {11,24.1867732448956} | 12 10 | {6,27.1661554144122} | 12 11 | {8,25.8069758011279} | 12 12 | {6,20.0249843945008} | 12 13 | {10,25} | 12 (13 rows)

H2

366

Reference

SELECT d1.gid, MinPair((d2.gid::double,distance(d1.geom,d2.geom))) as minpair, count(*) FROM points d1, points d2 WHERE distance (d1.geom,d2.geom) > 0 GROUP BY d1.gid; GID MINPAIR COUNT(*) 1 (8.0, 21.18962010041709) 12 2 (6.0, 18.439088914585774) 12 3 (10.0, 17.46424919657298) 12 4 (8.0, 15.524174696260024) 12 5 (8.0, 17.72004514666935) 12 6 (8.0, 28.635642126552707) 12 7 (13.0, 21.540659228538015) 12 8 (6.0, 28.635642126552707) 12 9 (11.0, 24.186773244895647) 12 10 (6.0, 27.16615541441225) 12 11 (8.0, 25.80697580112788) 12 12 (6.0, 20.024984394500787) 12 13 (10.0, 25.0) 12

Related functions
MinPair

367

Chapter 10. Functions Clarification


10.1. ST_Collect, ST_Force_Collection, ST_MakeGeomColl
ST_Collect Purpose ST_Force_Collection ST_MakeGeomColl Returns a geometry from Forces the geometry to be a Constructs a the collection of others GEOMETRYCOLLECTION. GeometryCollection object geometries. from a set of Geometries. geometry geometry geometry ST_Collect(bytea ST_Force_Collection ST_MakeGeomColl GeomA, bytea (bytea Geometry); (bytea GeomB); Geometry_Array); geometry ST_Collect(bytea[] Geometry_Array); geometry ST_Collect(bytea Aggregate); Input geometries 2 geometries Array of geometries Aggregate Example
SELECT ST_AsText(ST_Collect( ST_GeomFromText(' POLYGON ((3 2, 7 7, 7 2, 3 2))'), ST_GeomFromText(' POLYGON ((5 5, 9 10, 9 5, 5 5))') )); --Result MULTIPOLYGON (((30 20, 30 70, 70 70, 70 20, 30 20)), ((50 50, 50 100, 90 100, 90 50, 50 50))) SELECT ST_AsText( ST_Force_Collection ( ST_GeomFromText(' POLYGON ((3 2, 7 7, 7 2, 3 2))' ) )); --Result GEOMETRYCOLLECTION (POLYGON ((30 20, 30 70, 70 70, 70 20, 30 20))) SELECT ST_AsText( ST_MakeGeomColl ( st_accumagg(geom))) as geomcollect from (select array_get(( st_geomfromtext(' POLYGON ((3 2, 7 7, 7 2, 3 2))'), st_geomfromtext(' POLYGON ((5 5, 9 10, 9 5, 5 5))') ),x)::binary as geom from (select x from system_range(1,2) as foo) as table); --Result GEOMETRYCOLLECTION (POLYGON ((30 20, 30 70, 70 70, 70 20, 30 20)), POLYGON ((50 50, 50 100, 90 100, 90 50, 50 50)))

Synopsis

geometry ST_MakeGeomColl (bytea Geometry_Aggregate);

A single geometry

Array of geometries Aggregate

Result

GEOMETRYCOLLECTION GEOMETRYCOLLECTION MULTI* GEOMETRYCOLLECTION

368

Functions Clarification

10.2. ST_Expand for indexable queries


Find the lines that are within a distance of 1 meter to the "A" line. In this example, the quickest and most intuive way to find it is using a clause "WHERE ST_Distance (A,B) < 1".

In indexable queries the Bounding Boxes are used to reduce the searching area. First step is to expand the BBox.
SELECT ST_AsText(ST_Expand(A,1)) FROM (SELECT ST_GeomFromText('LINESTRING (1 1, 2 3, 3 2, 4 4)') AS A) as foo; --Result POLYGON ((0 0, 0 5, 5 5, 5 0, 0 0))

Next, ST_Expand (A,1) && B is used to do indexable queries. In the following query, we check if the Bounding Boxes overlap.
SELECT ((ST_Expand(A,1) && B)) as AB, ((ST_Expand(A,1) && C)) as AC FROM (SELECT ST_GeomFromText('LINESTRING (1 1, 2 3, 3 2, 4 4)') as A, ST_GeomFromText('LINESTRING (4 3, 5 2, 7 2, 7 2)') as B, ST_GeomFromText('LINESTRING (4 5, 5 6, 7 4)') as C ) as foo; --Result: ab | ac ----+---t | t (1 row)

The last step is to check , just in the overlapping BBoxes, if the geometries are really in a distance < 1 m.
SELECT ((ST_Expand(A,1) && B) and ST_Distance(A,B)<1) as AB, ((ST_Expand(A,1) && C) and ST_Distance(A,C)<1) as AC FROM (SELECT ST_GeomFromText('LINESTRING (1 1, 2 3, 3 2, 4 4)') as A, ST_GeomFromText('LINESTRING (4 3, 5 2, 7 2, 7 2)') as B, ST_GeomFromText('LINESTRING (4 5, 5 6, 7 4)') as C ) as foo; --Result ab | ac ----+---t | f (1 row)

369

Functions Clarification

ST_DWithin (A,B,1) is equivalent to ((ST_Expand(A,1) && B) and ST_Distance(A,B)<1), with the advantage of which it has a much simpler syntax The following example shows the same query with the ST_DWithin function
SELECT ST_DWithin (A,B,1) as AB, ST_DWithin (A,C,1) FROM (SELECT ST_GeomFromText('LINESTRING (1 1, 2 3, ST_GeomFromText('LINESTRING (4 3, 5 2, 7 2, 7 2)') ST_GeomFromText('LINESTRING (4 5, 5 6, 7 4)') as C as AC 3 2, 4 4)') as A, as B, ) as foo;

10.3. ST_Dump, ST_DumpRings, ST_DumpPoints


ST_Dump, ST_DumpRings and ST_DumpPoints are functions that takes some geometries and returns a set of geometries. The behaviour of these functions is differentent in Jaspa for PostgreSQL and Jaspa for H2.

10.3.1. PostgreSQL Simple entity


There are two ways of using ST_Dump 1. From ST_Dump
SELECT * from st_dump(st_geomfromewkt('MULTIPOINT (1 2, 3 4, 5 6)')); SELECT st_astext(a) from st_dump(st_geomfromewkt('MULTIPOINT (1 2, 3 4, 5 6)')) as a;

2. SELECT ST_Dump
SELECT st_dump(st_geomfromewkt('MULTIPOINT (1 2, 3 4, 5 6)')); SELECT ST_AsText(st_dump(st_geomfromewkt('MULTIPOINT (1 2, 3 4, 5 6)')));

Table
The use of ST_Dump with a set of geometries from a table appears in the following example:
select st_dump(geom) from table;

10.3.2. H2 Simple entity


The utilization of ST_Dump with a single geometry appears in the following example:
SELECT geom FROM ST_Dump('select st_geomfromewkt(''MULTIPOINT (1 2, 3 4, 5 6)'')');

Table
The use of ST_Dump with a set of geometries from a table appears in the following example:
select geom from st_dump('select <geometry_column> as geom from <table>')

You can also recover other fields from the dumped geometries. Just keep in mind that always the first argument of the ST_Dump select clause must be of geometry type. The next example illustrates it:
select a, geom from st_dump('select <geometry_column> as geom, <table_column> as a from <table>')

370

Appendix A. Jaspa Versions


A.1. Jaspa 0.2.0
Release date:

Changes
New internal JASPA binary format, it supports different format versions and prepares Jaspa for future versions. Bug in ST_AsEWKB function. Binary NDR encoding fixed. UMN Mapserver was not working. ST_CollectionExtract, imitates PostGIS behaviour. ST_SetPoint supports GeometryCollections, MultiPoints and Points. Code refactoring has been performed. Jaspa exceptions inherit from JASPAException class, all exceptions have been wrapped.

New Features
Chapter 6, Topology 71 topology rules (applicable to different types of geometries), including 30 of the 31 rules of ArcGIS 10 topology rules. shp2jaspapg /// shp2jaspah2 converters include a new parameter a new parameter -co / -CO to include / exclude fields in the conversion. jaspapg2shp // jaspah22shp converters to obtain shp files from jaspa files. Backup files to update a spatial database Connectors to GIS Kosmo 2.0.1 and gvSIG 1.11 ST_Last This function returns the last geometry of a set of geometries. ST_RepeatedPoints This function checks if a geometry has repeated vertices. If any, returns a MultiPoint geometry composed by the points that are duplicated. Jaspa_Java_Properties Returns information about the OS and the JRE used. MinPair Minpair MaxPair Maxpair Probe_Geometry_Columns Add spatial tables to the metadata table GEOMETRY_COLUMNS

A.2. Jaspa 0.1 RC1


Release date: 2010-07-22

371

You might also like