Ticket #12930: gis_docs.1.diff

File gis_docs.1.diff, 206.1 KB (added by jbronn, 15 years ago)

Alpha version of the docs.

  • docs/index.txt

     
    168168    * :ref:`Databrowse <ref-contrib-databrowse>`
    169169    * :ref:`E-mail (sending) <topics-email>`
    170170    * :ref:`Flatpages <ref-contrib-flatpages>`
     171    * :ref:`GeoDjango <ref-contrib-gis>`
    171172    * :ref:`Humanize <ref-contrib-humanize>`
    172173    * :ref:`Internationalization <topics-i18n>`
    173174    * :ref:`Jython support <howto-jython>`
  • docs/ref/contrib/gis/create_template_postgis-1.4.sh

     
     1#!/usr/bin/env bash
     2POSTGIS_SQL_PATH=`pg_config --sharedir`/contrib
     3createdb -E UTF8 template_postgis # Create the template spatial database.
     4createlang -d template_postgis plpgsql # Adding PLPGSQL language support.
     5psql -d postgres -c "UPDATE pg_database SET datistemplate='true' WHERE datname='template_postgis';"
     6psql -d template_postgis -f $POSTGIS_SQL_PATH/postgis.sql # Loading the PostGIS SQL routines
     7psql -d template_postgis -f $POSTGIS_SQL_PATH/spatial_ref_sys.sql
     8psql -d template_postgis -c "GRANT ALL ON geometry_columns TO PUBLIC;" # Enabling users to alter spatial tables.
     9psql -d template_postgis -c "GRANT ALL ON spatial_ref_sys TO PUBLIC;"
  • docs/ref/contrib/gis/measure.txt

     
     1=================================================
     2Measurement Units API (``Distance`` and ``Area``)
     3=================================================
     4
     5The `measure module`__ allows for convenient representation of distance and
     6area units of measure. [#]_ The module contains two objects, ``Distance``
     7and ``Area`` -- both of which may be accessed via the ``D`` and ``A`` aliases,
     8respectively.
     9
     10__ http://code.djangoproject.com/browser/django/branches/gis/django/contrib/gis/measure.py
     11
     12The ``Distance`` and ``Area`` Objects
     13=====================================
     14
     15``Distance`` objects may be instantiated using a keyword argument indicating the
     16context of the units.  In the example below, two different distance objects are
     17instantiated in units of kilometers (``km``) and miles (``mi``)::
     18
     19    >>> from django.contrib.gis.measure import Distance, D
     20    >>> d1 = Distance(km=5)
     21    >>> print d1
     22    5.0 km
     23    >>> d2 = D(mi=5) # `D` is an alias for `Distance`
     24    >>> print d2
     25    5.0 mi
     26
     27Conversions are easy, just access the preferred unit attribute name to get a
     28converted distance quantity::
     29
     30   >>> print d1.mi # Converting 5 kilometers to miles
     31   3.10685596119
     32   >>> print d2.km # Converting 5 miles to kilometers
     33   8.04672
     34
     35Moreover, arithmetic operations may be performed between the distance
     36objects::
     37
     38    >>> print d1 + d2 # Adding 5 miles to 5 kilometers
     39    13.04672 km   
     40    >>> print d2 - d1 # Subtracting 5 kilometers from 5 miles
     41    1.89314403881 mi
     42
     43Two ``Distance`` objects multiplied together will yield an ``Area`` object,
     44which uses squared units of measure::
     45
     46    >>> a = d1 * d2 # Returns an Area object.
     47    >>> print a
     48    40.2336 sq_km
     49
     50To determine what the attribute abbreviation of a unit is, the ``unit_attname``
     51class method may be used:
     52
     53    >>> print Distance.unit_attname('US Survey Foot')
     54    survey_ft
     55    >>> print Distance.unit_attname('centimeter')
     56    cm
     57
     58Supported units
     59===============
     60
     61=================================  ========================================
     62Unit Attribute                     Full name or alias(es)
     63=================================  ========================================
     64``km``                             Kilometre, Kilometer   
     65``mi``                             Mile
     66``m``                              Meter, Metre
     67``yd``                             Yard
     68``ft``                             Foot, Foot (International)
     69``survey_ft``                      U.S. Foot, US survey foot
     70``inch``                           Inches
     71``cm``                             Centimeter
     72``mm``                             Millimetre, Millimeter
     73``um``                             Micrometer, Micrometre
     74``british_ft``                     British foot (Sears 1922)
     75``british_yd``                     British yard (Sears 1922)
     76``british_chain_sears``            British chain (Sears 1922)
     77``indian_yd``                      Indian yard, Yard (Indian)
     78``sears_yd``                       Yard (Sears)
     79``clarke_ft``                      Clarke's Foot
     80``chain``                          Chain
     81``chain_benoit``                   Chain (Benoit)
     82``chain_sears``                    Chain (Sears)
     83``british_chain_benoit``           British chain (Benoit 1895 B)
     84``british_chain_sears_truncated``  British chain (Sears 1922 truncated)
     85``gold_coast_ft``                  Gold Coast foot
     86``link``                           Link
     87``link_benoit``                    Link (Benoit)
     88``link_sears``                     Link (Sears)
     89``clarke_link``                    Clarke's link
     90``fathom``                         Fathom
     91``rod``                            Rod
     92``nm``                             Nautical Mile
     93``nm_uk``                          Nautical Mile (UK)
     94``german_m``                       German legal metre
     95=================================  ========================================
     96
     97``Area`` attributes are the same as ``Distance`` attributes, except they are
     98prefixed with ``sq_`` (area units are square in nature).
     99
     100.. rubric:: Footnotes
     101.. [#] `Robert Coup <http://koordinates.com/>`_ is the initial author of the measure objects,
     102       and was inspired by Brian Beck's work in `geopy <http://exogen.case.edu/projects/geopy/>`_
     103       and Geoff Biggs' PhD work on dimensioned units for robotics.
  • docs/ref/contrib/gis/tutorial.txt

     
     1==================
     2GeoDjango Tutorial
     3==================
     4
     5Introduction
     6============
     7
     8GeoDjango is an add-on for Django that turns it into a world-class geographic
     9web framework.  GeoDjango strives to make at as simple as possible to create
     10geographic web applications, like location-based services.  Some features include:
     11
     12* Django model fields for `OGC`_ geometries, that may be edited in the admin.
     13* Extensions to Django's ORM for the querying and manipulation of spatial data.
     14* Loosely-coupled, high-level Python interfaces for GIS geometry operations and
     15  data formats.
     16
     17This tutorial assumes a familiarity with Django; thus, if you're brand new to
     18Django please read through the `regular tutorial`__ to introduce yourself with
     19Django concepts.  GeoDjango has special prerequisites over what is required by Django --
     20please consult the `GeoDjango installation documentation`_ for more details.
     21
     22This tutorial is going to guide you through guide the user through the creation
     23of a geographic web application for viewing the `world borders`_. [#]_  Some of
     24the code used in this tutorial is taken from and/or inspired by the
     25`GeoDjango basic apps`_ project. [#]_
     26
     27.. note:
     28
     29    Proceed through the tutorial sections sequentially for step-by-step
     30    instructions.
     31
     32
     33.. _OGC: http://www.opengeospatial.org/
     34.. _GeoDjango installation documentation: install.html
     35.. _world borders: http://thematicmapping.org/downloads/world_borders.php
     36.. _GeoDjango basic apps: http://code.google.com/p/geodjango-basic-apps/
     37
     38__ http://docs.djangoproject.com/en/dev/intro/tutorial01/#intro-tutorial01
     39
     40Setting Up
     41==========
     42
     43Create a Spatial Database
     44-------------------------
     45
     46.. note::
     47
     48    MySQL and Oracle users can skip this section because spatial types
     49    are already built into the database.
     50
     51First, a spatial database needs to be created for our project.  If using
     52PostgreSQL and PostGIS, then the following commands will
     53create the database from a `spatial database template`_::
     54
     55    $ createdb -T template_postgis geodjango
     56   
     57.. note::
     58
     59    This command must be issued by a database user that has permissions to
     60    create a database.  Here is an example set of commands to create such
     61    a user::
     62
     63        $ sudo su - postgres
     64        $ createuser --createdb geo
     65        $ exit
     66   
     67    Replace ``geo`` to correspond to the system login user name will be
     68    connecting to the database.  For example, ``johndoe`` if that is the
     69    system user that will be running GeoDjango.
     70
     71Users of SQLite and SpatiaLite should consult the instructions on how
     72to create a `SpatiaLite database`_.
     73
     74.. _spatial database template: install.html#spatialdb-template
     75.. _spatialite database: install.html#creating-a-spatial-database-for-spatialite
     76
     77Create GeoDjango Project
     78------------------------
     79
     80Use the ``django-admin.py`` script like normal to create a ``geodjango`` project::
     81
     82    $ django-admin.py startproject geodjango
     83
     84With the project initialized, now create a ``world`` Django application within
     85the ``geodjango`` project::
     86
     87    $ cd geodjango
     88    $ python manage.py startapp world
     89
     90Configure ``settings.py``
     91-------------------------
     92
     93The ``geodjango`` project settings are stored in the ``settings.py`` file.  Edit
     94the database connection settings appropriately::
     95
     96    DATABASE_ENGINE = 'postgresql_psycopg2'
     97    DATABASE_NAME = 'geodjango'
     98    DATABASE_USER = 'geo'
     99
     100In addition, modify the ``INSTALLED_APPS`` setting to include ``django.contrib.admin``,
     101``django.contrib.gis``, and ``geodjango.world`` (our newly created application)::
     102
     103    INSTALLED_APPS = (
     104        'django.contrib.auth',
     105        'django.contrib.contenttypes',
     106        'django.contrib.sessions',
     107        'django.contrib.sites',
     108        'django.contrib.admin',
     109        'django.contrib.gis',
     110        'geodjango.world'
     111    )
     112
     113Geographic Data
     114===============
     115
     116
     117.. _worldborders:
     118
     119World Borders
     120-------------
     121
     122The world borders data is available in this `zip file`__.  Create a data directory
     123in the ``world`` application, download the world borders data, and unzip::
     124
     125    $ mkdir world/data
     126    $ cd world/data
     127    $ wget http://thematicmapping.org/downloads/TM_WORLD_BORDERS-0.3.zip
     128    $ unzip TM_WORLD_BORDERS-0.3.zip
     129    $ cd ../..
     130
     131The world borders ZIP file contains a set of data files collectively known as
     132an `ESRI Shapefile`__, one of the most popular geospatial data formats.  When
     133unzipped the world borders data set includes files with the following extensions:
     134
     135* ``.shp``: Holds the vector data for the world borders geometries.
     136* ``.shx``: Spatial index file for geometries stored in the ``.shp``.
     137* ``.dbf``: Database file for holding non-geometric attribute data
     138  (e.g., integer and character fields).
     139* ``.prj``: Contains the spatial reference information for the geographic
     140  data stored in the shapefile.
     141
     142__ http://thematicmapping.org/downloads/TM_WORLD_BORDERS-0.3.zip
     143__ http://en.wikipedia.org/wiki/Shapefile
     144
     145Use ``ogrinfo`` to examine spatial data
     146---------------------------------------
     147
     148The GDAL ``ogrinfo`` utility is excellent for examining metadata about
     149shapefiles (or other vector data sources)::
     150
     151    $ ogrinfo world/data/TM_WORLD_BORDERS-0.3.shp
     152    INFO: Open of `world/data/TM_WORLD_BORDERS-0.3.shp'
     153          using driver `ESRI Shapefile' successful.
     154    1: TM_WORLD_BORDERS-0.3 (Polygon)
     155
     156Here ``ogrinfo`` is telling us that the shapefile has one layer, and that
     157layer contains polygon data.  To find out more we'll specify the layer name
     158and use the ``-so`` option to get only important summary information::
     159
     160    $ ogrinfo -so world/data/TM_WORLD_BORDERS-0.3.shp TM_WORLD_BORDERS-0.3
     161    INFO: Open of `world/data/TM_WORLD_BORDERS-0.3.shp'
     162          using driver `ESRI Shapefile' successful.
     163
     164    Layer name: TM_WORLD_BORDERS-0.3
     165    Geometry: Polygon
     166    Feature Count: 246
     167    Extent: (-180.000000, -90.000000) - (180.000000, 83.623596)
     168    Layer SRS WKT:
     169    GEOGCS["GCS_WGS_1984",
     170        DATUM["WGS_1984",
     171            SPHEROID["WGS_1984",6378137.0,298.257223563]],
     172        PRIMEM["Greenwich",0.0],
     173        UNIT["Degree",0.0174532925199433]]
     174    FIPS: String (2.0)
     175    ISO2: String (2.0)
     176    ISO3: String (3.0)
     177    UN: Integer (3.0)
     178    NAME: String (50.0)
     179    AREA: Integer (7.0)
     180    POP2005: Integer (10.0)
     181    REGION: Integer (3.0)
     182    SUBREGION: Integer (3.0)
     183    LON: Real (8.3)
     184    LAT: Real (7.3)
     185
     186This detailed summary information tells us the number of features in the layer
     187(246), the geographical extent, the spatial reference system ("SRS WKT"),
     188as well as detailed information for each attribute field.  For example,
     189``FIPS: String (2.0)`` indicates that there's a ``FIPS`` character field
     190with a maximum length of 2; similarly, ``LON: Real (8.3)`` is a floating-point
     191field that holds a maximum of 8 digits up to three decimal places.  Although
     192this information may be found right on the `world borders`_ website, this shows
     193you how to determine this information yourself when such metadata is not
     194provided.
     195
     196Geographic Models
     197=================
     198
     199Defining a Geographic Model
     200---------------------------
     201
     202Now that we've examined our world borders data set using ``ogrinfo``, we can
     203create a GeoDjango model to represent this data::
     204
     205    from django.contrib.gis.db import models
     206
     207    class WorldBorders(models.Model):
     208        # Regular Django fields corresponding to the attributes in the
     209        # world borders shapefile.
     210        name = models.CharField(max_length=50)
     211        area = models.IntegerField()
     212        pop2005 = models.IntegerField('Population 2005')
     213        fips = models.CharField('FIPS Code', max_length=2)
     214        iso2 = models.CharField('2 Digit ISO', max_length=2)
     215        iso3 = models.CharField('3 Digit ISO', max_length=3)
     216        un = models.IntegerField('United Nations Code')
     217        region = models.IntegerField('Region Code')
     218        subregion = models.IntegerField('Sub-Region Code')
     219        lon = models.FloatField()
     220        lat = models.FloatField()
     221
     222        # GeoDjango-specific: a geometry field (MultiPolygonField), and
     223        # overriding the default manager with a GeoManager instance.
     224        mpoly = models.MultiPolygonField()
     225        objects = models.GeoManager()
     226
     227        # So the model is pluralized correctly in the admin.
     228        class Meta:
     229            verbose_name_plural = "World Borders"
     230 
     231        # Returns the string representation of the model.       
     232        def __unicode__(self):
     233            return self.name
     234
     235Two important things to note:
     236
     2371. The ``models`` module is imported from ``django.contrib.gis.db``.
     2382. The model overrides its default manager with ``GeoManager``; this is *required*
     239   to perform spatial queries. 
     240
     241When declaring a geometry field on your model the default spatial reference system
     242is WGS84 (meaning the `SRID`__ is 4326) -- in other words, the field coordinates are in
     243longitude/latitude pairs in units of degrees.  If you want the coordinate system to be
     244different, then SRID of the geometry field may be customized by setting the ``srid``
     245with an integer corresponding to the coordinate system of your choice.
     246
     247__ http://en.wikipedia.org/wiki/SRID
     248
     249Run ``syncdb``
     250--------------
     251
     252After you've defined your model, it needs to be synced with the spatial database.
     253First, let's look at the SQL that will generate the table for the ``WorldBorders``
     254model::
     255
     256    $ python manage.py sqlall world
     257
     258This management command should produce the following output::
     259
     260    BEGIN;
     261    CREATE TABLE "world_worldborders" (
     262        "id" serial NOT NULL PRIMARY KEY,
     263        "name" varchar(50) NOT NULL,
     264        "area" integer NOT NULL,
     265        "pop2005" integer NOT NULL,
     266        "fips" varchar(2) NOT NULL,
     267        "iso2" varchar(2) NOT NULL,
     268        "iso3" varchar(3) NOT NULL,
     269        "un" integer NOT NULL,
     270        "region" integer NOT NULL,
     271        "subregion" integer NOT NULL,
     272        "lon" double precision NOT NULL,
     273        "lat" double precision NOT NULL
     274    )
     275    ;
     276    SELECT AddGeometryColumn('world_worldborders', 'mpoly', 4326, 'MULTIPOLYGON', 2);
     277    ALTER TABLE "world_worldborders" ALTER "mpoly" SET NOT NULL;
     278    CREATE INDEX "world_worldborders_mpoly_id" ON "world_worldborders" USING GIST ( "mpoly" GIST_GEOMETRY_OPS );
     279    COMMIT;
     280
     281If satisfied, you may then create this table in the database by running the
     282``syncdb`` management command::
     283
     284    $ python manage.py syncdb
     285    Creating table world_worldborders
     286    Installing custom SQL for world.WorldBorders model
     287
     288The ``syncdb`` command may also prompt you to create an admin user; go ahead and
     289do so (not required now, may be done at any point in the future using the
     290``createsuperuser`` management command).
     291
     292Importing Spatial Data
     293======================
     294
     295This section will show you how to take the data from the world borders
     296shapefile and import it into GeoDjango models using the `LayerMapping`_
     297utility.  There are many different different ways to import data in to a
     298spatial database -- besides the tools included within GeoDjango, you
     299may also use the following to populate your spatial database:
     300
     301* `ogr2ogr`_: Command-line utility, included with GDAL, that
     302  supports loading a multitude of vector data formats into
     303  the PostGIS, MySQL, and Oracle spatial databases.
     304* `shp2pgsql`_: This utility is included with PostGIS and only supports
     305  ESRI shapefiles.
     306
     307.. _LayerMapping: layermapping.html
     308.. _ogr2ogr: http://www.gdal.org/ogr/ogr2ogr.html
     309.. _shp2pgsql: http://postgis.refractions.net/documentation/manual-1.3/ch04.html#id2571948
     310
     311.. _gdalinterface:
     312
     313GDAL Interface
     314--------------
     315
     316Earlier we used the the ``ogrinfo`` to explore the contents of the world borders
     317shapefile.  Included within GeoDjango is an interface to GDAL's powerful OGR
     318library -- in other words, you'll be able explore all the vector data sources
     319that OGR supports via a Pythonic API.
     320
     321First, invoke the Django shell::
     322
     323    $ python manage.py shell
     324
     325If the :ref:`worldborders` data was downloaded like earlier in the
     326tutorial, then we can determine the path using Python's built-in
     327``os`` module::
     328
     329    >>> import os
     330    >>> from geodjango import world
     331    >>> world_shp = os.path.abspath(os.path.join(os.path.dirname(world.__file__),
     332    ...                             'data/TM_WORLD_BORDERS-0.3.shp'))
     333
     334Now, the world borders shapefile may be opened using GeoDjango's
     335``DataSource`` interface::
     336
     337    >>> from django.contrib.gis.gdal import *
     338    >>> ds = DataSource(world_shp)
     339    >>> print ds
     340    / ... /geodjango/world/data/TM_WORLD_BORDERS-0.3.shp (ESRI Shapefile)
     341
     342Data source objects can have different layers of geospatial features; however,
     343shapefiles are only allowed to have one layer::
     344
     345    >>> print len(ds)
     346    1
     347    >>> lyr = ds[0]
     348    >>> print lyr
     349    TM_WORLD_BORDERS-0.3
     350
     351You can see what the geometry type of the layer is and how many features it
     352contains::
     353
     354    >>> print lyr.geom_type
     355    Polygon
     356    >>> print len(lyr)
     357    246
     358
     359.. note::
     360
     361    Unfortunately the shapefile data format does not allow for greater
     362    specificity with regards to geometry types.  This shapefile, like
     363    many others, actually includes ``MultiPolygon`` geometries in its
     364    features.  You need to watch out for this when creating your models
     365    as a GeoDjango ``PolygonField`` will not accept a ``MultiPolygon``
     366    type geometry -- thus a ``MultiPolygonField`` is used in our model's
     367    definition instead.
     368
     369The ``Layer`` may also have a spatial reference system associated with
     370it -- if it does, the ``srs`` attribute will return a ``SpatialReference``
     371object::
     372
     373    >>> srs = lyr.srs
     374    >>> print srs
     375    GEOGCS["GCS_WGS_1984",
     376        DATUM["WGS_1984",
     377            SPHEROID["WGS_1984",6378137.0,298.257223563]],
     378        PRIMEM["Greenwich",0.0],
     379        UNIT["Degree",0.0174532925199433]]
     380    >>> srs.proj4 # PROJ.4 representation
     381    '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs '
     382
     383Here we've noticed that the shapefile is in the popular WGS84 spatial reference
     384system -- in other words, the data uses units of degrees longitude and latitude.
     385
     386In addition, shapefiles also support attribute fields that may contain
     387additional data.  Here are the fields on the World Borders layer:
     388
     389    >>> print lyr.fields
     390    ['FIPS', 'ISO2', 'ISO3', 'UN', 'NAME', 'AREA', 'POP2005', 'REGION', 'SUBREGION', 'LON', 'LAT']
     391
     392Here we are examining the OGR types (e.g., whether a field is an integer or
     393a string) associated with each of the fields:
     394
     395    >>> [fld.__name__ for fld in lyr.field_types]
     396    ['OFTString', 'OFTString', 'OFTString', 'OFTInteger', 'OFTString', 'OFTInteger', 'OFTInteger', 'OFTInteger', 'OFTInteger', 'OFTReal', 'OFTReal']
     397
     398You can iterate over each feature in the layer and extract information from both
     399the feature's geometry (accessed via the ``geom`` attribute) as well as the
     400feature's attribute fields (whose **values** are accessed via ``get()``
     401method)::
     402
     403    >>> for feat in lyr:
     404    ...    print feat.get('NAME'), feat.geom.num_points
     405    ...
     406    Guernsey 18
     407    Jersey 26
     408    South Georgia South Sandwich Islands 338
     409    Taiwan 363
     410
     411``Layer`` objects may be sliced::
     412
     413    >>> lyr[0:2]
     414    [<django.contrib.gis.gdal.feature.Feature object at 0x2f47690>, <django.contrib.gis.gdal.feature.Feature object at 0x2f47650>]
     415
     416And individual features may be retrieved by their feature ID::
     417
     418    >>> feat = lyr[234]
     419    >>> print feat.get('NAME')
     420    San Marino
     421
     422Here the boundary geometry for San Marino is extracted and looking
     423exported to WKT and GeoJSON::
     424
     425    >>> geom = feat.geom
     426    >>> print geom.wkt
     427    POLYGON ((12.415798 43.957954,12.450554 ...
     428    >>> print geom.json
     429    { "type": "Polygon", "coordinates": [ [ [ 12.415798, 43.957954 ], [ 12.450554, 43.979721 ], ...
     430
     431
     432``LayerMapping``
     433----------------
     434
     435We're going to dive right in -- create a file called ``load.py`` inside the
     436``world`` application, and insert the following::
     437
     438    import os
     439    from django.contrib.gis.utils import LayerMapping
     440    from models import WorldBorders
     441
     442    world_mapping = {
     443        'fips' : 'FIPS',
     444        'iso2' : 'ISO2',
     445        'iso3' : 'ISO3',
     446        'un' : 'UN',
     447        'name' : 'NAME',
     448        'area' : 'AREA',
     449        'pop2005' : 'POP2005',
     450        'region' : 'REGION',
     451        'subregion' : 'SUBREGION',
     452        'lon' : 'LON',
     453        'lat' : 'LAT',
     454        'mpoly' : 'MULTIPOLYGON',
     455    }
     456
     457    world_shp = os.path.abspath(os.path.join(os.path.dirname(__file__), 'data/TM_WORLD_BORDERS-0.3.shp'))
     458
     459    def run(verbose=True):
     460        lm = LayerMapping(WorldBorders, world_shp, world_mapping,
     461                          transform=False, encoding='iso-8859-1')
     462
     463        lm.save(strict=True, verbose=verbose)
     464
     465A few notes about what's going on:
     466
     467* Each key in the ``world_mapping`` dictionary corresponds to a field in the
     468  ``WorldBorders`` model, and the value is the name of the shapefile field
     469  that data will be loaded from.
     470* The key ``mpoly`` for the geometry field is ``MULTIPOLYGON``, the
     471  geometry type we wish to import as.  Even if simple polygons are encountered
     472  in the shapefile they will automatically be converted into collections prior
     473  to insertion into the database.
     474* The path to the shapefile is not absolute -- in other words, if you move the
     475  ``world`` application (with ``data`` subdirectory) to a different location,
     476  then the script will still work.
     477* The ``transform`` keyword is set to ``False`` because the data in the
     478  shapefile does not need to be converted -- it's already in WGS84 (SRID=4326).
     479* The ``encoding`` keyword is set to the character encoding of string values in
     480  the shapefile. This ensures that string values are read and saved correctly
     481  from their original encoding system.
     482
     483Afterwards, invoke the Django shell from the ``geodjango`` project directory::
     484
     485   $ python manage.py shell
     486
     487Next, import the ``load`` module, call the ``run`` routine, and watch ``LayerMapping``
     488do the work::
     489
     490   >>> from world import load
     491   >>> load.run()
     492
     493
     494Try ``ogrinspect``
     495------------------
     496Now that you've seen how to define geographic models and import data with the
     497``LayerMapping`` utility, it's possible to further automate this process with
     498use of the ``ogrinspect`` management command.  The ``ogrinspect`` command
     499introspects a GDAL-supported vector data source (e.g., a shapefile) and
     500generates a model definition and ``LayerMapping`` dictionary automatically.
     501
     502The general usage of the command goes as follows::
     503
     504    $ python manage.py ogrinspect <data_source> <model_name> [options]
     505
     506Where ``data_source`` is the path to the GDAL-supported data source and
     507``model_name`` is the name to use for the model.  Command-line options may
     508be used to further define how the model is generated.
     509
     510For example, the following command nearly reproduces the ``WorldBorders`` model
     511and mapping dictionary created above, automatically::
     512
     513    $ python manage.py ogrinspect world/data/TM_WORLD_BORDERS-0.3.shp WorldBorders --srid=4326 --mapping --multi
     514
     515A few notes about the command-line options given above:
     516
     517* The ``--srid=4326`` option sets the SRID for the geographic field.
     518* The ``--mapping`` option tells ``ogrinspect`` to also generate a
     519  mapping dictionary for use with ``LayerMapping``.
     520* The ``--multi`` option is specified so that the geographic field is a
     521  ``MultiPolygonField`` instead of just a ``PolygonField``.
     522
     523The command produces the following output, which may be copied
     524directly into the ``models.py`` of a GeoDjango application::
     525
     526    # This is an auto-generated Django model module created by ogrinspect.
     527    from django.contrib.gis.db import models
     528
     529    class WorldBorders(models.Model):
     530        fips = models.CharField(max_length=2)
     531        iso2 = models.CharField(max_length=2)
     532        iso3 = models.CharField(max_length=3)
     533        un = models.IntegerField()
     534        name = models.CharField(max_length=50)
     535        area = models.IntegerField()
     536        pop2005 = models.IntegerField()
     537        region = models.IntegerField()
     538        subregion = models.IntegerField()
     539        lon = models.FloatField()
     540        lat = models.FloatField()
     541        geom = models.MultiPolygonField(srid=4326)
     542        objects = models.GeoManager()
     543
     544    # Auto-generated `LayerMapping` dictionary for WorldBorders model
     545    worldborders_mapping = {
     546        'fips' : 'FIPS',
     547        'iso2' : 'ISO2',
     548        'iso3' : 'ISO3',
     549        'un' : 'UN',
     550        'name' : 'NAME',
     551        'area' : 'AREA',
     552        'pop2005' : 'POP2005',
     553        'region' : 'REGION',
     554        'subregion' : 'SUBREGION',
     555        'lon' : 'LON',
     556        'lat' : 'LAT',
     557        'geom' : 'MULTIPOLYGON',
     558    }
     559
     560Spatial Queries
     561===============
     562
     563Spatial Lookups
     564---------------
     565GeoDjango extends the Django ORM and allows the use of spatial lookups.
     566Let's do an example where we find the ``WorldBorder`` model that contains
     567a point.  First, fire up the management shell::
     568
     569    $ python manage.py shell
     570
     571Now, define a point of interest [#]_::
     572
     573    >>> pnt_wkt = 'POINT(-95.3385 29.7245)'
     574
     575The ``pnt_wkt`` string represents the point at -95.3385 degrees longitude,
     576and 29.7245 degrees latitude.  The geometry is in a format known as
     577Well Known Text (WKT), an open standard issued by the Open Geospatial
     578Consortium (OGC). [#]_  Import the ``WorldBorders`` model, and perform
     579a ``contains`` lookup using the ``pnt_wkt`` as the parameter::
     580
     581    >>> from world.models import WorldBorders
     582    >>> qs = WorldBorders.objects.filter(mpoly__contains=pnt_wkt)
     583    >>> qs
     584    [<WorldBorders: United States>]
     585
     586Here we retrieved a ``GeoQuerySet`` that has only one model: the one
     587for the United States (which is what we would expect).  Similarly,
     588a `GEOS geometry object`_ may also be used -- here the ``intersects``
     589spatial lookup is combined with the ``get`` method to retrieve
     590only the ``WorldBorders`` instance for San Marino instead of a queryset::
     591
     592    >>> from django.contrib.gis.geos import Point
     593    >>> pnt = Point(12.4604, 43.9420)
     594    >>> sm = WorldBorders.objects.get(mpoly__intersects=pnt)
     595    >>> sm
     596    <WorldBorders: San Marino>
     597
     598The ``contains`` and ``intersects`` lookups are just a subset of what's
     599available -- the `GeoDjango Database API`_ documentation has more.
     600
     601.. _GEOS geometry object: geos.html
     602.. _GeoDjango Database API: db-api.html
     603
     604Automatic Spatial Transformations
     605---------------------------------
     606When querying the spatial database GeoDjango automatically transforms
     607geometries if they're in a different coordinate system.  In the following
     608example, the coordinate will be expressed in terms of `EPSG SRID 32140`__,
     609a coordinate system specific to south Texas **only** and in units of
     610**meters** and not degrees::
     611
     612    >>> from django.contrib.gis.geos import *
     613    >>> pnt = Point(954158.1, 4215137.1, srid=32140)
     614
     615Note that ``pnt`` may also constructed with EWKT, an "extended" form of
     616WKT that includes the SRID::
     617
     618    >>> pnt = GEOSGeometry('SRID=32140;POINT(954158.1 4215137.1)')
     619
     620When using GeoDjango's ORM, it will automatically wrap geometry values
     621in transformation SQL, allowing the developer to work at a higher level
     622of abstraction::
     623
     624    >>> qs = WorldBorders.objects.filter(mpoly__intersects=pnt)
     625    >>> qs.query.as_sql() # Generating the SQL
     626    ('SELECT "world_worldborders"."id", "world_worldborders"."name", "world_worldborders"."area",
     627    "world_worldborders"."pop2005", "world_worldborders"."fips", "world_worldborders"."iso2",
     628    "world_worldborders"."iso3", "world_worldborders"."un", "world_worldborders"."region",
     629    "world_worldborders"."subregion", "world_worldborders"."lon", "world_worldborders"."lat",
     630    "world_worldborders"."mpoly" FROM "world_worldborders"
     631    WHERE ST_Intersects("world_worldborders"."mpoly", ST_Transform(%s, 4326))',
     632    (<django.contrib.gis.db.backend.postgis.adaptor.PostGISAdaptor object at 0x25641b0>,))
     633    >>> qs # printing evaluates the queryset
     634    [<WorldBorders: United States>]   
     635
     636__ http://spatialreference.org/ref/epsg/32140/
     637
     638Lazy Geometries
     639---------------
     640Geometries come to GeoDjango in a standardized textual representation.  Upon
     641access of the geometry field, GeoDjango creates a `GEOS geometry object`_,
     642exposing powerful functionality, such as serialization properties for
     643popular geospatial formats::
     644
     645    >>> sm = WorldBorders.objects.get(name='San Marino')
     646    >>> sm.mpoly
     647    <MultiPolygon object at 0x24c6798>
     648    >>> sm.mpoly.wkt # WKT
     649    MULTIPOLYGON (((12.4157980000000006 43.9579540000000009, 12.4505540000000003 43.9797209999999978, ...
     650    >>> sm.mpoly.wkb # WKB (as Python binary buffer)
     651    <read-only buffer for 0x1fe2c70, size -1, offset 0 at 0x2564c40>
     652    >>> sm.mpoly.geojson # GeoJSON (requires GDAL)
     653    '{ "type": "MultiPolygon", "coordinates": [ [ [ [ 12.415798, 43.957954 ], [ 12.450554, 43.979721 ], ...
     654
     655This includes access to all of the advanced geometric operations provided by
     656the GEOS library::
     657
     658    >>> pnt = Point(12.4604, 43.9420)
     659    >>> sm.mpoly.contains(pnt)
     660    True
     661    >>> pnt.contains(sm.mpoly)
     662    False
     663
     664``GeoQuerySet`` Methods
     665-----------------------
     666
     667
     668Putting your data on the map
     669============================
     670
     671Google
     672------
     673
     674Geographic Admin
     675----------------
     676
     677Basics
     678^^^^^^
     679
     680GeoDjango also supplements the Django admin by allowing users to create
     681and modify geometries on a JavaScript slippy map (powered by `OpenLayers`_).
     682
     683Let's dive in again -- create a file called ``admin.py`` inside the
     684``world`` application, and insert the following::
     685
     686    from django.contrib.gis import admin
     687    from models import WorldBorders
     688
     689    admin.site.register(WorldBorders, admin.GeoModelAdmin)
     690
     691Next, edit your ``urls.py`` in the ``geodjango`` project folder to look
     692as follows::
     693
     694    from django.conf.urls.defaults import *
     695    from django.contrib.gis import admin
     696
     697    admin.autodiscover()
     698
     699    urlpatterns = patterns('',
     700                           (r'^admin/(.*)', admin.site.root),
     701                           )
     702
     703Start up the Django development server::
     704
     705    $ python manage.py runserver
     706
     707Finally, browse to ``http://localhost:8000/admin/``, and log in with the admin
     708user created after running ``syncdb``.  Browse to any of the ``WorldBorders``
     709entries -- the borders may be edited by clicking on a polygon and dragging
     710the vertexes to the desired position.
     711
     712.. _OpenLayers: http://openlayers.org/
     713.. _spherical mercator projection be added: install.html#addgoogleprojection
     714.. _PROJ.4 installation instructions: install.html#proj4
     715.. _Open Street Map: http://openstreetmap.org/
     716.. _Vector Map Level 0: http://earth-info.nga.mil/publications/vmap0.html
     717.. _Metacarta: http://metacarta.com
     718
     719``OSMGeoAdmin``
     720^^^^^^^^^^^^^^^
     721
     722With the ``OSMGeoAdmin``, GeoDjango uses a `Open Street Map`_ layer in the admin.
     723This provides more context (including street and thoroughfare details) than
     724available with the ``GeoModelAdmin`` (which uses the `Vector Map Level 0`_
     725WMS data set hosted at `Metacarta`_).
     726
     727First, there are some important requirements and limitations:
     728
     729* The ``OSMGeoAdmin`` requires that the `spherical mercator projection be added`_
     730  to the to be added to the PostGIS ``spatial_ref_sys`` table.
     731* ``OSMGeoAdmin`` does not work with MySQL and Oracle spatial backends at
     732  this time.
     733* The PROJ.4 datum shifting files must be installed (see the
     734  `PROJ.4 installation instructions`_ for more details).
     735
     736If you meet these requirements, then just substitute in the ``OSMGeoAdmin``
     737option class in your ``admin.py`` file::
     738
     739    admin.site.register(WorldBorders, admin.OSMGeoAdmin)
     740
     741.. rubric:: Footnotes
     742
     743.. [#] Special thanks to Bjørn Sandvik of `thematicmapping.org <http://thematicmapping.org>`_ for providing and maintaining this data set.
     744.. [#] GeoDjango basic apps was written by Dane Springmeyer, Josh Livni, and Christopher Schmidt.
     745.. [#] Here the point is for the `University of Houston Law Center <http://www.law.uh.edu/>`_ .
     746.. [#] Open Geospatial Consortium, Inc., `OpenGIS Simple Feature Specification For SQL <http://www.opengis.org/docs/99-049.pdf>`_, Document 99-049.
  • docs/ref/contrib/gis/geoip.txt

     
     1==============================
     2GeoIP API
     3==============================
     4
     5The ``GeoIP`` object is a ctypes wrapper for the
     6`MaxMind GeoIP C API`__. [#]_  This interface is a BSD-licensed alternative
     7to the GPL-licensed `Python GeoIP`__ interface provided by MaxMind.
     8
     9In order to perform IP-based geolocation, the ``GeoIP`` object requires
     10the GeoIP C libary and either the GeoIP `Country`__ or `City`__
     11datasets in binary format (the CSV files will not work!).  These datasets may be
     12`downloaded from MaxMind`__.  Grab the ``GeoIP.dat.gz`` and ``GeoLiteCity.dat.gz``
     13and unzip them in a directory corresponding to what you set
     14``GEOIP_PATH`` with in your settings.  See the example and reference below
     15for more details.
     16
     17__ http://www.maxmind.com/app/c
     18__ http://www.maxmind.com/app/python
     19__ http://www.maxmind.com/app/country
     20__ http://www.maxmind.com/app/city
     21__ http://www.maxmind.com/download/geoip/database/
     22
     23Example
     24===========================
     25
     26Assuming you have the GeoIP C library installed, here is an example of its
     27usage::
     28
     29     >>> from django.contrib.gis.utils import GeoIP
     30     >>> g = GeoIP()
     31     >>> g.country('google.com')
     32     {'country_code': 'US', 'country_name': 'United States'}
     33     >>> g.city('72.14.207.99')
     34     {'area_code': 650,
     35     'city': 'Mountain View',
     36     'country_code': 'US',
     37     'country_code3': 'USA',
     38     'country_name': 'United States',
     39     'dma_code': 807,
     40     'latitude': 37.419200897216797,
     41     'longitude': -122.05740356445312,
     42     'postal_code': '94043',
     43     'region': 'CA'}
     44     >>> g.lat_lon('salon.com')
     45     (37.789798736572266, -122.39420318603516)
     46     >>> g.lon_lat('uh.edu')
     47     (-95.415199279785156, 29.77549934387207)
     48     >>> g.geos('24.124.1.80').wkt
     49     'POINT (-95.2087020874023438 39.0392990112304688)'
     50
     51Initialization
     52==============================
     53
     54The ``GeoIP`` object does not require any parameters to use the default
     55settings.  However, at the very least the ``GEOIP_PATH`` setting should
     56be set with the path of the location of your GeoIP data sets.  The
     57following intialization keywords may be used to customize any of the
     58defaults.
     59
     60    ===================  ======================================================
     61    Keyword Arguments    Description
     62    ===================  ======================================================
     63    ``path``             Base directory to where GeoIP data is located or the
     64                         full path to where the city or country data files
     65                         (.dat) are located.  Assumes that both the city and
     66                         country data sets are located in this directory;
     67                         overrides the ``GEOIP_PATH`` settings attribute.
     68
     69    ``cache``            The cache settings when opening up the GeoIP datasets,
     70                         and may be an integer in (0, 1, 2, 4) corresponding to
     71                         the ``GEOIP_STANDARD``, ``GEOIP_MEMORY_CACHE``,
     72                         ``GEOIP_CHECK_CACHE``, and ``GEOIP_INDEX_CACHE``
     73                         ``GeoIPOptions`` C API settings, respectively.
     74                         Defaults to 0 (``GEOIP_STANDARD``) -- see the cache
     75                         settings table below for more details.
     76 
     77    ``country``          The name of the GeoIP country data file.  Defaults
     78                         to ``GeoIP.dat``.  Setting this keyword overrides the
     79                         ``GEOIP_COUNTRY`` settings attribute.
     80
     81    ``city``             The name of the GeoIP city data file.  Defaults to
     82                         ``GeoLiteCity.dat``.  Setting this keyword overrides
     83                         the ``GEOIP_CITY`` settings attribute.
     84    ===================  ======================================================
     85
     86``GeoIP`` Methods
     87==========================
     88
     89Querying
     90--------------------------
     91
     92All the following querying routines may take either a string IP address
     93or a fully qualified domain name (FQDN).  For example, both
     94``'24.124.1.80'`` and ``'djangoproject.com'`` would be valid query
     95parameters.
     96
     97``city(query)``
     98^^^^^^^^^^^^^^^^^^^^^^^^^^
     99Returns a dictionary of city information for the given query.  Some
     100of the values in the dictionary may be undefined (``None``).
     101
     102``country(query)``
     103^^^^^^^^^^^^^^^^^^^^^^^^^^
     104Returns a dictionary with the country code and country for the given
     105query.
     106
     107``country_code(query)``
     108^^^^^^^^^^^^^^^^^^^^^^^^^^
     109
     110``country_name(query)``
     111^^^^^^^^^^^^^^^^^^^^^^^^^^
     112
     113Coordinate Retrieval
     114--------------------------
     115
     116``coords(query)``
     117^^^^^^^^^^^^^^^^^^^^^^^^^^
     118
     119``lon_lat(query)``
     120^^^^^^^^^^^^^^^^^^^^^^^^^^
     121
     122``lat_lon(query)``
     123^^^^^^^^^^^^^^^^^^^^^^^^^^
     124
     125``geos(query)``
     126^^^^^^^^^^^^^^^^^^^^^^^^^^
     127
     128GeoIP Database Information
     129---------------------------
     130
     131``country_info``
     132^^^^^^^^^^^^^^^^^^^^^^^^^^^
     133This property returns information about the GeoIP country database.
     134
     135``city_info``
     136^^^^^^^^^^^^^^^^^^^^^^^^^^^
     137This property returns information about the GeoIP city database.
     138
     139``info``
     140^^^^^^^^^^^^^^^^^^^^^^^^^^^
     141This property returns information about all GeoIP databases (both city
     142and country).
     143
     144GeoIP-Python API compatibility methods
     145----------------------------------------
     146
     147[explanation]
     148
     149``open(path, cache)``
     150^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     151This classmethod instantiates the GeoIP object from the given database path
     152and given cache setting.
     153
     154``regioin_by_addr(query)``
     155^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     156
     157``region_by_name(query)``
     158^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     159
     160``record_by_addr(query)``
     161^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     162
     163``record_by_name(query)``
     164^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     165
     166``country_code_by_addr(query)``
     167^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     168
     169``country_code_by_name(query)``
     170^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     171
     172``country_name_by_addr(query)``
     173^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     174
     175``country_name_by_name(query)``
     176^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     177
     178.. rubric:: Footnotes
     179.. [#] GeoIP(R) is a registered trademark of MaxMind, LLC of Boston, Massachusetts.
  • docs/ref/contrib/gis/install.txt

     
     1.. _ref-gis-install:
     2
     3======================
     4GeoDjango Installation
     5======================
     6
     7Overview
     8========
     9In general, GeoDjango installation requires:
     10
     111. :ref:`python24` and :ref:`django`
     122. :ref:`spatial_database`
     133. :ref:`geospatial_libs`
     14
     15Details for each of the requirements and installation instructions
     16are provided in the sections below.   In addition, platform-specific
     17instructions are available for:
     18
     19* :ref:`macosx`
     20* :ref:`ubuntudebian`
     21* :ref:`windows`
     22
     23.. admonition:: Use the Source
     24
     25    Because GeoDjango takes advantage of the latest in the open source geospatial
     26    software technology, recent versions of the libraries are necessary. 
     27    Unfortunately, binary packages are not available on many GNU/Linux systems
     28    (GEOS 3, in particular).  Thus, `installation from source`_ may be required.
     29    When compiling the libraries from source, please follow the directions closely,
     30    especially if you're a beginner.
     31
     32.. _installation from source: install.html#building-from-source
     33
     34Requirements
     35============
     36
     37.. _python24:
     38
     39Python 2.4+
     40-----------
     41Because of heavy use of the decorator syntax, Python 2.4 is minimum
     42version supported by GeoDjango. Python 2.5+ is recommended because the
     43`ctypes`__ module comes included; otherwise, 2.4 users will need to
     44`download and install ctypes`__.
     45
     46__ http://docs.python.org/lib/module-ctypes.html
     47__ http://sourceforge.net/project/showfiles.php?group_id=71702
     48
     49.. _django:
     50
     51Django
     52------
     53
     54Because GeoDjango is included with Django, please refer to Django's
     55`installation instructions`__ for details on how to install.
     56
     57__ http://docs.djangoproject.com/en/dev/intro/install/
     58
     59.. _spatial_database:
     60
     61Spatial Database
     62----------------
     63PostgreSQL (with PostGIS), MySQL, Oracle, and SQLite (with SpatiaLite) are
     64the spatial databases currently supported.
     65
     66.. note::
     67
     68    PostGIS is recommended, because it is the most mature and feature-rich
     69    open source spatial database.
     70
     71The geospatial libraries required for a GeoDjango installation depends
     72on the spatial database used.  The following lists the library requirements,
     73supported versions, and any notes for each of the supported database backends:
     74
     75==================  ==============================  ==================  ==========================================================
     76Database            Library Requirements            Supported Versions  Notes
     77==================  ==============================  ==================  ==========================================================
     78PostgreSQL          GEOS, PROJ.4, PostGIS           8.1+                Requires PostGIS.
     79MySQL               GEOS                            5.x                 Not OGC-compliant; limited functionality.
     80Oracle              GEOS                            10.2, 11            XE not supported; not tested with 9.
     81SQLite              GEOS, GDAL, PROJ.4, SpatiaLite  3.6.2+              Requires SpatiaLite 2.3+, pysqlite2 2.5+, and Django 1.1.
     82==================  ==============================  ==================  ==========================================================
     83
     84.. _geospatial_libs:
     85
     86Geospatial Libraries
     87--------------------
     88GeoDjango uses and/or provides interfaces for the the following open source
     89geospatial libraries:
     90
     91==============  ====================================  ================================  ==========================
     92Program         Description                           Required                          Supported Versions
     93==============  ====================================  ================================  ==========================
     94`GEOS`_         Geometry Engine Open Source           Yes                               3.1.x, 3.0.x
     95`PROJ.4`_       Cartographic Projections library      Yes (PostgreSQL and SQLite only)  4.7.x, 4.6.x, 4.5.x, 4.4.x
     96`GDAL`_         Geospatial Data Abstraction Library   No (but, required for SQLite)     1.6.x, 1.5.x, 1.4.x
     97`GeoIP`_        IP-based geolocation library          No                                1.4.x
     98`PostGIS`__     Spatial extensions for PostgreSQL     Yes (PostgreSQL only)             1.4.x, 1.3.x, 1.2.1
     99`SpatiaLite`__  Spatial extensions for SQLite         Yes (SQLite only)                 2.3.x
     100==============  ====================================  ================================  ==========================
     101
     102.. admonition::  Install GDAL
     103
     104    While :ref:`gdalbuild` is not required, it is *recommended*.
     105    Some features of GeoDjango (including ``LayerMapping`` and the geographic
     106    admin) depend on its functionality.
     107
     108.. note::
     109
     110    The GeoDjango interfaces to GEOS, GDAL, and GeoIP may be used
     111    independently of Django.  In other words, no database or settings file
     112    required -- just import them as normal from ``django.contrib.gis``.
     113
     114.. _GEOS: geos.html
     115.. _GDAL: gdal.html
     116.. _GeoIP: geoip.html
     117.. _PROJ.4: http://trac.osgeo.org/proj/
     118
     119__ http://postgis.refractions.net/
     120__ http://www.gaia-gis.it/spatialite/index.html
     121
     122.. _build_from_source:
     123
     124Building from Source
     125====================
     126
     127When installing from source on UNIX and GNU/Linux systems, please follow
     128the installation instructions carefully, and install the libraries in the
     129given order.  If using MySQL or Oracle as the spatial database, only GEOS
     130is required.
     131
     132.. note::
     133
     134    OS X users are required to install `Apple Developer Tools`_ in order
     135    to compile software from source.  This is typically included on your
     136    OS X installation DVDs.
     137
     138.. _Apple Developer Tools: http://developer.apple.com/tools/xcode/
     139
     140.. _geosbuild:
     141
     142GEOS
     143----
     144
     145GEOS is a C++ library for performing geometric operations, and is the default
     146internal geometry representation used by GeoDjango (it's behind the "lazy"
     147geometries).  Specifically, the C API library is called (e.g., ``libgeos_c.so``)
     148directly from Python using ctypes.
     149
     150First, download GEOS 3.1.1 from the refractions website and untar the source
     151archive::
     152
     153    $ wget http://download.osgeo.org/geos/geos-3.1.1.tar.bz2
     154    $ tar xjf geos-3.1.1.tar.bz2
     155
     156Next, change into the directory where GEOS was unpacked, run the configure
     157script, compile, and install::
     158
     159    $ cd geos-3.1.1
     160    $ ./configure
     161    $ make
     162    $ sudo make install
     163    $ cd ..
     164
     165Troubleshooting
     166^^^^^^^^^^^^^^^
     167
     168Can't find GEOS Library
     169~~~~~~~~~~~~~~~~~~~~~~~
     170
     171When GeoDjango can't find GEOS, this error is raised::
     172
     173    ImportError: Could not find the GEOS library (tried "geos_c"). Try setting GEOS_LIBRARY_PATH in your settings.
     174
     175The most common solution is to properly configure your :ref:`libsettings` *or* set
     176:ref:`geoslibrarypath` in your settings.
     177
     178If using a binary package of GEOS (e.g., on Ubuntu 8.10), you may need to :ref:`binutils`.
     179
     180.. _geoslibrarypath:
     181
     182``GEOS_LIBRARY_PATH``
     183~~~~~~~~~~~~~~~~~~~~~
     184
     185If your GEOS library is in a non-standard location, or you don't want to
     186modify the system's library path then the ``GEOS_LIBRARY_PATH`` setting
     187may be added to your Django settings file with the full path to the GEOS
     188C library.  For example::
     189
     190    GEOS_LIBRARY_PATH = '/home/bob/local/lib/libgeos_c.so'
     191
     192.. note::
     193
     194    The setting must be the *full* path to the **C** shared library; in
     195    other words you want to use ``libgeos_c.so``, not ``libgeos.so``.
     196
     197.. _proj4:
     198
     199PROJ.4
     200------
     201
     202`PROJ.4`_ is a library for converting geospatial data to different coordinate
     203reference systems.
     204
     205First, download the PROJ.4 source code and datum shifting files [#]_::
     206
     207    $ wget http://download.osgeo.org/proj/proj-4.7.0.tar.gz
     208    $ wget http://download.osgeo.org/proj/proj-datumgrid-1.5.zip
     209
     210Next, untar the source code archive, and extract the datum shifting files in the
     211``nad`` subdirectory.  This must be done *prior* to configuration::
     212
     213    $ tar xzf proj-4.7.0.tar.gz
     214    $ cd proj-4.7.0/nad
     215    $ unzip ../../proj-datumgrid-1.5.zip
     216    $ cd ..
     217
     218Finally, configure, make and install PROJ.4::
     219
     220    $ ./configure
     221    $ make
     222    $ sudo make install
     223    $ cd ..
     224
     225.. _postgis:
     226
     227PostGIS
     228-------
     229
     230`PostGIS`__ adds geographic object support to PostgreSQL, turning it
     231into a spatial database. :ref:`geosbuild` and :ref:`proj4` should be
     232installed prior to building PostGIS.
     233
     234.. note::
     235
     236    The `psycopg2`_ module is required for use as the database adaptor
     237    when using GeoDjango with PostGIS.  Thus, the ``DATABASE_ENGINE``
     238    Django setting needs to be ``postgresql_psycopg2``.
     239
     240.. _psycopg2: http://initd.org/projects/psycopg2
     241
     242First download the source archive, and extract::
     243
     244    $ wget http://postgis.refractions.net/download/postgis-1.4.0.tar.gz
     245    $ tar xzf postgis-1.4.0.tar.gz
     246    $ cd postgis-1.4.0
     247
     248Next, configure, make and install PostGIS::
     249
     250    $ ./configure
     251
     252.. note::
     253    PostGIS versions before 1.4 did not consistently install PostGIS files
     254    relative to PostgreSQL, so passing the an extra flag is recommended.
     255    Thus, when building PostGIS versions 1.3.x and below modify the configuration
     256    command to ensure standard placement of PostGIS SQL files::
     257
     258         $ ./configure --datadir=`pg_config --sharedir`
     259
     260Finally, make and install::
     261
     262    $ make
     263    $ sudo make install
     264    $ cd ..
     265
     266.. note::
     267
     268    GeoDjango does not automatically create a spatial database.  Please
     269    consult the section on :ref:`spatialdb_template` for more information.
     270
     271__ http://postgis.refractions.net/
     272
     273.. _gdalbuild:
     274
     275GDAL
     276----
     277
     278`GDAL`__ is an excellent open source geospatial library that has support for
     279reading most vector and raster spatial data formats.  Currently, GeoDjango only
     280supports GDAL's vector data capabilities [#]_.  :ref:`geosbuild` and :ref:`proj4`
     281should be installed prior to building GDAL.
     282
     283First download the latest GDAL version and untar the archive::
     284
     285    $ wget http://download.osgeo.org/gdal/gdal-1.6.2.tar.gz
     286    $ tar xzf gdal-1.6.2.tar.gz
     287    $ cd gdal-1.6.2
     288
     289Configure, make and install::
     290
     291    $ ./configure
     292    $ make # Go get some coffee, this takes a while.
     293    $ sudo make install
     294    $ cd ..
     295
     296.. note::
     297
     298   Because GeoDjango has it's own Python interface, the preceding instructions
     299   do not build GDAL's own Python bindings.  The bindings may be built by
     300   adding the ``--with-python`` flag when running ``configure``.  See
     301   `GDAL/OGR In Python`__ for more information on GDAL's bindings.
     302
     303If you have any problems, please see the troubleshooting section below for
     304suggestions and solutions.
     305
     306__ http://trac.osgeo.org/gdal/
     307__ http://trac.osgeo.org/gdal/wiki/GdalOgrInPython
     308
     309.. _gdaltrouble:
     310
     311Troubleshooting
     312^^^^^^^^^^^^^^^
     313
     314Can't find GDAL Library
     315~~~~~~~~~~~~~~~~~~~~~~~
     316
     317When GeoDjango can't find the GDAL library, the ``HAS_GDAL`` flag
     318will be false::
     319
     320    >>> from django.contrib.gis import gdal
     321    >>> gdal.HAS_GDAL
     322    False
     323
     324The solution is to properly configure your :ref:`libsettings` *or* set
     325:ref:`gdallibrarypath` in your settings.
     326
     327.. _gdallibrarypath:
     328
     329``GDAL_LIBRARY_PATH``
     330~~~~~~~~~~~~~~~~~~~~~
     331
     332If your GDAL library is in a non-standard location, or you don't want to
     333modify the system's library path then the ``GDAL_LIBRARY_PATH`` setting
     334may be added to your Django settings file with the full path to the GDAL
     335library.  For example::
     336
     337    GDAL_LIBRARY_PATH = '/home/sue/local/lib/libgdal.so'
     338
     339.. _gdaldata:
     340
     341Can't find GDAL data files (``GDAL_DATA``)
     342~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     343
     344When installed from source, GDAL versions 1.5.1 and below have an autoconf bug
     345that places data in the wrong location. [#]_   This can lead to error messages
     346like this::
     347
     348    ERROR 4: Unable to open EPSG support file gcs.csv.
     349    ...
     350    OGRException: OGR failure.
     351
     352The solution is to set the ``GDAL_DATA`` environment variable to the location of the
     353GDAL data files before invoking Python  (typically ``/usr/local/share``; use
     354``gdal-config --datadir`` to find out). For example::
     355
     356    $ export GDAL_DATA=`gdal-config --datadir`
     357    $ python manage.py shell
     358
     359If using Apache, you may need to add this environment variable to your configuration
     360file::
     361
     362    SetEnv GDAL_DATA /usr/local/share
     363
     364.. _spatialite:
     365
     366SpatiaLite
     367----------
     368.. versionadded:: 1.1
     369
     370.. note::
     371
     372   Mac OS X users should follow the instructions in the :ref:`kyngchaos` section,
     373   as it is much easier than building from source.
     374
     375`SpatiaLite`__ adds spatial support to SQLite, turning it into a full-featured
     376spatial database.  Because SpatiaLite has special requirements, it typically
     377requires SQLite and pysqlite2 (the Python SQLite DB-API adaptor) to be built from
     378source.  :ref:`geosbuild` and :ref:`proj4` should be installed prior to building
     379SpatiaLite.
     380
     381After installation is complete, don't forget to read the post-installation
     382docs on :ref:`create_spatialite_db`.
     383
     384__ http://www.gaia-gis.it/spatialite/index.html
     385
     386.. _sqlite:
     387
     388SQLite
     389^^^^^^
     390
     391Typically, SQLite packages are not compiled to include the `R*Tree module`__ --
     392thus it must be compiled from source.  First download the latest amalgamation
     393source archive from the `SQLite download page`__, and extract::
     394
     395    $ wget http://www.sqlite.org/sqlite-amalgamation-3.6.17.tar.gz
     396    $ tar xzf sqlite-amalgamation-3.6.17.tar.gz
     397    $ cd sqlite-3.6.17
     398
     399Next, run the ``configure`` script -- however the ``CFLAGS`` environment variable
     400needs to be customized so that SQLite knows to build the R*Tree module::
     401
     402    $ CFLAGS="-DSQLITE_ENABLE_RTREE=1" ./configure
     403    $ make
     404    $ sudo make install
     405    $ cd ..
     406
     407.. note::
     408
     409    If using Ubuntu, installing a newer SQLite from source can be very difficult
     410    because it links to the existing ``libsqlite3.so`` in ``/usr/lib`` which
     411    many other packages depend on.  Unfortunately, the best solution at this time
     412    is to overwrite the existing library by adding ``--prefix=/usr`` to the
     413    ``configure`` command.
     414
     415__ http://www.sqlite.org/rtree.html
     416__ http://www.sqlite.org/download.html
     417
     418.. _spatialitebuild :
     419
     420SpatiaLite Library (``libspatialite``) and Tools (``spatialite``)
     421^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     422
     423After SQLite has been built with the R*Tree module enabled, get the latest
     424SpatiaLite library source and tools bundle from the `download page`__::
     425
     426    $ wget http://www.gaia-gis.it/spatialite/libspatialite-amalgamation-2.3.1.tar.gz
     427    $ wget http://www.gaia-gis.it/spatialite/spatialite-tools-2.3.1.tar.gz
     428    $ tar xzf libspatialite-amalgamation-2.3.1.tar.gz
     429    $ tar xzf spatialite-tools-2.3.1.tar.gz
     430
     431Prior to attempting to build, please read the important notes below to see if
     432customization of the ``configure`` command is necessary.  If not, then run the
     433``configure`` script, make, and install for the SpatiaLite library::
     434
     435    $ cd libspatialite-amalgamation-2.3.1
     436    $ ./configure # May need to modified, see notes below.
     437    $ make
     438    $ sudo make install
     439    $ cd ..
     440
     441Finally, do the same for the SpatiaLite tools::
     442
     443    $ cd spatialite-tools-2.3.1   
     444    $ ./configure # May need to modified, see notes below.
     445    $ make
     446    $ sudo make install
     447    $ cd ..
     448
     449.. note::
     450
     451    If you've installed GEOS and PROJ.4 from binary packages, you will have to specify
     452    their paths when running the ``configure`` scripts for *both* the library and the
     453    tools (the configure scripts look, by default, in ``/usr/local``).  For example,
     454    on Debian/Ubuntu distributions that have GEOS and PROJ.4 packages, the command would be::
     455   
     456       $ ./configure --with-proj-include=/usr/include --with-proj-lib=/usr/lib --with-geos-include=/usr/include --with-geos-lib=/usr/lib
     457
     458.. note::
     459
     460    For Mac OS X users building from source, the SpatiaLite library *and* tools
     461    need to be linked into the existing ``iconv`` library. While this happens
     462    automatically on Linux, the ``configure`` scripts need to know about the
     463    specific location on Mac OS X (via modification of the ``CFLAGS`` and
     464    ``LDFLAGS`` environment variables prior to configuration)::
     465
     466        $ CFLAGS=-I/usr/include LDFLAGS="-L/usr/lib -liconv" ./configure
     467
     468__ http://www.gaia-gis.it/spatialite/sources.html
     469
     470.. _pysqlite2:
     471
     472pysqlite2
     473^^^^^^^^^
     474
     475Because SpatiaLite must be loaded as an external extension, it requires the
     476``enable_load_extension`` method, which is only available in versions 2.5+.
     477Thus, download pysqlite2 2.5, and untar::
     478 
     479    $ wget http://pysqlite.googlecode.com/files/pysqlite-2.5.6.tar.gz
     480    $ tar xzf pysqlite-2.5.6.tar.gz
     481    $ cd pysqlite-2.5.6
     482
     483Next, use a text editor (e.g., ``emacs`` or ``vi``) to edit the ``setup.cfg`` file
     484to look like the following::
     485
     486    [build_ext]
     487    #define=
     488    include_dirs=/usr/local/include
     489    library_dirs=/usr/local/lib
     490    libraries=sqlite3
     491    #define=SQLITE_OMIT_LOAD_EXTENSION
     492
     493.. note::
     494
     495    The important thing here is to make sure you comment out the the
     496    ``define=SQLITE_OMIT_LOAD_EXTENSION`` flag and that the ``include_dirs``
     497    and ``library_dirs`` settings are uncommented and set to the appropriate
     498    path if the SQLite header files and libraries are not in ``/usr/include``
     499    and ``/usr/lib``, respectively.   
     500
     501After modifying ``setup.cfg`` appropriately, then run the ``setup.py`` script
     502to build and install::
     503
     504    $ sudo python setup.py install
     505
     506Post-Installation
     507=================
     508
     509.. _spatialdb_template:
     510
     511Creating a Spatial Database Template for PostGIS
     512------------------------------------------------
     513
     514Creating a spatial database with PostGIS is different than normal because
     515additional SQL must be loaded to enable spatial functionality.  Because of
     516the steps in this process, it's better to create a database template that
     517can be reused later.
     518
     519First, you need to be able to execute the commands as a privileged database
     520user.  For example, you can use the following to become the ``postgres`` user::
     521
     522    $ sudo su - postgres
     523
     524Once you're a database super user, then you may execute the following commands
     525to create a PostGIS spatial database template.  If running Ubuntu :ref:`ibex`
     526or Debian :ref:`lenny`, please refer to their specific documentation for slight
     527modifications to these commands::
     528
     529    $ POSTGIS_SQL_PATH=`pg_config --sharedir`/contrib
     530    $ createdb -E UTF8 template_postgis # Creating the template spatial database.
     531    $ createlang -d template_postgis plpgsql # Adding PLPGSQL language support.
     532    $ psql -d postgres -c "UPDATE pg_database SET datistemplate='true' WHERE datname='template_postgis';" # Allows non-superusers the ability to create from this template
     533    $ psql -d template_postgis -f $POSTGIS_SQL_PATH/postgis.sql # Loading the PostGIS SQL routines
     534    $ psql -d template_postgis -f $POSTGIS_SQL_PATH/spatial_ref_sys.sql
     535    $ psql -d template_postgis -c "GRANT ALL ON geometry_columns TO PUBLIC;" # Enabling users to alter spatial tables.
     536    $ psql -d template_postgis -c "GRANT ALL ON spatial_ref_sys TO PUBLIC;"
     537
     538These commands may be placed in a shell script for later use; for convenience,
     539the `create_template_postgis-1.4.sh`__ script is provided here.  If using
     540PostGIS 1.3.x, please use the `create_template_postgis-1.3.sh`__ script
     541instead as the PostGIS SQL path and file names differ from 1.4.
     542
     543Afterwards, you may create a spatial database by simply specifying
     544``template_postgis`` as the template to use (via the ``-T`` option)::
     545
     546    $ createdb -T template_postgis <db name>
     547
     548.. note::
     549
     550    While the ``createdb`` command does not require database super-user privileges,
     551    it must be executed by a database user that has permissions to create databases.
     552    You can create such a user with the following command::
     553
     554        $ createuser --createdb <user>
     555
     556__ http://geodjango.org/docs/create_template_postgis-1.4.sh
     557__ http://geodjango.org/docs/create_template_postgis-1.3.sh
     558
     559.. _create_spatialite_db:
     560
     561Creating a Spatial Database for SpatiaLite
     562-------------------------------------------
     563
     564After the SpatiaLite library and tools have been installed, it is now possible
     565to create spatial database for use with GeoDjango.  In order to do this, download
     566the spatial database initialization SQL from the `SpatiaLite Resources`__ page::
     567
     568   $ wget http://www.gaia-gis.it/spatialite/init_spatialite-2.3.sql.gz
     569   $ gunzip init_spatialite-2.3.sql.gz
     570
     571Now, the ``spatialite`` command can be used to initialize a spatial database::
     572
     573   $ spatialite geodjango.db < init_spatialite-2.3.sql
     574
     575.. note::
     576
     577    The parameter ``geodjango.db`` is the *filename* of the SQLite database
     578    you want to use.  Use the same in the ``DATABASE_NAME`` setting inside
     579    your project's ``settings.py``.
     580
     581
     582__ http://www.gaia-gis.it/spatialite/resources.html
     583
     584
     585Add ``django.contrib.gis`` to ``INSTALLED_APPS``
     586------------------------------------------------
     587
     588Like other Django contrib applications, you will *only* need to add
     589``django.contrib.gis`` to ``INSTALLED_APPS`` in your settings.  This is the
     590so that ``gis`` templates can be located -- if not done, then features such as
     591the geographic admin or KML sitemaps will not function properly.
     592
     593.. _addgoogleprojection:
     594
     595Add Google Projection to ``spatial_ref_sys`` table
     596--------------------------------------------------
     597
     598.. note::
     599
     600    In Django 1.1 this step is no longer required to use the geographic
     601    admin with the OpenStreetMap base layer.
     602
     603In order to use the geographic admin with the OpenStreetMap base layer
     604(e.g., you want to use ``OSMGeoAdmin``), then the so-called "Google" projection
     605must be added to your spatial database's ``spatial_ref_sys`` table.  Invoke
     606the Django shell from your project and execute the following command::
     607
     608    $ ./manage shell
     609    >>> from django.contrib.gis.utils import add_postgis_srs
     610    >>> add_postgis_srs(900913)
     611
     612This adds an entry for the 900913 SRID to the ``spatial_ref_sys`` (or equivalent)
     613table, making it possible for the spatial database to transform coordinates in
     614this projection.  You only need to execute this command *once* per spatial database.
     615
     616Troubleshooting
     617===============
     618
     619If you can't find the solution to your problem here then participate in the
     620community!  You can:
     621
     622* Join the ``#geodjango`` IRC channel on FreeNode (may be accessed on the
     623  web via `Mibbit`__).  Please be patient and polite -- while you may not
     624  get an immediate response, someone will attempt to answer your question
     625  as soon as they see it.
     626* Ask your question on the `GeoDjango`__ mailing list.
     627* File a ticket on the `Django trac`__ if you think there's a bug.  Make
     628  sure to provide a complete description of the problem, versions used,
     629  and specify the component as "GIS".
     630
     631__ http://www.mibbit.com/?server=irc.freenode.net&channel=%23geodjango
     632__ http://groups.google.com/group/geodjango
     633__ http://code.djangoproject.com/simpleticket
     634
     635.. _libsettings:
     636
     637Library Environment Settings
     638----------------------------
     639
     640By far, the most common problem when installing GeoDjango is that the
     641external shared libraries (e.g., for GEOS and GDAL) cannot be located. [#]_
     642Typically, the cause of this problem is that the operating system isn't aware
     643of the directory where the libraries built from source were installed.
     644
     645In general, the library path may be set on a per-user basis by setting
     646an environment variable, or by configuring the library path for the entire
     647system.
     648
     649``LD_LIBRARY_PATH`` environment variable
     650^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     651
     652A user may set this environment variable to customize the library paths
     653they want to use.  The typical library directory for software
     654built from source is ``/usr/local/lib``.  Thus, ``/usr/local/lib`` needs
     655to be included in the ``LD_LIBRARY_PATH`` variable.  For example, the user
     656could place the following in their bash profile::
     657
     658    export LD_LIBRARY_PATH=/usr/local/lib
     659
     660Setting System Library Path
     661^^^^^^^^^^^^^^^^^^^^^^^^^^^
     662
     663On GNU/Linux systems, there is typically a file in ``/etc/ld.so.conf``, which may include
     664additional paths from files in another directory, such as ``/etc/ld.so.conf.d``.
     665As the root user, add the custom library path (like ``/usr/local/lib``) on a 
     666new line in ``ld.so.conf``.  This is *one* example of how to do so::
     667
     668    $ sudo echo /usr/local/lib >> /etc/ld.so.conf
     669    $ sudo ldconfig
     670
     671For OpenSolaris users, the system library path may be modified using the
     672``crle`` utility.  Run ``crle`` with no options to see the current configuration
     673and use ``crle -l`` to set with the new library path.  Be *very* careful when
     674modifying the system library path::
     675
     676    # crle -l $OLD_PATH:/usr/local/lib
     677
     678.. _binutils:
     679
     680Install ``binutils``
     681^^^^^^^^^^^^^^^^^^^^
     682
     683GeoDjango uses the ``find_library`` function (from the ``ctypes.util`` Python
     684module) to discover libraries.  The ``find_library`` routine uses a program
     685called ``objdump`` (part of the ``binutils`` package) to verify a shared
     686library on GNU/Linux systems.  Thus, if ``binutils`` is not installed on your
     687Linux system then Python's ctypes may not be able to find your library even if
     688your library path is set correctly and geospatial libraries were built perfectly.
     689
     690The ``binutils`` package may be installed on Debian and Ubuntu systems using the
     691following command::
     692
     693    $ sudo apt-get install binutils
     694
     695Similarly, on Red Hat and CentOS systems::
     696
     697    $ sudo yum install binutils
     698
     699Platform Specific Instructions
     700==============================
     701
     702.. _macosx:
     703
     704Mac OS X
     705--------
     706
     707Because of the variety of packaging systems available for OS X, users have
     708several different options for installing GeoDjango.  These options are:
     709
     710* :ref:`kyngchaos`
     711* :ref:`fink`
     712* :ref:`macports`
     713* :ref:`build_from_source`
     714
     715.. note::
     716
     717    Currently, the easiest and recommended approach for installing GeoDjango
     718    on OS X is to use the KyngChaos packages. 
     719
     720This section also includes instructions for installing an upgraded version
     721of :ref:`macosx_python` from packages provided by the Python Software
     722Foundation, however, this is not required.
     723
     724.. _macosx_python:
     725
     726Python
     727^^^^^^
     728
     729Although OS X comes with Python installed, users can use framework
     730installers (`2.5`__ and `2.6`__ are available) provided by
     731the Python Software Foundation.  An advantage to using the installer is
     732that OS X's Python will remain "pristine" for internal operating system
     733use.
     734
     735__ http://python.org/ftp/python/2.5.4/python-2.5.4-macosx.dmg
     736__ http://python.org/ftp/python/2.6.2/python-2.6.2-macosx2009-04-16.dmg
     737
     738.. note::
     739 
     740    You will need to modify the ``PATH`` environment variable in your
     741    ``.profile`` file so that the new version of Python is used when
     742    ``python`` is entered at the command-line::
     743
     744        export PATH=/Library/Frameworks/Python.framework/Versions/Current/bin:$PATH
     745
     746.. _kyngchaos:
     747
     748KyngChaos Packages
     749^^^^^^^^^^^^^^^^^^
     750
     751William Kyngesburye provides a number of `geospatial library binary packages`__
     752that make it simple to get GeoDjango installed on OS X without compiling
     753them from source.  However, the `Apple Developer Tools`_ are still necessary
     754for compiling the Python database adapters :ref:`psycopg2_kyngchaos` (for PostGIS)
     755and :ref:`pysqlite2_kyngchaos` (for SpatiaLite). 
     756
     757.. note::
     758
     759    SpatiaLite users should consult the :ref:`spatialite_kyngchaos` section
     760    after installing the packages for additional instructions.
     761
     762Download the framework packages for:
     763
     764* UnixImageIO
     765* PROJ
     766* GEOS
     767* SQLite3 (includes the SpatiaLite library)
     768* GDAL
     769
     770Install the packages in the order they are listed above, as the GDAL and SQLite
     771packages require the packages listed before them.  Afterwards, you can also
     772install the KyngChaos binary packages for `PostgreSQL and PostGIS`__.
     773
     774After installing the binary packages, you'll want to add the following to
     775your ``.profile`` to be able to run the package programs from the command-line::
     776
     777    export PATH=/Library/Frameworks/UnixImageIO.framework/Programs:$PATH
     778    export PATH=/Library/Frameworks/PROJ.framework/Programs:$PATH
     779    export PATH=/Library/Frameworks/GEOS.framework/Programs:$PATH
     780    export PATH=/Library/Frameworks/SQLite3.framework/Programs:$PATH
     781    export PATH=/Library/Frameworks/GDAL.framework/Programs:$PATH
     782    export PATH=/usr/local/pgsql/bin:$PATH
     783
     784__ http://www.kyngchaos.com/wiki/software:frameworks
     785__ http://www.kyngchaos.com/wiki/software:postgres
     786
     787.. note::
     788
     789    Use of these binaries requires Django 1.0.3 and above.  If you are
     790    using a previous version of Django (like 1.0.2), then you will have
     791    to add the the following in your settings::
     792
     793        GEOS_LIBRARY_PATH='/Library/Frameworks/GEOS.framework/GEOS'
     794        GDAL_LIBRARY_PATH='/Library/Frameworks/GDAL.framework/GDAL'
     795
     796.. _psycopg2_kyngchaos:
     797
     798psycopg2
     799~~~~~~~~
     800
     801After you've installed the KyngChaos binaries and modified your ``PATH``, as
     802described above, ``psycopg2`` may be installed using the following command::
     803
     804    $ sudo python easy_install psycopg2
     805
     806.. note::
     807
     808   To use ``easy_install`` you'll need to install Python's `setuptools`_.
     809
     810.. _setuptools: http://pypi.python.org/pypi/setuptools
     811
     812.. _pysqlite2_kyngchaos:
     813
     814pysqlite2
     815~~~~~~~~~
     816
     817Follow the :ref:`pysqlite2` source install instructions, however,
     818when editing the ``setup.cfg`` use the following instead::
     819
     820    [build_ext]
     821    #define=
     822    include_dirs=/Library/Frameworks/SQLite3.framework/unix/include
     823    library_dirs=/Library/Frameworks/SQLite3.framework/unix/lib
     824    libraries=sqlite3
     825    #define=SQLITE_OMIT_LOAD_EXTENSION
     826
     827.. _spatialite_kyngchaos:
     828
     829SpatiaLite
     830~~~~~~~~~~
     831
     832When :ref:`create_spatialite_db`, the ``spatialite`` program is required.
     833However, instead of attempting to compile the SpatiaLite tools from source,
     834download the `SpatiaLite Binaries`__ for OS X, and install ``spatialite`` in a
     835location available in your ``PATH``.  For example::
     836
     837    $ curl -O http://www.gaia-gis.it/spatialite/spatialite-tools-osx-x86-2.3.1.tar.gz
     838    $ tar xzf spatialite-tools-osx-x86-2.3.1.tar.gz
     839    $ cd spatialite-tools-osx-x86-2.3.1/bin
     840    $ sudo cp spatialite /Library/Frameworks/SQLite3.framework/Programs
     841
     842Finally, for GeoDjango to be able to find the KyngChaos SpatiaLite library,
     843add the following to your ``settings.py``::
     844
     845    SPATIALITE_LIBRARY_PATH='/Library/Frameworks/SQLite3.framework/SQLite3'
     846
     847__ http://www.gaia-gis.it/spatialite/binaries.html
     848
     849.. _fink:
     850
     851Fink
     852^^^^
     853
     854`Kurt Schwehr`__ has been gracious enough to create GeoDjango packages for users
     855of the `Fink`__ package system.  The following packages are available, depending
     856on which version of Python you want to use:
     857
     858* ``django-gis-py26``
     859* ``django-gis-py25``
     860* ``django-gis-py24``
     861
     862__ http://schwehr.org/blog/
     863__ http://www.finkproject.org/
     864
     865.. _macports:
     866
     867MacPorts
     868^^^^^^^^
     869
     870`MacPorts`__ may be used to install GeoDjango prerequisites on Macintosh
     871computers running OS X.  Because MacPorts still builds the software from source,
     872the `Apple Developer Tools`_ are required.
     873
     874Summary::
     875
     876    $ sudo port install postgresql83-server
     877    $ sudo port install geos
     878    $ sudo port install proj
     879    $ sudo port install postgis
     880    $ sudo port install gdal
     881    $ sudo port install libgeoip 
     882
     883.. note::
     884
     885    You will also have to modify the ``PATH`` in your ``.profile`` so
     886    that the MacPorts programs are accessible from the command-line::
     887
     888        export PATH=/opt/local/bin:/opt/local/lib/postgresql83/bin
     889
     890    In addition, add the ``FALLBACK_DYLD_LIBRARY_PATH`` setting so that
     891    the libraries can be found by Python::
     892
     893        export FALLBACK_DYLD_LIBRARY_PATH=/opt/local/lib:/opt/local/lib/postgresql83
     894
     895__ http://www.macports.org/
     896
     897.. _ubuntudebian:
     898
     899Ubuntu & Debian GNU/Linux
     900-------------------------
     901
     902.. _ubuntu:
     903
     904Ubuntu
     905^^^^^^
     906
     907.. _heron:
     908
     9098.04 and lower
     910~~~~~~~~~~~~~~
     911
     912The 8.04 (and lower) versions of Ubuntu use GEOS v2.2.3 in their binary packages,
     913which is incompatible with GeoDjango.  Thus, do *not* use the binary packages
     914for GEOS or PostGIS and build some prerequisites from source, per the instructions
     915in this document; however, it is okay to use the PostgreSQL binary packages.
     916
     917For more details, please see the Debian instructions for :ref:`etch` below.
     918
     919.. _ibex:
     920
     9218.10
     922~~~~
     923
     924Use the synaptic package manager to install the following packages::
     925
     926    $ sudo apt-get install binutils libgdal1-1.5.0 postgresql-8.3-postgis postgresql-server-dev-8.3 python-psycopg2 python-setuptools
     927
     928Afterwards, you may install Django with Python's ``easy_install`` script (the
     929Ubuntu package ``python-django`` uses an older version missing several
     930important bug fixes for GeoDjango)::
     931
     932    $ sudo easy_install Django
     933
     934That's it!  For the curious, the required binary prerequisites packages are:
     935
     936* ``binutils``: for ctypes to find libraries
     937* ``postgresql-8.3``
     938* ``postgresql-server-dev-8.3``: for ``pg_config``
     939* ``postgresql-8.3-postgis``: for PostGIS 1.3.3
     940* ``libgeos-3.0.0``, and ``libgeos-c1``: for GEOS 3.0.0
     941* ``libgdal1-1.5.0``: for GDAL 1.5.0 library
     942* ``proj``: for PROJ 4.6.0 -- but no datum shifting files, see note below
     943* ``python-psycopg2``
     944* ``python-setuptools``: for ``easy_install``
     945
     946Optional packages to consider:
     947
     948* ``libgeoip1``: for `GeoIP`_ support
     949* ``gdal-bin``: for GDAL command line programs like ``ogr2ogr``
     950* ``python-gdal`` for GDAL's own Python bindings -- includes interfaces for raster manipulation
     951
     952.. note::
     953   
     954    The Ubuntu ``proj`` package does not come with the datum shifting files
     955    installed, which will cause problems with the geographic admin because
     956    the ``null`` datum grid is not available for transforming geometries to the
     957    spherical mercator projection. A solution is to download the
     958    datum-shifting files, create the grid file, and install it yourself::
     959
     960        $ wget http://download.osgeo.org/proj/proj-datumgrid-1.4.tar.gz
     961        $ mkdir nad
     962        $ cd nad
     963        $ tar xzf ../proj-datumgrid-1.4.tar.gz
     964        $ nad2bin null < null.lla
     965        $ sudo cp null /usr/share/proj
     966
     967    Otherwise, the Ubuntu ``proj`` package is fine for general use as long as you
     968    do not plan on doing any database transformation of geometries to the
     969    Google projection (900913).
     970
     971.. note::
     972
     973    The PostGIS SQL files are not placed the PostgreSQL share directory in the
     974    Ubuntu packages.  Use the `create_template_postgis-debian.sh`__ script
     975    instead when :ref:`spatialdb_template`.
     976
     977__ http://geodjango.org/docs/create_template_postgis-debian.sh
     978
     979.. _debian:
     980
     981Debian
     982------
     983
     984.. _etch:
     985
     9864.0 (Etch)
     987^^^^^^^^^^
     988The situation here is the same as that of Ubuntu :ref:`heron` -- in other words,
     989some packages must be built from source to work properly with GeoDjango.
     990
     991Binary Packages
     992~~~~~~~~~~~~~~~
     993The following command will install acceptable binary packages, as well as
     994the development tools necessary to build the rest of the requirements::
     995
     996    $ sudo apt-get install binutils bzip2 gcc g++ flex make postgresql-8.1 postgresql-server-dev-8.1 python-ctypes python-psycopg2 python-setuptools
     997
     998Required package information:
     999
     1000* ``binutils``: for ctypes to find libraries
     1001* ``bzip2``: for decompressing the source packages
     1002* ``gcc``, ``g++``, ``make``: GNU developer tools used to compile the libraries
     1003* ``flex``: required to build PostGIS
     1004* ``postgresql-8.1``
     1005* ``postgresql-server-dev-8.1``: for ``pg_config``
     1006* ``python-ctypes``: Python 2.4 needs to have ctypes installed separately
     1007* ``python-psycopg2``
     1008* ``python-setuptools``: for ``easy_install``
     1009
     1010Optional packages:
     1011
     1012* ``libgeoip``: for `GeoIP`_ support
     1013
     1014Source Packages
     1015~~~~~~~~~~~~~~~
     1016You will still have to install :ref:`geosbuild`, :ref:`proj4`,
     1017:ref:`postgis`, and :ref:`gdalbuild` from source.  Please follow the
     1018directions carefully.
     1019
     1020.. _lenny:
     1021
     10225.0 (Lenny)
     1023^^^^^^^^^^^
     1024This version is comparable to Ubuntu :ref:`ibex`, so the command
     1025is very similar::
     1026
     1027    $ sudo apt-get install binutils libgdal1-1.5.0 postgresql-8.3 postgresql-8.3-postgis postgresql-server-dev-8.3 python-psycopg2 python-setuptools
     1028
     1029This assumes that you are using PostgreSQL version 8.3. Else, replace ``8.3``
     1030in the above command with the appropriate PostgreSQL version.
     1031
     1032.. note::
     1033
     1034   Please read the note in the Ubuntu :ref:`ibex` install documentation
     1035   about the ``proj`` package -- it also applies here because the package does
     1036   not include the datum shifting files.
     1037
     1038.. _post_install:
     1039
     1040Post-installation Notes
     1041~~~~~~~~~~~~~~~~~~~~~~~
     1042
     1043If the PostgreSQL database cluster was not initiated after installing, then it
     1044can be created (and started) with the following command::
     1045
     1046    $ sudo pg_createcluster --start 8.3 main
     1047
     1048Afterwards, the ``/etc/init.d/postgresql-8.3`` script should be used to manage
     1049the starting and stopping of PostgreSQL.
     1050
     1051In addition, the SQL files for PostGIS are placed in a different location on
     1052Debian 5.0 . Thus when :ref:`spatialdb_template` either:
     1053
     1054* Create a symbolic link to these files::
     1055
     1056    $ sudo ln -s /usr/share/postgresql-8.3-postgis/{lwpostgis,spatial_ref_sys}.sql /usr/share/postgresql/8.3
     1057
     1058  If not running PostgreSQL 8.3, then  replace ``8.3`` in the command above with the correct version.
     1059
     1060* Or use the `create_template_postgis-debain.sh`__ to create the spatial database.
     1061  If you're PostgreSQL version is not 8.3, you will have to modify the
     1062  ``POSTGIS_SQL_PATH`` variable in the script.
     1063
     1064__ http://geodjango.org/docs/create_template_postgis-debian.sh
     1065
     1066.. _windows:
     1067
     1068Windows XP
     1069----------
     1070
     1071Python
     1072^^^^^^
     1073
     1074First, download the `Python 2.6 installer`__ from the Python website.  Next,
     1075execute the installer and use defaults, e.g., keep 'Install for all users'
     1076checked and the installation path set as ``C:\Python26``.
     1077
     1078.. note::
     1079
     1080    You may already have a version of Python installed in ``C:\python`` as ESRI
     1081    products sometimes install a copy there.  *You should still install a
     1082    fresh version of Python 2.6.*
     1083
     1084__ http://python.org/ftp/python/2.6.2/python-2.6.2.msi
     1085
     1086PostgreSQL
     1087^^^^^^^^^^
     1088
     1089First, select a mirror and download the latest `PostgreSQL 8.3 installer`__ from
     1090the EnterpriseDB website.
     1091
     1092.. note::
     1093
     1094   PostgreSQL 8.3 is required because PostGIS is not available yet for 8.4.
     1095
     1096After downloading, simply click on the installer, follow the
     1097on-screen directions, and keep the default options (e.g., keep the installation
     1098path as ``C:\Program Files\PostgreSQL\8.3``).
     1099
     1100.. note::
     1101
     1102    This PostgreSQL installation process will create both a new windows user to be the
     1103    'postgres service account' and a special 'postgres superuser' to own the database
     1104    cluster. You will be prompted to set a password for both users (make sure to write
     1105    them down!). To see basic details on the 'service user' account right click on
     1106    'My Computer' and select 'Manage' or go to: Control Panel -> Administrative Tools ->
     1107    Computer Management -> System Tools -> Local Users and Groups.
     1108
     1109If installed successfully, the PostgreSQL server will run in the background each time
     1110the system as started as a Windows service.  When finished, the installer should launch
     1111the Application Stack Builder (ASB) -- use this to install PostGIS, see instructions
     1112below for more details.  A 'PostgreSQL 8.3' start menu group should be created that
     1113contains shortcuts for the ASB and 'Command Prompt', which launches a terminal window
     1114in the PostgreSQL directory.
     1115
     1116__ http://www.enterprisedb.com/products/pgdownload.do#windows
     1117
     1118PostGIS
     1119^^^^^^^
     1120
     1121From the Application Stack Builder (Programs -> PostgreSQL 8.3), select
     1122'PostgreSQL Database Server 8.3 on port 5432' from the drop down menu.  Next,
     1123select 'PostGIS 1.3.6 for PostgreSQL 8.3' from the 'Spatial Extensions' tree
     1124in the list.  Select only the default options during install (do not uncheck
     1125the option to create a default PostGIS database).
     1126
     1127.. note::
     1128
     1129    You will be prompted to enter your 'postgres superuser' password in the
     1130    'Database Connection Information' dialog.
     1131
     1132psycopg2
     1133^^^^^^^^
     1134
     1135The ``psycopg2`` Python module provides the interface between Python and the
     1136PostgreSQL database.  Download the `Windows installer`__ (v2.0.10) and run
     1137using the default settings. [#]_
     1138
     1139__ http://www.stickpeople.com/projects/python/win-psycopg/psycopg2-2.0.10.win32-py2.6-pg8.3.7-release.exe
     1140
     1141GeoDjango Installer
     1142^^^^^^^^^^^^^^^^^^^
     1143
     1144Download the `GeoDjango Installer`__; this was created [#]_ to simplify the rest
     1145of the process for installing GeoDjango on Windows platforms.  The installer
     1146automatically installs Django 1.1, GDAL 1.6.0, PROJ 4.6.1 (including datum grid
     1147files), and configures the necessary environment variables.
     1148
     1149Once the installer has completed, log out and log back in so that the
     1150modifications to the system environment variables take effect, and you
     1151should be good to go.
     1152
     1153.. note::
     1154
     1155    The installer modifies the system ``Path`` environment variable to
     1156    include ``C:\Program Files\PostgreSQL\8.3\bin`` and
     1157    ``C:\Program Files\GeoDjango\bin``.  This is required so that Python
     1158    may find the GEOS DLL provided by PostGIS and the GDAL DLL provided
     1159    by the installer. The installer also sets the ``GDAL_DATA`` and
     1160    ``PROJ_LIB`` environment variables.
     1161
     1162__ http://geodjango.org/windows/GeoDjango_Installer.exe
     1163
     1164.. rubric:: Footnotes
     1165.. [#] The datum shifting files are needed for converting data to and from certain projections.
     1166       For example, the PROJ.4 string for the `Google projection (900913) <http://spatialreference.org/ref/epsg/900913/proj4>`_
     1167       requires the ``null`` grid file only included in the extra datum shifting files. 
     1168       It is easier to install the shifting files now, then to have debug a problem caused by their absence later.
     1169.. [#] Specifically, GeoDjango provides support for the `OGR <http://gdal.org/ogr>`_ library, a component of GDAL.
     1170.. [#] See `GDAL ticket #2382 <http://trac.osgeo.org/gdal/ticket/2382>`_.
     1171.. [#] GeoDjango uses the `find_library <http://docs.python.org/library/ctypes.html#finding-shared-libraries>`_
     1172       routine from ``ctypes.util`` to locate shared libraries.
     1173.. [#] The ``psycopg2`` Windows installers are packaged and maintained by
     1174       `Jason Erickson <http://www.stickpeople.com/projects/python/win-psycopg/>`_.
     1175.. [#] The source code for the installer is available in the `nsis_installer <http://geodjango.org/hg/nsis_installer/>`_
     1176       GeoDjango mercurial repository.
  • docs/ref/contrib/gis/gdal.txt

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

     
     1.. _ref-contrib-gis:
     2
     3=========
     4GeoDjango
     5=========
     6
     7.. versionadded:: 1.0
     8
     9.. module:: django.contrib.gis
     10   :synopsis: Geographic Information System (GIS) extensions for Django
     11
     12.. currentmodule:: django.contrib.gis
     13
     14GeoDjango intends to be a world-class geographic web framework. Its goal is to
     15make it as easy as possible to build GIS web applications and harness the power
     16of spatially enabled data.
     17
     18.. toctree::
     19   :maxdepth: 1
     20
     21   tutorial
     22   install
     23   model-api
     24   db-api
     25   geos
     26   measure
     27   gdal
     28   utils
     29   feeds
     30   sitemaps
     31   testing
     32   deployment
  • docs/ref/contrib/gis/model-api.txt

     
     1.. _ref-gis-model-api:
     2
     3===================
     4GeoDjango Model API
     5===================
     6
     7.. module:: django.db.models.fields
     8   :synopsis: Built-in geometry field types.
     9
     10.. currentmodule:: django.contrib.gis.db.models
     11
     12This document explores the details of the GeoDjango Model API.  Throughout this
     13section, we'll be using the following geographic model of a `ZIP code`__ as our
     14example::
     15
     16    from django.contrib.gis.db import models
     17   
     18    class Zipcode(models.Model):
     19        code = models.CharField(max_length=5)
     20        poly = models.PolygonField()
     21        objects = models.GeoManager()
     22
     23__ http://en.wikipedia.org/wiki/ZIP_code
     24
     25.. _geometry-field-options:
     26
     27Geometry Field Options
     28======================
     29
     30In addition to the regular :ref:`ref-models-fields` available for
     31Django model fields, geometry fields have the following additional options.
     32All are optional.
     33
     34``srid``
     35--------
     36
     37.. attribute:: GeometryField.srid
     38
     39Sets the SRID [#]_ (Spatial Reference System Identity) of the geometry field to
     40the given value. Defaults to 4326 (also known as `WGS84`__, units are in degrees
     41of longitude and latitude).
     42
     43__ http://en.wikipedia.org/wiki/WGS84
     44
     45Selecting an SRID
     46^^^^^^^^^^^^^^^^^
     47
     48Choosing an appropriate SRID for your model is an important decision that the
     49developer should consider carefully.  The SRID is an integer specifier that
     50corresponds to the projection system that will be used to interpret the data
     51in the spatial database. [#]_  Projection systems give the context to the
     52coordinates that specify a location.  Although the details of `geodesy`__ are
     53beyond the scope of this documentation, the general problem is that the earth
     54is spherical and representations of the earth (e.g., paper maps, web maps)
     55are not.
     56
     57Most people are familiar with using latitude and longitude to reference a
     58location on the earth's surface.  However, latitude and longitude are angles,
     59not distances. [#]_  In other words, while the shortest path between two points on
     60a flat surface is a straight line, the shortest path between two points on a curved
     61surface (such as the earth) is an *arc* of a `great circle`__. [#]_  Thus,
     62additional computation is required to obtain distances in planar units (e.g.,
     63kilometers and miles).  Using a geographic coordinate system may introduce
     64complications for the developer later on.  For example, PostGIS does not
     65have the capability to perform distance calculations between non-point
     66geometries using geographic coordinate systems, e.g., constructing a query to
     67find all points within 5 miles of a county boundary stored as WGS84. [#]_
     68
     69Portions of the earth's surface may projected onto a two-dimensional, or
     70Cartesian, plane.  Projected coordinate systems are especially convenient
     71for region-specific applications, e.g., if you know that your database will
     72only cover geometries in `North Kansas`__, then you may consider using projection
     73system specific to that region.  Moreover, projected coordinate systems are
     74defined in Cartesian units (such as meters or feet), easing distance
     75calculations.
     76
     77Additional Resources:
     78
     79* `spatialreference.org`__: A Django-powered database of spatial reference
     80  systems.
     81* `The State Plane Coordinate System`__: A website covering the various
     82  projection systems used in the United States.  Much of the U.S. spatial
     83  data encountered will be in one of these coordinate systems rather than
     84  in a geographic coordinate system such as WGS84.
     85
     86__ http://en.wikipedia.org/wiki/Geodesy
     87__ http://en.wikipedia.org/wiki/Great_circle
     88__ http://www.spatialreference.org/ref/epsg/2796/
     89__ http://spatialreference.org/
     90__ http://welcome.warnercnr.colostate.edu/class_info/nr502/lg3/datums_coordinates/spcs.html
     91
     92``spatial_index``
     93-----------------
     94
     95.. attribute:: GeometryField.spatial_index
     96
     97Defaults to ``True``.  Creates a spatial index for the given geometry
     98field.
     99
     100.. note::
     101
     102    This is different from the ``db_index`` field option because spatial
     103    indexes are created in a different manner than regular database
     104    indexes.  Specifically, spatial indexes are typically created using
     105    a variant of the R-Tree, while regular indexes use B-Tree.
     106
     107``dim``
     108-------
     109
     110.. versionadded:: 1.2
     111
     112.. attribute:: GeometryField.dim
     113
     114This option may be used for customizing the coordinate dimension of the
     115geometry field.  By default, it is set to 2, for representing two-dimensional
     116geometries.  For spatial backends that support it, it may be set to 3 for
     117three-dimensonal support.
     118
     119.. note::
     120
     121    At this time 3D support requires that GEOS 3.1 be installed, and is
     122    limited only to the PostGIS spatial backend.
     123
     124Geometry Field Types
     125====================
     126
     127.. currentmodule:: django.contrib.gis.db.models
     128
     129Each of the following geometry field types correspond with the
     130OpenGIS Simple Features specification [#]_.
     131
     132``GeometryField``
     133-----------------
     134
     135.. class:: GeometryField
     136
     137``PointField``
     138--------------
     139
     140.. class:: PointField
     141
     142``LineStringField``
     143-------------------
     144
     145.. class:: LineStringField
     146
     147``PolygonField``
     148----------------
     149
     150.. class:: PolygonField
     151
     152``MultiPointField``
     153-------------------
     154
     155.. class:: MultiPointField
     156
     157``MultiLineStringField``
     158------------------------
     159
     160.. class:: MultiLineStringField
     161
     162``MultiPolygonField``
     163---------------------
     164
     165.. class:: MultiPolygonField
     166
     167``GeometryCollectionField``
     168---------------------------
     169
     170.. class:: GeometryCollectionField
     171
     172``GeoManager``
     173==============
     174
     175.. currentmodule:: django.contrib.gis.db.models
     176.. class:: GeoManager
     177
     178In order to conduct geographic queries, each geographic model requires
     179a ``GeoManager`` model manager.  This manager allows for the proper SQL
     180construction for geographic queries; thus, without it, all geographic filters
     181will fail.  It should also be noted that ``GeoManager`` is required even if the
     182model does not have a geographic field itself, e.g., in the case of a
     183``ForeignKey`` relation to a model with a geographic field.  For example,
     184if we had an ``Address`` model with a ``ForeignKey`` to our ``Zipcode``
     185model::
     186
     187    from django.contrib.gis.db import models
     188    from django.contrib.localflavor.us.models import USStateField
     189
     190    class Address(models.Model):
     191        num = models.IntegerField()
     192        street = models.CharField(max_length=100)
     193        city = models.CharField(max_length=100)
     194        state = USStateField()
     195        zipcode = models.ForeignKey(Zipcode)
     196        objects = models.GeoManager()
     197
     198The geographic manager is needed to do spatial queries on related ``Zipcode`` objects,
     199for example::
     200
     201    qs = Address.objects.filter(zipcode__poly__contains='POINT(-104.590948 38.319914)')
     202
     203.. rubric:: Footnotes
     204.. [#] OpenGIS Consortium, Inc., `Simple Feature Specification For SQL <http://www.opengis.org/docs/99-049.pdf>`_, Document 99-049 (May 5, 1999).
     205.. [#] *See id.* at Ch. 2.3.8, p. 39 (Geometry Values and Spatial Reference Systems).
     206.. [#] Typically, SRID integer corresponds to an EPSG (`European Petroleum Survey Group <http://www.epsg.org>`_) identifier.  However, it may also be associated with custom projections defined in spatial database's spatial reference systems table.
     207.. [#] Harvard Graduate School of Design, `An Overview of Geodesy and Geographic Referencing Systems <http://www.gsd.harvard.edu/gis/manual/projections/fundamentals/>`_.  This is an excellent resource for an overview of principles relating to geographic and Cartesian coordinate systems.
     208.. [#] Terry A. Slocum, Robert B. McMaster, Fritz C. Kessler, & Hugh H. Howard, *Thematic Cartography and Geographic Visualization* (Prentice Hall, 2nd edition), at Ch. 7.1.3.
     209.. [#] This isn't impossible using GeoDjango; you could for example, take a known point in a projected coordinate system, buffer it to the appropriate radius, and then perform an intersection operation with the buffer transformed to the geographic coordinate system.
  • docs/ref/contrib/gis/testing.txt

     
     1======================
     2Testing GeoDjango Apps
     3======================
     4
     5Creating a spatial database may require extra steps.  To accommodate this,
     6GeoDjango includes a test runner that will scaffold a spatial database
     7automatically.  To have your tests utilize the runner, just configure
     8your ``TEST_RUNNER`` in your settings like the following::
     9
     10    TEST_RUNNER='django.contrib.gis.tests.run_tests'
     11
     12If you want to run GeoDjango's test suite (do *not* use for testing your
     13applications) then the runner would be configured like so::
     14
     15    TEST_RUNNER='django.contrib.gis.tests.run_gis_tests'
     16
     17.. note::
     18
     19    In order to create a spatial database, the ``DATABASE_USER`` setting
     20    (or ``TEST_DATABASE_USER``, if optionally defined on Oracle) requires
     21    elevated privileges.  When using PostGIS or MySQL, the database user
     22    must have at least the ability to create databases.  When testing on Oracle,
     23    the user should be a superuser.
     24
     25Besides configuring the ``TEST_RUNNER`` setting, there are other options
     26to consider depending on your spatial backend (no additional
     27options or configuration instructions for the Oracle or MySQL spatial
     28backends).
     29
     30PostGIS
     31=======
     32
     33.. note::
     34
     35    In addition to setting ``TEST_RUNNER`` as described above, the
     36    recommended way to test GeoDjango applications with PostGIS
     37    is to set :ref:`postgis_template` with the name of your
     38    `spatial database template`_.
     39
     40.. _spatial database template: install.html#creating-a-spatial-database-template-for-postgis
     41
     42Settings
     43--------
     44
     45``POSTGIS_SQL_PATH``
     46^^^^^^^^^^^^^^^^^^^^
     47
     48If not using the ``POSTGIS_TEMPLATE`` setting, the GeoDjango test runner
     49assumes that the PostGIS SQL files (``lwpostgis.sql`` and
     50``spatial_ref_sys.sql``) are installed in the directory specified by
     51the following command::
     52
     53    $ pg_config --sharedir
     54
     55If that command cannot be executed, the test runner will default to
     56``/usr/local/share``, unless this setting is configured with a
     57different location.  For example, some PostGIS packages for Ubuntu
     58put the files in a nonstandard location, and placing this in the
     59settings would allow GeoDjango to find the files::
     60
     61    POSTGIS_SQL_PATH='/usr/share/postgresql-8.3-postgis'
     62
     63.. _postgis_template:
     64
     65``POSTGIS_TEMPLATE``
     66^^^^^^^^^^^^^^^^^^^^
     67.. versionadded:: 1.1
     68
     69If you have a PostGIS template already, then just configure with the
     70name of the template in your settings, for example::
     71
     72    POSTGIS_TEMPLATE='template_postgis'
     73
     74``POSTGIS_VERSION``
     75^^^^^^^^^^^^^^^^^^^
     76.. versionadded:: 1.1
     77
     78When GeoDjango's spatial backend initializes on PostGIS, it has to perform
     79a SQL query to determine the version.  Setting the version manually
     80prevents this query to the database::
     81
     82    POSTGIS_VERSION=('1.3.6', 1, 3, 6)
     83
     84Obtaining Sufficient Privileges
     85-------------------------------
     86
     87Depending on your configuration, this section describes several methods to
     88configure a database user with sufficient privileges to run tests for
     89GeoDjango applications on PostgreSQL.  If your `spatial database template`_
     90was created like in the instructions, then your testing database user
     91only needs to have the ability to create databases.  In other configurations,
     92you may be required to use a superuser.
     93
     94Create Database User
     95^^^^^^^^^^^^^^^^^^^^
     96To make database user with the ability to create databases, use the
     97following command::
     98
     99    $ createuser --createdb -R -S <user_name>
     100
     101The ``-R -S`` flags indicate that we do not want the user to have the ability
     102to create additional users (roles) or to be a superuser, respectively.
     103
     104Alternatively, you may alter an existing user's role from the SQL shell
     105(assuming this is done from an existing superuser account)::
     106
     107    postgres# ALTER ROLE <user_name> CREATEDB NOSUPERUSER NOCREATEROLE;
     108
     109Create Database Superuser
     110^^^^^^^^^^^^^^^^^^^^^^^^^
     111This may be done at the time the user is created, for example::
     112
     113    $ createuser --superuser <user_name>
     114
     115Or you may alter the user's role from the SQL shell (assuming this
     116is done from an existing superuser account)::
     117
     118    postgres# ALTER ROLE <user_name> SUPERUSER;
     119
     120
     121Create Local PostgreSQL Database
     122^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     1231. Initialize database: ``initdb -D /path/to/user/db``
     124
     1252. If there's already a Postgres instance on the machine, it will need
     126   to use a different TCP port than 5432. Edit ``postgresql.conf`` (in
     127   ``/path/to/user/db``) to change the database port (e.g. ``port = 5433``).
     128
     1293. Start this database ``pg_ctl -D /path/to/user/db start``
     130
     131Windows
     132-------
     133On Windows platforms the pgAdmin III utility may also be used as
     134a simple way to add superuser privileges to your database user.
     135
     136By default, the PostGIS installer on Windows includes a template
     137spatial database.  Take advantage of it by adding this to your
     138settings::
     139
     140   POSTGIS_TEMPLATE='template_postgis'
     141
     142SpatiaLite
     143==========
     144.. versionadded:: 1.1
     145
     146You will need to download the `initialization SQL`__ script for SpatiaLite::
     147
     148    $ wget http://www.gaia-gis.it/spatialite/init_spatialite-2.3.zip
     149    $ unzip init_spatialite-2.3.zip
     150
     151If ``init_spatialite-2.3.sql`` is in the same path as your project's ``manage.py``
     152script and your ``TEST_RUNNER`` is set, then all you have to do is::
     153
     154    $ ./manage.py test
     155
     156Settings
     157--------
     158
     159``SPATIALITE_SQL``
     160^^^^^^^^^^^^^^^^^^
     161.. versionadded:: 1.1
     162
     163By default, the GeoDjango test runner looks for the SpatiaLite SQL in the
     164same directory where it was invoked (by default the same directory where
     165``manage.py`` is located).  If you want to use a different location, then
     166you may add the following to your settings::
     167
     168    SPATIALITE_SQL='/path/to/init_spatialite-2.3.sql'
     169
     170__ http://www.gaia-gis.it/spatialite/init_spatialite-2.3.zip
  • docs/ref/contrib/gis/deployment.txt

     
     1===================
     2Deploying GeoDjango
     3===================
     4
     5.. warning::
     6
     7    GeoDjango uses the GEOS and GDAL geospatial libraries which are
     8    not thread safe at this time.  Thus, it is *highly* recommended
     9    to not use threading when deploying -- in other words, use a
     10    prefork version of Apache or the prefork method when using FastCGI
     11    through another web server.
     12
     13Apache
     14======
     15In this section there are some example ``VirtualHost`` directives for
     16when deploying using either ``mod_python`` or ``mod_wsgi``.  At this
     17time, we recommend ``mod_wsgi``, as it is now officially recommended
     18way to deploy Django applications with Apache.  Moreover, if
     19``mod_python`` is used, then a prefork version of Apache must also be
     20used.  As long as ``mod_wsgi`` is configured correctly, it does not
     21matter whether the version of Apache is prefork or worker.
     22
     23.. note::
     24
     25    The ``Alias`` and ``Directory`` configurations in the the examples
     26    below use an example path to a system-wide installation folder of Django. 
     27    Substitute in an appropriate location, if necessary, as it may be
     28    different than the path on your system.
     29
     30``mod_wsgi``
     31------------
     32
     33Example::
     34
     35    <VirtualHost *:80>
     36      WSGIDaemonProcess geodjango user=geo group=geo processes=5 threads=1
     37      WSGIProcessGroup geodjango
     38      WSGIScriptAlias / /home/geo/geodjango/world.wsgi
     39 
     40      Alias /media/ "/usr/lib/python2.5/site-packages/django/contrib/admin/media/"
     41      <Directory "/usr/lib/python2.5/site-packages/django/contrib/admin/media/">
     42        Order allow,deny
     43        Options Indexes
     44        Allow from all
     45        IndexOptions FancyIndexing
     46      </Directory>
     47   
     48    </VirtualHost>
     49
     50.. warning::
     51
     52    If the ``WSGIDaemonProcess`` attribute ``threads`` is not set to ``1``, then
     53    Apache may crash when running your GeoDjango application.  Increase the
     54    number of ``processes`` instead.
     55
     56For more information, please consult Django's `mod_wsgi documentation`__.
     57
     58__ http://docs.djangoproject.com/en/dev/howto/deployment/modwsgi/
     59
     60
     61``mod_python``
     62--------------
     63
     64Example::
     65
     66    <VirtualHost *:80>
     67   
     68      <Location "/">
     69        SetHandler mod_python
     70        PythonHandler django.core.handlers.modpython
     71        SetEnv DJANGO_SETTINGS_MODULE world.settings
     72        PythonDebug On
     73        PythonPath "['/var/www/apps'] + sys.path"
     74      </Location>
     75   
     76      Alias /media/ "/usr/lib/python2.5/site-packages/django/contrib/admin/media/"
     77      <Location "/media">
     78        SetHandler None
     79      </Location>
     80   
     81    </VirtualHost>
     82
     83.. warning::
     84
     85   When using ``mod_python`` you must be using a prefork version of Apache, or
     86   else your GeoDjango application may crash Apache.
     87
     88For more information, please consult Django's `mod_python documentation`__.
     89
     90__ http://docs.djangoproject.com/en/dev/howto/deployment/modpython/
     91
     92Lighttpd
     93========
     94
     95FastCGI
     96-------
     97
     98Nginx
     99=====
     100
     101FastCGI
     102-------
  • docs/ref/contrib/gis/create_template_postgis-debian.sh

     
     1#!/usr/bin/env bash
     2POSTGIS_SQL_PATH=/usr/share/postgresql-8.3-postgis
     3createdb -E UTF8 template_postgis # Create the template spatial database.
     4createlang -d template_postgis plpgsql # Adding PLPGSQL language support.
     5psql -d postgres -c "UPDATE pg_database SET datistemplate='true' WHERE datname='template_postgis';"
     6psql -d template_postgis -f $POSTGIS_SQL_PATH/lwpostgis.sql # Loading the PostGIS SQL routines
     7psql -d template_postgis -f $POSTGIS_SQL_PATH/spatial_ref_sys.sql
     8psql -d template_postgis -c "GRANT ALL ON geometry_columns TO PUBLIC;" # Enabling users to alter spatial tables.
     9psql -d template_postgis -c "GRANT ALL ON spatial_ref_sys TO PUBLIC;"
  • docs/ref/contrib/gis/sitemaps.txt

     
     1===================
     2Geographic Sitemaps
     3===================
     4
     5Google's sitemap protocol has been recently extended to support geospatial
     6content. [#]_   This includes the addition of the ``<url>`` child element
     7``<geo:geo>``, which tells Google that the content located at the URL is
     8geographic in nature. [#]_
     9
     10Example
     11=======
     12
     13Reference
     14=========
     15
     16``KMLSitemap``
     17--------------
     18
     19``KMZSitemap``
     20--------------
     21
     22``GeoRSSSitemap``
     23-----------------
     24
     25.. rubric:: Footnotes
     26.. [#] Google, Inc., `What is a Geo Sitemap? <http://www.google.com/support/webmasters/bin/answer.py?answer=94554>`_.
     27.. [#] Google, Inc., `Submit Your Geo Content to Google <http://code.google.com/apis/kml/documentation/kmlSearch.html>`_.
  • docs/ref/contrib/gis/feeds.txt

     
     1================
     2Geographic Feeds
     3================
     4
     5GeoDjango has its own ``Feed`` subclass that may embed location information
     6in RSS/Atom feeds formatted according to either the `Simple GeoRSS`__ or
     7`W3C Geo`_ standards.  Because GeoDjango's syndication API is a superset of
     8Django's, please consult `Django's syndication documentation`__ for details
     9on general usage.
     10
     11.. _W3C Geo: http://www.w3.org/2003/01/geo/
     12
     13__ http://georss.org/1.0#simple
     14__ http://docs.djangoproject.com/en/dev/ref/contrib/syndication/
     15
     16Example
     17=======
     18
     19API Reference
     20=============
     21
     22``Feed`` Subclass
     23-----------------
     24
     25In addition to methods provided by `base class`__ GeoDjango's ``Feed``
     26class (from ``django.contrib.gis.feeds``) provides the following overrides.
     27Note that these overrides may be done in multiple ways::
     28
     29    from django.contrib.gis.feeds import Feed
     30
     31    class MyFeed(Feed):
     32
     33         # First, as a class attribute.
     34         geometry = ...
     35         item_geometry = ...
     36
     37         # Also a function with no arguments
     38         def geometry(self):
     39             ...
     40
     41         def item_geometry(self):
     42             ...
     43
     44         # And as a function with a single argument
     45         def geometry(self, obj):
     46             ...
     47
     48         def item_geometry(self, item):
     49             ...
     50
     51__ http://docs.djangoproject.com/en/dev/ref/contrib/syndication/#django.contrib.syndication.django.contrib.syndication.feeds.Feed
     52
     53``Feed.geometry(obj)``
     54^^^^^^^^^^^^^^^^^^^^^^
     55
     56Takes the object returned by ``get_object()`` and returns the *feed's*
     57geometry.  Typically this is a ``GEOSGeometry`` instance, or can be a
     58tuple to represent a point or a box.  For example::
     59
     60    class ZipcodeFeed(Feed):
     61
     62        def geometry(self, obj):
     63            # Can also return: `obj.poly`, and `obj.poly.centroid`.
     64            return obj.poly.extent # tuple like: (X0, Y0, X1, Y1).
     65
     66``Feed.item_geometry(item)``
     67^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     68
     69Set this to return the geometry for each *item* in the feed.  This
     70can be a ``GEOSGeometry`` instance, or a tuple that represents a
     71point coordinate or bounding box.  For example::
     72
     73    class ZipcodeFeed(Feed):
     74
     75        def item_geometry(self, obj):
     76            # Returns the polygon.
     77            return obj.poly
     78
     79``SyndicationFeed`` Subclasses
     80------------------------------
     81
     82``GeoRSSFeed``
     83^^^^^^^^^^^^^^
     84
     85``GeoAtom1Feed``
     86^^^^^^^^^^^^^^^^
     87
     88``W3CGeoFeed``
     89^^^^^^^^^^^^^^
     90
     91.. note::
     92
     93    `W3C Geo`_ formatted feeds only support point geometries.
  • docs/ref/contrib/gis/layermapping.txt

     
     1.. _ref-layermapping:
     2
     3====================================
     4``LayerMapping`` data import utility
     5====================================
     6
     7.. module:: django.contrib.gis.utils.layermapping
     8   :synopsis: Spatial data import utility for GeoDjango models.
     9
     10.. currentmodule:: django.contrib.gis.utils
     11
     12The :class:`LayerMapping` class provides a way to map the contents of
     13vector spatial data files (e.g. shapefiles) intoto GeoDjango models.
     14
     15This utility grew out of the author's personal needs to eliminate
     16the code repetition that went into pulling geometries and fields out of
     17a vector layer, converting to another coordinate system (e.g. WGS84), and
     18then inserting into a GeoDjango model.
     19
     20.. note::
     21
     22    Use of :class:`LayerMapping` requires GDAL.
     23
     24.. warning ::
     25
     26    GIS data sources, like shapefiles, may be very large.  If you find
     27    that :class:`LayerMapping` is using too much memory, set
     28    ``DEBUG=False`` in your settings.  When ``DEBUG=True`` Django automatically
     29    logs *every* SQL query -- thus, when SQL statements contain geometries, it is
     30    easy to consume more memory than usual.
     31
     32Example
     33=======
     34
     351. You need a GDAL-supported data source, like a shapefile (here we're using
     36   a simple polygon shapefile, ``test_poly.shp``, with three features)::
     37
     38    >>> from django.contrib.gis.gdal import DataSource
     39    >>> ds = DataSource('test_poly.shp')
     40    >>> layer = ds[0]
     41    >>> print layer.fields # Exploring the fields in the layer, we only want the 'str' field.
     42    ['float', 'int', 'str']
     43    >>> print len(layer) # getting the number of features in the layer (should be 3)
     44    3
     45    >>> print layer.geom_type # Should be 3 (a Polygon)
     46    Polygon
     47    >>> print layer.srs # WGS84 in WKT
     48    GEOGCS["GCS_WGS_1984",
     49        DATUM["WGS_1984",
     50            SPHEROID["WGS_1984",6378137,298.257223563]],
     51        PRIMEM["Greenwich",0],
     52        UNIT["Degree",0.017453292519943295]]   
     53
     542. Now we define our corresponding Django model (make sure to use ``syncdb``)::
     55
     56    from django.contrib.gis.db import models
     57
     58    class TestGeo(models.Model):
     59        name = models.CharField(max_length=25) # corresponds to the 'str' field
     60        poly = models.PolygonField(srid=4269) # we want our model in a different SRID
     61        objects = models.GeoManager()
     62        def __unicode__(self):
     63            return 'Name: %s' % self.name
     64
     653. Use :class:`LayerMapping` to extract all the features and place them in the
     66   database::
     67
     68    >>> from django.contrib.gis.utils import LayerMapping
     69    >>> from geoapp.models import TestGeo
     70    >>> mapping = {'name' : 'str', # The 'name' model field maps to the 'str' layer field.
     71                   'poly' : 'POLYGON', # For geometry fields use OGC name.
     72                   } # The mapping is a dictionary
     73    >>> lm = LayerMapping(TestGeo, 'test_poly.shp', mapping)
     74    >>> lm.save(verbose=True) # Save the layermap, imports the data.
     75    Saved: Name: 1
     76    Saved: Name: 2
     77    Saved: Name: 3
     78
     79Here, :class:`LayerMapping` just transformed the three geometries from the
     80shapefile in their original spatial reference system (WGS84) to the spatial
     81reference system of the GeoDjango model (NAD83).  If no spatial reference
     82system is defined for the layer, use the ``source_srs`` keyword with a
     83:class:`django.contrib.gis.gdal.SpatialReference` object to specify one.
     84
     85``LayerMapping`` API
     86====================
     87
     88.. class:: LayerMapping(model, data_source, mapping[, layer=0, source_srs=None, encoding=None, transaction_mode='commit_on_success', transform=True, unique=True, using='default'])
     89
     90The following are the arguments and keywords that may be used during
     91instantiation of ``LayerMapping`` objects.
     92
     93=================  =========================================================
     94Argument           Description
     95=================  =========================================================
     96``model``          The geographic model, *not* an instance.
     97
     98``data_source``    The path to the OGR-supported data source file
     99                   (e.g., a shapefile).  Also accepts
     100                   :class:`django.contrib.gis.gdal.DataSource` instances.
     101
     102``mapping``        A dictionary: keys are strings corresponding to
     103                   the model field, and values correspond to
     104                   string field names for the OGR feature, or if the
     105                   model field is a geographic then it should
     106                   correspond to the OGR geometry type,
     107                   e.g., ``'POINT'``, ``'LINESTRING'``, ``'POLYGON'``.
     108=================  ========================================================= 
     109
     110=====================  =====================================================
     111Keyword Arguments
     112=====================  ===================================================== 
     113``layer``              The index of the layer to use from the Data Source
     114                       (defaults to 0)
     115   
     116``source_srs``         Use this to specify the source SRS manually (for
     117                       example, some shapefiles don't come with a '.prj'
     118                       file).  An integer SRID, WKT or PROJ.4 strings, and
     119                       :class:`django.contrib.gis.gdal.SpatialReference`
     120                       objects are accepted.
     121   
     122``encoding``           Specifies the character set encoding of the strings
     123                       in the OGR data source.  For example, ``'latin-1'``,
     124                       ``'utf-8'``, and ``'cp437'`` are all valid encoding
     125                       parameters.
     126   
     127``transaction_mode``   May be ``'commit_on_success'`` (default) or
     128                       ``'autocommit'``.
     129   
     130``transform``          Setting this to False will disable coordinate
     131                       transformations.  In other words, geometries will
     132                       be inserted into the database unmodified from their
     133                       original state in the data source.
     134   
     135``unique``             Setting this to the name, or a tuple of names,
     136                       from the given  model will create models unique
     137                       only to the given name(s). Geometries will from
     138                       each feature will be added into the collection
     139                       associated with the unique model.  Forces
     140                       the transaction mode to be ``'autocommit'``.
     141
     142``using``              New in version 1.2.  Sets the database to use when
     143                       importing spatial data.  Default is ``'default'``
     144=====================  ===================================================== 
     145
     146``save()`` Keyword Arguments
     147----------------------------
     148
     149.. method:: LayerMapping.save([verbose=False, fid_range=False, step=False, progress=False, silent=False, stream=sys.stdout, strict=False])
     150
     151The ``save()`` method also accepts keywords.  These keywords are
     152used for controlling output logging, error handling, and for importing
     153specific feature ranges.
     154
     155===========================  =================================================
     156Save Keyword Arguments       Description
     157===========================  =================================================
     158``fid_range``                May be set with a slice or tuple of
     159                             (begin, end) feature ID's to map from
     160                             the data source.  In other words, this
     161                             keyword enables the user to selectively
     162                             import a subset range of features in the
     163                             geographic data source.
     164
     165``progress``                 When this keyword is set, status information
     166                             will be printed giving the number of features
     167                             processed and successfully saved.  By default,
     168                             progress information will be printed every 1000
     169                             features processed, however, this default may
     170                             be overridden by setting this keyword with an
     171                             integer for the desired interval.
     172
     173``silent``                   By default, non-fatal error notifications are
     174                             printed to ``sys.stdout``, but this keyword may
     175                             be set to disable these notifications.
     176
     177``step``                     If set with an integer, transactions will
     178                             occur at every step interval. For example, if
     179                             ``step=1000``, a commit would occur after the
     180                             1,000th feature, the 2,000th feature etc.
     181
     182
     183``stream``                   Status information will be written to this file
     184                             handle.  Defaults to using ``sys.stdout``, but
     185                             any object with a ``write`` method is supported.
     186
     187``strict``                   Execution of the model mapping will cease upon
     188                             the first error encountered.  The default value
     189                             (``False``)
     190                             behavior is to attempt to continue.
     191
     192``verbose``                  If set, information will be printed
     193                             subsequent to each model save
     194                             executed on the database.
     195===========================  =================================================
     196
     197Troubleshooting
     198===============
     199
     200Running out of memory
     201---------------------
     202
     203As noted in the warning at the top of this section, Django stores all SQL
     204queries when ``DEBUG=True``.  Set ``DEBUG=False`` in your settings, and this
     205should stop excessive memory use when running ``LayerMapping`` scripts.
     206
     207MySQL: ``max_allowed_packet`` error
     208-----------------------------------
     209
     210If you encounter the following error when using ``LayerMapping`` and MySQL::
     211
     212    OperationalError: (1153, "Got a packet bigger than 'max_allowed_packet' bytes")
     213
     214Then the solution is to increase the value of the ``max_allowed_packet``
     215setting in your MySQL configuration.  For example, the default value may
     216be something low like one megabyte -- the setting may be modified in MySQL's
     217configuration file (``my.cnf``) in the ``[mysqld]`` section::
     218
     219    max_allowed_packet = 10M
  • docs/ref/contrib/gis/db-api.txt

     
     1.. _ref-gis-db-api:
     2
     3======================
     4GeoDjango Database API
     5======================
     6
     7.. currentmodule:: django.contrib.gis.db.models
     8
     9GeoDjango's lookup types may be used with any manager method like
     10``filter()``, ``exclude()``, etc.  However, the lookup types unique to
     11GeoDjango are only available with geographic fields.
     12Filters on 'normal' fields (e.g. ``CharField``) may be chained with those on
     13geographic fields.  Thus, geographic queries take the following form (assuming
     14the ``Zipcode`` model used in the :ref:`ref-gis-model-api`)::
     15
     16    >>> qs = Zipcode.objects.filter(<field>__<lookup_type>=<parameter>)
     17    >>> qs = Zipcode.objects.exclude(...)
     18
     19For example::
     20
     21    >>> qs = Zipcode.objects.filter(poly__contains=pnt)
     22
     23In this case, ``poly`` is the geographic field, ``contains`` is the lookup type,
     24and ``pnt`` is the parameter (which may be a ``GEOSGeometry`` object or a string
     25of GeoJSON , WKT, or HEXEWKB).
     26
     27.. note::
     28
     29    GeoDjango constructs spatial SQL with the ``GeoQuerySet``, a
     30    subclass of Django's ``QuerySet``.  The ``GeoManager`` instance
     31    attached to your model allows it to use ``GeoQuerySet``.
     32
     33Creating and Saving Geographic Models
     34=====================================
     35Here is an example of how to create a geometry object (assuming the ``Zipcode``
     36model)::
     37
     38    >>> from zipcode.models import Zipcode
     39    >>> z = Zipcode(code=77096, poly='POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))')
     40    >>> z.save()
     41
     42`GEOS geometry objects`_ may also be used to save geometric models::
     43
     44    >>> from django.contrib.gis.geos import GEOSGeometry
     45    >>> z = Zipcode(code=77096, poly=GEOSGeometry('POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))'))
     46    >>> z.save()
     47
     48Moreover, if the ``GEOSGeometry`` is in a different coordinate system (has a
     49different SRID value) than that of the field, then it will be implicitly
     50transformed into the SRID of the model's field, using the spatial database's
     51transform procedure::
     52
     53    >>> poly_3084 = GEOSGeometry('POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))', srid=3084)  # SRID 3084 is 'NAD83(HARN) / Texas Centric Lambert Conformal'
     54    >>> z = Zipcode(code=78212, poly=poly_3084)
     55    >>> z.save()
     56    >>> from django.db import connection
     57    >>> print connection.queries[-1]['sql'] # printing the last SQL statement executed (requires DEBUG=True)
     58    INSERT INTO "geoapp_zipcode" ("code", "poly") VALUES (78212, ST_Transform(ST_GeomFromWKB('\\001 ... ', 3084), 4326))
     59
     60Thus, geometry parameters may be passed in using the ``GEOSGeometry`` object, WKT
     61(Well Known Text [#]_), HEXEWKB (PostGIS specific -- a WKB geometry in
     62hexadecimal [#]_), and GeoJSON [#]_ (requires GDAL).  Essentially, if the input is not a
     63``GEOSGeometry`` object, the geometry field will attempt to create a ``GEOSGeometry``
     64instance from the input.
     65
     66Below are some examples of GEOS Geometry objects, WKT, and HEXEWKB, and
     67GeoJSON:
     68
     69* GEOS Geometry::
     70
     71    >>> from django.contrib.gis.geos import *
     72    >>> pnt  = Point(5, 23)
     73    >>> ls   = LineString((0, 0), (5, 23))
     74    >>> poly = GEOSGeometry('POLYGON (( 10 10, 10 20, 20 20, 20 15, 10 10))')
     75
     76* WKT Polygon: ``'POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))'``
     77* HEXEWKB Polygon : ``'0103000000010000000 ... 00000000000002440'``
     78* GeoJSON Point: ``{ "type": "Point", "coordinates": [100.0, 0.0] }``
     79
     80.. _GEOS geometry objects: geos.html
     81
     82Spatial Lookup Types
     83====================
     84
     85PostGIS
     86-------
     87
     88Spatial Operators
     89^^^^^^^^^^^^^^^^^
     90
     91The following lookup types correspond to PostGIS spatial operators. [#]_
     92
     93    :lookup:`bbcontains`
     94        Tests if the geometry field's bounding box completely contains the lookup
     95        geometry's bounding box.
     96
     97        Example::
     98
     99            Zipcode.objects.filter(poly__bbcontains=geom)
     100
     101        PostGIS equivalent::
     102 
     103            SELECT ... WHERE poly ~ geom
     104
     105    :lookup:`bboverlaps`
     106        Tests if the geometry field's bounding box overlaps the lookup geometry's
     107        bounding box.
     108
     109        Example::
     110
     111            Zipcode.objects.filter(poly__bboverlaps=geom)
     112
     113        PostGIS equivalent::
     114
     115            SELECT ... WHERE poly && geom
     116
     117    :lookup:`contained`
     118        Tests if the geometry field's bounding box is completely contained by the
     119        lookup geometry's bounding box.
     120
     121        Example::
     122
     123            Zipcode.objects.filter(poly__contained=geom)
     124
     125        PostGIS equivalent::
     126
     127            SELECT ... WHERE poly @ geom
     128
     129    :lookup:`exact` or :lookup:`same_as`
     130        Tests actual geometric equality of the geometry field against the the given
     131        lookup geometry, vertex-by-vertex.
     132
     133        The following examples are equivalent::
     134
     135            Zipcode.objects.filter(poly__exact=geom)
     136            Zipcode.objects.filter(poly=geom)
     137            Zipcode.objects.filter(poly__same_as=geom)
     138
     139        PostGIS equivalent::
     140
     141            SELECT ... WHERE poly ~= geom
     142
     143    :lookup:`left`
     144        Tests if the geometry field's bounding box is strictly to the left of the
     145        lookup geometry's bounding box.
     146
     147        Example::
     148
     149            Zipcode.objects.filter(poly__left=geom)
     150
     151        PostGIS equivalent::
     152
     153            SELECT ... WHERE poly << geom
     154
     155    :lookup:`right`
     156        Tests if the geometry field's bounding box is strictly to the right of the
     157        lookup geometry's bounding box.
     158
     159        Example::
     160
     161            Zipcode.objects.filter(poly__right=geom)
     162
     163        PostGIS equivalent::
     164
     165            SELECT ... WHERE poly >> geom
     166
     167    :lookup:`overlaps_left`
     168        Tests if the geometry field's bounding box overlaps or is to the left of the lookup
     169        geometry's bounding box.
     170
     171        Example::
     172
     173            Zipcode.objects.filter(poly__overlaps_left=geom)
     174
     175        PostGIS equivalent::
     176
     177            SELECT ... WHERE poly &< geom
     178
     179    :lookup:`overlaps_right`
     180        Tests if the geometry field's bounding box overlaps or is to the right of the lookup
     181        geometry's bounding box.
     182
     183        Example::
     184
     185            Zipcode.objects.filter(poly__overlaps_right=geom)
     186
     187        PostGIS equivalent::
     188
     189            SELECT ... WHERE poly &> geom
     190
     191    :lookup:`overlaps_above`
     192        Tests if the geometry field's bounding box overlaps or is above the lookup
     193        geometry's bounding box.
     194
     195        Example::
     196
     197            Zipcode.objects.filter(poly__overlaps_above=geom)
     198
     199        PostGIS equivalent::
     200
     201            SELECT ... WHERE poly |&> geom
     202
     203    :lookup:`overlaps_below`
     204        Tests if the geometry field's bounding box overlaps or is below the lookup
     205        geometry's bounding box.
     206
     207        Example::
     208
     209            Zipcode.objects.filter(poly__overlaps_below=geom)
     210
     211        PostGIS equivalent::
     212
     213            SELECT ... WHERE poly &<| geom
     214
     215    :lookup:`strictly_above`
     216        Tests if the geometry field's bounding box is strictly above the lookup
     217        geometry's bounding box.
     218
     219        Example::
     220
     221            Zipcode.objects.filter(poly__strictly_above=geom)
     222
     223        PostGIS equivalent::
     224
     225            SELECT ... WHERE poly |>> geom
     226
     227    :lookup:`strictly_below`
     228        Tests if the geometry field's bounding box is strictly below the lookup
     229        geometry's bounding box.
     230
     231        Example::
     232
     233            Zipcode.objects.filter(poly__strictly_below=geom)
     234
     235        PostGIS equivalent::
     236
     237            SELECT ... WHERE poly <<| geom
     238
     239Geometry Relationship Functions
     240^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     241
     242The following lookup types correspond to PostGIS geometry relationship
     243functions. [#]_  Please note that when using PostGIS 1.3.1 and above, index
     244support is automatically "inlined" -- in other words, the bounding box
     245equivalent is automatically evaluated prior to calling these, more
     246computationally expensive, functions.
     247
     248    :lookup:`contains`
     249        Tests if the geometry field spatially contains the lookup geometry.
     250
     251        Example::
     252
     253            Zipcode.objects.filter(poly__contains=geom)
     254
     255        PostGIS equivalent::
     256
     257            SELECT ... WHERE ST_Contains(poly, geom)
     258
     259    :lookup:`coveredby`
     260        Tests if no point in the geometry field is outside the lookup geometry. [#]_
     261        Only available in PostGIS 1.3.1 and above.
     262
     263        Example::
     264
     265            Zipcode.objects.filter(poly__coveredby=geom)
     266
     267        PostGIS equivalent::
     268
     269            SELECT ... WHERE ST_CoveredBy(poly, geom)
     270
     271    :lookup:`covers`
     272        Tests if no point in the lookup geometry is outside the geometry field. [#]_
     273        Only available in PostGIS 1.3.1 and above.
     274
     275        Example::
     276
     277            Zipcode.objects.filter(poly__covers=geom)
     278
     279        PostGIS equivalent::
     280
     281            SELECT ... WHERE ST_Covers(poly, geom)
     282
     283    :lookup:`crosses`
     284        Tests if the geometry field spatially crosses the lookup geometry.
     285
     286        Example::
     287
     288            Zipcode.objects.filter(poly__crosses=geom)
     289
     290        PostGIS equivalent::
     291
     292            SELECT ... WHERE ST_Crosses(poly, geom)
     293
     294    :lookup:`disjoint`
     295        Tests if the geometry field is spatially disjoint from the lookup geometry.
     296
     297        Example::
     298
     299            Zipcode.objects.filter(poly__disjoint=geom)
     300
     301        PostGIS equivalent::
     302
     303            SELECT ... WHERE ST_Disjoint(poly, geom)
     304
     305.. _dwithin_postgis:
     306
     307    :lookup:`dwithin`
     308        Tests if the geometry field is within the specified distance of the lookup
     309        geometry; uses indexes if available.  The lookup parameter is a two-element
     310        tuple: ``(geom, distance)``, where ``distance`` is a ``Distance`` object or a
     311        numeric value in units.   Only available in PostGIS versions 1.3.1 and above.
     312
     313        .. admonition:: Distance Parameters and Geographic Coordinate Systems
     314
     315            The ``dwithin`` lookup is meant for projected coordinate systems
     316            because PostGIS uses ``ST_Distance``, which calculates the
     317            Cartesian distance between geometries.  In other words,
     318            this will not return accurate results for geographic coordinate
     319            systems such as WGS84.  Thus, an exception will be raised if a
     320            ``Distance`` object is used on a geometry field in a geographic
     321            coordinate system.
     322           
     323            However, a numeric value is allowed for geometry fields in geographic
     324            coordinate systems.  This advanced usage allows users to limit
     325            querysets by distance more efficiently using units of degrees.
     326
     327        Example::
     328
     329            # If Zipcode uses a projected coordinate system, this is allowed.
     330            Zipcode.objects.filter(poly__dwithin=(geom, D(mi=5)))
     331
     332            # If Zipcode uses a geographic coordinate system, then the
     333            # distance unit must be a numeric value in units of degrees.
     334            Zipcode.objects.filter(poly__dwithin=(geom, 0.5))
     335
     336        PostGIS equivalent::
     337
     338            SELECT ... WHERE ST_DWithin(poly, geom, <units value>)
     339
     340    :lookup:`equals`
     341        Tests if the geometry field is spatially equal to the lookup geometry.
     342
     343        Example::
     344
     345            Zipcode.objects.filter(poly__equals=geom)
     346
     347        PostGIS equivalent::
     348
     349            SELECT ... WHERE ST_Equals(poly, geom)
     350
     351    :lookup:`intersects`
     352        Tests if the geometry field spatially intersects the lookup geometry.
     353
     354        Example::
     355
     356            Zipcode.objects.filter(poly__intersects=geom)
     357
     358        PostGIS equivalent::
     359
     360            SELECT ... WHERE ST_Intersects(poly, geom)
     361
     362    :lookup:`overlaps`
     363        Tests if the geometry field spatially overlaps the lookup geometry.
     364
     365        Example::
     366
     367            Zipcode.objects.filter(poly__overlaps=geom)
     368
     369        PostGIS equivalent::
     370
     371            SELECT ... WHERE ST_Overlaps(poly, geom)
     372
     373    :lookup:`relate`
     374        Tests if the geometry field is spatially related to the the lookup geometry by
     375        the values given in the intersection pattern matrix.  The intersection pattern
     376        matrix is a string comprising nine characters, which  define intersections between
     377        the interior, boundary, and exterior of the geometry field and the lookup geometry. 
     378        The intersection pattern matrix may only use the following characters:
     379        ``1``, ``2``, ``T``, ``F``, or ``*``.  This lookup type allows users to "fine tune"
     380        a specific geometric relationship consistent with the DE-9IM model. [#]_
     381
     382        Example::
     383
     384            # A tuple lookup parameter is used to specify the geometry and
     385            # the intersection pattern (the pattern here is for 'contains').
     386            Zipcode.objects.filter(poly__relate(geom, 'T*T***FF*'))
     387
     388        PostGIS equivalent::
     389
     390            SELECT ... WHERE ST_Relate(poly, geom, 'T*T***FF*')
     391
     392    :lookup:`touches`
     393        Tests if the geometry field spatially touches the lookup geometry.
     394
     395        Example::
     396
     397            Zipcode.objects.filter(poly__touches=geom)
     398
     399        PostGIS equivalent::
     400
     401            SELECT ... WHERE ST_Touches(poly, geom)
     402
     403    :lookup:`within`
     404        Tests if the geometry field is spatially within the lookup geometry.
     405
     406        Example::
     407
     408            Zipcode.objects.filter(poly__within=geom)
     409
     410        PostGIS equivalent::
     411
     412            SELECT ... WHERE ST_Within(poly, geom)
     413
     414
     415Oracle
     416------
     417For more information, see Oracle's `Spatial Operators`__ documentation. [#]_
     418
     419__ http://download.oracle.com/docs/html/B14255_01/sdo_operat.htm
     420
     421    :lookup:`contains`
     422        Tests if the geometry field spatially contains the lookup geometry.
     423
     424        Example::
     425
     426            Zipcode.objects.filter(poly__contains=geom)
     427
     428        Oracle equivalent::
     429
     430            SELECT ... WHERE SDO_CONTAINS(poly, geom)
     431
     432    :lookup:`covers`
     433        Tests if no point in the lookup geometry is outside the geometry field.
     434
     435        Oracle equivalent::
     436
     437            SELECT ... WHERE SDO_COVERS(poly, geom)
     438 
     439    :lookup:`coveredby`
     440        Tests if no point in the geometry field is outside the lookup geometry.
     441
     442        Oracle equivalent::
     443
     444            SELECT ... WHERE SDO_COVEREDBY(poly, geom)
     445 
     446    :lookup:`disjoint`
     447        Tests if the geometry field is spatially disjoint from the lookup geometry.
     448
     449        Oracle equivalent::
     450
     451            SELECT ... WHERE SDO_GEOM.RELATE(poly, 'DISJOINT', geom, 0.05)
     452
     453    :lookup:`dwithin`
     454        Tests if the geometry field is within the specified distance of the lookup
     455        geometry; uses indexes if available.  The lookup parameter is a two-element
     456        tuple: ``(geom, distance)``, where ``distance`` is a ``Distance`` object or a
     457        numeric value in units.
     458
     459        Oracle equivalent::
     460
     461            SELECT ... WHERE SDO_WITHIN_DISTANCE(poly, geom, 'distance=distance')
     462
     463    :lookup:`equals`, :lookup:`exact`, :lookup:`same_as`
     464        Tests if the geometry field is spatially equal to the lookup geometry.
     465        The following examples are equivalent on Oracle::
     466
     467            Zipcode.objects.filter(poly=geom)
     468            Zipcode.objects.filter(poly__exact=geom)
     469            Zipcode.objects.filter(poly__equals=geom)
     470            Zipcode.objects.filter(poly__same_as=geom)
     471
     472        Oracle equivalent::
     473
     474            SELECT ... WHERE SDO_EQUALS(poly, geom)
     475
     476    :lookup:`intersects`
     477        Tests if the geometry field spatially intersects the lookup geometry.
     478
     479        Oracle equivalent::
     480
     481            SELECT ... WHERE SDO_OVERLAPBDYINTERSECT(poly, geom)
     482
     483    :lookup:`overlaps`
     484        Tests if the geometry field spatially overlaps the lookup geometry.
     485
     486        Oracle equivalent::
     487
     488            SELECT ... WHERE SDO_OVERLAPS(poly, geom)
     489
     490    :lookup:`relate`
     491        Tests if the geometry field is spatially related to the the lookup geometry by
     492        the given mask component.  This lookup requires a tuple parameter,
     493        ``(geom, mask)``, where ``mask`` is at least one of the nine-intersection
     494        patterns: ``TOUCH``, ``OVERLAPBDYDISJOINT``, ``OVERLAPBDYINTERSECT``,
     495        ``EQUAL``, ``INSIDE``, ``COVEREDBY``, ``CONTAINS``, ``COVERS``, ``ANYINTERACT``,
     496        and ``ON``.  Multiple masks may be combined with the logical Boolean operator
     497        OR, for example, ``'inside+touch'``. [#]_  The mask relation strings are
     498        case-insensitive.
     499
     500        Example::
     501
     502            # A tuple lookup parameter is used to specify the geometry and
     503            # the mask component.
     504            Zipcode.objects.filter(poly__relate(geom, 'anyinteract'))
     505
     506        Oracle equivalent::
     507
     508            SELECT ... WHERE SDO_RELATE(poly, geom, 'anyinteract')
     509   
     510    :lookup:`touches`
     511        Tests if the geometry field spatially touches the lookup geometry.
     512
     513        Oracle equivalent::
     514
     515            SELECT ... WHERE SDO_TOUCH(poly, geom)
     516
     517    :lookup:`within`
     518        Tests if the geometry field is spatially within (inside) the lookup
     519        geometry.
     520
     521        Oracle equivalent::
     522
     523            SELECT ... WHERE SDO_INSIDE(poly, geom)
     524
     525MySQL
     526-----
     527For more information, see `Relations on Geometry Minimal Bounding Rectangles (MBRs)`__. [#]_
     528
     529__ http://dev.mysql.com/doc/refman/5.0/en/relations-on-geometry-mbr.html
     530
     531    :lookup:`bbcontains`, :lookup:`contains`
     532        * MySQL equivalent ``MBRContains(g1, g2)``
     533
     534    :lookup:`contained`, :lookup:`within`
     535        * MySQL equivalent ``MBRWithin(g1, g2)``
     536
     537    :lookup:`disjoint`
     538        * MySQL equivalent ``MBRDisjoint(g1, g2)``
     539
     540    :lookup:`equals`, :lookup:`exact`, :lookup:`same_as`
     541        * MySQL equivalent ``MBREqual(g1, g2)``
     542
     543    :lookup:`intersects`
     544        * MySQL equivalent ``MBRIntersects(g1, g2)``
     545
     546    :lookup:`overlaps`
     547        * MySQL equivalent ``MBROverlaps(g1, g2)``
     548
     549    :lookup:`touches`
     550        * MySQL equivalent ``MBRTouches(g1, g2)``
     551
     552SpatiaLite
     553----------
     554
     555For more information consult the `SpatiaLite SQL functions reference list`__.
     556
     557__ http://www.gaia-gis.it/spatialite/spatialite-sql-2.3.1.html
     558
     559    :lookup:`bbcontains`
     560        * SpatiaLite equivalient ``MbrContains(g1, g2)``
     561
     562    :lookup:`bboverlaps`
     563        * SpatiaLite equivalent ``MbrOverlaps(g1, g2)``
     564
     565    :lookup:`contained`
     566        * SpatiaLite equivalent ``MbrWithin(g1, g2)``
     567
     568    :lookup:`contains`
     569        * SpatiaLite equivalent ``Contains(g1, g2)``
     570
     571    :lookup:`crosses`
     572        * SpatiaLite equivalent ``Crosses(g1, g2)``
     573
     574    :lookup:`disjoint`
     575        * SpatiaLite equivalent ``Disjoint(g1, g2)``
     576
     577    :lookup:`equals`, :lookup:`exact`, :lookup:`same_as`
     578        * SpatiaLite equivalent ``Equals(g1, g2)``
     579
     580    :lookup:`intersects`
     581        * SpatiaLite equivalent ``Intersects(g1, g2)``
     582
     583    :lookup:`overlaps`
     584        * SpatiaLite equivalent ``Overlaps(g1, g2)``
     585
     586    :lookup:`relate`
     587        * SpatiaLite equivalent ``Relate(geom, pattern)``
     588
     589    :lookup:`touches`
     590        * SpatiaLite equivalent ``Touches(g1, g2)``
     591
     592    :lookup:`within`
     593        * SpatiaLite equivalent ``Within(g1, g2)``
     594
     595
     596Distance Queries
     597================
     598
     599Introduction
     600------------
     601Distance calculations with spatial data is tricky because, unfortunately,
     602the Earth is not flat.  Some distance queries with fields in a geographic
     603coordinate system may have to be expressed differently because of
     604limitations in PostGIS.  Please see the `Selecting an SRID`_ section in the
     605model API documentation for more details.
     606
     607.. _Selecting an SRID: model-api.html#selecting-an-srid
     608
     609Distance Lookups
     610----------------
     611*Availability*: PostGIS, Oracle, SpatiaLite
     612
     613Distance lookups take a tuple parameter comprising:
     614
     615#. A geometry to base calculations from; and
     616#. A number or ``Distance`` object containing the distance.
     617
     618If a ``Distance`` [#]_ object is used, it may be expressed in
     619any units (the SQL generated will use units converted to those of the field);
     620otherwise, numeric parameters will be assumed to be in the units of the field.
     621
     622.. note::
     623
     624    For PostGIS users, the routine ``ST_distance_sphere``
     625    is used by default for calculating distances on geographic coordinate systems
     626    -- which may only be called with point geometries [#]_.  Thus,
     627    geographic distance lookups on PostGIS are only allowed on ``PointField``
     628    model fields using points for the geographic parameter.
     629
     630The following distance lookups are available:
     631
     632* :lookup:`distance_lt`
     633* :lookup:`distance_lte`
     634* :lookup:`distance_gt`
     635* :lookup:`distance_gte`
     636* :lookup:`dwithin`
     637
     638In addition, there's the :ref:`distance` ``GeoQuerySet`` method.
     639
     640For example, let's say we have a ``SouthTexasCity`` model (from the
     641`GeoDjango distance tests`__ ) on a *projected* coordinate system valid for cities
     642in southern Texas::
     643
     644    from django.contrib.gis.db import models
     645   
     646    class SouthTexasCity(models.Model):
     647        name = models.CharField(max_length=30)
     648        # A projected coordinate system (only valid for South Texas!)
     649        # is used, units are in meters.
     650        point = models.PointField(srid=32140)
     651        objects = models.GeoManager()
     652
     653Then distance queries may be performed as follows::
     654
     655    >>> from django.contrib.gis.geos import *
     656    >>> from django.contrib.gis.measure import D # ``D`` is a shortcut for ``Distance``
     657    >>> from geoapp import SouthTexasCity
     658    # Distances will be calculated from this point, which does not have to be projected.
     659    >>> pnt = fromstr('POINT(-96.876369 29.905320)', srid=4326)
     660    # If numeric parameter, units of field (meters in this case) are assumed.
     661    >>> qs = SouthTexasCity.objects.filter(point__distance_lte=(pnt, 7000))
     662    # Find all Cities within 7 km, > 20 miles away, and > 100 chains  away (an obscure unit)
     663    >>> qs = SouthTexasCity.objects.filter(point__distance_lte=(pnt, D(km=7)))
     664    >>> qs = SouthTexasCity.objects.filter(point__distance_gte=(pnt, D(mi=20)))
     665    >>> qs = SouthTexasCity.objects.filter(point__distance_gte=(pnt, D(chain=100)))
     666
     667__ http://code.djangoproject.com/browser/django/trunk/django/contrib/gis/tests/distapp/models.py
     668
     669.. _geoqs_methods:
     670
     671``GeoQuerySet`` Methods
     672=======================
     673
     674``GeoQuerySet`` methods perform a spatial operation on each geographic
     675field in the queryset and store its output in a new attribute on the model
     676(which is generally the name of the ``GeoQuerySet`` method).
     677
     678There are also aggregate ``GeoQuerySet`` methods which return a single value
     679instead of a queryset.  This section will describe the API and availability
     680of every ``GeoQuerySet`` method available in GeoDjango.
     681
     682With a few exceptions, the following keyword arguments may be used with all
     683``GeoQuerySet`` methods:
     684
     685=====================  =====================================================
     686Keyword Argument       Description
     687=====================  =====================================================
     688``field_name``         By default, ``GeoQuerySet`` methods use the first
     689                       geographic field encountered in the model.  This
     690                       keyword should be used to specify another
     691                       geographic field (e.g., ``field_name='point2'``)
     692                       when there are multiple geographic fields in a model.
     693
     694                       On PostGIS, the ``field_name`` keyword may also be
     695                       used on geometry fields in models that are related
     696                       via a ``ForeignKey`` relation (e.g.,
     697                       ``field_name='related__point'``).
     698   
     699``model_att``          By default, ``GeoQuerySet`` methods typically attach
     700                       their output in an attribute with the same name as
     701                       the ``GeoQuerySet`` method.  Setting this keyword
     702                       with the desired attribute name will override this
     703                       default behavior.  For example,
     704                       ``qs = Zipcode.objects.centroid(model_att='c')`` will
     705                       attach the centroid of the ``Zipcode`` geometry field
     706                       in a ``c`` attribute on every model rather than in a
     707                       ``centroid`` attribute. 
     708
     709                       This keyword is required if
     710                       a method name clashes with an existing
     711                       ``GeoQuerySet`` method -- if you wanted to use the
     712                       ``area()`` method on model with a ``PolygonField``
     713                       named ``area``, for example.
     714=====================  =====================================================
     715
     716Aggregate Objects
     717-----------------
     718.. versionadded:: 1.1
     719
     720Example::
     721
     722    >>> from django.contrib.gis.db.models import Extent, Union
     723    >>> WorldBorders.objects.aggregate(Extent('mpoly'), Union('mpoly'))
     724
     725.. method:: Collect
     726
     727Returns the same as the :ref:`collect` aggregate method.
     728
     729.. method:: Extent
     730
     731Returns the same as the :ref:`extent` aggregate method.
     732
     733.. method:: Extent3D
     734
     735.. versionadded:: 1.2
     736
     737Returns the same as the :ref:`extent3d` aggregate method.
     738
     739.. method:: MakeLine
     740
     741Returns the same as the :ref:`makeline` aggregate method.
     742
     743.. method:: Union
     744
     745Returns the same as the :ref:`unionagg` aggregate method.
     746
     747Aggregate Methods
     748-----------------
     749
     750.. _collect:
     751
     752.. method:: collect()
     753
     754.. versionadded:: 1.1
     755
     756*Availability*: PostGIS
     757
     758Returns a ``GEOMETRYCOLLECTION`` or a ``MULTI`` geometry object from the geometry
     759column.  This is analagous to a simplified version of the :ref:`unionagg` routine,
     760except it can be several orders of magnitude faster than peforming a union because
     761it simply rolls up geometries into a collection or multi object, not caring about
     762dissolving boundaries.
     763
     764.. _extent:
     765
     766.. method:: extent()
     767
     768*Availability*: PostGIS, Oracle
     769
     770Returns the extent of the ``GeoQuerySet`` as a four-tuple, comprising the
     771lower left coordinate and the upper right coordinate.
     772
     773Example::
     774
     775    >>> qs = City.objects.filter(name__in=('Houston', 'Dallas'))
     776    >>> print qs.extent()
     777    (-96.8016128540039, 29.7633724212646, -95.3631439208984, 32.782058715820)
     778
     779
     780.. _extent3d:
     781
     782.. method:: extent3d()
     783
     784.. versionadded:: 1.2
     785
     786*Availability*: PostGIS
     787
     788Returns the 3D extent of the ``GeoQuerySet`` as a six-tuple, comprising
     789the lower left coordinate and upper right coordinate.
     790
     791Example::
     792
     793    >>> qs = City.objects.filter(name__in=('Houston', 'Dallas'))
     794    >>> print qs.extent3d()
     795    (-96.8016128540039, 29.7633724212646, 0, -95.3631439208984, 32.782058715820, 0)
     796
     797.. _makeline:
     798
     799.. method:: make_line()
     800
     801*Availability*: PostGIS
     802
     803Returns a ``LineString`` constructed from the point field geometries in the
     804``GeoQuerySet``.  Currently, ordering the queryset has no effect.
     805
     806Example::
     807
     808     >>> print City.objects.filter(name__in=('Houston', 'Dallas')).make_line()
     809     LINESTRING (-95.3631510000000020 29.7633739999999989, -96.8016109999999941 32.7820570000000018)
     810
     811.. _unionagg:
     812
     813.. function:: unionagg()
     814
     815*Availability*: PostGIS, Oracle, SpatiaLite
     816
     817This method returns a ``GEOSGeometry`` object comprising the union of every
     818geometry in the queryset.  Please note that use of `unionagg` is processor intensive
     819and may take a significant amount of time on large querysets.
     820
     821Example::
     822   
     823    >>> u = Zipcode.objects.unionagg() # This may take a long time.
     824    >>> u = Zipcode.objects.filter(poly__within=bbox).unionagg() # A more sensible approach.
     825
     826=====================  =====================================================
     827Keyword Argument       Description
     828=====================  =====================================================
     829``tolerance``          This keyword is for Oracle only.  It is for the
     830                       tolerance value used by the ``SDOAGGRTYPE``
     831                       procedure; the  `Oracle documentation`__ has more
     832                       details.
     833=====================  =====================================================
     834
     835__ http://download.oracle.com/docs/html/B14255_01/sdo_intro.htm#sthref150
     836
     837Measurement
     838-----------
     839*Availability*: PostGIS, Oracle, SpatiaLite
     840
     841.. _area:
     842
     843.. function:: area()
     844
     845Returns the area of the geographic field in an ``area`` attribute on
     846each element of this GeoQuerySet.
     847
     848.. _distance:
     849
     850.. function:: distance(geom)
     851
     852This method takes a geometry as a parameter, and attaches a ``distance``
     853attribute to every model in the returned queryset that contains the
     854distance (as a ``Distance`` object) to the given geometry.
     855
     856In the following example (taken from the `GeoDjango distance tests`__),
     857the distance from the `Tasmanian`__ city of Hobart to every other
     858``PointField`` in the ``AustraliaCity`` queryset is calculated::
     859
     860    >>> pnt = AustraliaCity.objects.get(name='Hobart').point
     861    >>> for city in AustraliaCity.objects.distance(pnt): print city.name, city.distance
     862    Wollongong 990071.220408 m
     863    Shellharbour 972804.613941 m
     864    Thirroul 1002334.36351 m
     865    Mittagong 975691.632637 m
     866    Batemans Bay 834342.185561 m
     867    Canberra 598140.268959 m
     868    Melbourne 575337.765042 m
     869    Sydney 1056978.87363 m
     870    Hobart 0.0 m
     871    Adelaide 1162031.83522 m
     872    Hillsdale 1049200.46122 m
     873
     874.. note::
     875
     876    Because the ``distance`` attribute is a ``Distance`` object, you can
     877    easily express the value in the units of your choice.  For example,
     878    ``city.distance.mi`` is the distance value in miles and
     879    ``city.distance.km`` is the distance value in kilometers.  See the
     880    `distance documentation`_ for usage details and the list of
     881    `supported units`_.
     882
     883.. _distance documentation: measure.html#the-distance-and-area-objects
     884.. _supported units: measure.html#supported-units
     885
     886__ http://en.wikipedia.org/wiki/Tasmania
     887__ http://code.djangoproject.com/browser/django/trunk/django/contrib/gis/tests/distapp/models.py
     888
     889.. function:: length()
     890
     891Returns the length of the geometry field in a ``length`` attribute
     892(a ``Distance`` object) on each model in the queryset.
     893
     894.. function:: perimiter()
     895
     896Returns the perimeter of the geometry field in a ``perimeter`` attribute
     897(a ``Distance`` object) on each model in the queryset.
     898
     899Geometry Methods
     900----------------
     901
     902With the exception of ``transform``, all of the following attach geometry objects
     903to each element of the ``GeoQuerySet`` that is the result of the method.
     904
     905.. function:: centroid()
     906
     907*Availability*: PostGIS, Oracle, SpatiaLite
     908
     909Returns the ``centroid`` value for the geographic field in a ``centroid``
     910attribute on each element of the ``GeoQuerySet``.
     911
     912.. function:: envelope()
     913
     914*Availability*: PostGIS, SpatiaLite
     915
     916Returns a geometry representing the bounding box of the geometry field in
     917an ``envelope`` attribute on each element of the ``GeoQuerySet``.
     918
     919.. function: point_on_surface()
     920
     921*Availability*: PostGIS, Oracle, SpatiaLite
     922
     923Returns a Point geometry guaranteed to lie on the surface of the
     924Geometry field in a `point_on_surface` attribute on each element
     925of this GeoQuerySet; otherwise sets with None.
     926
     927.. function:: scale(x, y, z=0.0)
     928
     929*Availability*: PostGIS, SpatiaLite
     930
     931.. function:: snap_to_grid(*args)
     932
     933.. versionadded:: 1.1
     934
     935Snap all points of the input geometry to the grid.  How the
     936geometry is snapped to the grid depends on how many numeric
     937(either float, integer, or long) arguments are given.
     938
     939===================  =====================================================
     940Number of Arguments  Description
     941===================  =====================================================
     9421                    A single size to snap bot the X and Y grids to.
     9432                    X and Y sizes to snap the grid to.
     9444                    X, Y sizes and the corresponding X, Y origins.
     945===================  =====================================================
     946
     947.. function:: translate(x, y, z=0.0)
     948
     949*Availability*: PostGIS, SpatiaLite
     950
     951Translates the geometry to a new location using the given numeric
     952parameters as offsets.
     953
     954.. function:: transform(srid)
     955
     956*Availability*: PostGIS, Oracle
     957
     958The ``transform`` method transforms the geometries in a model to the spatial
     959reference system specified by the ``srid`` parameter.  If no ``srid`` is given,
     960then 4326 (WGS84) is used by default.
     961
     962.. note ::
     963   
     964    What spatial reference system an integer SRID corresponds to may depend on
     965    the spatial database used.  In other words, the SRID numbers used for Oracle
     966    are not necessarily the same as those used by PostGIS.
     967
     968Example::
     969
     970    >>> qs = Zipcode.objects.all().transform() # Transforms to WGS84
     971    >>> qs = Zipcode.objects.all().transform(32140) # Transforming to "NAD83 / Texas South Central"
     972    >>> print qs[0].poly.srid
     973    32140
     974    >>> print qs[0].poly
     975    POLYGON ((234055.1698884720099159 4937796.9232223574072123 ...
     976
     977Geometry Operations
     978-------------------
     979*Availability*: PostGIS, Oracle, SpatiaLite
     980
     981The following methods all take a geometry as a parameter and attach a geometry
     982to each element of the ``GeoQuerySet`` that is the result of the operation.
     983
     984.. function:: difference(geom)
     985
     986Returns the spatial difference of the geographic field with the given
     987geometry in a ``difference`` attribute on each element of the
     988``GeoQuerySet``.
     989
     990.. function:: intersection(geom)
     991
     992Returns the spatial intersection of the geographic field with the
     993given geometry in an ``intersection`` attribute on each element of the
     994``GeoQuerySet``.
     995
     996.. function:: sym_difference(geom)
     997
     998Returns the symmetric difference of the geographic field with the
     999given geometry in a ``sym_difference`` attribute on each element of the
     1000``GeoQuerySet``.
     1001
     1002.. function:: union(geom)
     1003
     1004Returns the union of the geographic field with the given
     1005geometry in an ``union`` attribute on each element of the
     1006``GeoQuerySet``.
     1007
     1008Output
     1009------
     1010
     1011The following ``GeoQuerySet`` methods will return an attribute that has the value
     1012of the geometry field in each model converted to the requested output format.
     1013
     1014.. function:: geojson()
     1015
     1016.. versionadded:: 1.1
     1017
     1018*Availability*: PostGIS
     1019
     1020Attaches a ``geojson`` attribute to every model in the queryset that contains the
     1021`GeoJSON`__ representation of the geometry.
     1022
     1023=====================  =====================================================
     1024Keyword Argument       Description
     1025=====================  =====================================================
     1026``precision``          It may be used to specify the number of significant
     1027                       digits for the coordinates in the GeoJSON
     1028                       representation -- the default value is 8.
     1029
     1030``crs``                Set this to ``True`` if you want the coordinate
     1031                       reference system to be included in the returned
     1032                       GeoJSON.
     1033
     1034``bbox``               Set this to ``True`` if you want the bounding box
     1035                       to be included in the returned GeoJSON.
     1036=====================  =====================================================
     1037
     1038__ http://geojson.org/
     1039
     1040.. function:: gml()
     1041
     1042*Availability*: PostGIS, Oracle
     1043
     1044Attaches a ``gml`` attribute to every model in the queryset that contains the
     1045`Geographic Markup Language (GML)`__ representation of the geometry.
     1046
     1047Example::
     1048
     1049    >>> qs = Zipcode.objects.all().gml()
     1050    >>> print qs[0].gml
     1051    <gml:Polygon srsName="EPSG:4326"><gml:OuterBoundaryIs>-147.78711,70.245363 ...  -147.78711,70.245363</gml:OuterBoundaryIs></gml:Polygon>
     1052
     1053=====================  =====================================================
     1054Keyword Argument       Description
     1055=====================  =====================================================
     1056``precision``          This keyword is for PostGIS only.  It may be used
     1057                       to specify the number of significant digits for the
     1058                       coordinates in the GML representation -- the default
     1059                       value is 8.
     1060
     1061``version``            This keyword is for PostGIS only.  It may be used to
     1062                       specify the GML version used, and may only be values
     1063                       of 2 or 3.  The default value is 2.
     1064=====================  =====================================================
     1065
     1066__ http://en.wikipedia.org/wiki/Geography_Markup_Language
     1067
     1068.. function:: kml()
     1069
     1070*Availability*: PostGIS
     1071
     1072Attaches a ``kml`` attribute to every model in the queryset that contains the
     1073`Keyhole Markup Language (KML)`__ representation of the geometry fields. It
     1074should be noted that the contents of the KML are transformed to WGS84 if
     1075necessary.
     1076
     1077Example::
     1078
     1079    >>> qs = Zipcode.objects.all().kml()
     1080    >>> print qs[0].kml
     1081    <Polygon><outerBoundaryIs><LinearRing><coordinates>-103.04135,36.217596,0 ... -103.04135,36.217596,0</coordinates></LinearRing></outerBoundaryIs></Polygon>
     1082
     1083=====================  =====================================================
     1084Keyword Argument       Description
     1085=====================  =====================================================
     1086``precision``          This keyword may be used to specify the number of
     1087                       significant digits for the coordinates in the KML
     1088                       representation -- the default value is 8.
     1089=====================  =====================================================
     1090
     1091__ http://code.google.com/apis/kml/documentation/
     1092
     1093.. function:: svg()
     1094
     1095*Availability*: PostGIS, SpatiaLite
     1096
     1097Attaches a ``svg`` attribute to every model in the queryset that contains
     1098the `Scalable Vector Graphics (SVG)`__ path data of the geometry fields.
     1099
     1100=====================  =====================================================
     1101Keyword Argument       Description
     1102=====================  =====================================================
     1103``relative``           If set to ``True``, the path data will be implemented
     1104                       in terms of relative moves.  Defaults to ``False``,
     1105                       meaning that absolute moves are used instead.
     1106
     1107``precision``          This keyword may be used to specify the number of
     1108                       significant digits for the coordinates in the SVG
     1109                       representation -- the default value is 8.
     1110=====================  =====================================================
     1111
     1112__ http://www.w3.org/Graphics/SVG/
     1113
     1114Miscellaneous
     1115-------------
     1116
     1117.. function:: mem_size()
     1118
     1119*Availability*: PostGIS
     1120
     1121Returns the memory size (number of bytes) that the geometry field takes
     1122in a ``mem_size`` attribute  on each element of the ``GeoQuerySet``.
     1123
     1124.. function:: num_geom()
     1125
     1126*Availability*: PostGIS, Oracle, SpatiaLite
     1127
     1128Returns the number of geometries in a ``num_geom`` attribute on
     1129each element of the ``GeoQuerySet`` if the geometry field is a
     1130collection (e.g., a ``GEOMETRYCOLLECTION`` or ``MULTI*`` field);
     1131otherwise sets with ``None``.
     1132
     1133.. function:: num_points()
     1134
     1135*Availability*: PostGIS, Oracle, SpatiaLite
     1136
     1137Returns the number of points in the first linestring in the
     1138geometry field in a ``num_points`` attribute on each element of
     1139the ``GeoQuerySet``; otherwise sets with ``None``.
     1140
     1141Compatibility Table
     1142===================
     1143
     1144Spatial Lookup Types
     1145--------------------
     1146The following table provides a summary of what lookup types are available
     1147on each spatial backend.
     1148
     1149===========================  =========  ========  ============ ==========
     1150Lookup Type                  PostGIS    Oracle    MySQL [#]_   SpatiaLite
     1151===========================  =========  ========  ============ ==========
     1152``bbcontains``               X                    X            X
     1153``bboverlaps``               X                    X            X
     1154``contained``                X                    X            X
     1155``contains``                 X          X         X            X
     1156``coveredby``                X          X
     1157``covers``                   X          X
     1158``crosses``                  X                                 X
     1159``disjoint``                 X          X         X            X
     1160``distance_gt``              X          X                      X
     1161``distance_gte``             X          X                      X
     1162``distance_lt``              X          X                      X
     1163``distance_lte``             X          X                      X
     1164``dwithin``                  X          X
     1165``equals``                   X          X         X            X
     1166``exact``                    X          X         X            X
     1167``intersects``               X          X         X            X
     1168``overlaps``                 X          X         X            X
     1169``relate``                   X          X                      X
     1170``same_as``                  X          X         X            X
     1171``touches``                  X          X         X            X
     1172``within``                   X          X         X            X
     1173``left``                     X
     1174``right``                    X
     1175``overlaps_left``            X
     1176``overlaps_right``           X
     1177``overlaps_above``           X
     1178``overlaps_below``           X
     1179``strictly_above``           X
     1180``strictly_below``           X
     1181===========================  =========  ========  ============ ==========
     1182
     1183``GeoQuerySet`` Methods
     1184-----------------------
     1185The following table provides a summary of what ``GeoQuerySet`` methods
     1186are available on each spatial backend.  Please note that MySQL does not
     1187support any of these methods, and is thus excluded from the table.
     1188
     1189===========================  =========  ======== ==========
     1190Method                       PostGIS    Oracle   SpatiaLite
     1191===========================  =========  ======== ==========
     1192``area``                     X          X        X
     1193``centroid``                 X          X        X
     1194``collect``                  X           
     1195``difference``               X          X        X
     1196``distance``                 X          X        X
     1197``envelope``                 X                   X
     1198``extent``                   X          X
     1199``extent3d``                 X
     1200``geojson``                  X
     1201``gml``                      X          X
     1202``intersection``             X          X        X
     1203``kml``                      X
     1204``length``                   X          X        X
     1205``make_line``                X
     1206``mem_size``                 X
     1207``num_geom``                 X          X        X
     1208``num_points``               X          X        X
     1209``perimeter``                X          X
     1210``point_on_surface``         X          X        X
     1211``scale``                    X                   X
     1212``snap_to_grid``             X
     1213``svg``                      X                   X
     1214``sym_difference``           X          X        X
     1215``transform``                X          X        X
     1216``translate``                X                   X
     1217``union``                    X          X        X
     1218``unionagg``                 X          X        X
     1219===========================  =========  ======== ==========   
     1220
     1221.. rubric:: Footnotes
     1222.. [#] *See* Open Geospatial Consortium, Inc., `OpenGIS Simple Feature Specification For SQL <http://www.opengis.org/docs/99-049.pdf>`_, Document 99-049 (May 5, 1999), at  Ch. 3.2.5, p. 3-11 (SQL Textual Representation of Geometry).
     1223.. [#] *See* `PostGIS EWKB, EWKT and Canonical Forms <http://postgis.refractions.net/documentation/manual-1.3/ch04.html#id2571020>`_, PostGIS documentation at Ch. 4.1.2.
     1224.. [#] *See* Howard Butler, Martin Daly, Allan Doyle, Tim Schaub, & Christopher Schmidt, `The GeoJSON Format Specification <http://geojson.org/geojson-spec.html>`_, Revision 1.0 (June 16, 2008).
     1225.. [#] *See generally*, `Operators <http://postgis.refractions.net/documentation/manual-1.3/ch06.html#id2576880>`_, PostGIS Documentation at Ch. 6.2.2.
     1226.. [#] *See generally*, `Geometry Relationship Functions <http://postgis.refractions.net/documentation/manual-1.3/ch06.html#id2574517>`_ PostGIS Documentation at Ch. 6.1.2.
     1227.. [#] For an explanation of this routine, see `this entry <http://lin-ear-th-inking.blogspot.com/2007/06/subtleties-of-ogc-covers-spatial.html>`_ at the blog of Martin Davis (a PostGIS developer).
     1228.. [#] *See id.*
     1229.. [#] *See* `OpenGIS Simple Feature Specification For SQL <http://www.opengis.org/docs/99-049.pdf>`_, at Ch. 2.1.13.2, p. 2-13 (The Dimensionally Extended Nine-Intersection Model).
     1230.. [#] Oracle Spatial User's Guide and Manual, at Ch. 11.
     1231.. [#] *See id.* at `SDO_RELATE documentation <http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14255/sdo_operat.htm#sthref845>`_.
     1232.. [#] MySQL 5.0 Reference Manual, at Ch. 17.5.5.
     1233.. [#] *See* the `distance documentation`_ for more information on the ``Distance`` object.
     1234.. [#] *See* ``ST_distance_sphere`` in `Measurement Functions <http://postgis.refractions.net/documentation/manual-1.3/ch06.html#id2577138>`_, PostGIS documentation at Ch. 6.2.3.
     1235.. [#] MySQL only supports bounding box operations (known as minimum bounding rectangles, or MBR, in MySQL).  Thus, spatial lookups such as ``contains`` are really equivalent to ``bbcontains``.
  • docs/ref/contrib/gis/geos.txt

     
     1.. _ref-geos:
     2
     3========
     4GEOS API
     5========
     6
     7.. module:: django.contrib.gis.geos
     8   :synopsis: GeoDjango's high-level interface to the GEOS library.
     9
     10Background
     11==========
     12
     13What is GEOS?
     14-------------
     15
     16`GEOS`__ stands for **G**\ eometry **E**\ ngine - **O**\ pen **S**\ ource,
     17and is a C++ library, ported from the  `Java Topology Suite`__.  GEOS
     18implements the OpenGIS `Simple Features for SQL`__ spatial predicate functions
     19and spatial operators. GEOS, now an OSGeo project, was initially developed and
     20maintained by `Refractions Research`__ of Victoria, Canada.
     21
     22__ http://trac.osgeo.org/geos/
     23__ http://sourceforge.net/projects/jts-topo-suite/
     24__ http://www.opengeospatial.org/standards/sfs
     25__ http://www.refractions.net/
     26
     27Features
     28--------
     29
     30GeoDjango implements a high-level Python wrapper for the GEOS library, its
     31features include:
     32
     33* A BSD-licensed interface to the GEOS geometry routines, implemented purely
     34  in Python using ``ctypes``.
     35* Loosely-coupled to GeoDjango.  For example, :class:`GEOSGeometry` objects
     36  may be used outside of a django project/application.  In other words,
     37  no need to have ``DJANGO_SETTINGS_MODULE`` set or use a database, etc.
     38* Mutability: :class:`GEOSGeometry` objects may be modified.
     39* Cross-platform and tested; compatible with Windows, Linux, Solaris, and Mac
     40  OS X platforms.
     41
     42Tutorial
     43========
     44
     45This section contains a brief introduction and tutorial to using
     46:class:`GEOSGeometry` objects.
     47
     48Creating a Geometry
     49-------------------
     50
     51Modifying a Geometry
     52--------------------
     53
     54Geometry Objects
     55================
     56
     57``GEOSGeometry``
     58----------------
     59
     60.. class:: GEOSGeometry(geo_input[, srid=None])
     61
     62  :param geo_input: Geometry input value
     63  :type geo_input: string or buffer
     64  :param srid: spatial reference identifier
     65  :type srid: integer
     66
     67This is the base class for all GEOS geometry objects.  It initializes on the
     68given ``geo_input`` argument, and then assumes the proper geometry subclass
     69(e.g., ``GEOSGeometry('POINT(1 1)')`` will create a :class:`Point` object).
     70
     71The following formats are accepted:
     72
     73* WKT / EWKT
     74* HEX / HEXEWKB
     75* WKB / EWKB
     76* GeoJSON
     77
     78Properties
     79~~~~~~~~~~
     80
     81.. attribute:: GEOSGeometry.empty
     82
     83Returns whether or not the set of points in the geometry is empty.
     84
     85.. attribute:: GEOSGeometry.geom_type
     86
     87Returns a string corresponding to the type of geometry.  For example::
     88
     89    >>> pnt = GEOSGeometry('POINT(5 23)')
     90    >>> pnt.geom_type
     91    'Point'
     92
     93.. attribute:: GEOSGeometry.geom_typeid
     94
     95Returns the GEOS geometry type identification number.  The following table
     96shows the value for each geometry type:
     97
     98.. attribute:: GEOSGeometry.hasz
     99
     100Returns a boolean indicating whether the geometry is three-dimensional.
     101
     102.. attribute:: GEOSGeometry.ring
     103
     104Returns a boolean indicating whether the geometry is a ``LinearRing``.
     105
     106.. attribute:: GEOSGeometry.simple
     107
     108Returns a boolean indicating whether the geometry is 'simple'. A geometry
     109is simple if and only if it does not intersect itself (except at boundary
     110points).  For example, a :class:`LineString` object is not simple if it
     111intersects itself. Thus, :class:`LinearRing` and :class`Polygon` objects
     112are always simple because they do cannot intersect themselves, by
     113definition.
     114
     115.. attribute:: GEOSGeometry.valid
     116
     117Returns a boolean indicating whether the geometry is valid.
     118
     119===========================  ========
     120Geometry                     ID
     121===========================  ========
     122:class:`Point`               0
     123:class:`LineString`          1
     124:class:`LinearRing`          2
     125:class:`Polygon`             3
     126:class:`MultiPoint`          4
     127:class:`MultiLineString`     5
     128:class:`MultiPolygon`        6
     129:class:`GeometryCollection`  7
     130===========================  ========
     131
     132Output Properties
     133~~~~~~~~~~~~~~~~~
     134
     135The properties in this section export the :class:`GEOSGeometry` object into
     136a different.  This output may be in the form of a string, buffer, or even
     137another object.
     138
     139.. attribute:: GEOSGeometry.ewkt
     140
     141Returns the "extended" Well-Known Text of the geometry.  This representation
     142is specific to PostGIS and is a super set of the OGC WKT standard. [#]_
     143Essentially the SRID is prepended to the WKT representation, for example
     144``SRID=4326;POINT(5 23)``.
     145
     146.. note::
     147
     148   The output from this property does not include the 3dm, 3dz, and 4d
     149   information that PostGIS supports in its EWKT representations.
     150
     151.. attribute:: GEOSGeometry.hex
     152
     153Returns the WKB of this Geometry in hexadecimal form.  Please note
     154that the SRID and Z values are not included in this representation
     155because it is not a part of the OGC specification (use the
     156:attr:`GEOSGeometry.hexewkb` property instead).
     157
     158.. versionadded:: 1.2
     159
     160.. attribute:: GEOSGeometry.hexewkb
     161
     162Returns the EWKB of this Geometry in hexadecimal form.  This is an
     163extension of the WKB specification that includes SRID and Z values
     164that are a part of this geometry.
     165
     166.. note::
     167
     168   GEOS 3.1 is *required* if you want valid 3D HEXEWKB.
     169
     170.. attribute:: GEOSGeometry.json
     171
     172Returns the GeoJSON representation of the geometry.
     173
     174.. note::
     175
     176    Requires GDAL.
     177
     178.. attribute:: GEOSGeometry.geojson
     179
     180Alias for :attr:`GEOSGeometry.json`.
     181
     182.. attribute:: GEOSGeometry.kml
     183
     184Returns a `KML`__ (Keyhole Markup Language) representation of the
     185geometry.  This should only be used for geometries with an SRID of
     1864326 (WGS84), but this restriction is not enforced.
     187
     188.. attribute:: GEOSGeometry.ogr
     189
     190Returns a :class:`django.contrib.gis.gdal.OGRGeometry` object
     191correspondg to the GEOS geometry.
     192
     193.. note::
     194
     195    Requires GDAL.
     196
     197.. _wkb:
     198
     199.. attribute:: GEOSGeometry.wkb
     200
     201Returns the WKB (Well-Known Binary) representation of this Geometry
     202as a Python buffer.  SRID and Z values are not included, use the
     203:attr:`GEOSGeometry.ewkb` property instead.
     204
     205.. _ewkb:
     206
     207.. attribute:: GEOSGeometry.ewkb
     208
     209.. versionadded:: 1.2
     210
     211Return the EWKB representation of this Geometry as a Python buffer.
     212This is an extension of the WKB specification that includes any SRID
     213and Z values that are a part of this geometry.
     214
     215.. note::
     216
     217   GEOS 3.1 is *required* if you want valid 3D EWKB.
     218
     219.. attribute:: GEOSGeometry.wkt
     220
     221Returns the Well-Known Text of the geometry (an OGC standard).
     222
     223__ http://code.google.com/apis/kml/documentation/
     224
     225Spatial Predicate Methods
     226~~~~~~~~~~~~~~~~~~~~~~~~~
     227
     228All of the following spatial predicate methods take another
     229:class:`GEOSGeometry` instance (``other``) as a parameter, and
     230return a boolean.
     231
     232.. method:: GEOSGeometry.contains(other)
     233
     234Returns ``True`` if :meth:`GEOSGeometry.within` is ``False``.
     235
     236.. method:: GEOSGeometry.crosses(other)
     237
     238Returns ``True`` if the DE-9IM intersection matrix for the two Geometries
     239is ``T*T******`` (for a point and a curve,a point and an area or a line
     240and an area) ``0********`` (for two curves).
     241
     242.. method:: GEOSGeometry.disjoint(other)
     243
     244Returns ``True`` if the DE-9IM intersection matrix for the two geometries
     245is ``FF*FF****``.
     246
     247.. method:: GEOSGeometry.equals(other)
     248
     249Returns ``True`` if the DE-9IM intersection matrix for the two geometries
     250is ``T*F**FFF*``.
     251
     252.. method:: GEOSGeometry.equals_exact(other, tolerance=0)
     253
     254Returns true if the two geometries are exactly equal, up to a
     255specified tolerance.  The ``tolerance`` value should be a floating
     256point number representing the error tolerance in the comparison, e.g.,
     257``poly1.equals_exact(poly2, 0.001)`` will compare equality to within
     258one thousandth of a unit.
     259
     260.. method:: GEOSGeometry.intersects(other)
     261
     262Returns ``True`` if :meth:`GEOSGeometry.disjoint` is ``False``.
     263
     264.. method:: GEOSGeometry.overlaps(other)
     265
     266Returns true if the DE-9IM intersection matrix for the two geometries
     267is ``T*T***T**`` (for two points or two surfaces) ``1*T***T**``
     268(for two curves).
     269
     270.. method:: GEOSGeometry.relate_pattern(other, pattern)
     271
     272Returns ``True`` if the elements in the DE-9IM intersection matrix
     273for this geometry and the other matches the given ``pattern`` --
     274a string of nine characters from the alphabet: {``T``, ``F``, ``*``, ``0``}.
     275
     276.. method:: GEOSGeometry.touches(other)
     277
     278Returns ``True`` if the DE-9IM intersection matrix for the two geometries
     279is ``FT*******``, ``F**T*****`` or ``F***T****``.
     280
     281.. method:: GEOSGeometry.within(other)
     282
     283Returns ``True`` if the DE-9IM intersection matrix for the two geometries
     284is ``T*F**F***``.
     285
     286Topological Methods
     287~~~~~~~~~~~~~~~~~~~
     288
     289.. method:: GEOSGeometry.buffer(width, quadsegs=8)
     290
     291Returns a :class:`GEOSGeometry` that represents all points whose distance
     292from this geometry is less than or equal to the given ``width``. The optional
     293``quadsegs`` keyword sets the number of segments used to approximate a
     294quarter circle (defaults is 8).
     295
     296.. method:: GEOSGeometry.difference(other)
     297
     298Returns a :class:`GEOSGeometry` representing the points making up this
     299geometry that do not make up other.
     300
     301.. method:: GEOSGeometry:intersection(other)
     302
     303Returns a :class:`GEOSGeometry` representing the points shared by this
     304geometry and other.
     305
     306.. method:: GEOSGeometry.relate(other)
     307
     308Returns the DE-9IM intersection matrix (a string) representing the
     309topological relationship between this geometry and the other.
     310
     311.. method:: GEOSGeometry.simplify(tolerance=0.0, preserve_topology=False)
     312
     313Returns a new :class:`GEOSGeometry`, simplified using the Douglas-Peucker
     314algorithm to the specified tolerance.  A higher tolerance value implies
     315less points in the output.  If no tolerance is tolerance provided,
     316it defaults to 0.
     317
     318By default, this function does not preserve topology - e.g.,
     319:class:`Polygon` objects can be split, collapsed into lines or disappear.
     320:class:`Polygon` holes can be created or disappear, and lines can cross.
     321By specifying ``preserve_topology=True``, the result will have the same
     322dimension and number of components as the input, however, this is
     323significantly slower.   
     324
     325.. method:: GEOSGeometry.sym_difference(other)
     326
     327Returns a :class:`GEOSGeometry` combining the points in this geometry
     328not in other, and the points in other not in this geometry.
     329
     330.. method:: GEOSGeometry.union(other)
     331
     332Returns a :class:`GEOSGeometry` representing all the points in this
     333geometry and the other.
     334
     335Topological Properties
     336~~~~~~~~~~~~~~~~~~~~~~
     337
     338.. attribute:: GEOSGeometry.boundary
     339
     340Returns the boundary as a newly allocated Geometry object.
     341
     342.. attribute:: GEOSGeometry.centroid
     343
     344Returns a :class:`Point` object representing the geometric center of
     345the geometry.  The point is not guaranteed to be on the interior
     346of the geometry.
     347
     348.. attribute:: GEOSGeometry.convex_hull
     349
     350Returns the smallest :class:`Polygon` that contains all the points in
     351the geometry.
     352
     353.. attribute:: GEOSGeometry.envelope
     354
     355Returns a :class:`Polygon` that represents the bounding envelope of
     356this geometry.
     357
     358.. attribute:: GEOSGeometry.point_on_surface
     359
     360Computes and returns a :class:`Point` guaranteed to be on the interior
     361of this geometry.
     362
     363Other Properties & Methods
     364~~~~~~~~~~~~~~~~~~~~~~~~~~
     365
     366.. attribute:: GEOSGeometry.extent
     367
     368This property returns the extent of this geometry as a 4-tuple,
     369consisting of (xmin, ymin, xmax, ymax).
     370
     371.. attribute:: GEOSGeometry.area
     372
     373This property returns the area of the Geometry.
     374
     375.. method:: distance(geom)
     376
     377Returns the distance between the closest points on this Geometry and the given
     378``geom`` (another ``GEOSGeometry`` object).
     379
     380.. note::
     381
     382    GEOS distance calculations are  linear -- in other words, GEOS will not
     383    perform a spherical calculation even if the SRID specifies a geographic
     384    coordinate system.
     385
     386.. attribute:: GEOSGeometry.length
     387
     388Returns the length of this geometry (e.g., 0 for a :class:`Point`,
     389the length of a :class:`LineString`, or the circumference of
     390a :class:`Polygon`).
     391
     392.. attribute:: GEOSGeometry.prepared
     393
     394.. versionadded:: 1.1
     395
     396.. note::
     397
     398    Support for prepared geometries requires GEOS 3.1.
     399
     400Returns a GEOS ``PreparedGeometry`` for the contents of this geometry. 
     401``PreparedGeometry`` objects are optimized for the contains, intersects,
     402and covers operations.  Refer to the :ref:`prepared` documentation for
     403more information.
     404
     405.. attribute:: GEOSGeometry.srs
     406
     407Returns an OGR ``SpatialReference`` object corresponding to the SRID of the
     408geometry or ``None``.  Consult the `SpatialReference documentation`_ for more
     409information about these objects.
     410
     411.. _SpatialReference documentation: gdal.html#spatialreference
     412
     413.. note::
     414
     415    Requires GDAL.
     416
     417.. method:: transform(ct, clone=False)
     418
     419Transforms the geometry according to the given transformation object, which may
     420be an integer SRID, spatial reference WKT string, a PROJ.4 string, or a
     421``SpatialReference`` object. By default, the geometry is transformed in-place and
     422nothing is returned. However if the `clone` keyword is set, then the geometry
     423is not modified and a transformed clone is returned instead.
     424
     425``Point``
     426---------
     427
     428.. class:: Point(x, y, z=None, srid=None)
     429
     430
     431``LineString``
     432--------------
     433
     434.. class:: LineString(*args, **kwargs)
     435
     436``LinearRing``
     437--------------
     438
     439.. class:: LinearRing(*args, **kwargs)
     440
     441
     442``Polygon``
     443-----------
     444
     445.. class:: Polygon(*args, **kwargs)
     446
     447Geometry Collections
     448====================
     449
     450``MultiPoint``
     451--------------
     452
     453.. class:: MultiPoint(*args, **kwargs)
     454
     455``MultiLineString``
     456-------------------
     457
     458.. class:: MultiLineString(*args, **kwargs)
     459
     460``MultiPolygon``
     461----------------
     462
     463.. class:: MultiPolygon(*args, **kwargs)
     464
     465``GeometryCollection``
     466----------------------
     467
     468.. class:: GeometryCollection(*args, **kwargs)
     469
     470Prepared Geometries
     471===================
     472
     473Geometry Factories
     474==================
     475
     476.. function:: fromfile(file_h)
     477
     478   :param file_h: input file that contains spatial data
     479   :type file_h: a Python ``file`` object or a string path to the file
     480   :rtype: a :class:`GEOSGeometry` corresponding to the spatial data in the file
     481
     482Example::
     483
     484    >>> from django.contrib.gis.geos import fromfile
     485    >>> g = fromfile('/home/bob/geom.wkt')
     486
     487.. function:: fromstr(string, [,srid=None])
     488
     489   :param string: string that contains spatial data
     490   :type string: string
     491   :param srid: spatial reference identifier
     492   :type srid: integer
     493   :rtype: a :class:`GEOSGeometry` corresponding to the spatial data in the string
     494
     495Example::
     496
     497    >>> from django.contrib.gis.geos import fromstr
     498    >>> pnt = fromstr('POINT(-90.5 29.5)', srid=4326)
     499
     500
     501I/O Objects
     502===========
     503
     504.. versionadded: 1.1
     505
     506Reader Objects
     507--------------
     508
     509The reader I/O classes simply return a :class:`GEOSGeometry` instance from the
     510WKB and/or WKT input given to their ``read(geom)`` method.
     511
     512.. class:: WKBReader
     513
     514Example::
     515
     516    >>> from django.contrib.gis.geos import WKBReader
     517    >>> wkb_r = WKBReader()
     518    >>> wkb_r.read('0101000000000000000000F03F000000000000F03F')
     519    <Point object at 0x103a88910>
     520
     521.. class:: WKTReader
     522
     523Example::
     524
     525    >>> from django.contrib.gis.geos import WKTReader
     526    >>> wkt_r = WKTReader()
     527    >>> wkt_r.read('POINT(1 1)')
     528    <Point object at 0x103a88b50>
     529
     530Writer Objects
     531--------------
     532
     533All writer objects have a ``write(geom)`` method that returns either the
     534WKB or WKT of the given geometry.  In addition, :class:`WKBWriter` objects
     535also have properties that may be used to change the byte order, and or
     536include the SRID and 3D values (in other words, EWKB).
     537
     538.. class:: WKBWriter
     539
     540``WKBWriter`` provides the most control over its output.  By default it
     541returns OGC-compliant WKB when it's ``write`` method is called.  However,
     542it has properties that allow for the creation of EWKB, a superset of the
     543WKB standard that includes additional information.
     544
     545.. method:: WKBWriter.write(geom)
     546
     547Returns the WKB of the given geometry as a Python ``buffer`` object.
     548Example::
     549
     550    >>> from django.contrib.gis.geos import Point, WKBWriter
     551    >>> pnt = Point(1, 1)
     552    >>> wkb_w = WKBWriter()
     553    >>> wkb_w.write(pnt)
     554    <read-only buffer for 0x103a898f0, size -1, offset 0 at 0x103a89930>
     555
     556.. method:: WKBWriter.write_hex(geom)
     557
     558Returns WKB of the geometry in hexadecimal.  Example::
     559
     560    >>> from django.contrib.gis.geos import Point, WKBWriter
     561    >>> pnt = Point(1, 1)
     562    >>> wkb_w = WKBWriter()
     563    >>> wkb_w.write_hex(pnt)
     564    '0101000000000000000000F03F000000000000F03F'
     565
     566.. attribute:: WKBWriter.byteorder
     567
     568This property may be be set to change the byte-order of the geometry
     569representation.
     570
     571=============== =================================================
     572Byteorder Value Description
     573=============== =================================================
     5740               Big Endian (e.g., compatible with RISC systems)
     5751               Little Endian (e.g., compatible with x86 systems)
     576=============== =================================================
     577
     578Example::
     579
     580    >>> from django.contrib.gis.geos import Point, WKBWriter
     581    >>> wkb_w = WKBWriter()
     582    >>> pnt = Point(1, 1)
     583    >>> wkb_w.write_hex(pnt)
     584    '0101000000000000000000F03F000000000000F03F'
     585    >>> wkb_w.byteorder = 0
     586    '00000000013FF00000000000003FF0000000000000'
     587
     588.. attribute:: WKBWriter.outdim
     589
     590This property may be set to change the output dimension of the geometry
     591representation.  In other words, if you have a 3D geometry then set to 3
     592so that the Z value is included in the WKB.
     593
     594============ ===========================
     595Outdim Value Description
     596============ ===========================
     5972            The default, output 2D WKB.
     5983            Output 3D EWKB.
     599============ ===========================
     600
     601Example::
     602
     603    >>> from django.contrib.gis.geos import Point, WKBWriter
     604    >>> wkb_w = WKBWriter()
     605    >>> wkb_w.outdim
     606    2
     607    >>> pnt = Point(1, 1, 1)
     608    >>> wkb_w.write_hex(pnt) # By default, no Z value included:
     609    '0101000000000000000000F03F000000000000F03F'
     610    >>> wkb_w.outdim = 3 # Tell writer to include Z values
     611    >>> wkb_w.write_hex(pnt)
     612    '0101000080000000000000F03F000000000000F03F000000000000F03F'
     613
     614.. attribute:: WKBWriter.srid
     615
     616Set this property with a boolean to indicate whether the SRID of the
     617geometry should be included with the WKB representation.  Example::
     618
     619    >>> from django.contrib.gis.geos import Point, WKBWriter
     620    >>> wkb_w = WKBWriter()
     621    >>> pnt = Point(1, 1, srid=4326)
     622    >>> wkb_w.write_hex(pnt) # By default, no SRID included:
     623    '0101000000000000000000F03F000000000000F03F'
     624    >>> wkb_w.srid = True # Tell writer to include SRID
     625    >>> wkb_w.write_hex(pnt)
     626    '0101000020E6100000000000000000F03F000000000000F03F'
     627
     628.. class:: WKTWriter
     629
     630.. method:: WKTWriter.write(geom)
     631
     632Returns the WKT of the given geometry. Example::
     633
     634    >>> from django.contrib.gis.geos import Point, WKTWriter
     635    >>> pnt = Point(1, 1)
     636    >>> wkt_w = WKTWriter()
     637    >>> wkt_w.write(pnt)
     638    'POINT (1.0000000000000000 1.0000000000000000)'
     639
     640
     641.. rubric:: Footnotes
     642.. [#] *See* `PostGIS EWKB, EWKT and Canonical Forms <http://postgis.refractions.net/docs/ch04.html#id2591381>`_, PostGIS documentation at Ch. 4.1.2.
  • docs/ref/contrib/gis/create_template_postgis-1.3.sh

     
     1#!/usr/bin/env bash
     2POSTGIS_SQL_PATH=`pg_config --sharedir`
     3createdb -E UTF8 template_postgis # Create the template spatial database.
     4createlang -d template_postgis plpgsql # Adding PLPGSQL language support.
     5psql -d postgres -c "UPDATE pg_database SET datistemplate='true' WHERE datname='template_postgis';"
     6psql -d template_postgis -f $POSTGIS_SQL_PATH/lwpostgis.sql # Loading the PostGIS SQL routines
     7psql -d template_postgis -f $POSTGIS_SQL_PATH/spatial_ref_sys.sql
     8psql -d template_postgis -c "GRANT ALL ON geometry_columns TO PUBLIC;" # Enabling users to alter spatial tables.
     9psql -d template_postgis -c "GRANT ALL ON spatial_ref_sys TO PUBLIC;"
  • docs/ref/contrib/gis/utils.txt

     
     1======================
     2GeoDjango Utilities
     3======================
     4
     5The ``django.contrib.gis.utils`` module contains various utilities that are
     6useful in creating geospatial web applications.
     7
     8.. toctree::
     9   :maxdepth: 2
     10
     11   geoip
     12   layermapping
  • docs/ref/contrib/index.txt

     
    3232   databrowse
    3333   flatpages
    3434   formtools/index
     35   gis/index
    3536   humanize
    3637   localflavor
    3738   messages
     
    111112
    112113See the :ref:`form wizard documentation <ref-contrib-formtools-form-wizard>`.
    113114
     115gis
     116====
     117
     118A world-class geospatial framework built on top of Django.
     119
     120Allows storage, manipulation and display of Geographic data.
     121
    114122humanize
    115123========
    116124
Back to Top