我正在尝试以km为单位计算两点之间的距离。
但是我觉得我的公式可能有误,我用Google地图计算了距离(所以我觉得我有有效的测试数据)
职位1: 50.123248,8.847602
职位2: 50.120132,8.841926
距离(根据谷歌地图): 531,34米
public double distanceTo(Location location) {
final int EARTH_RADIUS_KM = 6371;
double lng1 = this.longitude;
double lng2 = location.getLongitude();
double lat1 = this.latitude;
double lat2 = location.getLatitude();
double theta = lng1 - lng2;
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;
dist = dist * 1.609344; //for Kilometers
return (dist);
}
/**
* decimal degrees to radians
*
* @param deg
* @return
*/
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
/**
* radians to decimal degrees
*
* @param rad
* @return
*/
private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
测试用例:
@Before
public void setup() {
location1 = new Location(50.123248, 8.847602);
location2 = new Location(50.120132, 8.841926);
}
@Test
public void testDistanceTo() {
//TODO No real assertion yet
System.out.print(location1.distanceTo(location2));
// Expecting 531,34 m - 0.531 KM
}
但实际结果为0.7179858613314315