我正在尝试使用CLLocationManager计算行驶距离,并在标签内显示距离。请求使用位置有效,但标签中没有显示任何内容。我试过在xCode模拟器中模拟驾驶,但没有成功。我有一个地图显示在应用程序内,这是可行的,它跟踪我的位置,但这就是所有的工作。
以下是我的locationManager方法:
func locationManager(manager:CLLocationManager, didUpdateLocations locations:[AnyObject]) {
// Map
theLabel.text = "\(locations[0])"
myLocations.append(locations[0] as! CLLocation)
let spanX = 0.007
let spanY = 0.007
let newRegion = MKCoordinateRegion(center: theMap.userLocation.coordinate, span: MKCoordinateSpanMake(spanX, spanY))
theMap.setRegion(newRegion, animated: true)
if (myLocations.count > 1){
let sourceIndex = myLocations.count - 1
let destinationIndex = myLocations.count - 2
let c1 = myLocations[sourceIndex].coordinate
let c2 = myLocations[destinationIndex].coordinate
var a = [c1, c2]
let polyline = MKPolyline(coordinates: &a, count: a.count)
theMap.add(polyline)
}
// Labels
let latestLocation: AnyObject = locations[locations.count - 1]
lat.text = String(format: "%.4f", latestLocation.coordinate.latitude)
long.text = String(format: "%.4f", latestLocation.coordinate.longitude)
horizAcc.text = String(format: "%.4f", latestLocation.horizontalAccuracy)
altitude.text = String(format: "%.4f", latestLocation.altitude)
vertAcc.text = String(format: "%.4f", latestLocation.verticalAccuracy)
if startLocation == nil {
startLocation = latestLocation as! CLLocation
}
let distanceBetween = (latestLocation.distance(from: startLocation))
distance.text = String(format: "%.2f", distanceBetween)
}
非常感谢您的帮助!如果需要的话,我可以提供更多的代码。
最佳答案
听起来您没有为CLLocationManager的实例正确设置delegate属性。您需要让它知道哪个对象包含您的CLLocationManagerDelegate方法的实现,就像您列出的那样。
因此,假设您的视图控制器符合CLLocationManagerDelegate
并包含您发布的方法,并且假设您已经为视图控制器CLLocationManager
提供了名为“locationManager”的属性,您只需如下设置:
self.locationManager.delegate = self
self.locationManager.startUpdatingLocation()
您可以将其放在viewDidLoad:中,或者放在适合您需要的任何位置,并且应该调用diddupdatelocation委托方法。