Find closest longitude and latitude in array from user location

不羁岁月 提交于 2019-12-06 09:11:43
Fogmeister

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.

@Fogmeister

I think this is a mistake which must be set right about DBL_MAX and an assignment.

First : Use DBL_MAX instead of DOUBLE_MAX.

DBL_MAX is a #define variable in math.h.
It's the value of maximum representable finite floating-point (double) number.

Second : In your condition, your assignment is wrong :

if (distance < smallestDistance) {
        distance = smallestDistance;
        closestLocation = location;
}

You must do :

if (distance < smallestDistance) {
        smallestDistance = distance;
        closestLocation = location;
}

The difference is that will be assign distance value into smallestDistance, and not the opposite.

The final result :

NSArray *locations = //your array of CLLocation objects
CLLocation *currentLocation = //current device Location

CLLocation *closestLocation;
CLLocationDistance smallestDistance = DBL_MAX; // set the max value

for (CLLocation *location in locations) {
    CLLocationDistance distance = [currentLocation distanceFromLocation:location];

    if (distance < smallestDistance) {
        smallestDistance = distance;
        closestLocation = location;
    }
}
NSLog(@"smallestDistance = %f", smallestDistance);

Can you confirm that is correct ?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!