I am trying to calculate the distance (in meters) between 2 lon/lng points of type shapely.geometry.point.Point using Python and Shapely. These 2 points are returned from PostGIS by SQLAlchemy/Geoalchemy2 as geoalchemy2.elements.WKBElement, which is then converted to shapely's shapely.geometry.point.Point using geoalchemy2.

However, when I try to use the distance function to calculate the distance in meters, the result is expected to be around 1490 m, but the code calculated it to be 0.013402616901217364.

What went wrong with our code? Thanks!

Note: Distance calculations will not exceed 30 km

from geoalchemy2.shape import to_shape

users = db_session().query(User).limit(2).all()
foo, bar = users[0], users[1]

print(type(foo.coordinates))               # <class 'geoalchemy2.elements.WKBElement'>
print(type(to_shape(foo.coordinates)))     # <class 'shapely.geometry.point.Point'>

distance = to_shape(foo.coordinates).distance(to_shape(bar.coordinates))
print(distance)                            # 0.013402616901217364
  • @gene Thanks, if I understand it correctly it appears that Shapely calculates the Euclidean distance, which is does not suitable for lat/lng data which requires WGS84 distance for it to be in the unit of meters. In this case, is it easier/better to work with the WKBElement originally returned by Geoalchemy?
    – Nyxynyx
    Jan 23 at 16:50
  • Simply change the projection of the geometry
    – gene
    Jan 23 at 17:33
  • 1
    @Nyxynyx, You're right about shapely returning the euclidean distance. If you want to do operations that involve CRS information, you'll probably want to use either geopandas or pyproj (which is what geopandas uses). For example pyproj.Geod.inv will solve your problem, I think. Feb 3 at 22:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.