├── Haversine.h └── Haversine.m /Haversine.h: -------------------------------------------------------------------------------- 1 | // 2 | // haversine.h 3 | // 4 | // Created by Carsten Nielsen on 23/04/09. 5 | // 6 | 7 | #import 8 | 9 | extern float const HAVERSINE_RADS_PER_DEGREE; 10 | extern float const HAVERSINE_MI_RADIUS; 11 | extern float const HAVERSINE_KM_RADIUS; 12 | extern float const HAVERSINE_M_PER_KM; 13 | extern float const HAVERSINE_F_PER_MI; 14 | 15 | @interface Haversine : NSObject { 16 | float lat1; 17 | float lon1; 18 | float lat2; 19 | float lon2; 20 | } 21 | 22 | @property float lat1; 23 | @property float lon1; 24 | @property float lat2; 25 | @property float lon2; 26 | 27 | - (id)init; 28 | - (id)initWithLat1:(float)newLat1 29 | lon1:(float)newLon1 30 | lat2:(float)newLat2 31 | lon2:(float)newLon2; 32 | - (float)distance; 33 | - (float)toKilometers; 34 | - (float)toMeters; 35 | - (float)toMiles; 36 | - (float)toFeet; 37 | 38 | @end 39 | -------------------------------------------------------------------------------- /Haversine.m: -------------------------------------------------------------------------------- 1 | // 2 | // haversine.m 3 | // 4 | // Created by Carsten Nielsen. 5 | // 6 | 7 | #import "Haversine.h" 8 | 9 | float const HAVERSINE_RADS_PER_DEGREE = 0.0174532925199433; 10 | float const HAVERSINE_MI_RADIUS = 3956.0; 11 | float const HAVERSINE_KM_RADIUS = 6371.0; 12 | float const HAVERSINE_M_PER_KM = 1000.0; 13 | float const HAVERSINE_F_PER_MI = 5282.0; 14 | 15 | 16 | @implementation Haversine 17 | 18 | @synthesize lat1, lon1, lat2, lon2; 19 | 20 | - (id)init { 21 | return [self initWithLat1:0.0 lon1:0.0 lat2:0.0 lon2:0.0]; 22 | } 23 | 24 | - (id)initWithLat1:(float)newLat1 25 | lon1:(float)newLon1 26 | lat2:(float)newLat2 27 | lon2:(float)newLon2 { 28 | self = [super init]; 29 | if (self) { 30 | self.lat1 = newLat1; 31 | self.lon1 = newLon1; 32 | self.lat2 = newLat2; 33 | self.lon2 = newLon2; 34 | } 35 | return self; 36 | } 37 | 38 | - (float)distance { 39 | float lat1Rad = lat1 * HAVERSINE_RADS_PER_DEGREE; 40 | float lat2Rad = lat2 * HAVERSINE_RADS_PER_DEGREE; 41 | float dLonRad = ((lon2 - lon1) * HAVERSINE_RADS_PER_DEGREE); 42 | float dLatRad = ((lat2 - lat1) * HAVERSINE_RADS_PER_DEGREE); 43 | float a = pow(sin(dLatRad / 2), 2) + cos(lat1Rad) * cos(lat2Rad) * pow(sin(dLonRad / 2), 2); 44 | return (2 * atan2(sqrt(a), sqrt(1 - a))); 45 | } 46 | 47 | - (float)toKilometers { 48 | return [self distance] * HAVERSINE_KM_RADIUS; 49 | } 50 | 51 | - (float)toMeters { 52 | return [self toKilometers] * HAVERSINE_M_PER_KM; 53 | } 54 | 55 | - (float)toMiles { 56 | return [self distance] * HAVERSINE_MI_RADIUS; 57 | } 58 | 59 | - (float)toFeet { 60 | return [self toMiles] * HAVERSINE_F_PER_MI; 61 | } 62 | 63 | @end 64 | --------------------------------------------------------------------------------