我是 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
}
这是应用程序的外观:
我意识到其他人也问过类似的问题,但这些问题要么没有答案,要么使用不同的语言(例如 Objective-C)。如果这个问题之前已经回答过而我只是忽略了它,有人可以将答案链接给我吗?谢谢!