2017-04-10 105 views
4

我不知道到底是什麼錯,但我想不出它在所有...的Python - 獲取從GPS經度和緯度的總距離

所以我有這樣的代碼:

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: too many values to unpack (expected 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 

現在是在一個文件,但這個數據將被存儲在數據庫中。

我該如何解決這個問題?我該如何擺脫這個錯誤?

+0

什麼錯誤?你能否給出一些簡單的輸入/輸出與預期輸出的例子。 – Scheme

+0

已更新。對不起,忘了放錯了。 – Robin

回答

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()使用您使用的是相同的基本邏輯,但包裹在一個函數邏輯了,最重要的,將值保持爲浮動。

+0

24秒前回答。該死,我的編輯啓動起來很慢。 – Scheme

+0

Okej,這樣的工作,但我怎麼能循環所有的價值?所以它會一直工作並給我正確的距離? – Robin