Find closest longitude and latitude in array from user location

安稳与你 提交于 2020-01-02 09:59:57

问题


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];

回答1:


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.




回答2:


@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 ?



来源:https://stackoverflow.com/questions/24783442/find-closest-longitude-and-latitude-in-array-from-user-location

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