2017-04-03 75 views
1

我想在啓動時顯示用戶的當前位置,然後繼續跟蹤他們的位置,但不要集中在當前位置。我的想法是以viewDidLoad()中的當前位置爲中心,但我不知道如何等待locationManager在居中之前更新當前位置。這裏是我的代碼的相關部分:如何檢查locationManager是否更新了當前位置?

var currentLocation : CLLocation? 
@IBOutlet weak var mapView: MKMapView! 

override func viewDidLoad() { 
    super.viewDidLoad() 

    if CLLocationManager.locationServicesEnabled() { 
     locationManager.desiredAccuracy = kCLLocationAccuracyBest 
     locationManager.delegate = self 
     locationManager.requestWhenInUseAuthorization() 
     locationManager.startUpdatingLocation() 

     // wait for currentLocation to be updated 
     animateMap(currentLocation!) 

    } 

    mapView.showsUserLocation = true 
} 

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
    currentLocation = locations.last! 
} 

func animateMap(_ location: CLLocation) { 
    let region = MKCoordinateRegionMakeWithDistance(location.coordinate, 1000, 1000) 
    mapView.setRegion(region, animated: true) 
} 

回答

0

你需要簡單地調用在委託方法didUpdateLocationsanimateMap(currentLocation!)功能你在哪裏初始化currentLocation

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
    currentLocation = locations.last! 
    animateMap(currentLocation!) 
    //Either Call `stop​Updating​Location()` 
    locationManager.stop​Updating​Location() 
    //Or you can create one boolean property with default value false and compare it inside this method 
    if !animatedFlag { 
     animateMap(currentLocation!) 
     animatedFlag = true 
    } 
} 

var animatedFlag = false 
+0

但是這也會調用animateMap,它以當前位置爲中心,每當發生位置更新時,對吧?我不希望發生這種情況。我只想在啓動時集中到當前位置。 – Asteria

+0

@Asteria然後你可以停止位置管理器來更新它,或者你可以使用可以創建一個適合你的布爾實例屬性。 –

+0

這樣做了。謝謝! – Asteria

0

// MARK: - 位置lattitude東經方法委託方法

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) 
{ 
    if locationManager.location != nil 
    { 
     let locValue = (locationManager.location?.coordinate)! 
     lat = locValue.latitude 
     long = locValue.longitude 
    } 
} 
0

在didUpdateLocations委託方法中調用animateMap函數,而不是在viewDidLoad中調用。而且,只允許地圖第一次居中。你可以爲你一些布爾變量。

var isLocationUpdated = false 

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
    currentLocation = locations.last! 
    if (!isLocationUpdated) 
    { 
     animateMap(currentLocation!) 
     isLocationUpdated = true 
    } 
} 
+0

是的。你做了同樣的事情。只有在我發佈我的消息後,我纔看到你的回答 – MBN

相關問題