Pages

Wednesday, December 3, 2014

WKT EPSG Strings Made Easy

This quick post is a follow on to my posts on map projections and creating .prj files for shapefiles.
 The .prj file format, created by Esri originally but now recognized by most geospatial software, is just a text file with a WKT string for the projection information.  Most of projections can be referenced by a simple EPSG code which is just a number.  Usually you'll have this number handy and need to look up the full WKT string on SpatialReference.org.

Dr. David Forrest, a research scientist at the Virginia Institute of Marine Sciences, sent me a simple function to make fetching WKT projection strings easy:

def getPRJwkt(epsg):
   """
   Grab an WKT version of an EPSG code
   usage getPRJwkt(4326)

   This makes use of links like 
   http://spatialreference.org/ref/epsg/4326/prettywkt/
   """
   
   import urllib
   sr = "http://spatialreference.org"
   f=urllib.urlopen(sr + "/ref/epsg/{0}/prettywkt/".format(epsg))
   return (f.read())

So then getting a WKT projection string is as easy as:

>>> wkt = getPRJwkt(4326)
>>> print wkt
GEOGCS["WGS 84",
    DATUM["WGS_1984",
        SPHEROID["WGS 84",6378137,298.257223563,
            AUTHORITY["EPSG","7030"]],
        AUTHORITY["EPSG","6326"]],
    PRIMEM["Greenwich",0,
        AUTHORITY["EPSG","8901"]],
    UNIT["degree",0.01745329251994328,
        AUTHORITY["EPSG","9122"]],
    AUTHORITY["EPSG","4326"]]

There's another, newer website called epsg.io that has some additional features beyond spatialreference.org.  The differences are in the FAQ on this page.

1 comment:

  1. here's a way for epsg.io:

    def getWKTio(epsg) :
    import urllib
    from bs4 import BeautifulSoup
    html = 'http://epsg.io/{}'.format(epsg)
    r = urllib.urlopen(html)
    data = r.read()
    soup = BeautifulSoup(data, "html")
    for tag in soup.find_all('pre'):
    if tag.get('id') == 's_esriwkt_text':
    return tag.contents

    getWKTio(4326)

    ReplyDelete