Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to calculate distance from array of coordinates in iOS

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.20k
    Comment on it

    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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: