3
votes

I know there are other questions similar to this one, but most of them deal with only converting one to the other. But I am searching for a algorithms that convert to and from each other. Simply using one of each has not produced the desired results.

For my purposes a unit sphere is more then acceptable. Any radius value would be 1.

Here are my current methods for performing this, in simple psudocode.

From latitude and longitude to a point on a unit sphere.

x = cos( longitude ) * sin( latitude )
y = sin( longitude ) * sin( latitude )
z = cos( latitude )

From 3D coordinates on a unit sphere to latitude and longitude.

latitude = acos( z )
longitude = atan2( x, y )

However these are not reversible and my trigonometry is not what it should be.

1
Many computer languages have an atan2(y, x) function, which may be what you need.Andrew Morton
Yes, but that doesn't solve the inherent reversibility problem.Chase
What is the reversibility problem you are seeing? Atan2 returns an angle in the correct quadrant, whereas atan won't necessarily do that.Andrew Morton
What do you mean that these are not reversible? You just reversed the conversion from xyz to lat/long yourself in the question. The only detail is the fact that atan won't return the angle in the correct quadrant, which is what atan2 is for.SirGuy
Edited the algorithm, but the problem remains. Try it with a latitude of 0 and a longitude of say 1 (which is about 57 degrees). The first produces 0,0,1, and feeding 0,0,1 into the second produces 0,0. Not reversible.Chase

1 Answers

2
votes

Converting from lat/long to xyz is always possible, but going from xyz to lat/long fails when sin(lat) == 0. There is no solution to this in lat/long space so just stay away from it.
Other than that your formula just has a small error where atan2 takes y then x instead of x then y.