我正在尝试显示用户的平均速度, 我还想显示数组的最高值。
我搜索了论坛并找到了很多方法来实现此目的,但没有任何效果。
我尝试的是//最高速度
和//平均速度
这是我的代码:
// Location
let manager = CLLocationManager()
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
let span = MKCoordinateSpanMake(0.015, 0.015)
let myLocation = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
let region = MKCoordinateRegionMake(myLocation, span)
mapView.setRegion(region, animated: true)
self.mapView.showsUserLocation = true
// Altitude
let altitude = location.altitude
let altitudeNoDecimals = Int(altitude)
altitudeLabel.text = "\(altitudeNoDecimals)"
// m/s to km/h
let kmt = location.speed * (18/5)
let kmtLabel = Int(kmt)
statusLabel.text = "\(kmtLabel)"
// Top Speed
// let maxSpeed: Int = (kmtLabel as AnyObject).value(forKeyPath: "@maxSpeed.self") as! Int
// topSpeedLabel.text = "\(maxSpeed)"
let max = location.toIntMax()
topSpeedLabel.text = "\(max)"
// Average speed
var avg: Double = (list as AnyObject).valueForKeyPath("@avg.self") as Double
averageSpeed.text = "\(avg)"
}
override func viewDidLoad() {
super.viewDidLoad()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
}
最佳答案
您只需将所有速度更新保存到自己的数组中,该数组应定义为类实例属性,并且您可以将平均速度和最高速度定义为计算属性,这样您就不需要每次都手动更新它们您会收到位置更新。
let manager = CLLocationManager()
var speeds = [CLLocationSpeed]()
var avgSpeed: CLLocationSpeed {
return speeds.reduce(0,+)/Double(speeds.count) //the reduce returns the sum of the array, then dividing it by the count gives its average
}
var topSpeed: CLLocationSpeed {
return speeds.max() ?? 0 //return 0 if the array is empty
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
...
speeds.append(contentsOf: locations.map{$0.speed}) //append all new speed updates to the array
// m/s to km/h
let kmt = location.speed * (18/5)
let kmtLabel = Int(kmt)
statusLabel.text = "\(kmtLabel)"
// Top Speed
topSpeedLabel.text = "\(topSpeed)"
// Average speed
averageSpeed.text = "\(avgSpeed)"
}
请记住,我没有将 avgSpeed
或 topSpeed
的单位更改为 km/h,如果您需要,您可以在编写之前进行更改将它们添加到标签中,或者更确切地说,在将它们附加到数组之前。
关于arrays - 阵列平均速度和最高速度 "CoreLocation",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45870783/