If we want to calculate the distance from the array which contains the coordinates i.e Latitude and Longitude then use the following code-
-(void) getDistanceFromArray {
CLLocationDistance totalKilometers = 0;
for (int i = 0; i < (self.arrayName.count - 1); i++) // <-- count - 1
{
CLLocation *loc1 = [self cLLocationFromString:[self.arrayName objectAtIndex:i]];
CLLocation *loc2 = [self cLLocationFromString:[self.arrayName objectAtIndex:(i + 1)]];
CLLocationDistance distance = [loc1 distanceFromLocation:loc2];
CLLocationDistance kilometers = distance / 1000.0;
totalKilometers += kilometers;
}
self.distanceString = [NSString stringWithFormat:@"%f", totalKilometers];
}
Here distanceString is the property of NSString type which convert the total distance into NSString.
Latitude and Longitude should be comma seprated.
-(CLLocation*) cLLocationFromString:(NSString*)string
{
NSArray *coordinates = [string componentsSeparatedByString:@","];
CGFloat latitude = [[coordinates objectAtIndex:0] doubleValue];
CGFloat longitude = [[coordinates objectAtIndex:1] doubleValue];
return [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
}
0 Comment(s)