如何获得公里的距离在机器人?(How to get Distance Kilometer in an

2019-07-03 12:42发布

我是很新的谷歌地图我想计算的Android两两地之间的距离。

对于我得到两个地纬度和滞后的,我写了下面的代码的位置:

private double getDistance(double lat1, double lat2, double lon1, double lon2) {
    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));
    double temp = 6371 * c;
    temp=temp*0.621;
    return temp;
}

上面的代码不能给两两地之间的精确的距离。 什么是另一种方式来寻找距离,请给我任何建议。

Answer 1:

@Chirag帕特尔

double distance;
Location locationA = new Location(“Point A”);
locationA.setLatitude(latA);
locationA.setLongitude(lngA);

Location locationB = new Location(“Point B”);
locationB.setLatitude(latB);
locationB.setLongitude(lngB);

// distance = locationA.distanceTo(locationB);   // in meters
distance = locationA.distanceTo(locationB)/1000;   // in km


Answer 2:

使用下面这段代码你发现的距离,但要在转换公里。

double distance;
Location locationA = new Location("point A");
locationA.setLatitude(latA);
locationA.setLongitude(lngA);

Location locationB = new Location("point B");
locationB.setLatitude(latB);
locationB.setLongitude(lngB);

distance = locationA.distanceTo(locationB);


Answer 3:

只要使用Location.distanceTo(位置),它会给你两个不同位置之间的距离真的。



Answer 4:

使用代码中找到距离米,公里,公里英里

Location locationA = new Location(“Point A”);
locationA.setLatitude(latA);
locationA.setLongitude(lngA);

Location locationB = new Location(“Point B”);
locationB.setLatitude(latB);
locationB.setLongitude(lngB);

distance = locationA.distanceTo(locationB);   // in meters
distance = locationA.distanceTo(locationB)/1000;   // in km
distance = locationA.distanceTo(locationB)/1609.344;   // in miles


Answer 5:

            Location locationA = new Location("Point A");
            locationA.setLatitude(fromLatitude);
            locationA.setLongitude(fromLongitude);


            Location locationB = new Location("point B");
            locationB.setLatitude(toLatitude);
            locationB.setLongitude(toLongitude);


            distance = locationA.distanceTo(locationB);


文章来源: How to get Distance Kilometer in android?