[GIS] OSR Python testSR.ImportFromEPSG(4326) returns empty spatial reference

ogrpython

This is empty using Python .ImportFromEPSG(4326):

import osr
#this fails:
testSR = osr.SpatialReference()
testSR.ImportFromEPSG(4326)
print testSR.ExportToPrettyWkt()

#why did the import from EPSG fail above?
testSR.SetWellKnownGeogCS("WGS84")
print testSR.ExportToPrettyWkt()
GEOGCS["WGS 84",
DATUM["WGS_1984", and so on...

Best Answer

First, the real error was skipped, since ImportFromEPSG returned a non-zero error code:

from osgeo import osr
testSR = osr.SpatialReference()
res = testSR.ImportFromEPSG(4326)
if res != 0:
    raise RuntimeError(repr(res) + ': could not import from EPSG')
print testSR.ExportToPrettyWkt()

Now the cause. GDAL needs an environment variable GDAL_DATA to find and use projection info. If it is not available, then some things stop working. The SRID look-up codes are in GDAL_DATA, for instance. Check if you have it:

import os
'GDAL_DATA' in os.environ

if False, it should be added to either your system's environment variables, or you can add it in run-time:

if 'GDAL_DATA' not in os.environ:
    os.environ['GDAL_DATA'] = r'/path/to/gdal_data'
Related Question