如何找到离 POINT 最近的 LINESTRING?

how to find the nearest LINESTRING to a POINT?

如何为一个点附近最近的 LINESTRING 提供资金?

首先我有一个 LINESTRING 和点值的列表。我如何获得最接近 POINT (5.41 3.9) 的 LINESTRING 以及距离?

from shapely.geometry import Point, LineString

line_string = [LINESTRING (-1.15.12 9.9, -1.15.13 9.93), LINESTRING (-2.15.12 8.9, -2.15.13 8.93)]
point = POINT (5.41 3.9)

#distance 
line_string [0].distance(point)

到目前为止,我认为我通过对第一个 LINESTRING 执行 line_string [0].distance(point) 得到了距离值,但我只是想确保我以正确的方式进行.

  • 您的示例几何对于线串无效,已修改
  • 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

距离(米)

  • 使用以米为单位的 CRS。如果所有点不在同一区域,UTM 有其局限性
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

这是一个函数,它接受 LineStrings 和 point 的列表,以及 returns 最接近 pointLineString,以及作为距离。

from shapely.geometry import Point, LineString

# set up lines and points
line_string_list = [LineString([(-1,1),(1,.5)]), LineString([(-1,-.5),(.5,-1)]), LineString([(-1,0),(.5,-.5)])]
point = Point(.25,-.75)

def closest_line(lines, point):
    # get distances
    distance_list = [line.distance(point) for line in line_string_list]
    shortest_distance = min(distance_list) # find the line closest to the point
    return(lines[distance_list.index(shortest_distance)], # return the closest line
           shortest_distance) # return the distance to that line
    
print(closest_line(line_string_list, point))