Search code examples
pythonpandasgeometrygeopandasgeo

How to turn latitude and longitude distance into meters?


I was able to get the shortest distance between a point and LINESTRING. The points and line string where in "epsg=4326" which I am assuming is latitude and longitude. How do I make sure the distance is in meters or km.

I was able to get the distance below


import geopandas as gpd
import shapely.wkt
import shapely.geometry

line_string = ["LINESTRING (-1.15.12 9.9, -1.15.13 9.93)", "LINESTRING (-2.15.12 8.9, -2.15.13 8.93)"]
# fix invalid wkt string...
line_string = ["LINESTRING (-1.15 9.9, -1.15 9.93)", "LINESTRING (-2.15 8.9, -2.15 8.93)"]
point = "POINT (5.41 3.9)"

gdf_p = gpd.GeoDataFrame(geometry=[shapely.wkt.loads(point)])
gdf_l = gpd.GeoDataFrame(geometry=pd.Series(line_string).apply(shapely.wkt.loads))

df_n = gpd.sjoin_nearest(gdf_p, gdf_l).merge(gdf_l, left_on="index_right", right_index=True)

df_n["distance"] = df_n.apply(lambda r: r["geometry_x"].distance(r["geometry_y"]), axis=1)

df_n


Solution

  • You need to reproject your geometries from EPSG:4326, which is in decimal degrees, to a metric coordinate system, e.g. EPSG:3857 or some local coordinate system for higher precision.

    You will only need to modify these lines:

    gdf_p = gpd.GeoDataFrame(geometry=[shapely.wkt.loads(point)]).set_crs('EPSG:4326').to_crs('EPSG:3857')
    
    gdf_l = gpd.GeoDataFrame(geometry=pd.Series(line_string).apply(shapely.wkt.loads)).set_crs('EPSG:4326').to_crs('EPSG:3857')