6

I'm trying to add coordinate information to my database, adding django.contrib.gis support to my app. I'm writing a south data migration that takes the addresses from the database, and asks Google for the coordinates (so far I think my best bet is to use geopy for this).

Next I need to convert the returned coordinates from WGS84:4326, Google's coordinate system, to WGS84:22186, my coordinate system.

I'm lost among the GeoDjango docs trying to find a way to do this. This far, I gather I need to do this:

gcoord = SpatialReference("4326")
mycoord = SpatialReference("22186")
trans = CoordTransform(gcoord, mycoord)

but then, I don't know how to use that CoordTransform object.. seems to be used by GDAL's data objects, but that's overkill for what I want to do..

Lacrymology
  • 2,269
  • 2
  • 20
  • 28

2 Answers2

12

If you have all your libraries installed correctly there is no need to use the CoordTransform object, the point object's transform method will do the work for you if you know your desired srid value.

>>> from django.contrib.gis.geos import Point
>>> pnt = Point(30, 50, srid=4326)
>>> desired_srid = 22186
>>> pnt.transform(desired_srid)
>>> pnt.ewkt
u'SRID=22186;POINT (11160773.5712331663817167 19724623.9116888605058193)'
monkut
  • 42,176
  • 24
  • 124
  • 155
8

CoordTransform wouldn't work without GDAL that's true. But the rest of it is simple enough:

>>> from django.contrib.gis.gdal import SpatialReference, CoordTransform
>>> from django.contrib.gis.geos import Point
>>> gcoord = SpatialReference(4326)
>>> mycoord = SpatialReference(22186)
>>> trans = CoordTransform(gcoord, mycoord)

>>> pnt = Point(30, 50, srid=4326)
>>> print 'x: %s; y: %s; srid: %s' % (pnt.x, pnt.y, pnt.srid)
x: 30.0; y: 50.0; srid: 4326
>>> pnt.transform(trans)
>>> print 'x: %s; y: %s; srid: %s' % (pnt.x, pnt.y, pnt.srid)
x: 11160773.5712; y: 19724623.9117; srid: 22186

Note that point is transformed in place.

Pill
  • 4,815
  • 1
  • 24
  • 26
  • 2
    it's worth remembering that points are mutable and therefore the original coordinates will change when you transform it (even if it has been assigned to a new variable). You can create a copy of your point by creating a new point out your point which will not be mutated. For example: new_point = Point(old_point.x, old_point.y) so when you transform old_point, new_point will remain in the old projection. – zom-pro Apr 03 '15 at 09:52