Search code examples
mathgeolocationgeometrylatitude-longitudegeography

Calculate distance between 2 GPS coordinates


How do I calculate distance between two GPS coordinates (using latitude and longitude)?


Solution

  • Calculate the distance between two coordinates by latitude and longitude, including a Javascript implementation.

    West and South locations are negative. Remember minutes and seconds are out of 60 so S31 30' is -31.50 degrees.

    Don't forget to convert degrees to radians. Many languages have this function. Or its a simple calculation: radians = degrees * PI / 180.

    function degreesToRadians(degrees) {
      return degrees * Math.PI / 180;
    }
    
    function distanceInKmBetweenEarthCoordinates(lat1, lon1, lat2, lon2) {
      var earthRadiusKm = 6371;
    
      var dLat = degreesToRadians(lat2-lat1);
      var dLon = degreesToRadians(lon2-lon1);
    
      lat1 = degreesToRadians(lat1);
      lat2 = degreesToRadians(lat2);
    
      var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
              Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); 
      var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
      return earthRadiusKm * c;
    }
    

    Here are some examples of usage:

    distanceInKmBetweenEarthCoordinates(0,0,0,0)  // Distance between same 
                                                  // points should be 0
    0
    
    distanceInKmBetweenEarthCoordinates(51.5, 0, 38.8, -77.1) // From London
                                                              // to Arlington
    5918.185064088764