Calculating the distance between 2 points in c#

后端 未结 4 1789
借酒劲吻你
借酒劲吻你 2020-12-18 04:41

I am trying to sort out a method to calculate the distance between 2 points in c#.

This is the code I have been trying though I fear the answer I get is not correct.

4条回答
  •  长情又很酷
    2020-12-18 05:10

    double lat1 = {};
    double lat2 = {};
    double lon1 = {};
    double lon2 = {};
    
    var R = 6376.5000; //Km
    lat1 = lat1.ToRad();
    lat2 = lat2.ToRad();
    lon1 = lon1.ToRad();
    lon2 = lon2.ToRad();
    var dLat = lat2 - lat1;
    var dLon = lon2 - lon1;
    var a = Math.Pow(Math.Sin(dLat / 2), 2) + (Math.Pow(Math.Sin(dLon / 2), 2) * Math.Cos(lat1) * Math.Cos(lat2));
    var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
    var distance = R * c;
    
    public double ToRad(this double degs) {
        return degs * (Math.PI/180.0);
    }
    

    Input expects doubles.

    This is the haversine formula, it's used to calculate the distances on our globe between two points. This is the distance in a straight line, if you need the distance on a path you will have to find all points on that path and then calculate the distances between each two points and then take the sum of that.

提交回复
热议问题