我想创建一个带参数的函数:
返回用户位置和阵列位置之间的最近位置。
以下是我的位置:
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
功能总是在两个最近的位置之间返回一个很大的距离&#34;。
输入参数
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为单位)非常巨大,而这些位置是同一个城市。
答案 0 :(得分:6)
您可以使用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)