1. 程式人生 > 程式設計 >Python經緯度座標轉換為距離及角度的實現

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,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)為終點,結合百度地圖、谷歌地圖等進行效果驗證。

程式執行結果如下:

Python經緯度座標轉換為距離及角度的實現

百度測距為38.3km

Google地圖手動測距為39.31km

Python經緯度座標轉換為距離及角度的實現

Python經緯度座標轉換為距離及角度的實現

距離與角度均無問題。

到此這篇關於Python經緯度座標轉換為距離及角度的實現的文章就介紹到這了,更多相關Python經緯度座標轉換為距離及角度內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!