How to transform geometries with PostGIS
By Dillon Smart · · · 0 Comments
PostGIS is a power extention for PostgreSQL databases. It provides a suite of tools to handle and manipulate geographic data. At times, you may need to transform geometries with PostGIS for different base maps or to perform more accurate calculations, such as calculating the area of a polygon.
- How to install PostGIS
- Using ST_Transform in PostGIS
- Find a geometries SRID
- Setting a geometries SRID
Transform geometry with PostGIS
PostGIS has a helpful function ST_Transfrom(geometry, SRID) which takes a geometry as its first parameter, and transforms the geometry to a different spatial reference system, which is the second parameter. See the offial documentation.
For example, if your geometry had an SRID of 27700, and you needed to transform it to 3857, you would use the following, where the value of the SRID parameter is the SRID you want the geometry transfromed to.
ST_Transform(geometry_field, 3857)
Geometry has an unknown SRID
ST_Transform not working? Often, when working with geometries which are poorly documented, you can find youself unaware of the SRID for a given geometry. Typically, if the data is sourced online, the creators will give a couple of options for the geometries projection. However, this isn’t always the case.
When executing the ST_Transform function, you may be presented with the “ST_Transform: Input geometry has unknown (0) SRID” error. This error message indicates that the geometries SRID cannot be changed because the geometry is of an unknown SRID.
To overcome this issue, PostGIS has a helpful function to determing the SRID of a given geomtery. You can find the SRID of a geometry using the ST_SRID function.
ST_SRID(geometry) // outputs the SRID of the geometry e.g. 27700
Once you know the SRID of the geometry, you can use the same ST_Transform method. If passing 3 parameters, the second parameter becomes the from_srid and the third parameter becomes the to_srid, like so:
ST_Transform(geometry_field, 27700, 3857)
Using ST_SetSRID to set the SRID of geometry
The same can be achieved by wrpping the geometry in the ST_SetSRID function.
ST_Transform(ST_SetSRID(geometry_fiels, 27700), 3857)
0 Comment