components/InteractiveGlobe/searchReveal.jsjavascript
// Geometry helpers for InteractiveGlobe's search reveal: after a search, if
// none of the matching markers is in view, the globe turns to the nearest
// one. Kept free of react-globe.gl so they only deal with plain
// {lat, lng[, altitude]} objects.
const toRad = (deg) => (deg * Math.PI) / 180;
// share of the visible cap's angular radius a marker has to be inside of to
// count as "in view" - a marker right at the horizon is technically on the
// near side but squashed flat against the globe's silhouette, so it
// shouldn't stop the reveal rotation
const HORIZON_MARGIN = 0.9;
/**
* Great-circle angle between two coordinates, in radians.
*
* @param {{lat: number, lng: number}} a
* @param {{lat: number, lng: number}} b
* @returns {number}
*/
export const angularDistance = (a, b) => {
const cos =
Math.sin(toRad(a.lat)) * Math.sin(toRad(b.lat)) +
Math.cos(toRad(a.lat)) * Math.cos(toRad(b.lat)) * Math.cos(toRad(a.lng - b.lng));
// clamped: floating point error can push identical points slightly past 1
return Math.acos(Math.min(1, Math.max(-1, cos)));
};
/**
* Whether `location` lies on the camera-facing side of the globe, i.e.
* inside the cap a camera at `pov` can see (its horizon sits at
* acos(1 / (1 + altitude)) from the point straight below it).
*
* @param {{lat: number, lng: number, altitude: number}} pov - Camera point of view, as
* returned by react-globe.gl's pointOfView().
* @param {{lat: number, lng: number}} location
* @returns {boolean}
*/
export const isOnVisibleSide = (pov, location) => {
const horizon = Math.acos(1 / (1 + pov.altitude));
return angularDistance(pov, location) < horizon * HORIZON_MARGIN;
};
/**
* The location closest to the point straight below the camera - the
* shortest rotation needed to bring one of them into view.
*
* @template {{lat: number, lng: number}} T
* @param {{lat: number, lng: number}} pov
* @param {T[]} locations - Must not be empty.
* @returns {T}
*/
export const nearestLocation = (pov, locations) =>
locations.reduce((nearest, location) =>
angularDistance(pov, location) < angularDistance(pov, nearest) ? location : nearest
);