Arturo
Arturo

Reputation: 4180

Find closest locationS between user's coordinates and coordinates array

I have the following code to get a single closest location:

My data:

let coord1 = CLLocation(latitude: 52.45678, longitude: 13.98765)
let coord2 = CLLocation(latitude: 52.12345, longitude: 13.54321)
let coord3 = CLLocation(latitude: 48.771896, longitude: 2.270748000000026)


closestLocation(locations: [coord1, coord2, coord3], closestToLocation: coord3)

 // This calculates closest location giving out 1 point
    func closestLocation(locations: [CLLocation], closestToLocation location: CLLocation) -> CLLocation? {
        if let closestLocation = locations.min(by: { location.distance(from: $0) < location.distance(from: $1) }) {
            print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
            print("Closest location: \(closestLocation), \n distance: \(location.distance(from: closestLocation))")
            return closestLocation
        } else {
            print("coordinates is empty")
            return nil
        }
    }


    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        var userLocation:CLLocation = locations[0]
        let long = userLocation.coordinate.longitude;
        let lat = userLocation.coordinate.latitude;

        userLocation = CLLocation(latitude: lat, longitude: long)

        print("My location: \(userLocation)")
    }

How can I calculate, let's say the 2 closest to given a 4th array to compare?

My idea is to get the current location of a user, store it in the DB, and then sort some posts by location. So If I have the user location and the posts location, how can I find the 2 closest to the user?

Thanks

Upvotes: 1

Views: 923

Answers (1)

David Pasztor
David Pasztor

Reputation: 54716

All you need to do is call sorted(by:) instead of min(by:) to sort the array based on the same closure you used to find its minimum, then you can take the first n elements to get the n closest coordinates to the user.

extension Array where Element == CLLocation {
    func sortedByDistance(to location: CLLocation) -> [CLLocation] {
        return sorted(by: { location.distance(from: $0) < location.distance(from: $1) })
    }
}

let coord1 = CLLocation(latitude: 52.45678, longitude: 13.98765)
let coord2 = CLLocation(latitude: 52.12345, longitude: 13.54321)
let coord3 = CLLocation(latitude: 48.771896, longitude: 2.270748000000026)
let coords = [coord1, coord2, coord3]

let sortedCoordinates = coords.sortedByDistance(to: coord3)
print(sortedCoordinates)
let closestTwoCoordinates = sortedCoordinates.prefix(2)

Upvotes: 3

Related Questions