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

问题描述 投票:0回答: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)


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个位置?

谢谢

arrays swift core-location cllocation
1个回答
1
投票

您需要做的就是调用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)
© www.soinside.com 2019 - 2024. All rights reserved.