Find the nearest longitude and latitude in the array from the user's location

I have an array full of longitude and latitude. I have two double variables with my users location. I would like to check the distance between my user locations against my array to find out which location is closest. How to do it?

This will get the distance between the two locations, but fades out to understand how I would 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
source share
2 answers

You just need to go through an array checking 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 cycle, you will have the smallest distance and the closest place.

+3
source

@Fogmeister

I think this is a bug that should be set correctly in relation to DBL_MAX and destination.

First: Use DBL_MAX instead of DOUBLE_MAX.

DBL_MAX is the #define variable in math.h.
This is the value of the maximum representable finite floating point number (double).

Second: In your state, your assignment is incorrect:

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

You must do:

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

The difference is that it will assign the distance value to the smallest distance, and not vice versa.

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 this is correct?

+2
source

Source: https://habr.com/ru/post/1236861/


All Articles