Reputation: 9390
I want to calculate the distance between two places using Haversine formula. Actually i am having the latitude and longitude values of two places. Now i want to calculate the distance between that places using Haversine formula.
For Eg:
First Place:
"lat" : 12.97159870,
"lng" : -77.59456270
Second Place:
"lat" : 9.915996999999999,
"lng" : -78.1218470
},
Now i want to calculate the distance using Haversine Formula.
Please help me out. Thanks!
Upvotes: 0
Views: 2691
Reputation: 129
// Copy library to your project https://github.com/heycarsten/haversine-objc. Then you get distance between two location by using
Haversine *hvs = [[Haversine alloc]initWithLat1:Lati1 lon1:Longi1 lat2:Lati2 lon2:Longi2];
// Getting Distance using Math Formula..
double dLat1InRad = DEGREES_TO_RADIANS(Lati1);
double dLong1InRad = DEGREES_TO_RADIANS(Longi1);
double dLat2InRad = DEGREES_TO_RADIANS(Lati2);
double dLong2InRad = DEGREES_TO_RADIANS(Longi2);
double dLongitude = dLong2InRad - dLong1InRad;
double dLatitude = dLat2InRad - dLat1InRad;
double a = pow(sin(dLatitude/2.0), 2)+ cos(dLat1InRad) * cos(dLat2InRad) * pow(sin(dLongitude / 2.0), 2);
double c = 2.0 * asin(sqrt(a));
const double kEarthRadiusKms = 6376.5;
double dDistance = kEarthRadiusKms * c;
Upvotes: 1
Reputation: 1696
You can use CLLocation class (CoreLocation.framework) method's distanceFromLocation:(CLLocation*)loc;
CLLocation *locA = [[CLLocation alloc] initWithLatitude:lat1 longitude:long1];
CLLocation *locB = [[CLLocation alloc] initWithLatitude:lat2 longitude:long2];
CLLocationDistance distance = [locA distanceFromLocation:locB];
[locA release]; [locB release];
Upvotes: 12
Reputation: 170859
iOS provides standard means to calculate the distance between 2 geographic locations - you need to use CLLocation class for that:
#import <CoreLocation/CoreLocation.h>
CLLocation *loc1 = [[[CLLocation alloc] initWithLatitude:12.97159870 longitude:-77.59456270] autorelease];
CLLocation *loc2 = [[[CLLocation alloc] initWithLatitude: 9.915996 longitude:-78.1218470] autorelease];
double distance = [loc1 distanceFromLocation: loc2];
You'll also need to add CoreLocation.framework
to link with your project.
Upvotes: 6