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:
And here is the output for the North Pole, lat:90, lon:135:
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;
}
void createLand()
{
ObjectMarker.position = radiusEarth * Vector3.right;
}
void createLand()
{
ObjectMarker.position = radiusEarth * Vector3.up;
}
You are using the wrong axes for your conversion to 3d space.
sin(latitude)
. z = 1*radiusEarth
, so z needs to be the one with cos*cos. 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With