Versor
Rotate the globe with the mouse.
The naïve method uses mouse.x
and mouse.y
as proxies for longitude and latitude. It works when the rotation is small, but try to put the globe "upside-down" and suddenly moving the mouse to the left rotates the globe to the right, and vice versa.
The correct solution is to track the spherical coordinates of the point that is under the mouse, and apply a rotation to the globe that will move the initial point to the current mouse position. Computing that rotation involves quaternions.
This method, introduced by Jason Davies and Mike Bostock, is called versor dragging.
This module contains the quaternion & versor functions. For a directly usable package, see d3-inertia.
In Node:
const versor = require("versor");
versor.interpolate(rotation0, rotation1);
const p0 = [0, 0],
p1 = [90, 0],
c0 = versor.cartesian(p0),
c1 = versor.cartesian(p1);
versor.delta(c0, c1);
versor.delta(c0, c1, 0.5);
versor.cartesian = function(e) {
var l = e[0] * radians, p = e[1] * radians, cp = cos(p);
return [cp * cos(l), cp * sin(l), sin(p)];
};
const q0 = versor([90,0,0]);
const q1 = versor([0,90,0]);
q01 = versor.multiply(q0, q1);
versor.rotation(q01);
In a browser:
<!DOCTYPE html>
<script src="https://unpkg.com/versor"></script>
<script>
versor([90,0,0]);
</script>