在android中可采用如下代码获取距离:
Java代码
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方法,可以采用如下代码获取,该方法的参数为正常的经纬度数据,将返回以KM为单位的值:
Java代码
public static double geo_distance(double lat1, double lng1, double lat2, double lng2) { // earth's mean radius in KM double r = 6378.137; lat1 = Math.toRadians(lat1); lng1 = Math.toRadians(lng1); lat2 = Math.toRadians(lat2); lng2 = Math.toRadians(lng2); double d1 = Math.abs(lat1 - lat2); double d2 = Math.abs(lng1 - lng2); double p = Math.pow(Math.sin(d1 / 2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(d2 / 2), 2); double dis = r * 2 * Math.asin(Math.sqrt(p)); return dis; }
//将角度转换为弧度 public static double deg2rad(double degree) { return degree / 180 * Math.PI; } //将弧度转换为角度 public static double rad2deg(double radian) { return radian * 180 / Math.PI; }
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;}
这个计算得出的结果是英里,如果要转换成公里,需要乘以1.609344,若是海里需要乘以0.8684.
最后在提供另一思路,采用weiservice请求方式,直接获取返回的更为精准的结果,例如实用国内比较有名的地图服务提供商MapABC的webservice接口:
http://search1.mapabc.com/sisserver?highLight=false&config=CDX&ver=2.0&x1= ??? &y1= ??? &x2= ??? &y2= ??? &enc=utf-8&resType=json & a_k= "your key" &ctx=1933347&a_nocache=715403361154
以json格式返回结果,使用时注意要到其官网 申请一key...