计算2个坐标(经纬度)之间的距离,.Net

.Net 中计算2个点之间的距离的方法,或者叫计算2个坐标,2个经纬度之间的距离。

代码如下:

 1 /// <summary>
 2     /// Calculates the distance between two geographics locations
 3     /// </summary>
 4     public static class GeoDistance
 5     {
 6         public static double Between(double latitude1, double longitude1, double latitude2, double longitude2,
 7             DistanceUnits units = DistanceUnits.Kilometers)
 8         {
 9             double a1 = latitude1 * RadianConversionFactor;
10             double b1 = longitude1 * RadianConversionFactor;
11             double a2 = latitude2 * RadianConversionFactor;
12             double b2 = longitude2 * RadianConversionFactor;
13 
14             double distance =
15                 Math.Acos(Math.Cos(a1) * Math.Cos(b1) * Math.Cos(a2) * Math.Cos(b2) +
16                     Math.Cos(a1) * Math.Sin(b1) * Math.Cos(a2) * Math.Sin(b2) + Math.Sin(a1) * Math.Sin(a2)) * DistanceConstants[units];
17 
18             return distance;
19         }
20 
21         private const double RadianConversionFactor = Math.PI / 180;
22 
23         private static readonly Dictionary<DistanceUnits, double> DistanceConstants = new Dictionary<DistanceUnits, double>(3) {
24             { DistanceUnits.Miles, 3963.1 },
25             { DistanceUnits.NauticalMiles, 3443.9 },
26             { DistanceUnits.Kilometers, 6378 }
27         };
28     }
29 
30     public enum DistanceUnits
31     {
32         Miles,
33         NauticalMiles,
34         Kilometers,
35     }

代码很简单,但是费了不少劲。就是还没测试效率怎么样。如果有高效的算法,请不要吝啬指教!!!

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。