Calculate distance between 2 GPS coordinates

前端 未结 29 3487
青春惊慌失措
青春惊慌失措 2020-11-21 23:34

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

29条回答
  •  被撕碎了的回忆
    2020-11-22 00:14

    Look for haversine with Google; here is my solution:

    #include 
    #include "haversine.h"
    
    #define d2r (M_PI / 180.0)
    
    //calculate haversine distance for linear distance
    double haversine_km(double lat1, double long1, double lat2, double long2)
    {
        double dlong = (long2 - long1) * d2r;
        double dlat = (lat2 - lat1) * d2r;
        double a = pow(sin(dlat/2.0), 2) + cos(lat1*d2r) * cos(lat2*d2r) * pow(sin(dlong/2.0), 2);
        double c = 2 * atan2(sqrt(a), sqrt(1-a));
        double d = 6367 * c;
    
        return d;
    }
    
    double haversine_mi(double lat1, double long1, double lat2, double long2)
    {
        double dlong = (long2 - long1) * d2r;
        double dlat = (lat2 - lat1) * d2r;
        double a = pow(sin(dlat/2.0), 2) + cos(lat1*d2r) * cos(lat2*d2r) * pow(sin(dlong/2.0), 2);
        double c = 2 * atan2(sqrt(a), sqrt(1-a));
        double d = 3956 * c; 
    
        return d;
    }
    

提交回复
热议问题