Skip to content

Instantly share code, notes, and snippets.

@mariomartinezsz
Last active June 16, 2017 18:27
Show Gist options
  • Save mariomartinezsz/e6be35e1b54b900881aa69f19912397b to your computer and use it in GitHub Desktop.
Save mariomartinezsz/e6be35e1b54b900881aa69f19912397b to your computer and use it in GitHub Desktop.
Calculate distance between Latitude/Longitude points. This uses the 'haversine' formula to calculate the great-circle distance between two points.
// Calculate distance between Latitude/Longitude points
// This uses the ‘haversine’ formula to calculate the great-circle distance between two points.
// Sources:
// http://www.movable-type.co.uk/scripts/latlong.html
// https://stackoverflow.com/questions/27928/calculate-distance-between-two-latitude-longitude-points-haversine-formula
// Distance in km
function deg2rad(deg): number {
return deg * (Math.PI/180);
}
function getDistanceInKm( lat1: number, lon1: number, lat2: number, lon2: number ) : number {
let R: number = 6371; // Earth's radius (km)
let dLat: number = deg2rad(lat2 - lat1);
let dLon: number = deg2rad(lon2 - lon1);
let a: number = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
let c: number = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
let d: number = R * c; // Distance in km
return d;
}
// Testing: distance between Mexico city and Queretaro
document.body.innerHTML = String(getDistanceInKm(19.4326077, -99.13320799999997, 20.5888184, -100.38988760000001));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment