Find the nearest longitude and latitude in an array from the user's location - iOS Swift

In the question answer here, the user asked:

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 allow you to get the distance between the two locations, but clouding over to understand how I would check it for an array of locations.

In response, he received the following code:

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

I have the same problem in the application I'm working on, and I think this piece of code can work just fine. However, I use Swift, and this code is in Objective-C.

My only question is: what should it look like in Swift?

Thanks for any help. I am new to this and see that this piece of code in Swift can be a big foot.

+5
source share
2 answers
 var closestLocation: CLLocation? var smallestDistance: CLLocationDistance? for location in locations { let distance = currentLocation.distanceFromLocation(location) if smallestDistance == nil || distance < smallestDistance { closestLocation = location smallestDistance = distance } } print("smallestDistance = \(smallestDistance)") 

or as a function:

 func locationInLocations(locations: [CLLocation], closestToLocation location: CLLocation) -> CLLocation? { if locations.count == 0 { return nil } var closestLocation: CLLocation? var smallestDistance: CLLocationDistance? for location in locations { let distance = location.distanceFromLocation(location) if smallestDistance == nil || distance < smallestDistance { closestLocation = location smallestDistance = distance } } print("closestLocation: \(closestLocation), distance: \(smallestDistance)") return closestLocation } 
+16
source

For Swift 3, I created this little piece of "functional" code:

 let coord1 = CLLocation(latitude: 52.12345, longitude: 13.54321) let coord2 = CLLocation(latitude: 52.45678, longitude: 13.98765) let coord3 = CLLocation(latitude: 53.45678, longitude: 13.54455) let coordinates = [coord1, coord2, coord3] let userLocation = CLLocation(latitude: 52.23678, longitude: 13.55555) let closest = coordinates.min(by: { $0.distance(from: userLocation) < $1.distance(from: userLocation) }) 
+16
source

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


All Articles