Currently I can calculate the distance between two coordinates which are NSString
s.
I am now trying to calculate a list of coordinates which are in a NSMutableArray
but I'm stuck.
I somehow need to calculate the distance between all loc
or is there a better way of doing this?
for (int i=0; i < self.trackArray.count; i++)
{
CGFloat latitude = [[self.trackArray objectAtIndex:0] doubleValue];
CGFloat longitude = [[self.trackArray objectAtIndex:1] doubleValue];
CLLocation *loc = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
CLLocationDistance distance = [loc distanceFromLocation:loc];
CLLocationDistance kilometers = distance / 1000.0;
self.distanceString = [NSString stringWithFormat:@"%f", kilometers];
}
Update. An example of how the array looks from the NSLog.
(
"37.335009,-122.032722",
"37.334977,-122.032813",
"37.334948,-122.032921",
"37.334922,-122.033042",
"37.334892,-122.033184",
"37.334858,-122.033344",
"37.334821,-122.033509",
"37.334780,-122.033696"
)
Sorry for not making it clear what Im trying to do, I have an app that tracks a users location and draws a line behind them, above are coordinates that were tracked from the user, I want to find the distance travelled, currently the calculated distance is as the crow fly's which is the first line of the coordinates and the last line. I want to e.g. calculate the distance between the first 2 lines of coordinates then add that distance to the next 2 lines of coordinates etc. So if the user walks in a circle I want to know the distance.
Try this:
-(void) test {
CLLocationDistance totalKilometers = 0;
for (int i = 0; i < (self.trackArray.count - 1); i++) // <-- count - 1
{
CLLocation *loc1 = [self cLLocationFromString:[self.trackArray objectAtIndex:i]];
CLLocation *loc2 = [self cLLocationFromString:[self.trackArray objectAtIndex:(i + 1)]];
CLLocationDistance distance = [loc1 distanceFromLocation:loc2];
CLLocationDistance kilometers = distance / 1000.0;
totalKilometers += kilometers;
}
self.distanceString = [NSString stringWithFormat:@"%f", totalKilometers];
}
-(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];
}