Cartesian to Lat Long

313 Views Asked by At

I am trying to convert a Vector in Unity from its x y and z values to a latitude longitude position and my math seems to be a little off. I am placing an object on a sphere, and using that objects position to get the Vector3 that I pass into a function where I try to calculate the appropriate Latitude and Longitude. My math currently looks like this (Keep in mind in Unity the y is the up position).

public Vector2 VectorToLatLon(float x, float y, float z){
    Vector2 latLon = new Vector2();
    latLon.y = Mathf.Atan2 (x, z);
    var xzLen = new Vector2 (x, z).magnitude;
    latLon.x = Mathf.Atan2 (-y, xzLen);
    latLon *= Mathf.Rad2Deg;
    return latLon;
}

Basically how the function works is you pass it in a Vector3 in world space as x y and z coordinates, do the appropriate math, and hopefully return the new Latitude Longitude as a Vector2, where the Vector2 x is lat and the y is the long. I apologize for the block of code as I am a developer and not much of a mathematician, but this question seemed more suited for this exchange in comparison to a programming one. Does anyone know where I may be going wrong?

1

There are 1 best solutions below

0
On

hintto finish

Let $Lo= $ longitude and $La=latitude $

then

$$x=r\cos (La)\cos (Lo) $$ $$y=r\cos (La)\sin(Lo) $$ and $$z=r\sin (La) $$

thus

$$Lo=\arctan (\frac {y}{x}) $$