路线规划提供了获取路线距离的方法,见MKRoutePlan 类的 getDistance 方法。
如果是计算任意两点的距离,自2.0.0版本开始,Android SDK为开发者提供了计算距离的接口(DistanceUtil),具体使用方法如下:
1.GeoPoint p1LL = new GeoPoint(39971802, 116347927);
2.GeoPoint p2LL = new GeoPoint(39892131, 116498555);
3.double distance = DistanceUtil.getDistance(p1LL, p2LL);
如果开发者使用的是1.3.5及以前的版本,在计算任意两点之前的距离时,有如下两种方法:一种利用勾股定理计算,适用于两点距离很近的情况;一种按标准的球面大圆劣弧长度计算,适用于距离较远的情况。
- static double DEF_PI = 3.14159265359;
- static double DEF_2PI= 6.28318530712;
- static double DEF_PI180= 0.01745329252;
- static double DEF_R =6370693.5;
- public double GetShortDistance(double lon1, double lat1, double lon2, double lat2)
- {
- double ew1, ns1, ew2, ns2;
- double dx, dy, dew;
- double distance;
-
- ew1 = lon1 * DEF_PI180;
- ns1 = lat1 * DEF_PI180;
- ew2 = lon2 * DEF_PI180;
- ns2 = lat2 * DEF_PI180;
-
- dew = ew1 - ew2;
-
- if (dew > DEF_PI)
- dew = DEF_2PI - dew;
- else if (dew < -DEF_PI)
- dew = DEF_2PI + dew;
- dx = DEF_R * Math.cos(ns1) * dew;
- dy = DEF_R * (ns1 - ns2);
-
- distance = Math.sqrt(dx * dx + dy * dy);
- return distance;
- }
- public double GetLongDistance(double lon1, double lat1, double lon2, double lat2)
- {
- double ew1, ns1, ew2, ns2;
- double distance;
-
- ew1 = lon1 * DEF_PI180;
- ns1 = lat1 * DEF_PI180;
- ew2 = lon2 * DEF_PI180;
- ns2 = lat2 * DEF_PI180;
-
- distance = Math.sin(ns1) * Math.sin(ns2) + Math.cos(ns1) * Math.cos(ns2) * Math.cos(ew1 - ew2);
-
- if (distance > 1.0)
- distance = 1.0;
- else if (distance < -1.0)
- distance = -1.0;
-
- distance = DEF_R * Math.acos(distance);
- return distance;
- }
- double mLat1 = 39.90923;
- double mLon1 = 116.357428;
- double mLat2 = 39.90923;
- double mLon2 = 116.397428;
- double distance = GetShortDistance(mLon1, mLat1, mLon2, mLat2);