Skip to main content
 首页 » 编程设计

c#之缩短这段确定 C# 中两个纬度/经度之间距离的代码

2024年02月24日28xing901022

public static double Distance(LatLong from, LatLong to) 
{ 
    double lat1 = from.Latitude * (Math.PI / 180.0); 
    double lat2 = to.Latitude * (Math.PI / 180.0); 
 
    return 
        Math.Acos((Math.Sin(lat1) * Math.Sin(lat2)) + 
        (Math.Cos(lat1) * Math.Cos(lat2) * 
        Math.Cos((Math.PI / 180.0) * (to.Longitude - from.Longitude)))) * 3958.760; 
} 

你能缩短这段代码吗?我只是想知道...

请您参考如下方法:

这是余弦公式的标准球面定律。没有比这更简单的了。充其量,您可以稍微清理一下代码:

public static double Distance(LatLong from, LatLong to) 
{ 
    double deg = Math.PI / 180.0;       // One degree in radians 
    double lat1 = from.Latitude * deg; 
    double lat2 = to.Latitude * deg; 
    double dLng = (to.Longitude - from.Longitude) * deg; 
    double R = 3958.760; 
 
    return Math.Acos(Math.Sin(lat1) * Math.Sin(lat2) + 
                     Math.Cos(lat1) * Math.Cos(lat2) * Math.Cos(dLng)) * R; 
}