Answers:
这是一个解析几何问题,Paul Bourke在1998年提出了解决方案(点与线之间的最小距离)。从点到线或线段的最短距离是从该点到线段的垂直线。他的算法的几种版本已在多种语言中提出,包括Python,如在Python中测量从点到线段的距离。但还有很多其他的东西(例如 Shapely 在点层和线层之间的最近邻居)
# basic example with PyQGIS
# the end points of the line
line_start = QgsPoint(50,50)
line_end = QgsPoint(100,150)
# the line
line = QgsGeometry.fromPolyline([line_start,line_end])
# the point
point = QgsPoint(30,120)
def intersect_point_to_line(point, line_start, line_end):
''' Calc minimum distance from a point and a line segment and intersection'''
# sqrDist of the line (PyQGIS function = magnitude (length) of a line **2)
magnitude2 = line_start.sqrDist(line_end)
# minimum distance
u = ((point.x() - line_start.x()) * (line_end.x() - line_start.x()) + (point.y() - line_start.y()) * (line_end.y() - line_start.y()))/(magnitude2)
# intersection point on the line
ix = line_start.x() + u * (line_end.x() - line_start.x())
iy = line_start.y() + u * (line_end.y() - line_start.y())
return QgsPoint(ix,iy)
line = QgsGeometry.fromPolyline([point,intersect_point_to_line(point, line_start, line_end)])
结果是
使解决方案适应您的问题很容易,只需遍历所有线段,提取线段端点并应用功能即可。