gdal.txt 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399
  1. ========
  2. GDAL API
  3. ========
  4. .. module:: django.contrib.gis.gdal
  5. :synopsis: GeoDjango's high-level interface to the GDAL library.
  6. `GDAL`__ stands for **Geospatial Data Abstraction Library**,
  7. and is a veritable "Swiss army knife" of GIS data functionality. A subset
  8. of GDAL is the `OGR`__ Simple Features Library, which specializes
  9. in reading and writing vector geographic data in a variety of standard
  10. formats.
  11. GeoDjango provides a high-level Python interface for some of the
  12. capabilities of OGR, including the reading and coordinate transformation
  13. of vector spatial data and minimal support for GDAL's features with respect
  14. to raster (image) data.
  15. .. note::
  16. Although the module is named ``gdal``, GeoDjango only supports
  17. some of the capabilities of OGR and GDAL's raster features at this time.
  18. __ http://www.gdal.org/
  19. __ http://www.gdal.org/ogr/
  20. Overview
  21. ========
  22. .. _gdal_sample_data:
  23. Sample Data
  24. -----------
  25. The GDAL/OGR tools described here are designed to help you read in
  26. your geospatial data, in order for most of them to be useful you have
  27. to have some data to work with. If you're starting out and don't yet
  28. have any data of your own to use, GeoDjango tests contain a number of
  29. simple data sets that you can use for testing. You can download them here::
  30. $ wget https://raw.githubusercontent.com/django/django/master/tests/gis_tests/data/cities/cities.{shp,prj,shx,dbf}
  31. $ wget https://raw.githubusercontent.com/django/django/master/tests/gis_tests/data/rasters/raster.tif
  32. Vector Data Source Objects
  33. ==========================
  34. ``DataSource``
  35. --------------
  36. :class:`DataSource` is a wrapper for the OGR data source object that
  37. supports reading data from a variety of OGR-supported geospatial file
  38. formats and data sources using a simple, consistent interface. Each
  39. data source is represented by a :class:`DataSource` object which contains
  40. one or more layers of data. Each layer, represented by a :class:`Layer`
  41. object, contains some number of geographic features (:class:`Feature`),
  42. information about the type of features contained in that layer (e.g.
  43. points, polygons, etc.), as well as the names and types of any
  44. additional fields (:class:`Field`) of data that may be associated with
  45. each feature in that layer.
  46. .. class:: DataSource(ds_input, [encoding='utf-8'])
  47. The constructor for ``DataSource`` only requires one parameter: the path of
  48. the file you want to read. However, OGR
  49. also supports a variety of more complex data sources, including
  50. databases, that may be accessed by passing a special name string instead
  51. of a path. For more information, see the `OGR Vector Formats`__
  52. documentation. The :attr:`name` property of a ``DataSource``
  53. instance gives the OGR name of the underlying data source that it is
  54. using.
  55. The optional ``encoding`` parameter allows you to
  56. specify a non-standard encoding of the strings in the source. This is
  57. typically useful when you obtain ``DjangoUnicodeDecodeError`` exceptions
  58. while reading field values.
  59. Once you've created your ``DataSource``, you can find out how many
  60. layers of data it contains by accessing the :attr:`layer_count` property,
  61. or (equivalently) by using the ``len()`` function. For information on
  62. accessing the layers of data themselves, see the next section::
  63. >>> from django.contrib.gis.gdal import DataSource
  64. >>> ds = DataSource('/path/to/your/cities.shp')
  65. >>> ds.name
  66. '/path/to/your/cities.shp'
  67. >>> ds.layer_count # This file only contains one layer
  68. 1
  69. .. attribute:: layer_count
  70. Returns the number of layers in the data source.
  71. .. attribute:: name
  72. Returns the name of the data source.
  73. __ http://www.gdal.org/ogr/ogr_formats.html
  74. ``Layer``
  75. ---------
  76. .. class:: Layer
  77. ``Layer`` is a wrapper for a layer of data in a ``DataSource`` object.
  78. You never create a ``Layer`` object directly. Instead, you retrieve
  79. them from a :class:`DataSource` object, which is essentially a standard
  80. Python container of ``Layer`` objects. For example, you can access a
  81. specific layer by its index (e.g. ``ds[0]`` to access the first
  82. layer), or you can iterate over all the layers in the container in a
  83. ``for`` loop. The ``Layer`` itself acts as a container for geometric
  84. features.
  85. Typically, all the features in a given layer have the same geometry type.
  86. The :attr:`geom_type` property of a layer is an :class:`OGRGeomType`
  87. that identifies the feature type. We can use it to print out some basic
  88. information about each layer in a :class:`DataSource`::
  89. >>> for layer in ds:
  90. ... print('Layer "%s": %i %ss' % (layer.name, len(layer), layer.geom_type.name))
  91. ...
  92. Layer "cities": 3 Points
  93. The example output is from the cities data source, loaded above, which
  94. evidently contains one layer, called ``"cities"``, which contains three
  95. point features. For simplicity, the examples below assume that you've
  96. stored that layer in the variable ``layer``::
  97. >>> layer = ds[0]
  98. .. attribute:: name
  99. Returns the name of this layer in the data source.
  100. >>> layer.name
  101. 'cities'
  102. .. attribute:: num_feat
  103. Returns the number of features in the layer. Same as ``len(layer)``::
  104. >>> layer.num_feat
  105. 3
  106. .. attribute:: geom_type
  107. Returns the geometry type of the layer, as an :class:`OGRGeomType`
  108. object::
  109. >>> layer.geom_type.name
  110. 'Point'
  111. .. attribute:: num_fields
  112. Returns the number of fields in the layer, i.e the number of fields of
  113. data associated with each feature in the layer::
  114. >>> layer.num_fields
  115. 4
  116. .. attribute:: fields
  117. Returns a list of the names of each of the fields in this layer::
  118. >>> layer.fields
  119. ['Name', 'Population', 'Density', 'Created']
  120. .. attribute field_types
  121. Returns a list of the data types of each of the fields in this layer.
  122. These are subclasses of ``Field``, discussed below::
  123. >>> [ft.__name__ for ft in layer.field_types]
  124. ['OFTString', 'OFTReal', 'OFTReal', 'OFTDate']
  125. .. attribute:: field_widths
  126. Returns a list of the maximum field widths for each of the fields in
  127. this layer::
  128. >>> layer.field_widths
  129. [80, 11, 24, 10]
  130. .. attribute:: field_precisions
  131. Returns a list of the numeric precisions for each of the fields in
  132. this layer. This is meaningless (and set to zero) for non-numeric
  133. fields::
  134. >>> layer.field_precisions
  135. [0, 0, 15, 0]
  136. .. attribute:: extent
  137. Returns the spatial extent of this layer, as an :class:`Envelope`
  138. object::
  139. >>> layer.extent.tuple
  140. (-104.609252, 29.763374, -95.23506, 38.971823)
  141. .. attribute:: srs
  142. Property that returns the :class:`SpatialReference` associated
  143. with this layer::
  144. >>> print(layer.srs)
  145. GEOGCS["GCS_WGS_1984",
  146. DATUM["WGS_1984",
  147. SPHEROID["WGS_1984",6378137,298.257223563]],
  148. PRIMEM["Greenwich",0],
  149. UNIT["Degree",0.017453292519943295]]
  150. If the :class:`Layer` has no spatial reference information associated
  151. with it, ``None`` is returned.
  152. .. attribute:: spatial_filter
  153. Property that may be used to retrieve or set a spatial filter for this
  154. layer. A spatial filter can only be set with an :class:`OGRGeometry`
  155. instance, a 4-tuple extent, or ``None``. When set with something
  156. other than ``None``, only features that intersect the filter will be
  157. returned when iterating over the layer::
  158. >>> print(layer.spatial_filter)
  159. None
  160. >>> print(len(layer))
  161. 3
  162. >>> [feat.get('Name') for feat in layer]
  163. ['Pueblo', 'Lawrence', 'Houston']
  164. >>> ks_extent = (-102.051, 36.99, -94.59, 40.00) # Extent for state of Kansas
  165. >>> layer.spatial_filter = ks_extent
  166. >>> len(layer)
  167. 1
  168. >>> [feat.get('Name') for feat in layer]
  169. ['Lawrence']
  170. >>> layer.spatial_filter = None
  171. >>> len(layer)
  172. 3
  173. .. method:: get_fields()
  174. A method that returns a list of the values of a given field for each
  175. feature in the layer::
  176. >>> layer.get_fields('Name')
  177. ['Pueblo', 'Lawrence', 'Houston']
  178. .. method:: get_geoms([geos=False])
  179. A method that returns a list containing the geometry of each feature
  180. in the layer. If the optional argument ``geos`` is set to ``True``
  181. then the geometries are converted to :class:`~django.contrib.gis.geos.GEOSGeometry`
  182. objects. Otherwise, they are returned as :class:`OGRGeometry` objects::
  183. >>> [pt.tuple for pt in layer.get_geoms()]
  184. [(-104.609252, 38.255001), (-95.23506, 38.971823), (-95.363151, 29.763374)]
  185. .. method:: test_capability(capability)
  186. Returns a boolean indicating whether this layer supports the
  187. given capability (a string). Examples of valid capability strings
  188. include: ``'RandomRead'``, ``'SequentialWrite'``, ``'RandomWrite'``,
  189. ``'FastSpatialFilter'``, ``'FastFeatureCount'``, ``'FastGetExtent'``,
  190. ``'CreateField'``, ``'Transactions'``, ``'DeleteFeature'``, and
  191. ``'FastSetNextByIndex'``.
  192. ``Feature``
  193. -----------
  194. .. class:: Feature
  195. ``Feature`` wraps an OGR feature. You never create a ``Feature``
  196. object directly. Instead, you retrieve them from a :class:`Layer` object.
  197. Each feature consists of a geometry and a set of fields containing
  198. additional properties. The geometry of a field is accessible via its
  199. ``geom`` property, which returns an :class:`OGRGeometry` object. A ``Feature``
  200. behaves like a standard Python container for its fields, which it returns as
  201. :class:`Field` objects: you can access a field directly by its index or name,
  202. or you can iterate over a feature's fields, e.g. in a ``for`` loop.
  203. .. attribute:: geom
  204. Returns the geometry for this feature, as an ``OGRGeometry`` object::
  205. >>> city.geom.tuple
  206. (-104.609252, 38.255001)
  207. .. attribute:: get
  208. A method that returns the value of the given field (specified by name)
  209. for this feature, **not** a ``Field`` wrapper object::
  210. >>> city.get('Population')
  211. 102121
  212. .. attribute:: geom_type
  213. Returns the type of geometry for this feature, as an :class:`OGRGeomType`
  214. object. This will be the same for all features in a given layer, and
  215. is equivalent to the :attr:`Layer.geom_type` property of the
  216. :class:`Layer` object the feature came from.
  217. .. attribute:: num_fields
  218. Returns the number of fields of data associated with the feature.
  219. This will be the same for all features in a given layer, and is
  220. equivalent to the :attr:`Layer.num_fields` property of the
  221. :class:`Layer` object the feature came from.
  222. .. attribute:: fields
  223. Returns a list of the names of the fields of data associated with the
  224. feature. This will be the same for all features in a given layer, and
  225. is equivalent to the :attr:`Layer.fields` property of the :class:`Layer`
  226. object the feature came from.
  227. .. attribute:: fid
  228. Returns the feature identifier within the layer::
  229. >>> city.fid
  230. 0
  231. .. attribute:: layer_name
  232. Returns the name of the :class:`Layer` that the feature came from.
  233. This will be the same for all features in a given layer::
  234. >>> city.layer_name
  235. 'cities'
  236. .. attribute:: index
  237. A method that returns the index of the given field name. This will be
  238. the same for all features in a given layer::
  239. >>> city.index('Population')
  240. 1
  241. ``Field``
  242. ---------
  243. .. class:: Field
  244. .. attribute:: name
  245. Returns the name of this field::
  246. >>> city['Name'].name
  247. 'Name'
  248. .. attribute:: type
  249. Returns the OGR type of this field, as an integer. The
  250. ``FIELD_CLASSES`` dictionary maps these values onto
  251. subclasses of ``Field``::
  252. >>> city['Density'].type
  253. 2
  254. .. attribute:: type_name
  255. Returns a string with the name of the data type of this field::
  256. >>> city['Name'].type_name
  257. 'String'
  258. .. attribute:: value
  259. Returns the value of this field. The ``Field`` class itself
  260. returns the value as a string, but each subclass returns the
  261. value in the most appropriate form::
  262. >>> city['Population'].value
  263. 102121
  264. .. attribute:: width
  265. Returns the width of this field::
  266. >>> city['Name'].width
  267. 80
  268. .. attribute:: precision
  269. Returns the numeric precision of this field. This is meaningless (and
  270. set to zero) for non-numeric fields::
  271. >>> city['Density'].precision
  272. 15
  273. .. method:: as_double()
  274. Returns the value of the field as a double (float)::
  275. >>> city['Density'].as_double()
  276. 874.7
  277. .. method:: as_int()
  278. Returns the value of the field as an integer::
  279. >>> city['Population'].as_int()
  280. 102121
  281. .. method:: as_string()
  282. Returns the value of the field as a string::
  283. >>> city['Name'].as_string()
  284. 'Pueblo'
  285. .. method:: as_datetime()
  286. Returns the value of the field as a tuple of date and time components::
  287. >>> city['Created'].as_datetime()
  288. (c_long(1999), c_long(5), c_long(23), c_long(0), c_long(0), c_long(0), c_long(0))
  289. ``Driver``
  290. ----------
  291. .. class:: Driver(dr_input)
  292. The ``Driver`` class is used internally to wrap an OGR :class:`DataSource` driver.
  293. .. attribute:: driver_count
  294. Returns the number of OGR vector drivers currently registered.
  295. OGR Geometries
  296. ==============
  297. ``OGRGeometry``
  298. ---------------
  299. :class:`OGRGeometry` objects share similar functionality with
  300. :class:`~django.contrib.gis.geos.GEOSGeometry` objects, and are thin
  301. wrappers around OGR's internal geometry representation. Thus,
  302. they allow for more efficient access to data when using :class:`DataSource`.
  303. Unlike its GEOS counterpart, :class:`OGRGeometry` supports spatial reference
  304. systems and coordinate transformation::
  305. >>> from django.contrib.gis.gdal import OGRGeometry
  306. >>> polygon = OGRGeometry('POLYGON((0 0, 5 0, 5 5, 0 5))')
  307. .. class:: OGRGeometry(geom_input[, srs=None])
  308. This object is a wrapper for the `OGR Geometry`__ class.
  309. These objects are instantiated directly from the given ``geom_input``
  310. parameter, which may be a string containing WKT, HEX, GeoJSON, a ``buffer``
  311. containing WKB data, or an :class:`OGRGeomType` object. These objects
  312. are also returned from the :class:`Feature.geom` attribute, when
  313. reading vector data from :class:`Layer` (which is in turn a part of
  314. a :class:`DataSource`).
  315. __ http://www.gdal.org/ogr/classOGRGeometry.html
  316. .. classmethod:: from_bbox(bbox)
  317. Constructs a :class:`Polygon` from the given bounding-box (a 4-tuple).
  318. .. method:: __len__()
  319. Returns the number of points in a :class:`LineString`, the
  320. number of rings in a :class:`Polygon`, or the number of geometries in a
  321. :class:`GeometryCollection`. Not applicable to other geometry types.
  322. .. method:: __iter__()
  323. Iterates over the points in a :class:`LineString`, the rings in a
  324. :class:`Polygon`, or the geometries in a :class:`GeometryCollection`.
  325. Not applicable to other geometry types.
  326. .. method:: __getitem__()
  327. Returns the point at the specified index for a :class:`LineString`, the
  328. interior ring at the specified index for a :class:`Polygon`, or the geometry
  329. at the specified index in a :class:`GeometryCollection`. Not applicable to
  330. other geometry types.
  331. .. attribute:: dimension
  332. Returns the number of coordinated dimensions of the geometry, i.e. 0
  333. for points, 1 for lines, and so forth::
  334. >> polygon.dimension
  335. 2
  336. .. attribute:: coord_dim
  337. Returns or sets the coordinate dimension of this geometry. For
  338. example, the value would be 2 for two-dimensional geometries.
  339. .. attribute:: geom_count
  340. Returns the number of elements in this geometry::
  341. >>> polygon.geom_count
  342. 1
  343. .. attribute:: point_count
  344. Returns the number of points used to describe this geometry::
  345. >>> polygon.point_count
  346. 4
  347. .. attribute:: num_points
  348. Alias for :attr:`point_count`.
  349. .. attribute:: num_coords
  350. Alias for :attr:`point_count`.
  351. .. attribute:: geom_type
  352. Returns the type of this geometry, as an :class:`OGRGeomType` object.
  353. .. attribute:: geom_name
  354. Returns the name of the type of this geometry::
  355. >>> polygon.geom_name
  356. 'POLYGON'
  357. .. attribute:: area
  358. Returns the area of this geometry, or 0 for geometries that do not
  359. contain an area::
  360. >>> polygon.area
  361. 25.0
  362. .. attribute:: envelope
  363. Returns the envelope of this geometry, as an :class:`Envelope` object.
  364. .. attribute:: extent
  365. Returns the envelope of this geometry as a 4-tuple, instead of as an
  366. :class:`Envelope` object::
  367. >>> point.extent
  368. (0.0, 0.0, 5.0, 5.0)
  369. .. attribute:: srs
  370. This property controls the spatial reference for this geometry, or
  371. ``None`` if no spatial reference system has been assigned to it.
  372. If assigned, accessing this property returns a :class:`SpatialReference`
  373. object. It may be set with another :class:`SpatialReference` object,
  374. or any input that :class:`SpatialReference` accepts. Example::
  375. >>> city.geom.srs.name
  376. 'GCS_WGS_1984'
  377. .. attribute:: srid
  378. Returns or sets the spatial reference identifier corresponding to
  379. :class:`SpatialReference` of this geometry. Returns ``None`` if
  380. there is no spatial reference information associated with this
  381. geometry, or if an SRID cannot be determined.
  382. .. attribute:: geos
  383. Returns a :class:`~django.contrib.gis.geos.GEOSGeometry` object
  384. corresponding to this geometry.
  385. .. attribute:: gml
  386. Returns a string representation of this geometry in GML format::
  387. >>> OGRGeometry('POINT(1 2)').gml
  388. '<gml:Point><gml:coordinates>1,2</gml:coordinates></gml:Point>'
  389. .. attribute:: hex
  390. Returns a string representation of this geometry in HEX WKB format::
  391. >>> OGRGeometry('POINT(1 2)').hex
  392. '0101000000000000000000F03F0000000000000040'
  393. .. attribute:: json
  394. Returns a string representation of this geometry in JSON format::
  395. >>> OGRGeometry('POINT(1 2)').json
  396. '{ "type": "Point", "coordinates": [ 1.000000, 2.000000 ] }'
  397. .. attribute:: kml
  398. Returns a string representation of this geometry in KML format.
  399. .. attribute:: wkb_size
  400. Returns the size of the WKB buffer needed to hold a WKB representation
  401. of this geometry::
  402. >>> OGRGeometry('POINT(1 2)').wkb_size
  403. 21
  404. .. attribute:: wkb
  405. Returns a ``buffer`` containing a WKB representation of this geometry.
  406. .. attribute:: wkt
  407. Returns a string representation of this geometry in WKT format.
  408. .. attribute:: ewkt
  409. Returns the EWKT representation of this geometry.
  410. .. method:: clone()
  411. Returns a new :class:`OGRGeometry` clone of this geometry object.
  412. .. method:: close_rings()
  413. If there are any rings within this geometry that have not been closed,
  414. this routine will do so by adding the starting point to the end::
  415. >>> triangle = OGRGeometry('LINEARRING (0 0,0 1,1 0)')
  416. >>> triangle.close_rings()
  417. >>> triangle.wkt
  418. 'LINEARRING (0 0,0 1,1 0,0 0)'
  419. .. method:: transform(coord_trans, clone=False)
  420. Transforms this geometry to a different spatial reference system. May
  421. take a :class:`CoordTransform` object, a :class:`SpatialReference` object,
  422. or any other input accepted by :class:`SpatialReference` (including
  423. spatial reference WKT and PROJ.4 strings, or an integer SRID).
  424. By default nothing is returned and the geometry is transformed in-place.
  425. However, if the ``clone`` keyword is set to ``True`` then a transformed
  426. clone of this geometry is returned instead.
  427. .. method:: intersects(other)
  428. Returns ``True`` if this geometry intersects the other, otherwise returns
  429. ``False``.
  430. .. method:: equals(other)
  431. Returns ``True`` if this geometry is equivalent to the other, otherwise returns
  432. ``False``.
  433. .. method:: disjoint(other)
  434. Returns ``True`` if this geometry is spatially disjoint to (i.e. does
  435. not intersect) the other, otherwise returns ``False``.
  436. .. method:: touches(other)
  437. Returns ``True`` if this geometry touches the other, otherwise returns
  438. ``False``.
  439. .. method:: crosses(other)
  440. Returns ``True`` if this geometry crosses the other, otherwise returns
  441. ``False``.
  442. .. method:: within(other)
  443. Returns ``True`` if this geometry is contained within the other, otherwise returns
  444. ``False``.
  445. .. method:: contains(other)
  446. Returns ``True`` if this geometry contains the other, otherwise returns
  447. ``False``.
  448. .. method:: overlaps(other)
  449. Returns ``True`` if this geometry overlaps the other, otherwise returns
  450. ``False``.
  451. .. method:: boundary()
  452. The boundary of this geometry, as a new :class:`OGRGeometry` object.
  453. .. attribute:: convex_hull
  454. The smallest convex polygon that contains this geometry, as a new
  455. :class:`OGRGeometry` object.
  456. .. method:: difference()
  457. Returns the region consisting of the difference of this geometry and
  458. the other, as a new :class:`OGRGeometry` object.
  459. .. method:: intersection()
  460. Returns the region consisting of the intersection of this geometry and
  461. the other, as a new :class:`OGRGeometry` object.
  462. .. method:: sym_difference()
  463. Returns the region consisting of the symmetric difference of this
  464. geometry and the other, as a new :class:`OGRGeometry` object.
  465. .. method:: union()
  466. Returns the region consisting of the union of this geometry and
  467. the other, as a new :class:`OGRGeometry` object.
  468. .. attribute:: tuple
  469. Returns the coordinates of a point geometry as a tuple, the
  470. coordinates of a line geometry as a tuple of tuples, and so forth::
  471. >>> OGRGeometry('POINT (1 2)').tuple
  472. (1.0, 2.0)
  473. >>> OGRGeometry('LINESTRING (1 2,3 4)').tuple
  474. ((1.0, 2.0), (3.0, 4.0))
  475. .. attribute:: coords
  476. An alias for :attr:`tuple`.
  477. .. class:: Point
  478. .. attribute:: x
  479. Returns the X coordinate of this point::
  480. >>> OGRGeometry('POINT (1 2)').x
  481. 1.0
  482. .. attribute:: y
  483. Returns the Y coordinate of this point::
  484. >>> OGRGeometry('POINT (1 2)').y
  485. 2.0
  486. .. attribute:: z
  487. Returns the Z coordinate of this point, or ``None`` if the
  488. point does not have a Z coordinate::
  489. >>> OGRGeometry('POINT (1 2 3)').z
  490. 3.0
  491. .. class:: LineString
  492. .. attribute:: x
  493. Returns a list of X coordinates in this line::
  494. >>> OGRGeometry('LINESTRING (1 2,3 4)').x
  495. [1.0, 3.0]
  496. .. attribute:: y
  497. Returns a list of Y coordinates in this line::
  498. >>> OGRGeometry('LINESTRING (1 2,3 4)').y
  499. [2.0, 4.0]
  500. .. attribute:: z
  501. Returns a list of Z coordinates in this line, or ``None`` if the
  502. line does not have Z coordinates::
  503. >>> OGRGeometry('LINESTRING (1 2 3,4 5 6)').z
  504. [3.0, 6.0]
  505. .. class:: Polygon
  506. .. attribute:: shell
  507. Returns the shell or exterior ring of this polygon, as a ``LinearRing``
  508. geometry.
  509. .. attribute:: exterior_ring
  510. An alias for :attr:`shell`.
  511. .. attribute:: centroid
  512. Returns a :class:`Point` representing the centroid of this polygon.
  513. .. class:: GeometryCollection
  514. .. method:: add(geom)
  515. Adds a geometry to this geometry collection. Not applicable to other
  516. geometry types.
  517. ``OGRGeomType``
  518. ---------------
  519. .. class:: OGRGeomType(type_input)
  520. This class allows for the representation of an OGR geometry type
  521. in any of several ways::
  522. >>> from django.contrib.gis.gdal import OGRGeomType
  523. >>> gt1 = OGRGeomType(3) # Using an integer for the type
  524. >>> gt2 = OGRGeomType('Polygon') # Using a string
  525. >>> gt3 = OGRGeomType('POLYGON') # It's case-insensitive
  526. >>> print(gt1 == 3, gt1 == 'Polygon') # Equivalence works w/non-OGRGeomType objects
  527. True True
  528. .. attribute:: name
  529. Returns a short-hand string form of the OGR Geometry type::
  530. >>> gt1.name
  531. 'Polygon'
  532. .. attribute:: num
  533. Returns the number corresponding to the OGR geometry type::
  534. >>> gt1.num
  535. 3
  536. .. attribute:: django
  537. Returns the Django field type (a subclass of GeometryField) to use for
  538. storing this OGR type, or ``None`` if there is no appropriate Django
  539. type::
  540. >>> gt1.django
  541. 'PolygonField'
  542. ``Envelope``
  543. ------------
  544. .. class:: Envelope(*args)
  545. Represents an OGR Envelope structure that contains the
  546. minimum and maximum X, Y coordinates for a rectangle bounding box.
  547. The naming of the variables is compatible with the OGR Envelope
  548. C structure.
  549. .. attribute:: min_x
  550. The value of the minimum X coordinate.
  551. .. attribute:: min_y
  552. The value of the maximum X coordinate.
  553. .. attribute:: max_x
  554. The value of the minimum Y coordinate.
  555. .. attribute:: max_y
  556. The value of the maximum Y coordinate.
  557. .. attribute:: ur
  558. The upper-right coordinate, as a tuple.
  559. .. attribute:: ll
  560. The lower-left coordinate, as a tuple.
  561. .. attribute:: tuple
  562. A tuple representing the envelope.
  563. .. attribute:: wkt
  564. A string representing this envelope as a polygon in WKT format.
  565. .. method:: expand_to_include(*args)
  566. Coordinate System Objects
  567. =========================
  568. ``SpatialReference``
  569. --------------------
  570. .. class:: SpatialReference(srs_input)
  571. Spatial reference objects are initialized on the given ``srs_input``,
  572. which may be one of the following:
  573. * OGC Well Known Text (WKT) (a string)
  574. * EPSG code (integer or string)
  575. * PROJ.4 string
  576. * A shorthand string for well-known standards (``'WGS84'``, ``'WGS72'``, ``'NAD27'``, ``'NAD83'``)
  577. Example::
  578. >>> wgs84 = SpatialReference('WGS84') # shorthand string
  579. >>> wgs84 = SpatialReference(4326) # EPSG code
  580. >>> wgs84 = SpatialReference('EPSG:4326') # EPSG string
  581. >>> proj4 = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs '
  582. >>> wgs84 = SpatialReference(proj4) # PROJ.4 string
  583. >>> wgs84 = SpatialReference("""GEOGCS["WGS 84",
  584. DATUM["WGS_1984",
  585. SPHEROID["WGS 84",6378137,298.257223563,
  586. AUTHORITY["EPSG","7030"]],
  587. AUTHORITY["EPSG","6326"]],
  588. PRIMEM["Greenwich",0,
  589. AUTHORITY["EPSG","8901"]],
  590. UNIT["degree",0.01745329251994328,
  591. AUTHORITY["EPSG","9122"]],
  592. AUTHORITY["EPSG","4326"]]""") # OGC WKT
  593. .. method:: __getitem__(target)
  594. Returns the value of the given string attribute node, ``None`` if the node
  595. doesn't exist. Can also take a tuple as a parameter, (target, child),
  596. where child is the index of the attribute in the WKT. For example::
  597. >>> wkt = 'GEOGCS["WGS 84", DATUM["WGS_1984, ... AUTHORITY["EPSG","4326"]]')
  598. >>> srs = SpatialReference(wkt) # could also use 'WGS84', or 4326
  599. >>> print(srs['GEOGCS'])
  600. WGS 84
  601. >>> print(srs['DATUM'])
  602. WGS_1984
  603. >>> print(srs['AUTHORITY'])
  604. EPSG
  605. >>> print(srs['AUTHORITY', 1]) # The authority value
  606. 4326
  607. >>> print(srs['TOWGS84', 4]) # the fourth value in this wkt
  608. 0
  609. >>> print(srs['UNIT|AUTHORITY']) # For the units authority, have to use the pipe symbol.
  610. EPSG
  611. >>> print(srs['UNIT|AUTHORITY', 1]) # The authority value for the units
  612. 9122
  613. .. method:: attr_value(target, index=0)
  614. The attribute value for the given target node (e.g. ``'PROJCS'``).
  615. The index keyword specifies an index of the child node to return.
  616. .. method:: auth_name(target)
  617. Returns the authority name for the given string target node.
  618. .. method:: auth_code(target)
  619. Returns the authority code for the given string target node.
  620. .. method:: clone()
  621. Returns a clone of this spatial reference object.
  622. .. method:: identify_epsg()
  623. This method inspects the WKT of this SpatialReference, and will
  624. add EPSG authority nodes where an EPSG identifier is applicable.
  625. .. method:: from_esri()
  626. Morphs this SpatialReference from ESRI's format to EPSG
  627. .. method:: to_esri()
  628. Morphs this SpatialReference to ESRI's format.
  629. .. method:: validate()
  630. Checks to see if the given spatial reference is valid, if not
  631. an exception will be raised.
  632. .. method:: import_epsg(epsg)
  633. Import spatial reference from EPSG code.
  634. .. method:: import_proj(proj)
  635. Import spatial reference from PROJ.4 string.
  636. .. method:: import_user_input(user_input)
  637. .. method:: import_wkt(wkt)
  638. Import spatial reference from WKT.
  639. .. method:: import_xml(xml)
  640. Import spatial reference from XML.
  641. .. attribute:: name
  642. Returns the name of this Spatial Reference.
  643. .. attribute:: srid
  644. Returns the SRID of top-level authority, or ``None`` if undefined.
  645. .. attribute:: linear_name
  646. Returns the name of the linear units.
  647. .. attribute:: linear_units
  648. Returns the value of the linear units.
  649. .. attribute:: angular_name
  650. Returns the name of the angular units."
  651. .. attribute:: angular_units
  652. Returns the value of the angular units.
  653. .. attribute:: units
  654. Returns a 2-tuple of the units value and the units name,
  655. and will automatically determines whether to return the linear
  656. or angular units.
  657. .. attribute:: ellipsoid
  658. Returns a tuple of the ellipsoid parameters for this spatial
  659. reference: (semimajor axis, semiminor axis, and inverse flattening)
  660. .. attribute:: semi_major
  661. Returns the semi major axis of the ellipsoid for this spatial reference.
  662. .. attribute:: semi_minor
  663. Returns the semi minor axis of the ellipsoid for this spatial reference.
  664. .. attribute:: inverse_flattening
  665. Returns the inverse flattening of the ellipsoid for this spatial reference.
  666. .. attribute:: geographic
  667. Returns ``True`` if this spatial reference is geographic
  668. (root node is ``GEOGCS``).
  669. .. attribute:: local
  670. Returns ``True`` if this spatial reference is local
  671. (root node is ``LOCAL_CS``).
  672. .. attribute:: projected
  673. Returns ``True`` if this spatial reference is a projected coordinate
  674. system (root node is ``PROJCS``).
  675. .. attribute:: wkt
  676. Returns the WKT representation of this spatial reference.
  677. .. attribute:: pretty_wkt
  678. Returns the 'pretty' representation of the WKT.
  679. .. attribute:: proj
  680. Returns the PROJ.4 representation for this spatial reference.
  681. .. attribute:: proj4
  682. Alias for :attr:`SpatialReference.proj`.
  683. .. attribute:: xml
  684. Returns the XML representation of this spatial reference.
  685. ``CoordTransform``
  686. ------------------
  687. .. class:: CoordTransform(source, target)
  688. Represents a coordinate system transform. It is initialized with two
  689. :class:`SpatialReference`, representing the source and target coordinate
  690. systems, respectively. These objects should be used when performing
  691. the same coordinate transformation repeatedly on different geometries::
  692. >>> ct = CoordTransform(SpatialReference('WGS84'), SpatialReference('NAD83'))
  693. >>> for feat in layer:
  694. ... geom = feat.geom # getting clone of feature geometry
  695. ... geom.transform(ct) # transforming
  696. .. _raster-data-source-objects:
  697. Raster Data Objects
  698. ===================
  699. .. versionadded:: 1.8
  700. ``GDALRaster``
  701. ----------------
  702. :class:`GDALRaster` is a wrapper for the GDAL raster source object that
  703. supports reading data from a variety of GDAL-supported geospatial file
  704. formats and data sources using a simple, consistent interface. Each
  705. data source is represented by a :class:`GDALRaster` object which contains
  706. one or more layers of data named bands. Each band, represented by a
  707. :class:`GDALBand` object, contains georeferenced image data. For example, an RGB
  708. image is represented as three bands: one for red, one for green, and one for
  709. blue.
  710. .. note::
  711. For raster data there is no difference between a raster instance and its
  712. data source. Unlike for the Geometry objects, :class:`GDALRaster` objects are
  713. always a data source. Temporary rasters can be instantiated in memory
  714. using the corresponding driver, but they will be of the same class as file-based
  715. raster sources.
  716. .. class:: GDALRaster(ds_input, write=False)
  717. The constructor for ``GDALRaster`` accepts two parameters. The first parameter
  718. defines the raster source, it is either a path to a file or spatial data with
  719. values defining the properties of a new raster (such as size and name). If the
  720. input is a file path, the second parameter specifies if the raster should
  721. be opened with write access. If the input is raw data, the parameters ``width``,
  722. ``heigth``, and ``srid`` are required. The following example shows how rasters
  723. can be created from different input sources (using the sample data from the
  724. GeoDjango tests, see also the :ref:`gdal_sample_data` section)::
  725. >>> from django.contrib.gis.gdal import GDALRaster
  726. >>> rst = GDALRaster('/path/to/your/raster.tif', write=False)
  727. >>> rst.name
  728. '/path/to/your/raster.tif'
  729. >>> rst.width, rst.height # This file has 163 x 174 pixels
  730. (163, 174)
  731. >>> rst = GDALRaster({'srid': 4326, 'width': 1, 'height': 2, 'datatype': 1
  732. ... 'bands': [{'data': [0, 1]}]}) # Creates in-memory raster
  733. >>> rst.srs.srid
  734. 4326
  735. >>> rst.width, rst.height
  736. (1, 2)
  737. >>> rst.bands[0].data()
  738. array([[0, 1]], dtype=int8)
  739. .. versionchanged:: 1.9
  740. ``GDALRaster`` objects can now be instantiated directly from raw data.
  741. Setters have been added for the following properties: ``srs``,
  742. ``geotransform``, ``origin``, ``scale``, and ``skew``.
  743. .. attribute:: name
  744. The name of the source which is equivalent to the input file path or the name
  745. provided upon instantiation.
  746. >>> GDALRaster({'width': 10, 'height': 10, 'name': 'myraster', 'srid': 4326}).name
  747. 'myraster'
  748. .. attribute:: driver
  749. The name of the GDAL driver used to handle the input file. For ``GDALRaster``\s created
  750. from a file, the driver type is detected automatically. The creation of rasters from
  751. scratch is a in-memory raster by default (``'MEM'``), but can be altered as
  752. needed. For instance, use ``GTiff`` for a ``GeoTiff`` file. For a list of file types,
  753. see also the `GDAL Raster Formats`__ list.
  754. __ http://www.gdal.org/formats_list.html
  755. An in-memory raster is created through the following example:
  756. >>> GDALRaster({'width': 10, 'height': 10, 'srid': 4326}).driver.name
  757. 'MEM'
  758. A file based GeoTiff raster is created through the following example:
  759. >>> import tempfile
  760. >>> rstfile = tempfile.NamedTemporaryFile(suffix='.tif')
  761. >>> rst = GDALRaster({'driver': 'GTiff', 'name': rstfile.name, 'srid': 4326,
  762. ... 'width': 255, 'height': 255, 'nr_of_bands': 1})
  763. >>> rst.name
  764. '/tmp/tmp7x9H4J.tif' # The exact filename will be different on your computer
  765. >>> rst.driver.name
  766. 'GTiff'
  767. .. attribute:: width
  768. The width of the source in pixels (X-axis).
  769. >>> GDALRaster({'width': 10, 'height': 20, 'srid': 4326}).width
  770. 10
  771. .. attribute:: height
  772. The height of the source in pixels (Y-axis).
  773. >>> GDALRaster({'width': 10, 'height': 20, 'srid': 4326}).height
  774. 20
  775. .. attribute:: srs
  776. The spatial reference system of the raster, as a
  777. :class:`SpatialReference` instance. The SRS can be changed by
  778. setting it to an other :class:`SpatialReference` or providing any input
  779. that is accepted by the :class:`SpatialReference` constructor.
  780. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  781. >>> rst.srs.srid
  782. 4326
  783. >>> rst.srs = 3086
  784. >>> rst.srs.srid
  785. 3086
  786. .. attribute:: geotransform
  787. The affine transformation matrix used to georeference the source, as a
  788. tuple of six coefficients which map pixel/line coordinates into
  789. georeferenced space using the following relationship::
  790. Xgeo = GT(0) + Xpixel*GT(1) + Yline*GT(2)
  791. Ygeo = GT(3) + Xpixel*GT(4) + Yline*GT(5)
  792. The same values can be retrieved by accessing the :attr:`origin`
  793. (indices 0 and 3), :attr:`scale` (indices 1 and 5) and :attr:`skew`
  794. (indices 2 and 4) properties.
  795. The default is ``[0.0, 1.0, 0.0, 0.0, 0.0, -1.0]``.
  796. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  797. >>> rst.geotransform
  798. [0.0, 1.0, 0.0, 0.0, 0.0, -1.0]
  799. .. attribute:: origin
  800. Coordinates of the top left origin of the raster in the spatial
  801. reference system of the source, as a point object with ``x`` and ``y``
  802. members.
  803. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  804. >>> rst.origin
  805. [0.0, 0.0]
  806. >>> rst.origin.x = 1
  807. >>> rst.origin
  808. [1.0, 0.0]
  809. .. attribute:: scale
  810. Pixel width and height used for georeferencing the raster, as a as a
  811. point object with ``x`` and ``y`` members. See :attr:`geotransform`
  812. for more information.
  813. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  814. >>> rst.scale
  815. [1.0, -1.0]
  816. >>> rst.scale.x = 2
  817. >>> rst.scale
  818. [2.0, -1.0]
  819. .. attribute:: skew
  820. Skew coefficients used to georeference the raster, as a point object
  821. with ``x`` and ``y`` members. In case of north up images, these
  822. coefficients are both ``0``.
  823. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  824. >>> rst.skew
  825. [0.0, 0.0]
  826. >>> rst.skew.x = 3
  827. >>> rst.skew
  828. [3.0, 0.0]
  829. .. attribute:: extent
  830. Extent (boundary values) of the raster source, as a 4-tuple
  831. ``(xmin, ymin, xmax, ymax)`` in the spatial reference system of the
  832. source.
  833. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  834. >>> rst.extent
  835. (0.0, -20.0, 10.0, 0.0)
  836. >>> rst.origin.x = 100
  837. >>> rst.extent
  838. (100.0, -20.0, 110.0, 0.0)
  839. .. attribute:: bands
  840. List of all bands of the source, as :class:`GDALBand` instances.
  841. >>> rst = GDALRaster({"width": 1, "height": 2, 'srid': 4326,
  842. ... "bands": [{"data": [0, 1]}, {"data": [2, 3]}]})
  843. >>> len(rst.bands)
  844. 2
  845. >>> rst.bands[1].data()
  846. array([[ 2., 3.]], dtype=float32)
  847. ``GDALBand``
  848. ------------
  849. .. class:: GDALBand
  850. ``GDALBand`` instances are not created explicitly, but rather obtained
  851. from a :class:`GDALRaster` object, through its :attr:`~GDALRaster.bands`
  852. attribute. The GDALBands contain the actual pixel values of the raster.
  853. .. attribute:: description
  854. The name or description of the band, if any.
  855. .. attribute:: width
  856. The width of the band in pixels (X-axis).
  857. .. attribute:: height
  858. The height of the band in pixels (Y-axis).
  859. .. attribute:: pixel_count
  860. .. versionadded:: 1.9
  861. The total number of pixels in this band. Is equal to ``width * height``.
  862. .. attribute:: min
  863. The minimum pixel value of the band (excluding the "no data" value).
  864. .. attribute:: max
  865. The maximum pixel value of the band (excluding the "no data" value).
  866. .. attribute:: nodata_value
  867. The "no data" value for a band is generally a special marker value used
  868. to mark pixels that are not valid data. Such pixels should generally not
  869. be displayed, nor contribute to analysis operations.
  870. .. versionchanged:: 1.9
  871. This property can now be set as well.
  872. .. method:: datatype([as_string=False])
  873. The data type contained in the band, as an integer constant between 0
  874. (Unknown) and 11. If ``as_string`` is ``True``, the data type is
  875. returned as a string with the following possible values:
  876. ``GDT_Unknown``, ``GDT_Byte``, ``GDT_UInt16``, ``GDT_Int16``,
  877. ``GDT_UInt32``, ``GDT_Int32``, ``GDT_Float32``, ``GDT_Float64``,
  878. ``GDT_CInt16``, ``GDT_CInt32``, ``GDT_CFloat32``, and ``GDT_CFloat64``.
  879. .. method:: data(data=None, offset=None, size=None)
  880. .. versionadded:: 1.9
  881. The accessor to the pixel values of the ``GDALBand``. Returns the complete
  882. data array if no parameters are provided. A subset of the pixel array can
  883. be requested by specifying an offset and block size as tuples.
  884. If NumPy is available, the data is returned as NumPy array. For performance
  885. reasons, it is highly recommended to use NumPy.
  886. Data is written to the ``GDALBand`` if the ``data`` parameter is provided.
  887. The input can be of one of the following types - packed string, buffer, list,
  888. array, and NumPy array. The number of items in the input must correspond to the
  889. total number of pixels in the band, or to the number of pixels for a specific
  890. block of pixel values if the ``offset`` and ``size`` parameters are provided.
  891. For example:
  892. >>> rst = GDALRaster({'width': 4, 'height': 4, 'srid': 4326, 'datatype': 1, 'nr_of_bands': 1})
  893. >>> bnd = rst.bands[0]
  894. >>> bnd.data(range(16))
  895. >>> bnd.data()
  896. array([[ 0, 1, 2, 3],
  897. [ 4, 5, 6, 7],
  898. [ 8, 9, 10, 11],
  899. [12, 13, 14, 15]], dtype=int8)
  900. >>> bnd.data(offset=(1, 1), size=(2, 2))
  901. array([[ 5, 6],
  902. [ 9, 10]], dtype=int8)
  903. >>> bnd.data(data=[-1, -2, -3, -4], offset=(1, 1), size=(2, 2))
  904. >>> bnd.data()
  905. array([[ 0, 1, 2, 3],
  906. [ 4, -1, -2, 7],
  907. [ 8, -3, -4, 11],
  908. [12, 13, 14, 15]], dtype=int8)
  909. >>> bnd.data(data='\x9d\xa8\xb3\xbe', offset=(1, 1), size=(2, 2))
  910. >>> bnd.data()
  911. array([[ 0, 1, 2, 3],
  912. [ 4, -99, -88, 7],
  913. [ 8, -77, -66, 11],
  914. [ 12, 13, 14, 15]], dtype=int8)
  915. Settings
  916. ========
  917. .. setting:: GDAL_LIBRARY_PATH
  918. GDAL_LIBRARY_PATH
  919. -----------------
  920. A string specifying the location of the GDAL library. Typically,
  921. this setting is only used if the GDAL library is in a non-standard
  922. location (e.g., ``/home/john/lib/libgdal.so``).