arrays - 阵列平均速度和最高速度 "CoreLocation"

标签 arrays swift average

我正在尝试显示用户的平均速度, 我还想显示数组的最高值。

我搜索了论坛并找到了很多方法来实现此目的,但没有任何效果。

我尝试的是//最高速度//平均速度

这是我的代码:

// 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)"
}

请记住,我没有将 avgSpeedtopSpeed 的单位更改为 km/h,如果您需要,您可以在编写之前进行更改将它们添加到标签中,或者更确切地说,在将它们附加到数组之前。

关于arrays - 阵列平均速度和最高速度 "CoreLocation",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45870783/

相关文章:

PHP 从一个 mysql 行的列中创建一个多维数组?

c - 如何在数组中使用int?

swift - 具有显示关系的导航 Controller

swift - 在 Safari 中打开 UIWebView 链接

ios - Swift - 将 DynamoDB 分页输出结果传递给另一个类

Javascript:在对象中分组数据

javascript - 从对象数组中获取所有唯一的对象属性

java - 在返回语句和平均问题中找不到符号

r - R 中的累积和、移动平均数和 SQL "group by"等价物

python - 找到最低的测试分数和两个高分的平均值