在我的Android应用程序中, 我计算用户当前位置与用户点击地图的点之间的距离。 我用这个函数来计算:
public double CalculationByDistance(LatLng StartP, LatLng EndP) {
int Radius=6371;//radius of earth in Km
double lat1 = StartP.latitude;
double lat2 = EndP.latitude;
double lon1 = StartP.longitude;
double lon2 = EndP.longitude;
double dLat = Math.toRadians(lat2-lat1);
double dLon = Math.toRadians(lon2-lon1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2);
double c = 2 * Math.asin(Math.sqrt(a));
double valueResult= Radius*c;
double km=valueResult/1;
DecimalFormat newFormat = new DecimalFormat("####");
int kmInDec = Integer.valueOf(newFormat.format(km));
double meter=valueResult%1000;
int meterInDec= Integer.valueOf(newFormat.format(meter));
Log.i("Radius Value",""+valueResult+" KM "+kmInDec+" Meter "+meterInDec);
return Radius * c;
}
但是我的结果距离很长,例如。我到达距离大约20米的两个地方之间的距离为10947公里。任何人都可以帮助我吗?
答案 0 :(得分:4)
Android提供了计算两个纬度/经度点之间距离的方法。
android.location.Location.distanceBetween(double startLatitude,
double startLongitude, double endLatitude, double endLongitude, float[] results)
答案 1 :(得分:0)
使用此方法:
private 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);
dist = dist * 60 * 1.1515;
return (dist);
}
或者只需查看此conversation
即可答案 2 :(得分:0)
搜索有关Haversine方程式。这是一个在Meter中返回距离的实现:
public static double haversine(double lat1, double lon1, double lat2, double lon2) {
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
lat1 = Math.toRadians(lat1);
lat2 = Math.toRadians(lat2);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
}
其中R = 6371000;
答案 3 :(得分:0)
以公里计算距离的方法
public static double distanceKM(double lat1, double lon1, double lat2,
double lon2) {
int EARTH_RADIUS_KM = 6371;
double lat1Rad = Math.toRadians(lat1);
double lat2Rad = Math.toRadians(lat2);
double deltaLonRad = Math.toRadians(lon2 - lon1);
double dist_travelled = Math
.acos(Math.sin(lat1Rad) * Math.sin(lat2Rad) + Math.cos(lat1Rad)
* Math.cos(lat2Rad) * Math.cos(deltaLonRad))
* EARTH_RADIUS_KM;
dist_travelled = Double.parseDouble(new DecimalFormat("##.######")
.format(dist_travelled));
return dist_travelled;
}