PostGIS Tutorial
Geospatial Database
Table of Contents
-
What is a geospatial database?
Features of a geospatial database
-
Why PostGIS?
Reasons to choose PostGIS over other DBs
-
Setup PostGIS
Setup PostgreSQL and create PostGIS extension
-
PostGIS Geometry
Data types for geometries.
-
PostGIS Functions
Geo spatial query functions
-
PostGIS Transformations
Apply changes to geometries
PostGIS Cheat Sheet
Click here to download a Quick Reference cheat sheet
What is a geospatial database?
A geospatial database is a relational database which support the concept of geographic features:
- It has special geometric data types which describe geographic features such as Points, Lines and Polygons.
- It has special geometric operations to modify and query geographic features. For instance, there is an operation to check if two Polygons intersect.
Setup PostGIS
Install & Setup PostgreSQL
PostgreSQL is the database platform on top of which PostGIS runs.
PostGIS is one of many extensions to the PostgreSQL database. Therefore, you need to install PostgreSQL.
On Ubuntu/Linux
Execute the following in the shell:
# update system repositories
sudo apt update
# install PostgreSQL and support packages
sudo apt install postgresql postgresql-contrib
# install PostGIS
sudo apt install postgis
# start PostgreSQL service
sudo systemctl start postgresql.service
# optional - enable service to start on boot
sudo systemctl enable postgresql.service
On Windows and Mac OS
The EDB company provides PostgreSQL installers for Windows and Mac OS here.
Create Database & Enable PostGIS
Geospatial capabilities of PostGIS must be enabled before they can be used. You can enable PostGIS both - on existing and new databases.
First, you have to log into database as a psql client shell.
On Ubuntu/Linux in the shell:
# log in as the postgres system user
sudo su postgres
# open the postgreSQL client terminal
psql
Optionally, you can create a new logical database.
Inside the psql client:
-- optionally, create a new logical database
CREATE DATABASE postgis_example;
-- connect to the database
\c postgis_example;
-- enable the PostGIS
CREATE EXTENSION postgis;
-- Test if PostGIS is enabled
SELECT PostGIS_Version();
+-------------------------------------+
|postgis_version |
+-------------------------------------+
|3.1 USE_GEOS=1 USE_PROJ=1 USE_STATS=1|
+-------------------------------------+
PostGIS Geometry
PostGIS Datatypes
Geospatial databases provide special data types for spatial features: geometry. Columns of data type geometry save spatial geometry information in binary format. The binary format saves space and is optimized for fast operations and indexing.
You can populate geometry columns from a human-readable textual format call Well Known Text (WKT). The SQL functions ST_AsText() and ST_GeomFromText() allow us to convert between WKT and the binary format:
-- create a table which uses the geometry type in column location
CREATE TABLE city (name text, location geometry);
-- use ST_GeomFromText() to convert from WKT representation
INSERT INTO city(name, location) VALUES
('New York', ST_GeomFromText('POINT(-74.006111 40.712778)', 4326)),
('Dubai', ST_GeomFromText('POINT(55.297222 25.263056)', 4326)),
('Tokyo', ST_GeomFromText('POINT(139.692222 35.689722)', 4326));
-- use ST_AsText() to display the geometry
SELECT name, ST_AsText(location) AS "location" FROM city;
+--------+---------------------------+
|name |location |
+--------+---------------------------+
|New York|POINT(-74.006111 40.712778)|
|Dubai |POINT(55.297222 25.263056) |
|Tokyo |POINT(139.692222 35.689722)|
+--------+---------------------------+
ST_GeomFromText(), accepts the Coordinate Reference System's SRID as an optional second parameter. It is good habit to always specify the SRID.
ST_GeomFromText() accepts different geometries. Here is a list of the most important geometries:
POINT
Represents a single Point geometry.
POINT(5.0 5.0)
LINESTRING
Represents a line made up of multiple coordinates. The coordinates are defined in serial, comma-separated list.
LINESTRING(1 0, 2 3, 5 5, 7 7, 5 10)
POLYGON
Creates a Polygon from a series of coordinates.
- The last and first coordinate needs to be duplicated to close the polygon.
- The direction (winding) of coordinates is important. Arrange the coordinates counter-clockwise.
POLYGON((1 0, 8 1, 5 5, 7 9, 1 8, 1 0))
POLYGON() requires a list of coordinate series. For a simple polygon (no holes) this list contains only one series of coordinates: POLYGON((coordinates))
Polygons can have holes. These holes are defined by additional polygons inside the list:
POLYGON((1 0, 8 1, 5 5, 7 9, 1 8, 1 0), (3 3, 4 6, 2 6, 3 3))
Besides those three basic geometry types, PostGIS also recognizes geometry collections MULTIPOINT, MULTILINESTRING and MULTIPOLYGON. These collection types accept multiple geometries in a comma-separated list:
MULTIPOINT((14.49370 35.54659), (14.89928 35.85830))
PostGIS Queries
Queries for Geospatial Relationships
The real power of using PostGIS for geospatial data inside rests in its queries: You can create spatial queries addressing the geometric information of your data. For example:
- By Distance: You can query all geometries which are below a distance from a given geometry: Select all drivers which are less than 5km away from the city center.
- GeoFencing & Spatial Relationships: You can query all geometries which are inside another geometry: Select all drivers which are within an area polygon. Or select all power lines which intersect with roads.
The most common PostGIS query operations are:
ST_Distance() for measuring distances
ST_Distance(firstGeometry, secondGeometry) measures the distance between the first geometry and second geometry.
The distance is calculated in projected units of the underlying coordinate system. To measure the distance of latitude/longitude in meters, you need to project your coordinates into Spherical Mercator first. This guide is an example of how to distance lat/lon coordinates in meters.
-- create a table with a geometry column
CREATE TABLE test_geometries (name VARCHAR(50) NOT NULL, geom GEOMETRY);
-- insert the point values
INSERT INTO test_geometries (name, geom)
VALUES
('(5, 5)', ST_GeomFromText('POINT(5 5)')),
('(2,10)', ST_GeomFromText('POINT(2 10)')),
('(9, 9)', ST_GeomFromText('POINT(9 9)')),
('(7, 7)', ST_GeomFromText('POINT(7 7)')),
('(3, 3)', ST_GeomFromText('POINT(3 3)')),
('(6, 3)', ST_GeomFromText('POINT(6 3)')),
('(0, 9)', ST_GeomFromText('POINT(0 9)'));
-- select rows with distance <5 from the point (5,5)
SELECT name, ST_Distance(ST_GeomFromText('POINT(5 5)'), geom) AS "distance"
FROM test_geometries
WHERE ST_Distance(ST_GeomFromText('POINT(5 5)'), geom) < 5.0;
+------+------------------+
|name |distance |
+------+------------------+
|(5, 5)|0 |
|(7, 7)|2.8284271247461903|
|(3, 3)|2.8284271247461903|
|(6, 3)|2.23606797749979 |
+------+------------------+
ST_Distance() works for all geometry types. ST_Distance() will return the distance of the closest approach between geometries of different types.
CREATE TABLE test_geometries (name VARCHAR(50) NOT NULL, geom GEOMETRY);
-- insert geometries of different types
INSERT INTO test_geometries (name, geom)
VALUES
-- reference point
('(5,5)', ST_GeomFromText('POINT(5 5)')),
-- geometries with distance >5 from (5,5)
('Polygon (0,9)', ST_GeomFromText('POLYGON((0 9, 0 10, 1 10, 1 9, 0 9))')),
('Line (8,10)', ST_GeomFromText('LINESTRING(8 10, 9 9, 10 9)')),
('Point (2,10)', ST_GeomFromText('POINT(2 10)')),
-- geometries with distance <5 from (5,5)
('Polygon (3,5)', ST_GeomFromText('POLYGON((3 5, 0 1, 3 0, 3 5))')),
('Line (7,7)', ST_GeomFromText('LINESTRING(7 7, 7 4)')),
('Point (6,3)', ST_GeomFromText('POINT(6 3)'));
-- select rows with distance <5 from the point (5,5)
SELECT name, ST_Distance(ST_GeomFromText('POINT(5 5)'), geom) AS "distance"
FROM test_geometries
WHERE ST_Distance(ST_GeomFromText('POINT(5 5)'), geom) < 5.0;
+-------------+----------------+
|name |distance |
+-------------+----------------+
|(5,5) |0 |
|Polygon (3,5)|2 |
|Line (7,7) |2 |
|Point (6,3) |2.23606797749979|
+-------------+----------------+
ST_Contains() one geometry completely contains another geometry
ST_Contains(firstGeometry, secondGeometry) returns true if the first geometry completely encapsulates the second geometry.
-- table with geometries and id as PK
CREATE TABLE test_geometries (name VARCHAR(50) NOT NULL, geom GEOMETRY);
-- insert some test geometries
INSERT INTO test_geometries (name, geom)
VALUES
-- geometries outside
('Point (2,10)', ST_GeomFromText('POINT(2 10)')),
('Polygon (4,9)', ST_GeomFromText('POLYGON((4 9, 3 9, 4 7, 4 9))')),
('Line (8,10)', ST_GeomFromText('LINESTRING(8 10, 9 9, 10 9)')),
('Line (10,3)', ST_GeomFromText('LINESTRING(10 3, 7 3)')),
('Polygon (0,6)', ST_GeomFromText('POLYGON((0 6, 0 7, 1 7, 1 6, 0 6))')),
-- this is on the edge - but still not inside
('Line (8,6)', ST_GeomFromText('LINESTRING(8 6, 8 4)')),
-- geometries inside
('Polygon (5,3)', ST_GeomFromText('POLYGON((5 3, 3 5, 3 3, 5 3))')),
('Point (5,6)', ST_GeomFromText('POINT(5 6)')),
('Line (7,7)', ST_GeomFromText('LINESTRING(7 7, 7 4)'));
-- select the rows inside the geo fence
SELECT name, ST_AsText(geom) AS "geometry"
FROM test_geometries
-- where will check if the row is inside the geo fence
WHERE ST_Contains(
-- create the geo fence from text
ST_GeomFromText('POLYGON((2 2, 8 2, 8 8, 2 8, 2 2))'), geom
)
+-------------+--------------------------+
|name |geometry |
+-------------+--------------------------+
|Polygon (5,3)|POLYGON((5 3,3 5,3 3,5 3))|
|Point (5,6) |POINT(5 6) |
|Line (7,7) |LINESTRING(7 7,7 4) |
+-------------+--------------------------+
ST_Intersects() one geometry intersects with another geometry
ST_Intersects(firstGeometry, secondGeometry) returns true if the first geometry intersects the second geometry.
ST_Intersects() returns true if firstGeometry and secondGeometry share at least one common coordinate irrelevant of their geometry type.
-- table with geometries and id as PK
CREATE TABLE test_geometries (name VARCHAR(50) NOT NULL, geom GEOMETRY);
-- insert some test geometries
INSERT INTO test_geometries (name, geom)
VALUES
-- no intersection
-- not a single common coordinate
('Polygon (0,6)', ST_GeomFromText('POLYGON((0 6, 0 7, 1 7, 1 6, 0 6))')),
('Point (2,10)', ST_GeomFromText('POINT(2 10)')),
('Line (8,10)', ST_GeomFromText('LINESTRING(8 10, 9 9, 10 9)')),
-- does intersect
-- because has at least one common coordinate
('Polygon (4,9)', ST_GeomFromText('POLYGON((4 9, 3 9, 4 7, 4 9))')),
('Polygon (5,3)', ST_GeomFromText('POLYGON((5 3, 3 5, 3 3, 5 3))')),
('Point (5,6)', ST_GeomFromText('POINT(5 6)')),
('Line (7,7)', ST_GeomFromText('LINESTRING(7 7, 7 4)')),
('Line (10,3)', ST_GeomFromText('LINESTRING(10 3, 7 3)')),
('Line (8,6)', ST_GeomFromText('LINESTRING(8 6, 8 4)'));
-- select the rows inside the geo fence
SELECT name, ST_AsText(geom) AS "geometry"
FROM test_geometries
-- where will check if the row intersects with the geo fence
WHERE ST_Intersects(
-- create the geo fence from text
ST_GeomFromText('POLYGON((2 2, 8 2, 8 8, 2 8, 2 2))'), geom
);
+-------------+--------------------------+
|name |geometry |
+-------------+--------------------------+
|Polygon (5,3)|POLYGON((5 3,3 5,3 3,5 3))|
|Point (5,6) |POINT(5 6) |
|Line (7,7) |LINESTRING(7 7,7 4) |
|Line (10,3) |LINESTRING(10 3,7 3) |
|Line (8,6) |LINESTRING(8 6,8 4) |
|Polygon (4,9)|POLYGON((4 9,3 9,4 7,4 9))|
+-------------+--------------------------+
ST_Overlaps() one geometry overlaps another geometry
ST_Overlaps(firstGeometry, secondGeometry) returns true if the first geometry overlaps the second geometry.
ST_Overlaps() returns true if:
- The firstGeometry is of the same type as the secondGeometry (e.g. POLYGON/POLYGON).
- The firstGeometry and secondGeometry share at least one common coordinate.
- The firstGeometry and secondGeometry have at least one different coordinate.
-- table with geometries and id as PK
CREATE TABLE test_geometries (name VARCHAR(50) NOT NULL, geom GEOMETRY);
-- insert some test geometries
INSERT INTO test_geometries (name, geom)
VALUES
-- no overlap
('Polygon (0,6)', ST_GeomFromText('POLYGON((0 6, 0 7, 1 7, 1 6, 0 6))')),
('Point (2,10)', ST_GeomFromText('POINT(2 10)')),
('Line (8,10)', ST_GeomFromText('LINESTRING(8 10, 9 9, 10 9)')),
('Polygon (5,3)', ST_GeomFromText('POLYGON((5 3, 3 5, 3 3, 5 3))')),
('Point (5,6)', ST_GeomFromText('POINT(5 6)')),
('Line (7,7)', ST_GeomFromText('LINESTRING(7 7, 7 4)')),
('Line (10,3)', ST_GeomFromText('LINESTRING(10 3, 7 3)')),
('Line (8,6)', ST_GeomFromText('LINESTRING(8 6, 8 4)')),
-- the only overlapping geometry
-- because (1) same type (2) one common coordinate and
-- (3) two uncommon coordinates
('Polygon (4,9)', ST_GeomFromText('POLYGON((4 9, 3 9, 4 7, 4 9))'));
-- select the rows inside the geo fence
SELECT name, ST_AsText(geom) AS "geometry"
FROM test_geometries
-- where will check if the row overlaps with the geo fence
WHERE ST_Overlaps(
-- create the geo fence from text
ST_GeomFromText('POLYGON((2 2, 8 2, 8 8, 2 8, 2 2))'), geom
);
+-------------+--------------------------+
|name |geometry |
+-------------+--------------------------+
|Polygon (4,9)|POLYGON((4 9,3 9,4 7,4 9))|
+-------------+--------------------------+
PostGIS Transformations
Changes to Geometries
Transformations make changes to geometries. They are used to modify and combine geometric shapes. Basically, they are SQL functions which accept one or more geometries as an input and create a new geometry as an output.
All transformations have one or more input geometry and one output geometry. The type of the input and output is determined by the function itself.
ST_Collect(geometries)
Transforms a set of individual geometries into a single multigeometry.
The output type of the multigeometry depends on the input geometries:
- If all input geometries are of type POINT, the output type will be MULTIPOINT
- If all input geometries are of type LINE, the output type will be MULTILINE
- In any other case the output type will be MULTIPOLYGON
ST_Collect() is an aggregate function. Many of the other transformations (e.g. ST_ConvexHull()) expect a multigeometry as input. ST_Collect() is often used to prepare this input from a subquery:
SELECT famous_buildings.name,
ST_Contains(city_area.boundary, famous_buildings.geom) AS "is_in_london"
FROM famous_buildings
CROSS JOIN
(SELECT ST_ConvexHull(ST_Collect(geom)) AS boundary
FROM corner_stones
WHERE city = 'London'
GROUP BY city) AS city_area
+---------------------+------------+
|name |is_in_london|
+---------------------+------------+
|Eiffel Tower |false |
|Tower Bridge |true |
|Empire State Building|false |
|Burj Khalifa |false |
|Buckingham Palace |true |
|Tokyo Tower |false |
+---------------------+------------+
ST_Buffer(geometry, buffer_width)
Creates a buffered enlargement of a geometry. This is commonly used to test if geometries for minimum distances. buffer_width defines the width of the buffer space in coordinate units.
ST_ConcaveHull(geometries, concaveness)
Creates a polygon which encompasses all the geometries in the given collection of geometries.
Unlike ST_ConvexHull(),
it attempts to closely resemble the contours of the collection.
The concaveness parameter ranges from 0 to 1.
1 produces a convex hull, whereas 0 produces a maximum align with contours.
0.15 is a good guess.
Watch Performance
ST_ConcaveHull() may take a while to produce a result depending on the size of the geometry collection.
ST_ConvexHull(geometries)
Creates a polygon which encompasses all the geometries in the given collection of geometries. Unlike ST_ConcaveHull(), the convex polygon is shrink-wrapped around the geometries.
ST_Centroid(geometries)
Creates a POINT geometry which represents the center of mass of the given geometries. The input can be a multigeometry of any type.
ST_Union(firstGeometry, secondGeometry)
Creates a POLYGON geometry which is the merged geometries of the firstGeometry and secondGeometry.
This assumes that firstGeometry and secondGeometry do overlap. If the input geometries do not overlap, a multigeometry (i.e. MULTIPOLYGON) is created - much similar to ST_Collect().
ST_Union() also accepts aggregated geometries as an input: ST_Union(geometries)
ST_Intersection(firstGeometry, secondGeometry)
Creates a POLYGON geometry which is the merged geometries of the common overlap area between firstGeometry and secondGeometry.
This assumes that firstGeometry and secondGeometry do overlap. If the input geometries do not overlap, an empty POLYGON geometry is created.
ST_Intersection() also accepts aggregated geometries as an input: ST_Intersection(geometries)
ST_Difference(firstGeometry, secondGeometry)
Creates a POLYGON from the firstGeometry with the common overlap between firstGeometry and secondGeometry removed.
If firstGeometry and secondGeometry do not overlap, ST_Intersection() returns the unchanged firstGeometry.
ST_Difference() also accepts aggregated geometries as an input: ST_Difference(geometries)
PostGIS Output Formatting
Export Geometries
PostGIS uses a binary format to save geospatial geometries internally. We have already seen how to read and write geometries by text.
However, even the geometry represented as text requires further processing before it can be displayed or handled by a map client.
Fortunately, PostGIS provides a function which creates the GeoJSON representation of a geometry feature: ST_AsGeoJSON()
Geometries selected by ST_AsGeoJSON() can easily be read and displayed by map client libraries such as OpenLayers.
SELECT name, ST_AsGeoJSON(geom) FROM famous_buildings
+---------------------+-----------------------------------------------------+
|name |st_asgeojson |
+---------------------+-----------------------------------------------------+
|Eiffel Tower |{"type":"Point","coordinates":[2.2945,48.858222]} |
|Tower Bridge |{"type":"Point","coordinates":[-0.075406,51.5055]} |
|Empire State Building|{"type":"Point","coordinates":[-79.985278,40.748333]}|
|Burj Khalifa |{"type":"Point","coordinates":[55.274167,25.197222]} |
|Buckingham Palace |{"type":"Point","coordinates":[-0.141944,51.500833]} |
|Tokyo Tower |{"type":"Point","coordinates":[139.745556,35.658611]}|
+---------------------+-----------------------------------------------------+
ST_AsGeoJSON() creates the GeoJSON geometry representation. We can use PostgerSQL's native json constructors to create a valid GeoJSON feature including non-geometric parameters:
SELECT json_build_object(
'type', 'Feature', -- according to GeoJSON sepc
'id', id,
'geometry', ST_AsGeoJson(geom),
'properties', json_build_object('name', name)
) AS "geo_json"
FROM famous_buildings;
+--------------------------------------------------------------------------+
|geo_json |
+--------------------------------------------------------------------------+
|{ |
|"id": 1, |
|"type": "Feature", |
|"geometry": "{\"type\":\"Point\",\"coordinates\":[2.2945,48.858222]}", |
|"properties": { |
|"name": "Eiffel Tower" |
|} |
|} |
+--------------------------------------------------------------------------+
GeoJSON expects coordinates in lon/lat EPSG:4326
If your geometries are of a different CRS, make sure to transform them using ST_Transform(geom, 4326)