我需要开发一个应用程序,用户需要定位他停放的车辆,并显示他与停放的车辆之间的距离。我使用了GPS和位置服务。为了计算距离,我使用了哈弗赛恩公式,但是距离总是显示为0米。我在谷歌上尝试了很多搜索解决方案,但没有找到正确的解决方案。请问有人可以提供建议吗?
谷歌文档有两种方法
如果从GeoPoint获取lat / lon,则它们以微度为单位。 您必须乘以1e6。
但我更喜欢使用以下方法。(基于Haversine公式)
http://www.codecodex.com/wiki/Calculate_Distance_Between_Two_Points_on_a_Globe
double dist = GeoUtils.distanceKm(mylat, mylon, lat, lon);
/**
* Computes the distance in kilometers between two points on Earth.
*
* @param lat1 Latitude of the first point
* @param lon1 Longitude of the first point
* @param lat2 Latitude of the second point
* @param lon2 Longitude of the second point
* @return Distance between the two points in kilometers.
*/
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);
return Math.acos(Math.sin(lat1Rad) * Math.sin(lat2Rad) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.cos(deltaLonRad)) * EARTH_RADIUS_KM;
}
最后,我想分享一些额外的信息。
如果你正在寻找驾车路线、两个地点之间的路线,请前往
public class DistanceCalculator {
// earth’s radius = 6,371km
private static final double EARTH_RADIUS = 6371 ;
public static double distanceCalcByHaversine(GeoPoint startP, GeoPoint endP) {
double lat1 = startP.getLatitudeE6()/1E6;
double lat2 = endP.getLatitudeE6()/1E6;
double lon1 = startP.getLongitudeE6()/1E6;
double lon2 = endP.getLongitudeE6()/1E6;
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.atan2(Math.sqrt(a), Math.sqrt(1-a));
return EARTH_RADIUS * c;
}
}
android.location.Location.distanceBetween(double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] results)
地理点有getLongitudeE6()和getLatitudeE6()来帮助。请记住,这些是E6,因此您需要除以1E6。
distanceBetween不是真实距离(路程距离)。因此,我建议您访问此Google源代码,它将向您显示两个地理点之间的真实道路距离。 链接 有Android和黑莓两个版本,请查看。