Skip to content

Instantly share code, notes, and snippets.

@kenshin03
Created April 9, 2013 04:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kenshin03/4ca299e543df5d25873d to your computer and use it in GitHub Desktop.
Save kenshin03/4ca299e543df5d25873d to your computer and use it in GitHub Desktop.
calculateDistanceBetweenCoord method
+ (NSNumber*)calculateDistanceBetweenCoord:(CLLocationCoordinate2D)coord1 coord:(CLLocationCoordinate2D)coord2 {
NSInteger nRadius = 6371; // Earth's radius in Kilometers
double latDiff = (coord2.latitude - coord1.latitude) * (M_PI/180);
double lonDiff = (coord2.longitude - coord1.longitude) * (M_PI/180);
double lat1InRadians = coord1.latitude * (M_PI/180);
double lat2InRadians = coord2.latitude * (M_PI/180);
double nA = pow ( sin(latDiff/2), 2 ) + cos(lat1InRadians) * cos(lat2InRadians) * pow ( sin(lonDiff/2), 2 );
double nC = 2 * atan2( sqrt(nA), sqrt( 1 - nA ));
double nD = nRadius * nC;
// convert to miles
double distanceInMiles = nD * 0.621371;
return @(distanceInMiles);
}
+ (NSNumber*)calculateDistanceInMetersBetweenCoord:(CLLocationCoordinate2D)coord1 coord:(CLLocationCoordinate2D)coord2 {
NSInteger nRadius = 6371; // Earth's radius in Kilometers
double latDiff = (coord2.latitude - coord1.latitude) * (M_PI/180);
double lonDiff = (coord2.longitude - coord1.longitude) * (M_PI/180);
double lat1InRadians = coord1.latitude * (M_PI/180);
double lat2InRadians = coord2.latitude * (M_PI/180);
double nA = pow ( sin(latDiff/2), 2 ) + cos(lat1InRadians) * cos(lat2InRadians) * pow ( sin(lonDiff/2), 2 );
double nC = 2 * atan2( sqrt(nA), sqrt( 1 - nA ));
double nD = nRadius * nC;
// convert to meters
return @(nD*1000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment