I've tried using distanceTo()
between two Location
objects, but AFAIK it isn't returning the correct values in all situations. Instead, I've written a custom method which returns what I think are the correct values.
float distanceBetween(Location l1, Location l2)
{
float lat1= (float)l1.getLatitude();
float lon1=(float)l1.getLongitude();
float lat2=(float)l2.getLatitude();
float lon2=(float)l2.getLongitude();
float R = 6371; // km
float dLat = (float)((lat2-lat1)*Math.PI/180);
float dLon = (float)((lon2-lon1)*Math.PI/180);
lat1 = (float)(lat1*Math.PI/180);
lat2 = (float)(lat2*Math.PI/180);
float a = (float)(Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2));
float c = (float)(2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)));
float d = R * c * 1000;
return d;
}
Could anyone tell me what the difference is between my implementation and what distanceTo()
is returning?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…