Abhi Abhi - 1 year ago 77
iOS Question

iOS: How to get the distance of multiple location from one location

i am working on a project in which i have to show the distance of multiple locations from user's locations. locations are based on latitude and longitude.

i am using the following code to get the distance between two locations is shows nearly same distance

CLLocation *locA = [[CLLocation alloc] initWithLatitude:28.6379 longitude: 77.2432];
CLLocation *locB = [[CLLocation alloc] initWithLatitude:28.6562 longitude:77.2410];

CLLocationDistance distance = [locA distanceFromLocation:locB];
NSLog(@"Distance is %f",distance);
float i = distance/1000;
NSLog(@"distance between two places is %f KM", i);

but now i am struct to get the distance of multiple locations from my location: locaA.

for example i take NSarray for latitude and longitude as

NSArray * latArray = [[NSArray alloc]initWithObjects:@"28.6129",@"28.6020",@"28.5244", nil];
NSArray * longArray = [[NSArray alloc]initWithObjects:@"77.2295",@"77.2478",@"77.1855", nil];

Please help me to resolve it

Take locaA as user's location

Answer Source
CLLocation *currentLocation = ... // This is a reference to your current location as a CLLocation
NSArray *arrayOfOtherCLLocationObjects = ... // This is an array that contains all of the other points you want to calculate the distance to as CLLocations

NSMutableArray *distancesFromCurrentLocation = [[NSMutableArray alloc] initWithCapacity:arrayOfOtherCLLocationObjects.count]; // We will add all of the calculated distances to this array

for (CLLocation *location in arrayOfOtherCLLocationObjects) // Iterate through each location object
  CLLocationDistance distance = [location distanceFromLocation:currentLocation]; // Calculate distance
  [distancesFromCurrentLocation addObject:@(distance)]; // Append distance to array. You need to wrap the distance object as an NSNumber so you can append it to the array.

// At this point, you have the distance for each location point in the array distancesFromCurrentLocation