我想创建一个以参数为参数的函数:
填充坐标的数组
当前用户位置
并返回用户位置和阵列位置之间的最近位置.
这是我的位置:
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)
编辑
结果当我打印closestLocation
和distanceKM
:
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为单位)非常巨大,而这些位置是同一个城市.
您可以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)