在android中可采用如下代码获取距离:
- public double getDistance(double lat1, double lon1, double lat2, double lon2) {
- float[] results=new float[1];
- Location.distanceBetween(lat1, lon1, lat2, lon2, results);
- return results[0];
- }
在其他设备若没有类似android的Location的distanceBetween方法开采用如下代码获取:
- double distance(double lat1, double lon1, double lat2, double lon2) {
- double theta = lon1 - lon2;
- double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2))
- + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2))
- * Math.cos(deg2rad(theta));
- dist = Math.acos(dist);
- dist = rad2deg(dist);
- double miles = dist * 60 * 1.1515;
- return miles;
- }
- static double deg2rad(double degree) {
- return degree / 180 * Math.PI;
- }
- static double rad2deg(double radian) {
- return radian * 180 / Math.PI;
- }
这个计算得出的结果是英里,如果要转换成公里,需要乘以1.609344,若是海里需要乘以0.8684
http://alex-yang-xiansoftware-com.javaeye.com/blog/649462
用于GPS换算世界上任意两点间距离
///
/// 计算地球上任意两点距离
///
///
///
///
///
/// 返回长度单位是米
private static double Distance(double long1, double lat1, double long2, double lat2)
{
double a, b, R;
R = 6378137; //地球半径
lat1 = lat1 * Math.PI / 180.0;
lat2 = lat2 * Math.PI / 180.0;
a = lat1 - lat2;
b = (long1 - long2) * Math.PI / 180.0;
double d;
double sa2, sb2;
sa2 = Math.Sin(a / 2.0);
sb2 = Math.Sin(b / 2.0);
d = 2 * R * Math.Asin(Math.Sqrt(sa2 * sa2 + Math.Cos(lat1) * Math.Cos(lat2) * sb2 * sb2));
return d;
}
---------------------------------------------------------
专注移动开发
Android, Windows Mobile, iPhone, J2ME, BlackBerry, Symbian
http://www.blogjava.net/TiGERTiAN/archive/2010/05/01/319853.html
从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;
}