- your sample geometry is invalid for line strings, have modified
- it's simple to achieve with
sjoin_nearest()
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
|
geometry_x |
index_right |
geometry_y |
distance |
0 |
POINT (5.41 3.9) |
0 |
LINESTRING (-1.15 9.9, -1.15 9.93) |
8.89008 |
distance in meters
- use a CRS that is in meters. UTM has it's limitations if all points are not in same zone
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)], crs="epsg:4326")
gdf_l = gpd.GeoDataFrame(geometry=pd.Series(line_string).apply(shapely.wkt.loads), crs="epsg:4326")
gdf_p = gdf_p.to_crs(gdf_p.estimate_utm_crs())
gdf_l = gdf_l.to_crs(gdf_p.crs)
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