the spatial reference class represents ogr spatial reference objects example from django contrib gis gdal import spatialreference srs spatialreference wgs84 printsrs geogcswgs 84 datumwgs1984 spheroidwgs 84 6378137 298 257223563 ityepsg 7030 towgs840 0 0 0 0 0 0 ityepsg 6326 primemgreenwich 0 ityepsg 8901 unitdegree 0 01745329251994328 ityepsg 9122 ityepsg 4326 printsrs proj projlonglat ellpswgs84 datumwgs84 nodefs printsrs ellipsoid 6378137 0 6356752 3142451793 298 25722356300003 printsrs projected srs geographic false true srs importepsg32140 printsrs name nad83 texas south central a wrapper for the ogrspatialreference object according to the gdal web site the spatialreference object provides services to represent coordinate systems projections and datums and to transform between them create a gdal osr spatial reference object from the given input the input may be string of ogc well known text wkt an integer epsg code a proj string andor a projection well known shorthand string one of wgs84 wgs72 nad27 nad83 if srid is a string e g 4326 then make acceptable as user input epsg integer code was input input is already an srs pointer creating a new srs pointer using the string buffer if the pointer is null throw an exception importing from either the user input string or an integer srid return the value of the given string attribute node none if the node doesn t exist can also take a tuple as a parameter target child where child is the index of the attribute in the wkt for example wkt geogcswgs 84 datumwgs1984 ityepsg 4326 srs spatialreferencewkt could also use wgs84 or 4326 printsrs geogcs wgs 84 printsrs datum wgs1984 printsrs ity epsg printsrs ity 1 the ity value 4326 printsrs towgs84 4 the fourth value in this wkt 0 for the units ity have to use the pipe symbole printsrs unitity epsg printsrs unitity 1 the ity value for the units 9122 spatialreference methods the attribute value for the given target node e g projcs the index keyword specifies an index of the child node to return this method inspects the wkt of this spatialreference and will add epsg ity nodes where an epsg identifier is applicable name srid properties unit properties return a 2tuple of the units value and the units name automatically determine whether to return the linear or angular units spheroidellipsoid properties return a tuple of the ellipsoid parameters semimajor axis semiminor axis and inverse flattening boolean properties return true if this spatialreference is geographic root node is geogcs return true if this spatialreference is a projected coordinate system root node is projcs import routines import the spatial reference from a proj string capi fromprojself ptr proj def importuserinputself userinput import the spatial reference from the given user input string capi fromuserinputself ptr forcebytesuserinput def importwktself wkt import the spatial reference from ogc wkt string capi fromwktself ptr byrefccharpforcebyteswkt def importxmlself xml import the spatial reference from an xml string capi fromxmlself ptr xml export properties property def wktself return the wkt representation of this spatial reference return capi towktself ptr byrefccharp property def prettywktself simplify0 return the pretty representation of the wkt return capi toprettywktself ptr byrefccharp simplify property def projself a wrapper for the ogrspatialreference object according to the gdal web site the spatialreference object provide s services to represent coordinate systems projections and datums and to transform between them create a gdal osr spatial reference object from the given input the input may be string of ogc well known text wkt an integer epsg code a proj string and or a projection well known shorthand string one of wgs84 wgs72 nad27 nad83 if srid is a string e g 4326 then make acceptable as user input epsg integer code was input input is already an srs pointer creating a new srs pointer using the string buffer if the pointer is null throw an exception importing from either the user input string or an integer srid return the value of the given string attribute node none if the node doesn t exist can also take a tuple as a parameter target child where child is the index of the attribute in the wkt for example wkt geogcs wgs 84 datum wgs_1984 ity epsg 4326 srs spatialreference wkt could also use wgs84 or 4326 print srs geogcs wgs 84 print srs datum wgs_1984 print srs ity epsg print srs ity 1 the ity value 4326 print srs towgs84 4 the fourth value in this wkt 0 for the units ity have to use the pipe symbole print srs unit ity epsg print srs unit ity 1 the ity value for the units 9122 spatialreference methods the attribute value for the given target node e g projcs the index keyword specifies an index of the child node to return this method inspects the wkt of this spatialreference and will add epsg ity nodes where an epsg identifier is applicable name srid properties unit properties return a 2 tuple of the units value and the units name automatically determine whether to return the linear or angular units spheroid ellipsoid properties return a tuple of the ellipsoid parameters semimajor axis semiminor axis and inverse flattening boolean properties return true if this spatialreference is geographic root node is geogcs return true if this spatialreference is a projected coordinate system root node is projcs import routines import the spatial reference from a proj string export properties return the proj representation for this spatial reference
from ctypes import byref, c_char_p, c_int
from enum import IntEnum
from types import NoneType

from django.contrib.gis.gdal.base import GDALBase
from django.contrib.gis.gdal.error import SRSException
from django.contrib.gis.gdal.libgdal import GDAL_VERSION
from django.contrib.gis.gdal.prototypes import srs as capi
from django.utils.encoding import force_bytes, force_str


class AxisOrder(IntEnum):
    TRADITIONAL = 0
    AUTHORITY = 1


class SpatialReference(GDALBase):
    

    destructor = capi.release_srs

    def __init__(self, srs_input="", srs_type="user", axis_order=None):
        
        if not isinstance(axis_order, (NoneType, AxisOrder)):
            raise ValueError(
                "SpatialReference.axis_order must be an AxisOrder instance."
            )
        self.axis_order = axis_order or AxisOrder.TRADITIONAL
        if srs_type == "wkt":
            self.ptr = capi.new_srs(c_char_p(b""))
            self.import_wkt(srs_input)
            if self.axis_order == AxisOrder.TRADITIONAL and GDAL_VERSION >= (3, 0):
                capi.set_axis_strategy(self.ptr, self.axis_order)
            elif self.axis_order != AxisOrder.TRADITIONAL and GDAL_VERSION < (3, 0):
                raise ValueError("%s is not supported in GDAL < 3.0." % self.axis_order)
            return
        elif isinstance(srs_input, str):
            try:
                
                
                srid = int(srs_input)
                srs_input = "EPSG:%d" % srid
            except ValueError:
                pass
        elif isinstance(srs_input, int):
            
            srs_type = "epsg"
        elif isinstance(srs_input, self.ptr_type):
            srs = srs_input
            srs_type = "ogr"
        else:
            raise TypeError('Invalid SRS type "%s"' % srs_type)

        if srs_type == "ogr":
            
            srs = srs_input
        else:
            
            buf = c_char_p(b"")
            srs = capi.new_srs(buf)

        
        if not srs:
            raise SRSException(
                "Could not create spatial reference from: %s" % srs_input
            )
        else:
            self.ptr = srs

        if self.axis_order == AxisOrder.TRADITIONAL and GDAL_VERSION >= (3, 0):
            capi.set_axis_strategy(self.ptr, self.axis_order)
        elif self.axis_order != AxisOrder.TRADITIONAL and GDAL_VERSION < (3, 0):
            raise ValueError("%s is not supported in GDAL < 3.0." % self.axis_order)
        
        if srs_type == "user":
            self.import_user_input(srs_input)
        elif srs_type == "epsg":
            self.import_epsg(srs_input)

    def __getitem__(self, target):
        
        if isinstance(target, tuple):
            return self.attr_value(*target)
        else:
            return self.attr_value(target)

    def __str__(self):
        "Use 'pretty' WKT."
        return self.pretty_wkt

    
    def attr_value(self, target, index=0):
        
        if not isinstance(target, str) or not isinstance(index, int):
            raise TypeError
        return capi.get_attr_value(self.ptr, force_bytes(target), index)

    def auth_name(self, target):
        "Return the authority name for the given string target node."
        return capi.get_auth_name(
            self.ptr, target if target is None else force_bytes(target)
        )

    def auth_code(self, target):
        "Return the authority code for the given string target node."
        return capi.get_auth_code(
            self.ptr, target if target is None else force_bytes(target)
        )

    def clone(self):
        "Return a clone of this SpatialReference object."
        return SpatialReference(capi.clone_srs(self.ptr), axis_order=self.axis_order)

    def from_esri(self):
        "Morph this SpatialReference from ESRI's format to EPSG."
        capi.morph_from_esri(self.ptr)

    def identify_epsg(self):
        
        capi.identify_epsg(self.ptr)

    def to_esri(self):
        "Morph this SpatialReference to ESRI's format."
        capi.morph_to_esri(self.ptr)

    def validate(self):
        "Check to see if the given spatial reference is valid."
        capi.srs_validate(self.ptr)

    
    @property
    def name(self):
        "Return the name of this Spatial Reference."
        if self.projected:
            return self.attr_value("PROJCS")
        elif self.geographic:
            return self.attr_value("GEOGCS")
        elif self.local:
            return self.attr_value("LOCAL_CS")
        else:
            return None

    @property
    def srid(self):
        "Return the SRID of top-level authority, or None if undefined."
        try:
            return int(self.auth_code(target=None))
        except (TypeError, ValueError):
            return None

    
    @property
    def linear_name(self):
        "Return the name of the linear units."
        units, name = capi.linear_units(self.ptr, byref(c_char_p()))
        return name

    @property
    def linear_units(self):
        "Return the value of the linear units."
        units, name = capi.linear_units(self.ptr, byref(c_char_p()))
        return units

    @property
    def angular_name(self):
        "Return the name of the angular units."
        units, name = capi.angular_units(self.ptr, byref(c_char_p()))
        return name

    @property
    def angular_units(self):
        "Return the value of the angular units."
        units, name = capi.angular_units(self.ptr, byref(c_char_p()))
        return units

    @property
    def units(self):
        
        units, name = None, None
        if self.projected or self.local:
            units, name = capi.linear_units(self.ptr, byref(c_char_p()))
        elif self.geographic:
            units, name = capi.angular_units(self.ptr, byref(c_char_p()))
        if name is not None:
            name = force_str(name)
        return (units, name)

    
    @property
    def ellipsoid(self):
        
        return (self.semi_major, self.semi_minor, self.inverse_flattening)

    @property
    def semi_major(self):
        "Return the Semi Major Axis for this Spatial Reference."
        return capi.semi_major(self.ptr, byref(c_int()))

    @property
    def semi_minor(self):
        "Return the Semi Minor Axis for this Spatial Reference."
        return capi.semi_minor(self.ptr, byref(c_int()))

    @property
    def inverse_flattening(self):
        "Return the Inverse Flattening for this Spatial Reference."
        return capi.invflattening(self.ptr, byref(c_int()))

    
    @property
    def geographic(self):
        
        return bool(capi.isgeographic(self.ptr))

    @property
    def local(self):
        "Return True if this SpatialReference is local (root node is LOCAL_CS)."
        return bool(capi.islocal(self.ptr))

    @property
    def projected(self):
        
        return bool(capi.isprojected(self.ptr))

    
    def import_epsg(self, epsg):
        "Import the Spatial Reference from the EPSG code (an integer)."
        capi.from_epsg(self.ptr, epsg)

    def import_proj(self, proj):
        
        capi.from_proj(self.ptr, proj)

    def import_user_input(self, user_input):
        "Import the Spatial Reference from the given user input string."
        capi.from_user_input(self.ptr, force_bytes(user_input))

    def import_wkt(self, wkt):
        "Import the Spatial Reference from OGC WKT (string)"
        capi.from_wkt(self.ptr, byref(c_char_p(force_bytes(wkt))))

    def import_xml(self, xml):
        "Import the Spatial Reference from an XML string."
        capi.from_xml(self.ptr, xml)

    
    @property
    def wkt(self):
        "Return the WKT representation of this Spatial Reference."
        return capi.to_wkt(self.ptr, byref(c_char_p()))

    @property
    def pretty_wkt(self, simplify=0):
        "Return the 'pretty' representation of the WKT."
        return capi.to_pretty_wkt(self.ptr, byref(c_char_p()), simplify)

    @property
    def proj(self):
        
        return capi.to_proj(self.ptr, byref(c_char_p()))

    @property
    def proj4(self):
        "Alias for proj()."
        return self.proj

    @property
    def xml(self, dialect=""):
        "Return the XML representation of this Spatial Reference."
        return capi.to_xml(self.ptr, byref(c_char_p()), force_bytes(dialect))


class CoordTransform(GDALBase):
    "The coordinate system transformation object."
    destructor = capi.destroy_ct

    def __init__(self, source, target):
        "Initialize on a source and target SpatialReference objects."
        if not isinstance(source, SpatialReference) or not isinstance(
            target, SpatialReference
        ):
            raise TypeError("source and target must be of type SpatialReference")
        self.ptr = capi.new_ct(source._ptr, target._ptr)
        self._srs1_name = source.name
        self._srs2_name = target.name

    def __str__(self):
        return 'Transform from "%s" to "%s"' % (self._srs1_name, self._srs2_name)