如何使用didUpdateLocation函数之外的坐标?

时间:2016-04-17 00:55:46

标签: ios swift core-location

我正在尝试使用didUpdateLocations函数之外的坐标,但我无法使其工作。

我尝试将坐标声明为函数之外的一个度,但这不起作用。

我如何获得一些指导?

var currentUserLatitude:CLLocationDegrees?
var currentUserLongitude:CLLocationDegrees?

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){
    //location info about the user
    let location = locations.last
    let center = CLLocationCoordinate2D(latitude: (location?.coordinate.latitude)!, longitude: (location?.coordinate.longitude)!)
    let span = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
    let region = MKCoordinateRegion(center: center, span:span)
    self.mapView.setRegion(region, animated: true)
// i want to use these variables outside the function
    var currentUserLatitude = location!.coordinate.latitude
    var currentUserLongitude = location!.coordinate.longitude

}

1 个答案:

答案 0 :(得分:1)

如果要为在本地函数之外声明的变量赋值,请不要将变量重新声明为局部变量。

更改这些行:

var currentUserLatitude = location!.coordinate.latitude
var currentUserLongitude = location!.coordinate.longitude

为:

currentUserLatitude = location!.coordinate.latitude
currentUserLongitude = location!.coordinate.longitude