Calculating the distance between 2 latitudes and longitudes that are saved in a text file?

前端 未结 4 602
悲哀的现实
悲哀的现实 2020-12-16 04:10

I\'ve looked around and still couldn\'t find anything to help me really! I\'ve written a program to calculate the distance between 2 cities using their Latitudes and Longitu

4条回答
  •  甜味超标
    2020-12-16 04:48

    As it is said, Haversine formula is your answer:

    #include 
    #include  
    #define earthRadiusKm 6371.0
    
    // This function converts decimal degrees to radians
    double deg2rad(double deg) {
      return (deg * M_PI / 180);
    }
    
    //  This function converts radians to decimal degrees
    double rad2deg(double rad) {
      return (rad * 180 / M_PI);
    }
    
    /**
     * Returns the distance between two points on the Earth.
     * Direct translation from http://en.wikipedia.org/wiki/Haversine_formula
     * @param lat1d Latitude of the first point in degrees
     * @param lon1d Longitude of the first point in degrees
     * @param lat2d Latitude of the second point in degrees
     * @param lon2d Longitude of the second point in degrees
     * @return The distance between the two points in kilometers
     */
    double distanceEarth(double lat1d, double lon1d, double lat2d, double lon2d) {
      double lat1r, lon1r, lat2r, lon2r, u, v;
      lat1r = deg2rad(lat1d);
      lon1r = deg2rad(lon1d);
      lat2r = deg2rad(lat2d);
      lon2r = deg2rad(lon2d);
      u = sin((lat2r - lat1r)/2);
      v = sin((lon2r - lon1r)/2);
      return 2.0 * earthRadiusKm * asin(sqrt(u * u + cos(lat1r) * cos(lat2r) * v * v));
    }
    

提交回复
热议问题