Robun
Robun

Reputation: 61

how to convert latitude/longitude to pixels in 3d using three.js

I have lat/lon of a portion of a map. I want to put the point of this lat/lon in 3d space webgl(lib: three.js). Then how to convert lat/lon to corresponding x,y,z cords.

Upvotes: 2

Views: 3315

Answers (3)

som
som

Reputation: 2437

Spent a bit of time searching for the best "three.js way" to solve this. Figured I'd include it here for posterity's sake. Following assumes Y is up:

const latLngToVector3 = (latLng, radius) => {
  const phi = Math.PI * (0.5 - (latLng.lat / 180));
  const theta = Math.PI * (latLng.lng / 180);
  const spherical = THREE.Spherical(radius || latLng.radius || 1, phi, theta);
  return new THREE.Vector3().setFromSpherical(spherical);
};

const vector3ToLatLng = (v3) => {
  const spherical = new THREE.Spherical().setFromVector3(v3);
  return {
    lat: 180 * (0.5 - (spherical.phi / Math.PI)),
    lng: 180 * (spherical.theta / Math.PI),
  };
};

// convert to x,y,z with radius = 1
const v3 = latLngToVector3({ lat: -16.8985, lng: 145.7134 });

// convert back to lat/lng
const latLng = vector3ToLatLng(v3);

Check out the Spherical.setFromvector3 and Vector3.setFromSpherical methods to see the inner workings here.

Upvotes: 1

mimipaskova
mimipaskova

Reputation: 64

When you create a new point with pixels, it converts to lat an lng.

var offsetX = 10;
var offsetY = 10;
var mapZoom = 5;
var point = new google.maps.Point(
     offsetX / Math.pow(2, mapZoom),
     offsetY / Math.pow(2, mapZoom)
);

And after this you can just sum point.x and point.y with another point.

Upvotes: 0

Alexander Myshov
Alexander Myshov

Reputation: 3101

Because latitude and longitude are pieces of 2D-representation, you need to choose which plane will be used for the projection. The most simple one will be: X - longitude, and Y - latitude. Second do scaling if you need some precise location. But it is the most simple case as I've already said. In general the map projection is a lot more complex. See for example the answers here lat/lon conversion to x/y-coordinates. Hope it will help you.

Upvotes: 1

Related Questions