Python - 从GPS经纬度获取总距离

4

我不知道这个有什么问题,但是我完全搞不懂。

所以我有这段代码:

from model.Formulas import Formulas

f = open("coords_data.txt", "r")
line1 = f.readline()
line2 = f.readline()

orig = line1.split(';')
dest = line2.split(';')

origin = (orig[0] + ", " + orig[1].strip("\n"))
destination = (dest[0] + ", " + dest[1].strip("\n"))

print("Orig: " + str(origin))
print("Dest: " + str(destination))

total_dist = Formulas.calculateDistance(str(origin), str(destination))

# Formulas.calculateDistance()

导入代码为:

import math

class Formulas:
    # 3959  # radius of the great circle in miles...some algorithms use 3956
    # 6371  # radius in kilometers...some algorithms use 6367
    # 3959 * 5280  # radius in feet
    # 6371 * 1000  # radius in meters
    @staticmethod
    def calculateDistance(origin, destination, rounding=0):
        lat1, lon1 = origin
        lat2, lon2 = destination
        radius = 6371  # km

        dlat = math.radians(lat2 - lat1)
        dlon = math.radians(lon2 - lon1)
        a = math.sin(dlat / 2) * math.sin(dlat / 2) + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon / 2) * math.sin(dlon / 2)
        c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
        d = radius * c
        return round(d, rounding)

现在我希望从一个包含5057行坐标的大型列表中获取确切的总距离。因此,它需要计算所有距离之间的差异并返回一个大型数字(例如150公里)。

我收到的错误消息是:

ValueError:要拆分的值过多(预期2个)

文件中的坐标看起来像这样:

5114.8268;00457.9847
5114.8271;00457.9845
5114.8271;00457.9845
5114.8271;00457.9845
5114.8270;00457.9846
5114.8271;00457.9846
5114.8272;00457.9847
5114.8272;00457.9847
5114.8274;00457.9843
5114.8272;00457.9846
5114.8274;00457.9843
5114.8277;00457.9837
5114.8287;00457.9835
5114.8274;00457.9843
5114.8288;00457.9831
5114.8287;00457.9835
5114.8286;00457.9813
5114.8274;00457.9843
5114.8287;00457.9815
5114.8286;00457.9813
5114.8270;00457.9846
5114.8286;00457.9813
5114.8355;00457.9784
5114.8292;00457.9814
5114.8274;00457.9843
5114.8376;00457.9776
5114.8395;00457.9769

现在这些数据已经存储在文件中,但是将来会存储到数据库中。

我该怎么解决这个问题?如何消除这个错误?


什么错误?你能给一些简单的输入/输出示例和预期输出吗? - axwr
已更新。抱歉,忘记放置错误。 - Robin
1个回答

3

Formulas.calculateDistance()希望接受由浮点数组成的元组:

试试这个:

line1 = "5114.8268;00457.9847"
line2 = "5114.8271;00457.9845"

def strip_line(line_str):
    x, y = line_str.split(';')
    return float(x), float(y.strip())

total_dist = Formulas.calculateDistance(
    strip_line(line1), strip_line(line2))

strip_line()函数使用了与您相同的基本逻辑,但将逻辑封装在一个函数中,并最重要的是,将值保持为浮点数。


刚才回答了。该死,我的编辑器启动太慢了。 - axwr
好的,那可以工作,但是如何循环遍历所有值呢?这样它将始终工作并给出正确的距离? - Robin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接