【问题标题】:Python - Get total distance from GPS longitude and latitudePython - 从 GPS 经度和纬度获取总距离
【发布时间】:2017-09-05 23:46:46
【问题描述】:

我不知道这到底是怎么回事,但我根本想不通。

所以我有这个代码:

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 行)中获取确切的总距离。所以它需要计算距离之间的所有差异并返回一个大数字(例如150km)。

我得到的错误是:

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

它现在在一个文件中,但这些数据将存储在一个数据库中。

我该如何解决这个问题?我应该如何摆脱这个错误?

【问题讨论】:

  • 什么错误?你能举一些简单的输入/输出与预期输出的例子吗?
  • 已更新。抱歉,忘记写错了。

标签: python python-3.x gps coordinates


【解决方案1】:

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() 使用与您使用的相同的基本逻辑,但将逻辑包装在一个函数中,最重要的是,将值保持为浮点数。

【讨论】:

  • 24 秒前回答。该死,我的编辑器启动很慢。
  • Okej,这样行得通,但是我怎样才能循环遍历所有值?所以它总是可以工作并给我正确的距离?
猜你喜欢
  • 1970-01-01
  • 2014-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多