通过两个点的经纬度计算地面距离
1:原JAVA
double distanceByLnglat(double _Longitude1,
double _Latidute1,
double _Longitude2,
double _Latidute2)
{
double radLat1 = _Latidute1 * Math.PI / 180;
double radLat2 = _Latidute2 * Math.PI / 180;
double a = radLat1 - radLat2;
double b = _Longitude1 * Math.PI / 180 - _Longitude2 * Math.PI / 180;
double s = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / 2), 2) + Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(b / 2), 2)));
s = s * 6378137.0;// 取WGS84标准参考椭球中的地球长半径(单位:m)
s = Math.Round(s * 10000) / 10000;
return s;
}
2:原.Net
public struct EarthPoint
{
public const double Ea = 6378137; // 赤道半径 WGS84标准参考椭球中的地球长半径(单位:m)
public const double Eb = 6356725; // 极半径
public readonly double Longitude,Latidute;
public readonly double Jd;
public readonly double Wd;
public readonly double Ec;
public readonly double Ed;
public EarthPoint(double _Longitude,double _Latidute)
{
Longitude = _Longitude;
Latidute = _Latidute;
Jd = Longitude * Math.PI / 180; //转换成角度
Wd = Latidute * Math.PI /180; //转换成角度
Ec = Eb + (Ea - Eb) * (90 - Latidute) / 90;
Ed = Ec * Math.Cos(Wd);
}
public double Distance(EarthPoint _Point)
{
double dx = (_Point.Jd - Jd) * Ed;
double dy = (_Point.Wd - Wd) * Ec;
return Math.Sqrt(dx * dx + dy *dy);
}
}
public static Double GetDistance(double _Longitude1,
double _Latidute1,
double _Longitude2,
double _Latidute2)
{
EarthPoint p1 = new EarthPoint(_Longitude1,_Latidute1);
EarthPoint p2 = new EarthPoint(_Longitude2,_Latidute2);
return p1.Distance(p2);
}
测试代码:
DateTime dt1=DateTime.Now;
DateTime dt2 = DateTime.Now;
TimeSpan ts1;
dt1 = DateTime.Now;
for(int i=0;i<sumCount;i++)
ss = distanceByLnglat(jd1,wd1,jd2,wd2);
dt2 = DateTime.Now;
ts1 = dt2- dt1;
this.label4.Text = String.Format("Java:{0:N3}米 计算次数: {1:N:0} 用时: {2:N1} 毫妙",ss,sumCount,ts1.TotalMilliseconds);
dt1=DateTime.Now;
for(int i=0;i<sumCount;i++)
ss = GetDistance(jd1,wd1,jd2,wd2);
dt2 = DateTime.Now;
ts1 = dt2- dt1;
this.label3.Text = String.Format("Net:{0:N3}米 计算次数: {1:N:0} 用时: {2:N1} 毫妙",ss,sumCount,ts1.TotalMilliseconds);
第一种方法用时基本上是第二种方法的用时的2倍!
此处没有比较2种语言的意思,因为根本没有在2种环境下运行,这里只比较了算法的执行效率而已!
-------------------------------------------------------------------------------------------------
从google maps的脚本里扒了段代码,没准啥时会用上。大家一块看看是怎么算的。
private const double EARTH_RADIUS = 6378.137;
private static double rad(double d)
{
return d * Math.PI / 180.0;
}
public static double GetDistance(double lat1, double lng1, double lat2, double lng2)
{
double radLat1 = rad(lat1);
double radLat2 = rad(lat2);
double a = radLat1 - radLat2;
double b = rad(lng1) - rad(lng2);
double s = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a/2),2) +
Math.Cos(radLat1)*Math.Cos(radLat2)*Math.Pow(Math.Sin(b/2),2)));
s = s * EARTH_RADIUS;
s = Math.Round(s * 10000) / 10000;
return s;
}