Ticket #12930: geodjango_doc_merge.diff
File geodjango_doc_merge.diff, 209.5 KB (added by , 15 years ago) |
---|
-
docs/index.txt
168 168 * :ref:`Databrowse <ref-contrib-databrowse>` 169 169 * :ref:`E-mail (sending) <topics-email>` 170 170 * :ref:`Flatpages <ref-contrib-flatpages>` 171 * :ref:`GeoDjango <ref-contrib-gis>` 171 172 * :ref:`Humanize <ref-contrib-humanize>` 172 173 * :ref:`Internationalization <topics-i18n>` 173 174 * :ref:`Jython support <howto-jython>` -
docs/ref/contrib/gis/create_template_postgis-1.4.sh
1 #!/usr/bin/env bash 2 POSTGIS_SQL_PATH=`pg_config --sharedir`/contrib 3 createdb -E UTF8 template_postgis # Create the template spatial database. 4 createlang -d template_postgis plpgsql # Adding PLPGSQL language support. 5 psql -d postgres -c "UPDATE pg_database SET datistemplate='true' WHERE datname='template_postgis';" 6 psql -d template_postgis -f $POSTGIS_SQL_PATH/postgis.sql # Loading the PostGIS SQL routines 7 psql -d template_postgis -f $POSTGIS_SQL_PATH/spatial_ref_sys.sql 8 psql -d template_postgis -c "GRANT ALL ON geometry_columns TO PUBLIC;" # Enabling users to alter spatial tables. 9 psql -d template_postgis -c "GRANT ALL ON spatial_ref_sys TO PUBLIC;" -
docs/ref/contrib/gis/measure.txt
Property changes on: docs/ref/contrib/gis/create_template_postgis-1.4.sh ___________________________________________________________________ Name: svn:executable + *
1 ================================================= 2 Measurement Units API (``Distance`` and ``Area``) 3 ================================================= 4 5 The `measure module`__ allows for convenient representation of distance and 6 area units of measure. [#]_ The module contains two objects, ``Distance`` 7 and ``Area`` -- both of which may be accessed via the ``D`` and ``A`` aliases, 8 respectively. 9 10 __ http://code.djangoproject.com/browser/django/branches/gis/django/contrib/gis/measure.py 11 12 The ``Distance`` and ``Area`` Objects 13 ===================================== 14 15 ``Distance`` objects may be instantiated using a keyword argument indicating the 16 context of the units. In the example below, two different distance objects are 17 instantiated 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 27 Conversions are easy, just access the preferred unit attribute name to get a 28 converted 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 35 Moreover, arithmetic operations may be performed between the distance 36 objects:: 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 43 Two ``Distance`` objects multiplied together will yield an ``Area`` object, 44 which uses squared units of measure:: 45 46 >>> a = d1 * d2 # Returns an Area object. 47 >>> print a 48 40.2336 sq_km 49 50 To determine what the attribute abbreviation of a unit is, the ``unit_attname`` 51 class 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 58 Supported units 59 =============== 60 61 ================================= ======================================== 62 Unit 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 98 prefixed 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 ================== 2 GeoDjango Tutorial 3 ================== 4 5 Introduction 6 ============ 7 8 GeoDjango is an add-on for Django that turns it into a world-class geographic 9 web framework. GeoDjango strives to make at as simple as possible to create 10 geographic 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 17 This tutorial assumes a familiarity with Django; thus, if you're brand new to 18 Django please read through the `regular tutorial`__ to introduce yourself with 19 Django concepts. GeoDjango has special prerequisites over what is required by Django -- 20 please consult the `GeoDjango installation documentation`_ for more details. 21 22 This tutorial is going to guide you through guide the user through the creation 23 of a geographic web application for viewing the `world borders`_. [#]_ Some of 24 the 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 40 Setting Up 41 ========== 42 43 Create 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 51 First, a spatial database needs to be created for our project. If using 52 PostgreSQL and PostGIS, then the following commands will 53 create 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 71 Users of SQLite and SpatiaLite should consult the instructions on how 72 to 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 77 Create GeoDjango Project 78 ------------------------ 79 80 Use the ``django-admin.py`` script like normal to create a ``geodjango`` project:: 81 82 $ django-admin.py startproject geodjango 83 84 With the project initialized, now create a ``world`` Django application within 85 the ``geodjango`` project:: 86 87 $ cd geodjango 88 $ python manage.py startapp world 89 90 Configure ``settings.py`` 91 ------------------------- 92 93 The ``geodjango`` project settings are stored in the ``settings.py`` file. Edit 94 the database connection settings appropriately:: 95 96 DATABASE_ENGINE = 'postgresql_psycopg2' 97 DATABASE_NAME = 'geodjango' 98 DATABASE_USER = 'geo' 99 100 In 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 113 Geographic Data 114 =============== 115 116 117 .. _worldborders: 118 119 World Borders 120 ------------- 121 122 The world borders data is available in this `zip file`__. Create a data directory 123 in 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 131 The world borders ZIP file contains a set of data files collectively known as 132 an `ESRI Shapefile`__, one of the most popular geospatial data formats. When 133 unzipped 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 145 Use ``ogrinfo`` to examine spatial data 146 --------------------------------------- 147 148 The GDAL ``ogrinfo`` utility is excellent for examining metadata about 149 shapefiles (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 156 Here ``ogrinfo`` is telling us that the shapefile has one layer, and that 157 layer contains polygon data. To find out more we'll specify the layer name 158 and 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 186 This detailed summary information tells us the number of features in the layer 187 (246), the geographical extent, the spatial reference system ("SRS WKT"), 188 as well as detailed information for each attribute field. For example, 189 ``FIPS: String (2.0)`` indicates that there's a ``FIPS`` character field 190 with a maximum length of 2; similarly, ``LON: Real (8.3)`` is a floating-point 191 field that holds a maximum of 8 digits up to three decimal places. Although 192 this information may be found right on the `world borders`_ website, this shows 193 you how to determine this information yourself when such metadata is not 194 provided. 195 196 Geographic Models 197 ================= 198 199 Defining a Geographic Model 200 --------------------------- 201 202 Now that we've examined our world borders data set using ``ogrinfo``, we can 203 create 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 235 Two important things to note: 236 237 1. The ``models`` module is imported from ``django.contrib.gis.db``. 238 2. The model overrides its default manager with ``GeoManager``; this is *required* 239 to perform spatial queries. 240 241 When declaring a geometry field on your model the default spatial reference system 242 is WGS84 (meaning the `SRID`__ is 4326) -- in other words, the field coordinates are in 243 longitude/latitude pairs in units of degrees. If you want the coordinate system to be 244 different, then SRID of the geometry field may be customized by setting the ``srid`` 245 with an integer corresponding to the coordinate system of your choice. 246 247 __ http://en.wikipedia.org/wiki/SRID 248 249 Run ``syncdb`` 250 -------------- 251 252 After you've defined your model, it needs to be synced with the spatial database. 253 First, let's look at the SQL that will generate the table for the ``WorldBorders`` 254 model:: 255 256 $ python manage.py sqlall world 257 258 This 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 281 If 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 288 The ``syncdb`` command may also prompt you to create an admin user; go ahead and 289 do so (not required now, may be done at any point in the future using the 290 ``createsuperuser`` management command). 291 292 Importing Spatial Data 293 ====================== 294 295 This section will show you how to take the data from the world borders 296 shapefile and import it into GeoDjango models using the `LayerMapping`_ 297 utility. There are many different different ways to import data in to a 298 spatial database -- besides the tools included within GeoDjango, you 299 may 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 313 GDAL Interface 314 -------------- 315 316 Earlier we used the the ``ogrinfo`` to explore the contents of the world borders 317 shapefile. Included within GeoDjango is an interface to GDAL's powerful OGR 318 library -- in other words, you'll be able explore all the vector data sources 319 that OGR supports via a Pythonic API. 320 321 First, invoke the Django shell:: 322 323 $ python manage.py shell 324 325 If the :ref:`worldborders` data was downloaded like earlier in the 326 tutorial, 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 334 Now, 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 342 Data source objects can have different layers of geospatial features; however, 343 shapefiles 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 351 You can see what the geometry type of the layer is and how many features it 352 contains:: 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 369 The ``Layer`` may also have a spatial reference system associated with 370 it -- if it does, the ``srs`` attribute will return a ``SpatialReference`` 371 object:: 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 383 Here we've noticed that the shapefile is in the popular WGS84 spatial reference 384 system -- in other words, the data uses units of degrees longitude and latitude. 385 386 In addition, shapefiles also support attribute fields that may contain 387 additional 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 392 Here we are examining the OGR types (e.g., whether a field is an integer or 393 a 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 398 You can iterate over each feature in the layer and extract information from both 399 the feature's geometry (accessed via the ``geom`` attribute) as well as the 400 feature's attribute fields (whose **values** are accessed via ``get()`` 401 method):: 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 416 And individual features may be retrieved by their feature ID:: 417 418 >>> feat = lyr[234] 419 >>> print feat.get('NAME') 420 San Marino 421 422 Here the boundary geometry for San Marino is extracted and looking 423 exported 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 435 We'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 465 A 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 483 Afterwards, invoke the Django shell from the ``geodjango`` project directory:: 484 485 $ python manage.py shell 486 487 Next, import the ``load`` module, call the ``run`` routine, and watch ``LayerMapping`` 488 do the work:: 489 490 >>> from world import load 491 >>> load.run() 492 493 494 Try ``ogrinspect`` 495 ------------------ 496 Now 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 498 use of the ``ogrinspect`` management command. The ``ogrinspect`` command 499 introspects a GDAL-supported vector data source (e.g., a shapefile) and 500 generates a model definition and ``LayerMapping`` dictionary automatically. 501 502 The general usage of the command goes as follows:: 503 504 $ python manage.py ogrinspect <data_source> <model_name> [options] 505 506 Where ``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 508 be used to further define how the model is generated. 509 510 For example, the following command nearly reproduces the ``WorldBorders`` model 511 and 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 515 A 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 523 The command produces the following output, which may be copied 524 directly 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 560 Spatial Queries 561 =============== 562 563 Spatial Lookups 564 --------------- 565 GeoDjango extends the Django ORM and allows the use of spatial lookups. 566 Let's do an example where we find the ``WorldBorder`` model that contains 567 a point. First, fire up the management shell:: 568 569 $ python manage.py shell 570 571 Now, define a point of interest [#]_:: 572 573 >>> pnt_wkt = 'POINT(-95.3385 29.7245)' 574 575 The ``pnt_wkt`` string represents the point at -95.3385 degrees longitude, 576 and 29.7245 degrees latitude. The geometry is in a format known as 577 Well Known Text (WKT), an open standard issued by the Open Geospatial 578 Consortium (OGC). [#]_ Import the ``WorldBorders`` model, and perform 579 a ``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 586 Here we retrieved a ``GeoQuerySet`` that has only one model: the one 587 for the United States (which is what we would expect). Similarly, 588 a `GEOS geometry object`_ may also be used -- here the ``intersects`` 589 spatial lookup is combined with the ``get`` method to retrieve 590 only 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 598 The ``contains`` and ``intersects`` lookups are just a subset of what's 599 available -- the `GeoDjango Database API`_ documentation has more. 600 601 .. _GEOS geometry object: geos.html 602 .. _GeoDjango Database API: db-api.html 603 604 Automatic Spatial Transformations 605 --------------------------------- 606 When querying the spatial database GeoDjango automatically transforms 607 geometries if they're in a different coordinate system. In the following 608 example, the coordinate will be expressed in terms of `EPSG SRID 32140`__, 609 a 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 615 Note that ``pnt`` may also constructed with EWKT, an "extended" form of 616 WKT that includes the SRID:: 617 618 >>> pnt = GEOSGeometry('SRID=32140;POINT(954158.1 4215137.1)') 619 620 When using GeoDjango's ORM, it will automatically wrap geometry values 621 in transformation SQL, allowing the developer to work at a higher level 622 of 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 638 Lazy Geometries 639 --------------- 640 Geometries come to GeoDjango in a standardized textual representation. Upon 641 access of the geometry field, GeoDjango creates a `GEOS geometry object`_, 642 exposing powerful functionality, such as serialization properties for 643 popular 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 655 This includes access to all of the advanced geometric operations provided by 656 the 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 668 Putting your data on the map 669 ============================ 670 671 Google 672 ------ 673 674 Geographic Admin 675 ---------------- 676 677 Basics 678 ^^^^^^ 679 680 GeoDjango also supplements the Django admin by allowing users to create 681 and modify geometries on a JavaScript slippy map (powered by `OpenLayers`_). 682 683 Let'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 691 Next, edit your ``urls.py`` in the ``geodjango`` project folder to look 692 as 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 703 Start up the Django development server:: 704 705 $ python manage.py runserver 706 707 Finally, browse to ``http://localhost:8000/admin/``, and log in with the admin 708 user created after running ``syncdb``. Browse to any of the ``WorldBorders`` 709 entries -- the borders may be edited by clicking on a polygon and dragging 710 the 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 722 With the ``OSMGeoAdmin``, GeoDjango uses a `Open Street Map`_ layer in the admin. 723 This provides more context (including street and thoroughfare details) than 724 available with the ``GeoModelAdmin`` (which uses the `Vector Map Level 0`_ 725 WMS data set hosted at `Metacarta`_). 726 727 First, 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 736 If you meet these requirements, then just substitute in the ``OSMGeoAdmin`` 737 option 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 ============================== 2 GeoIP API 3 ============================== 4 5 The ``GeoIP`` object is a ctypes wrapper for the 6 `MaxMind GeoIP C API`__. [#]_ This interface is a BSD-licensed alternative 7 to the GPL-licensed `Python GeoIP`__ interface provided by MaxMind. 8 9 In order to perform IP-based geolocation, the ``GeoIP`` object requires 10 the GeoIP C libary and either the GeoIP `Country`__ or `City`__ 11 datasets 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`` 13 and unzip them in a directory corresponding to what you set 14 ``GEOIP_PATH`` with in your settings. See the example and reference below 15 for 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 23 Example 24 =========================== 25 26 Assuming you have the GeoIP C library installed, here is an example of its 27 usage:: 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 51 Initialization 52 ============================== 53 54 The ``GeoIP`` object does not require any parameters to use the default 55 settings. However, at the very least the ``GEOIP_PATH`` setting should 56 be set with the path of the location of your GeoIP data sets. The 57 following intialization keywords may be used to customize any of the 58 defaults. 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 89 Querying 90 -------------------------- 91 92 All the following querying routines may take either a string IP address 93 or a fully qualified domain name (FQDN). For example, both 94 ``'24.124.1.80'`` and ``'djangoproject.com'`` would be valid query 95 parameters. 96 97 ``city(query)`` 98 ^^^^^^^^^^^^^^^^^^^^^^^^^^ 99 Returns a dictionary of city information for the given query. Some 100 of the values in the dictionary may be undefined (``None``). 101 102 ``country(query)`` 103 ^^^^^^^^^^^^^^^^^^^^^^^^^^ 104 Returns a dictionary with the country code and country for the given 105 query. 106 107 ``country_code(query)`` 108 ^^^^^^^^^^^^^^^^^^^^^^^^^^ 109 110 ``country_name(query)`` 111 ^^^^^^^^^^^^^^^^^^^^^^^^^^ 112 113 Coordinate 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 128 GeoIP Database Information 129 --------------------------- 130 131 ``country_info`` 132 ^^^^^^^^^^^^^^^^^^^^^^^^^^^ 133 This property returns information about the GeoIP country database. 134 135 ``city_info`` 136 ^^^^^^^^^^^^^^^^^^^^^^^^^^^ 137 This property returns information about the GeoIP city database. 138 139 ``info`` 140 ^^^^^^^^^^^^^^^^^^^^^^^^^^^ 141 This property returns information about all GeoIP databases (both city 142 and country). 143 144 GeoIP-Python API compatibility methods 145 ---------------------------------------- 146 147 [explanation] 148 149 ``open(path, cache)`` 150 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 151 This classmethod instantiates the GeoIP object from the given database path 152 and 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 ====================== 2 GeoDjango Installation 3 ====================== 4 5 Overview 6 ======== 7 In general, GeoDjango installation requires: 8 9 1. :ref:`python24` and :ref:`django` 10 2. :ref:`spatial_database` 11 3. :ref:`geospatial_libs` 12 13 Details for each of the requirements and installation instructions 14 are provided in the sections below. In addition, platform-specific 15 instructions are available for: 16 17 * :ref:`macosx` 18 * :ref:`ubuntudebian` 19 * :ref:`windows` 20 21 .. admonition:: Use the Source 22 23 Because GeoDjango takes advantage of the latest in the open source geospatial 24 software technology, recent versions of the libraries are necessary. 25 Unfortunately, binary packages are not available on many GNU/Linux systems 26 (GEOS 3, in particular). Thus, `installation from source`_ may be required. 27 When compiling the libraries from source, please follow the directions closely, 28 especially if you're a beginner. 29 30 .. _installation from source: install.html#building-from-source 31 32 Requirements 33 ============ 34 35 .. _python24: 36 37 Python 2.4+ 38 ----------- 39 Because of heavy use of the decorator syntax, Python 2.4 is minimum 40 version supported by GeoDjango. Python 2.5+ is recommended because the 41 `ctypes`__ module comes included; otherwise, 2.4 users will need to 42 `download and install ctypes`__. 43 44 __ http://docs.python.org/lib/module-ctypes.html 45 __ http://sourceforge.net/project/showfiles.php?group_id=71702 46 47 .. _django: 48 49 Django 50 ------ 51 52 Because GeoDjango is included with Django, please refer to Django's 53 `installation instructions`__ for details on how to install. 54 55 __ http://docs.djangoproject.com/en/dev/intro/install/ 56 57 .. _spatial_database: 58 59 Spatial Database 60 ---------------- 61 PostgreSQL (with PostGIS), MySQL, Oracle, and SQLite (with SpatiaLite) are 62 the spatial databases currently supported. 63 64 .. note:: 65 66 PostGIS is recommended, because it is the most mature and feature-rich 67 open source spatial database. 68 69 The geospatial libraries required for a GeoDjango installation depends 70 on the spatial database used. The following lists the library requirements, 71 supported versions, and any notes for each of the supported database backends: 72 73 ================== ============================== ================== ========================================================== 74 Database Library Requirements Supported Versions Notes 75 ================== ============================== ================== ========================================================== 76 PostgreSQL GEOS, PROJ.4, PostGIS 8.1+ Requires PostGIS. 77 MySQL GEOS 5.x Not OGC-compliant; limited functionality. 78 Oracle GEOS 10.2, 11 XE not supported; not tested with 9. 79 SQLite GEOS, GDAL, PROJ.4, SpatiaLite 3.6.2+ Requires SpatiaLite 2.3+, pysqlite2 2.5+, and Django 1.1. 80 ================== ============================== ================== ========================================================== 81 82 .. _geospatial_libs: 83 84 Geospatial Libraries 85 -------------------- 86 GeoDjango uses and/or provides interfaces for the the following open source 87 geospatial libraries: 88 89 ============== ==================================== ================================ ========================== 90 Program Description Required Supported Versions 91 ============== ==================================== ================================ ========================== 92 `GEOS`_ Geometry Engine Open Source Yes 3.1.x, 3.0.x 93 `PROJ.4`_ Cartographic Projections library Yes (PostgreSQL and SQLite only) 4.7.x, 4.6.x, 4.5.x, 4.4.x 94 `GDAL`_ Geospatial Data Abstraction Library No (but, required for SQLite) 1.6.x, 1.5.x, 1.4.x 95 `GeoIP`_ IP-based geolocation library No 1.4.x 96 `PostGIS`__ Spatial extensions for PostgreSQL Yes (PostgreSQL only) 1.4.x, 1.3.x, 1.2.1 97 `SpatiaLite`__ Spatial extensions for SQLite Yes (SQLite only) 2.3.x 98 ============== ==================================== ================================ ========================== 99 100 .. admonition:: Install GDAL 101 102 While :ref:`gdalbuild` is not required, it is *recommended*. 103 Some features of GeoDjango (including ``LayerMapping`` and the geographic 104 admin) depend on its functionality. 105 106 .. note:: 107 108 The GeoDjango interfaces to GEOS, GDAL, and GeoIP may be used 109 independently of Django. In other words, no database or settings file 110 required -- just import them as normal from ``django.contrib.gis``. 111 112 .. _GEOS: geos.html 113 .. _GDAL: gdal.html 114 .. _GeoIP: geoip.html 115 .. _PROJ.4: http://trac.osgeo.org/proj/ 116 117 __ http://postgis.refractions.net/ 118 __ http://www.gaia-gis.it/spatialite/index.html 119 120 .. _build_from_source: 121 122 Building from Source 123 ==================== 124 125 When installing from source on UNIX and GNU/Linux systems, please follow 126 the installation instructions carefully, and install the libraries in the 127 given order. If using MySQL or Oracle as the spatial database, only GEOS 128 is required. 129 130 .. note:: 131 132 OS X users are required to install `Apple Developer Tools`_ in order 133 to compile software from source. This is typically included on your 134 OS X installation DVDs. 135 136 .. _Apple Developer Tools: http://developer.apple.com/tools/xcode/ 137 138 .. _geosbuild: 139 140 GEOS 141 ---- 142 143 GEOS is a C++ library for performing geometric operations, and is the default 144 internal geometry representation used by GeoDjango (it's behind the "lazy" 145 geometries). Specifically, the C API library is called (e.g., ``libgeos_c.so``) 146 directly from Python using ctypes. 147 148 First, download GEOS 3.1.1 from the refractions website and untar the source 149 archive:: 150 151 $ wget http://download.osgeo.org/geos/geos-3.1.1.tar.bz2 152 $ tar xjf geos-3.1.1.tar.bz2 153 154 Next, change into the directory where GEOS was unpacked, run the configure 155 script, compile, and install:: 156 157 $ cd geos-3.1.1 158 $ ./configure 159 $ make 160 $ sudo make install 161 $ cd .. 162 163 Troubleshooting 164 ^^^^^^^^^^^^^^^ 165 166 Can't find GEOS Library 167 ~~~~~~~~~~~~~~~~~~~~~~~ 168 169 When GeoDjango can't find GEOS, this error is raised:: 170 171 ImportError: Could not find the GEOS library (tried "geos_c"). Try setting GEOS_LIBRARY_PATH in your settings. 172 173 The most common solution is to properly configure your :ref:`libsettings` *or* set 174 :ref:`geoslibrarypath` in your settings. 175 176 If using a binary package of GEOS (e.g., on Ubuntu 8.10), you may need to :ref:`binutils`. 177 178 .. _geoslibrarypath: 179 180 ``GEOS_LIBRARY_PATH`` 181 ~~~~~~~~~~~~~~~~~~~~~ 182 183 If your GEOS library is in a non-standard location, or you don't want to 184 modify the system's library path then the ``GEOS_LIBRARY_PATH`` setting 185 may be added to your Django settings file with the full path to the GEOS 186 C library. For example:: 187 188 GEOS_LIBRARY_PATH = '/home/bob/local/lib/libgeos_c.so' 189 190 .. note:: 191 192 The setting must be the *full* path to the **C** shared library; in 193 other words you want to use ``libgeos_c.so``, not ``libgeos.so``. 194 195 .. _proj4: 196 197 PROJ.4 198 ------ 199 200 `PROJ.4`_ is a library for converting geospatial data to different coordinate 201 reference systems. 202 203 First, download the PROJ.4 source code and datum shifting files [#]_:: 204 205 $ wget http://download.osgeo.org/proj/proj-4.7.0.tar.gz 206 $ wget http://download.osgeo.org/proj/proj-datumgrid-1.5.zip 207 208 Next, untar the source code archive, and extract the datum shifting files in the 209 ``nad`` subdirectory. This must be done *prior* to configuration:: 210 211 $ tar xzf proj-4.7.0.tar.gz 212 $ cd proj-4.7.0/nad 213 $ unzip ../../proj-datumgrid-1.5.zip 214 $ cd .. 215 216 Finally, configure, make and install PROJ.4:: 217 218 $ ./configure 219 $ make 220 $ sudo make install 221 $ cd .. 222 223 .. _postgis: 224 225 PostGIS 226 ------- 227 228 `PostGIS`__ adds geographic object support to PostgreSQL, turning it 229 into a spatial database. :ref:`geosbuild` and :ref:`proj4` should be 230 installed prior to building PostGIS. 231 232 .. note:: 233 234 The `psycopg2`_ module is required for use as the database adaptor 235 when using GeoDjango with PostGIS. Thus, the ``DATABASE_ENGINE`` 236 Django setting needs to be ``postgresql_psycopg2``. 237 238 .. _psycopg2: http://initd.org/projects/psycopg2 239 240 First download the source archive, and extract:: 241 242 $ wget http://postgis.refractions.net/download/postgis-1.4.0.tar.gz 243 $ tar xzf postgis-1.4.0.tar.gz 244 $ cd postgis-1.4.0 245 246 Next, configure, make and install PostGIS:: 247 248 $ ./configure 249 250 .. note:: 251 PostGIS versions before 1.4 did not consistently install PostGIS files 252 relative to PostgreSQL, so passing the an extra flag is recommended. 253 Thus, when building PostGIS versions 1.3.x and below modify the configuration 254 command to ensure standard placement of PostGIS SQL files:: 255 256 $ ./configure --datadir=`pg_config --sharedir` 257 258 Finally, make and install:: 259 260 $ make 261 $ sudo make install 262 $ cd .. 263 264 .. note:: 265 266 GeoDjango does not automatically create a spatial database. Please 267 consult the section on :ref:`spatialdb_template` for more information. 268 269 __ http://postgis.refractions.net/ 270 271 .. _gdalbuild: 272 273 GDAL 274 ---- 275 276 `GDAL`__ is an excellent open source geospatial library that has support for 277 reading most vector and raster spatial data formats. Currently, GeoDjango only 278 supports GDAL's vector data capabilities [#]_. :ref:`geosbuild` and :ref:`proj4` 279 should be installed prior to building GDAL. 280 281 First download the latest GDAL version and untar the archive:: 282 283 $ wget http://download.osgeo.org/gdal/gdal-1.6.2.tar.gz 284 $ tar xzf gdal-1.6.2.tar.gz 285 $ cd gdal-1.6.2 286 287 Configure, make and install:: 288 289 $ ./configure 290 $ make # Go get some coffee, this takes a while. 291 $ sudo make install 292 $ cd .. 293 294 .. note:: 295 296 Because GeoDjango has it's own Python interface, the preceding instructions 297 do not build GDAL's own Python bindings. The bindings may be built by 298 adding the ``--with-python`` flag when running ``configure``. See 299 `GDAL/OGR In Python`__ for more information on GDAL's bindings. 300 301 If you have any problems, please see the troubleshooting section below for 302 suggestions and solutions. 303 304 __ http://trac.osgeo.org/gdal/ 305 __ http://trac.osgeo.org/gdal/wiki/GdalOgrInPython 306 307 .. _gdaltrouble: 308 309 Troubleshooting 310 ^^^^^^^^^^^^^^^ 311 312 Can't find GDAL Library 313 ~~~~~~~~~~~~~~~~~~~~~~~ 314 315 When GeoDjango can't find the GDAL library, the ``HAS_GDAL`` flag 316 will be false:: 317 318 >>> from django.contrib.gis import gdal 319 >>> gdal.HAS_GDAL 320 False 321 322 The solution is to properly configure your :ref:`libsettings` *or* set 323 :ref:`gdallibrarypath` in your settings. 324 325 .. _gdallibrarypath: 326 327 ``GDAL_LIBRARY_PATH`` 328 ~~~~~~~~~~~~~~~~~~~~~ 329 330 If your GDAL library is in a non-standard location, or you don't want to 331 modify the system's library path then the ``GDAL_LIBRARY_PATH`` setting 332 may be added to your Django settings file with the full path to the GDAL 333 library. For example:: 334 335 GDAL_LIBRARY_PATH = '/home/sue/local/lib/libgdal.so' 336 337 .. _gdaldata: 338 339 Can't find GDAL data files (``GDAL_DATA``) 340 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 341 342 When installed from source, GDAL versions 1.5.1 and below have an autoconf bug 343 that places data in the wrong location. [#]_ This can lead to error messages 344 like this:: 345 346 ERROR 4: Unable to open EPSG support file gcs.csv. 347 ... 348 OGRException: OGR failure. 349 350 The solution is to set the ``GDAL_DATA`` environment variable to the location of the 351 GDAL data files before invoking Python (typically ``/usr/local/share``; use 352 ``gdal-config --datadir`` to find out). For example:: 353 354 $ export GDAL_DATA=`gdal-config --datadir` 355 $ python manage.py shell 356 357 If using Apache, you may need to add this environment variable to your configuration 358 file:: 359 360 SetEnv GDAL_DATA /usr/local/share 361 362 .. _spatialite: 363 364 SpatiaLite 365 ---------- 366 .. versionadded:: 1.1 367 368 .. note:: 369 370 Mac OS X users should follow the instructions in the :ref:`kyngchaos` section, 371 as it is much easier than building from source. 372 373 `SpatiaLite`__ adds spatial support to SQLite, turning it into a full-featured 374 spatial database. Because SpatiaLite has special requirements, it typically 375 requires SQLite and pysqlite2 (the Python SQLite DB-API adaptor) to be built from 376 source. :ref:`geosbuild` and :ref:`proj4` should be installed prior to building 377 SpatiaLite. 378 379 After installation is complete, don't forget to read the post-installation 380 docs on :ref:`create_spatialite_db`. 381 382 __ http://www.gaia-gis.it/spatialite/index.html 383 384 .. _sqlite: 385 386 SQLite 387 ^^^^^^ 388 389 Typically, SQLite packages are not compiled to include the `R*Tree module`__ -- 390 thus it must be compiled from source. First download the latest amalgamation 391 source archive from the `SQLite download page`__, and extract:: 392 393 $ wget http://www.sqlite.org/sqlite-amalgamation-3.6.17.tar.gz 394 $ tar xzf sqlite-amalgamation-3.6.17.tar.gz 395 $ cd sqlite-3.6.17 396 397 Next, run the ``configure`` script -- however the ``CFLAGS`` environment variable 398 needs to be customized so that SQLite knows to build the R*Tree module:: 399 400 $ CFLAGS="-DSQLITE_ENABLE_RTREE=1" ./configure 401 $ make 402 $ sudo make install 403 $ cd .. 404 405 .. note:: 406 407 If using Ubuntu, installing a newer SQLite from source can be very difficult 408 because it links to the existing ``libsqlite3.so`` in ``/usr/lib`` which 409 many other packages depend on. Unfortunately, the best solution at this time 410 is to overwrite the existing library by adding ``--prefix=/usr`` to the 411 ``configure`` command. 412 413 __ http://www.sqlite.org/rtree.html 414 __ http://www.sqlite.org/download.html 415 416 .. _spatialitebuild : 417 418 SpatiaLite Library (``libspatialite``) and Tools (``spatialite``) 419 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 420 421 After SQLite has been built with the R*Tree module enabled, get the latest 422 SpatiaLite library source and tools bundle from the `download page`__:: 423 424 $ wget http://www.gaia-gis.it/spatialite/libspatialite-amalgamation-2.3.1.tar.gz 425 $ wget http://www.gaia-gis.it/spatialite/spatialite-tools-2.3.1.tar.gz 426 $ tar xzf libspatialite-amalgamation-2.3.1.tar.gz 427 $ tar xzf spatialite-tools-2.3.1.tar.gz 428 429 Prior to attempting to build, please read the important notes below to see if 430 customization of the ``configure`` command is necessary. If not, then run the 431 ``configure`` script, make, and install for the SpatiaLite library:: 432 433 $ cd libspatialite-amalgamation-2.3.1 434 $ ./configure # May need to modified, see notes below. 435 $ make 436 $ sudo make install 437 $ cd .. 438 439 Finally, do the same for the SpatiaLite tools:: 440 441 $ cd spatialite-tools-2.3.1 442 $ ./configure # May need to modified, see notes below. 443 $ make 444 $ sudo make install 445 $ cd .. 446 447 .. note:: 448 449 If you've installed GEOS and PROJ.4 from binary packages, you will have to specify 450 their paths when running the ``configure`` scripts for *both* the library and the 451 tools (the configure scripts look, by default, in ``/usr/local``). For example, 452 on Debian/Ubuntu distributions that have GEOS and PROJ.4 packages, the command would be:: 453 454 $ ./configure --with-proj-include=/usr/include --with-proj-lib=/usr/lib --with-geos-include=/usr/include --with-geos-lib=/usr/lib 455 456 .. note:: 457 458 For Mac OS X users building from source, the SpatiaLite library *and* tools 459 need to be linked into the existing ``iconv`` library. While this happens 460 automatically on Linux, the ``configure`` scripts need to know about the 461 specific location on Mac OS X (via modification of the ``CFLAGS`` and 462 ``LDFLAGS`` environment variables prior to configuration):: 463 464 $ CFLAGS=-I/usr/include LDFLAGS="-L/usr/lib -liconv" ./configure 465 466 __ http://www.gaia-gis.it/spatialite/sources.html 467 468 .. _pysqlite2: 469 470 pysqlite2 471 ^^^^^^^^^ 472 473 Because SpatiaLite must be loaded as an external extension, it requires the 474 ``enable_load_extension`` method, which is only available in versions 2.5+. 475 Thus, download pysqlite2 2.5, and untar:: 476 477 $ wget http://pysqlite.googlecode.com/files/pysqlite-2.5.6.tar.gz 478 $ tar xzf pysqlite-2.5.6.tar.gz 479 $ cd pysqlite-2.5.6 480 481 Next, use a text editor (e.g., ``emacs`` or ``vi``) to edit the ``setup.cfg`` file 482 to look like the following:: 483 484 [build_ext] 485 #define= 486 include_dirs=/usr/local/include 487 library_dirs=/usr/local/lib 488 libraries=sqlite3 489 #define=SQLITE_OMIT_LOAD_EXTENSION 490 491 .. note:: 492 493 The important thing here is to make sure you comment out the the 494 ``define=SQLITE_OMIT_LOAD_EXTENSION`` flag and that the ``include_dirs`` 495 and ``library_dirs`` settings are uncommented and set to the appropriate 496 path if the SQLite header files and libraries are not in ``/usr/include`` 497 and ``/usr/lib``, respectively. 498 499 After modifying ``setup.cfg`` appropriately, then run the ``setup.py`` script 500 to build and install:: 501 502 $ sudo python setup.py install 503 504 Post-Installation 505 ================= 506 507 .. _spatialdb_template: 508 509 Creating a Spatial Database Template for PostGIS 510 ------------------------------------------------ 511 512 Creating a spatial database with PostGIS is different than normal because 513 additional SQL must be loaded to enable spatial functionality. Because of 514 the steps in this process, it's better to create a database template that 515 can be reused later. 516 517 First, you need to be able to execute the commands as a privileged database 518 user. For example, you can use the following to become the ``postgres`` user:: 519 520 $ sudo su - postgres 521 522 Once you're a database super user, then you may execute the following commands 523 to create a PostGIS spatial database template. If running Ubuntu :ref:`ibex` 524 or Debian :ref:`lenny`, please refer to their specific documentation for slight 525 modifications to these commands:: 526 527 $ POSTGIS_SQL_PATH=`pg_config --sharedir`/contrib 528 $ createdb -E UTF8 template_postgis # Creating the template spatial database. 529 $ createlang -d template_postgis plpgsql # Adding PLPGSQL language support. 530 $ psql -d postgres -c "UPDATE pg_database SET datistemplate='true' WHERE datname='template_postgis';" # Allows non-superusers the ability to create from this template 531 $ psql -d template_postgis -f $POSTGIS_SQL_PATH/postgis.sql # Loading the PostGIS SQL routines 532 $ psql -d template_postgis -f $POSTGIS_SQL_PATH/spatial_ref_sys.sql 533 $ psql -d template_postgis -c "GRANT ALL ON geometry_columns TO PUBLIC;" # Enabling users to alter spatial tables. 534 $ psql -d template_postgis -c "GRANT ALL ON spatial_ref_sys TO PUBLIC;" 535 536 These commands may be placed in a shell script for later use; for convenience, 537 the `create_template_postgis-1.4.sh`__ script is provided here. If using 538 PostGIS 1.3.x, please use the `create_template_postgis-1.3.sh`__ script 539 instead as the PostGIS SQL path and file names differ from 1.4. 540 541 Afterwards, you may create a spatial database by simply specifying 542 ``template_postgis`` as the template to use (via the ``-T`` option):: 543 544 $ createdb -T template_postgis <db name> 545 546 .. note:: 547 548 While the ``createdb`` command does not require database super-user privileges, 549 it must be executed by a database user that has permissions to create databases. 550 You can create such a user with the following command:: 551 552 $ createuser --createdb <user> 553 554 __ http://geodjango.org/docs/create_template_postgis-1.4.sh 555 __ http://geodjango.org/docs/create_template_postgis-1.3.sh 556 557 .. _create_spatialite_db: 558 559 Creating a Spatial Database for SpatiaLite 560 ------------------------------------------- 561 562 After the SpatiaLite library and tools have been installed, it is now possible 563 to create spatial database for use with GeoDjango. In order to do this, download 564 the spatial database initialization SQL from the `SpatiaLite Resources`__ page:: 565 566 $ wget http://www.gaia-gis.it/spatialite/init_spatialite-2.3.sql.gz 567 $ gunzip init_spatialite-2.3.sql.gz 568 569 Now, the ``spatialite`` command can be used to initialize a spatial database:: 570 571 $ spatialite geodjango.db < init_spatialite-2.3.sql 572 573 .. note:: 574 575 The parameter ``geodjango.db`` is the *filename* of the SQLite database 576 you want to use. Use the same in the ``DATABASE_NAME`` setting inside 577 your project's ``settings.py``. 578 579 580 __ http://www.gaia-gis.it/spatialite/resources.html 581 582 583 Add ``django.contrib.gis`` to ``INSTALLED_APPS`` 584 ------------------------------------------------ 585 586 Like other Django contrib applications, you will *only* need to add 587 ``django.contrib.gis`` to ``INSTALLED_APPS`` in your settings. This is the 588 so that ``gis`` templates can be located -- if not done, then features such as 589 the geographic admin or KML sitemaps will not function properly. 590 591 .. _addgoogleprojection: 592 593 Add Google Projection to ``spatial_ref_sys`` table 594 -------------------------------------------------- 595 596 .. note:: 597 598 In Django 1.1 this step is no longer required to use the geographic 599 admin with the OpenStreetMap base layer. 600 601 In order to use the geographic admin with the OpenStreetMap base layer 602 (e.g., you want to use ``OSMGeoAdmin``), then the so-called "Google" projection 603 must be added to your spatial database's ``spatial_ref_sys`` table. Invoke 604 the Django shell from your project and execute the following command:: 605 606 $ ./manage shell 607 >>> from django.contrib.gis.utils import add_postgis_srs 608 >>> add_postgis_srs(900913) 609 610 This adds an entry for the 900913 SRID to the ``spatial_ref_sys`` (or equivalent) 611 table, making it possible for the spatial database to transform coordinates in 612 this projection. You only need to execute this command *once* per spatial database. 613 614 Troubleshooting 615 =============== 616 617 If you can't find the solution to your problem here then participate in the 618 community! You can: 619 620 * Join the ``#geodjango`` IRC channel on FreeNode (may be accessed on the 621 web via `Mibbit`__). Please be patient and polite -- while you may not 622 get an immediate response, someone will attempt to answer your question 623 as soon as they see it. 624 * Ask your question on the `GeoDjango`__ mailing list. 625 * File a ticket on the `Django trac`__ if you think there's a bug. Make 626 sure to provide a complete description of the problem, versions used, 627 and specify the component as "GIS". 628 629 __ http://www.mibbit.com/?server=irc.freenode.net&channel=%23geodjango 630 __ http://groups.google.com/group/geodjango 631 __ http://code.djangoproject.com/simpleticket 632 633 .. _libsettings: 634 635 Library Environment Settings 636 ---------------------------- 637 638 By far, the most common problem when installing GeoDjango is that the 639 external shared libraries (e.g., for GEOS and GDAL) cannot be located. [#]_ 640 Typically, the cause of this problem is that the operating system isn't aware 641 of the directory where the libraries built from source were installed. 642 643 In general, the library path may be set on a per-user basis by setting 644 an environment variable, or by configuring the library path for the entire 645 system. 646 647 ``LD_LIBRARY_PATH`` environment variable 648 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 649 650 A user may set this environment variable to customize the library paths 651 they want to use. The typical library directory for software 652 built from source is ``/usr/local/lib``. Thus, ``/usr/local/lib`` needs 653 to be included in the ``LD_LIBRARY_PATH`` variable. For example, the user 654 could place the following in their bash profile:: 655 656 export LD_LIBRARY_PATH=/usr/local/lib 657 658 Setting System Library Path 659 ^^^^^^^^^^^^^^^^^^^^^^^^^^^ 660 661 On GNU/Linux systems, there is typically a file in ``/etc/ld.so.conf``, which may include 662 additional paths from files in another directory, such as ``/etc/ld.so.conf.d``. 663 As the root user, add the custom library path (like ``/usr/local/lib``) on a 664 new line in ``ld.so.conf``. This is *one* example of how to do so:: 665 666 $ sudo echo /usr/local/lib >> /etc/ld.so.conf 667 $ sudo ldconfig 668 669 For OpenSolaris users, the system library path may be modified using the 670 ``crle`` utility. Run ``crle`` with no options to see the current configuration 671 and use ``crle -l`` to set with the new library path. Be *very* careful when 672 modifying the system library path:: 673 674 # crle -l $OLD_PATH:/usr/local/lib 675 676 .. _binutils: 677 678 Install ``binutils`` 679 ^^^^^^^^^^^^^^^^^^^^ 680 681 GeoDjango uses the ``find_library`` function (from the ``ctypes.util`` Python 682 module) to discover libraries. The ``find_library`` routine uses a program 683 called ``objdump`` (part of the ``binutils`` package) to verify a shared 684 library on GNU/Linux systems. Thus, if ``binutils`` is not installed on your 685 Linux system then Python's ctypes may not be able to find your library even if 686 your library path is set correctly and geospatial libraries were built perfectly. 687 688 The ``binutils`` package may be installed on Debian and Ubuntu systems using the 689 following command:: 690 691 $ sudo apt-get install binutils 692 693 Similarly, on Red Hat and CentOS systems:: 694 695 $ sudo yum install binutils 696 697 Platform Specific Instructions 698 ============================== 699 700 .. _macosx: 701 702 Mac OS X 703 -------- 704 705 Because of the variety of packaging systems available for OS X, users have 706 several different options for installing GeoDjango. These options are: 707 708 * :ref:`kyngchaos` 709 * :ref:`fink` 710 * :ref:`macports` 711 * :ref:`build_from_source` 712 713 .. note:: 714 715 Currently, the easiest and recommended approach for installing GeoDjango 716 on OS X is to use the KyngChaos packages. 717 718 This section also includes instructions for installing an upgraded version 719 of :ref:`macosx_python` from packages provided by the Python Software 720 Foundation, however, this is not required. 721 722 .. _macosx_python: 723 724 Python 725 ^^^^^^ 726 727 Although OS X comes with Python installed, users can use framework 728 installers (`2.5`__ and `2.6`__ are available) provided by 729 the Python Software Foundation. An advantage to using the installer is 730 that OS X's Python will remain "pristine" for internal operating system 731 use. 732 733 __ http://python.org/ftp/python/2.5.4/python-2.5.4-macosx.dmg 734 __ http://python.org/ftp/python/2.6.2/python-2.6.2-macosx2009-04-16.dmg 735 736 .. note:: 737 738 You will need to modify the ``PATH`` environment variable in your 739 ``.profile`` file so that the new version of Python is used when 740 ``python`` is entered at the command-line:: 741 742 export PATH=/Library/Frameworks/Python.framework/Versions/Current/bin:$PATH 743 744 .. _kyngchaos: 745 746 KyngChaos Packages 747 ^^^^^^^^^^^^^^^^^^ 748 749 William Kyngesburye provides a number of `geospatial library binary packages`__ 750 that make it simple to get GeoDjango installed on OS X without compiling 751 them from source. However, the `Apple Developer Tools`_ are still necessary 752 for compiling the Python database adapters :ref:`psycopg2_kyngchaos` (for PostGIS) 753 and :ref:`pysqlite2_kyngchaos` (for SpatiaLite). 754 755 .. note:: 756 757 SpatiaLite users should consult the :ref:`spatialite_kyngchaos` section 758 after installing the packages for additional instructions. 759 760 Download the framework packages for: 761 762 * UnixImageIO 763 * PROJ 764 * GEOS 765 * SQLite3 (includes the SpatiaLite library) 766 * GDAL 767 768 Install the packages in the order they are listed above, as the GDAL and SQLite 769 packages require the packages listed before them. Afterwards, you can also 770 install the KyngChaos binary packages for `PostgreSQL and PostGIS`__. 771 772 After installing the binary packages, you'll want to add the following to 773 your ``.profile`` to be able to run the package programs from the command-line:: 774 775 export PATH=/Library/Frameworks/UnixImageIO.framework/Programs:$PATH 776 export PATH=/Library/Frameworks/PROJ.framework/Programs:$PATH 777 export PATH=/Library/Frameworks/GEOS.framework/Programs:$PATH 778 export PATH=/Library/Frameworks/SQLite3.framework/Programs:$PATH 779 export PATH=/Library/Frameworks/GDAL.framework/Programs:$PATH 780 export PATH=/usr/local/pgsql/bin:$PATH 781 782 __ http://www.kyngchaos.com/wiki/software:frameworks 783 __ http://www.kyngchaos.com/wiki/software:postgres 784 785 .. note:: 786 787 Use of these binaries requires Django 1.0.3 and above. If you are 788 using a previous version of Django (like 1.0.2), then you will have 789 to add the the following in your settings:: 790 791 GEOS_LIBRARY_PATH='/Library/Frameworks/GEOS.framework/GEOS' 792 GDAL_LIBRARY_PATH='/Library/Frameworks/GDAL.framework/GDAL' 793 794 .. _psycopg2_kyngchaos: 795 796 psycopg2 797 ~~~~~~~~ 798 799 After you've installed the KyngChaos binaries and modified your ``PATH``, as 800 described above, ``psycopg2`` may be installed using the following command:: 801 802 $ sudo python easy_install psycopg2 803 804 .. note:: 805 806 To use ``easy_install`` you'll need to install Python's `setuptools`_. 807 808 .. _setuptools: http://pypi.python.org/pypi/setuptools 809 810 .. _pysqlite2_kyngchaos: 811 812 pysqlite2 813 ~~~~~~~~~ 814 815 Follow the :ref:`pysqlite2` source install instructions, however, 816 when editing the ``setup.cfg`` use the following instead:: 817 818 [build_ext] 819 #define= 820 include_dirs=/Library/Frameworks/SQLite3.framework/unix/include 821 library_dirs=/Library/Frameworks/SQLite3.framework/unix/lib 822 libraries=sqlite3 823 #define=SQLITE_OMIT_LOAD_EXTENSION 824 825 .. _spatialite_kyngchaos: 826 827 SpatiaLite 828 ~~~~~~~~~~ 829 830 When :ref:`create_spatialite_db`, the ``spatialite`` program is required. 831 However, instead of attempting to compile the SpatiaLite tools from source, 832 download the `SpatiaLite Binaries`__ for OS X, and install ``spatialite`` in a 833 location available in your ``PATH``. For example:: 834 835 $ curl -O http://www.gaia-gis.it/spatialite/spatialite-tools-osx-x86-2.3.1.tar.gz 836 $ tar xzf spatialite-tools-osx-x86-2.3.1.tar.gz 837 $ cd spatialite-tools-osx-x86-2.3.1/bin 838 $ sudo cp spatialite /Library/Frameworks/SQLite3.framework/Programs 839 840 Finally, for GeoDjango to be able to find the KyngChaos SpatiaLite library, 841 add the following to your ``settings.py``:: 842 843 SPATIALITE_LIBRARY_PATH='/Library/Frameworks/SQLite3.framework/SQLite3' 844 845 __ http://www.gaia-gis.it/spatialite/binaries.html 846 847 .. _fink: 848 849 Fink 850 ^^^^ 851 852 `Kurt Schwehr`__ has been gracious enough to create GeoDjango packages for users 853 of the `Fink`__ package system. The following packages are available, depending 854 on which version of Python you want to use: 855 856 * ``django-gis-py26`` 857 * ``django-gis-py25`` 858 * ``django-gis-py24`` 859 860 __ http://schwehr.org/blog/ 861 __ http://www.finkproject.org/ 862 863 .. _macports: 864 865 MacPorts 866 ^^^^^^^^ 867 868 `MacPorts`__ may be used to install GeoDjango prerequisites on Macintosh 869 computers running OS X. Because MacPorts still builds the software from source, 870 the `Apple Developer Tools`_ are required. 871 872 Summary:: 873 874 $ sudo port install postgresql83-server 875 $ sudo port install geos 876 $ sudo port install proj 877 $ sudo port install postgis 878 $ sudo port install gdal 879 $ sudo port install libgeoip 880 881 .. note:: 882 883 You will also have to modify the ``PATH`` in your ``.profile`` so 884 that the MacPorts programs are accessible from the command-line:: 885 886 export PATH=/opt/local/bin:/opt/local/lib/postgresql83/bin 887 888 In addition, add the ``FALLBACK_DYLD_LIBRARY_PATH`` setting so that 889 the libraries can be found by Python:: 890 891 export FALLBACK_DYLD_LIBRARY_PATH=/opt/local/lib:/opt/local/lib/postgresql83 892 893 __ http://www.macports.org/ 894 895 .. _ubuntudebian: 896 897 Ubuntu & Debian GNU/Linux 898 ------------------------- 899 900 .. _ubuntu: 901 902 Ubuntu 903 ^^^^^^ 904 905 .. _heron: 906 907 8.04 and lower 908 ~~~~~~~~~~~~~~ 909 910 The 8.04 (and lower) versions of Ubuntu use GEOS v2.2.3 in their binary packages, 911 which is incompatible with GeoDjango. Thus, do *not* use the binary packages 912 for GEOS or PostGIS and build some prerequisites from source, per the instructions 913 in this document; however, it is okay to use the PostgreSQL binary packages. 914 915 For more details, please see the Debian instructions for :ref:`etch` below. 916 917 .. _ibex: 918 919 8.10 920 ~~~~ 921 922 Use the synaptic package manager to install the following packages:: 923 924 $ sudo apt-get install binutils libgdal1-1.5.0 postgresql-8.3-postgis postgresql-server-dev-8.3 python-psycopg2 python-setuptools 925 926 Afterwards, you may install Django with Python's ``easy_install`` script (the 927 Ubuntu package ``python-django`` uses an older version missing several 928 important bug fixes for GeoDjango):: 929 930 $ sudo easy_install Django 931 932 That's it! For the curious, the required binary prerequisites packages are: 933 934 * ``binutils``: for ctypes to find libraries 935 * ``postgresql-8.3`` 936 * ``postgresql-server-dev-8.3``: for ``pg_config`` 937 * ``postgresql-8.3-postgis``: for PostGIS 1.3.3 938 * ``libgeos-3.0.0``, and ``libgeos-c1``: for GEOS 3.0.0 939 * ``libgdal1-1.5.0``: for GDAL 1.5.0 library 940 * ``proj``: for PROJ 4.6.0 -- but no datum shifting files, see note below 941 * ``python-psycopg2`` 942 * ``python-setuptools``: for ``easy_install`` 943 944 Optional packages to consider: 945 946 * ``libgeoip1``: for `GeoIP`_ support 947 * ``gdal-bin``: for GDAL command line programs like ``ogr2ogr`` 948 * ``python-gdal`` for GDAL's own Python bindings -- includes interfaces for raster manipulation 949 950 .. note:: 951 952 The Ubuntu ``proj`` package does not come with the datum shifting files 953 installed, which will cause problems with the geographic admin because 954 the ``null`` datum grid is not available for transforming geometries to the 955 spherical mercator projection. A solution is to download the 956 datum-shifting files, create the grid file, and install it yourself:: 957 958 $ wget http://download.osgeo.org/proj/proj-datumgrid-1.4.tar.gz 959 $ mkdir nad 960 $ cd nad 961 $ tar xzf ../proj-datumgrid-1.4.tar.gz 962 $ nad2bin null < null.lla 963 $ sudo cp null /usr/share/proj 964 965 Otherwise, the Ubuntu ``proj`` package is fine for general use as long as you 966 do not plan on doing any database transformation of geometries to the 967 Google projection (900913). 968 969 .. note:: 970 971 The PostGIS SQL files are not placed the PostgreSQL share directory in the 972 Ubuntu packages. Use the `create_template_postgis-debian.sh`__ script 973 instead when :ref:`spatialdb_template`. 974 975 __ http://geodjango.org/docs/create_template_postgis-debian.sh 976 977 .. _debian: 978 979 Debian 980 ------ 981 982 .. _etch: 983 984 4.0 (Etch) 985 ^^^^^^^^^^ 986 The situation here is the same as that of Ubuntu :ref:`heron` -- in other words, 987 some packages must be built from source to work properly with GeoDjango. 988 989 Binary Packages 990 ~~~~~~~~~~~~~~~ 991 The following command will install acceptable binary packages, as well as 992 the development tools necessary to build the rest of the requirements:: 993 994 $ sudo apt-get install binutils bzip2 gcc g++ flex make postgresql-8.1 postgresql-server-dev-8.1 python-ctypes python-psycopg2 python-setuptools 995 996 Required package information: 997 998 * ``binutils``: for ctypes to find libraries 999 * ``bzip2``: for decompressing the source packages 1000 * ``gcc``, ``g++``, ``make``: GNU developer tools used to compile the libraries 1001 * ``flex``: required to build PostGIS 1002 * ``postgresql-8.1`` 1003 * ``postgresql-server-dev-8.1``: for ``pg_config`` 1004 * ``python-ctypes``: Python 2.4 needs to have ctypes installed separately 1005 * ``python-psycopg2`` 1006 * ``python-setuptools``: for ``easy_install`` 1007 1008 Optional packages: 1009 1010 * ``libgeoip``: for `GeoIP`_ support 1011 1012 Source Packages 1013 ~~~~~~~~~~~~~~~ 1014 You will still have to install :ref:`geosbuild`, :ref:`proj4`, 1015 :ref:`postgis`, and :ref:`gdalbuild` from source. Please follow the 1016 directions carefully. 1017 1018 .. _lenny: 1019 1020 5.0 (Lenny) 1021 ^^^^^^^^^^^ 1022 This version is comparable to Ubuntu :ref:`ibex`, so the command 1023 is very similar:: 1024 1025 $ 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 1026 1027 This assumes that you are using PostgreSQL version 8.3. Else, replace ``8.3`` 1028 in the above command with the appropriate PostgreSQL version. 1029 1030 .. note:: 1031 1032 Please read the note in the Ubuntu :ref:`ibex` install documentation 1033 about the ``proj`` package -- it also applies here because the package does 1034 not include the datum shifting files. 1035 1036 .. _post_install: 1037 1038 Post-installation Notes 1039 ~~~~~~~~~~~~~~~~~~~~~~~ 1040 1041 If the PostgreSQL database cluster was not initiated after installing, then it 1042 can be created (and started) with the following command:: 1043 1044 $ sudo pg_createcluster --start 8.3 main 1045 1046 Afterwards, the ``/etc/init.d/postgresql-8.3`` script should be used to manage 1047 the starting and stopping of PostgreSQL. 1048 1049 In addition, the SQL files for PostGIS are placed in a different location on 1050 Debian 5.0 . Thus when :ref:`spatialdb_template` either: 1051 1052 * Create a symbolic link to these files:: 1053 1054 $ sudo ln -s /usr/share/postgresql-8.3-postgis/{lwpostgis,spatial_ref_sys}.sql /usr/share/postgresql/8.3 1055 1056 If not running PostgreSQL 8.3, then replace ``8.3`` in the command above with the correct version. 1057 1058 * Or use the `create_template_postgis-debain.sh`__ to create the spatial database. 1059 If you're PostgreSQL version is not 8.3, you will have to modify the 1060 ``POSTGIS_SQL_PATH`` variable in the script. 1061 1062 __ http://geodjango.org/docs/create_template_postgis-debian.sh 1063 1064 .. _windows: 1065 1066 Windows XP 1067 ---------- 1068 1069 Python 1070 ^^^^^^ 1071 1072 First, download the `Python 2.6 installer`__ from the Python website. Next, 1073 execute the installer and use defaults, e.g., keep 'Install for all users' 1074 checked and the installation path set as ``C:\Python26``. 1075 1076 .. note:: 1077 1078 You may already have a version of Python installed in ``C:\python`` as ESRI 1079 products sometimes install a copy there. *You should still install a 1080 fresh version of Python 2.6.* 1081 1082 __ http://python.org/ftp/python/2.6.2/python-2.6.2.msi 1083 1084 PostgreSQL 1085 ^^^^^^^^^^ 1086 1087 First, select a mirror and download the latest `PostgreSQL 8.3 installer`__ from 1088 the EnterpriseDB website. 1089 1090 .. note:: 1091 1092 PostgreSQL 8.3 is required because PostGIS is not available yet for 8.4. 1093 1094 After downloading, simply click on the installer, follow the 1095 on-screen directions, and keep the default options (e.g., keep the installation 1096 path as ``C:\Program Files\PostgreSQL\8.3``). 1097 1098 .. note:: 1099 1100 This PostgreSQL installation process will create both a new windows user to be the 1101 'postgres service account' and a special 'postgres superuser' to own the database 1102 cluster. You will be prompted to set a password for both users (make sure to write 1103 them down!). To see basic details on the 'service user' account right click on 1104 'My Computer' and select 'Manage' or go to: Control Panel -> Administrative Tools -> 1105 Computer Management -> System Tools -> Local Users and Groups. 1106 1107 If installed successfully, the PostgreSQL server will run in the background each time 1108 the system as started as a Windows service. When finished, the installer should launch 1109 the Application Stack Builder (ASB) -- use this to install PostGIS, see instructions 1110 below for more details. A 'PostgreSQL 8.3' start menu group should be created that 1111 contains shortcuts for the ASB and 'Command Prompt', which launches a terminal window 1112 in the PostgreSQL directory. 1113 1114 __ http://www.enterprisedb.com/products/pgdownload.do#windows 1115 1116 PostGIS 1117 ^^^^^^^ 1118 1119 From the Application Stack Builder (Programs -> PostgreSQL 8.3), select 1120 'PostgreSQL Database Server 8.3 on port 5432' from the drop down menu. Next, 1121 select 'PostGIS 1.3.6 for PostgreSQL 8.3' from the 'Spatial Extensions' tree 1122 in the list. Select only the default options during install (do not uncheck 1123 the option to create a default PostGIS database). 1124 1125 .. note:: 1126 1127 You will be prompted to enter your 'postgres superuser' password in the 1128 'Database Connection Information' dialog. 1129 1130 psycopg2 1131 ^^^^^^^^ 1132 1133 The ``psycopg2`` Python module provides the interface between Python and the 1134 PostgreSQL database. Download the `Windows installer`__ (v2.0.10) and run 1135 using the default settings. [#]_ 1136 1137 __ http://www.stickpeople.com/projects/python/win-psycopg/psycopg2-2.0.10.win32-py2.6-pg8.3.7-release.exe 1138 1139 GeoDjango Installer 1140 ^^^^^^^^^^^^^^^^^^^ 1141 1142 Download the `GeoDjango Installer`__; this was created [#]_ to simplify the rest 1143 of the process for installing GeoDjango on Windows platforms. The installer 1144 automatically installs Django 1.1, GDAL 1.6.0, PROJ 4.6.1 (including datum grid 1145 files), and configures the necessary environment variables. 1146 1147 Once the installer has completed, log out and log back in so that the 1148 modifications to the system environment variables take effect, and you 1149 should be good to go. 1150 1151 .. note:: 1152 1153 The installer modifies the system ``Path`` environment variable to 1154 include ``C:\Program Files\PostgreSQL\8.3\bin`` and 1155 ``C:\Program Files\GeoDjango\bin``. This is required so that Python 1156 may find the GEOS DLL provided by PostGIS and the GDAL DLL provided 1157 by the installer. The installer also sets the ``GDAL_DATA`` and 1158 ``PROJ_LIB`` environment variables. 1159 1160 __ http://geodjango.org/windows/GeoDjango_Installer.exe 1161 1162 .. rubric:: Footnotes 1163 .. [#] The datum shifting files are needed for converting data to and from certain projections. 1164 For example, the PROJ.4 string for the `Google projection (900913) <http://spatialreference.org/ref/epsg/900913/proj4>`_ 1165 requires the ``null`` grid file only included in the extra datum shifting files. 1166 It is easier to install the shifting files now, then to have debug a problem caused by their absence later. 1167 .. [#] Specifically, GeoDjango provides support for the `OGR <http://gdal.org/ogr>`_ library, a component of GDAL. 1168 .. [#] See `GDAL ticket #2382 <http://trac.osgeo.org/gdal/ticket/2382>`_. 1169 .. [#] GeoDjango uses the `find_library <http://docs.python.org/library/ctypes.html#finding-shared-libraries>`_ 1170 routine from ``ctypes.util`` to locate shared libraries. 1171 .. [#] The ``psycopg2`` Windows installers are packaged and maintained by 1172 `Jason Erickson <http://www.stickpeople.com/projects/python/win-psycopg/>`_. 1173 .. [#] The source code for the installer is available in the `nsis_installer <http://geodjango.org/hg/nsis_installer/>`_ 1174 GeoDjango mercurial repository. -
docs/ref/contrib/gis/gdal.txt
1 ======== 2 GDAL API 3 ======== 4 5 `GDAL`__ stands for **G**\ eospatial **D**\ ata **A**\ bstraction **L**\ ibrary, 6 and is a veritable "swiss army knife" of GIS data functionality. It 7 also includes the `OGR`__ Simple Features Library, which specializes 8 in reading and writing geographic data in a variety of standard 9 formats. 10 11 __ http://www.gdal.org/ 12 __ http://www.gdal.org/ogr/ 13 14 Overview 15 ======== 16 17 Sample Data 18 ----------- 19 20 The GDAL/OGR tools described here are designed to help you read in 21 your geospatial data, in order for most of them to be useful you have 22 to have some data to work with. If you're starting out and don't yet 23 have any data of your own to use, GeoDjango comes with a number of 24 simple data sets that you can use for testing. This snippet will 25 determine where these sample files are installed on your computer:: 26 27 >>> import os 28 >>> import django.contrib.gis 29 >>> GIS_PATH = os.path.dirname(django.contrib.gis.__file__) 30 >>> CITIES_PATH = os.path.join(GIS_PATH, 'tests/layermap/cities/cities.shp') 31 32 ``DataSource`` 33 ============== 34 35 ``DataSource`` is a wrapper for the OGR data source object that 36 supports reading data from a variety of OGR-supported geospatial file 37 formats and data sources using a simple, consistent interface. Each 38 data source is represented by a ``DataSource`` object which contains 39 one or more layers of data. Each layer, represented by a ``Layer`` 40 object, contains some number of geographic features, as well as 41 information about the type of features contained in that layer (e.g. 42 points, polygons, etc.), as well as the names and types of any 43 additional fields of data that may be associated with each feature in 44 that layer. 45 46 The constructor for the ``DataSource`` object normally takes just a 47 single parameter, the path of the file you want to read. However, OGR 48 also supports a variety of more complex data sources, including 49 databases, that you access by passing it a special name string instead 50 of a path. For more information, see the `OGR Vector Formats`__ 51 documentation. The ``name`` property of a ``DataSource`` will tell 52 you the OGR name of the underlying data source that it is using. 53 54 Once you've created your ``DataSource``, you can find out how many 55 layers of data it contains by accessing the ``layer_count`` property, 56 or (equivalently) by using the ``len()`` function. For information on 57 accessing the layers of data themselves, see the next section:: 58 59 >>> from django.contrib.gis.gdal import DataSource 60 >>> ds = DataSource(CITIES_PATH) 61 >>> ds.name # The exact filename may be different on your computer 62 '/usr/local/lib/python2.6/site-packages/django/contrib/gis/tests/layermap/cities/cities.shp' 63 >>> ds.layer_count # This file only contains one layer 64 1 65 66 __ http://www.gdal.org/ogr/ogr_formats.html 67 68 ``Layer`` 69 --------- 70 71 ``Layer`` is a wrapper for a layer of data in a ``DataSource`` object. 72 You never create a ``Layer`` object directly. Instead, you retrieve 73 them from a ``DataSource`` object, which is essentially a standard 74 Python container of ``Layer`` objects. For example, you can access a 75 specific layer by its index (e.g. ``ds[0]`` to access the first 76 layer), or you can iterate over all the layers in the container in a 77 ``for`` loop. The ``Layer`` itself acts as a container for geometric 78 features. 79 80 All the features in a given layer have the same geometry type. The 81 ``geom_type`` property of a layer is an ``OGRGeomType`` object, 82 discussed below, that identifies the feature type. We can use it 83 to print out some basic information about each layer in a data source:: 84 85 >>> for layer in ds: 86 ... print 'Layer "%s": %i %ss' % (layer.name, len(layer), layer.geom_type.name) 87 ... 88 Layer "cities": 3 Points 89 90 The example output is from the cities data source, loaded above, which 91 evidently contains one layer, called ``"cities"``, which contains three 92 point features. For simplicity, the examples below assume that you've 93 stored that layer in the variable ``layer``:: 94 95 >>> layer = ds[0] 96 97 .. attribute:: name 98 99 Returns the name of this layer in the data source. 100 101 >>> layer.name 102 'cities' 103 104 .. attribute:: num_feat 105 106 Returns the number of features in the layer. Same as ``len(layer)``:: 107 108 >>> layer.num_feat 109 3 110 111 .. attribute:: geom_type 112 113 Returns the geometry type of the layer, as an ``OGRGeomType`` object 114 (see below):: 115 116 >>> layer.geom_type.name 117 'Point' 118 119 attribute:: get_geoms 120 121 A method that returns a list containing the geometry of each feature 122 in the layer. If the optional argument ``geos`` is set to ``True`` 123 then the geometries are converted to GEOS geometry objects. 124 Otherwise, they are returned as ``OGRGeometry`` objects (see below):: 125 126 >>> [pt.tuple for pt in layer.get_geoms()] 127 [(-104.609252, 38.255001), (-95.23506, 38.971823), (-95.363151, 29.763374)] 128 129 .. attribute:: num_fields 130 131 Returns the number of fields in the layer, i.e the number of fields of 132 data associated with each feature in the layer:: 133 134 >>> layer.num_fields 135 4 136 137 .. attribute:: fields 138 139 Returns a list of the names of each of the fields in this layer:: 140 141 >>> layer.fields 142 ['Name', 'Population', 'Density', 'Created'] 143 144 .. attribute field_types 145 146 Returns a list of the data types of each of the fields in this layer. 147 These are subclasses of ``Field``, discussed below:: 148 149 >>> [ft.__name__ for ft in layer.field_types] 150 ['OFTString', 'OFTReal', 'OFTReal', 'OFTDate'] 151 152 .. method:: get_fields() 153 154 A method that returns a list of the values of a given field for each 155 feature in the layer:: 156 157 >>> layer.get_fields('Name') 158 ['Pueblo', 'Lawrence', 'Houston'] 159 160 .. attribute:: field_widths 161 162 Returns a list of the maximum field widths for each of the fields in 163 this layer:: 164 165 >>> layer.field_widths 166 [80, 11, 24, 10] 167 168 .. attribute:: field_precisions 169 170 Returns a list of the numeric precisions for each of the fields in 171 this layer. This is meaningless (and set to zero) for non-numeric 172 fields:: 173 174 >>> layer.field_precisions 175 [0, 0, 15, 0] 176 177 .. attribute:: extent 178 179 Returns the spatial extent of this layer, as an ``Envelope`` object (see below):: 180 181 >>> layer.extent.tuple 182 (-104.609252, 29.763374, -95.23506, 38.971823) 183 184 .. attribute:: srs 185 186 Returns the spatial reference system used in this layer, as a 187 ``SpatialReference`` object (see below):: 188 189 >>> layer.srs.name 190 'GCS_WGS_1984' 191 192 ``Feature`` 193 ----------- 194 195 ``Feature`` wraps an OGR feature. You never create a ``Feature`` 196 object directly. Instead, you retrieve them from a ``Layer`` object. 197 Each feature consists of a geometry and a set of fields containing 198 additional properties. The geometry of a field is accessible via its 199 ``geom`` property, which returns an ``OGRGeometry`` object (discussed 200 below). A ``Feature`` behaves like a standard Python container for 201 its fields, which it returns as ``Field`` objects: you can access a 202 field directly by its index or name, or you can iterate over a 203 feature's fields, e.g. in a ``for`` loop. 204 205 .. attribute:: geom 206 207 Returns the geometry for this feature, as an ``OGRGeometry`` object:: 208 209 >>> city.geom.tuple 210 (-104.609252, 38.255001) 211 212 .. attribute:: get 213 214 A method that returns the value of the given field (specified by name) 215 for this feature, **not** a ``Field`` wrapper object:: 216 217 >>> city.get('Population') 218 102121 219 220 .. attribute:: geom_type 221 222 Returns the type of geometry for this feature, as an ``OGRGeomType`` 223 object. This will be the same for all features in a given layer, and 224 is equivalent to the ``geom_type`` property of the ``Layer`` object 225 itself. 226 227 .. attribute:: num_fields 228 229 Returns the number of fields of data associated with the feature. 230 This will be the same for all features in a given layer, and is 231 equivalent to the ``num_fields`` property of the ``Layer`` object 232 itself. 233 234 .. attribute:: fields 235 236 Returns a list of the names of the fields of data associated with the 237 feature. This will be the same for all features in a given layer, and 238 is equivalent to the ``fields`` property of the ``Layer`` object 239 itself. 240 241 .. attribute:: fid 242 243 Returns the feature identifier within the layer:: 244 245 >>> city.fid 246 0 247 248 .. attribute:: layer_name 249 250 Returns the name of the layer that the feature came from. This will 251 be the same for all features in a given layer:: 252 253 >>> city.layer_name 254 'cities' 255 256 .. attribute:: index 257 258 A method that returns the index of the given field name. This will be 259 the same for all features in a given layer:: 260 261 >>> city.index('Population') 262 1 263 264 ``Field`` 265 --------- 266 267 .. attribute:: name 268 269 Returns the name of this field:: 270 271 >>> city['Name'].name 272 'Name' 273 274 .. attribute:: type 275 276 Returns the OGR type of this field, as an integer. The 277 ``FIELD_CLASSES`` dictionary maps these values onto 278 subclasses of ``Field``:: 279 280 >>> city['Density'].type 281 2 282 283 .. attribute:: type_name 284 285 Returns a string with the name of the data type of this field:: 286 287 >>> city['Name'].type_name 288 'String' 289 290 .. attribute:: value 291 292 Returns the value of this field. The ``Field`` class itself 293 returns the value as a string, but each subclass returns the 294 value in the most appropriate form:: 295 296 >>> city['Population'].value 297 102121 298 299 .. attribute:: width 300 301 Returns the width of this field:: 302 303 >>> city['Name'].width 304 80 305 306 .. attribute:: precision 307 308 Returns the numeric precision of this field. This is meaningless (and 309 set to zero) for non-numeric fields:: 310 311 >>> city['Density'].precision 312 15 313 314 .. attribute:: as_double 315 316 Returns the value of the field as a double (float):: 317 318 >>> city['Density'].as_double() 319 874.7 320 321 .. attribute:: as_int 322 323 Returns the value of the field as an integer:: 324 325 >>> city['Population'].as_int() 326 102121 327 328 .. attribute:: as_string 329 330 Returns the value of the field as a string:: 331 332 >>> city['Name'].as_string() 333 'Pueblo' 334 335 .. attribute:: as_datetime 336 337 Returns the value of the field as a tuple of date and time components:: 338 339 >>> city['Created'].as_datetime() 340 (c_long(1999), c_long(5), c_long(23), c_long(0), c_long(0), c_long(0), c_long(0)) 341 342 .. attribute:: Driver 343 344 ``Driver`` is used internally to wrap an OGR data source driver. 345 346 347 Geometries 348 ========== 349 350 .. _ogrgeometry: 351 352 .. attribute:: OGRGeometry 353 354 ``OGRGeometry`` is a wrapper for the OGR `Geometry`__ class. 355 ``OGRGeometry`` objects can be instantiated from a string containing a 356 geometry object in WKT or HEX WKB format, a ``buffer`` containing WKB 357 data, or an ``OGRGeomType`` object. They are also returned when 358 reading geometry data from OGR data sources via a ``DataSource`` 359 object. 360 361 __ http://www.gdal.org/ogr/classOGRGeometry.html 362 363 ``OGRGeometry`` objects share some functionality with ``GEOSGeometry`` 364 objects. ``OGRGeometry`` objects are thin wrappers around OGR 365 geometry objects, and so they allow for more efficient access to data 366 when using ``DataSource``. Also, unlike its GEOS counterpart, 367 ``OGRGeometry`` supports spatial reference systems and their 368 transformation:: 369 370 >>> from django.contrib.gis.gdal import OGRGeometry 371 >>> polygon = OGRGeometry('POLYGON((0 0, 5 0, 5 5, 0 5))') 372 373 .. attribute:: dimension 374 375 Returns the number of coordinated dimensions of the geometry, i.e. 0 376 for points, 1 for lines, and so forth:: 377 378 >> polygon.dimension 379 2 380 381 .. attribute:: geom_count 382 383 Returns the number of elements in this geometry:: 384 385 >>> polygon.geom_count 386 1 387 388 .. attribute:: point_count 389 .. attribute:: num_points 390 .. attribute:: num_coords 391 392 These identical properties each return the number of points used to 393 describe this geometry:: 394 395 >>> polygon.point_count 396 4 397 398 .. attribute:: geom_type 399 400 Returns the type of this geometry, as an ``OGRGeomType`` object. 401 402 .. attribute:: geom_name 403 404 Returns the name of the type of this geometry:: 405 406 >>> polygon.geom_name 407 'POLYGON' 408 409 .. attribute:: area 410 411 Returns the area of this geometry, or 0 for geometries that do not 412 contain an area:: 413 414 >>> polygon.area 415 25.0 416 417 .. attribute:: envelope 418 419 Returns the envelope of this geometry, as an ``Envelope`` object. 420 421 .. attribute:: extent 422 423 Returns the envelope of this geometry as a 4-tuple, instead of as an 424 ``Envelope`` object:: 425 426 >>> point.extent 427 (0.0, 0.0, 5.0, 5.0) 428 429 .. attribute:: srs 430 431 This property controls the spatial reference for this geometry, or 432 None if no spatial reference system has been assigned to it. You 433 can get or set this property as a ``SpatialReference`` object:: 434 435 >>> city.geom.srs.name 436 'GCS_WGS_1984' 437 438 .. attribute:: srid 439 440 This property controls the spatial reference for this geometry, or 441 None if no spatial reference system has been assigned to it. You 442 can get or set this property as an integer ID. 443 444 .. attribute:: geos 445 446 Returns a ``GEOSGeometry`` object corresponding to this geometry. 447 448 .. attribute:: gml 449 450 Returns a string representation of this geometry in GML format:: 451 452 >>> OGRGeometry('POINT(1 2)').gml 453 '<gml:Point><gml:coordinates>1,2</gml:coordinates></gml:Point>' 454 455 .. attribute:: hex 456 457 Returns a string representation of this geometry in HEX WKB format:: 458 459 >>> OGRGeometry('POINT(1 2)').hex 460 '0101000000000000000000F03F0000000000000040' 461 462 .. attribute:: json 463 464 Returns a string representation of this geometry in JSON format:: 465 466 >>> OGRGeometry('POINT(1 2)').hex 467 '{ "type": "Point", "coordinates": [ 1.000000, 2.000000 ] }' 468 469 .. attribute:: wkb_size 470 471 Returns the size of the WKB buffer needed to hold a WKB representation 472 of this geometry:: 473 474 >>> OGRGeometry('POINT(1 2)').wkb_size 475 21 476 477 .. attribute:: wkb 478 479 Returns a ``buffer`` containing a WKB representation of this geometry. 480 481 .. attribute:: wkt 482 483 Returns a string representation of this geometry in WKT format. 484 485 .. function:: clone 486 487 Clones this geometry object. 488 489 .. function:: close_rings 490 491 If there are any rings within this geometry that have not been closed, 492 this routine will do so by adding the starting point to the end:: 493 494 >>> triangle = OGRGeometry('LINEARRING (0 0,0 1,1 0)') 495 >>> triangle.close_rings() 496 >>> triangle.wkt 497 'LINEARRING (0 0,0 1,1 0,0 0)' 498 499 .. function:: transform 500 501 Transforms this geometry to a different spatial reference system. May 502 take a ``CoordTransform`` object, a ``SpatialReference`` object, a WKT 503 or PROJ.4 string, or an integer SRID. By default nothing is returned 504 and the geometry is transformed in-place. However, if the `clone` 505 argument is set to ``True`` then a transformed clone of this geometry 506 will be returned instead. 507 508 .. function:: intersects 509 510 Returns ``True`` if this geometry intersects the other, otherwise returns 511 ``False``. 512 513 .. function:: equals 514 515 Returns ``True`` if this geometry is equivalent to the other, otherwise returns 516 ``False``. 517 518 .. function:: disjoint 519 520 Returns ``True`` if this geometry is spatially disjoint to (i.e. does 521 not intersect) the other, otherwise returns 522 ``False``. 523 524 .. function:: touches 525 526 Returns ``True`` if this geometry touches the other, otherwise returns 527 ``False``. 528 529 .. function:: crosses 530 531 Returns ``True`` if this geometry crosses the other, otherwise returns 532 ``False``. 533 534 .. function:: within 535 536 Returns ``True`` if this geometry is contained within the other, otherwise returns 537 ``False``. 538 539 .. function:: contains 540 541 Returns ``True`` if this geometry contains the other, otherwise returns 542 ``False``. 543 544 .. function:: overlaps 545 546 Returns ``True`` if this geometry overlaps the other, otherwise returns 547 ``False``. 548 549 .. function:: boundary 550 551 The boundary of this geometry, as a new ``OGRGeometry`` object. 552 553 .. attribute:: convex_hull 554 555 The smallest convex polygon that contains this geometry, as a new 556 ``OGRGeometry`` object. 557 558 .. function:: difference 559 560 Returns the region consisting of the difference of this geometry and 561 the other, as a new ``OGRGeometry`` object. 562 563 .. function:: intersection 564 565 Returns the region consisting of the intersection of this geometry and 566 the other, as a new ``OGRGeometry`` object. 567 568 .. function:: sym_difference 569 570 Returns the region consisting of the symmetric difference of this 571 geometry and the other, as a new ``OGRGeometry`` object. 572 573 .. function:: union 574 575 Returns the region consisting of the union of this geometry and 576 the other, as a new ``OGRGeometry`` object. 577 578 .. attribute:: x 579 580 Returns the X coordinate of a point geometry, or a list of X 581 coordinates of a LineString geometry. Not applicable to other 582 geometry types. 583 584 >>> OGRGeometry('POINT (1 2)').x 585 1.0 586 >>> OGRGeometry('LINESTRING (1 2,3 4)').x 587 [1.0, 3.0] 588 589 .. attribute:: y 590 591 Returns the X coordinate of a point geometry, or a list of X 592 coordinates of a LineString geometry. Not applicable to other 593 geometry types. 594 595 >>> OGRGeometry('POINT (1 2)').y 596 2.0 597 >>> OGRGeometry('LINESTRING (1 2,3 4)').y 598 [2.0, 4.0] 599 600 .. attribute:: z 601 602 Returns the Z coordinate of a point geometry, or a list of Z 603 coordinates of a LineString geometry. Returns ``None`` if the 604 geometry does not have Z coordinates. Not applicable to other 605 geometry types:: 606 607 >>> OGRGeometry('POINT (1 2 3)').z 608 3.0 609 >>> OGRGeometry('LINESTRING (1 2 3,4 5 6)').z 610 [3.0, 6.0] 611 612 .. attribute:: tuple 613 .. attribute:: coords 614 615 Returns the coordinates of a point geometry as a tuple, the 616 coordinates of a line geometry as a tuple of tuples, and so forth:: 617 618 >>> OGRGeometry('POINT (1 2)').tuple 619 (1.0, 2.0) 620 >>> OGRGeometry('LINESTRING (1 2,3 4)').tuple 621 ((1.0, 2.0), (3.0, 4.0)) 622 623 .. function:: add 624 625 Adds a geometry to this geometry collection. Not applicable to other 626 geometry types. 627 628 .. function:: shell 629 .. function:: exterior_ring 630 631 Returns the shell or exterior ring of this polygon, as a ``LinearRing`` 632 geometry. Not applicable to other geometry types. 633 634 .. function:: __len__ 635 636 Returns the number of points in a LineString, of the number of interior 637 rings in a Polygon, or the number of geometries in a 638 GeometryCollection. Not applicable to other geometry types. 639 640 .. function:: __iter__ 641 642 Iterates over the points in a LineString, of the interior rings in a 643 Polygon, or the geometries in a GeometryCollection. Not applicable to 644 other geometry types. 645 646 .. function:: __getitem__ 647 648 Returns the point at the specified index for this LineString, or the 649 interior ring at the specified index for this Polygon, or the geometry 650 at the specified index for this GeometryCollection. Not applicable to 651 other geometry types. 652 653 ``LineString`` 654 -------------- 655 656 A subclass of ``OGRGeometry`` representing a line string. 657 658 .. function:: shell 659 660 .. function:: point_count 661 662 .. function:: centroid 663 664 .. function:: OGRGeomType 665 666 The ``OGRGeomType`` class is makes it easy to specify an OGR geometry 667 type in any of several ways:: 668 669 >>> from django.contrib.gis.gdal import OGRGeomType 670 >>> gt1 = OGRGeomType(3) # Using an integer for the type 671 >>> gt2 = OGRGeomType('Polygon') # Using a string 672 >>> gt3 = OGRGeomType('POLYGON') # It's case-insensitive 673 >>> print gt1 == 3, gt1 == 'Polygon' # Equivalence works w/non-OGRGeomType objects 674 True True 675 676 .. attribute:: name 677 678 Returns a short-hand string form of the OGR Geometry type:: 679 680 >>> gt1.name 681 'Polygon' 682 683 .. attribute:: django 684 685 Returns the Django field type (a subclass of GeometryField) to use for 686 storing this OGR type, or ``None`` if there is no appropriate Django 687 type:: 688 689 >>> gt1.django 690 'PolygonField' 691 692 .. _spatialreference: 693 694 ``SpatialReference`` 695 ==================== 696 697 .. function:: attr_value 698 699 .. function:: auth_name 700 701 .. function:: auth_code 702 703 .. function:: clone 704 705 .. function:: identify_epsg 706 707 .. function:: validate 708 709 .. function:: name 710 711 .. function:: srid 712 713 .. function:: linear_name 714 715 .. function:: linear_units 716 717 .. function:: angular_name 718 719 .. function:: angular_units 720 721 .. function:: units 722 723 .. function:: ellisoid 724 725 .. function:: semi_major 726 727 .. function:: semi_minor 728 729 .. function:: inverse_flattening 730 731 .. function:: geographic 732 733 .. function:: local 734 735 .. function:: projected 736 737 .. function:: import_wkt 738 739 .. function:: import_proj 740 741 .. function:: import_epsg 742 743 .. function:: import_xml 744 745 .. function:: wkt 746 747 .. function:: pretty_wkt 748 749 .. function:: proj 750 .. function:: proj4 751 752 .. function:: xml 753 754 .. function:: to_esri 755 756 .. function:: from_esri 757 758 .. function:: CoordTransform 759 760 ``CoordTransform`` represents a coordinate system transform. It is 761 initialized with two ``SpatialReference``, representing the source and 762 target coordinate systems, respectively. 763 764 .. function:: Envelope 765 766 ``Envelope`` represents an OGR Envelope structure that contains the 767 minimum and maximum X, Y coordinates for a rectangle bounding box. 768 The naming of the variables is compatible with the OGR Envelope 769 structure. 770 771 .. function:: min_x 772 773 The value of the minimum X coordinate. 774 775 .. function:: min_y 776 777 The value of the maximum X coordinate. 778 779 .. function:: max_x 780 781 The value of the minimum Y coordinate. 782 783 .. function:: max_y 784 785 The value of the maximum Y coordinate. 786 787 .. function:: ur 788 789 The upper-right coordinate, as a tuple. 790 791 .. function:: ll 792 793 The lower-left coordinate, as a tuple. 794 795 .. function:: tuple 796 797 A tuple representing the envelope. 798 799 .. function:: wkt 800 801 A string representing this envelope as a polygon in WKT format. -
docs/ref/contrib/gis/index.txt
1 .. _ref-contrib-gis: 2 3 ========= 4 GeoDjango 5 ========= 6 7 .. versionadded:: 1.0 8 9 GeoDjango intends to be a world-class geographic web framework. Our goal is to make it as easy 10 as possible to build GIS web applications and harness the power of spatially enabled data. 11 12 .. toctree:: 13 :maxdepth: 2 14 15 tutorial 16 install 17 model-api 18 db-api 19 geos 20 measure 21 gdal 22 utils 23 feeds 24 sitemaps 25 testing 26 deployment -
docs/ref/contrib/gis/model-api.txt
1 =================== 2 GeoDjango Model API 3 =================== 4 5 This document explores the details of the GeoDjango Model API. Throughout this 6 section, we'll be using the following geographic model of a `ZIP code`__ as our 7 example:: 8 9 from django.contrib.gis.db import models 10 11 class Zipcode(models.Model): 12 code = models.CharField(max_length=5) 13 poly = models.PolygonField() 14 objects = models.GeoManager() 15 16 __ http://en.wikipedia.org/wiki/ZIP_code 17 18 Geometry Field Types 19 ==================== 20 21 The following geometry fields are available: 22 23 * ``PointField`` 24 * ``LineStringField`` 25 * ``PolygonField`` 26 * ``MultiPointField`` 27 * ``MultiLineStringField`` 28 * ``MultiPolygonField`` 29 * ``GeometryCollectionField`` 30 31 Each of these fields correspond with OpenGIS Simple Features [#]_. 32 33 Geometry Field Options 34 ---------------------- 35 36 In addition to the regular `field options`__ available for Django model fields, 37 geometry fields have the following additional options: 38 39 ====================== =================================================== 40 Argument Description 41 ====================== =================================================== 42 ``srid`` Sets the SRID [#]_ (Spatial Reference System 43 Identity) of the geometry field to the given value. 44 Defaults to 4326 (also known as `WGS84`__, units 45 are in degrees of longitude and latitude). 46 47 ``dim`` *New in version 1.2* 48 49 Sets the coordinate dimension for the geometry 50 field. By default, it is 2 (for two-dimensional 51 geometries), but may be set to 3 if GeoDjango 52 supports 3D geometries for your spatial backend and 53 GEOS 3.1 is installed. 54 55 ``spatial_index`` Defaults to True. Creates a spatial index for the 56 given geometry. Please note that this is different 57 from the ``db_index`` field option because 58 spatial indexes are created in a different manner 59 than regular database indexes. 60 ====================== =================================================== 61 62 __ http://docs.djangoproject.com/en/dev/ref/models/fields/#field-options 63 __ http://en.wikipedia.org/wiki/WGS84 64 65 Selecting an SRID 66 ^^^^^^^^^^^^^^^^^ 67 68 Choosing an appropriate SRID for your model is an important decision that the 69 developer should consider carefully. The SRID is an integer specifier that 70 corresponds to the projection system that will be used to interpret the data 71 in the spatial database. [#]_ Projection systems give the context to the 72 coordinates that specify a location. Although the details of `geodesy`__ are 73 beyond the scope of this documentation, the general problem is that the earth 74 is spherical and representations of the earth (e.g., paper maps, web maps) 75 are not. 76 77 Most people are familiar with using latitude and longitude to reference a 78 location on the earth's surface. However, latitude and longitude are angles, 79 not distances. [#]_ In other words, while the shortest path between two points on 80 a flat surface is a straight line, the shortest path between two points on a curved 81 surface (such as the earth) is an *arc* of a `great circle`__. [#]_ Thus, 82 additional computation is required to obtain distances in planar units (e.g., 83 kilometers and miles). Using a geographic coordinate system may introduce 84 complications for the developer later on. For example, PostGIS does not 85 have the capability to perform distance calculations between non-point 86 geometries using geographic coordinate systems, e.g., constructing a query to 87 find all points within 5 miles of a county boundary stored as WGS84. [#]_ 88 89 Portions of the earth's surface may projected onto a two-dimensional, or 90 Cartesian, plane. Projected coordinate systems are especially convenient 91 for region-specific applications, e.g., if you know that your database will 92 only cover geometries in `North Kansas`__, then you may consider using projection 93 system specific to that region. Moreover, projected coordinate systems are 94 defined in Cartesian units (such as meters or feet), easing distance 95 calculations. 96 97 Additional Resources: 98 99 * `spatialreference.org`__: A Django-powered database of spatial reference 100 systems. 101 * `The State Plane Coordinate System`__: A website covering the various 102 projection systems used in the United States. Much of the U.S. spatial 103 data encountered will be in one of these coordinate systems rather than 104 in a geographic coordinate system such as WGS84. 105 106 __ http://en.wikipedia.org/wiki/Geodesy 107 __ http://en.wikipedia.org/wiki/Great_circle 108 __ http://www.spatialreference.org/ref/epsg/2796/ 109 __ http://spatialreference.org/ 110 __ http://welcome.warnercnr.colostate.edu/class_info/nr502/lg3/datums_coordinates/spcs.html 111 112 ``GeoManager`` 113 ============== 114 115 In order to conduct geographic queries, each geographic model requires 116 a ``GeoManager`` model manager. This manager allows for the proper SQL 117 construction for geographic queries; thus, without it, all geographic filters 118 will fail. It should also be noted that ``GeoManager`` is required even if the 119 model does not have a geographic field itself, e.g., in the case of a 120 ``ForeignKey`` relation to a model with a geographic field. For example, 121 if we had an ``Address`` model with a ``ForeignKey`` to our ``Zipcode`` 122 model:: 123 124 from django.contrib.gis.db import models 125 from django.contrib.localflavor.us.models import USStateField 126 127 class Address(models.Model): 128 num = models.IntegerField() 129 street = models.CharField(max_length=100) 130 city = models.CharField(max_length=100) 131 state = USStateField() 132 zipcode = models.ForeignKey(Zipcode) 133 objects = models.GeoManager() 134 135 The geographic manager is needed to do spatial queries on related ``Zipcode`` objects, 136 for example:: 137 138 qs = Address.objects.filter(zipcode__poly__contains='POINT(-104.590948 38.319914)') 139 140 .. rubric:: Footnotes 141 .. [#] OpenGIS Consortium, Inc., `Simple Feature Specification For SQL <http://www.opengis.org/docs/99-049.pdf>`_, Document 99-049 (May 5, 1999). 142 .. [#] *See id.* at Ch. 2.3.8, p. 39 (Geometry Values and Spatial Reference Systems). 143 .. [#] 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. 144 .. [#] 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. 145 .. [#] 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. 146 .. [#] 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 ====================== 2 Testing GeoDjango Apps 3 ====================== 4 5 Creating a spatial database may require extra steps. To accommodate this, 6 GeoDjango includes a test runner that will scaffold a spatial database 7 automatically. To have your tests utilize the runner, just configure 8 your ``TEST_RUNNER`` in your settings like the following:: 9 10 TEST_RUNNER='django.contrib.gis.tests.run_tests' 11 12 If you want to run GeoDjango's test suite (do *not* use for testing your 13 applications) 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 25 Besides configuring the ``TEST_RUNNER`` setting, there are other options 26 to consider depending on your spatial backend (no additional 27 options or configuration instructions for the Oracle or MySQL spatial 28 backends). 29 30 PostGIS 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 42 Settings 43 -------- 44 45 ``POSTGIS_SQL_PATH`` 46 ^^^^^^^^^^^^^^^^^^^^ 47 48 If not using the ``POSTGIS_TEMPLATE`` setting, the GeoDjango test runner 49 assumes that the PostGIS SQL files (``lwpostgis.sql`` and 50 ``spatial_ref_sys.sql``) are installed in the directory specified by 51 the following command:: 52 53 $ pg_config --sharedir 54 55 If that command cannot be executed, the test runner will default to 56 ``/usr/local/share``, unless this setting is configured with a 57 different location. For example, some PostGIS packages for Ubuntu 58 put the files in a nonstandard location, and placing this in the 59 settings 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 69 If you have a PostGIS template already, then just configure with the 70 name of the template in your settings, for example:: 71 72 POSTGIS_TEMPLATE='template_postgis' 73 74 ``POSTGIS_VERSION`` 75 ^^^^^^^^^^^^^^^^^^^ 76 .. versionadded:: 1.1 77 78 When GeoDjango's spatial backend initializes on PostGIS, it has to perform 79 a SQL query to determine the version. Setting the version manually 80 prevents this query to the database:: 81 82 POSTGIS_VERSION=('1.3.6', 1, 3, 6) 83 84 Obtaining Sufficient Privileges 85 ------------------------------- 86 87 Depending on your configuration, this section describes several methods to 88 configure a database user with sufficient privileges to run tests for 89 GeoDjango applications on PostgreSQL. If your `spatial database template`_ 90 was created like in the instructions, then your testing database user 91 only needs to have the ability to create databases. In other configurations, 92 you may be required to use a superuser. 93 94 Create Database User 95 ^^^^^^^^^^^^^^^^^^^^ 96 To make database user with the ability to create databases, use the 97 following command:: 98 99 $ createuser --createdb -R -S <user_name> 100 101 The ``-R -S`` flags indicate that we do not want the user to have the ability 102 to create additional users (roles) or to be a superuser, respectively. 103 104 Alternatively, 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 109 Create Database Superuser 110 ^^^^^^^^^^^^^^^^^^^^^^^^^ 111 This may be done at the time the user is created, for example:: 112 113 $ createuser --superuser <user_name> 114 115 Or you may alter the user's role from the SQL shell (assuming this 116 is done from an existing superuser account):: 117 118 postgres# ALTER ROLE <user_name> SUPERUSER; 119 120 121 Create Local PostgreSQL Database 122 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 123 1. Initialize database: ``initdb -D /path/to/user/db`` 124 125 2. 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 129 3. Start this database ``pg_ctl -D /path/to/user/db start`` 130 131 Windows 132 ------- 133 On Windows platforms the pgAdmin III utility may also be used as 134 a simple way to add superuser privileges to your database user. 135 136 By default, the PostGIS installer on Windows includes a template 137 spatial database. Take advantage of it by adding this to your 138 settings:: 139 140 POSTGIS_TEMPLATE='template_postgis' 141 142 SpatiaLite 143 ========== 144 .. versionadded:: 1.1 145 146 You 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 151 If ``init_spatialite-2.3.sql`` is in the same path as your project's ``manage.py`` 152 script and your ``TEST_RUNNER`` is set, then all you have to do is:: 153 154 $ ./manage.py test 155 156 Settings 157 -------- 158 159 ``SPATIALITE_SQL`` 160 ^^^^^^^^^^^^^^^^^^ 161 .. versionadded:: 1.1 162 163 By default, the GeoDjango test runner looks for the SpatiaLite SQL in the 164 same 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 166 you 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 =================== 2 Deploying 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 13 Apache 14 ====== 15 In this section there are some example ``VirtualHost`` directives for 16 when deploying using either ``mod_python`` or ``mod_wsgi``. At this 17 time, we recommend ``mod_wsgi``, as it is now officially recommended 18 way to deploy Django applications with Apache. Moreover, if 19 ``mod_python`` is used, then a prefork version of Apache must also be 20 used. As long as ``mod_wsgi`` is configured correctly, it does not 21 matter 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 33 Example:: 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 56 For 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 64 Example:: 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 88 For more information, please consult Django's `mod_python documentation`__. 89 90 __ http://docs.djangoproject.com/en/dev/howto/deployment/modpython/ 91 92 Lighttpd 93 ======== 94 95 FastCGI 96 ------- 97 98 Nginx 99 ===== 100 101 FastCGI 102 ------- -
docs/ref/contrib/gis/create_template_postgis-debian.sh
1 #!/usr/bin/env bash 2 POSTGIS_SQL_PATH=/usr/share/postgresql-8.3-postgis 3 createdb -E UTF8 template_postgis # Create the template spatial database. 4 createlang -d template_postgis plpgsql # Adding PLPGSQL language support. 5 psql -d postgres -c "UPDATE pg_database SET datistemplate='true' WHERE datname='template_postgis';" 6 psql -d template_postgis -f $POSTGIS_SQL_PATH/lwpostgis.sql # Loading the PostGIS SQL routines 7 psql -d template_postgis -f $POSTGIS_SQL_PATH/spatial_ref_sys.sql 8 psql -d template_postgis -c "GRANT ALL ON geometry_columns TO PUBLIC;" # Enabling users to alter spatial tables. 9 psql -d template_postgis -c "GRANT ALL ON spatial_ref_sys TO PUBLIC;" -
docs/ref/contrib/gis/sitemaps.txt
Property changes on: docs/ref/contrib/gis/create_template_postgis-debian.sh ___________________________________________________________________ Name: svn:executable + *
1 =================== 2 Geographic Sitemaps 3 =================== 4 5 Google's sitemap protocol has been recently extended to support geospatial 6 content. [#]_ This includes the addition of the ``<url>`` child element 7 ``<geo:geo>``, which tells Google that the content located at the URL is 8 geographic in nature. [#]_ 9 10 Example 11 ======= 12 13 Reference 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 ================ 2 Geographic Feeds 3 ================ 4 5 GeoDjango has its own ``Feed`` subclass that may embed location information 6 in RSS/Atom feeds formatted according to either the `Simple GeoRSS`__ or 7 `W3C Geo`_ standards. Because GeoDjango's syndication API is a superset of 8 Django's, please consult `Django's syndication documentation`__ for details 9 on 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 16 Example 17 ======= 18 19 API Reference 20 ============= 21 22 ``Feed`` Subclass 23 ----------------- 24 25 In addition to methods provided by `base class`__ GeoDjango's ``Feed`` 26 class (from ``django.contrib.gis.feeds``) provides the following overrides. 27 Note 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 56 Takes the object returned by ``get_object()`` and returns the *feed's* 57 geometry. Typically this is a ``GEOSGeometry`` instance, or can be a 58 tuple 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 69 Set this to return the geometry for each *item* in the feed. This 70 can be a ``GEOSGeometry`` instance, or a tuple that represents a 71 point 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 ================ 2 ``LayerMapping`` 3 ================ 4 5 *Requirements:* The GDAL library must be installed. 6 7 The LayerMapping class provides a way to map the contents of OGR 8 vector files (e.g. shapefiles) to Geographic-enabled Django models. 9 10 This grew out of the author's personal needs; specifically, the code 11 repetition that went into pulling geometries and fields out of an OGR 12 layer, converting to another coordinate system (e.g. WGS84), and 13 inserting into a GeoDjango model. 14 15 Usage:: 16 17 lm = LayerMapping(model, data_source, mapping, 18 [layer=LAYER, source_srs=SRS, encoding=ENCODING, 19 transaction_mode=XMODE, transform=XFORM]) 20 lm.save([fid_range=FID_RANGE, progress=PROGRESS, silent=SILENT, 21 step=STEP, stream=STREAM, strict=STRICT, verbose=VERBOSE]) 22 23 .. warning :: 24 25 GIS data sources, like shapefiles, may be very large. If you find 26 that ``LayerMapping`` is using too much memory, set 27 ``DEBUG=False`` in your settings. When ``DEBUG=True`` Django automatically 28 logs *every* SQL query -- thus, when SQL statements contain geometries, it is 29 easy to consume more memory than usual. 30 31 Example 32 ======= 33 34 1. You need a GDAL-supported data source, like a shapefile (here we're using 35 a simple polygon shapefile, ``test_poly.shp``, with three features):: 36 37 >>> from django.contrib.gis.gdal import DataSource 38 >>> ds = DataSource('test_poly.shp') 39 >>> layer = ds[0] 40 >>> print layer.fields # Exploring the fields in the layer, we only want the 'str' field. 41 ['float', 'int', 'str'] 42 >>> print len(layer) # getting the number of features in the layer (should be 3) 43 3 44 >>> print layer.geom_type # Should be 3 (a Polygon) 45 3 46 >>> print layer.srs # WGS84 47 GEOGCS["GCS_WGS_1984", 48 DATUM["WGS_1984", 49 SPHEROID["WGS_1984",6378137,298.257223563]], 50 PRIMEM["Greenwich",0], 51 UNIT["Degree",0.017453292519943295]] 52 53 2. Now we define our corresponding Django model (make sure to use syncdb):: 54 55 from django.contrib.gis.db import models 56 57 class TestGeo(models.Model): 58 name = models.CharField(max_length=25) # corresponds to the 'str' field 59 poly = models.PolygonField(srid=4269) # we want our model in a different SRID 60 objects = models.GeoManager() 61 def __str__(self): 62 return 'Name: %s' % self.name 63 64 3. Use ``LayerMapping`` to extract all the features and place them in the database:: 65 66 >>> from django.contrib.gis.utils import LayerMapping 67 >>> from geoapp.models import TestGeo 68 >>> mapping = {'name' : 'str', # The 'name' model field maps to the 'str' layer field. 69 'poly' : 'POLYGON', # For geometry fields use OGC name. 70 } # The mapping is a dictionary 71 >>> lm = LayerMapping(TestGeo, 'test_poly.shp', mapping) 72 >>> lm.save(verbose=True) # Save the layermap, imports the data. 73 Saved: Name: 1 74 Saved: Name: 2 75 Saved: Name: 3 76 77 LayerMapping just transformed the three geometries from the SHP file from their 78 source spatial reference system (WGS84) to the spatial reference system of 79 the GeoDjango model (NAD83). If no spatial reference system is defined for 80 the layer, use the ``source_srs`` keyword with a SpatialReference object to 81 specify one. 82 83 API Reference 84 ============= 85 86 Initialization 87 -------------- 88 89 The following are the arguments and keywords that may be used during 90 instantiation of ``LayerMapping`` objects. 91 92 ================= ========================================================= 93 Argument Description 94 ================= ========================================================= 95 ``model`` The geographic model, *not* an instance. 96 97 ``data_source`` The path to the OGR-supported data source file 98 (e.g., a shapefile). Also accepts 99 ``gdal.DataSource`` instances. 100 101 ``mapping`` A dictionary: keys are strings corresponding to 102 the model field, and values correspond to 103 string field names for the OGR feature, or if the 104 model field is a geographic then it should 105 correspond to the OGR geometry type, 106 e.g., ``'POINT'``, ``'LINESTRING'``, ``'POLYGON'``. 107 ================= ========================================================= 108 109 ===================== ===================================================== 110 Keyword Arguments 111 ===================== ===================================================== 112 ``layer`` The index of the layer to use from the Data Source 113 (defaults to 0) 114 115 ``source_srs`` Use this to specify the source SRS manually (for 116 example, some shapefiles don't come with a '.prj' 117 file). An integer SRID, WKT or PROJ.4 strings, and 118 ``SpatialReference`` objects are accepted. 119 120 ``encoding`` Specifies the character set encoding of the strings 121 in the OGR data source. For example, 'latin-1', 122 'utf-8', and 'cp437' are all valid encoding 123 parameters. 124 125 ``transaction_mode`` May be 'commit_on_success' (default) or 126 'autocommit'. 127 128 ``transform`` Setting this to False will disable coordinate 129 transformations. In other words, geometries will 130 be inserted into the database unmodified from their 131 original state in the data source. 132 133 ``unique`` Setting this to the name, or a tuple of names, 134 from the given model will create models unique 135 only to the given name(s). Geometries will from 136 each feature will be added into the collection 137 associated with the unique model. Forces 138 the transaction mode to be 'autocommit'. 139 ===================== ===================================================== 140 141 Keyword Arguments for ``save()`` 142 -------------------------------- 143 144 The ``save()`` method also accepts keywords. These keywords are 145 used for controlling output logging, error handling, and for importing 146 specific feature ranges. 147 148 =========================== ================================================= 149 Save Keyword Arguments Description 150 =========================== ================================================= 151 ``fid_range`` May be set with a slice or tuple of 152 (begin, end) feature ID's to map from 153 the data source. In other words, this 154 keyword enables the user to selectively 155 import a subset range of features in the 156 geographic data source. 157 158 ``progress`` When this keyword is set, status information 159 will be printed giving the number of features 160 processed and successfully saved. By default, 161 progress information will be printed every 1000 162 features processed, however, this default may 163 be overridden by setting this keyword with an 164 integer for the desired interval. 165 166 ``silent`` By default, non-fatal error notifications are 167 printed to ``sys.stdout``, but this keyword may 168 be set to disable these notifications. 169 170 ``step`` If set with an integer, transactions will 171 occur at every step interval. For example, if 172 ``step=1000``, a commit would occur after the 173 1,000th feature, the 2,000th feature etc. 174 175 176 ``stream`` Status information will be written to this file 177 handle. Defaults to using ``sys.stdout``, but 178 any object with a ``write`` method is supported. 179 180 ``strict`` Execution of the model mapping will cease upon 181 the first error encountered. The default value 182 (``False``) 183 behavior is to attempt to continue. 184 185 ``verbose`` If set, information will be printed 186 subsequent to each model save 187 executed on the database. 188 =========================== ================================================= 189 190 Troubleshooting 191 =============== 192 193 Running out of memory 194 --------------------- 195 196 As noted in the warning at the top of this section, Django stores all SQL 197 queries when ``DEBUG=True``. Set ``DEBUG=False`` in your settings, and this 198 should stop excessive memory use when running ``LayerMapping`` scripts. 199 200 MySQL: ``max_allowed_packet`` error 201 ----------------------------------- 202 203 If you encounter the following error when using ``LayerMapping`` and MySQL:: 204 205 OperationalError: (1153, "Got a packet bigger than 'max_allowed_packet' bytes") 206 207 Then the solution is to increase the value of the ``max_allowed_packet`` 208 setting in your MySQL configuration. For example, the default value may 209 be something low like one megabyte -- the setting may be modified in MySQL's 210 configuration file (``my.cnf``) in the ``[mysqld]`` section:: 211 212 max_allowed_packet = 10M -
docs/ref/contrib/gis/db-api.txt
1 ====================== 2 GeoDjango Database API 3 ====================== 4 5 GeoDjango's lookup types may be used with any manager method like 6 ``filter()``, ``exclude()``, etc. However, the lookup types unique to 7 GeoDjango are only available with geographic fields. 8 Filters on 'normal' fields (e.g. ``CharField``) may be chained with those on 9 geographic fields. Thus, geographic queries take the following form (assuming 10 the ``Zipcode`` model used in the `GeoDjango Model API`_):: 11 12 >>> qs = Zipcode.objects.filter(<field>__<lookup_type>=<parameter>) 13 >>> qs = Zipcode.objects.exclude(...) 14 15 For example:: 16 17 >>> qs = Zipcode.objects.filter(poly__contains=pnt) 18 19 In this case, ``poly`` is the geographic field, ``contains`` is the lookup type, 20 and ``pnt`` is the parameter (which may be a ``GEOSGeometry`` object or a string 21 of GeoJSON , WKT, or HEXEWKB). 22 23 .. note:: 24 25 GeoDjango constructs spatial SQL with the ``GeoQuerySet``, a 26 subclass of Django's ``QuerySet``. The ``GeoManager`` instance 27 attached to your model allows it to use ``GeoQuerySet``. 28 29 .. _GeoDjango Model API: model-api.html 30 31 Creating and Saving Geographic Models 32 ===================================== 33 Here is an example of how to create a geometry object (assuming the ``Zipcode`` 34 model):: 35 36 >>> from zipcode.models import Zipcode 37 >>> z = Zipcode(code=77096, poly='POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))') 38 >>> z.save() 39 40 `GEOS geometry objects`_ may also be used to save geometric models:: 41 42 >>> from django.contrib.gis.geos import GEOSGeometry 43 >>> z = Zipcode(code=77096, poly=GEOSGeometry('POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))')) 44 >>> z.save() 45 46 Moreover, if the ``GEOSGeometry`` is in a different coordinate system (has a 47 different SRID value) than that of the field, then it will be implicitly 48 transformed into the SRID of the model's field, using the spatial database's 49 transform procedure:: 50 51 >>> 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' 52 >>> z = Zipcode(code=78212, poly=poly_3084) 53 >>> z.save() 54 >>> from django.db import connection 55 >>> print connection.queries[-1]['sql'] # printing the last SQL statement executed (requires DEBUG=True) 56 INSERT INTO "geoapp_zipcode" ("code", "poly") VALUES (78212, ST_Transform(ST_GeomFromWKB('\\001 ... ', 3084), 4326)) 57 58 Thus, geometry parameters may be passed in using the ``GEOSGeometry`` object, WKT 59 (Well Known Text [#]_), HEXEWKB (PostGIS specific -- a WKB geometry in 60 hexadecimal [#]_), and GeoJSON [#]_ (requires GDAL). Essentially, if the input is not a 61 ``GEOSGeometry`` object, the geometry field will attempt to create a ``GEOSGeometry`` 62 instance from the input. 63 64 Below are some examples of GEOS Geometry objects, WKT, and HEXEWKB, and 65 GeoJSON: 66 67 * GEOS Geometry:: 68 69 >>> from django.contrib.gis.geos import * 70 >>> pnt = Point(5, 23) 71 >>> ls = LineString((0, 0), (5, 23)) 72 >>> poly = GEOSGeometry('POLYGON (( 10 10, 10 20, 20 20, 20 15, 10 10))') 73 74 * WKT Polygon: ``'POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))'`` 75 * HEXEWKB Polygon : ``'0103000000010000000 ... 00000000000002440'`` 76 * GeoJSON Point: ``{ "type": "Point", "coordinates": [100.0, 0.0] }`` 77 78 .. _GEOS geometry objects: geos.html 79 80 Spatial Lookup Types 81 ==================== 82 83 PostGIS 84 ------- 85 86 Spatial Operators 87 ^^^^^^^^^^^^^^^^^ 88 89 The following lookup types correspond to PostGIS spatial operators. [#]_ 90 91 ``bbcontains`` 92 ~~~~~~~~~~~~~~ 93 Tests if the geometry field's bounding box completely contains the lookup 94 geometry's bounding box. 95 96 Example:: 97 98 Zipcode.objects.filter(poly__bbcontains=geom) 99 100 PostGIS equivalent:: 101 102 SELECT ... WHERE poly ~ geom 103 104 ``bboverlaps`` 105 ~~~~~~~~~~~~~~ 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 ``contained`` 118 ~~~~~~~~~~~~~ 119 Tests if the geometry field's bounding box is completely contained by the 120 lookup geometry's bounding box. 121 122 Example:: 123 124 Zipcode.objects.filter(poly__contained=geom) 125 126 PostGIS equivalent:: 127 128 SELECT ... WHERE poly @ geom 129 130 ``exact`` or ``same_as`` 131 ~~~~~~~~~~~~~~~~~~~~~~~~ 132 Tests actual geometric equality of the geometry field against the the given 133 lookup geometry, vertex-by-vertex. 134 135 The following examples are equivalent:: 136 137 Zipcode.objects.filter(poly__exact=geom) 138 Zipcode.objects.filter(poly=geom) 139 Zipcode.objects.filter(poly__same_as=geom) 140 141 PostGIS equivalent:: 142 143 SELECT ... WHERE poly ~= geom 144 145 ``left`` 146 ~~~~~~~~ 147 Tests if the geometry field's bounding box is strictly to the left of the 148 lookup geometry's bounding box. 149 150 Example:: 151 152 Zipcode.objects.filter(poly__left=geom) 153 154 PostGIS equivalent:: 155 156 SELECT ... WHERE poly << geom 157 158 ``right`` 159 ~~~~~~~~~ 160 Tests if the geometry field's bounding box is strictly to the right of the 161 lookup geometry's bounding box. 162 163 Example:: 164 165 Zipcode.objects.filter(poly__right=geom) 166 167 PostGIS equivalent:: 168 169 SELECT ... WHERE poly >> geom 170 171 ``overlaps_left`` 172 ~~~~~~~~~~~~~~~~~ 173 Tests if the geometry field's bounding box overlaps or is to the left of the lookup 174 geometry's bounding box. 175 176 Example:: 177 178 Zipcode.objects.filter(poly__overlaps_left=geom) 179 180 PostGIS equivalent:: 181 182 SELECT ... WHERE poly &< geom 183 184 ``overlaps_right`` 185 ~~~~~~~~~~~~~~~~~~ 186 Tests if the geometry field's bounding box overlaps or is to the right of the lookup 187 geometry's bounding box. 188 189 Example:: 190 191 Zipcode.objects.filter(poly__overlaps_right=geom) 192 193 PostGIS equivalent:: 194 195 SELECT ... WHERE poly &> geom 196 197 ``overlaps_above`` 198 ~~~~~~~~~~~~~~~~~~ 199 Tests if the geometry field's bounding box overlaps or is above the lookup 200 geometry's bounding box. 201 202 Example:: 203 204 Zipcode.objects.filter(poly__overlaps_above=geom) 205 206 PostGIS equivalent:: 207 208 SELECT ... WHERE poly |&> geom 209 210 ``overlaps_below`` 211 ~~~~~~~~~~~~~~~~~~ 212 Tests if the geometry field's bounding box overlaps or is below the lookup 213 geometry's bounding box. 214 215 Example:: 216 217 Zipcode.objects.filter(poly__overlaps_below=geom) 218 219 PostGIS equivalent:: 220 221 SELECT ... WHERE poly &<| geom 222 223 ``strictly_above`` 224 ~~~~~~~~~~~~~~~~~~ 225 Tests if the geometry field's bounding box is strictly above the lookup 226 geometry's bounding box. 227 228 Example:: 229 230 Zipcode.objects.filter(poly__strictly_above=geom) 231 232 PostGIS equivalent:: 233 234 SELECT ... WHERE poly |>> geom 235 236 ``strictly_below`` 237 ~~~~~~~~~~~~~~~~~~ 238 Tests if the geometry field's bounding box is strictly below the lookup 239 geometry's bounding box. 240 241 Example:: 242 243 Zipcode.objects.filter(poly__strictly_below=geom) 244 245 PostGIS equivalent:: 246 247 SELECT ... WHERE poly <<| geom 248 249 Geometry Relationship Functions 250 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 251 252 The following lookup types correspond to PostGIS geometry relationship 253 functions. [#]_ Please note that when using PostGIS 1.3.1 and above, index 254 support is automatically "inlined" -- in other words, the bounding box 255 equivalent is automatically evaluated prior to calling these, more 256 computationally expensive, functions. 257 258 ``contains`` 259 ~~~~~~~~~~~~ 260 Tests if the geometry field spatially contains the lookup geometry. 261 262 Example:: 263 264 Zipcode.objects.filter(poly__contains=geom) 265 266 PostGIS equivalent:: 267 268 SELECT ... WHERE ST_Contains(poly, geom) 269 270 ``coveredby`` 271 ~~~~~~~~~~~~~ 272 Tests if no point in the geometry field is outside the lookup geometry. [#]_ 273 Only available in PostGIS 1.3.1 and above. 274 275 Example:: 276 277 Zipcode.objects.filter(poly__coveredby=geom) 278 279 PostGIS equivalent:: 280 281 SELECT ... WHERE ST_CoveredBy(poly, geom) 282 283 ``covers`` 284 ~~~~~~~~~~ 285 Tests if no point in the lookup geometry is outside the geometry field. [#]_ 286 Only available in PostGIS 1.3.1 and above. 287 288 Example:: 289 290 Zipcode.objects.filter(poly__covers=geom) 291 292 PostGIS equivalent:: 293 294 SELECT ... WHERE ST_Covers(poly, geom) 295 296 ``crosses`` 297 ~~~~~~~~~~~ 298 Tests if the geometry field spatially crosses the lookup geometry. 299 300 Example:: 301 302 Zipcode.objects.filter(poly__crosses=geom) 303 304 PostGIS equivalent:: 305 306 SELECT ... WHERE ST_Crosses(poly, geom) 307 308 ``disjoint`` 309 ~~~~~~~~~~~~ 310 Tests if the geometry field is spatially disjoint from the lookup geometry. 311 312 Example:: 313 314 Zipcode.objects.filter(poly__disjoint=geom) 315 316 PostGIS equivalent:: 317 318 SELECT ... WHERE ST_Disjoint(poly, geom) 319 320 .. _dwithin_postgis: 321 322 ``dwithin`` 323 ~~~~~~~~~~~ 324 Tests if the geometry field is within the specified distance of the lookup 325 geometry; uses indexes if available. The lookup parameter is a two-element 326 tuple: ``(geom, distance)``, where ``distance`` is a ``Distance`` object or a 327 numeric value in units. Only available in PostGIS versions 1.3.1 and above. 328 329 .. admonition:: Distance Parameters and Geographic Coordinate Systems 330 331 The ``dwithin`` lookup is meant for projected coordinate systems 332 because PostGIS uses ``ST_Distance``, which calculates the 333 Cartesian distance between geometries. In other words, 334 this will not return accurate results for geographic coordinate 335 systems such as WGS84. Thus, an exception will be raised if a 336 ``Distance`` object is used on a geometry field in a geographic 337 coordinate system. 338 339 However, a numeric value is allowed for geometry fields in geographic 340 coordinate systems. This advanced usage allows users to limit 341 querysets by distance more efficiently using units of degrees. 342 343 Example:: 344 345 # If Zipcode uses a projected coordinate system, this is allowed. 346 Zipcode.objects.filter(poly__dwithin=(geom, D(mi=5))) 347 348 # If Zipcode uses a geographic coordinate system, then the 349 # distance unit must be a numeric value in units of degrees. 350 Zipcode.objects.filter(poly__dwithin=(geom, 0.5)) 351 352 PostGIS equivalent:: 353 354 SELECT ... WHERE ST_DWithin(poly, geom, <units value>) 355 356 ``equals`` 357 ~~~~~~~~~~ 358 Tests if the geometry field is spatially equal to the lookup geometry. 359 360 Example:: 361 362 Zipcode.objects.filter(poly__equals=geom) 363 364 PostGIS equivalent:: 365 366 SELECT ... WHERE ST_Equals(poly, geom) 367 368 ``intersects`` 369 ~~~~~~~~~~~~~~ 370 Tests if the geometry field spatially intersects the lookup geometry. 371 372 Example:: 373 374 Zipcode.objects.filter(poly__intersects=geom) 375 376 PostGIS equivalent:: 377 378 SELECT ... WHERE ST_Intersects(poly, geom) 379 380 ``overlaps`` 381 ~~~~~~~~~~~~ 382 Tests if the geometry field spatially overlaps the lookup geometry. 383 384 Example:: 385 386 Zipcode.objects.filter(poly__overlaps=geom) 387 388 PostGIS equivalent:: 389 390 SELECT ... WHERE ST_Overlaps(poly, geom) 391 392 ``relate`` 393 ~~~~~~~~~~ 394 Tests if the geometry field is spatially related to the the lookup geometry by 395 the values given in the intersection pattern matrix. The intersection pattern 396 matrix is a string comprising nine characters, which define intersections between 397 the interior, boundary, and exterior of the geometry field and the lookup geometry. 398 The intersection pattern matrix may only use the following characters: 399 ``1``, ``2``, ``T``, ``F``, or ``*``. This lookup type allows users to "fine tune" 400 a specific geometric relationship consistent with the DE-9IM model. [#]_ 401 402 Example:: 403 404 # A tuple lookup parameter is used to specify the geometry and 405 # the intersection pattern (the pattern here is for 'contains'). 406 Zipcode.objects.filter(poly__relate(geom, 'T*T***FF*')) 407 408 PostGIS equivalent:: 409 410 SELECT ... WHERE ST_Relate(poly, geom, 'T*T***FF*') 411 412 ``touches`` 413 ~~~~~~~~~~~ 414 Tests if the geometry field spatially touches the lookup geometry. 415 416 Example:: 417 418 Zipcode.objects.filter(poly__touches=geom) 419 420 PostGIS equivalent:: 421 422 SELECT ... WHERE ST_Touches(poly, geom) 423 424 ``within`` 425 ~~~~~~~~~~ 426 Tests if the geometry field is spatially within the lookup geometry. 427 428 Example:: 429 430 Zipcode.objects.filter(poly__within=geom) 431 432 PostGIS equivalent:: 433 434 SELECT ... WHERE ST_Within(poly, geom) 435 436 437 Oracle 438 ------ 439 For more information, see Oracle's `Spatial Operators`__ documentation. [#]_ 440 441 __ http://download.oracle.com/docs/html/B14255_01/sdo_operat.htm 442 443 ``contains`` 444 ^^^^^^^^^^^^ 445 Tests if the geometry field spatially contains the lookup geometry. 446 447 Example:: 448 449 Zipcode.objects.filter(poly__contains=geom) 450 451 Oracle equivalent:: 452 453 SELECT ... WHERE SDO_CONTAINS(poly, geom) 454 455 ``covers`` 456 ^^^^^^^^^^ 457 Tests if no point in the lookup geometry is outside the geometry field. 458 459 Oracle equivalent:: 460 461 SELECT ... WHERE SDO_COVERS(poly, geom) 462 463 ``coveredby`` 464 ^^^^^^^^^^^^^ 465 Tests if no point in the geometry field is outside the lookup geometry. 466 467 Oracle equivalent:: 468 469 SELECT ... WHERE SDO_COVEREDBY(poly, geom) 470 471 ``disjoint`` 472 ^^^^^^^^^^^^ 473 Tests if the geometry field is spatially disjoint from the lookup geometry. 474 475 Oracle equivalent:: 476 477 SELECT ... WHERE SDO_GEOM.RELATE(poly, 'DISJOINT', geom, 0.05) 478 479 ``dwithin`` 480 ^^^^^^^^^^^ 481 Tests if the geometry field is within the specified distance of the lookup 482 geometry; uses indexes if available. The lookup parameter is a two-element 483 tuple: ``(geom, distance)``, where ``distance`` is a ``Distance`` object or a 484 numeric value in units. 485 486 Oracle equivalent:: 487 488 SELECT ... WHERE SDO_WITHIN_DISTANCE(poly, geom, 'distance=distance') 489 490 ``equals``, ``exact``, ``same_as`` 491 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 492 Tests if the geometry field is spatially equal to the lookup geometry. 493 The following examples are equivalent on Oracle:: 494 495 Zipcode.objects.filter(poly=geom) 496 Zipcode.objects.filter(poly__exact=geom) 497 Zipcode.objects.filter(poly__equals=geom) 498 Zipcode.objects.filter(poly__same_as=geom) 499 500 Oracle equivalent:: 501 502 SELECT ... WHERE SDO_EQUALS(poly, geom) 503 504 ``intersects`` 505 ^^^^^^^^^^^^^^ 506 Tests if the geometry field spatially intersects the lookup geometry. 507 508 Oracle equivalent:: 509 510 SELECT ... WHERE SDO_OVERLAPBDYINTERSECT(poly, geom) 511 512 ``overlaps`` 513 ^^^^^^^^^^^^ 514 Tests if the geometry field spatially overlaps the lookup geometry. 515 516 Oracle equivalent:: 517 518 SELECT ... WHERE SDO_OVERLAPS(poly, geom) 519 520 ``relate`` 521 ^^^^^^^^^^ 522 Tests if the geometry field is spatially related to the the lookup geometry by 523 the given mask component. This lookup requires a tuple parameter, 524 ``(geom, mask)``, where ``mask`` is at least one of the nine-intersection 525 patterns: ``TOUCH``, ``OVERLAPBDYDISJOINT``, ``OVERLAPBDYINTERSECT``, 526 ``EQUAL``, ``INSIDE``, ``COVEREDBY``, ``CONTAINS``, ``COVERS``, ``ANYINTERACT``, 527 and ``ON``. Multiple masks may be combined with the logical Boolean operator 528 OR, for example, ``'inside+touch'``. [#]_ The mask relation strings are 529 case-insensitive. 530 531 Example:: 532 533 # A tuple lookup parameter is used to specify the geometry and 534 # the mask component. 535 Zipcode.objects.filter(poly__relate(geom, 'anyinteract')) 536 537 Oracle equivalent:: 538 539 SELECT ... WHERE SDO_RELATE(poly, geom, 'anyinteract') 540 541 ``touches`` 542 ^^^^^^^^^^^ 543 Tests if the geometry field spatially touches the lookup geometry. 544 545 Oracle equivalent:: 546 547 SELECT ... WHERE SDO_TOUCH(poly, geom) 548 549 ``within`` 550 ^^^^^^^^^^ 551 Tests if the geometry field is spatially within (inside) the lookup 552 geometry. 553 554 Oracle equivalent:: 555 556 SELECT ... WHERE SDO_INSIDE(poly, geom) 557 558 MySQL 559 ----- 560 For more information, see `Relations on Geometry Minimal Bounding Rectangles (MBRs)`__. [#]_ 561 562 __ http://dev.mysql.com/doc/refman/5.0/en/relations-on-geometry-mbr.html 563 564 ``bbcontains``, ``contains`` 565 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 566 * MySQL equivalent ``MBRContains(g1, g2)`` 567 568 ``contained``, ``within`` 569 ^^^^^^^^^^^^^^^^^^^^^^^^^ 570 * MySQL equivalent ``MBRWithin(g1, g2)`` 571 572 ``disjoint`` 573 ^^^^^^^^^^^^ 574 * MySQL equivalent ``MBRDisjoint(g1, g2)`` 575 576 ``equals``, ``exact``, ``same_as`` 577 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 578 * MySQL equivalent ``MBREqual(g1, g2)`` 579 580 ``intersects`` 581 ^^^^^^^^^^^^^^ 582 * MySQL equivalent ``MBRIntersects(g1, g2)`` 583 584 ``overlaps`` 585 ^^^^^^^^^^^^ 586 * MySQL equivalent ``MBROverlaps(g1, g2)`` 587 588 ``touches`` 589 ^^^^^^^^^^^ 590 * MySQL equivalent ``MBRTouches(g1, g2)`` 591 592 SpatiaLite 593 ---------- 594 595 For more information consult the `SpatiaLite SQL functions reference list`__. 596 597 __ http://www.gaia-gis.it/spatialite/spatialite-sql-2.3.1.html 598 599 ``bbcontains`` 600 ^^^^^^^^^^^^^^ 601 * SpatiaLite equivalient ``MbrContains(g1, g2)`` 602 603 ``bboverlaps`` 604 ^^^^^^^^^^^^^^ 605 * SpatiaLite equivalent ``MbrOverlaps(g1, g2)`` 606 607 ``contained`` 608 ^^^^^^^^^^^^^ 609 * SpatiaLite equivalent ``MbrWithin(g1, g2)`` 610 611 ``contains`` 612 ^^^^^^^^^^^^ 613 * SpatiaLite equivalent ``Contains(g1, g2)`` 614 615 ``crosses`` 616 ^^^^^^^^^^^ 617 * SpatiaLite equivalent ``Crosses(g1, g2)`` 618 619 ``disjoint`` 620 ^^^^^^^^^^^^ 621 * SpatiaLite equivalent ``Disjoint(g1, g2)`` 622 623 ``equals``, ``exact``, ``same_as`` 624 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 625 * SpatiaLite equivalent ``Equals(g1, g2)`` 626 627 ``intersects`` 628 ^^^^^^^^^^^^^^ 629 * SpatiaLite equivalent ``Intersects(g1, g2)`` 630 631 ``overlaps`` 632 ^^^^^^^^^^^^ 633 * SpatiaLite equivalent ``Overlaps(g1, g2)`` 634 635 ``relate`` 636 ^^^^^^^^^^ 637 * SpatiaLite equivalent ``Relate(geom, pattern)`` 638 639 ``touches`` 640 ^^^^^^^^^^^ 641 * SpatiaLite equivalent ``Touches(g1, g2)`` 642 643 ``within`` 644 ^^^^^^^^^^ 645 * SpatiaLite equivalent ``Within(g1, g2)`` 646 647 648 Distance Queries 649 ================ 650 651 Introduction 652 ------------ 653 Distance calculations with spatial data is tricky because, unfortunately, 654 the Earth is not flat. Some distance queries with fields in a geographic 655 coordinate system may have to be expressed differently because of 656 limitations in PostGIS. Please see the `Selecting an SRID`_ section in the 657 model API documentation for more details. 658 659 .. _Selecting an SRID: model-api.html#selecting-an-srid 660 661 Distance Lookups 662 ---------------- 663 *Availability*: PostGIS, Oracle, SpatiaLite 664 665 Distance lookups take a tuple parameter comprising: 666 667 #. A geometry to base calculations from; and 668 #. A number or ``Distance`` object containing the distance. 669 670 If a ``Distance`` [#]_ object is used, it may be expressed in 671 any units (the SQL generated will use units converted to those of the field); 672 otherwise, numeric parameters will be assumed to be in the units of the field. 673 674 .. note:: 675 676 For PostGIS users, the routine ``ST_distance_sphere`` 677 is used by default for calculating distances on geographic coordinate systems 678 -- which may only be called with point geometries [#]_. Thus, 679 geographic distance lookups on PostGIS are only allowed on ``PointField`` 680 model fields using points for the geographic parameter. 681 682 The following distance lookups are available: 683 684 * ``distance_lt`` 685 * ``distance_lte`` 686 * ``distance_gt`` 687 * ``distance_gte`` 688 * ``dwithin`` 689 690 In addition, there's the :ref:`distance` ``GeoQuerySet`` method. 691 692 For example, let's say we have a ``SouthTexasCity`` model (from the 693 `GeoDjango distance tests`__ ) on a *projected* coordinate system valid for cities 694 in southern Texas:: 695 696 from django.contrib.gis.db import models 697 698 class SouthTexasCity(models.Model): 699 name = models.CharField(max_length=30) 700 # A projected coordinate system (only valid for South Texas!) 701 # is used, units are in meters. 702 point = models.PointField(srid=32140) 703 objects = models.GeoManager() 704 705 Then distance queries may be performed as follows:: 706 707 >>> from django.contrib.gis.geos import * 708 >>> from django.contrib.gis.measure import D # ``D`` is a shortcut for ``Distance`` 709 >>> from geoapp import SouthTexasCity 710 # Distances will be calculated from this point, which does not have to be projected. 711 >>> pnt = fromstr('POINT(-96.876369 29.905320)', srid=4326) 712 # If numeric parameter, units of field (meters in this case) are assumed. 713 >>> qs = SouthTexasCity.objects.filter(point__distance_lte=(pnt, 7000)) 714 # Find all Cities within 7 km, > 20 miles away, and > 100 chains away (an obscure unit) 715 >>> qs = SouthTexasCity.objects.filter(point__distance_lte=(pnt, D(km=7))) 716 >>> qs = SouthTexasCity.objects.filter(point__distance_gte=(pnt, D(mi=20))) 717 >>> qs = SouthTexasCity.objects.filter(point__distance_gte=(pnt, D(chain=100))) 718 719 __ http://code.djangoproject.com/browser/django/trunk/django/contrib/gis/tests/distapp/models.py 720 721 .. _geoqs_methods: 722 723 ``GeoQuerySet`` Methods 724 ======================= 725 726 ``GeoQuerySet`` methods perform a spatial operation on each geographic 727 field in the queryset and store its output in a new attribute on the model 728 (which is generally the name of the ``GeoQuerySet`` method). 729 730 There are also aggregate ``GeoQuerySet`` methods which return a single value 731 instead of a queryset. This section will describe the API and availability 732 of every ``GeoQuerySet`` method available in GeoDjango. 733 734 With a few exceptions, the following keyword arguments may be used with all 735 ``GeoQuerySet`` methods: 736 737 ===================== ===================================================== 738 Keyword Argument Description 739 ===================== ===================================================== 740 ``field_name`` By default, ``GeoQuerySet`` methods use the first 741 geographic field encountered in the model. This 742 keyword should be used to specify another 743 geographic field (e.g., ``field_name='point2'``) 744 when there are multiple geographic fields in a model. 745 746 On PostGIS, the ``field_name`` keyword may also be 747 used on geometry fields in models that are related 748 via a ``ForeignKey`` relation (e.g., 749 ``field_name='related__point'``). 750 751 ``model_att`` By default, ``GeoQuerySet`` methods typically attach 752 their output in an attribute with the same name as 753 the ``GeoQuerySet`` method. Setting this keyword 754 with the desired attribute name will override this 755 default behavior. For example, 756 ``qs = Zipcode.objects.centroid(model_att='c')`` will 757 attach the centroid of the ``Zipcode`` geometry field 758 in a ``c`` attribute on every model rather than in a 759 ``centroid`` attribute. 760 761 This keyword is required if 762 a method name clashes with an existing 763 ``GeoQuerySet`` method -- if you wanted to use the 764 ``area()`` method on model with a ``PolygonField`` 765 named ``area``, for example. 766 ===================== ===================================================== 767 768 Aggregate Objects 769 ----------------- 770 .. versionadded:: 1.1 771 772 Example:: 773 774 >>> from django.contrib.gis.db.models import Extent, Union 775 >>> WorldBorders.objects.aggregate(Extent('mpoly'), Union('mpoly')) 776 777 ``Collect`` 778 ^^^^^^^^^^^ 779 780 Returns the same as the :ref:`collect` aggregate method. 781 782 ``Extent`` 783 ^^^^^^^^^^ 784 785 Returns the same as the :ref:`extent` aggregate method. 786 787 ``Extent3D`` 788 ^^^^^^^^^^^^ 789 .. versionadded:: 1.2 790 791 Returns the same as the :ref:`extent3d` aggregate method. 792 793 ``MakeLine`` 794 ^^^^^^^^^^^^ 795 796 Returns the same as the :ref:`makeline` aggregate method. 797 798 ``Union`` 799 ^^^^^^^^^ 800 801 Returns the same as the :ref:`unionagg` aggregate method. 802 803 Aggregate Methods 804 ----------------- 805 806 .. _collect: 807 808 ``collect()`` 809 ^^^^^^^^^^^^^ 810 .. versionadded:: 1.1 811 812 *Availability*: PostGIS 813 814 .. function:: collect() 815 816 Returns a ``GEOMETRYCOLLECTION`` or a ``MULTI`` geometry object from the geometry 817 column. This is analagous to a simplified version of the :ref:`unionagg` routine, 818 except it can be several orders of magnitude faster than peforming a union because 819 it simply rolls up geometries into a collection or multi object, not caring about 820 dissolving boundaries. 821 822 .. _extent: 823 824 ``extent()`` 825 ^^^^^^^^^^^^ 826 *Availability*: PostGIS, Oracle 827 828 .. function:: extent() 829 830 Returns the extent of the ``GeoQuerySet`` as a four-tuple, comprising the 831 lower left coordinate and the upper right coordinate. 832 833 Example:: 834 835 >>> qs = City.objects.filter(name__in=('Houston', 'Dallas')) 836 >>> print qs.extent() 837 (-96.8016128540039, 29.7633724212646, -95.3631439208984, 32.782058715820) 838 839 840 .. _extent3d: 841 842 ``extent3d()`` 843 ^^^^^^^^^^^^^^ 844 .. versionadded:: 1.2 845 846 *Availability*: PostGIS 847 848 .. function:: extent3d() 849 850 Returns the 3D extent of the ``GeoQuerySet`` as a six-tuple, comprising 851 the lower left coordinate and upper right coordinate. 852 853 Example:: 854 855 >>> qs = City.objects.filter(name__in=('Houston', 'Dallas')) 856 >>> print qs.extent3d() 857 (-96.8016128540039, 29.7633724212646, 0, -95.3631439208984, 32.782058715820, 0) 858 859 .. _makeline: 860 861 ``make_line()`` 862 ^^^^^^^^^^^^^^^ 863 *Availability*: PostGIS 864 865 .. function:: make_line() 866 867 Returns a ``LineString`` constructed from the point field geometries in the 868 ``GeoQuerySet``. Currently, ordering the queryset has no effect. 869 870 Example:: 871 872 >>> print City.objects.filter(name__in=('Houston', 'Dallas')).make_line() 873 LINESTRING (-95.3631510000000020 29.7633739999999989, -96.8016109999999941 32.7820570000000018) 874 875 .. _unionagg: 876 877 ``unionagg()`` 878 ^^^^^^^^^^^^^^ 879 *Availability*: PostGIS, Oracle, SpatiaLite 880 881 .. function:: unionagg() 882 883 This method returns a ``GEOSGeometry`` object comprising the union of every 884 geometry in the queryset. Please note that use of `unionagg` is processor intensive 885 and may take a significant amount of time on large querysets. 886 887 Example:: 888 889 >>> u = Zipcode.objects.unionagg() # This may take a long time. 890 >>> u = Zipcode.objects.filter(poly__within=bbox).unionagg() # A more sensible approach. 891 892 ===================== ===================================================== 893 Keyword Argument Description 894 ===================== ===================================================== 895 ``tolerance`` This keyword is for Oracle only. It is for the 896 tolerance value used by the ``SDOAGGRTYPE`` 897 procedure; the `Oracle documentation`__ has more 898 details. 899 ===================== ===================================================== 900 901 __ http://download.oracle.com/docs/html/B14255_01/sdo_intro.htm#sthref150 902 903 Measurement 904 ----------- 905 *Availability*: PostGIS, Oracle, SpatiaLite 906 907 .. _area 908 909 ``area()`` 910 ^^^^^^^^^^ 911 912 .. function:: area() 913 Returns the area of the geographic field in an ``area`` attribute on 914 each element of this GeoQuerySet. 915 916 .. _distance: 917 918 ``distance(geom)`` 919 ^^^^^^^^^^^^^^^^^^ 920 921 .. function:: distance(geom) 922 923 This method takes a geometry as a parameter, and attaches a ``distance`` 924 attribute to every model in the returned queryset that contains the 925 distance (as a ``Distance`` object) to the given geometry. 926 927 In the following example (taken from the `GeoDjango distance tests`__), 928 the distance from the `Tasmanian`__ city of Hobart to every other 929 ``PointField`` in the ``AustraliaCity`` queryset is calculated:: 930 931 >>> pnt = AustraliaCity.objects.get(name='Hobart').point 932 >>> for city in AustraliaCity.objects.distance(pnt): print city.name, city.distance 933 Wollongong 990071.220408 m 934 Shellharbour 972804.613941 m 935 Thirroul 1002334.36351 m 936 Mittagong 975691.632637 m 937 Batemans Bay 834342.185561 m 938 Canberra 598140.268959 m 939 Melbourne 575337.765042 m 940 Sydney 1056978.87363 m 941 Hobart 0.0 m 942 Adelaide 1162031.83522 m 943 Hillsdale 1049200.46122 m 944 945 .. note:: 946 947 Because the ``distance`` attribute is a ``Distance`` object, you can 948 easily express the value in the units of your choice. For example, 949 ``city.distance.mi`` is the distance value in miles and 950 ``city.distance.km`` is the distance value in kilometers. See the 951 `distance documentation`_ for usage details and the list of 952 `supported units`_. 953 954 .. _distance documentation: measure.html#the-distance-and-area-objects 955 .. _supported units: measure.html#supported-units 956 957 __ http://en.wikipedia.org/wiki/Tasmania 958 __ http://code.djangoproject.com/browser/django/trunk/django/contrib/gis/tests/distapp/models.py 959 960 ``length()`` 961 ^^^^^^^^^^^^ 962 .. function:: length() 963 Returns the length of the geometry field in a ``length`` attribute 964 (a ``Distance`` object) on each model in the queryset. 965 966 ``perimeter()`` 967 ^^^^^^^^^^^^^^^ 968 .. function:: perimiter() 969 Returns the perimeter of the geometry field in a ``perimeter`` attribute 970 (a ``Distance`` object) on each model in the queryset. 971 972 Geometry Methods 973 ---------------- 974 975 With the exception of ``transform``, all of the following attach geometry objects 976 to each element of the ``GeoQuerySet`` that is the result of the method. 977 978 ``centroid()`` 979 ^^^^^^^^^^^^^^ 980 *Availability*: PostGIS, Oracle, SpatiaLite 981 982 .. function:: centroid() 983 Returns the ``centroid`` value for the geographic field in a ``centroid`` 984 attribute on each element of the ``GeoQuerySet``. 985 986 ``envelope()`` 987 ^^^^^^^^^^^^^^ 988 *Availability*: PostGIS, SpatiaLite 989 990 .. function:: envelope() 991 Returns a geometry representing the bounding box of the geometry field in 992 an ``envelope`` attribute on each element of the ``GeoQuerySet``. 993 994 ``point_on_surface()`` 995 ^^^^^^^^^^^^^^^^^^^^^^ 996 *Availability*: PostGIS, Oracle, SpatiaLite 997 998 .. function: point_on_surface() 999 Returns a Point geometry guaranteed to lie on the surface of the 1000 Geometry field in a `point_on_surface` attribute on each element 1001 of this GeoQuerySet; otherwise sets with None. 1002 1003 ``scale(x, y, z=0.0)`` 1004 ^^^^^^^^^^^^^^^^^^^^^^ 1005 *Availability*: PostGIS, SpatiaLite 1006 1007 .. function:: scale(x, y, z=0.0) 1008 ``snap_to_grid(*args)`` 1009 ^^^^^^^^^^^^^^^^^^^^^^^ 1010 .. versionadded:: 1.1 1011 1012 .. function:: snap_to_grid(*args) 1013 Snap all points of the input geometry to the grid. How the 1014 geometry is snapped to the grid depends on how many numeric 1015 (either float, integer, or long) arguments are given. 1016 1017 =================== ===================================================== 1018 Number of Arguments Description 1019 =================== ===================================================== 1020 1 A single size to snap bot the X and Y grids to. 1021 2 X and Y sizes to snap the grid to. 1022 4 X, Y sizes and the corresponding X, Y origins. 1023 =================== ===================================================== 1024 1025 ``translate(x, y, z=0.0)`` 1026 ^^^^^^^^^^^^^^^^^^^^^^^^^^ 1027 *Availability*: PostGIS, SpatiaLite 1028 1029 .. function:: translate(x, y, z=0.0) 1030 Translates the geometry to a new location using the given numeric 1031 parameters as offsets. 1032 1033 ``transform(srid)`` 1034 ^^^^^^^^^^^^^^^^^^^ 1035 *Availability*: PostGIS, Oracle 1036 1037 .. function:: transform(srid) 1038 The ``transform`` method transforms the geometries in a model to the spatial 1039 reference system specified by the ``srid`` parameter. If no ``srid`` is given, 1040 then 4326 (WGS84) is used by default. 1041 1042 .. note :: 1043 1044 What spatial reference system an integer SRID corresponds to may depend on 1045 the spatial database used. In other words, the SRID numbers used for Oracle 1046 are not necessarily the same as those used by PostGIS. 1047 1048 Example:: 1049 1050 >>> qs = Zipcode.objects.all().transform() # Transforms to WGS84 1051 >>> qs = Zipcode.objects.all().transform(32140) # Transforming to "NAD83 / Texas South Central" 1052 >>> print qs[0].poly.srid 1053 32140 1054 >>> print qs[0].poly 1055 POLYGON ((234055.1698884720099159 4937796.9232223574072123 ... 1056 1057 Geometry Operations 1058 ------------------- 1059 *Availability*: PostGIS, Oracle, SpatiaLite 1060 1061 The following methods all take a geometry as a parameter and attach a geometry 1062 to each element of the ``GeoQuerySet`` that is the result of the operation. 1063 1064 ``difference(geom)`` 1065 ^^^^^^^^^^^^^^^^^^^^ 1066 1067 .. function:: difference(geom) 1068 Returns the spatial difference of the geographic field with the given 1069 geometry in a ``difference`` attribute on each element of the 1070 ``GeoQuerySet``. 1071 1072 ``intersection(geom)`` 1073 ^^^^^^^^^^^^^^^^^^^^^^ 1074 1075 .. function:: intersection(geom) 1076 Returns the spatial intersection of the geographic field with the 1077 given geometry in an ``intersection`` attribute on each element of the 1078 ``GeoQuerySet``. 1079 1080 ``sym_difference(geom)`` 1081 ^^^^^^^^^^^^^^^^^^^^^^^^ 1082 1083 .. function:: sym_difference(geom) 1084 Returns the symmetric difference of the geographic field with the 1085 given geometry in a ``sym_difference`` attribute on each element of the 1086 ``GeoQuerySet``. 1087 1088 ``union(geom)`` 1089 ^^^^^^^^^^^^^^^ 1090 1091 .. function:: union(geom) 1092 Returns the union of the geographic field with the given 1093 geometry in an ``union`` attribute on each element of the 1094 ``GeoQuerySet``. 1095 1096 Output 1097 ------ 1098 1099 The following ``GeoQuerySet`` methods will return an attribute that has the value 1100 of the geometry field in each model converted to the requested output format. 1101 1102 ``geojson()`` 1103 ^^^^^^^^^^^^^ 1104 .. versionadded:: 1.1 1105 1106 *Availability*: PostGIS 1107 1108 .. function:: geojson() 1109 Attaches a ``geojson`` attribute to every model in the queryset that contains the 1110 `GeoJSON`__ representation of the geometry. 1111 1112 ===================== ===================================================== 1113 Keyword Argument Description 1114 ===================== ===================================================== 1115 ``precision`` It may be used to specify the number of significant 1116 digits for the coordinates in the GeoJSON 1117 representation -- the default value is 8. 1118 1119 ``crs`` Set this to ``True`` if you want the coordinate 1120 reference system to be included in the returned 1121 GeoJSON. 1122 1123 ``bbox`` Set this to ``True`` if you want the bounding box 1124 to be included in the returned GeoJSON. 1125 ===================== ===================================================== 1126 1127 __ http://geojson.org/ 1128 1129 ``gml()`` 1130 ^^^^^^^^^ 1131 *Availability*: PostGIS, Oracle 1132 1133 .. function:: gml() 1134 Attaches a ``gml`` attribute to every model in the queryset that contains the 1135 `Geographic Markup Language (GML)`__ representation of the geometry. 1136 1137 Example:: 1138 1139 >>> qs = Zipcode.objects.all().gml() 1140 >>> print qs[0].gml 1141 <gml:Polygon srsName="EPSG:4326"><gml:OuterBoundaryIs>-147.78711,70.245363 ... -147.78711,70.245363</gml:OuterBoundaryIs></gml:Polygon> 1142 1143 ===================== ===================================================== 1144 Keyword Argument Description 1145 ===================== ===================================================== 1146 ``precision`` This keyword is for PostGIS only. It may be used 1147 to specify the number of significant digits for the 1148 coordinates in the GML representation -- the default 1149 value is 8. 1150 1151 ``version`` This keyword is for PostGIS only. It may be used to 1152 specify the GML version used, and may only be values 1153 of 2 or 3. The default value is 2. 1154 ===================== ===================================================== 1155 1156 __ http://en.wikipedia.org/wiki/Geography_Markup_Language 1157 1158 ``kml()`` 1159 ^^^^^^^^^ 1160 *Availability*: PostGIS 1161 1162 .. function:: kml() 1163 Attaches a ``kml`` attribute to every model in the queryset that contains the 1164 `Keyhole Markup Language (KML)`__ representation of the geometry fields. It 1165 should be noted that the contents of the KML are transformed to WGS84 if 1166 necessary. 1167 1168 Example:: 1169 1170 >>> qs = Zipcode.objects.all().kml() 1171 >>> print qs[0].kml 1172 <Polygon><outerBoundaryIs><LinearRing><coordinates>-103.04135,36.217596,0 ... -103.04135,36.217596,0</coordinates></LinearRing></outerBoundaryIs></Polygon> 1173 1174 ===================== ===================================================== 1175 Keyword Argument Description 1176 ===================== ===================================================== 1177 ``precision`` This keyword may be used to specify the number of 1178 significant digits for the coordinates in the KML 1179 representation -- the default value is 8. 1180 ===================== ===================================================== 1181 1182 __ http://code.google.com/apis/kml/documentation/ 1183 1184 ``svg()`` 1185 ^^^^^^^^^ 1186 *Availability*: PostGIS, SpatiaLite 1187 1188 .. function:: svg() 1189 Attaches a ``svg`` attribute to every model in the queryset that contains 1190 the `Scalable Vector Graphics (SVG)`__ path data of the geometry fields. 1191 1192 ===================== ===================================================== 1193 Keyword Argument Description 1194 ===================== ===================================================== 1195 ``relative`` If set to ``True``, the path data will be implemented 1196 in terms of relative moves. Defaults to ``False``, 1197 meaning that absolute moves are used instead. 1198 1199 ``precision`` This keyword may be used to specify the number of 1200 significant digits for the coordinates in the SVG 1201 representation -- the default value is 8. 1202 ===================== ===================================================== 1203 1204 __ http://www.w3.org/Graphics/SVG/ 1205 1206 Miscellaneous 1207 ------------- 1208 1209 ``mem_size()`` 1210 ^^^^^^^^^^^^^^ 1211 *Availability*: PostGIS 1212 1213 .. function:: mem_size() 1214 Returns the memory size (number of bytes) that the geometry field takes 1215 in a ``mem_size`` attribute on each element of the ``GeoQuerySet``. 1216 1217 ``num_geom()`` 1218 ^^^^^^^^^^^^^^ 1219 *Availability*: PostGIS, Oracle, SpatiaLite 1220 1221 .. function:: num_geom() 1222 Returns the number of geometries in a ``num_geom`` attribute on 1223 each element of the ``GeoQuerySet`` if the geometry field is a 1224 collection (e.g., a ``GEOMETRYCOLLECTION`` or ``MULTI*`` field); 1225 otherwise sets with ``None``. 1226 1227 ``num_points()`` 1228 ^^^^^^^^^^^^^^^^ 1229 *Availability*: PostGIS, Oracle, SpatiaLite 1230 1231 .. function:: num_points() 1232 Returns the number of points in the first linestring in the 1233 geometry field in a ``num_points`` attribute on each element of 1234 the ``GeoQuerySet``; otherwise sets with ``None``. 1235 1236 Compatibility Table 1237 =================== 1238 1239 Spatial Lookup Types 1240 -------------------- 1241 The following table provides a summary of what lookup types are available 1242 on each spatial backend. 1243 1244 =========================== ========= ======== ============ ========== 1245 Lookup Type PostGIS Oracle MySQL [#]_ SpatiaLite 1246 =========================== ========= ======== ============ ========== 1247 ``bbcontains`` X X X 1248 ``bboverlaps`` X X X 1249 ``contained`` X X X 1250 ``contains`` X X X X 1251 ``coveredby`` X X 1252 ``covers`` X X 1253 ``crosses`` X X 1254 ``disjoint`` X X X X 1255 ``distance_gt`` X X X 1256 ``distance_gte`` X X X 1257 ``distance_lt`` X X X 1258 ``distance_lte`` X X X 1259 ``dwithin`` X X 1260 ``equals`` X X X X 1261 ``exact`` X X X X 1262 ``intersects`` X X X X 1263 ``overlaps`` X X X X 1264 ``relate`` X X X 1265 ``same_as`` X X X X 1266 ``touches`` X X X X 1267 ``within`` X X X X 1268 ``left`` X 1269 ``right`` X 1270 ``overlaps_left`` X 1271 ``overlaps_right`` X 1272 ``overlaps_above`` X 1273 ``overlaps_below`` X 1274 ``strictly_above`` X 1275 ``strictly_below`` X 1276 =========================== ========= ======== ============ ========== 1277 1278 ``GeoQuerySet`` Methods 1279 ----------------------- 1280 The following table provides a summary of what ``GeoQuerySet`` methods 1281 are available on each spatial backend. Please note that MySQL does not 1282 support any of these methods, and is thus excluded from the table. 1283 1284 =========================== ========= ======== ========== 1285 Method PostGIS Oracle SpatiaLite 1286 =========================== ========= ======== ========== 1287 ``area`` X X X 1288 ``centroid`` X X X 1289 ``collect`` X 1290 ``difference`` X X X 1291 ``distance`` X X X 1292 ``envelope`` X X 1293 ``extent`` X X 1294 ``extent3d`` X 1295 ``geojson`` X 1296 ``gml`` X X 1297 ``intersection`` X X X 1298 ``kml`` X 1299 ``length`` X X X 1300 ``make_line`` X 1301 ``mem_size`` X 1302 ``num_geom`` X X X 1303 ``num_points`` X X X 1304 ``perimeter`` X X 1305 ``point_on_surface`` X X X 1306 ``scale`` X X 1307 ``snap_to_grid`` X 1308 ``svg`` X X 1309 ``sym_difference`` X X X 1310 ``transform`` X X X 1311 ``translate`` X X 1312 ``union`` X X X 1313 ``unionagg`` X X X 1314 =========================== ========= ======== ========== 1315 1316 .. rubric:: Footnotes 1317 .. [#] *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). 1318 .. [#] *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. 1319 .. [#] *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). 1320 .. [#] *See generally*, `Operators <http://postgis.refractions.net/documentation/manual-1.3/ch06.html#id2576880>`_, PostGIS Documentation at Ch. 6.2.2. 1321 .. [#] *See generally*, `Geometry Relationship Functions <http://postgis.refractions.net/documentation/manual-1.3/ch06.html#id2574517>`_ PostGIS Documentation at Ch. 6.1.2. 1322 .. [#] 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). 1323 .. [#] *See id.* 1324 .. [#] *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). 1325 .. [#] Oracle Spatial User's Guide and Manual, at Ch. 11. 1326 .. [#] *See id.* at `SDO_RELATE documentation <http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14255/sdo_operat.htm#sthref845>`_. 1327 .. [#] MySQL 5.0 Reference Manual, at Ch. 17.5.5. 1328 .. [#] *See* the `distance documentation`_ for more information on the ``Distance`` object. 1329 .. [#] *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. 1330 .. [#] 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 ======== 2 GEOS API 3 ======== 4 5 Background 6 ========== 7 8 What is GEOS? 9 ------------- 10 11 `GEOS`__ stands for **G**\ eometry **E**\ ngine - **O**\ pen **S**\ ource, and is a C++ 12 port of the `Java Topology Suite`__, implementing the OpenGIS 13 `Simple Features for SQL`__ spatial predicate functions and spatial operators. 14 GEOS, now an OSGeo project, was initially developed and maintained by 15 `Refractions Research`__ of Victoria, Canada. 16 17 __ http://trac.osgeo.org/geos/ 18 __ http://sourceforge.net/projects/jts-topo-suite/ 19 __ http://www.opengeospatial.org/standards/sfs 20 __ http://www.refractions.net/ 21 22 Why the new API? 23 ---------------- 24 1. The GEOS SWIG wrapper is no longer maintained, and requires the installation 25 of `SWIG`__. [#]_ 26 2. The `PCL implementation`__ is over 2K+ lines of C and would make PCL a 27 requisite package for the GeoDjango application stack. 28 3. Cross-platform compatibility. 29 30 Thus, the Python ``ctypes`` [#]_ package was used to wrap the `GEOS C API`__ 31 to bring the rich capabilities of GEOS to Python and GeoDjango. 32 33 Features: 34 35 * A BSD-licensed interface to the GEOS geometry routines, implemented purely 36 in Python using ``ctypes``. 37 * Loosely-coupled to GeoDjango. For example, GEOS geometry objects may be 38 used outside a django project/application (no need to have 39 ``DJANGO_SETTINGS_MODULE`` set, etc.) 40 * Mutability. GEOS Geometry objects may be modified. 41 * Cross-platform and tested. GeoDjango GEOS geometries are well-tested and 42 compatible with Windows, Linux, Solaris, and Mac OS X platforms. 43 44 __ http://www.swig.org/ 45 __ http://trac.gispython.org/projects/PCL/browser/PCL/trunk/PCL-Core/cartography/geometry 46 __ http://trac.osgeo.org/geos/browser/trunk/capi/geos_c.h.in 47 48 Related Work 49 ------------ 50 51 The ``GEOSGeometry`` interface was first committed to the Django SVN by Justin 52 Bronn (the lead developer of GeoDjango) in April, 2007. [#]_ After learning of 53 GeoDjango's interface [#]_, Sean Gillies created his own ``ctypes`` interface, 54 "Shapely." [#]_ Justin Bronn declined to merge the projects because Shapely 55 was initially licensed under the LGPL, a license incompatible with GeoDjango. [#]_ 56 While Shapely was later relicensed under the BSD license (the same as GeoDjango) 57 [#]_, differences in design and implementation prevent the projects from 58 merging at the moment, but are not irreconcilable. 59 60 Geometry Objects 61 ================ 62 63 .. _point: 64 65 ``Point`` 66 --------- 67 68 .. class:: Point 69 70 The ``Point`` object may be initialized with either a tuple, or individual 71 parameters. For example:: 72 73 >>> from django.contrib.gis.geos import Point 74 >>> p = Point((5, 23)) # 2D point, passed in as a tuple 75 >>> p = Point(5, 23) # Same, passed in with individual parameters 76 77 The ``srid`` keyword may be used to specify the SRID for the point:: 78 79 >>> pnt = Point(5, 23, srid=4326) 80 81 Additionally, 3D geometries may be created by specifing a Z value:: 82 83 >>> pnt_3d = Point(5, 23, 17) # Also: Point( (5, 23, 17) ) 84 >>> pnt_3d.hasz 85 True 86 >>> pnt_3d.z 87 17 88 89 Properties 90 ^^^^^^^^^^ 91 92 .. attribute:: x 93 94 This property sets or retrieves the X coordinate for the point. 95 96 .. attribute:: y 97 98 This property sets or retrieves the Y coordinate for the point. 99 100 .. attribute:: z 101 102 This property sets or retrieves the Z (3D) coordinate for the point. 103 If the point has no Z coordinate, ``None`` is returned. 104 105 .. note: 106 107 The ``Point`` must have been created as 3D before it is possible 108 to set the ``z`` property. 109 110 .. _linestring: 111 112 .. class:: LineString 113 114 .. class:: LinearRing 115 116 ``LineString`` objects initialize on a given sequence. For example, the constructor may 117 take lists, tuples, `NumPy`__ arrays of X,Y[,Z] pairs, or ``Point`` objects. If ``Point`` 118 objects are used, ownership of the points is *not* transferred to the ``LineString`` 119 object. Examples:: 120 121 >>> from django.contrib.gis.geos import LineString, Point 122 >>> ls = LineString((1, 1), (2, 2)) 123 >>> ls = LineString([(1, 1), (2, 2)]) 124 >>> ls = LineString(Point(1, 1), Point(2, 2)) 125 >>> from numpy import array 126 >>> ls = LineString(array([(1, 1), (2, 2)])) 127 128 ``LinearRing`` objects are subclasses of ``LineString``; however, an error will 129 be raised if the points used during initialization are not closed (the first 130 point is equal to the last point):: 131 132 >>> from django.contrib.gis.geos import LinearRing 133 >>> lr = LinearRing((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)) 134 >>> lr = LinearRing((0, 0), (0, 1)) 135 GEOS_ERROR: IllegalArgumentException: points must form a closed linestring 136 137 __ http://numpy.scipy.org/ 138 139 Methods 140 ^^^^^^^ 141 142 .. method:: LineString(coords) 143 144 .. attribute:: x 145 146 This property returns the X values in a list, or a NumPy array (if installed). 147 148 .. attribute:: y 149 150 This property returns the Y values in a list, or a NumPy array (if installed). 151 152 .. attribute:: z 153 154 This property returns the Z values in a list, or a NumPy array (if installed). 155 156 .. _polygon: 157 158 ``Polygon`` 159 ----------- 160 161 .. class:: Polygon 162 163 Polygons are composed of an exterior ring (the shell), and may also have 164 interior rings that denote areas excluded from the exterior. 165 166 Methods 167 ^^^^^^^ 168 169 ``Polygon(rings)`` 170 ~~~~~~~~~~~~~~~~~~ 171 The ``Polygon`` initializes on arguments that are either ``LinearRing`` instances 172 or may be accepted by the ``LinearRing`` constructor. 173 174 ``from_bbox(bbox)`` 175 ~~~~~~~~~~~~~~~~~~~ 176 .. versionadded:: 1.1 177 .. method:: from_bbox(bbox) 178 179 Returns a new ``Polygon`` object for the given bounding box. The bounding box 180 should be a four-tuple comprising the X and Y minimum values followed by the 181 X and Y maximum values. For example:: 182 183 >>> from django.contrib.gis.geos import Polygon 184 >>> bbox = (0, 0, 5, 5) 185 >>> poly = Polygon.from_bbox(bbox) 186 >>> print poly 187 POLYGON ((0.0000000000000000 0.0000000000000000, 0.0000000000000000 5.0000000000000000, 5.0000000000000000 5.0000000000000000, 5.0000000000000000 0.0000000000000000, 0.0000000000000000 0.0000000000000000)) 188 189 ``shell``, ``exterior_ring`` 190 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 191 192 .. method:: shell() 193 .. method:: exterior_ring() 194 195 Returns a ``LinearRing`` corresponding to the exterior ring, or shell, of the 196 ``Polygon``. 197 198 ``num_interior_rings`` 199 ~~~~~~~~~~~~~~~~~~~~~~ 200 201 .. method:: num_interior_rings 202 203 Returns the number of interior rings contained in the ``Polygon``. 204 205 Geometry Collections 206 ==================== 207 208 .. _multipoint: 209 210 ``MultiPoint`` 211 -------------- 212 213 .. class:: MultiPoint 214 215 >>> from django.contrib.gis.geos import Point 216 >>> from django.contrib.gis.geos import MultiPoint 217 >>> p1 = Point((0,0)) 218 >>> p2 = Point((1,2)) 219 >>> mp = MultiPoint(p1, p2) 220 >>> mp 221 <MultiPoint object> 222 >>> mp[0].wkt 223 'POINT (0.0000000000000000 0.0000000000000000)' 224 >>> len(mp) 225 2 226 >>> [ p.wkt for p in mp ] 227 ['POINT (0.0000000000000000 0.0000000000000000)', 'POINT (1.0000000000000000 2.0000000000000000)'] 228 >>> mp.ring 229 False 230 231 .. _multilinestring: 232 233 ``MultiLineString`` 234 ------------------- 235 236 .. class:: MultiLineString 237 238 .. _multipolygon: 239 240 ``MultiPolygon`` 241 ---------------- 242 243 .. class:: MultiPolygon 244 245 Methods 246 ^^^^^^^ 247 248 ``cascaded_union`` 249 ~~~~~~~~~~~~~~~~~~ 250 .. versionadded:: 1.1 251 252 .. method:: cascaded_union 253 254 .. note:: 255 256 Use of this method requires at least GEOS 3.1. 257 258 .. _geometrycollection: 259 260 ``GeometryCollection`` 261 ---------------------- 262 263 .. class:: GeometryCollection 264 265 .. _prepared: 266 267 Prepared Geometries 268 =================== 269 .. versionadded: 1.1 270 271 In order to obtain a prepared geometry, just access the ``prepared`` 272 property on any ``GEOSGeometry`` object. Once you have a 273 ``PreparedGeometry`` instance its spatial predicate methods, listed below, 274 may be used with other ``GEOSGeometry`` objects. An operation with a prepared 275 geometry can be orders of magnitude faster -- the more complex the geometry 276 that is prepared, the larger the speedup in the operation. 277 278 .. note:: 279 280 GEOS 3.1 is *required* in order to use prepared geometries. 281 282 For example:: 283 284 >>> from django.contrib.gis.geos import Point, Polygon 285 >>> poly = Polygon.from_bbox((0, 0, 5, 5)) 286 >>> prep_poly = poly.prepared 287 >>> prep_poly.contains(Point(2.5, 2.5)) 288 True 289 290 ``PreparedGeometry`` 291 -------------------- 292 293 .. class:: PreparedGeometry 294 295 All methods on ``PreparedGeometry`` take an ``other`` argument, which 296 must be a ``GEOSGeometry`` object. 297 298 ``contains(other)`` 299 ^^^^^^^^^^^^^^^^^^^ 300 301 .. method:: contains(other) 302 303 ``contains_properly(other)`` 304 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 305 306 .. method:: contains_properly(other) 307 308 ``covers(other)`` 309 ^^^^^^^^^^^^^^^^^ 310 311 .. method:: covers(other) 312 313 ``intersects(other)`` 314 ^^^^^^^^^^^^^^^^^^^^^ 315 316 .. method:: intersects(other) 317 318 I/O Objects 319 =========== 320 .. versionadded: 1.1 321 322 Inside GEOS, I/O classes are used to output geometries to WKT, WKB, and EWKB. 323 GeoDjango allows access to these I/O classes if finer-grained control of 324 serialization is required. Typically, 325 326 Reader Objects 327 -------------- 328 329 The reader I/O classes simply return a ``GEOSGeometry`` instance from the 330 WKB and/or WKT input given to their ``read(geom)`` method. 331 332 ``WKBReader`` 333 ^^^^^^^^^^^^^ 334 335 .. class:: WKBReader 336 337 Example:: 338 339 >>> from django.contrib.gis.geos import WKBReader 340 >>> wkb_r = WKBReader() 341 >>> wkb_r.read('0101000000000000000000F03F000000000000F03F') 342 <Point object at 0x103a88910> 343 344 ``WKTReader`` 345 ^^^^^^^^^^^^^ 346 347 .. class:: WKTReader 348 349 Example:: 350 351 >>> from django.contrib.gis.geos import WKTReader 352 >>> wkt_r = WKTReader() 353 >>> wkt_r.read('POINT(1 1)') 354 <Point object at 0x103a88b50> 355 356 Writer Objects 357 -------------- 358 359 All writer objects have a ``write(geom)`` method that returns either the 360 WKB or WKT of the given geometry. In addition, ``WKBWriter`` objects 361 also have properties that may be used to change the byte order, and or 362 include the SRID and 3D values (in other words, EWKB). 363 364 ``WKBWriter`` 365 ^^^^^^^^^^^^^ 366 367 .. class:: WKBWriter 368 369 The ``WKBWriter`` provides the most control over its output. By default it 370 returns OGC-compliant WKB when it's ``write`` method is called. However, 371 it has properties that 372 373 ``write(geom)`` 374 ~~~~~~~~~~~~~~~ 375 376 .. function:: write(geom) 377 378 Returns the WKB of the given geometry as a Python ``buffer`` object. 379 Example:: 380 381 >>> from django.contrib.gis.geos import Point, WKBWriter 382 >>> pnt = Point(1, 1) 383 >>> wkb_w = WKBWriter() 384 >>> wkb_w.write(pnt) 385 <read-only buffer for 0x103a898f0, size -1, offset 0 at 0x103a89930> 386 387 ``write_hex(geom)`` 388 ~~~~~~~~~~~~~~~~~~~ 389 390 .. function:: write_hex(geom) 391 392 Returns WKB of the geometry in hexadecimal. Example:: 393 394 >>> from django.contrib.gis.geos import Point, WKBWriter 395 >>> pnt = Point(1, 1) 396 >>> wkb_w = WKBWriter() 397 >>> wkb_w.write_hex(pnt) 398 '0101000000000000000000F03F000000000000F03F' 399 400 ``byteorder`` 401 ~~~~~~~~~~~~~ 402 403 .. function:: byteorder 404 405 This property may be be set to change the byte-order of the geometry 406 representation. 407 408 =============== ================================================= 409 Byteorder Value Description 410 =============== ================================================= 411 0 Big Endian (e.g., compatible with RISC systems) 412 1 Little Endian (e.g., compatible with x86 systems) 413 =============== ================================================= 414 415 Example:: 416 417 >>> from django.contrib.gis.geos import Point, WKBWriter 418 >>> wkb_w = WKBWriter() 419 >>> pnt = Point(1, 1) 420 >>> wkb_w.write_hex(pnt) 421 '0101000000000000000000F03F000000000000F03F' 422 >>> wkb_w.byteorder = 0 423 '00000000013FF00000000000003FF0000000000000' 424 425 ``outdim`` 426 ~~~~~~~~~~ 427 428 .. attribute:: outdim 429 430 This property may be set to change the output dimension of the geometry 431 representation. In other words, if you have a 3D geometry then set to 3 432 so that the Z value is included in the WKB. 433 434 ============ =========================== 435 Outdim Value Description 436 ============ =========================== 437 2 The default, output 2D WKB. 438 3 Output 3D EWKB. 439 ============ =========================== 440 441 Example:: 442 443 >>> from django.contrib.gis.geos import Point, WKBWriter 444 >>> wkb_w = WKBWriter() 445 >>> wkb_w.outdim 446 2 447 >>> pnt = Point(1, 1, 1) 448 >>> wkb_w.write_hex(pnt) # By default, no Z value included: 449 '0101000000000000000000F03F000000000000F03F' 450 >>> wkb_w.outdim = 3 # Tell writer to include Z values 451 >>> wkb_w.write_hex(pnt) 452 '0101000080000000000000F03F000000000000F03F000000000000F03F' 453 454 ``srid`` 455 ~~~~~~~~ 456 457 .. attribute:: srid 458 459 Set this property with a boolean to indicate whether the SRID of the 460 geometry should be included with the WKB representation. Example:: 461 462 >>> from django.contrib.gis.geos import Point, WKBWriter 463 >>> wkb_w = WKBWriter() 464 >>> pnt = Point(1, 1, srid=4326) 465 >>> wkb_w.write_hex(pnt) # By default, no SRID included: 466 '0101000000000000000000F03F000000000000F03F' 467 >>> wkb_w.srid = True # Tell writer to include SRID 468 >>> wkb_w.write_hex(pnt) 469 '0101000020E6100000000000000000F03F000000000000F03F' 470 471 ``WKTWriter`` 472 ^^^^^^^^^^^^^ 473 474 .. class:: WKTWriter 475 476 ``write(geom)`` 477 ~~~~~~~~~~~~~~~ 478 479 .. method:: write(geom) 480 481 Returns the WKT of the given geometry. Example:: 482 483 >>> from django.contrib.gis.geos import Point, WKTWriter 484 >>> pnt = Point(1, 1) 485 >>> wkt_w = WKTWriter() 486 >>> wkt_w.write(pnt) 487 'POINT (1.0000000000000000 1.0000000000000000)' 488 489 API 490 === 491 492 Creation 493 -------- 494 495 ``GEOSGeometry(geo_input, srid=None)`` 496 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 497 .. class:: GEOSGeometry 498 499 Geometries may be created using the ``GEOSGeometry`` constructor; ``geo_input`` 500 may be any of the following types of data: 501 502 ============ ====================== ========================================================================================= 503 Input Type Python Type Example 504 ============ ====================== ========================================================================================= 505 WKT ``str`` / ``unicode`` ``'POINT(5 23)'`` 506 EWKT ``str`` / ``unicode`` ``'SRID=4326;POINT(5 23)'`` 507 HEX ``str`` / ``unicode`` ``'010100000000000000000014400000000000003740'`` 508 HEXEWKB ``str`` / ``unicode`` ``''0101000020E610000000000000000014400000000000003740'`` 509 GeoJSON ``str`` / ``unicode`` ``'{ "type": "Point", "coordinates": [ 5.000000, 23.000000 ] }'`` 510 WKB ``buffer`` ``buffer('\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x14@\x00\x00\x00\x00\x00\x007@')`` 511 ============ ====================== ========================================================================================= 512 513 While this may seem like an acronym soup, all are standardized geospatial data 514 formats or extensions thereof. 515 516 The ``srid`` keyword may be used to set the spatial reference system 517 identifier number for the geometry. This will be used to conduct any needed 518 transformations for spatial lookups and geographic model creation. 519 520 ``fromfile(file_h)`` 521 ^^^^^^^^^^^^^^^^^^^^ 522 This factory creates a GEOS geometry from the given file name or an open 523 file handle (1.1 only):: 524 525 >>> from django.contrib.gis.geos import fromfile 526 >>> g = fromfile('/home/bob/geom.wkt') 527 528 ``fromstr(string)`` 529 ^^^^^^^^^^^^^^^^^^^ 530 GEOS geometry objects may be created from strings using the ``fromstr()`` 531 factory, or using the constructor for each geometry object (as described 532 above):: 533 534 >>> from django.contrib.gis.geos import fromstr 535 >>> pnt = fromstr('POINT(-90.5 29.5)', srid=4326) 536 537 It should be noted that ``fromstr`` is a shortcut to the constructor for the 538 base ``GEOSGeometry`` object. 539 540 Geometry Properties 541 ------------------- 542 543 ``empty`` 544 ^^^^^^^^^ 545 .. attribute:: empty 546 Returns whether or not the set of points in the geometry is empty. 547 548 ``geom_type`` 549 ^^^^^^^^^^^^^ 550 .. attribute:: geom_type 551 Returns a string corresponding to the type of geometry. For example:: 552 553 >>> pnt = GEOSGeometry('POINT(5 23)') 554 >>> pnt.geom_type 555 'Point' 556 557 ``geom_typeid`` 558 ^^^^^^^^^^^^^^^ 559 .. attribute:: geom_typeid 560 Returns the GEOS geometry type identification number. The following table 561 shows the value for each geometry type: 562 563 ====================== ======== 564 Geometry ID 565 ====================== ======== 566 ``Point`` 0 567 ``LineString`` 1 568 ``LinearRing`` 2 569 ``Polygon`` 3 570 ``MultiPoint`` 4 571 ``MultiLineString`` 5 572 ``MultiPolygon`` 6 573 ``GeometryCollection`` 7 574 ====================== ======== 575 576 ``hasz`` 577 ^^^^^^^^ 578 .. attribute:: hasz 579 Returns a boolean indicating whether the geometry is three-dimensional. 580 581 ``num_coords``, ``num_points`` 582 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 583 .. attribute:: num_coords 584 .. attribute:: num_points 585 Returns the total number of coordinates in this geometry. For 586 polygons and collections, this is the cumulative number of all 587 coordinates from the component geometries. 588 589 ``ring`` 590 ^^^^^^^^ 591 .. attribute:: ring 592 Returns a boolean indicating whether the geometry is a ``LinearRing``. 593 594 ``simple`` 595 ^^^^^^^^^^ 596 .. attribute:: simple 597 A Geometry is simple if and only if the only self-intersections are at boundary 598 points. For example, a ``LineString`` object is not simple if it intersects 599 itself. Thus, ``LinearRing`` and ``Polygon`` objects are always simple because 600 they do not intersect themselves. 601 602 ``valid`` 603 ^^^^^^^^^ 604 .. attribute:: valid 605 Returns a boolean indicating whether the geometry is valid. 606 607 Output Properties 608 ----------------- 609 610 .. _ewkt: 611 612 ``ewkt`` 613 ^^^^^^^^ 614 .. attribute:: ewkt 615 Returns the "extended" Well-Known Text of the geometry. This representation 616 is specific to PostGIS and is a super set of the OGC WKT standard. [#]_ 617 Essentially the SRID is prepended to the WKT representation, for example 618 ``SRID=4326;POINT(5 23)``. Please note that this does not include 619 the 3dm, 3dz, and 4d information that PostGIS supports in its EWKT 620 representations. 621 622 .. _hex: 623 624 ``hex`` 625 ^^^^^^^ 626 .. attribute:: hex 627 Returns the WKB of this Geometry in hexadecimal form. Please note 628 that the SRID and Z values are not included in this representation 629 because it is not a part of the OGC specification (use the :ref:`hexewkb` 630 property instead). 631 632 .. _hexewkb: 633 634 ``hexewkb`` 635 ^^^^^^^^^^^ 636 .. versionadded:: 1.2 637 .. attribute:: hexewkb 638 639 Returns the EWKB of this Geometry in hexadecimal form. This is an 640 extension of the WKB specification that includes SRID and Z values 641 that are a part of this geometry. 642 643 .. note:: 644 645 GEOS 3.1 is *required* if you want valid 3D HEXEWKB. 646 647 ``json``, ``geojson`` 648 ^^^^^^^^^^^^^^^^^^^^^ 649 .. attribute:: json 650 .. attribute:: geojson 651 Returns the GeoJSON representation of the geometry. Requires GDAL. 652 653 ``kml`` 654 ^^^^^^^^^ 655 .. attribute:: kml 656 Returns a `KML`__ (Keyhole Markup Language) representation of the 657 geometry. This should only be used for geometries with an SRID of 658 4326 (WGS84), but this restriction is not enforced. 659 660 ``ogr`` 661 ^^^^^^^^ 662 .. attribute:: ogr 663 Returns an OGR ``OGRGeometry`` object correspondg to the GEOS geometry. 664 Consult the `OGRGeometry`_ documentation for more information. 665 666 .. _OGRGeometry: gdal.html#ogrgeometry 667 668 .. note:: 669 670 Requires GDAL. 671 672 .. _wkb: 673 674 ``wkb`` 675 ^^^^^^^^ 676 .. attribute:: wkb 677 Returns the WKB (Well-Known Binary) representation of this Geometry 678 as a Python buffer. SRID and Z values are not included, use the 679 :ref:`ewkb` property instead. 680 681 .. _ewkb: 682 683 ``ewkb`` 684 ^^^^^^^^^ 685 .. attribute:: ewkb 686 .. versionadded:: 1.2 687 688 Return the EWKB representation of this Geometry as a Python buffer. 689 This is an extension of the WKB specification that includes any SRID 690 and Z values that are a part of this geometry. 691 692 .. note:: 693 694 GEOS 3.1 is *required* if you want valid 3D EWKB. 695 696 ``wkt`` 697 ^^^^^^^^^ 698 .. attribute:: wkt 699 Returns the Well-Known Text of the geometry (an OGC standard). 700 701 __ http://code.google.com/apis/kml/documentation/ 702 703 Spatial Predicate Methods 704 ------------------------- 705 All of the following spatial predicate methods take another GEOS Geometry 706 instance (``other``) as an argument. 707 708 ``contains(other)`` 709 ^^^^^^^^^^^^^^^^^^^ 710 .. method:: contains(other) 711 Returns True if ``within(other)`` is False. 712 713 ``crosses(other)`` 714 ^^^^^^^^^^^^^^^^^^ 715 .. method:: crosses(other) 716 Returns true if the DE-9IM intersection matrix for the two Geometries 717 is ``T*T******`` (for a point and a curve,a point and an area or a line 718 and an area) ``0********`` (for two curves). 719 720 ``disjoint(other)`` 721 ^^^^^^^^^^^^^^^^^^^ 722 .. method:: disjoint(other) 723 Returns true if the DE-9IM intersection matrix for the two Geometries 724 is ``FF*FF****``. 725 726 ``equals(other)`` 727 ^^^^^^^^^^^^^^^^^ 728 .. method:: equals(other) 729 Returns true if the DE-9IM intersection matrix for the two Geometries 730 is ``T*F**FFF*``. 731 732 ``equals_exact(other, tolerance=0)`` 733 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 734 .. method:: equals_exact(other, tolerance=0) 735 Returns true if the two Geometries are exactly equal, up to a 736 specified tolerance. The ``tolerance`` value should be a floating 737 point number representing the error tolerance in the comparison, e.g., 738 ``poly1.equals_exact(poly2, 0.001)`` will compare equality to within 739 one thousandth of a unit. 740 741 ``intersects(other)`` 742 ^^^^^^^^^^^^^^^^^^^^^ 743 .. method:: intersects(other) 744 Returns True if ``disjoint(other)`` is False. 745 746 ``overlaps(other)`` 747 ^^^^^^^^^^^^^^^^^^^ 748 .. method:: overlaps(other) 749 Returns true if the DE-9IM intersection matrix for the two Geometries 750 is ``T*T***T**`` (for two points or two surfaces) ``1*T***T**`` 751 (for two curves). 752 753 ``relate_pattern(other, pattern)`` 754 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 755 .. method:: relate_pattern(other, pattern) 756 Returns true if the elements in the DE-9IM intersection matrix 757 for this geometry and the other matches the given ``pattern`` -- 758 a string of nine characters from the alphabet: {``T``, ``F``, ``*``, ``0``}. 759 760 ``touches(other)`` 761 ^^^^^^^^^^^^^^^^^^ 762 .. method:: touches(other) 763 Returns true if the DE-9IM intersection matrix for the two Geometries 764 is ``FT*******``, ``F**T*****`` or ``F***T****``. 765 766 ``within(other)`` 767 ^^^^^^^^^^^^^^^^^ 768 .. method:: within(other) 769 Returns true if the DE-9IM intersection matrix for the two Geometries 770 is ``T*F**F***``. 771 772 Topological Methods 773 ------------------- 774 775 ``buffer(width, quadsegs=8)`` 776 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 777 .. method:: buffer(width, quadsegs=8) 778 Returns a geometry that represents all points whose distance from this 779 geometry is less than or equal to the given ``width``. The optional 780 ``quadsegs`` keyword sets the number of segments used to approximate a 781 quarter circle (defaults is 8). 782 783 ``difference(other)`` 784 ^^^^^^^^^^^^^^^^^^^^^ 785 .. method:: difference(other) 786 Returns a geometry representing the points making up this geometry 787 that do not make up other. 788 789 ``intersection(other)`` 790 ^^^^^^^^^^^^^^^^^^^^^^^ 791 .. method:: intersection(other) 792 Returns a geometry representing the points shared by this geometry and other. 793 794 ``relate(other)`` 795 ^^^^^^^^^^^^^^^^^ 796 .. method:: relate(other) 797 Returns the DE-9IM intersection matrix for this geometry and the other. 798 799 ``simplify(tolerance=0.0, preserve_topology=False)`` 800 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 801 .. method:: simplify(tolerance=0.0, preserve_topology=False) 802 Returns the geometry, simplified using the Douglas-Peucker algorithm 803 to the specified tolerance (higher tolerance => less points). If no 804 tolerance provided, defaults to 0. 805 806 By default, this function does not preserve topology - e.g. polygons can 807 be split, collapse to lines or disappear holes can be created or 808 disappear, and lines can cross. By specifying ``preserve_topology=True``, 809 the result will have the same dimension and number of components as the 810 input. This is significantly slower. 811 812 ``sym_difference(other)`` 813 ^^^^^^^^^^^^^^^^^^^^^^^^^ 814 .. method:: sym_difference(other) 815 Returns a set combining the points in this geometry not in other, 816 and the points in other not in this geometry. 817 818 ``union(other)`` 819 ^^^^^^^^^^^^^^^^ 820 .. method:: union(other) 821 Returns a Geometry representing all the points in this Geometry and other. 822 823 Topological Properties 824 ---------------------- 825 826 ``boundary`` 827 ^^^^^^^^^^^^ 828 .. attribute:: boundary 829 Returns the boundary as a newly allocated Geometry object. 830 831 ``centroid`` 832 ^^^^^^^^^^^^ 833 .. attribute:: centroid 834 The centroid is equal to the centroid of the set of component Geometries 835 of highest dimension (since the lower-dimension geometries contribute zero 836 "weight" to the centroid). 837 838 ``convex_hull`` 839 ^^^^^^^^^^^^^^^ 840 .. attribute:: convex_hull 841 Returns the smallest convex Polygon that contains all the points in 842 the Geometry. 843 844 ``envelope`` 845 ^^^^^^^^^^^^ 846 .. attribute:: envelope 847 Returns a ``Polygon`` that represents the bounding envelope of this geometry. 848 849 ``point_on_surface`` 850 ^^^^^^^^^^^^^^^^^^^^ 851 .. attribute:: point_on_surface 852 Computes and returns a ``Point`` guaranteed to be on the interior of this 853 geometry. 854 855 Other Properties & Methods 856 -------------------------- 857 858 ``extent`` 859 ^^^^^^^^^^ 860 .. attribute:: extent 861 This property returns the extent of this geometry as a 4-tuple, 862 consisting of (xmin, ymin, xmax, ymax). 863 864 ``area`` 865 ^^^^^^^^ 866 .. attribute:: area 867 This property returns the area of the Geometry. 868 869 ``distance(geom)`` 870 ^^^^^^^^^^^^^^^^^^ 871 .. method:: distance(geom) 872 Returns the distance between the closest points on this Geometry and the given 873 ``geom`` (another ``GEOSGeometry`` object). 874 875 .. note:: 876 877 GEOS distance calculations are linear -- in other words, GEOS will not 878 perform a spherical calculation even if the SRID specifies a geographic 879 coordinate system. 880 881 ``length`` 882 ^^^^^^^^^^ 883 .. attribute:: length 884 Returns the length of this Geometry (e.g., 0 for point or the 885 circumference of a Polygon). 886 887 ``prepared`` 888 ^^^^^^^^^^^^ 889 .. attribute:: prepared 890 .. versionadded:: 1.1 891 892 .. note:: 893 894 Support for prepared geometries requires GEOS 3.1. 895 896 Returns a GEOS ``PreparedGeometry`` for the contents of this geometry. 897 ``PreparedGeometry`` objects are optimized for the contains, intersects, 898 and covers operations. Refer to the :ref:`prepared` documentation for 899 more information. 900 901 ``srs`` 902 ^^^^^^^ 903 .. attribute:: srs 904 Returns an OGR ``SpatialReference`` object corresponding to the SRID of the 905 geometry or ``None``. Consult the `SpatialReference documentation`_ for more 906 information about these objects. 907 908 .. _SpatialReference documentation: gdal.html#spatialreference 909 910 .. note:: 911 912 Requires GDAL. 913 914 ``transform(ct, clone=False)`` 915 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 916 .. method:: transform(ct, clone=False) 917 Transforms the geometry according to the given transformation object, which may 918 be an integer SRID, spatial reference WKT string, a PROJ.4 string, or a 919 ``SpatialReference`` object. By default, the geometry is transformed in-place and 920 nothing is returned. However if the `clone` keyword is set, then the geometry 921 is not modified and a transformed clone is returned instead. 922 923 .. note:: 924 925 GDAL and PROJ.4 are required to perform coordinate system transformations. 926 927 .. rubric:: Footnotes 928 .. [#] *See* Sean Gillies, `Geometries for Python <http://zcologia.com/news/150/geometries-for-python/>`_ (blog post explaining rationale for abandoning GEOS support); *see also* Sean's message on the `geos-devel mailing list <http://geos.refractions.net/pipermail/geos-devel/2007-March/002851.html>`_, Mar. 5, 2007 929 .. [#] *See generally* `Python's ctypes documentation <http://docs.python.org/lib/module-ctypes.html>`_, at Ch. 14.14. 930 .. [#] Specifically, ``GEOSGeometry`` was introduced in `revision 5008 <http://code.djangoproject.com/changeset/5008>`_ on April 15th, 2007. 931 .. [#] *See* Sean Gillies, `Geometries for Python Update <http://zcologia.com/news/429/geometries-for-python-update/>`_, April 16th 2007 ("The ctypes-based geometry module in r5008 looks kickass. I'm checking it out now."). 932 .. [#] Sean Gillies, `Proposal to launch the Shapely Project <http://lists.gispython.org/pipermail/community/2007-May/000953.html>`_, May 1, 2007. 933 .. [#] Justin Bronn, `RE: Proposal to launch the Shapely project <http://lists.gispython.org/pipermail/community/2007-May/000964.html>`_, May 1, 2007. 934 .. [#] Sean Gillies, `Proposal to change Shapely license from LGPL to BSD <http://lists.gispython.org/pipermail/community/2007-November/001271.html>`_, Nov. 20, 2007. 935 .. [#] *See* `PostGIS EWKB, EWKT and Canonical Forms <http://postgis.refractions.net/docs/ch04.html#id2591381>`_, PostGIS documentation at Ch. 4.1.2. 936 -
docs/ref/contrib/gis/create_template_postgis-1.3.sh
1 #!/usr/bin/env bash 2 POSTGIS_SQL_PATH=`pg_config --sharedir` 3 createdb -E UTF8 template_postgis # Create the template spatial database. 4 createlang -d template_postgis plpgsql # Adding PLPGSQL language support. 5 psql -d postgres -c "UPDATE pg_database SET datistemplate='true' WHERE datname='template_postgis';" 6 psql -d template_postgis -f $POSTGIS_SQL_PATH/lwpostgis.sql # Loading the PostGIS SQL routines 7 psql -d template_postgis -f $POSTGIS_SQL_PATH/spatial_ref_sys.sql 8 psql -d template_postgis -c "GRANT ALL ON geometry_columns TO PUBLIC;" # Enabling users to alter spatial tables. 9 psql -d template_postgis -c "GRANT ALL ON spatial_ref_sys TO PUBLIC;" -
docs/ref/contrib/gis/utils.txt
Property changes on: docs/ref/contrib/gis/create_template_postgis-1.3.sh ___________________________________________________________________ Name: svn:executable + *
1 ====================== 2 GeoDjango Utilities 3 ====================== 4 5 The ``django.contrib.gis.utils`` module contains various utilities that are 6 useful in creating geospatial web applications. 7 8 .. toctree:: 9 :maxdepth: 2 10 11 geoip 12 layermapping -
docs/ref/contrib/index.txt
32 32 databrowse 33 33 flatpages 34 34 formtools/index 35 gis/index 35 36 humanize 36 37 localflavor 37 38 messages … … 111 112 112 113 See the :ref:`form wizard documentation <ref-contrib-formtools-form-wizard>`. 113 114 115 gis 116 ==== 117 118 A world-class geospatial framework built on top of Django. 119 120 Allows storage, manipulation and display of Geographic data. 121 114 122 humanize 115 123 ======== 116 124