| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
""" |
| 20 |
Utility functions to convert between coordinate systems and calculate distances. |
| 21 |
""" |
| 22 |
|
| 23 |
import math |
| 24 |
from .constants import DTOR, RTOD |
| 25 |
|
| 26 |
|
| 27 |
WGS84_A = 6378137.0 |
| 28 |
WGS84_F = 1.0/298.257223563 |
| 29 |
WGS84_B = WGS84_A * (1 - WGS84_F) |
| 30 |
WGS84_ECC_SQ = 1 - WGS84_B * WGS84_B / (WGS84_A * WGS84_A) |
| 31 |
WGS84_ECC = math.sqrt(WGS84_ECC_SQ) |
| 32 |
|
| 33 |
|
| 34 |
SPHERICAL_R = 6371e3 |
| 35 |
|
| 36 |
|
| 37 |
_wgs84_ep = math.sqrt((WGS84_A**2 - WGS84_B**2) / WGS84_B**2) |
| 38 |
_wgs84_ep2_b = _wgs84_ep**2 * WGS84_B |
| 39 |
_wgs84_e2_a = WGS84_ECC_SQ * WGS84_A |
| 40 |
|
| 41 |
|
| 42 |
def llh2ecef(llh): |
| 43 |
"""Converts from WGS84 lat/lon/height to ellipsoid-earth ECEF""" |
| 44 |
|
| 45 |
lat = llh[0] * DTOR |
| 46 |
lng = llh[1] * DTOR |
| 47 |
alt = llh[2] |
| 48 |
|
| 49 |
slat = math.sin(lat) |
| 50 |
slng = math.sin(lng) |
| 51 |
clat = math.cos(lat) |
| 52 |
clng = math.cos(lng) |
| 53 |
|
| 54 |
d = math.sqrt(1 - (slat * slat * WGS84_ECC_SQ)) |
| 55 |
rn = WGS84_A / d |
| 56 |
|
| 57 |
x = (rn + alt) * clat * clng |
| 58 |
y = (rn + alt) * clat * slng |
| 59 |
z = (rn * (1 - WGS84_ECC_SQ) + alt) * slat |
| 60 |
|
| 61 |
return (x, y, z) |
| 62 |
|
| 63 |
|
| 64 |
def ecef2llh(ecef): |
| 65 |
"Converts from ECEF to WGS84 lat/lon/height" |
| 66 |
|
| 67 |
x, y, z = ecef |
| 68 |
|
| 69 |
lon = math.atan2(y, x) |
| 70 |
|
| 71 |
p = math.sqrt(x**2 + y**2) |
| 72 |
th = math.atan2(WGS84_A * z, WGS84_B * p) |
| 73 |
lat = math.atan2(z + _wgs84_ep2_b * math.sin(th)**3, |
| 74 |
p - _wgs84_e2_a * math.cos(th)**3) |
| 75 |
|
| 76 |
N = WGS84_A / math.sqrt(1 - WGS84_ECC_SQ * math.sin(lat)**2) |
| 77 |
alt = p / math.cos(lat) - N |
| 78 |
|
| 79 |
return (lat*RTOD, lon*RTOD, alt) |
| 80 |
|
| 81 |
|
| 82 |
def greatcircle(p0, p1): |
| 83 |
"""Returns a great-circle distance in metres between two LLH points, |
| 84 |
_assuming spherical earth_ and _ignoring altitude_. Don't use this if you |
| 85 |
need a distance accurate to better than 1%.""" |
| 86 |
|
| 87 |
lat0 = p0[0] * DTOR |
| 88 |
lon0 = p0[1] * DTOR |
| 89 |
lat1 = p1[0] * DTOR |
| 90 |
lon1 = p1[1] * DTOR |
| 91 |
return SPHERICAL_R * math.acos( |
| 92 |
math.sin(lat0) * math.sin(lat1) + |
| 93 |
math.cos(lat0) * math.cos(lat1) * math.cos(abs(lon0 - lon1))) |
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
def ecef_distance(p0, p1): |
| 99 |
"""Returns the straight-line distance in metres between two ECEF points.""" |
| 100 |
return math.sqrt((p0[0] - p1[0])**2 + (p0[1] - p1[1])**2 + (p0[2] - p1[2])**2) |