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

var phi   = (90-lat)*(Math.PI/180);
var theta = (lng+180)*(Math.PI/180);

marker_mesh.position.x = ((rad) * Math.sin(phi)*Math.cos(theta));
marker_mesh.position.z = ((rad) * Math.sin(phi)*Math.sin(theta));
marker_mesh.position.y = ((rad) * Math.cos(phi));

given the above my marker is not translating into the correct position on a 3D sphere ... thoughts?

It is relatively close (on the same continent) but that close :\

given below ... it should be rendering in at

lat: 41.7307619 long: -71.276195

my globe has a boundRadius: 500px

the current result of the function is

x: -119.7801015013779

y: 332.8157297895266

z: 353.3927238766871

enter image description here

Answers:

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.