您好我在使用Haversine公式实现我在Java中计算距离的方法时遇到了问题。
我尝试实现它的部分是:
if(gps.canGetLocation()){
double latitude1 = gps.getLatitude();
double longitude1 = gps.getLongitude();
double atrium_longitude = -122.6078622;
double atrium_latitude = 49.170241;
//double latitude = 49.1702665;
//double longitude = -122.6078454;
String atriumString = "Atrium";
double distanceMeters = (latitude1, longitude1, atrium_latitude, atrium_longitude, atriumString);
TextView distanceToText;
distanceToText = (TextView) findViewById(R.id.distanceTo);
distanceToText.setText("" + distanceMeters);
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude1 + "\nLong: " + longitude1 + "\n", Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
Haversine方法是:
public static double calculateDistance(double latitude1, double longitude1, double latitude2, double longitude2, String buildingName) {
double toRad = (Math.PI/180);
//double latitude = gps.getLatitude();
//double longitude = gps.getLongitude();
//double latitude = 49.1702665;
//double longitude = -122.6078454;
double radius = 6371000;
double lat1 = latitude1 * toRad;
double lon1 = longitude1 * toRad;
double lat2 = latitude2 * toRad;
double lon2 = longitude2 * toRad;
double deltaLat = (latitude2 - latitude1) * toRad;
double deltaLon = (longitude2 - longitude1) * toRad;
double aHaversine = Math.sin(deltaLat/2) * Math.sin(deltaLat/2) +
Math.cos(lat1) * Math.cos(lat2) *
Math.sin(deltaLon/2) * Math.sin(deltaLon/2);
double cHaversine = 2 * Math.atan2(Math.sqrt(aHaversine), Math.sqrt(1-aHaversine));
double distanceHaversine = radius * cHaversine;
return distanceHaversine;
}
我相信我的方法是正确的,但我可能错了,因为我在大学的第一年只是一个业余编程。此外,如果有更有效的方式来实施此公式,请务必告诉我。
答案 0 :(得分:0)
看起来您实际上并没有打电话给您已经写过的calculateDistance()
方法。
我认为这一行:
double distanceMeters = (latitude1, longitude1, atrium_latitude, atrium_longitude, atriumString);
应该是:
double distanceMeters = calculateDistance(latitude1, longitude1, atrium_latitude, atrium_longitude, atriumString);
可能只是复制和粘贴错误。如果是这样,请使用您获得的任何complile /运行时错误更新您的问题。