Skip to content

Instantly share code, notes, and snippets.

@ayamflow
Last active June 20, 2022 09:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayamflow/93e0979f09d25a723914c47818ffa151 to your computer and use it in GitHub Desktop.
Save ayamflow/93e0979f09d25a723914c47818ffa151 to your computer and use it in GitHub Desktop.
(WebGL) Longitude / Latitude to 3D to UV
// Check your coordinates space!
// Lat, Lon (SW) = -Lat, -Lon (NE)
// Lat, Lon (NW) = -Lat, Lon (NE)
// etc
var ray = new Ray()
/*
positionToUV
Converts a 3D world position to UV coordinates on a given sphere mesh
{pos} the 3D world position (on the surface of the mesh).
{mesh} the mesh to project onto
*/
function positionToUV(pos, mesh) {
ray.set(pos, pos.clone().negate())
let hits = ray.intersectObject(mesh)
if (hits.length) return hits[0].uv
}
/*
latLonToUV
Converts lat/lon coordinates into UV coordinates on the surface of a given sphere.
{lat} the latittude from the north
{long} the longitude, from the east
*/
function latLonToUV(lat, lon, mesh) {
return positionToUV(latLonToPosition(lat, lon), mesh)
}
/*
latLonToPosition
Converts a lat, lon (NE) to a 3D world position.
{radius} the globe radius in world units
*/
function latLonToPosition(lat, lng, radius = 1) {
let phi = (90 - lat) * Math.PI / 180
let theta = (180 - lng) * Math.PI / 180
let pos = new Vector3()
pos.x = radius * Math.sin(phi) * Math.cos(theta)
pos.y = radius * Math.cos(phi)
pos.z = radius * Math.sin(phi) * Math.sin(theta)
return pos
}
export const LatLon3D = {
positionToUV,
latLonToUV,
latLonToPosition
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment