Sunday, December 6, 2009

PostGIS - Error about using two geometries with different SRIDs

Hi:

This term for my master's degree I took a class on GIS. It disappointed given the lack of theoretical background taught by the professor, but I liked the applications very much. Roughly, these were the main interesting topics (for me, anyway):

1. Using GvSIG with layers from SHP files.
2. Using QGis with layers from SHP files.
3. Using GvSIG with layers from Web Map Services (WMS).
4. Using PostGIS (install, basic querying, importing layers form SHP, etc.).
5. Using QGis with layers from PostGIS database.

While working on the final project, I was trying to write a query to create a new layer from the intersection of two preexisting layers (tables in the DB). So I was using calls like ST_intersection(table_a.the_geom, table_b.the_geom) on the query, but Postgres refused to work telling me I was doing operations on geometries with different SRIDs. I went to the the geometry_columns table (where postgis stores the references to all geometry columns on the database, along with their SRID, column name, table name, etc.), and found that one of the tables had the wrong SRID associated. I thought it would be enough to just update it to the right value. WRONG. It did not work, postgis still complained about the different SRIDs. SO I googled around a little and found a fix for this.

First, you need to update the SRID of the geometry you want to fix to the correct value. This is basically what I tried to do, but the correct way to do it is not by updating values on the table. PostGIS provides a nice function for this:

select updategeometrysrid('cultivos_ilicitos', 'the_geom', 21897);

Here, cultivos_ilicitos is the table I want to fix, the_geom is the name of the column that has the geometries, and 21897 is the EPSG code of the SRID. This is the first part of the fix. Now, you have to tell postgis to modify any geometries that are stored on the_geom column of the cultivos_ilicitos table, so that they are referenced to the correct SRID. You can do this by running the following:

select setsrid(the_geom, 21897) from cultivos_ilicitos;

So basically, the first instruction fixed the geometry_columns table, while the second one fixes the actual geometries stored on the table with the layer of interest.

I hope this is useful for someone out there.



No comments: