Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Latitude and Longitude to Vector3 Not Aligning on 3D Sphere

I am trying to convert latitude and longitude to a Vector3 format. For a given latitude and longitude, I want to convert it into a Vector3, where a marker object will be positioned at this Vector3 location.

Here is my code:

void createLand()
{
    double latitude_rad = (latitude) * Math.PI / 180;
    double longitude_rad = (longitude) * Math.PI / 180;

    double xPos = (radiusEarth * Math.Cos((latitude_rad)) * Math.Cos((longitude_rad)));
    double yPos = (radiusEarth * Math.Cos((latitude_rad)) * Math.Sin((longitude_rad)));
    double zPos = (radiusEarth * Math.Sin((latitude_rad)));

    markerPos.x = (float)xPos;
    markerPos.y = (float)yPos;
    markerPos.z = (float)zPos;

    ObjectMarker.position = markerPos;
}

I am using 6371 as radiusEarth, Here is the output for London lat:51.509865, lon:-0.118092:

Output for London Coordinates

And here is the output for the North Pole, lat:90, lon:135:

Output for North Pole Coordinates

The marker (which is the small shiny sphere) is in the wrong position.

Is there anything wrong with my conversion or is there any other way to fix this?

EDIT...

Earth texture that I have used can be found here, it is the 10K image. I built the sphere and applied the texture using Blender - I applied a rotation to the sphere so that the front view will reflect the position of lat,long: 0,0.

Code to create the Earth object:

void createEarth()
{
    ObjectEarth.gameObject.transform.localScale = 1f * radiusEarth * Vector3.one;
}

EDIT 2...

This is where the marker is placed when using Unity's predefined vectors:

void createLand()
{
    ObjectMarker.position = radiusEarth * Vector3.forward;
}

enter image description here

void createLand()
{
    ObjectMarker.position = radiusEarth * Vector3.right;
}

enter image description here

void createLand()
{
    ObjectMarker.position = radiusEarth * Vector3.up;
}

enter image description here

like image 838
SidS Avatar asked Sep 12 '25 10:09

SidS


1 Answers

You are using the wrong axes for your conversion to 3d space.

  • Y is the up/down axis, so that should definitely be the one that is sin(latitude).
  • 0,0 is at z = 1*radiusEarth, so z needs to be the one with cos*cos.
  • 0,90 is at x = -1 * radiusEarth, so x needs to be negative cos*sin.

Altogether:

void createLand()
{
    double latitude_rad = latitude * Math.PI / 180;
    double longitude_rad = longitude * Math.PI / 180;

    double zPos = radiusEarth * Math.Cos(latitude_rad) * Math.Cos(longitude_rad);
    double xPos = -radiusEarth * Math.Cos(latitude_rad) * Math.Sin(longitude_rad);
    double yPos = radiusEarth * Math.Sin(latitude_rad);

    markerPos.x = (float)xPos;
    markerPos.y = (float)yPos;
    markerPos.z = (float)zPos;

    ObjectMarker.position = markerPos;
}
like image 87
Ruzihm Avatar answered Sep 14 '25 01:09

Ruzihm