How to calculate the distance between two latitude-longitude points in C++

1 Answer

0 votes
#include <iostream>
#include <cmath>

// ------------------------------------------------------------
// Convert degrees to radians
// ------------------------------------------------------------
double degToRad(double deg) {
    return deg * M_PI / 180.0;
}

// ------------------------------------------------------------
// Compute the great-circle distance between two points on Earth
// using the Haversine formula.
// lat1, lon1, lat2, lon2 are in degrees.
// The result is returned in kilometers.
// ------------------------------------------------------------
double haversine(double lat1, double lon1, double lat2, double lon2) {
    // Earth's mean radius in kilometers
    constexpr double R = 6371.0;

    // Convert all angles to radians
    double rlat1 = degToRad(lat1);
    double rlon1 = degToRad(lon1);
    double rlat2 = degToRad(lat2);
    double rlon2 = degToRad(lon2);

    // Differences
    double dlat = rlat2 - rlat1;
    double dlon = rlon2 - rlon1;

    // Haversine formula
    // a is the Haversine of the central angle between the two points.
    
    // It combines the differences in latitude and longitude, adjusted by 
    // cosine terms to account for Earth’s curvature.
    double a = std::sin(dlat / 2) * std::sin(dlat / 2) +
               std::cos(rlat1) * std::cos(rlat2) *
               std::sin(dlon / 2) * std::sin(dlon / 2);

    // c is the central angle between the two points on the Earth’s surface.
    // This angle is measured in radians.
    // It tells you how large the arc is between the two points on the globe.
    double c = 2 * std::asin(std::sqrt(a));

    // Final distance
    return R * c;
}

int main() {
    // Example coordinates:
    // Austin, Texas
    double lat1 = 30.2672;
    double lon1 = -97.7431;

    // Houston, Texas
    double lat2 = 29.7604;
    double lon2 = -95.3698;

    double distanceKm = haversine(lat1, lon1, lat2, lon2);

    // Convert kilometers to miles
    double distanceMiles = distanceKm * 0.621371;

    std::cout << "Distance: " << distanceKm << " km\n";
    std::cout << "Distance: " << distanceMiles << " miles\n";
}


/*
run:

Distance: 235.352 km
Distance: 146.241 miles

*/

 



answered Aug 6 by avibootz
edited Aug 7 by avibootz

Related questions

...