Search code examples
djangogdalgeodjangocoordinate-transformation

Geodjango: transform() swaps lat/long incorrectly


I'm using geodjango and load a shapefile as follows:

datasource = DataSource("/path/to/shape.shp")
for each in datasource[0]:
    geo = each.geom    
    geo.transform(4326)

What I'm trying to do here is to transform a geometry to 4326 so I can record it in my database, which uses this SRID. However, a rather odd thing happens. When I run this locally (using GDAL 2.4.0, Django 3.0.6) this works perfectly fine. Here is an example of a polygon that is transformed.

Input:

POLYGON ((141192.63413501 167690.231242441,141198.39365501 167695.515882441...

Which is then transformed into:

POLYGON ((4.24376514198078 50.8195815928706,4.24384675060931 50.819629186136...

This works well. However, when this runs in production (GDAL 3.0.4, Django 3.0.3), then this fails in a very weird way. There is no error message, and the transform() function does its thing... but it reverses latitude and longitude! So my output becomes:

POLYGON ((50.8195818670687 4.24376485512428,50.8196294603646 4.24384646375124...

I can not fathom why this happens...?! It all seems to be fine, expect for this very odd swapping of lat/long.


Solution

  • The problem is that you are using different environments for development and production.

    Django 3.0.3/3.0.6 does not create a problem (but it's better to upgrade to the latest patch release with pip install django==3.0.* -U).

    But GDAL creates. You need at least read GDAL migration guide before moving on to a new release.

    3.0 have incompatible changes with axis which you seem to have encountered.

    You can try method, that suggested here:

    import osgeo
    
    # ... so something to create and SRS:
    srs = SpatialReference()
    
    if int(osgeo.__version__[0]) >= 3:
        # GDAL 3 changes axis order: https://github.com/OSGeo/gdal/issues/1546
        srs.SetAxisMappingStrategy(osgeo.osr.OAMS_TRADITIONAL_GIS_ORDER)
    

    But your development and production environments must always match.