Skip to content

Instantly share code, notes, and snippets.

@igorjs
Last active August 12, 2025 15:41
Show Gist options
  • Save igorjs/54b36e50259222e7bfac1db70f163b21 to your computer and use it in GitHub Desktop.
Save igorjs/54b36e50259222e7bfac1db70f163b21 to your computer and use it in GitHub Desktop.
/**
* Calculate the distance between two points on Earth using the Haversine formula
* @param Point1 { lat: number; lng: number } - The first point
* @param Point2 { lat: number; lng: number } - The second point
* @returns Distance in metres
*/
function calcDistanceInMetresBetweenTwoPoints(Point1, Point2) {
const EARTH_RADIUS_METERS = 6371000; // Earth's radius in meters
// Convert degrees to radians
const lat1Rad = Point1.lat * (Math.PI / 180);
const lng1Rad = Point1.lng * (Math.PI / 180);
const lat2Rad = Point2.lat * (Math.PI / 180);
const lng2Rad = Point2.lng * (Math.PI / 180);
// Calculate differences
const deltaLatitude = lat2Rad - lat1Rad;
const deltaLongitude = lng2Rad - lng1Rad;
// Haversine formula
const angle = Math.sin(deltaLatitude / 2) ** 2 +
Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.sin(deltaLongitude / 2) ** 2;
const theta = 2 * Math.atan2(Math.sqrt(angle), Math.sqrt(1 - angle));
const distance = EARTH_RADIUS_METERS * theta;
// Return distance in metres
return distance;
}
// Test
const PointA = { lat: -33.84887785692942, lon: 151.2106926524797 };
const PointB = { lat: -33.85469551244261, lon: 151.22570778047384 };
const result = calcDistanceInMetresBetweenTwoPoints(PointA, PointB);
console.log(result); // 1530.0543614899987 metres
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment