我需要开发应用程序,用户必须在其中找到他停放的汽车并显示他和停放的汽车之间的距离。我使用 GPS 和定位服务。
对于距离,我使用了半正弦公式,但距离始终显示 0 米。
我尝试了很多在谷歌中寻找解决方案,但没有得到任何正确的解决方案。
任何人都可以提出他们的建议吗?
我需要开发应用程序,用户必须在其中找到他停放的汽车并显示他和停放的汽车之间的距离。我使用 GPS 和定位服务。
对于距离,我使用了半正弦公式,但距离始终显示 0 米。
我尝试了很多在谷歌中寻找解决方案,但没有得到任何正确的解决方案。
任何人都可以提出他们的建议吗?
Google Docs 有两种方法
如果您从 GeoPoint 获取纬度/经度,那么它们是微度数。您必须乘以 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;
}
最后,我想分享奖金信息。
如果您正在寻找行车路线,请在两个地点之间选择路线,然后前往
尝试在android.location API中使用此方法
此方法计算两个位置之间的近似距离(以米为单位),以及可选的它们之间最短路径的初始和最终方位
注意:如果您从 GeoPoint 获得纬度/经度,那么它们是微度数。你必须乘以 1E6
如果您想通过Haversine 公式计算 2 个 Geopoint 之间的距离
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;
}
}
distanceBetween()
方法将为您提供两点之间的直线距离。得到两点之间的路线距离见我的答案在这里
android.location.Location.distanceBetween(double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] 结果)
地理点有 getLongitudeE6() 和 getLatitudeE6() 提供帮助。请记住,这些是 E6,因此您需要除以 1E6。
harvesine 公式的问题在于它不计算实际距离。它是球体上两点的距离。实际距离取决于街道或水路。harvesine 公式也有点复杂,因此更容易让 Google-Api 给出真实距离。使用 Googlemaps Api,您需要学习路线 API。
distanceBetween 不是指真实距离(道路距离)所以我建议你访问这个谷歌源代码,它会显示你 2 个地理点之间的真实道路距离。 链接 有 2 个版本,一个适用于Android,一个适用于黑莓,请查看