Search code examples
pythonmappingsatellite

Converting XYZ coordinates to longitutde/latitude in Python


I've got some XYZ coordinates in Kilometers (gotten using wgs) with the origin at the center of the Earth, is it possible to convert this into latitude and longitude?

In addition: how can I do this quickly inside python?

It's simply a reverse of this question here: Converting from longitude\latitude to Cartesian coordinates


Solution

  • This is how you do it. Taking into account both radiuses. Based on: https://gist.github.com/govert/1b373696c9a27ff4c72a and verifyed.

    import math
    
    x = float(4333216) #in meters
    y = float(3193635) #in meters
    z = float(3375365) #in meters
    
    a = 6378137.0 #in meters
    b = 6356752.314245 #in meters
    
    f = (a - b) / a
    f_inv = 1.0 / f
    
    e_sq = f * (2 - f)                       
    eps = e_sq / (1.0 - e_sq)
    
    p = math.sqrt(x * x + y * y)
    q = math.atan2((z * a), (p * b))
    
    sin_q = math.sin(q)
    cos_q = math.cos(q)
    
    sin_q_3 = sin_q * sin_q * sin_q
    cos_q_3 = cos_q * cos_q * cos_q
    
    phi = math.atan2((z + eps * b * sin_q_3), (p - e_sq * a * cos_q_3))
    lam = math.atan2(y, x)
    
    v = a / math.sqrt(1.0 - e_sq * math.sin(phi) * math.sin(phi))
    h   = (p / math.cos(phi)) - v
    
    lat = math.degrees(phi)
    lon = math.degrees(lam)
    
    print(lat,lon,h)