使用地理坐标,给定任意点,如何找到线串上最近的现有点?

问题描述 投票:0回答:1

我正在使用 shapely 和 django-gis。我得到了一个具有完整坐标的线串和一个四舍五入到 6 坐标的点。

我需要的是从给定的任意点(线串上最近的点)找到距离我的线串最近的现有点的索引,并在索引+1处添加线串上最近点的坐标。

我的代码如下。然而,对于某些点,它会引发 ValueError,因为最近的点不在线串中。

成功数据示例:

输入:

(4.756696, 45.381095)
输出:
(4.75669614409327, 45.3810948660022)

失败数据示例:

输入:

(4.756614, 45.380532)
输出
(4.756613683262075, 45.38053204640647) # this point is not inside the given linestring.

class SomeClass:
    @staticmethod
    def closest_point_on_linestring(line_coords: list, point: Point):
        line = LineString(line_coords)
        min_dist = float('inf')
        closest_point = None

        for idx in range(len(line_coords) - 1):
            segment_start = line_coords[idx]
            segment_end = line_coords[idx + 1]
            segment = LineString([segment_start, segment_end])

            # Project the point onto the segment
            projected_point = segment.interpolate(segment.project(point))

            # Calculate the distance from the point to the segment
            distance = projected_point.distance(point)

            # Calculate the distance between the segment's start and end points
            segment_length = Point(segment_start).distance(Point(segment_end))

            # Check if the distance to the segment is within the segment length
            if 0 <= segment.project(projected_point) <= segment_length:
                if distance < min_dist:
                    min_dist = distance
                    closest_point = projected_point

        return closest_point

   def another_function(self):
       ...
       closest = self.closest_point_on_linestring(line, Point(landmark_point))
       index = list(line_string.coords).index(closest.coords[0])
       ...

下面是我的要求的可怕绘图:

黑线代表我的线串,红点代表该线串的点,绿点代表我给出的任意点。我需要找到每个绿点最近的红点以及线串内最近的点(插值用蓝线表示)。

python geolocation geo shapely
1个回答
0
投票

这听起来像是树的典型操作,这里是一个使用 scipy 的示例:

创建线串:

import numpy as np
import shapely
from scipy.spatial import KDTree

curve = ((5, 5), (5, 6), (6, 7), (7, 7), (8, 7.5))
linestring = shapely.LineString(curve)

在给定点的情况下找到形状线串的最近点:

tree = KDTree(np.array(linestring.coords))
point = [6.6, 6.5]
_, index = tree.query(point)

print(f"closest point: {curve[index]}")
© www.soinside.com 2019 - 2024. All rights reserved.