Calculate distance of two geo points in km c#

前端 未结 7 719
夕颜
夕颜 2020-12-03 00:21

I`d like calculate the distance of two geo points. the points are given in longitude and latitude.

the coordinates are:

point 1: 36.578581, -118.291994

7条回答
  •  清歌不尽
    2020-12-03 00:30

    Your formula is almost correct, but you have to swap parameters for longitude an latitude

    Console.WriteLine(DistanceAlgorithm.DistanceBetweenPlaces(-118.291994, 36.578581, -116.83171, 36.23998)); // = 136 km
    

    I'm using simplified formula:

    // cos(d) = sin(φА)·sin(φB) + cos(φА)·cos(φB)·cos(λА − λB),
    //  where φА, φB are latitudes and λА, λB are longitudes
    // Distance = d * R
    public static double DistanceBetweenPlaces(double lon1, double lat1, double lon2, double lat2)
    {
        double R = 6371; // km
    
        double sLat1 = Math.Sin(Radians(lat1));
        double sLat2 = Math.Sin(Radians(lat2));
        double cLat1 = Math.Cos(Radians(lat1));
        double cLat2 = Math.Cos(Radians(lat2));
        double cLon = Math.Cos(Radians(lon1) - Radians(lon2));
    
        double cosD = sLat1*sLat2 + cLat1*cLat2*cLon;
    
        double d = Math.Acos(cosD);
    
        double dist = R * d;
    
        return dist;
    }
    

    Testing:

    (Distance at Equator): Longitudes 0, 100; Latitudes = 0,0; DistanceBetweenPlaces(0, 0, 100, 0) = 11119.5 km

    (Distance at North Pole): Longitudes 0, 100; Latitudes = 90,90; DistanceBetweenPlaces(0, 90, 100, 90) = 0 km

    Longitudes: -118.291994, -116.83171; Latitudes: 36.578581, 36.23998 = 135.6 km

    Longitudes: 36.578581, 36.23998; Latitudes: -118.291994, -116.83171 = 163.2 km

    Best regards

    P.S. At web site you use for result comparison, for every point first text box is latitude, second - longitude

提交回复
热议问题