Search code examples
iosobjective-cmkmapviewcllocationmanagercllocationdistance

Find closest longitude and latitude in array from user location


I have an array full of longitudes and latitudes. I have two double variables with my users location. I'd like to test the distance between my user's locations against my array to see which location is the closest. How do I do this?

This will get the distance between 2 location but stuggeling to understand how I'd test it against an array of locations.

CLLocation *startLocation = [[CLLocation alloc] initWithLatitude:userlatitude longitude:userlongitude];
CLLocation *endLocation = [[CLLocation alloc] initWithLatitude:annotation.coordinate.latitude longitude:annotation.coordinate.longitude];
CLLocationDistance distance = [startLocation distanceFromLocation:endLocation];

Solution

  • You just need to iterate through the array checking the distances.

    NSArray *locations = //your array of CLLocation objects
    CLLocation *currentLocation = //current device Location
    
    CLLocation *closestLocation;
    CLLocationDistance smallestDistance = DOUBLE_MAX;
    
    for (CLLocation *location in locations) {
        CLLocationDistance distance = [currentLocation distanceFromLocation:location];
    
        if (distance < smallestDistance) {
            smallestDistance = distance;
            closestLocation = location;
        }
    }
    

    At the end of the loop you will have the smallest distance and the closest location.