Python經緯度坐標轉換為距離及角度的實現
更新時間:2020年11月01日 10:44:43 作者:_Seven°
這篇文章主要介紹了Python經緯度坐標轉換為距離及角度的實現,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
最近項目上有這樣的需求,需要依據設備的經緯度坐標計算距離及角度。經驗證后效果較好,并分享。
1 經緯度轉換距離代碼
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Seven' import math # 計算距離 def getDistance(latA, lonA, latB, lonB): ra = 6378140 # 赤道半徑 rb = 6356755 # 極半徑 flatten = (ra - rb) / ra # Partial rate of the earth # change angle to radians radLatA = math.radians(latA) radLonA = math.radians(lonA) radLatB = math.radians(latB) radLonB = math.radians(lonB) pA = math.atan(rb / ra * math.tan(radLatA)) pB = math.atan(rb / ra * math.tan(radLatB)) x = math.acos(math.sin(pA) * math.sin(pB) + math.cos(pA) * math.cos(pB) * math.cos(radLonA - radLonB)) c1 = (math.sin(x) - x) * (math.sin(pA) + math.sin(pB)) ** 2 / math.cos(x / 2) ** 2 c2 = (math.sin(x) + x) * (math.sin(pA) - math.sin(pB)) ** 2 / math.sin(x / 2) ** 2 dr = flatten / 8 * (c1 - c2) distance = ra * (x + dr) distance = round(distance / 1000, 4) return f'{distance}km'
2 經緯度轉化角度代碼
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Seven' import math # 計算角度 def getDegree(latA, lonA, latB, lonB): radLatA = math.radians(latA) radLonA = math.radians(lonA) radLatB = math.radians(latB) radLonB = math.radians(lonB) dLon = radLonB - radLonA y = math.sin(dLon) * math.cos(radLatB) x = math.cos(radLatA) * math.sin(radLatB) - math.sin(radLatA) * math.cos(radLatB) * math.cos(dLon) brng = math.degrees(math.atan2(y, x)) brng = round((brng + 360) % 360, 4) brng = int(brng) if (brng == 0.0) or ((brng == 360.0)): return '正北方向' elif brng == 90.0: return '正東方向' elif brng == 180.0: return '正南方向' elif brng == 270.0: return '正西方向' elif 0 < brng < 90: return f'北偏東{brng}' elif 90 < brng < 180: return f'東偏南{brng - 90}' elif 180 < brng < 270: return f'西偏南{270 - brng}' elif 270 < brng < 360: return f'北偏西{brng - 270}' else: pass
3 驗證
選取深圳野生動物園(22.599578, 113.973129)為起點,深圳坪山站(22.6986848, 114.3311032)為終點,結合百度地圖、谷歌地圖等進行效果驗證。
程序運行結果如下:
百度測距為38.3km
Google地圖手動測距為39.31km
距離與角度均無問題。
到此這篇關于Python經緯度坐標轉換為距離及角度的實現的文章就介紹到這了,更多相關Python經緯度坐標轉換為距離及角度內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python之日期與時間處理模塊(date和datetime)
這篇文章主要介紹了Python之日期與時間處理模塊(date和datetime),小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02