我在使用这段代码时遇到问题,我无法计算两个位置之间的距离。我已经在互联网上搜索过,但无法解决。这是我的 didUpdateLocations 函数:
func locationManager(manager:CLLocationManager, didUpdateLocations locations:[AnyObject]) {
var userLocation:CLLocation = locations[0] as CLLocation
var startLocation = userLocation
var endLocation = userLocation
if x == 0 {
var startLocation = userLocation
star.text = "\(startLocation)"
}
if x > 0 {
var endLocation = userLocation
end.text = "\(endLocation)"
let distance: CLLocationDistance = startLocation.distanceFromLocation(endLocation)
println(distance)
}
x = x + 1
}
最佳答案
您只需将 var startLocation 声明为可选但不在您的函数内。
var startLocation :CLLocation!
然后在 didUpdate 函数中测试 startLocation 变量是否为 nil:
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
if startLocation == nil {
startLocation = locations.first as? CLLocation
}
let distance = startLocation.distanceFromLocation(locations.last as! CLLocation)
println( "\(startLocation)")
println( "\(locations.last as! CLLocation)")
println("DISTANCE: \(distance)")
}
关于ios - CLLocationDistance 不起作用 - 快速,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28653496/