How to create geoalchemy expression for a point geometry?

2.3k views Asked by At

I have a table with lat and long, i don't want to store geometry. Instead i am storing lat and longs.

How to create point based queries using position expression? basically it should return point. Which should be converted to SQL expression like ".....ST_Point(home.latitude, home.longitude)....."

There is no func.ST_Point in geoalchemy ? or am i missing something ? if i dont write expression obviously i get

"sqlalchemy.exc.InternalError: (InternalError) parse error - invalid geometry
HINT:  "POINT(Ve" <-- parse error at position 8 within geometry"

Code:

class Home(Base):
__tablename__ = 'vehicle_path'

id = Column(BigInteger, primary_key=True)
latitude = Column(Float)
longitude = Column(Float)

@hybrid_property
def position(self):
    return WKTElement(
        ''.join(['POINT(', str(self.longitude),' ', str(self.latitude), ')']), 4326)

@position.expression
def position(cls):
    return  <???what to return???>

I am using sqlalchemy, Geoalchmey2 with postgis, postgres, pyramid.

1

There are 1 answers

0
John Powell On

It sounds like you are looking for WKTElement http://geoalchemy-2.readthedocs.org/en/latest/elements.html#geoalchemy2.elements.WKTElement There is an ST_MakePoint(x,y) function in Postgis, but not in Geoalchemy it would seem. As a matter of interest, why would you want to store latitude and longitude instead of a geometry (or Point in your case). You can easily recover the latitude and longitude from the geometry using ST_X(geom), ST_Y(geom), but more importantly you can put a spatial index on a geometry column, which will perform much better than two separate non-spatial columns for any kind of spatial queries.