Question

How do I find the closest location from the user? Basically, I have a bunch of CLLocation's, and I want to find the one closest to the user. I have retrieved the users current location but I want to find the closest CLLocation. How would I go about doing this? You can just NSLog the closest.

Was it helpful?

Solution

CLLocation *currentLocation;
NSArray *otherLocations;

CLLocation *closestLocation;
CLLocationDistance closestDistance = DBL_MAX;

for (CLLocation* location in otherLocations) {
    CLLocationDistance distance = [currentLocation distanceFromLocation:location];
    if (distance < closestDistance) {
        closestLocation = location;
        closestDistance = distance;
    }
}
NSLog(@"the closest location is %@", closestLocation);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top