Search code examples
pythonpostgisgeoalchemy2

Storing a WKBElement in PostGis using Geoalchemy2 results in an incorrect longitude


I'm working on an application which needs to be able to store a point in a PostGis database. I'm using GeoAlchemy, and it seems to store an incorrect longitude.

I have this code to process a request to add an Event with Point location data.

json_data = request.get_json(force=True)
if "location" in json_data:
    json_location = json_data["location"]
    geojson_geom = geojson.loads(json.dumps(json_location))
    geom = from_shape(asShape(geojson_geom), srid=4326)
    json_data["location"] = geom

event = Event(**json_data)
try:
  session = Session()
  session.add(event)
  session.commit()
  session.refresh(event)
except IntegrityError as e:
  abort(409, error=e.args[0])

The model I use

class Event(Base):
    __tablename__ = 'events'

    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)
    location = Column(Geography(geometry_type='POINT', srid=4326), nullable=False)

When I use this test data:

{
  "name": "Test",
  "location": {
    "coordinates": [
      47.65641, 
      -117.42733
    ],
    "type": "Point"
  }
}

Then str(geom) will equal 010100000039622d3e05d4474061a6ed5f595b5dc0, and if I use this converter I get POINT(47.65641 -117.42733), which is the correct location.

However when I look up the row in the database I see that 0101000020E610000039622D3E05D447403EB324404D494FC0 is stored in the location column, which is POINT(47.65641 -62.57267): a very different longitude.

As far as I know, I supply the correct data and format to GeoAlchemy2 and I would greatly appreciate if someone could hint at what I am doing wrong here.


Solution

  • In Postgis, the points coordinates are expressed as Point(longitude, latitude), so the value -117 is the latitude, which is invalid in 4326.

    Try swapping the input coordinates in the test data.