You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

srs.py 11KB

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