Changing the CRS

The data in the database is using World Geodetic System 84 (WGS 84), latitude and longitude. What if you need the data out in European Petroleum Survey Group (EPSG) 3857? You can change the spatial reference in your query using ST_Transform(). The following code shows you how by using PostGIS functions:

cursor.execute("SELECT UpdateGeometrySRID('art_pieces','location',4326)")
cursor.execute("SELECT Find_SRID('public','art_pieces','location')")
cursor.fetchall()

The previous code makes two queries to the database:

  • Firstly, it assigns a spatial reference system identifier to the geometry column in the table using UpdateGeomtrySRID(). This needs to be done because the points were put in the table without any reference to an SRID. So when we try to get the results back using a different coordinate reference system, the database will not know how to transform our coordinates.
  • Secondly, the code queries the database to tell us what the SRID is on the geometry column in the table using Find_SRID(). If you do not have a properly added geometry column, the function will fail.

Now that you have an SRID set on the column in the table, you can query the data and transform it:

cursor.execute("SELECT code, ST_AsTexT(ST_Transform(location,3857)) from art_pieces")
cursor.fetchone()

The previous code is a basic select code and location, as text, from art_pieces, but now there is an ST_Transform method. This method takes the column with geometry and the SRID you want the data sent back in. Now, the piece of art at (-106.59, 35.155) is returned using 3857, and shown as follows with the transformed coordinates:

('101', 'POINT(-11865749.1623 4185033.1034)')
..................Content has been hidden....................

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