Skip to content

Use PostGIS for Spatial Data

Enable PostGIS on Managed PostgreSQL, choose between the geometry and geography types, index spatial columns, and write distance queries that use the index.

Enable the Extension

Connect as avnadmin and create the extension in each database that stores spatial data:

CREATE EXTENSION postgis;

Check the versions of PostGIS and of the libraries it uses:

SELECT postgis_full_version();

Companion Extensions

ExtensionWhat it adds
postgis_rasterThe raster type and raster functions
postgis_sfcgal3D operations based on SFCGAL
postgis_topologyTopology types and functions, in a topology schema
postgis_tiger_geocoderUS TIGER geocoder, in a tiger schema

They depend on postgis. CASCADE installs postgis when it is missing:

CREATE EXTENSION postgis_raster CASCADE;
CREATE EXTENSION postgis_sfcgal CASCADE;
CREATE EXTENSION postgis_topology CASCADE;

postgis_tiger_geocoder is the exception: with CASCADE and no postgis yet, it fails with permission denied to create extension "postgis". Create postgis first, then CREATE EXTENSION postgis_tiger_geocoder CASCADE;.

postgis_topology objects are in the topology schema: call them as topology.CreateTopology(...), or add the schema to your search_path.

postgis_legacy is not available: CREATE EXTENSION postgis_legacy fails with extension "postgis_legacy" is not available. Code that uses pre-2.0 function names must move to the ST_ names.

pgrouting, h3, h3_postgis and address_standardizer are also available, see Supported extensions.

Choose Between Geometry and Geography

geometrygeography
ModelFlat planeSpheroid (WGS 84)
Distance unitUnit of the SRIDMeters
SpeedFasterSlower
FunctionsAll of PostGISA subset
Good forProjected data, local analysisLongitude and latitude data, distances without projecting

Declare the SRID in the column type, so PostgreSQL rejects mismatches:

-- Longitude and latitude, distances in meters:
location geography(Point, 4326)

-- Swiss coordinates (CH1903+ / LV95), distances in meters:
geom geometry(Point, 2056)

Warning

ST_Distance() between two geometry(Point, 4326) values returns degrees, not meters. Store the column as geography, or project with ST_Transform() into a metric SRID before measuring.

Common SRIDs for European data:

SRIDNameUnitUse
4326WGS 84DegreesGPS, GeoJSON, data exchange
3857Web MercatorMetersMap tiles; distorts distances, do not measure with it
2056CH1903+ / LV95MetersSwitzerland
25832ETRS89 / UTM zone 32NMeters6°E to 12°E, for example western Germany and Austria
25833ETRS89 / UTM zone 33NMeters12°E to 18°E, for example eastern Germany and Vienna
3035ETRS89-extended / LAEA EuropeMetersEurope-wide area analysis

Pick the UTM zone your data falls in. For a segment near Vienna (16.4°E), zone 33N gives a distance close to the geography result, zone 32N about 25 m more:

SELECT
  round(ST_Distance(ST_SetSRID(ST_MakePoint(16.32, 48.2), 4326)::geography,
                    ST_SetSRID(ST_MakePoint(16.42, 48.2), 4326)::geography)::numeric, 1) AS geography_m,
  round(ST_Distance(ST_Transform(ST_SetSRID(ST_MakePoint(16.32, 48.2), 4326), 25832),
                    ST_Transform(ST_SetSRID(ST_MakePoint(16.42, 48.2), 4326), 25832))::numeric, 1) AS utm32_m,
  round(ST_Distance(ST_Transform(ST_SetSRID(ST_MakePoint(16.32, 48.2), 4326), 25833),
                    ST_Transform(ST_SetSRID(ST_MakePoint(16.42, 48.2), 4326), 25833))::numeric, 1) AS utm33_m;
 geography_m | utm32_m | utm33_m
-------------+---------+---------
      7433.6 |  7458.1 |  7431.6

Index Spatial Columns

PostGIS uses GiST indexes for geometry and geography:

CREATE INDEX charging_stations_location_idx
    ON charging_stations
    USING gist (location);

ANALYZE charging_stations;

Run ANALYZE after loading data, so that the planner has spatial statistics.

  • GiST fits nearly all cases.
  • SP-GiST and BRIN are also available. BRIN suits very large tables whose rows are stored in spatial order.
  • For 3D data, use USING gist (geom gist_geometry_ops_nd).

Only bounding-box operators and the functions built on them use the index: &&, the nearest-neighbor operator <->, ST_Intersects(), ST_Contains(), ST_Within(), ST_DWithin().

Tip

Filter by distance with ST_DWithin(a, b, 5000), which uses the index. ST_Distance(a, b) < 5000 computes the distance for every row first.

Worked Example: Nearest Points Within a Radius

A table of charging stations stored as geography, so distances are in meters:

CREATE TABLE charging_stations (
    id        bigserial PRIMARY KEY,
    name      text NOT NULL,
    operator  text,
    power_kw  numeric(6,2),
    location  geography(Point, 4326) NOT NULL
);

INSERT INTO charging_stations (name, operator, power_kw, location) VALUES
    ('Gare Cornavin',  'ExampleCharge', 150,
     ST_SetSRID(ST_MakePoint(6.14264, 46.21044), 4326)::geography),
    ('Plainpalais',    'ExampleCharge',  50,
     ST_SetSRID(ST_MakePoint(6.13980, 46.19680), 4326)::geography),
    ('Aéroport',       'OtherOperator', 300,
     ST_SetSRID(ST_MakePoint(6.10895, 46.23180), 4326)::geography),
    ('Nyon Centre',    'ExampleCharge',  22,
     ST_SetSRID(ST_MakePoint(6.23920, 46.38300), 4326)::geography);

CREATE INDEX charging_stations_location_idx
    ON charging_stations USING gist (location);

ANALYZE charging_stations;

ST_MakePoint() takes longitude first, then latitude.

Chargers of at least 50 kW within 5 km of a point, closest first:

WITH origin AS (
    SELECT ST_SetSRID(ST_MakePoint(6.14320, 46.20440), 4326)::geography AS g
)
SELECT
    s.name,
    s.operator,
    s.power_kw,
    round(ST_Distance(s.location, o.g)::numeric, 1) AS meters
FROM charging_stations s, origin o
WHERE ST_DWithin(s.location, o.g, 5000)
  AND s.power_kw >= 50
ORDER BY s.location <-> o.g
LIMIT 10;
     name      |   operator    | power_kw | meters
---------------+---------------+----------+--------
 Gare Cornavin | ExampleCharge |   150.00 |  672.8
 Plainpalais   | ExampleCharge |    50.00 |  884.6
 Aéroport      | OtherOperator |   300.00 | 4032.3
  • ST_DWithin(s.location, o.g, 5000) filters with the index; on geography the radius is in meters.
  • ORDER BY s.location <-> o.g orders by distance using the index.
  • ST_Distance() computes the exact distance for the remaining rows.

Check the plan:

EXPLAIN
SELECT name FROM charging_stations
WHERE ST_DWithin(location,
                 ST_SetSRID(ST_MakePoint(6.14320, 46.20440), 4326)::geography,
                 5000);

On a table of realistic size, the plan shows Index Scan using charging_stations_location_idx. On a few rows, the planner prefers a sequential scan, which is cheaper there.

Load Spatial Data

ogr2ogr (GDAL) and shp2pgsql run on your machine and connect to the service like any client. Get the connection URI as described in Connect with psql.

ogr2ogr -f PostgreSQL PG:"CONNECTION_URI" INPUT_FILE -nln TABLE_NAME -lco GEOMETRY_NAME=geom

Parameters:

  • CONNECTION_URI: connection URI of the service, with sslmode=require.
  • INPUT_FILE: source dataset, for example a GeoPackage or a Shapefile.
  • TABLE_NAME: target table.

GeoJSON can be inserted in SQL:

INSERT INTO regions (name, geom)
VALUES ('Canton de Genève', ST_SetSRID(ST_GeomFromGeoJSON($1), 4326));

Server-side COPY ... FROM 'file' fails with permission denied to COPY from a file, because avnadmin does not have pg_read_server_files. Use the psql meta-command \copy, which reads the file on your machine:

\copy regions (name, wkt) FROM 'regions.csv' WITH (FORMAT csv, HEADER true)

Common Pitfalls

  • Mixed SRIDs. Functions refuse geometries with different SRIDs, for example ST_Distance: Operation on mixed SRID geometries (Point, 4326) != (Point, 2056). Transform on load and declare the SRID in the column type.
  • Implicit casts between geometry and geography in one predicate. Cast explicitly.
  • Invalid geometries, such as self-intersecting polygons. Check with ST_IsValid() and ST_IsValidReason(), repair with ST_MakeValid().
  • No ANALYZE after a bulk load.
  • Measuring in Web Mercator (3857). Distances are inflated away from the equator.

Keep PostGIS Current

Compare the installed version with the version offered by the service:

SELECT name, default_version, installed_version
FROM pg_available_extensions
WHERE name LIKE 'postgis%';

When installed_version is lower, update all PostGIS extensions of the database:

SELECT postgis_extensions_upgrade();

A database that uses postgis_topology and comes from a PostGIS version older than 3.6 needs extra steps for its topogeometry columns. Follow the upgrade notes of the PostGIS documentation for that version.

Related Pages

Last updated on