srs.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. """
  2. The Spatial Reference class, represents OGR Spatial Reference objects.
  3. Example:
  4. >>> from django.contrib.gis.gdal import SpatialReference
  5. >>> srs = SpatialReference('WGS84')
  6. >>> print(srs)
  7. GEOGCS["WGS 84",
  8. DATUM["WGS_1984",
  9. SPHEROID["WGS 84",6378137,298.257223563,
  10. AUTHORITY["EPSG","7030"]],
  11. TOWGS84[0,0,0,0,0,0,0],
  12. AUTHORITY["EPSG","6326"]],
  13. PRIMEM["Greenwich",0,
  14. AUTHORITY["EPSG","8901"]],
  15. UNIT["degree",0.01745329251994328,
  16. AUTHORITY["EPSG","9122"]],
  17. AUTHORITY["EPSG","4326"]]
  18. >>> print(srs.proj)
  19. +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs
  20. >>> print(srs.ellipsoid)
  21. (6378137.0, 6356752.3142451793, 298.25722356300003)
  22. >>> print(srs.projected, srs.geographic)
  23. False True
  24. >>> srs.import_epsg(32140)
  25. >>> print(srs.name)
  26. NAD83 / Texas South Central
  27. """
  28. from ctypes import byref, c_char_p, c_int
  29. from enum import IntEnum
  30. from types import NoneType
  31. from django.contrib.gis.gdal.base import GDALBase
  32. from django.contrib.gis.gdal.error import SRSException
  33. from django.contrib.gis.gdal.prototypes import srs as capi
  34. from django.utils.encoding import force_bytes, force_str
  35. class AxisOrder(IntEnum):
  36. TRADITIONAL = 0
  37. AUTHORITY = 1
  38. class SpatialReference(GDALBase):
  39. """
  40. A wrapper for the OGRSpatialReference object. According to the GDAL web site,
  41. the SpatialReference object "provide[s] services to represent coordinate
  42. systems (projections and datums) and to transform between them."
  43. """
  44. destructor = capi.release_srs
  45. def __init__(self, srs_input="", srs_type="user", axis_order=None):
  46. """
  47. Create a GDAL OSR Spatial Reference object from the given input.
  48. The input may be string of OGC Well Known Text (WKT), an integer
  49. EPSG code, a PROJ string, and/or a projection "well known" shorthand
  50. string (one of 'WGS84', 'WGS72', 'NAD27', 'NAD83').
  51. """
  52. if not isinstance(axis_order, (NoneType, AxisOrder)):
  53. raise ValueError(
  54. "SpatialReference.axis_order must be an AxisOrder instance."
  55. )
  56. self.axis_order = axis_order or AxisOrder.TRADITIONAL
  57. if srs_type == "wkt":
  58. self.ptr = capi.new_srs(c_char_p(b""))
  59. self.import_wkt(srs_input)
  60. if self.axis_order == AxisOrder.TRADITIONAL:
  61. capi.set_axis_strategy(self.ptr, self.axis_order)
  62. return
  63. elif isinstance(srs_input, str):
  64. try:
  65. # If SRID is a string, e.g., '4326', then make acceptable
  66. # as user input.
  67. srid = int(srs_input)
  68. srs_input = "EPSG:%d" % srid
  69. except ValueError:
  70. pass
  71. elif isinstance(srs_input, int):
  72. # EPSG integer code was input.
  73. srs_type = "epsg"
  74. elif isinstance(srs_input, self.ptr_type):
  75. srs = srs_input
  76. srs_type = "ogr"
  77. else:
  78. raise TypeError('Invalid SRS type "%s"' % srs_type)
  79. if srs_type == "ogr":
  80. # Input is already an SRS pointer.
  81. srs = srs_input
  82. else:
  83. # Creating a new SRS pointer, using the string buffer.
  84. buf = c_char_p(b"")
  85. srs = capi.new_srs(buf)
  86. # If the pointer is NULL, throw an exception.
  87. if not srs:
  88. raise SRSException(
  89. "Could not create spatial reference from: %s" % srs_input
  90. )
  91. else:
  92. self.ptr = srs
  93. if self.axis_order == AxisOrder.TRADITIONAL:
  94. capi.set_axis_strategy(self.ptr, self.axis_order)
  95. # Importing from either the user input string or an integer SRID.
  96. if srs_type == "user":
  97. self.import_user_input(srs_input)
  98. elif srs_type == "epsg":
  99. self.import_epsg(srs_input)
  100. def __getitem__(self, target):
  101. """
  102. Return the value of the given string attribute node, None if the node
  103. doesn't exist. Can also take a tuple as a parameter, (target, child),
  104. where child is the index of the attribute in the WKT. For example:
  105. >>> wkt = 'GEOGCS["WGS 84", DATUM["WGS_1984, ... AUTHORITY["EPSG","4326"]]'
  106. >>> srs = SpatialReference(wkt) # could also use 'WGS84', or 4326
  107. >>> print(srs['GEOGCS'])
  108. WGS 84
  109. >>> print(srs['DATUM'])
  110. WGS_1984
  111. >>> print(srs['AUTHORITY'])
  112. EPSG
  113. >>> print(srs['AUTHORITY', 1]) # The authority value
  114. 4326
  115. >>> print(srs['TOWGS84', 4]) # the fourth value in this wkt
  116. 0
  117. >>> # For the units authority, have to use the pipe symbole.
  118. >>> print(srs['UNIT|AUTHORITY'])
  119. EPSG
  120. >>> print(srs['UNIT|AUTHORITY', 1]) # The authority value for the units
  121. 9122
  122. """
  123. if isinstance(target, tuple):
  124. return self.attr_value(*target)
  125. else:
  126. return self.attr_value(target)
  127. def __str__(self):
  128. "Use 'pretty' WKT."
  129. return self.pretty_wkt
  130. # #### SpatialReference Methods ####
  131. def attr_value(self, target, index=0):
  132. """
  133. The attribute value for the given target node (e.g. 'PROJCS'). The index
  134. keyword specifies an index of the child node to return.
  135. """
  136. if not isinstance(target, str) or not isinstance(index, int):
  137. raise TypeError
  138. return capi.get_attr_value(self.ptr, force_bytes(target), index)
  139. def auth_name(self, target):
  140. "Return the authority name for the given string target node."
  141. return capi.get_auth_name(
  142. self.ptr, target if target is None else force_bytes(target)
  143. )
  144. def auth_code(self, target):
  145. "Return the authority code for the given string target node."
  146. return capi.get_auth_code(
  147. self.ptr, target if target is None else force_bytes(target)
  148. )
  149. def clone(self):
  150. "Return a clone of this SpatialReference object."
  151. return SpatialReference(capi.clone_srs(self.ptr), axis_order=self.axis_order)
  152. def from_esri(self):
  153. "Morph this SpatialReference from ESRI's format to EPSG."
  154. capi.morph_from_esri(self.ptr)
  155. def identify_epsg(self):
  156. """
  157. This method inspects the WKT of this SpatialReference, and will
  158. add EPSG authority nodes where an EPSG identifier is applicable.
  159. """
  160. capi.identify_epsg(self.ptr)
  161. def to_esri(self):
  162. "Morph this SpatialReference to ESRI's format."
  163. capi.morph_to_esri(self.ptr)
  164. def validate(self):
  165. "Check to see if the given spatial reference is valid."
  166. capi.srs_validate(self.ptr)
  167. # #### Name & SRID properties ####
  168. @property
  169. def name(self):
  170. "Return the name of this Spatial Reference."
  171. if self.projected:
  172. return self.attr_value("PROJCS")
  173. elif self.geographic:
  174. return self.attr_value("GEOGCS")
  175. elif self.local:
  176. return self.attr_value("LOCAL_CS")
  177. else:
  178. return None
  179. @property
  180. def srid(self):
  181. "Return the SRID of top-level authority, or None if undefined."
  182. try:
  183. return int(self.auth_code(target=None))
  184. except (TypeError, ValueError):
  185. return None
  186. # #### Unit Properties ####
  187. @property
  188. def linear_name(self):
  189. "Return the name of the linear units."
  190. units, name = capi.linear_units(self.ptr, byref(c_char_p()))
  191. return name
  192. @property
  193. def linear_units(self):
  194. "Return the value of the linear units."
  195. units, name = capi.linear_units(self.ptr, byref(c_char_p()))
  196. return units
  197. @property
  198. def angular_name(self):
  199. "Return the name of the angular units."
  200. units, name = capi.angular_units(self.ptr, byref(c_char_p()))
  201. return name
  202. @property
  203. def angular_units(self):
  204. "Return the value of the angular units."
  205. units, name = capi.angular_units(self.ptr, byref(c_char_p()))
  206. return units
  207. @property
  208. def units(self):
  209. """
  210. Return a 2-tuple of the units value and the units name. Automatically
  211. determine whether to return the linear or angular units.
  212. """
  213. units, name = None, None
  214. if self.projected or self.local:
  215. units, name = capi.linear_units(self.ptr, byref(c_char_p()))
  216. elif self.geographic:
  217. units, name = capi.angular_units(self.ptr, byref(c_char_p()))
  218. if name is not None:
  219. name = force_str(name)
  220. return (units, name)
  221. # #### Spheroid/Ellipsoid Properties ####
  222. @property
  223. def ellipsoid(self):
  224. """
  225. Return a tuple of the ellipsoid parameters:
  226. (semimajor axis, semiminor axis, and inverse flattening)
  227. """
  228. return (self.semi_major, self.semi_minor, self.inverse_flattening)
  229. @property
  230. def semi_major(self):
  231. "Return the Semi Major Axis for this Spatial Reference."
  232. return capi.semi_major(self.ptr, byref(c_int()))
  233. @property
  234. def semi_minor(self):
  235. "Return the Semi Minor Axis for this Spatial Reference."
  236. return capi.semi_minor(self.ptr, byref(c_int()))
  237. @property
  238. def inverse_flattening(self):
  239. "Return the Inverse Flattening for this Spatial Reference."
  240. return capi.invflattening(self.ptr, byref(c_int()))
  241. # #### Boolean Properties ####
  242. @property
  243. def geographic(self):
  244. """
  245. Return True if this SpatialReference is geographic
  246. (root node is GEOGCS).
  247. """
  248. return bool(capi.isgeographic(self.ptr))
  249. @property
  250. def local(self):
  251. "Return True if this SpatialReference is local (root node is LOCAL_CS)."
  252. return bool(capi.islocal(self.ptr))
  253. @property
  254. def projected(self):
  255. """
  256. Return True if this SpatialReference is a projected coordinate system
  257. (root node is PROJCS).
  258. """
  259. return bool(capi.isprojected(self.ptr))
  260. # #### Import Routines #####
  261. def import_epsg(self, epsg):
  262. "Import the Spatial Reference from the EPSG code (an integer)."
  263. capi.from_epsg(self.ptr, epsg)
  264. def import_proj(self, proj):
  265. """Import the Spatial Reference from a PROJ string."""
  266. capi.from_proj(self.ptr, proj)
  267. def import_user_input(self, user_input):
  268. "Import the Spatial Reference from the given user input string."
  269. capi.from_user_input(self.ptr, force_bytes(user_input))
  270. def import_wkt(self, wkt):
  271. "Import the Spatial Reference from OGC WKT (string)"
  272. capi.from_wkt(self.ptr, byref(c_char_p(force_bytes(wkt))))
  273. def import_xml(self, xml):
  274. "Import the Spatial Reference from an XML string."
  275. capi.from_xml(self.ptr, xml)
  276. # #### Export Properties ####
  277. @property
  278. def wkt(self):
  279. "Return the WKT representation of this Spatial Reference."
  280. return capi.to_wkt(self.ptr, byref(c_char_p()))
  281. @property
  282. def pretty_wkt(self, simplify=0):
  283. "Return the 'pretty' representation of the WKT."
  284. return capi.to_pretty_wkt(self.ptr, byref(c_char_p()), simplify)
  285. @property
  286. def proj(self):
  287. """Return the PROJ representation for this Spatial Reference."""
  288. return capi.to_proj(self.ptr, byref(c_char_p()))
  289. @property
  290. def proj4(self):
  291. "Alias for proj()."
  292. return self.proj
  293. @property
  294. def xml(self, dialect=""):
  295. "Return the XML representation of this Spatial Reference."
  296. return capi.to_xml(self.ptr, byref(c_char_p()), force_bytes(dialect))
  297. class CoordTransform(GDALBase):
  298. "The coordinate system transformation object."
  299. destructor = capi.destroy_ct
  300. def __init__(self, source, target):
  301. "Initialize on a source and target SpatialReference objects."
  302. if not isinstance(source, SpatialReference) or not isinstance(
  303. target, SpatialReference
  304. ):
  305. raise TypeError("source and target must be of type SpatialReference")
  306. self.ptr = capi.new_ct(source._ptr, target._ptr)
  307. self._srs1_name = source.name
  308. self._srs2_name = target.name
  309. def __str__(self):
  310. return 'Transform from "%s" to "%s"' % (self._srs1_name, self._srs2_name)