distanceBetween method
Method which calculates the distance, in kilometers, between two locations, via the Haversine formula. Note that this is approximate due to the fact that the Earth's radius varies between 6356.752 km and 6378.137 km.
@param location1 The latitude, longitude
pair of the first location.
@param location2 The latitude, longitude
pair of the second location.
@returns The distance, in kilometers, between the inputted locations.
Implementation
double distanceBetween(GeoPoint location1, GeoPoint location2) {
validateLocation(location1);
validateLocation(location2);
var radius = 6371; // Earth's radius in kilometers
var latDelta = degreesToRadians(location2.latitude - location1.latitude);
var lonDelta = degreesToRadians(location2.longitude - location1.longitude);
var a = (sin(latDelta / 2) * sin(latDelta / 2)) +
(cos(degreesToRadians(location1.latitude)) *
cos(degreesToRadians(location2.latitude)) *
sin(lonDelta / 2) *
sin(lonDelta / 2));
var c = 2 * atan2(sqrt(a), sqrt(1 - a));
return radius * c;
}