Gearflow Blog

TIL: Haversine Calculations

Written by Christian Koch | Nov 26, 2025 2:52:03 PM

Today I Learned (TIL)

Haversine Formula

"The haversine formula determines the great-circle distance between two points on a sphere given their longitudes and latitudes. Important in navigation, it is a special case of a more general formula in spherical trigonometry, the law of haversines, that relates the sides and angles of spherical triangles. "

https://en.wikipedia.org/wiki/Haversine_formula

https://resources.wolframcloud.com/FormulaRepository/resources/Law-of-Haversines

I was working on geolocating a user in order to find the closest point. I have previously used PostGIS to handle this distance calculation but for this use case, I wanted to calculate it on the client. 

My colleague, Claude, and I did a bit of searching and quickly landed on this special case of spherical geometry and implemented a haversine calculation. 

For the curious the implementation looked like this:

// Calculate distance using Haversine formula
const getDistance = (lat: number, lng: number) => {
  const R = 6371 // Earth's radius in km
  const dLat = ((lat - locLat) * Math.PI) / 180
  const dLng = ((lng - locLng) * Math.PI) / 180
  const a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
      Math.cos((locLat * Math.PI) / 180) *
      Math.cos((lat * Math.PI) / 180) *
      Math.sin(dLng / 2) * Math.sin(dLng / 2)
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
  return R * c
}