我试图显示用户的平均速度, 我还想显示数组的最高值。
我在论坛上搜索并找到了许多方法来实现这一点,但没有任何作用。
我尝试过的是// top speed
和// average speed
这是我的代码:
// 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()
}
答案 0 :(得分:1)
您必须自己将所有速度更新保存到数组中,应将其定义为类实例属性,并且您可以将平均速度和最高速度定义为计算属性,这样您就不需要手动更新它们每次收到位置更新。
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,如果您需要,可以先将其写入标签或而是在将它们附加到数组之前。