Calculating Distance in JavaScript

Henry Rossiter
2 min readMay 7, 2020

Recently I’ve gotten exposure to various mobile applications using location based contact tracing. These apps are used to calculate who you’ve been near based on recorded GPS data. In location-based contact tracing, one calculation is essential: the distance between two points.

How can we tell if two users crossed paths? One solution is to conduct a time-wise comparison of their locations. At each point in time, we can calculate the distance between two locations. Easy enough, right? Surprisingly, this simple calculation isn’t so simple.

Method 1: Pythagorean Identity

The equirectangular projection is likely the simplest map projection in existence. The projection maps meridians to equally spaced vertical straight lines. Similarly, it maps circles of latitude to equally spaced horizontal straight lines.

Equirectangular projection of Earth. Spacial deformation is visualized by orange circles. Clearly, this assumption is best used for coordinates near the equator.

The equirectangular projection simplifies our calculation by allowing us to use latitude and longitude coordinates as a cartesian grid system. As a result, we can simply use the Pythagorean Identity to calculate the distance between two points.

This method is best used when measuring short distances, measuring distances near the equator, or when computational efficiency is critically important.

Method 2: Law of Haversines

Despite the persistent movement to believe otherwise, we know the earth is curved. Methods 2 and 3 assume the Earth is spherical.

The Law of Haversines defines relations between the sides and angles of spherical triangles. The Haversine Formula is derived from the Law of Haversines and can be used to calculate distance. My JavaScript implementation is outlined below.

Method 3: Spherical Law of Cosines

Similar to the Law of Haversines, the Spherical Law of Cosines uses trigonometric identities. This method, however, provides slightly better accuracy than Method 2.

The spherical Law of Cosines states that cos(c)=cos(a)cos(b) + sin(a)sin(b)cos(C)

Since modern JavaScript uses 64-bit floating-point numbers with 15 significant figures of precision, the difference between Method 2 and Method 3 is often non-zero. Since the computational efficiencies are similar, this method is often preferred.

Method 4: Vincenty’s Formulae

Although the spherical approximation of the figure of Earth is satisfactory for many purposes, it’s technically not valid. The Earth is actually closer to an oblate spheroid. When extreme precision is required, Vincenty’s Formulae can be used to calculate geographical distances.

--

--