简体   繁体   中英

Find longest “straight” path between Point and Polygon

Is it possible to find the longest straight distance between a Point (latitude and longitude) and a Polygon in Shapely ? I read it's possible to find the closest path, but i'm not sure about the longest.

Try the Hausdorff distance , which is returned by the g1.hausdorff_distance(g2) fuction:

from shapely.geometry import Polygon, Point
poly = Polygon([(-1, -1), (-2, 2), (4, 4), (4, -1), (-1, -1)])
p = Point(0, 0)
poly.hausdorff_distance(p)  # 5.656854249492381

Keep in mind, Shapely only works in Cartesian space. Your question asks about "latitude and longitude", so these distance units are in degrees. You'd need to project this into a suitable coordinate reference system (CRS) to get more conventional units of length. Furthermore, the definition of "straight path" changes depending on the choice of CRS.

One way is discretizing the exterior of the polygon into set of points and calculate the distance between the point and each point in this set of points:

def longest(poly, p, num):

    lr = LinearRing(poly.exterior.coords)
    dist = 0
    for i in np.linspace(0, lr.length, num):
        d = p.distance(lr.interpolate(i))
        if d > dist:
            dist = d
    return dist


poly = Polygon([(-1, -1), (-2,2), (4,4), (4, -1), (-1, -1)])
p = Point(0,0)
longest(poly, p, 20)
# out: 5.428886519426354
longest(poly, p, 100)
# out: 5.622291976018042

Of course it is not exact, but it can be a reasonable approximation for many situations.

Remark: you should not use lon/lat with shapely for distance. Shapely is based on cartesian coordinate system. Generally, you should first project your geometries (using pyproj) to be able to use shapely for measuring distance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM