当前位置:  开发笔记 > IOS > 正文

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

如何解决《找到用户坐标和坐标数组之间的最近位置》经验,为你挑选了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)

用户定位功能:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    var userLocation:CLLocation = locations[0]
    let long = userLocation.coordinate.longitude;
    let lat = userLocation.coordinate.latitude;

    let coordinates = [ coord1, coord2, coord3]

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

    print("my location: \(userLocation)")
    closestLocation(locations: coordinates, closestToLocation: userLocation)
}

坐标比较功能

    func closestLocation(locations: [CLLocation], closestToLocation location: CLLocation) -> CLLocation? {

    if let closestLocation: CLLocation = locations.min(by: { userLocation.distance(from: $0) < userLocation.distance(from: $1) }) {

        let distanceMeters = userLocation.distance(from: closestLocation)
        let distanceKM = distanceMeters / 1000

        print("closest location: \(closestLocation), distance: \(distanceKM)")
        return closestLocation
    } else {
        print("coordinates is empty")
        return nil
    }

}

它实际上不起作用,我的closestLocation功能总是在两个"最近的位置"之间返回一个很大的距离.

输入参数

closestLocation(locations: coordinates, closestToLocation: userLocation)

编辑

结果当我打印closestLocationdistanceKM:

closest location: <+48.77189600,+2.27074800> +/- 0.00m (speed -1.00 mps / course -1.00) @ 14/01/2017 00:16:04 heure normale d’Europe centrale, distance: 5409.0

如您所见,距离(以km为单位)非常巨大,而这些位置是同一个城市.



1> Code Differe..:

您可以Array.min(by: )根据排序条件(在您的情况下距离)来查找最小元素:

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

// We know the answer is coord3 and the distance is 0    
closestLocation(locations: [coord1, coord2, coord3], closestToLocation: coord3)

推荐阅读
mobiledu2402851173
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有