如果您正在地图上寻找与列表中所有坐标的距离最短的任何点,您可以尝试编写一个函数来计算从一个坐标到另一个坐标的距离。如果您准备好使用该功能,则只需计算从测试点到所有点的总距离。
然后,从一些人为创建的坐标中,您将使用沿线的东西最小化到所有点的距离
import numpy as np
lats = [12.3, 12.4, 12.5]
lons = [16.1, 15.1, 14.1]
def total_distance_to_lats_and_lons(lat, lon):
# some summation over distances from lat, lon to lats, lons
# create two lists with 0.01 degree precision as an artificial grid of possibilities
test_lats = np.arange(min(lats), max(lats), 0.01)
test_lons = np.arange(min(lons), max(lons), 0.01)
test_distances = [] # empty list to fill with the total_distance to each combination of test_lat, test_lon
coordinate_index_combinations = [] # corresponding coordinates
for test_lat in test_lats:
for test_lon in test_lons:
coordinate_combinations.append([test_lat, test_lon]) # add a combination of indices
test_distances.append(total_distance_to_lats_and_lons(test_lat, test_lon)) # add a distance
index_of_best_test_coordinate = np.argmin(test_distances) # find index of the minimum value
print('Best match is index {}'.format(index_of_best_test_coordinate))
print('Coordinates: {}'.format(coordinate_combinations[index_of_best_test_coordinate]))
print('Total distance: {}'.format(test_distances[index_of_best_test_coordinate]))
这种蛮力方法有一些精度限制,很快就会变成一个昂贵的循环,所以你也可以迭代地应用这个方法,在每一轮之后找到最小值,这样迭代地提高精度并减少测试坐标列表中的起点和终点.经过几次迭代后,您应该有一个非常精确的估计。另一方面,这种迭代方法有可能收敛到多个局部最小值中的一个,只产生多个解中的一个。