我有一个问题是从我的2个地理点获得正确的距离。如何让它发挥作用?
来自gps类:
double latitude; // latitude
String mlat;
latitude = location.getLatitude();
mlat = String.valueOf(latitude);
来自ListView的:
// Get distance
String mReportA;
double mLocB;
int distance;
mReportA = e.getString("lat");
mReportA = e.getString("lon");
mLocB = gps.latitude;
mLocB = gps.longitude;
distance = mReportA.distanceTo(mLocB);
Eclipse中的错误:类型为String的方法distanceTo(double)
未定义
我从json
e.getString("lat");
答案 0 :(得分:3)
您可以将纬度和经度值加倍,然后只计算距离。所以不要将double值更改为string。
Location locationA = new Location("point A");
locationA.setLatitude(orginlat);
locationA.setLongitude(orginlong);
Location locationB = new Location("point B");
locationB.setLatitude(tolat);
locationB.setLongitude(tolong);
Float distance = locationA.distanceTo(locationB);
字符串转换为 double ,
public static double parseDoubleSafely(String str) {
double result = 0;
try {
result = Double.parseDouble(str);
} catch (NullPointerException npe) {
//sysout found null
return 0;
} catch (NumberFormatException nfe) {
//sysout NFE
return 0;
}
return result;
}
答案 1 :(得分:1)
// Here is the code to find out the distance between two locations
float distance;
Location locationA = new Location("A");
locationA.setLatitude(latA);
locationA.setLongitude(lngA);
Location locationB = new Location("B");
locationB.setLatitude(latB);
LocationB.setLongitude(lngB);
distance = locationA.distanceTo(locationB);
答案 2 :(得分:1)
要计算两个地理位置之间的距离,您可以按照以下示例进行操作。
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
double endLatitude = lat;
double endLongitude = lng;
float[] results = new float[3];
Location.distanceBetween(currentLatitude, currentLongitude,endLatitude, endLongitude, results);
BigDecimal bd = new BigDecimal(results[0]);// results in meters
BigDecimal rounded = bd.setScale(2, RoundingMode.HALF_UP);
double values = rounded.doubleValue();
修改强>
if (values > 1000) {
values = (Double) (values * 0.001f);// convert meters to Kilometers
bd = new BigDecimal(values);
rounded = bd.setScale(2, RoundingMode.HALF_UP);
values = rounded.doubleValue();
}