GPS Distance Calculation

During a recent project I needed to calculate the distance between two GPS coordinates. After a little research I found tons of people that have done this before and most(well the correct ones) are baseed on the Haversine formula. I wanted to share my implementation just to help people get to the answer quickly with-out having to analyze the trig.

A little helper I will be calling.

var toRad = function(deg) {
    return deg * Math.PI / 180;
}

The meat of the work…

var earthRadiusMiles = 3963; // earths radius in Miles var lat1 = coord1.lat; // get lat of coord1 in deg var lon1 = coord1.lon; // get lon of coord1 in deg var lat2 = coord2.lat; // get lat of coord2 in deg var lon2 = coord2.lon; // get lon of coord2 in deg var latRad1 = toRad(lat1); // convert to rad var lonRad1 = toRad(lon1); var latRad2 = toRad(lat2); var lonRad2 = toRad(lon2); var distance = 0; // this will hold our final distance distance = Math.sin(latRad1) * Math.sin(latRad2) + Math.cos(latRad1) * Math.cos(latRad2) * Math.cos(lonRad2 - lonRad1); distance = earthRadiusMiles * (-1 * Math.atan(distance / Math.sqrt(1 - distance * distance))+ Math.PI / 2); // distance now holds the distance in miles along the earths surface between the 2 given points // if you wish to have the distance in km you can multiply distance by 1.609.