在用户坐标和坐标数组之间查找最近的位置

时间:2019-11-07 19:39:51

标签: arrays swift core-location cllocation

我有以下代码来获取一个最接近的位置:

我的数据:

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)")
    }

我该如何计算,比方说最接近给定第4个数组的2?

我的想法是获取用户的当前位置,将其存储在数据库中,然后按位置对一些帖子进行排序。因此,如果我有用户位置和帖子位置,如何找到距离用户最近的2个?

谢谢

1 个答案:

答案 0 :(得分:2)

您需要做的就是调用sorted(by:)而不是min(by:)来根据用于查找最小值的相同闭包对数组进行排序,然后可以使用第一个n元素以获得最接近用户的n坐标。

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)