我有一个getNearestSuperMarket
方法,可以在靠近我所在位置的最近的超级市场列表中返回。我从calculateDistance
方法得到的结果是错误的。你知道哪种方法最有效吗?
limit=9000000 //in meters
public List<Market> getNearestMarkets(String lat1, String lng1) throws Exception{
flat1 = Float.parseFloat(lat1);
flng1 = Float.parseFloat(lng1);
list_markets2=getAllMarkets(); //returns all the markets from the database
for ( Market ma: list_markets2){
x1=ma.getLatitude_market();
y1=Float.parseFloat(x1);
x2=ma.getLongtitude_market();
y2=Float.parseFloat(x2);
dist=calculateDistance(flat1,flng1,y1,y2);
try{
if ( dist< limit ){
ma.setDistance(dist);
list_nearest_markets.add(ma);
}
}
catch (NumberFormatException ex){
throw new Exception("somethings happened"+ex.getMessage());
}
catch (Exception e0){
errorMessages ="error: "+e0.getMessage();
throw new Exception(e0.getMessage());
}
}
return list_nearest_markets;
}//end of method
public float calculateDistance(float flat1, float flng1, float flat2, float flng2) throws Exception{
try{
double earthRadius = 6371000; //meters
double dLat = Math.toRadians(flat2-flat1);
double dLng = Math.toRadians(flng2-flng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(flat1)) * Math.cos(Math.toRadians(flat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
float dist = (float) (earthRadius * c);
return dist;
}catch(Exception e10){
throw new Exception("error"+e10.getMessage());
}
}//end of method