在GIS进行空间分析时经常会需要计算最短路径,我也是最近在计算DPC的时候有这方面的需求,刚开始直接是用面的中心点求得距离,但其对不规则或空洞面很不友好。所以今天跟大家分享一下基于Geopandas和Shapely计算矢量面最短路径,这里的最短即点/边的最短!
原创作者:RS迷途小书童
# -*- coding: utf-8 -*-
"""
@Time : 2024/7/3 9:52
@Auth : RS迷途小书童
@File :Vectors Data Short Distance.py
@IDE :PyCharm
@Purpose:检查两个要素的最短路径
@Web:博客地址:https://blog.csdn.net/m0_56729804
"""
from shapely.geometry import Polygon
from shapely.ops import nearest_points
import matplotlib.pyplot as plt
import geopandas as gpd
def check_short_distance_between_vector(shp_path=r"Y:\1.shp"):
"""
:param shp_path: 输入面矢量文件,默认计算前两个要素的最短路径
:return: 最近点1,最近点2,最短路径
"""
gdf = gpd.read_file(shp_path)
list_geometry = []
for index, row in gdf.iterrows(): # 循环矢量属性表
geometry = row['geometry']
list_geometry.append(geometry)
# polygon1 = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])
# polygon2 = Polygon([(2, 2), (3, 2), (3, 3), (2, 3)])
polygon1, polygon2 = list_geometry[0], list_geometry[1]
point1, point2 = nearest_points(polygon1, polygon2) # 使用 nearest_points 函数找到两个多边形之间的最近点
distance = point1.distance(point2) # 计算两点之间的距离
print(f"The shortest path between the two polygons is {distance} units.")
print(f"The points are {point1} and {point2}.")
fig, ax = plt.subplots() # 可视化两个多边形和最短路径
x1, y1 = polygon1.exterior.xy
x2, y2 = polygon2.exterior.xy
ax.plot(x1, y1, color='blue', label='Polygon 1') # 绘制多边形
ax.plot(x2, y2, color='green', label='Polygon 2')
ax.plot([point1.x, point2.x], [point1.y, point2.y], color='red', linestyle='--', label='Shortest Path') # 绘制最短路径
ax.scatter([point1.x, point2.x], [point1.y, point2.y], color='red')
ax.legend()
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Shortest Path between Two Polygons')
plt.grid(True)
plt.show()
return point1, point2, distance
if __name__ == "__main__":
check_short_distance_between_vector()
标签:distance,plt,GIS,Shapely,point1,Python,geometry,point2,ax From: https://www.cnblogs.com/RSran/p/18281161