#JavaScript #Snippets April 07, 2023

JavaScript: Haversine Formula

Here's the formula for calculating the distance between one location to another. I may use this someday for an airport game I've always wanted to build.

function getDistance(lat1, lon1, lat2, lon2) {
  const R = 6371e3; // radius of Earth in meters
  const φ1 = toRadians(lat1);
  const φ2 = toRadians(lat2);
  const Δφ = toRadians(lat2 - lat1);
  const Δλ = toRadians(lon2 - lon1);

  const a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
            Math.cos(φ1) * Math.cos(φ2) *
            Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

  return (R * c) / 1000;
}

function toRadians(degrees) {
  return degrees * Math.PI / 180;
}

const london = { name: "London", lat: 51.5074, lon: -0.1278 };
const newYork = { name: "New York", lat: 40.7128, lon: -74.0060 };
const tokyo = { name: "Tokyo", lat: 35.6895, lon: 139.6917 };

const londonToNewYork = getDistance(london.lat, london.lon, newYork.lat, newYork.lon);
const newYorkToTokyo = getDistance(newYork.lat, newYork.lon, tokyo.lat, tokyo.lon);
const londonToTokyo = getDistance(london.lat, london.lon, tokyo.lat, tokyo.lon);

console.log(`Distance from ${london.name} to ${newYork.name}: ${londonToNewYork.toFixed(2)} kilometers`);
console.log(`Distance from ${newYork.name} to ${tokyo.name}: ${newYorkToTokyo.toFixed(2)} kilometers`);
console.log(`Distance from ${london.name} to ${tokyo.name}: ${londonToTokyo.toFixed(2)} kilometers`);

SEARCH