I'm trying to convert GPS coordinates into Cartesian so I can use them in a Unity application. I'm using the below function to do so, but it seems the values I'm using are not quite placed at the right location. My guess is that there's an issue due to the shape of the Earth. I've also included a picture of my data, which should resemble a flat loop, but instead is at an incline. Visualization
Vector3 WGS84ToCartesian(float lat, float lon, float h){
float earthRadius = 6378137.0f;
float cosLat = Mathf.Cos(lat * Mathf.PI / 180.0f);
float sinLat = Mathf.Sin(lat * Mathf.PI / 180.0f);
float cosLon = Mathf.Cos(lon * Mathf.PI / 180.0f);
float sinLon = Mathf.Sin(lon * Mathf.PI / 180.0f);
float f = 1.0f / 298.257224f;
float C = 1.0f / Mathf.Sqrt(cosLat * cosLat + (1 - f) * (1 - f) * sinLat * sinLat);
float S = (1.0f - f) * (1.0f - f) * C;
float x = (earthRadius * C + h) * cosLat * cosLon;
float y = (earthRadius * C + h) * cosLat * sinLon;
float z = (earthRadius * S + h) * sinLat;
return new Vector3(x, y, z);
}
Your solution assumes that the earth is a sphere. It's not. According to Wikipedia, the polar diameter is about 3,950, while the equatorial diameter is more like 3,963 mi, about a 13 mile difference, about $0.3\%$. That's probably enough to mess up your computations.
(It's certainly enough to mess up a pendulum clock --- apparently a friend of Newton's moved from Paris to Cayenne, and found that his nicely calibrated clock now ran slower than it should, from which Newton determined that the earth must not be round, and even came up with a good estimate of its eccentricity. The details (which I've surely muddled up a bit) are in Spivak's "Physics for Mathematicians", should you be interested.