Lat Long to X Y Z position in JS .. not working

Your formula differs slightly from the geodetic to ECEF calculation. Refer to the formulas on Dr Math Latitude and Longitude, GPS Conversion and Wikipedia Geodetic to/from ECEF coordinates. This projects the latitude, longitude to a flattened sphere (i.e. the real Earth is not perfectly spherical).

var cosLat = Math.cos(lat * Math.PI / 180.0);
var sinLat = Math.sin(lat * Math.PI / 180.0);
var cosLon = Math.cos(lon * Math.PI / 180.0);
var sinLon = Math.sin(lon * Math.PI / 180.0);
var rad = 6378137.0;
var f = 1.0 / 298.257224;
var C = 1.0 / Math.sqrt(cosLat * cosLat + (1 - f) * (1 - f) * sinLat * sinLat);
var S = (1.0 - f) * (1.0 - f) * C;
var h = 0.0;
marker_mesh.position.x = (rad * C + h) * cosLat * cosLon;
marker_mesh.position.y = (rad * C + h) * cosLat * sinLon;
marker_mesh.position.z = (rad * S + h) * sinLat;

In your scenario, because it seems you’re gunning for a perfect sphere, you will need to put f = 0.0 and rad = 500.0 instead. This will cause C and S to become 1.0, so, the simplified version of the formula reduces to:

var cosLat = Math.cos(lat * Math.PI / 180.0);
var sinLat = Math.sin(lat * Math.PI / 180.0);
var cosLon = Math.cos(lon * Math.PI / 180.0);
var sinLon = Math.sin(lon * Math.PI / 180.0);
var rad = 500.0;
marker_mesh.position.x = rad * cosLat * cosLon;
marker_mesh.position.y = rad * cosLat * sinLon;
marker_mesh.position.z = rad * sinLat;

N.B. I have not validated the syntax of the Java code examples.

Leave a Comment