AndrewX192
AndrewX192

Reputation: 23

GeoDjango Converting SRID 4326 to SRID 3857

I'm having difficulty converting SRID 4326 coordinates from a geocoder to SRID 3857 for storage within my postgres-postgis database. I am using the following code to test transforming between SRIDs:

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

pnt = Point(47.61, -122.33, srid=4326)
print 'x: %s; y: %s; srid: %s' % (pnt.x, pnt.y, pnt.srid)

x: 47.61; y: -122.33; srid: 4326

pnt.transform(trans)
print 'x: %s; y: %s; srid: %s' % (pnt.x, pnt.y, pnt.srid)

django.contrib.gis.gdal.error.GDALException: OGR failure.

Within Django, I get the more helpful error message:

transform: couldn't project point (47.61 -122.33 0): latitude or longitude exceeded limits (-14)

I've performed some rudimentary testing and determined that lat/long coordinate outside of 0-90 trigger this condition. Setting my Point field in Django to srid=4326 and migrating the database still results in the Point being converted to SRID 3857.

Upvotes: 2

Views: 3835

Answers (1)

Andrew Basile
Andrew Basile

Reputation: 896

I also stumbled here. The issue is that, in calling the Point constructor, the longitude needs to come before the latitude. (Never mind that latitude/longitude, in that order, may be engrained in our minds...) Longitude is 'x' and latitude is 'y'. So, you should have:

pnt = Point(-122.33, 47.61, srid=4326)

Or, better yet, use named arguments for clarity:

pnt = Point(x=-122.33, y=47.61, srid=4326)

Upvotes: 5

Related Questions