此代码发现不正确的结果

时间:2014-01-28 11:26:01

标签: android location distance

根据GeoPoint坐标计算2个点之间的距离。     找到您的位置距离以及您想去哪里的位置。

 private double mesafe() {
// TODO Auto-generated method stub

 // 6378.1 is gravity of earth
 double EARTH_RADIUS = 6371;


double latitude = 38.452261 ;
double longitude = 27.216243 ;

Location locationA = new Location("EGE");

         /*your location*/
Location lc = new Location("KONUM");

currentLat = lc.getLatitude();//your location Latitude
currentLon = lc.getLongitude(); //your location Longitude

double lat2 = currentLat;
double lon2 = currentLon;

//The difference between latitudes and longitudes
double deltalat = Math.toRadians( lat2 - latitude) ;
double deltalon = Math.toRadians(lon2 - longitude) ;
double a=Math.sin(deltalat / 2)*Math.sin(deltalat/2)+
  Math.cos(Math.toRadians(latitude))* Math.sin(deltalon / 2) 
                             * Math.sin(deltalon / 2);

double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 

double distance = EARTH_RADIUS*c; //find your distance

mesafee.setText(String.valueOf(distance)+"  km"); 

return distance;
  } 

此代码找到距离但不正确。

2 个答案:

答案 0 :(得分:0)

我使用Haversine formular编写了这段代码用于距离计算:

private Double calculateDistance(double lat1, final double lon1, double lat2, final double lon2) {
    final int R = 6371; // earth radius in km
    final double dLat = Math.toRadians(lat2-lat1);
    final 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;
  }

请记住,这是一条直线(航空公司)距离,当然不是路线。如果你需要一个道路距离,这是一个完全不同的故事,你需要某种路由服务器。你可以,例如使用Google Maps API,查看Distance Matrix APIDirections API

答案 1 :(得分:0)

使用此方法,

位置locationA =新位置(“A点”);

locationA.setLatitude(orginlat); locationA.setLongitude(orginlong);

位置locationB =新位置(“B点”);

locationB.setLatitude(tolat); locationB.setLongitude(tolong);

浮动距离= locationA.distanceTo(locationB);