|
1 def add_postgis_srs(srs, auth_name='EPSG', auth_srid=None, ref_sys_name=None): |
|
2 """ |
|
3 This function takes a GDAL SpatialReference system and adds its |
|
4 information to the PostGIS `spatial_ref_sys` table -- enabling |
|
5 spatial transformations with PostGIS. This is handy for adding |
|
6 spatial reference systems not included by default with PostGIS. |
|
7 For example, the following adds the so-called "Google Maps Mercator |
|
8 Projection" (available in GDAL 1.5): |
|
9 |
|
10 >>> add_postgis_srs(SpatialReference(900913)) |
|
11 |
|
12 Keyword Arguments: |
|
13 auth_name: This keyword may be customized with the value of the |
|
14 `auth_name` field. Defaults to 'EPSG'. |
|
15 |
|
16 auth_srid: This keyword may be customized with the value of the |
|
17 `auth_srid` field. Defaults to the SRID determined |
|
18 by GDAL. |
|
19 |
|
20 ref_sys_name: For SpatiaLite users only, sets the value of the |
|
21 the `ref_sys_name` field. Defaults to the name |
|
22 determined by GDAL. |
|
23 """ |
|
24 from django.contrib.gis.db.backend import SpatialBackend |
|
25 from django.contrib.gis.models import SpatialRefSys |
|
26 from django.contrib.gis.gdal import SpatialReference |
|
27 |
|
28 if SpatialBackend.oracle or SpatialBackend.mysql: |
|
29 raise Exception('This utility not supported on Oracle or MySQL spatial backends.') |
|
30 |
|
31 if not isinstance(srs, SpatialReference): |
|
32 srs = SpatialReference(srs) |
|
33 |
|
34 if srs.srid is None: |
|
35 raise Exception('Spatial reference requires an SRID to be compatible with PostGIS.') |
|
36 |
|
37 # Initializing the keyword arguments dictionary for both PostGIS and SpatiaLite. |
|
38 kwargs = {'srid' : srs.srid, |
|
39 'auth_name' : auth_name, |
|
40 'auth_srid' : auth_srid or srs.srid, |
|
41 'proj4text' : srs.proj4, |
|
42 } |
|
43 |
|
44 # Backend-specific keyword settings. |
|
45 if SpatialBackend.postgis: kwargs['srtext'] = srs.wkt |
|
46 if SpatialBackend.spatialite: kwargs['ref_sys_name'] = ref_sys_name or srs.name |
|
47 |
|
48 # Creating the spatial_ref_sys model. |
|
49 sr, created = SpatialRefSys.objects.get_or_create(**kwargs) |