计算c#中两点之间的距离

时间:2014-03-27 10:09:14

标签: c# google-maps latitude-longitude

我使用这个代码,它取两个不同位置的经度和纬度,并计算它们之间的距离 我的代码是

protected void Button1_Click(object sender, EventArgs e)
{
    double lat1= Convert.ToDouble(TextBox1.Text);
    double lon1= Convert.ToDouble(TextBox2.Text);
    double lat2= Convert.ToDouble(TextBox3.Text);
    double lon2= Convert.ToDouble(TextBox4.Text);

    var rlat1 = Math.PI * lat1/180;
    var rlat2 = Math.PI * lat2/180;
    var rlon1 = Math.PI * lon1/180;
    var rlon2 = Math.PI * lon2 / 180;
    var theta = lon1-lon2;
    var rtheta = Math.PI * theta/180;
    var dist = Math.Sign(rlat1) * Math.Sign(rlat2) + Math.Cos(rlat1) * Math.Cos(rlat2) * Math.Cos(rtheta);
    dist = Math.Acos(dist);
    dist = dist * 180/Math.PI;
    dist = dist * 60 * 1.1515;
    dist = dist * 1.609344 ;
    TextBox5.Text = dist.ToString("0.######");  
}

但是对于所有输入值,我得到的结果是NaN.please帮助我。

2 个答案:

答案 0 :(得分:10)

好的,因为我带着你之前的回答引导你走上花园小径,我移植了this给你一个有效的算法:

void Main()
{
    double lat1=12.916933d, 
           lon1=77.562658d,
           lat2=12.930140d,
           lon2=77.587732d;
    double dist = GetDistanceFromLatLonInKm(lat1, lon1, lat2, lon2);
    // dist == 3.08890370651166 yay!

}

double GetDistanceFromLatLonInKm(double lat1,
                                 double lon1,
                                 double lat2,
                                 double lon2) {
  var R = 6371d; // Radius of the earth in km
  var dLat = Deg2Rad(lat2 - lat1);  // deg2rad below
  var dLon = Deg2Rad(lon2 - lon1); 
  var a = 
    Math.Sin(dLat / 2d) * Math.Sin(dLat / 2d) +
    Math.Cos(Deg2Rad(lat1)) * Math.Cos(Deg2Rad(lat2)) * 
    Math.Sin(dLon / 2d) * Math.Sin(dLon / 2d); 
  var c = 2d * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1d - a)); 
  var d = R * c; // Distance in km
  return d;
}

double Deg2Rad(double deg) {
  return deg * (Math.PI / 180d);
}

当您提供固定值时,您的计算似乎正常工作:

var lat1 = 0d;
var lon1 = 52d;
var lat2 = 0d;
var lon2 = -52d;

这意味着这些转换失败了:

double lat1 = Convert.ToDouble(TextBox1.Text);
double lon1 = Convert.ToDouble(TextBox2.Text);
double lat2 = Convert.ToDouble(TextBox3.Text);
double lon2 = Convert.ToDouble(TextBox4.Text);

如果您仍遇到问题,请在这些行上放置一个断点,然后查看TextBox1.Text等的值。

要获得更可预测的浮点数解析,最好提供文化信息:

Convert.ToDouble("1.2", System.Globalization.CultureInfo.InvariantCulture)

<击>

答案 1 :(得分:2)

检查小数分隔符是否有效。它必须是逗号或点,具体取决于您的区域设置。