Tuesday 9 August 2016

coordinate system - Shapefile PRJ to PostGIS SRID lookup table?


I was wondering if there is such a thing as an shapefile PRJ to PostGIS SRID lookup table? Something that can translate the most standard shapefile PRJ definitions into the likely SRID.


When using PostGIS and pgAdminIII, if you use the postgisgui to import your shapefiles, the SRID is left as "-1". It seems like the tool should be able to parse the Esri PRJ and determine the correct (or at least a couple of options) that are the likely SRID, rather than just leave the default.


Or does the importer have the capability to reproject on the fly if you choose another SRID?


It may seem lazy on my part, but to me it seems curious that this function hasn't already been put in place. Does anyone know if this concept is in the works, or good reason's why it has been left out?




Answer



Borrowing the idea from @iant, here is a PL/Python3 module that will look up the EPSG SRID integer codes from a PRJ file using the http://prj2epsg.org web service.


First, install PL/Python3:


CREATE LANGUAGE plpython3u;

an now add the SQL function, which has code written for Python 3:


CREATE OR REPLACE FUNCTION prj2epsg(prj_file text) RETURNS integer AS
$BODY$

import json

from urllib.parse import urlencode
from urllib.request import urlopen

with open(prj_file, 'r') as fp:
prj_txt = fp.read()

query = urlencode({
'exact': True,
'error': True,
'mode': 'wkt',

'terms': prj_txt})

webres = urlopen('http://prj2epsg.org/search.json', query.encode())
jres = json.loads(webres.read().decode())

return int(jres['codes'][0]['code'])

$BODY$ LANGUAGE plpython3u VOLATILE COST 100;

To use it from PostgreSQL:



SELECT prj2epsg(E'C:\\Temp\\countries.prj');

returns 4326 for my test Shapefile.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...