我正在寻找解决任何给定多边形的问题,如何找到 2 个最远的坐标对(也称为最大线性范围)并计算给定多边形的这 2 个最远坐标之间的距离(以海里为单位)。
尽管我的尝试没有成功,下面是到目前为止我尝试过的代码:
import shapely.geometry as sg
import math
from shapely import Polygon, length
import geopy.distance as distance
# Create the polygon object
t1 = sg.Polygon([(-74.418225663382, 39.36239030236737), # Further Point 1: Atlantic City, NJ
(-74.27880733397238, 39.71055595453288),
(-74.75681303480502, 40.219387193292164),
(-75.4705021020208, 40.60356289498688),
(-76.88460230031765, 40.264996135212186), # Further Point 2: Harrisburg, PA
(-74.418225663382, 39.36239030236737)])
# Initialize variables to store the furthest coordinates
furthest_pair = None
max_distance = 0
# Iterate through all pairs of coordinates in the polygon
for i, p1 in enumerate(t1.exterior.coords):
for j, p2 in enumerate(t1.exterior.coords[i+1:]):
distance = p1.distance(p2) # Calculate the distance between the points
if distance > max_distance:
max_distance = distance
furthest_pair = (p1, p2)
# Print the furthest coordinates and their distance
print("Furthest coordinates:", furthest_pair) # This should print 2 furthest coordinates pair
print("Distance between them:", max_distance) # Distance in Nautical Miles
print("Should be: ", 126.0, "NM")
感谢任何反馈和支持。谢谢!
正如口译员所说:
AttributeError: 'tuple' object has no attribute 'distance'
原因是你写的是:
import geopy.distance as distance
但这行的意思是:导入
geopy.distance
又名distance
。这是错误的,因为我认为您想要导入距离方法。这就是代码应该是的:
from geopy.distance import distance
距离方法也具有以下语法(官方文档):
distance(tuple1, tuple2)
。如果您想要以海里为单位的距离,请在方法末尾使用 .nm
。
总结:
import shapely.geometry as sg
from geopy.distance import distance
# Create the polygon object
t1 = sg.Polygon([(-74.418225663382, 39.36239030236737), # Further Point 1: Atlantic City, NJ
(-74.27880733397238, 39.71055595453288),
(-74.75681303480502, 40.219387193292164),
(-75.4705021020208, 40.60356289498688),
(-76.88460230031765, 40.264996135212186), # Further Point 2: Harrisburg, PA
(-74.418225663382, 39.36239030236737)])
# Initialize variables to store the furthest coordinates
furthest_pair = None
max_distance = 0
# Iterate through all pairs of coordinates in the polygon
for i, p1 in enumerate(t1.exterior.coords):
for j, p2 in enumerate(t1.exterior.coords[i+1:]):
dist = distance(p1, p2).nm # Calculate the distance between the points
if dist > max_distance:
max_distance = dist
furthest_pair = (p1, p2)
# Print the furthest coordinates and their distance
print("Furthest coordinates:", furthest_pair) # This should print 2 furthest coordinates pair
print("Distance between them:", max_distance) # Distance in Nautical Miles
print("Should be: ", 126.0, "NM")
我可以通过三个小修改让你的代码正常工作:
p1.distance(p2)
,但 p1 是一个元组并且没有名为 distance
的函数。您会收到一条错误通知。相反,请致电
distance.distance(p1, p2)
。distance
来表示不同的含义。第一个在这里:import geopy.distance as distance
distance = p1.distance(p2)
distance
模块,并将其替换为距离函数返回的任何内容(我相信是测地线)。这会在下次循环并尝试使用该模块时导致错误:AttributeError: 'geodesic' object has no attribute 'distance'
。pair_distance
或类似的名称。