0

This is not a dupe of Converting from longitude\latitude to Cartesian coordinates.

I want to have functions that will translate back and forth between X, Y, Z coordinates and Latitude and Longitude. The things is the application already has this function to go from latitude/longitude to XYZ (this function is not changeable)...

export function getXYZ(lat, lng, radius) {
  radius = radius || 200;

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

  var x = radius * Math.sin(gamma) * Math.cos(theta);
  var y = radius * Math.cos(gamma);
  var z = radius * Math.sin(gamma) * Math.sin(theta);

  return {x: x, y: y, z: z};
}

I tried to create a paired function to go back the other way, but there's something not right.

export function getLatLng(vector, radius) {
  radius = radius || 200;

  var lat, latRads, lng, lngRads;

  latRads = Math.acos(vector.y / radius);
  lngRads = Math.atan2(vector.z, vector.x);

  lat = (Math.PI / 2 - latRads) * 180 / Math.PI;
  lng = (Math.PI - lngRads) * 180 / Math.PI;

  return [lat, lng];
}

Any ideas?

Community
  • 1
  • 1
delimited
  • 2,140
  • 1
  • 13
  • 11

2 Answers2

1

I'll just go ahead and answer my own question...

export function getLatLng(vector, radius) {
      radius = radius || 200;

      var latRads = Math.acos(vector.y / radius);
      var lngRads = Math.atan2(vector.z, vector.x);
      var lat = (Math.PI / 2 - latRads) * (180 / Math.PI);
      var lng = (Math.PI - lngRads) * (180 / Math.PI);

      return [lat, lng - 180];
    }

And the other way around...

 export function getXYZ(lat, lng, radius) {
      radius = radius || 200;

      var latRads = ( 90 - lat) * Math.PI / 180;
      var lngRads = (180 - lng) * Math.PI / 180;

      var x = radius * Math.sin(latRads) * Math.cos(lngRads);
      var y = radius * Math.cos(latRads);
      var z = radius * Math.sin(latRads) * Math.sin(lngRads);

      return {x: x, y: y, z: z};
    }
delimited
  • 2,140
  • 1
  • 13
  • 11
0

I can't post comment so i'll start an "answer" although its not one:

In the getXYZ the radius can be passed as a parameter, but in the inverse function radius cannot be a parameter: it must be length(vector). Try replace the "radius = radius || 200;" by var radius = length(vector)" and remove the radius argument (didnt test).

Xavier Gomez
  • 124
  • 4