Reprojecting geometries

Reprojecting, also called transformation, is a process of converting a geometry's coordinates from one coordinate system to another. Since PostGIS spatial analysis functions can't operate on geometries with different coordinate systems, it's a very important functionality. It's provided by the ST_Transform function.

ST_Transform accepts two arguments: the input geometry and the target SRID. For example, to transform the coordinates of a point feature (city center) to latitude-longitude, we write the following:

SELECT ST_AsText(ST_Transform(wkb_geometry,4326)) FROM points WHERE osm_id = '253525668'; 

st_astext
POINT(18.5419933 50.0955793)

While ST_Transform can be used on the fly, it's computationally expensive and can cause a complex query to run very slowly. If it's necessary to run a spatial analysis using tables with different SRIDs, it's will be wise to create a materialized view with geometries reprojected beforehand:

CREATE MATERIALIZED VIEW boundaries_3857 AS SELECT ogc_fid, name, boundary, admin_level, ST_Transform(wkb_geometry,3857) AS wkb_geometry FROM multipolygons WHERE boundary='administrative'; 

This will create a materialized view containing a subset of the multipolygons table (administrative boundaries) with their geometries reprojected into the web mercator coordinate system, which has an SRID of 3857.

For efficient querying, this materialized view should also have a spatial index:

CREATE INDEX boundaries_3857_sidx ON boundaries_3857 USING GIST(wkb_geometry); 

Now, any spatial queries with features in the EPSG:3857 coordinate system will run as smoothly as possible.

Geometries can also be reprojected in place, for example:

UPDATE multilinestrings SET wkb_geometry = ST_Transform(wkb_geometry,3857); 

But this will fail if a geometry column has a typmod indicating the only possible SRID, which is true in our case, and the query will result in an error:

Geometry SRID (3857) does not match column SRID (32633) 

To work around this, a typmod can be removed with an ALTER COLUMN statement:

ALTER TABLE multilinestrings ALTER COLUMN wkb_geometry SET DATA TYPE geometry; 

Beware, though - this will remove the protection from accidentally inserting a geometry in another SRID into the table.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset