gpt4 book ai didi

ios - CLLocation 距离跟踪开始时不正确

转载 作者:行者123 更新时间:2023-11-30 12:36:20 26 4
gpt4 key购买 nike

我是 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)。如果这个问题之前已经被回答过,而我只是忽略了它,有人可以将答案链接给我吗?谢谢!

最佳答案

当位置管理器启动时,返回的第一个位置是缓存的最后知道的位置。您需要通过时间戳来检查这一点,并检查返回的准确性级别。您的 didUpdateLocations 委托(delegate)中的类似内容:

let newLocation = locations.last

let timeDiff = newLocation?.timestamp.timeIntervalSinceNow

let accuracyNeeded:CLLocationAccuracy=100.0

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

关于ios - CLLocation 距离跟踪开始时不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42823519/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com