tutorial.txt 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. ==================
  2. GeoDjango Tutorial
  3. ==================
  4. Introduction
  5. ============
  6. GeoDjango is an included contrib module for Django that turns it into a
  7. world-class geographic Web framework. GeoDjango strives to make it as simple
  8. as possible to create geographic Web applications, like location-based services.
  9. Its features include:
  10. * Django model fields for `OGC`_ geometries.
  11. * Extensions to Django's ORM for querying and manipulating spatial data.
  12. * Loosely-coupled, high-level Python interfaces for GIS geometry operations and
  13. data formats.
  14. * Editing geometry fields from the admin.
  15. This tutorial assumes familiarity with Django; thus, if you're brand new to
  16. Django, please read through the :doc:`regular tutorial </intro/tutorial01>` to
  17. familiarize yourself with Django first.
  18. .. note::
  19. GeoDjango has additional requirements beyond what Django requires --
  20. please consult the :doc:`installation documentation <install/index>`
  21. for more details.
  22. This tutorial will guide you through the creation of a geographic web
  23. application for viewing the `world borders`_. [#]_ Some of the code
  24. used in this tutorial is taken from and/or inspired by the `GeoDjango
  25. basic apps`_ project. [#]_
  26. .. note::
  27. Proceed through the tutorial sections sequentially for step-by-step
  28. instructions.
  29. .. _OGC: http://www.opengeospatial.org/
  30. .. _world borders: http://thematicmapping.org/downloads/world_borders.php
  31. .. _GeoDjango basic apps: http://code.google.com/p/geodjango-basic-apps/
  32. Setting Up
  33. ==========
  34. Create a Spatial Database
  35. -------------------------
  36. .. note::
  37. MySQL and Oracle users can skip this section because spatial types
  38. are already built into the database.
  39. First, create a spatial database for your project.
  40. If you are using PostGIS, create the database from the :ref:`spatial database
  41. template <spatialdb_template>`:
  42. .. code-block:: console
  43. $ createdb -T template_postgis geodjango
  44. .. note::
  45. This command must be issued by a database user with enough privileges to
  46. create a database. To create a user with ``CREATE DATABASE`` privileges in
  47. PostgreSQL, use the following commands:
  48. .. code-block:: console
  49. $ sudo su - postgres
  50. $ createuser --createdb geo
  51. $ exit
  52. Replace ``geo`` with your Postgres database user's username.
  53. (In PostgreSQL, this user will also be an OS-level user.)
  54. If you are using SQLite and SpatiaLite, consult the instructions on how
  55. to create a :ref:`SpatiaLite database <create_spatialite_db>`.
  56. Create a New Project
  57. ------------------------
  58. Use the standard ``django-admin`` script to create a project called
  59. ``geodjango``:
  60. .. code-block:: console
  61. $ django-admin startproject geodjango
  62. This will initialize a new project. Now, create a ``world`` Django application
  63. within the ``geodjango`` project:
  64. .. code-block:: console
  65. $ cd geodjango
  66. $ python manage.py startapp world
  67. Configure ``settings.py``
  68. -------------------------
  69. The ``geodjango`` project settings are stored in the ``geodjango/settings.py``
  70. file. Edit the database connection settings to match your setup::
  71. DATABASES = {
  72. 'default': {
  73. 'ENGINE': 'django.contrib.gis.db.backends.postgis',
  74. 'NAME': 'geodjango',
  75. 'USER': 'geo',
  76. }
  77. }
  78. In addition, modify the :setting:`INSTALLED_APPS` setting to include
  79. :mod:`django.contrib.admin`, :mod:`django.contrib.gis`,
  80. and ``world`` (your newly created application)::
  81. INSTALLED_APPS = [
  82. 'django.contrib.admin',
  83. 'django.contrib.auth',
  84. 'django.contrib.contenttypes',
  85. 'django.contrib.sessions',
  86. 'django.contrib.messages',
  87. 'django.contrib.staticfiles',
  88. 'django.contrib.gis',
  89. 'world'
  90. ]
  91. Geographic Data
  92. ===============
  93. .. _worldborders:
  94. World Borders
  95. -------------
  96. The world borders data is available in this `zip file`__. Create a ``data``
  97. directory in the ``world`` application, download the world borders data, and
  98. unzip. On GNU/Linux platforms, use the following commands:
  99. .. code-block:: console
  100. $ mkdir world/data
  101. $ cd world/data
  102. $ wget http://thematicmapping.org/downloads/TM_WORLD_BORDERS-0.3.zip
  103. $ unzip TM_WORLD_BORDERS-0.3.zip
  104. $ cd ../..
  105. The world borders ZIP file contains a set of data files collectively known as
  106. an `ESRI Shapefile`__, one of the most popular geospatial data formats. When
  107. unzipped, the world borders dataset includes files with the following
  108. extensions:
  109. * ``.shp``: Holds the vector data for the world borders geometries.
  110. * ``.shx``: Spatial index file for geometries stored in the ``.shp``.
  111. * ``.dbf``: Database file for holding non-geometric attribute data
  112. (e.g., integer and character fields).
  113. * ``.prj``: Contains the spatial reference information for the geographic
  114. data stored in the shapefile.
  115. __ http://thematicmapping.org/downloads/TM_WORLD_BORDERS-0.3.zip
  116. __ http://en.wikipedia.org/wiki/Shapefile
  117. Use ``ogrinfo`` to examine spatial data
  118. ---------------------------------------
  119. The GDAL ``ogrinfo`` utility allows examining the metadata of shapefiles or
  120. other vector data sources:
  121. .. code-block:: console
  122. $ ogrinfo world/data/TM_WORLD_BORDERS-0.3.shp
  123. INFO: Open of `world/data/TM_WORLD_BORDERS-0.3.shp'
  124. using driver `ESRI Shapefile' successful.
  125. 1: TM_WORLD_BORDERS-0.3 (Polygon)
  126. ``ogrinfo`` tells us that the shapefile has one layer, and that this
  127. layer contains polygon data. To find out more, we'll specify the layer name
  128. and use the ``-so`` option to get only the important summary information:
  129. .. code-block:: console
  130. $ ogrinfo -so world/data/TM_WORLD_BORDERS-0.3.shp TM_WORLD_BORDERS-0.3
  131. INFO: Open of `world/data/TM_WORLD_BORDERS-0.3.shp'
  132. using driver `ESRI Shapefile' successful.
  133. Layer name: TM_WORLD_BORDERS-0.3
  134. Geometry: Polygon
  135. Feature Count: 246
  136. Extent: (-180.000000, -90.000000) - (180.000000, 83.623596)
  137. Layer SRS WKT:
  138. GEOGCS["GCS_WGS_1984",
  139. DATUM["WGS_1984",
  140. SPHEROID["WGS_1984",6378137.0,298.257223563]],
  141. PRIMEM["Greenwich",0.0],
  142. UNIT["Degree",0.0174532925199433]]
  143. FIPS: String (2.0)
  144. ISO2: String (2.0)
  145. ISO3: String (3.0)
  146. UN: Integer (3.0)
  147. NAME: String (50.0)
  148. AREA: Integer (7.0)
  149. POP2005: Integer (10.0)
  150. REGION: Integer (3.0)
  151. SUBREGION: Integer (3.0)
  152. LON: Real (8.3)
  153. LAT: Real (7.3)
  154. This detailed summary information tells us the number of features in the layer
  155. (246), the geographic bounds of the data, the spatial reference system
  156. ("SRS WKT"), as well as type information for each attribute field. For example,
  157. ``FIPS: String (2.0)`` indicates that the ``FIPS`` character field has
  158. a maximum length of 2. Similarly, ``LON: Real (8.3)`` is a floating-point
  159. field that holds a maximum of 8 digits up to three decimal places.
  160. Geographic Models
  161. =================
  162. Defining a Geographic Model
  163. ---------------------------
  164. Now that you've examined your dataset using ``ogrinfo``, create a GeoDjango
  165. model to represent this data::
  166. from django.contrib.gis.db import models
  167. class WorldBorder(models.Model):
  168. # Regular Django fields corresponding to the attributes in the
  169. # world borders shapefile.
  170. name = models.CharField(max_length=50)
  171. area = models.IntegerField()
  172. pop2005 = models.IntegerField('Population 2005')
  173. fips = models.CharField('FIPS Code', max_length=2)
  174. iso2 = models.CharField('2 Digit ISO', max_length=2)
  175. iso3 = models.CharField('3 Digit ISO', max_length=3)
  176. un = models.IntegerField('United Nations Code')
  177. region = models.IntegerField('Region Code')
  178. subregion = models.IntegerField('Sub-Region Code')
  179. lon = models.FloatField()
  180. lat = models.FloatField()
  181. # GeoDjango-specific: a geometry field (MultiPolygonField), and
  182. # overriding the default manager with a GeoManager instance.
  183. mpoly = models.MultiPolygonField()
  184. objects = models.GeoManager()
  185. # Returns the string representation of the model.
  186. def __str__(self): # __unicode__ on Python 2
  187. return self.name
  188. Please note two important things:
  189. 1. The ``models`` module is imported from ``django.contrib.gis.db``.
  190. 2. You must override the model's default manager with
  191. :class:`~django.contrib.gis.db.models.GeoManager` to perform spatial queries.
  192. The default spatial reference system for geometry fields is WGS84 (meaning
  193. the `SRID`__ is 4326) -- in other words, the field coordinates are in
  194. longitude, latitude pairs in units of degrees. To use a different
  195. coordinate system, set the SRID of the geometry field with the ``srid``
  196. argument. Use an integer representing the coordinate system's EPSG code.
  197. __ http://en.wikipedia.org/wiki/SRID
  198. Run ``migrate``
  199. ---------------
  200. After defining your model, you need to sync it with the database. First,
  201. create a database migration:
  202. .. code-block:: console
  203. $ python manage.py makemigrations
  204. Migrations for 'world':
  205. 0001_initial.py:
  206. - Create model WorldBorder
  207. Let's look at the SQL that will generate the table for the ``WorldBorder``
  208. model:
  209. .. code-block:: console
  210. $ python manage.py sqlmigrate world 0001
  211. This command should produce the following output:
  212. .. code-block:: sql
  213. BEGIN;
  214. --
  215. -- Create model WorldBorder
  216. --
  217. CREATE TABLE "world_worldborder" (
  218. "id" serial NOT NULL PRIMARY KEY,
  219. "name" varchar(50) NOT NULL,
  220. "area" integer NOT NULL,
  221. "pop2005" integer NOT NULL,
  222. "fips" varchar(2) NOT NULL,
  223. "iso2" varchar(2) NOT NULL,
  224. "iso3" varchar(3) NOT NULL,
  225. "un" integer NOT NULL,
  226. "region" integer NOT NULL,
  227. "subregion" integer NOT NULL,
  228. "lon" double precision NOT NULL,
  229. "lat" double precision NOT NULL
  230. "mpoly" geometry(MULTIPOLYGON,4326) NOT NULL
  231. )
  232. ;
  233. CREATE INDEX "world_worldborder_mpoly_id" ON "world_worldborder" USING GIST ( "mpoly" );
  234. COMMIT;
  235. .. note::
  236. With PostGIS < 2.0, the output is slightly different. The ``mpoly`` geometry
  237. column is added through a separate ``SELECT AddGeometryColumn(...)``
  238. statement.
  239. If this looks correct, run :djadmin:`migrate` to create this table in the
  240. database:
  241. .. code-block:: console
  242. $ python manage.py migrate
  243. Operations to perform:
  244. Apply all migrations: admin, world, contenttypes, auth, sessions
  245. Running migrations:
  246. ...
  247. Applying world.0001_initial... OK
  248. Importing Spatial Data
  249. ======================
  250. This section will show you how to import the world borders shapefile into the
  251. database via GeoDjango models using the :doc:`layermapping`.
  252. There are many different ways to import data into a spatial database --
  253. besides the tools included within GeoDjango, you may also use the following:
  254. * `ogr2ogr`_: A command-line utility included with GDAL that
  255. can import many vector data formats into PostGIS, MySQL, and Oracle databases.
  256. * `shp2pgsql`_: This utility included with PostGIS imports ESRI shapefiles into
  257. PostGIS.
  258. .. _ogr2ogr: http://www.gdal.org/ogr2ogr.html
  259. .. _shp2pgsql: http://postgis.net/docs/manual-1.5/ch04.html#shp2pgsql_usage
  260. .. _gdalinterface:
  261. GDAL Interface
  262. --------------
  263. Earlier, you used ``ogrinfo`` to examine the contents of the world borders
  264. shapefile. GeoDjango also includes a Pythonic interface to GDAL's powerful OGR
  265. library that can work with all the vector data sources that OGR supports.
  266. First, invoke the Django shell:
  267. .. code-block:: console
  268. $ python manage.py shell
  269. If you downloaded the :ref:`worldborders` data earlier in the
  270. tutorial, then you can determine its path using Python's built-in
  271. ``os`` module::
  272. >>> import os
  273. >>> import world
  274. >>> world_shp = os.path.abspath(os.path.join(os.path.dirname(world.__file__),
  275. ... 'data/TM_WORLD_BORDERS-0.3.shp'))
  276. Now, open the world borders shapefile using GeoDjango's
  277. :class:`~django.contrib.gis.gdal.DataSource` interface::
  278. >>> from django.contrib.gis.gdal import DataSource
  279. >>> ds = DataSource(world_shp)
  280. >>> print(ds)
  281. / ... /geodjango/world/data/TM_WORLD_BORDERS-0.3.shp (ESRI Shapefile)
  282. Data source objects can have different layers of geospatial features; however,
  283. shapefiles are only allowed to have one layer::
  284. >>> print(len(ds))
  285. 1
  286. >>> lyr = ds[0]
  287. >>> print(lyr)
  288. TM_WORLD_BORDERS-0.3
  289. You can see the layer's geometry type and how many features it contains::
  290. >>> print(lyr.geom_type)
  291. Polygon
  292. >>> print(len(lyr))
  293. 246
  294. .. note::
  295. Unfortunately, the shapefile data format does not allow for greater
  296. specificity with regards to geometry types. This shapefile, like
  297. many others, actually includes ``MultiPolygon`` geometries, not Polygons.
  298. It's important to use a more general field type in models: a
  299. GeoDjango ``MultiPolygonField`` will accept a ``Polygon`` geometry, but a
  300. ``PolygonField`` will not accept a ``MultiPolygon`` type geometry. This
  301. is why the ``WorldBorder`` model defined above uses a ``MultiPolygonField``.
  302. The :class:`~django.contrib.gis.gdal.Layer` may also have a spatial reference
  303. system associated with it. If it does, the ``srs`` attribute will return a
  304. :class:`~django.contrib.gis.gdal.SpatialReference` object::
  305. >>> srs = lyr.srs
  306. >>> print(srs)
  307. GEOGCS["GCS_WGS_1984",
  308. DATUM["WGS_1984",
  309. SPHEROID["WGS_1984",6378137.0,298.257223563]],
  310. PRIMEM["Greenwich",0.0],
  311. UNIT["Degree",0.0174532925199433]]
  312. >>> srs.proj4 # PROJ.4 representation
  313. '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs '
  314. This shapefile is in the popular WGS84 spatial reference
  315. system -- in other words, the data uses longitude, latitude pairs in
  316. units of degrees.
  317. In addition, shapefiles also support attribute fields that may contain
  318. additional data. Here are the fields on the World Borders layer:
  319. >>> print(lyr.fields)
  320. ['FIPS', 'ISO2', 'ISO3', 'UN', 'NAME', 'AREA', 'POP2005', 'REGION', 'SUBREGION', 'LON', 'LAT']
  321. The following code will let you examine the OGR types (e.g. integer or
  322. string) associated with each of the fields:
  323. >>> [fld.__name__ for fld in lyr.field_types]
  324. ['OFTString', 'OFTString', 'OFTString', 'OFTInteger', 'OFTString', 'OFTInteger', 'OFTInteger', 'OFTInteger', 'OFTInteger', 'OFTReal', 'OFTReal']
  325. You can iterate over each feature in the layer and extract information from both
  326. the feature's geometry (accessed via the ``geom`` attribute) as well as the
  327. feature's attribute fields (whose **values** are accessed via ``get()``
  328. method)::
  329. >>> for feat in lyr:
  330. ... print(feat.get('NAME'), feat.geom.num_points)
  331. ...
  332. Guernsey 18
  333. Jersey 26
  334. South Georgia South Sandwich Islands 338
  335. Taiwan 363
  336. :class:`~django.contrib.gis.gdal.Layer` objects may be sliced::
  337. >>> lyr[0:2]
  338. [<django.contrib.gis.gdal.feature.Feature object at 0x2f47690>, <django.contrib.gis.gdal.feature.Feature object at 0x2f47650>]
  339. And individual features may be retrieved by their feature ID::
  340. >>> feat = lyr[234]
  341. >>> print(feat.get('NAME'))
  342. San Marino
  343. Boundary geometries may be exported as WKT and GeoJSON::
  344. >>> geom = feat.geom
  345. >>> print(geom.wkt)
  346. POLYGON ((12.415798 43.957954,12.450554 ...
  347. >>> print(geom.json)
  348. { "type": "Polygon", "coordinates": [ [ [ 12.415798, 43.957954 ], [ 12.450554, 43.979721 ], ...
  349. ``LayerMapping``
  350. ----------------
  351. To import the data, use a LayerMapping in a Python script.
  352. Create a file called ``load.py`` inside the ``world`` application,
  353. with the following code::
  354. import os
  355. from django.contrib.gis.utils import LayerMapping
  356. from models import WorldBorder
  357. world_mapping = {
  358. 'fips' : 'FIPS',
  359. 'iso2' : 'ISO2',
  360. 'iso3' : 'ISO3',
  361. 'un' : 'UN',
  362. 'name' : 'NAME',
  363. 'area' : 'AREA',
  364. 'pop2005' : 'POP2005',
  365. 'region' : 'REGION',
  366. 'subregion' : 'SUBREGION',
  367. 'lon' : 'LON',
  368. 'lat' : 'LAT',
  369. 'mpoly' : 'MULTIPOLYGON',
  370. }
  371. world_shp = os.path.abspath(os.path.join(os.path.dirname(__file__), 'data/TM_WORLD_BORDERS-0.3.shp'))
  372. def run(verbose=True):
  373. lm = LayerMapping(WorldBorder, world_shp, world_mapping,
  374. transform=False, encoding='iso-8859-1')
  375. lm.save(strict=True, verbose=verbose)
  376. A few notes about what's going on:
  377. * Each key in the ``world_mapping`` dictionary corresponds to a field in the
  378. ``WorldBorder`` model. The value is the name of the shapefile field
  379. that data will be loaded from.
  380. * The key ``mpoly`` for the geometry field is ``MULTIPOLYGON``, the
  381. geometry type GeoDjango will import the field as. Even simple polygons in
  382. the shapefile will automatically be converted into collections prior to
  383. insertion into the database.
  384. * The path to the shapefile is not absolute -- in other words, if you move the
  385. ``world`` application (with ``data`` subdirectory) to a different location,
  386. the script will still work.
  387. * The ``transform`` keyword is set to ``False`` because the data in the
  388. shapefile does not need to be converted -- it's already in WGS84 (SRID=4326).
  389. * The ``encoding`` keyword is set to the character encoding of the string
  390. values in the shapefile. This ensures that string values are read and saved
  391. correctly from their original encoding system.
  392. Afterwards, invoke the Django shell from the ``geodjango`` project directory:
  393. .. code-block:: console
  394. $ python manage.py shell
  395. Next, import the ``load`` module, call the ``run`` routine, and watch
  396. ``LayerMapping`` do the work::
  397. >>> from world import load
  398. >>> load.run()
  399. .. _ogrinspect-intro:
  400. Try ``ogrinspect``
  401. ------------------
  402. Now that you've seen how to define geographic models and import data with the
  403. :doc:`layermapping`, it's possible to further automate this process with
  404. use of the :djadmin:`ogrinspect` management command. The :djadmin:`ogrinspect`
  405. command introspects a GDAL-supported vector data source (e.g., a shapefile)
  406. and generates a model definition and ``LayerMapping`` dictionary automatically.
  407. The general usage of the command goes as follows:
  408. .. code-block:: console
  409. $ python manage.py ogrinspect [options] <data_source> <model_name> [options]
  410. ``data_source`` is the path to the GDAL-supported data source and
  411. ``model_name`` is the name to use for the model. Command-line options may
  412. be used to further define how the model is generated.
  413. For example, the following command nearly reproduces the ``WorldBorder`` model
  414. and mapping dictionary created above, automatically:
  415. .. code-block:: console
  416. $ python manage.py ogrinspect world/data/TM_WORLD_BORDERS-0.3.shp WorldBorder \
  417. --srid=4326 --mapping --multi
  418. A few notes about the command-line options given above:
  419. * The ``--srid=4326`` option sets the SRID for the geographic field.
  420. * The ``--mapping`` option tells ``ogrinspect`` to also generate a
  421. mapping dictionary for use with
  422. :class:`~django.contrib.gis.utils.LayerMapping`.
  423. * The ``--multi`` option is specified so that the geographic field is a
  424. :class:`~django.contrib.gis.db.models.MultiPolygonField` instead of just a
  425. :class:`~django.contrib.gis.db.models.PolygonField`.
  426. The command produces the following output, which may be copied
  427. directly into the ``models.py`` of a GeoDjango application::
  428. # This is an auto-generated Django model module created by ogrinspect.
  429. from django.contrib.gis.db import models
  430. class WorldBorder(models.Model):
  431. fips = models.CharField(max_length=2)
  432. iso2 = models.CharField(max_length=2)
  433. iso3 = models.CharField(max_length=3)
  434. un = models.IntegerField()
  435. name = models.CharField(max_length=50)
  436. area = models.IntegerField()
  437. pop2005 = models.IntegerField()
  438. region = models.IntegerField()
  439. subregion = models.IntegerField()
  440. lon = models.FloatField()
  441. lat = models.FloatField()
  442. geom = models.MultiPolygonField(srid=4326)
  443. objects = models.GeoManager()
  444. # Auto-generated `LayerMapping` dictionary for WorldBorder model
  445. worldborders_mapping = {
  446. 'fips' : 'FIPS',
  447. 'iso2' : 'ISO2',
  448. 'iso3' : 'ISO3',
  449. 'un' : 'UN',
  450. 'name' : 'NAME',
  451. 'area' : 'AREA',
  452. 'pop2005' : 'POP2005',
  453. 'region' : 'REGION',
  454. 'subregion' : 'SUBREGION',
  455. 'lon' : 'LON',
  456. 'lat' : 'LAT',
  457. 'geom' : 'MULTIPOLYGON',
  458. }
  459. Spatial Queries
  460. ===============
  461. Spatial Lookups
  462. ---------------
  463. GeoDjango adds spatial lookups to the Django ORM. For example, you
  464. can find the country in the ``WorldBorder`` table that contains
  465. a particular point. First, fire up the management shell:
  466. .. code-block:: console
  467. $ python manage.py shell
  468. Now, define a point of interest [#]_::
  469. >>> pnt_wkt = 'POINT(-95.3385 29.7245)'
  470. The ``pnt_wkt`` string represents the point at -95.3385 degrees longitude,
  471. 29.7245 degrees latitude. The geometry is in a format known as
  472. Well Known Text (WKT), a standard issued by the Open Geospatial
  473. Consortium (OGC). [#]_ Import the ``WorldBorder`` model, and perform
  474. a ``contains`` lookup using the ``pnt_wkt`` as the parameter::
  475. >>> from world.models import WorldBorder
  476. >>> qs = WorldBorder.objects.filter(mpoly__contains=pnt_wkt)
  477. >>> qs
  478. [<WorldBorder: United States>]
  479. Here, you retrieved a ``QuerySet`` with only one model: the border of the
  480. United States (exactly what you would expect).
  481. Similarly, you may also use a :doc:`GEOS geometry object <geos>`.
  482. Here, you can combine the ``intersects`` spatial lookup with the ``get``
  483. method to retrieve only the ``WorldBorder`` instance for San Marino instead
  484. of a queryset::
  485. >>> from django.contrib.gis.geos import Point
  486. >>> pnt = Point(12.4604, 43.9420)
  487. >>> sm = WorldBorder.objects.get(mpoly__intersects=pnt)
  488. >>> sm
  489. <WorldBorder: San Marino>
  490. The ``contains`` and ``intersects`` lookups are just a subset of the
  491. available queries -- the :doc:`db-api` documentation has more.
  492. Automatic Spatial Transformations
  493. ---------------------------------
  494. When doing spatial queries, GeoDjango automatically transforms
  495. geometries if they're in a different coordinate system. In the following
  496. example, coordinates will be expressed in `EPSG SRID 32140`__,
  497. a coordinate system specific to south Texas **only** and in units of
  498. **meters**, not degrees::
  499. >>> from django.contrib.gis.geos import Point, GEOSGeometry
  500. >>> pnt = Point(954158.1, 4215137.1, srid=32140)
  501. Note that ``pnt`` may also be constructed with EWKT, an "extended" form of
  502. WKT that includes the SRID::
  503. >>> pnt = GEOSGeometry('SRID=32140;POINT(954158.1 4215137.1)')
  504. GeoDjango's ORM will automatically wrap geometry values
  505. in transformation SQL, allowing the developer to work at a higher level
  506. of abstraction::
  507. >>> qs = WorldBorder.objects.filter(mpoly__intersects=pnt)
  508. >>> print(qs.query) # Generating the SQL
  509. SELECT "world_worldborder"."id", "world_worldborder"."name", "world_worldborder"."area",
  510. "world_worldborder"."pop2005", "world_worldborder"."fips", "world_worldborder"."iso2",
  511. "world_worldborder"."iso3", "world_worldborder"."un", "world_worldborder"."region",
  512. "world_worldborder"."subregion", "world_worldborder"."lon", "world_worldborder"."lat",
  513. "world_worldborder"."mpoly" FROM "world_worldborder"
  514. WHERE ST_Intersects("world_worldborder"."mpoly", ST_Transform(%s, 4326))
  515. >>> qs # printing evaluates the queryset
  516. [<WorldBorder: United States>]
  517. __ http://spatialreference.org/ref/epsg/32140/
  518. .. admonition:: Raw queries
  519. When using :doc:`raw queries </topics/db/sql>`, you should generally wrap
  520. your geometry fields with the ``asText()`` SQL function (or ``ST_AsText``
  521. for PostGIS) so that the field value will be recognized by GEOS::
  522. City.objects.raw('SELECT id, name, asText(point) from myapp_city')
  523. This is not absolutely required by PostGIS, but generally you should only
  524. use raw queries when you know exactly what you are doing.
  525. Lazy Geometries
  526. ---------------
  527. GeoDjango loads geometries in a standardized textual representation. When the
  528. geometry field is first accessed, GeoDjango creates a `GEOS geometry object
  529. <ref-geos>`, exposing powerful functionality, such as serialization properties
  530. for popular geospatial formats::
  531. >>> sm = WorldBorder.objects.get(name='San Marino')
  532. >>> sm.mpoly
  533. <MultiPolygon object at 0x24c6798>
  534. >>> sm.mpoly.wkt # WKT
  535. MULTIPOLYGON (((12.4157980000000006 43.9579540000000009, 12.4505540000000003 43.9797209999999978, ...
  536. >>> sm.mpoly.wkb # WKB (as Python binary buffer)
  537. <read-only buffer for 0x1fe2c70, size -1, offset 0 at 0x2564c40>
  538. >>> sm.mpoly.geojson # GeoJSON (requires GDAL)
  539. '{ "type": "MultiPolygon", "coordinates": [ [ [ [ 12.415798, 43.957954 ], [ 12.450554, 43.979721 ], ...
  540. This includes access to all of the advanced geometric operations provided by
  541. the GEOS library::
  542. >>> pnt = Point(12.4604, 43.9420)
  543. >>> sm.mpoly.contains(pnt)
  544. True
  545. >>> pnt.contains(sm.mpoly)
  546. False
  547. Geographic annotations
  548. ----------------------
  549. GeoDjango also offers a set of geographic annotations to compute distances and
  550. several other operations (intersection, difference, etc.). See the
  551. :doc:`functions` documentation.
  552. Putting your data on the map
  553. ============================
  554. Geographic Admin
  555. ----------------
  556. GeoDjango extends :doc:`Django's admin application </ref/contrib/admin/index>`
  557. with support for editing geometry fields.
  558. Basics
  559. ^^^^^^
  560. GeoDjango also supplements the Django admin by allowing users to create
  561. and modify geometries on a JavaScript slippy map (powered by `OpenLayers`_).
  562. Let's dive right in. Create a file called ``admin.py`` inside the
  563. ``world`` application with the following code::
  564. from django.contrib.gis import admin
  565. from models import WorldBorder
  566. admin.site.register(WorldBorder, admin.GeoModelAdmin)
  567. Next, edit your ``urls.py`` in the ``geodjango`` application folder as follows::
  568. from django.conf.urls import url, include
  569. from django.contrib.gis import admin
  570. urlpatterns = [
  571. url(r'^admin/', include(admin.site.urls)),
  572. ]
  573. Create an admin user:
  574. .. code-block:: console
  575. $ python manage.py createsuperuser
  576. Next, start up the Django development server:
  577. .. code-block:: console
  578. $ python manage.py runserver
  579. Finally, browse to ``http://localhost:8000/admin/``, and log in with the user
  580. you just created. Browse to any of the ``WorldBorder`` entries -- the borders
  581. may be edited by clicking on a polygon and dragging the vertexes to the desired
  582. position.
  583. .. _OpenLayers: http://openlayers.org/
  584. .. _Open Street Map: http://www.openstreetmap.org/
  585. .. _Vector Map Level 0: http://earth-info.nga.mil/publications/vmap0.html
  586. .. _OSGeo: http://www.osgeo.org
  587. .. _osmgeoadmin-intro:
  588. ``OSMGeoAdmin``
  589. ^^^^^^^^^^^^^^^
  590. With the :class:`~django.contrib.gis.admin.OSMGeoAdmin`, GeoDjango uses
  591. a `Open Street Map`_ layer in the admin.
  592. This provides more context (including street and thoroughfare details) than
  593. available with the :class:`~django.contrib.gis.admin.GeoModelAdmin`
  594. (which uses the `Vector Map Level 0`_ WMS dataset hosted at `OSGeo`_).
  595. First, there are some important requirements:
  596. * :class:`~django.contrib.gis.admin.OSMGeoAdmin` requires that
  597. :doc:`GDAL <gdal>` is installed. If you are running GDAL 1.6 (uncommon)
  598. you will also need to add the :ref:`spherical mercator projection
  599. <addgoogleprojection>` to the ``spatial_ref_sys`` table.
  600. * The PROJ.4 datum shifting files must be installed (see the
  601. :ref:`PROJ.4 installation instructions <proj4>` for more details).
  602. If you meet this requirement, then just substitute the ``OSMGeoAdmin``
  603. option class in your ``admin.py`` file::
  604. admin.site.register(WorldBorder, admin.OSMGeoAdmin)
  605. .. rubric:: Footnotes
  606. .. [#] Special thanks to Bjørn Sandvik of `thematicmapping.org
  607. <http://thematicmapping.org>`_ for providing and maintaining this
  608. dataset.
  609. .. [#] GeoDjango basic apps was written by Dane Springmeyer, Josh Livni, and
  610. Christopher Schmidt.
  611. .. [#] This point is the `University of Houston Law Center
  612. <http://www.law.uh.edu/>`_.
  613. .. [#] Open Geospatial Consortium, Inc., `OpenGIS Simple Feature Specification
  614. For SQL <http://www.opengeospatial.org/standards/sfs>`_.