CLLocation距离跟踪错误地开始

时间:2017-03-16 01:05:27

标签: ios swift swift3 cllocationmanager cllocationdistance

我是Swift的新手(和这个网站一样,如果我做错了就很抱歉),我正在尝试创建一个跟踪用户位置的正在运行的应用程序。虽然我用来跟踪距离的功能有效,但它不会从0开始。当我按下开始按钮时,距离从一个随机数开始,然后从那里开始跟踪。

我的问题是:我有没有正确解决问题?如果是这样,有没有办法解决它,以便跟踪更准确?以下是我到目前为止的情况:

override func viewDidLoad() {
    super.viewDidLoad()


    stopwatchLabel.text = "00:00.00"
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.delegate = self

    locationManager.requestAlwaysAuthorization()
    locationManager.activityType = .fitness
   locationManager.distanceFilter = 10.0
    mapView.showsUserLocation = true
    startLocation = nil

    // Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Location Delegate Methods


func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
    let location = locations.last
    let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.002, longitudeDelta: 0.002))
    self.mapView.setRegion(region, animated: true)


    if startLocation == nil {
        startLocation = locations.first
    }
    var distance = startLocation.distance(from: location!)
    let lastDistance = location?.distance(from: location!)
    distance += lastDistance!
    distanceString = "\(distance)"
    distanceLabel.text = distanceString


}

这是应用程序的样子:

the run screen

我意识到其他人也提出了类似的问题,但这些问题要么没有答案,要么使用不同的语言(例如Objective-C)。如果之前已经回答过这个问题并且我只是忽略它,那么有人可以将答案链接给我吗?谢谢!

2 个答案:

答案 0 :(得分:0)

当位置管理器启动时,返回的第一个位置是缓存的,最后知道的位置。您需要通过时间戳检查这一点,并检查返回的准确度级别。您didUpdateLocations代表中的此类内容:

let newLocation = locations.last

    let timeDiff = newLocation?.timestamp.timeIntervalSinceNow

let accuracyNeeded:CLLocationAccuracy=100.0

    if timeDiff < 5.0 && (newLocation?.horizontalAccuracy)!<=accuracyNeeded{
        //your code here
    }

答案 1 :(得分:0)

你必须让传感器有时间预热。

这是一个典型的didUpdateLocations实现。我们跟踪自开始更新位置以来经过的时间以及传感器预热时提高的水平精度。如果水平精度在合理的时间内没有改善,我们会放弃。

您需要nil属性,Date?,名为startTime,常量REQ_TIMEREQ_ACCself.stopTrying()关闭了更新,并将startTime重置为nil

        let loc = locations.last!
        let acc = loc.horizontalAccuracy
        let time = loc.timestamp
        let coord = loc.coordinate
        if self.startTime == nil { // Date? property, keep track of time
            self.startTime = Date()
            return // ignore first attempt
        }
        let elapsed = time.timeIntervalSince(self.startTime)
        if elapsed > REQ_TIME { // required time before giving up
            self.stopTrying()
            return
        }
        if acc < 0 || acc > REQ_ACC { // desired accuracy
            return // wait for the next one
        }
        // got it
        print("You are at \(coord.latitude) \(coord.longitude)")